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 * distinguish datagram size limits from flow control limits in SEQPACKET
55 * rethink name space problems
56 * need a proper out-of-band
59 #include <sys/cdefs.h>
60 __FBSDID("$FreeBSD$");
64 #include <sys/param.h>
65 #include <sys/domain.h>
66 #include <sys/fcntl.h>
67 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
68 #include <sys/eventhandler.h>
70 #include <sys/filedesc.h>
71 #include <sys/kernel.h>
74 #include <sys/mount.h>
75 #include <sys/mutex.h>
76 #include <sys/namei.h>
78 #include <sys/protosw.h>
79 #include <sys/queue.h>
80 #include <sys/resourcevar.h>
81 #include <sys/rwlock.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/signalvar.h>
87 #include <sys/sysctl.h>
88 #include <sys/systm.h>
89 #include <sys/taskqueue.h>
91 #include <sys/unpcb.h>
92 #include <sys/vnode.h>
100 #include <security/mac/mac_framework.h>
106 * (l) Locked using list lock
107 * (g) Locked using linkage lock
110 static uma_zone_t unp_zone;
111 static unp_gen_t unp_gencnt; /* (l) */
112 static u_int unp_count; /* (l) Count of local sockets. */
113 static ino_t unp_ino; /* Prototype for fake inode numbers. */
114 static int unp_rights; /* (g) File descriptors in flight. */
115 static struct unp_head unp_shead; /* (l) List of stream sockets. */
116 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
117 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
120 SLIST_ENTRY(unp_defer) ud_link;
123 static SLIST_HEAD(, unp_defer) unp_defers;
124 static int unp_defers_count;
126 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
129 * Garbage collection of cyclic file descriptor/socket references occurs
130 * asynchronously in a taskqueue context in order to avoid recursion and
131 * reentrance in the UNIX domain socket, file descriptor, and socket layer
132 * code. See unp_gc() for a full description.
134 static struct task unp_gc_task;
137 * The close of unix domain sockets attached as SCM_RIGHTS is
138 * postponed to the taskqueue, to avoid arbitrary recursion depth.
139 * The attached sockets might have another sockets attached.
141 static struct task unp_defer_task;
144 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
145 * stream sockets, although the total for sender and receiver is actually
148 * Datagram sockets really use the sendspace as the maximum datagram size,
149 * and don't really want to reserve the sendspace. Their recvspace should be
150 * large enough for at least one max-size datagram plus address.
155 static u_long unpst_sendspace = PIPSIZ;
156 static u_long unpst_recvspace = PIPSIZ;
157 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
158 static u_long unpdg_recvspace = 4*1024;
159 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
160 static u_long unpsp_recvspace = PIPSIZ;
162 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
163 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
164 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
165 SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
168 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
169 &unpst_sendspace, 0, "Default stream send space.");
170 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
171 &unpst_recvspace, 0, "Default stream receive space.");
172 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
173 &unpdg_sendspace, 0, "Default datagram send space.");
174 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
175 &unpdg_recvspace, 0, "Default datagram receive space.");
176 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
177 &unpsp_sendspace, 0, "Default seqpacket send space.");
178 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
179 &unpsp_recvspace, 0, "Default seqpacket receive space.");
180 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
181 "File descriptors in flight.");
182 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
183 &unp_defers_count, 0,
184 "File descriptors deferred to taskqueue for close.");
187 * Locking and synchronization:
189 * Three types of locks exit in the local domain socket implementation: a
190 * global list mutex, a global linkage rwlock, and per-unpcb mutexes. Of the
191 * global locks, the list lock protects the socket count, global generation
192 * number, and stream/datagram global lists. The linkage lock protects the
193 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
194 * held exclusively over the acquisition of multiple unpcb locks to prevent
197 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
198 * allocated in pru_attach() and freed in pru_detach(). The validity of that
199 * pointer is an invariant, so no lock is required to dereference the so_pcb
200 * pointer if a valid socket reference is held by the caller. In practice,
201 * this is always true during operations performed on a socket. Each unpcb
202 * has a back-pointer to its socket, unp_socket, which will be stable under
203 * the same circumstances.
205 * This pointer may only be safely dereferenced as long as a valid reference
206 * to the unpcb is held. Typically, this reference will be from the socket,
207 * or from another unpcb when the referring unpcb's lock is held (in order
208 * that the reference not be invalidated during use). For example, to follow
209 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
210 * as unp_socket remains valid as long as the reference to unp_conn is valid.
212 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
213 * atomic reads without the lock may be performed "lockless", but more
214 * complex reads and read-modify-writes require the mutex to be held. No
215 * lock order is defined between unpcb locks -- multiple unpcb locks may be
216 * acquired at the same time only when holding the linkage rwlock
217 * exclusively, which prevents deadlocks.
219 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
220 * protocols, bind() is a non-atomic operation, and connect() requires
221 * potential sleeping in the protocol, due to potentially waiting on local or
222 * distributed file systems. We try to separate "lookup" operations, which
223 * may sleep, and the IPC operations themselves, which typically can occur
224 * with relative atomicity as locks can be held over the entire operation.
226 * Another tricky issue is simultaneous multi-threaded or multi-process
227 * access to a single UNIX domain socket. These are handled by the flags
228 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
229 * binding, both of which involve dropping UNIX domain socket locks in order
230 * to perform namei() and other file system operations.
232 static struct rwlock unp_link_rwlock;
233 static struct mtx unp_list_lock;
234 static struct mtx unp_defers_lock;
236 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
239 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
241 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
244 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
245 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
246 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
247 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
248 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
251 #define UNP_LIST_LOCK_INIT() mtx_init(&unp_list_lock, \
252 "unp_list_lock", NULL, MTX_DEF)
253 #define UNP_LIST_LOCK() mtx_lock(&unp_list_lock)
254 #define UNP_LIST_UNLOCK() mtx_unlock(&unp_list_lock)
256 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
257 "unp_defer", NULL, MTX_DEF)
258 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
259 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
261 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
262 "unp_mtx", "unp_mtx", \
263 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
264 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
265 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
266 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
267 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
269 static int uipc_connect2(struct socket *, struct socket *);
270 static int uipc_ctloutput(struct socket *, struct sockopt *);
271 static int unp_connect(struct socket *, struct sockaddr *,
273 static int unp_connect2(struct socket *so, struct socket *so2, int);
274 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
275 static void unp_dispose(struct mbuf *);
276 static void unp_shutdown(struct unpcb *);
277 static void unp_drop(struct unpcb *, int);
278 static void unp_gc(__unused void *, int);
279 static void unp_scan(struct mbuf *, void (*)(struct file *));
280 static void unp_discard(struct file *);
281 static void unp_freerights(struct file **, int);
282 static void unp_init(void);
283 static int unp_internalize(struct mbuf **, struct thread *);
284 static void unp_internalize_fp(struct file *);
285 static int unp_externalize(struct mbuf *, struct mbuf **);
286 static int unp_externalize_fp(struct file *);
287 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
288 static void unp_process_defers(void * __unused, int);
291 * Definitions of protocols supported in the LOCAL domain.
293 static struct domain localdomain;
294 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
295 static struct pr_usrreqs uipc_usrreqs_seqpacket;
296 static struct protosw localsw[] = {
298 .pr_type = SOCK_STREAM,
299 .pr_domain = &localdomain,
300 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
301 .pr_ctloutput = &uipc_ctloutput,
302 .pr_usrreqs = &uipc_usrreqs_stream
305 .pr_type = SOCK_DGRAM,
306 .pr_domain = &localdomain,
307 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
308 .pr_usrreqs = &uipc_usrreqs_dgram
311 .pr_type = SOCK_SEQPACKET,
312 .pr_domain = &localdomain,
315 * XXXRW: For now, PR_ADDR because soreceive will bump into them
316 * due to our use of sbappendaddr. A new sbappend variants is needed
317 * that supports both atomic record writes and control data.
319 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
321 .pr_usrreqs = &uipc_usrreqs_seqpacket,
325 static struct domain localdomain = {
326 .dom_family = AF_LOCAL,
328 .dom_init = unp_init,
329 .dom_externalize = unp_externalize,
330 .dom_dispose = unp_dispose,
331 .dom_protosw = localsw,
332 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
337 uipc_abort(struct socket *so)
339 struct unpcb *unp, *unp2;
342 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
346 unp2 = unp->unp_conn;
349 unp_drop(unp2, ECONNABORTED);
350 UNP_PCB_UNLOCK(unp2);
357 uipc_accept(struct socket *so, struct sockaddr **nam)
359 struct unpcb *unp, *unp2;
360 const struct sockaddr *sa;
363 * Pass back name of connected socket, if it was bound and we are
364 * still connected (our peer may have closed already!).
367 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
369 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
371 unp2 = unp->unp_conn;
372 if (unp2 != NULL && unp2->unp_addr != NULL) {
374 sa = (struct sockaddr *) unp2->unp_addr;
375 bcopy(sa, *nam, sa->sa_len);
376 UNP_PCB_UNLOCK(unp2);
379 bcopy(sa, *nam, sa->sa_len);
386 uipc_attach(struct socket *so, int proto, struct thread *td)
388 u_long sendspace, recvspace;
392 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
393 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
394 switch (so->so_type) {
396 sendspace = unpst_sendspace;
397 recvspace = unpst_recvspace;
401 sendspace = unpdg_sendspace;
402 recvspace = unpdg_recvspace;
406 sendspace = unpsp_sendspace;
407 recvspace = unpsp_recvspace;
411 panic("uipc_attach");
413 error = soreserve(so, sendspace, recvspace);
417 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
420 LIST_INIT(&unp->unp_refs);
421 UNP_PCB_LOCK_INIT(unp);
422 unp->unp_socket = so;
424 unp->unp_refcount = 1;
427 unp->unp_gencnt = ++unp_gencnt;
429 switch (so->so_type) {
431 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
435 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
439 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
443 panic("uipc_attach");
451 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
453 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
455 int error, namelen, vfslocked;
463 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
465 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
470 * We don't allow simultaneous bind() calls on a single UNIX domain
471 * socket, so flag in-progress operations, and return an error if an
472 * operation is already in progress.
474 * Historically, we have not allowed a socket to be rebound, so this
475 * also returns an error. Not allowing re-binding simplifies the
476 * implementation and avoids a great many possible failure modes.
479 if (unp->unp_vnode != NULL) {
483 if (unp->unp_flags & UNP_BINDING) {
487 unp->unp_flags |= UNP_BINDING;
490 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
491 bcopy(soun->sun_path, buf, namelen);
496 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
497 UIO_SYSSPACE, buf, td);
498 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
503 vfslocked = NDHASGIANT(&nd);
504 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
505 NDFREE(&nd, NDF_ONLY_PNBUF);
515 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
518 VFS_UNLOCK_GIANT(vfslocked);
522 vattr.va_type = VSOCK;
523 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
525 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
529 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
530 NDFREE(&nd, NDF_ONLY_PNBUF);
533 vn_finished_write(mp);
537 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
538 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
542 vp->v_socket = unp->unp_socket;
544 unp->unp_addr = soun;
545 unp->unp_flags &= ~UNP_BINDING;
549 vn_finished_write(mp);
550 VFS_UNLOCK_GIANT(vfslocked);
555 VFS_UNLOCK_GIANT(vfslocked);
557 unp->unp_flags &= ~UNP_BINDING;
564 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
568 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
570 error = unp_connect(so, nam, td);
576 uipc_close(struct socket *so)
578 struct unpcb *unp, *unp2;
581 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
585 unp2 = unp->unp_conn;
588 unp_disconnect(unp, unp2);
589 UNP_PCB_UNLOCK(unp2);
596 uipc_connect2(struct socket *so1, struct socket *so2)
598 struct unpcb *unp, *unp2;
603 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
606 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
608 error = unp_connect2(so1, so2, PRU_CONNECT2);
609 UNP_PCB_UNLOCK(unp2);
616 uipc_detach(struct socket *so)
618 struct unpcb *unp, *unp2;
619 struct sockaddr_un *saved_unp_addr;
621 int freeunp, local_unp_rights;
624 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
629 LIST_REMOVE(unp, unp_link);
630 unp->unp_gencnt = ++unp_gencnt;
635 * XXXRW: Should assert vp->v_socket == so.
637 if ((vp = unp->unp_vnode) != NULL) {
638 unp->unp_vnode->v_socket = NULL;
639 unp->unp_vnode = NULL;
641 unp2 = unp->unp_conn;
644 unp_disconnect(unp, unp2);
645 UNP_PCB_UNLOCK(unp2);
649 * We hold the linkage lock exclusively, so it's OK to acquire
650 * multiple pcb locks at a time.
652 while (!LIST_EMPTY(&unp->unp_refs)) {
653 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
656 unp_drop(ref, ECONNRESET);
659 local_unp_rights = unp_rights;
661 unp->unp_socket->so_pcb = NULL;
662 saved_unp_addr = unp->unp_addr;
663 unp->unp_addr = NULL;
665 freeunp = (unp->unp_refcount == 0);
666 if (saved_unp_addr != NULL)
667 free(saved_unp_addr, M_SONAME);
669 UNP_PCB_LOCK_DESTROY(unp);
670 uma_zfree(unp_zone, unp);
676 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
678 VFS_UNLOCK_GIANT(vfslocked);
680 if (local_unp_rights)
681 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
685 uipc_disconnect(struct socket *so)
687 struct unpcb *unp, *unp2;
690 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
694 unp2 = unp->unp_conn;
697 unp_disconnect(unp, unp2);
698 UNP_PCB_UNLOCK(unp2);
706 uipc_listen(struct socket *so, int backlog, struct thread *td)
712 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
715 if (unp->unp_vnode == NULL) {
721 error = solisten_proto_check(so);
723 cru2x(td->td_ucred, &unp->unp_peercred);
724 unp->unp_flags |= UNP_HAVEPCCACHED;
725 solisten_proto(so, backlog);
733 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
735 struct unpcb *unp, *unp2;
736 const struct sockaddr *sa;
739 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
741 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
744 * XXX: It seems that this test always fails even when connection is
745 * established. So, this else clause is added as workaround to
746 * return PF_LOCAL sockaddr.
748 unp2 = unp->unp_conn;
751 if (unp2->unp_addr != NULL)
752 sa = (struct sockaddr *) unp2->unp_addr;
755 bcopy(sa, *nam, sa->sa_len);
756 UNP_PCB_UNLOCK(unp2);
759 bcopy(sa, *nam, sa->sa_len);
766 uipc_rcvd(struct socket *so, int flags)
768 struct unpcb *unp, *unp2;
774 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
776 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
777 panic("uipc_rcvd socktype %d", so->so_type);
780 * Adjust backpressure on sender and wakeup any waiting to write.
782 * The unp lock is acquired to maintain the validity of the unp_conn
783 * pointer; no lock on unp2 is required as unp2->unp_socket will be
784 * static as long as we don't permit unp2 to disconnect from unp,
785 * which is prevented by the lock on unp. We cache values from
786 * so_rcv to avoid holding the so_rcv lock over the entire
787 * transaction on the remote so_snd.
789 SOCKBUF_LOCK(&so->so_rcv);
790 mbcnt = so->so_rcv.sb_mbcnt;
791 sbcc = so->so_rcv.sb_cc;
792 SOCKBUF_UNLOCK(&so->so_rcv);
794 unp2 = unp->unp_conn;
799 so2 = unp2->unp_socket;
800 SOCKBUF_LOCK(&so2->so_snd);
801 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
802 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
803 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
804 newhiwat, RLIM_INFINITY);
805 sowwakeup_locked(so2);
806 unp->unp_mbcnt = mbcnt;
813 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
814 struct mbuf *control, struct thread *td)
816 struct unpcb *unp, *unp2;
818 u_int mbcnt_delta, sbcc;
823 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
825 if (flags & PRUS_OOB) {
829 if (control != NULL && (error = unp_internalize(&control, td)))
831 if ((nam != NULL) || (flags & PRUS_EOF))
835 switch (so->so_type) {
838 const struct sockaddr *from;
840 unp2 = unp->unp_conn;
842 UNP_LINK_WLOCK_ASSERT();
847 error = unp_connect(so, nam, td);
850 unp2 = unp->unp_conn;
854 * Because connect() and send() are non-atomic in a sendto()
855 * with a target address, it's possible that the socket will
856 * have disconnected before the send() can run. In that case
857 * return the slightly counter-intuitive but otherwise
858 * correct error that the socket is not connected.
865 if (unp2->unp_flags & UNP_WANTCRED)
866 control = unp_addsockcred(td, control);
868 if (unp->unp_addr != NULL)
869 from = (struct sockaddr *)unp->unp_addr;
872 so2 = unp2->unp_socket;
873 SOCKBUF_LOCK(&so2->so_rcv);
874 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
875 sorwakeup_locked(so2);
879 SOCKBUF_UNLOCK(&so2->so_rcv);
883 UNP_LINK_WLOCK_ASSERT();
885 unp_disconnect(unp, unp2);
886 UNP_PCB_UNLOCK(unp2);
894 if ((so->so_state & SS_ISCONNECTED) == 0) {
896 UNP_LINK_WLOCK_ASSERT();
897 error = unp_connect(so, nam, td);
907 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
913 * Because connect() and send() are non-atomic in a sendto()
914 * with a target address, it's possible that the socket will
915 * have disconnected before the send() can run. In that case
916 * return the slightly counter-intuitive but otherwise
917 * correct error that the socket is not connected.
919 * Locking here must be done carefully: the linkage lock
920 * prevents interconnections between unpcbs from changing, so
921 * we can traverse from unp to unp2 without acquiring unp's
922 * lock. Socket buffer locks follow unpcb locks, so we can
923 * acquire both remote and lock socket buffer locks.
925 unp2 = unp->unp_conn;
930 so2 = unp2->unp_socket;
932 SOCKBUF_LOCK(&so2->so_rcv);
933 if (unp2->unp_flags & UNP_WANTCRED) {
935 * Credentials are passed only once on SOCK_STREAM.
937 unp2->unp_flags &= ~UNP_WANTCRED;
938 control = unp_addsockcred(td, control);
941 * Send to paired receive port, and then reduce send buffer
942 * hiwater marks to maintain backpressure. Wake up readers.
944 switch (so->so_type) {
946 if (control != NULL) {
947 if (sbappendcontrol_locked(&so2->so_rcv, m,
951 sbappend_locked(&so2->so_rcv, m);
954 case SOCK_SEQPACKET: {
955 const struct sockaddr *from;
958 if (sbappendaddr_locked(&so2->so_rcv, from, m,
966 * XXXRW: While fine for SOCK_STREAM, this conflates maximum
967 * datagram size and back-pressure for SOCK_SEQPACKET, which
968 * can lead to undesired return of EMSGSIZE on send instead
969 * of more desirable blocking.
971 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
972 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
973 sbcc = so2->so_rcv.sb_cc;
974 sorwakeup_locked(so2);
976 SOCKBUF_LOCK(&so->so_snd);
977 if ((int)so->so_snd.sb_hiwat >= (int)(sbcc - unp2->unp_cc))
978 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
981 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
982 newhiwat, RLIM_INFINITY);
983 so->so_snd.sb_mbmax -= mbcnt_delta;
984 SOCKBUF_UNLOCK(&so->so_snd);
986 UNP_PCB_UNLOCK(unp2);
991 panic("uipc_send unknown socktype");
995 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
997 if (flags & PRUS_EOF) {
1001 UNP_PCB_UNLOCK(unp);
1004 if ((nam != NULL) || (flags & PRUS_EOF))
1009 if (control != NULL && error != 0)
1010 unp_dispose(control);
1013 if (control != NULL)
1021 uipc_sense(struct socket *so, struct stat *sb)
1023 struct unpcb *unp, *unp2;
1026 unp = sotounpcb(so);
1027 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1029 sb->st_blksize = so->so_snd.sb_hiwat;
1032 unp2 = unp->unp_conn;
1033 if ((so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) &&
1035 so2 = unp2->unp_socket;
1036 sb->st_blksize += so2->so_rcv.sb_cc;
1039 if (unp->unp_ino == 0)
1040 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1041 sb->st_ino = unp->unp_ino;
1042 UNP_PCB_UNLOCK(unp);
1048 uipc_shutdown(struct socket *so)
1052 unp = sotounpcb(so);
1053 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1059 UNP_PCB_UNLOCK(unp);
1065 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1068 const struct sockaddr *sa;
1070 unp = sotounpcb(so);
1071 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1073 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1075 if (unp->unp_addr != NULL)
1076 sa = (struct sockaddr *) unp->unp_addr;
1079 bcopy(sa, *nam, sa->sa_len);
1080 UNP_PCB_UNLOCK(unp);
1084 static struct pr_usrreqs uipc_usrreqs_dgram = {
1085 .pru_abort = uipc_abort,
1086 .pru_accept = uipc_accept,
1087 .pru_attach = uipc_attach,
1088 .pru_bind = uipc_bind,
1089 .pru_connect = uipc_connect,
1090 .pru_connect2 = uipc_connect2,
1091 .pru_detach = uipc_detach,
1092 .pru_disconnect = uipc_disconnect,
1093 .pru_listen = uipc_listen,
1094 .pru_peeraddr = uipc_peeraddr,
1095 .pru_rcvd = uipc_rcvd,
1096 .pru_send = uipc_send,
1097 .pru_sense = uipc_sense,
1098 .pru_shutdown = uipc_shutdown,
1099 .pru_sockaddr = uipc_sockaddr,
1100 .pru_soreceive = soreceive_dgram,
1101 .pru_close = uipc_close,
1104 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1105 .pru_abort = uipc_abort,
1106 .pru_accept = uipc_accept,
1107 .pru_attach = uipc_attach,
1108 .pru_bind = uipc_bind,
1109 .pru_connect = uipc_connect,
1110 .pru_connect2 = uipc_connect2,
1111 .pru_detach = uipc_detach,
1112 .pru_disconnect = uipc_disconnect,
1113 .pru_listen = uipc_listen,
1114 .pru_peeraddr = uipc_peeraddr,
1115 .pru_rcvd = uipc_rcvd,
1116 .pru_send = uipc_send,
1117 .pru_sense = uipc_sense,
1118 .pru_shutdown = uipc_shutdown,
1119 .pru_sockaddr = uipc_sockaddr,
1120 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1121 .pru_close = uipc_close,
1124 static struct pr_usrreqs uipc_usrreqs_stream = {
1125 .pru_abort = uipc_abort,
1126 .pru_accept = uipc_accept,
1127 .pru_attach = uipc_attach,
1128 .pru_bind = uipc_bind,
1129 .pru_connect = uipc_connect,
1130 .pru_connect2 = uipc_connect2,
1131 .pru_detach = uipc_detach,
1132 .pru_disconnect = uipc_disconnect,
1133 .pru_listen = uipc_listen,
1134 .pru_peeraddr = uipc_peeraddr,
1135 .pru_rcvd = uipc_rcvd,
1136 .pru_send = uipc_send,
1137 .pru_sense = uipc_sense,
1138 .pru_shutdown = uipc_shutdown,
1139 .pru_sockaddr = uipc_sockaddr,
1140 .pru_soreceive = soreceive_generic,
1141 .pru_close = uipc_close,
1145 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1151 if (sopt->sopt_level != 0)
1154 unp = sotounpcb(so);
1155 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1157 switch (sopt->sopt_dir) {
1159 switch (sopt->sopt_name) {
1160 case LOCAL_PEERCRED:
1162 if (unp->unp_flags & UNP_HAVEPC)
1163 xu = unp->unp_peercred;
1165 if (so->so_type == SOCK_STREAM)
1170 UNP_PCB_UNLOCK(unp);
1172 error = sooptcopyout(sopt, &xu, sizeof(xu));
1176 /* Unlocked read. */
1177 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1178 error = sooptcopyout(sopt, &optval, sizeof(optval));
1181 case LOCAL_CONNWAIT:
1182 /* Unlocked read. */
1183 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1184 error = sooptcopyout(sopt, &optval, sizeof(optval));
1194 switch (sopt->sopt_name) {
1196 case LOCAL_CONNWAIT:
1197 error = sooptcopyin(sopt, &optval, sizeof(optval),
1202 #define OPTSET(bit) do { \
1203 UNP_PCB_LOCK(unp); \
1205 unp->unp_flags |= bit; \
1207 unp->unp_flags &= ~bit; \
1208 UNP_PCB_UNLOCK(unp); \
1211 switch (sopt->sopt_name) {
1213 OPTSET(UNP_WANTCRED);
1216 case LOCAL_CONNWAIT:
1217 OPTSET(UNP_CONNWAIT);
1226 error = ENOPROTOOPT;
1239 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1241 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1243 struct socket *so2, *so3;
1244 struct unpcb *unp, *unp2, *unp3;
1245 int error, len, vfslocked;
1246 struct nameidata nd;
1247 char buf[SOCK_MAXADDRLEN];
1248 struct sockaddr *sa;
1250 UNP_LINK_WLOCK_ASSERT();
1252 unp = sotounpcb(so);
1253 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1255 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1258 bcopy(soun->sun_path, buf, len);
1262 if (unp->unp_flags & UNP_CONNECTING) {
1263 UNP_PCB_UNLOCK(unp);
1267 unp->unp_flags |= UNP_CONNECTING;
1268 UNP_PCB_UNLOCK(unp);
1270 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1271 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1278 ASSERT_VOP_LOCKED(vp, "unp_connect");
1279 vfslocked = NDHASGIANT(&nd);
1280 NDFREE(&nd, NDF_ONLY_PNBUF);
1284 if (vp->v_type != VSOCK) {
1289 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1293 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1296 VFS_UNLOCK_GIANT(vfslocked);
1298 unp = sotounpcb(so);
1299 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1302 * Lock linkage lock for two reasons: make sure v_socket is stable,
1303 * and to protect simultaneous locking of multiple pcbs.
1308 error = ECONNREFUSED;
1311 if (so->so_type != so2->so_type) {
1315 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1316 if (so2->so_options & SO_ACCEPTCONN) {
1317 CURVNET_SET(so2->so_vnet);
1318 so3 = sonewconn(so2, 0);
1323 error = ECONNREFUSED;
1326 unp = sotounpcb(so);
1327 unp2 = sotounpcb(so2);
1328 unp3 = sotounpcb(so3);
1332 if (unp2->unp_addr != NULL) {
1333 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1334 unp3->unp_addr = (struct sockaddr_un *) sa;
1339 * The connecter's (client's) credentials are copied from its
1340 * process structure at the time of connect() (which is now).
1342 cru2x(td->td_ucred, &unp3->unp_peercred);
1343 unp3->unp_flags |= UNP_HAVEPC;
1346 * The receiver's (server's) credentials are copied from the
1347 * unp_peercred member of socket on which the former called
1348 * listen(); uipc_listen() cached that process's credentials
1349 * at that time so we can use them now.
1351 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1352 ("unp_connect: listener without cached peercred"));
1353 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1354 sizeof(unp->unp_peercred));
1355 unp->unp_flags |= UNP_HAVEPC;
1356 if (unp2->unp_flags & UNP_WANTCRED)
1357 unp3->unp_flags |= UNP_WANTCRED;
1358 UNP_PCB_UNLOCK(unp3);
1359 UNP_PCB_UNLOCK(unp2);
1360 UNP_PCB_UNLOCK(unp);
1362 mac_socketpeer_set_from_socket(so, so3);
1363 mac_socketpeer_set_from_socket(so3, so);
1368 unp = sotounpcb(so);
1369 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1370 unp2 = sotounpcb(so2);
1371 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1374 error = unp_connect2(so, so2, PRU_CONNECT);
1375 UNP_PCB_UNLOCK(unp2);
1376 UNP_PCB_UNLOCK(unp);
1381 * Giant has been previously acquired. This means filesystem
1382 * isn't MPSAFE. Do it once again.
1388 VFS_UNLOCK_GIANT(vfslocked);
1392 unp->unp_flags &= ~UNP_CONNECTING;
1393 UNP_PCB_UNLOCK(unp);
1398 unp_connect2(struct socket *so, struct socket *so2, int req)
1403 unp = sotounpcb(so);
1404 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1405 unp2 = sotounpcb(so2);
1406 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1408 UNP_LINK_WLOCK_ASSERT();
1409 UNP_PCB_LOCK_ASSERT(unp);
1410 UNP_PCB_LOCK_ASSERT(unp2);
1412 if (so2->so_type != so->so_type)
1413 return (EPROTOTYPE);
1414 unp->unp_conn = unp2;
1416 switch (so->so_type) {
1418 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1423 case SOCK_SEQPACKET:
1424 unp2->unp_conn = unp;
1425 if (req == PRU_CONNECT &&
1426 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1434 panic("unp_connect2");
1440 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1444 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1446 UNP_LINK_WLOCK_ASSERT();
1447 UNP_PCB_LOCK_ASSERT(unp);
1448 UNP_PCB_LOCK_ASSERT(unp2);
1450 unp->unp_conn = NULL;
1451 switch (unp->unp_socket->so_type) {
1453 LIST_REMOVE(unp, unp_reflink);
1454 so = unp->unp_socket;
1456 so->so_state &= ~SS_ISCONNECTED;
1461 case SOCK_SEQPACKET:
1462 soisdisconnected(unp->unp_socket);
1463 unp2->unp_conn = NULL;
1464 soisdisconnected(unp2->unp_socket);
1470 * unp_pcblist() walks the global list of struct unpcb's to generate a
1471 * pointer list, bumping the refcount on each unpcb. It then copies them out
1472 * sequentially, validating the generation number on each to see if it has
1473 * been detached. All of this is necessary because copyout() may sleep on
1477 unp_pcblist(SYSCTL_HANDLER_ARGS)
1481 struct unpcb *unp, **unp_list;
1483 struct xunpgen *xug;
1484 struct unp_head *head;
1487 switch ((intptr_t)arg1) {
1496 case SOCK_SEQPACKET:
1501 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1505 * The process of preparing the PCB list is too time-consuming and
1506 * resource-intensive to repeat twice on every request.
1508 if (req->oldptr == NULL) {
1510 req->oldidx = 2 * (sizeof *xug)
1511 + (n + n/8) * sizeof(struct xunpcb);
1515 if (req->newptr != NULL)
1519 * OK, now we're committed to doing something.
1521 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1523 gencnt = unp_gencnt;
1527 xug->xug_len = sizeof *xug;
1529 xug->xug_gen = gencnt;
1530 xug->xug_sogen = so_gencnt;
1531 error = SYSCTL_OUT(req, xug, sizeof *xug);
1537 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1540 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1541 unp = LIST_NEXT(unp, unp_link)) {
1543 if (unp->unp_gencnt <= gencnt) {
1544 if (cr_cansee(req->td->td_ucred,
1545 unp->unp_socket->so_cred)) {
1546 UNP_PCB_UNLOCK(unp);
1549 unp_list[i++] = unp;
1550 unp->unp_refcount++;
1552 UNP_PCB_UNLOCK(unp);
1555 n = i; /* In case we lost some during malloc. */
1558 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1559 for (i = 0; i < n; i++) {
1562 unp->unp_refcount--;
1563 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1564 xu->xu_len = sizeof *xu;
1567 * XXX - need more locking here to protect against
1568 * connect/disconnect races for SMP.
1570 if (unp->unp_addr != NULL)
1571 bcopy(unp->unp_addr, &xu->xu_addr,
1572 unp->unp_addr->sun_len);
1573 if (unp->unp_conn != NULL &&
1574 unp->unp_conn->unp_addr != NULL)
1575 bcopy(unp->unp_conn->unp_addr,
1577 unp->unp_conn->unp_addr->sun_len);
1578 bcopy(unp, &xu->xu_unp, sizeof *unp);
1579 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1580 UNP_PCB_UNLOCK(unp);
1581 error = SYSCTL_OUT(req, xu, sizeof *xu);
1583 freeunp = (unp->unp_refcount == 0);
1584 UNP_PCB_UNLOCK(unp);
1586 UNP_PCB_LOCK_DESTROY(unp);
1587 uma_zfree(unp_zone, unp);
1594 * Give the user an updated idea of our state. If the
1595 * generation differs from what we told her before, she knows
1596 * that something happened while we were processing this
1597 * request, and it might be necessary to retry.
1599 xug->xug_gen = unp_gencnt;
1600 xug->xug_sogen = so_gencnt;
1601 xug->xug_count = unp_count;
1602 error = SYSCTL_OUT(req, xug, sizeof *xug);
1604 free(unp_list, M_TEMP);
1609 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1610 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1611 "List of active local datagram sockets");
1612 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1613 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1614 "List of active local stream sockets");
1615 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1616 CTLTYPE_OPAQUE | CTLFLAG_RD,
1617 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1618 "List of active local seqpacket sockets");
1621 unp_shutdown(struct unpcb *unp)
1626 UNP_LINK_WLOCK_ASSERT();
1627 UNP_PCB_LOCK_ASSERT(unp);
1629 unp2 = unp->unp_conn;
1630 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1631 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1632 so = unp2->unp_socket;
1639 unp_drop(struct unpcb *unp, int errno)
1641 struct socket *so = unp->unp_socket;
1644 UNP_LINK_WLOCK_ASSERT();
1645 UNP_PCB_LOCK_ASSERT(unp);
1647 so->so_error = errno;
1648 unp2 = unp->unp_conn;
1652 unp_disconnect(unp, unp2);
1653 UNP_PCB_UNLOCK(unp2);
1657 unp_freerights(struct file **rp, int fdcount)
1662 for (i = 0; i < fdcount; i++) {
1670 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1672 struct thread *td = curthread; /* XXX */
1673 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1679 socklen_t clen = control->m_len, datalen;
1684 UNP_LINK_UNLOCK_ASSERT();
1687 if (controlp != NULL) /* controlp == NULL => free control messages */
1689 while (cm != NULL) {
1690 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1694 data = CMSG_DATA(cm);
1695 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1696 if (cm->cmsg_level == SOL_SOCKET
1697 && cm->cmsg_type == SCM_RIGHTS) {
1698 newfds = datalen / sizeof(struct file *);
1701 /* If we're not outputting the descriptors free them. */
1702 if (error || controlp == NULL) {
1703 unp_freerights(rp, newfds);
1706 FILEDESC_XLOCK(td->td_proc->p_fd);
1707 /* if the new FD's will not fit free them. */
1708 if (!fdavail(td, newfds)) {
1709 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1711 unp_freerights(rp, newfds);
1716 * Now change each pointer to an fd in the global
1717 * table to an integer that is the index to the local
1718 * fd table entry that we set up to point to the
1719 * global one we are transferring.
1721 newlen = newfds * sizeof(int);
1722 *controlp = sbcreatecontrol(NULL, newlen,
1723 SCM_RIGHTS, SOL_SOCKET);
1724 if (*controlp == NULL) {
1725 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1727 unp_freerights(rp, newfds);
1732 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1733 for (i = 0; i < newfds; i++) {
1734 if (fdalloc(td, 0, &f))
1735 panic("unp_externalize fdalloc failed");
1737 td->td_proc->p_fd->fd_ofiles[f] = fp;
1738 unp_externalize_fp(fp);
1741 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1743 /* We can just copy anything else across. */
1744 if (error || controlp == NULL)
1746 *controlp = sbcreatecontrol(NULL, datalen,
1747 cm->cmsg_type, cm->cmsg_level);
1748 if (*controlp == NULL) {
1753 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1756 controlp = &(*controlp)->m_next;
1759 if (CMSG_SPACE(datalen) < clen) {
1760 clen -= CMSG_SPACE(datalen);
1761 cm = (struct cmsghdr *)
1762 ((caddr_t)cm + CMSG_SPACE(datalen));
1774 unp_zone_change(void *tag)
1777 uma_zone_set_max(unp_zone, maxsockets);
1785 if (!IS_DEFAULT_VNET(curvnet))
1788 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1789 NULL, NULL, UMA_ALIGN_PTR, 0);
1790 if (unp_zone == NULL)
1792 uma_zone_set_max(unp_zone, maxsockets);
1793 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1794 NULL, EVENTHANDLER_PRI_ANY);
1795 LIST_INIT(&unp_dhead);
1796 LIST_INIT(&unp_shead);
1797 LIST_INIT(&unp_sphead);
1798 SLIST_INIT(&unp_defers);
1799 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1800 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1801 UNP_LINK_LOCK_INIT();
1802 UNP_LIST_LOCK_INIT();
1803 UNP_DEFERRED_LOCK_INIT();
1807 unp_internalize(struct mbuf **controlp, struct thread *td)
1809 struct mbuf *control = *controlp;
1810 struct proc *p = td->td_proc;
1811 struct filedesc *fdescp = p->p_fd;
1812 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1813 struct cmsgcred *cmcred;
1819 socklen_t clen = control->m_len, datalen;
1823 UNP_LINK_UNLOCK_ASSERT();
1827 while (cm != NULL) {
1828 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1829 || cm->cmsg_len > clen) {
1833 data = CMSG_DATA(cm);
1834 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1836 switch (cm->cmsg_type) {
1838 * Fill in credential information.
1841 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1842 SCM_CREDS, SOL_SOCKET);
1843 if (*controlp == NULL) {
1847 cmcred = (struct cmsgcred *)
1848 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1849 cmcred->cmcred_pid = p->p_pid;
1850 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1851 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1852 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1853 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1855 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1856 cmcred->cmcred_groups[i] =
1857 td->td_ucred->cr_groups[i];
1861 oldfds = datalen / sizeof (int);
1863 * Check that all the FDs passed in refer to legal
1864 * files. If not, reject the entire operation.
1867 FILEDESC_SLOCK(fdescp);
1868 for (i = 0; i < oldfds; i++) {
1870 if ((unsigned)fd >= fdescp->fd_nfiles ||
1871 fdescp->fd_ofiles[fd] == NULL) {
1872 FILEDESC_SUNLOCK(fdescp);
1876 fp = fdescp->fd_ofiles[fd];
1877 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1878 FILEDESC_SUNLOCK(fdescp);
1886 * Now replace the integer FDs with pointers to the
1887 * associated global file table entry..
1889 newlen = oldfds * sizeof(struct file *);
1890 *controlp = sbcreatecontrol(NULL, newlen,
1891 SCM_RIGHTS, SOL_SOCKET);
1892 if (*controlp == NULL) {
1893 FILEDESC_SUNLOCK(fdescp);
1898 rp = (struct file **)
1899 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1900 for (i = 0; i < oldfds; i++) {
1901 fp = fdescp->fd_ofiles[*fdp++];
1903 unp_internalize_fp(fp);
1905 FILEDESC_SUNLOCK(fdescp);
1909 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1910 SCM_TIMESTAMP, SOL_SOCKET);
1911 if (*controlp == NULL) {
1915 tv = (struct timeval *)
1916 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1925 controlp = &(*controlp)->m_next;
1926 if (CMSG_SPACE(datalen) < clen) {
1927 clen -= CMSG_SPACE(datalen);
1928 cm = (struct cmsghdr *)
1929 ((caddr_t)cm + CMSG_SPACE(datalen));
1941 static struct mbuf *
1942 unp_addsockcred(struct thread *td, struct mbuf *control)
1944 struct mbuf *m, *n, *n_prev;
1945 struct sockcred *sc;
1946 const struct cmsghdr *cm;
1950 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1951 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1955 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1956 sc->sc_uid = td->td_ucred->cr_ruid;
1957 sc->sc_euid = td->td_ucred->cr_uid;
1958 sc->sc_gid = td->td_ucred->cr_rgid;
1959 sc->sc_egid = td->td_ucred->cr_gid;
1960 sc->sc_ngroups = ngroups;
1961 for (i = 0; i < sc->sc_ngroups; i++)
1962 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1965 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1966 * created SCM_CREDS control message (struct sockcred) has another
1969 if (control != NULL)
1970 for (n = control, n_prev = NULL; n != NULL;) {
1971 cm = mtod(n, struct cmsghdr *);
1972 if (cm->cmsg_level == SOL_SOCKET &&
1973 cm->cmsg_type == SCM_CREDS) {
1975 control = n->m_next;
1977 n_prev->m_next = n->m_next;
1985 /* Prepend it to the head. */
1986 m->m_next = control;
1990 static struct unpcb *
1991 fptounp(struct file *fp)
1995 if (fp->f_type != DTYPE_SOCKET)
1997 if ((so = fp->f_data) == NULL)
1999 if (so->so_proto->pr_domain != &localdomain)
2001 return sotounpcb(so);
2005 unp_discard(struct file *fp)
2007 struct unp_defer *dr;
2009 if (unp_externalize_fp(fp)) {
2010 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2012 UNP_DEFERRED_LOCK();
2013 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2014 UNP_DEFERRED_UNLOCK();
2015 atomic_add_int(&unp_defers_count, 1);
2016 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2018 (void) closef(fp, (struct thread *)NULL);
2022 unp_process_defers(void *arg __unused, int pending)
2024 struct unp_defer *dr;
2025 SLIST_HEAD(, unp_defer) drl;
2030 UNP_DEFERRED_LOCK();
2031 if (SLIST_FIRST(&unp_defers) == NULL) {
2032 UNP_DEFERRED_UNLOCK();
2035 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2036 UNP_DEFERRED_UNLOCK();
2038 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2039 SLIST_REMOVE_HEAD(&drl, ud_link);
2040 closef(dr->ud_fp, NULL);
2044 atomic_add_int(&unp_defers_count, -count);
2049 unp_internalize_fp(struct file *fp)
2054 if ((unp = fptounp(fp)) != NULL) {
2056 unp->unp_msgcount++;
2064 unp_externalize_fp(struct file *fp)
2070 if ((unp = fptounp(fp)) != NULL) {
2071 unp->unp_msgcount--;
2081 * unp_defer indicates whether additional work has been defered for a future
2082 * pass through unp_gc(). It is thread local and does not require explicit
2085 static int unp_marked;
2086 static int unp_unreachable;
2089 unp_accessable(struct file *fp)
2093 if ((unp = fptounp(fp)) == NULL)
2095 if (unp->unp_gcflag & UNPGC_REF)
2097 unp->unp_gcflag &= ~UNPGC_DEAD;
2098 unp->unp_gcflag |= UNPGC_REF;
2103 unp_gc_process(struct unpcb *unp)
2109 /* Already processed. */
2110 if (unp->unp_gcflag & UNPGC_SCANNED)
2115 * Check for a socket potentially in a cycle. It must be in a
2116 * queue as indicated by msgcount, and this must equal the file
2117 * reference count. Note that when msgcount is 0 the file is NULL.
2119 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2120 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2121 unp->unp_gcflag |= UNPGC_DEAD;
2127 * Mark all sockets we reference with RIGHTS.
2129 so = unp->unp_socket;
2130 SOCKBUF_LOCK(&so->so_rcv);
2131 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2132 SOCKBUF_UNLOCK(&so->so_rcv);
2135 * Mark all sockets in our accept queue.
2138 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2139 SOCKBUF_LOCK(&soa->so_rcv);
2140 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2141 SOCKBUF_UNLOCK(&soa->so_rcv);
2144 unp->unp_gcflag |= UNPGC_SCANNED;
2147 static int unp_recycled;
2148 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2149 "Number of unreachable sockets claimed by the garbage collector.");
2151 static int unp_taskcount;
2152 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2153 "Number of times the garbage collector has run.");
2156 unp_gc(__unused void *arg, int pending)
2158 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2160 struct unp_head **head;
2161 struct file *f, **unref;
2168 * First clear all gc flags from previous runs.
2170 for (head = heads; *head != NULL; head++)
2171 LIST_FOREACH(unp, *head, unp_link)
2172 unp->unp_gcflag = 0;
2175 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2176 * is reachable all of the sockets it references are reachable.
2177 * Stop the scan once we do a complete loop without discovering
2178 * a new reachable socket.
2181 unp_unreachable = 0;
2183 for (head = heads; *head != NULL; head++)
2184 LIST_FOREACH(unp, *head, unp_link)
2185 unp_gc_process(unp);
2186 } while (unp_marked);
2188 if (unp_unreachable == 0)
2192 * Allocate space for a local list of dead unpcbs.
2194 unref = malloc(unp_unreachable * sizeof(struct file *),
2198 * Iterate looking for sockets which have been specifically marked
2199 * as as unreachable and store them locally.
2203 for (total = 0, head = heads; *head != NULL; head++)
2204 LIST_FOREACH(unp, *head, unp_link)
2205 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2207 if (unp->unp_msgcount == 0 || f == NULL ||
2208 f->f_count != unp->unp_msgcount)
2212 KASSERT(total <= unp_unreachable,
2213 ("unp_gc: incorrect unreachable count."));
2219 * Now flush all sockets, free'ing rights. This will free the
2220 * struct files associated with these sockets but leave each socket
2221 * with one remaining ref.
2223 for (i = 0; i < total; i++) {
2226 so = unref[i]->f_data;
2227 CURVNET_SET(so->so_vnet);
2233 * And finally release the sockets so they can be reclaimed.
2235 for (i = 0; i < total; i++)
2236 fdrop(unref[i], NULL);
2237 unp_recycled += total;
2238 free(unref, M_TEMP);
2242 unp_dispose(struct mbuf *m)
2246 unp_scan(m, unp_discard);
2250 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2257 socklen_t clen, datalen;
2260 while (m0 != NULL) {
2261 for (m = m0; m; m = m->m_next) {
2262 if (m->m_type != MT_CONTROL)
2265 cm = mtod(m, struct cmsghdr *);
2268 while (cm != NULL) {
2269 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2272 data = CMSG_DATA(cm);
2273 datalen = (caddr_t)cm + cm->cmsg_len
2276 if (cm->cmsg_level == SOL_SOCKET &&
2277 cm->cmsg_type == SCM_RIGHTS) {
2278 qfds = datalen / sizeof (struct file *);
2280 for (i = 0; i < qfds; i++)
2284 if (CMSG_SPACE(datalen) < clen) {
2285 clen -= CMSG_SPACE(datalen);
2286 cm = (struct cmsghdr *)
2287 ((caddr_t)cm + CMSG_SPACE(datalen));
2300 db_print_indent(int indent)
2304 for (i = 0; i < indent; i++)
2309 db_print_unpflags(int unp_flags)
2314 if (unp_flags & UNP_HAVEPC) {
2315 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2318 if (unp_flags & UNP_HAVEPCCACHED) {
2319 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2322 if (unp_flags & UNP_WANTCRED) {
2323 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2326 if (unp_flags & UNP_CONNWAIT) {
2327 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2330 if (unp_flags & UNP_CONNECTING) {
2331 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2334 if (unp_flags & UNP_BINDING) {
2335 db_printf("%sUNP_BINDING", comma ? ", " : "");
2341 db_print_xucred(int indent, struct xucred *xu)
2345 db_print_indent(indent);
2346 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2347 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2348 db_print_indent(indent);
2349 db_printf("cr_groups: ");
2351 for (i = 0; i < xu->cr_ngroups; i++) {
2352 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2359 db_print_unprefs(int indent, struct unp_head *uh)
2365 LIST_FOREACH(unp, uh, unp_reflink) {
2366 if (counter % 4 == 0)
2367 db_print_indent(indent);
2368 db_printf("%p ", unp);
2369 if (counter % 4 == 3)
2373 if (counter != 0 && counter % 4 != 0)
2377 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2382 db_printf("usage: show unpcb <addr>\n");
2385 unp = (struct unpcb *)addr;
2387 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2390 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2393 db_printf("unp_refs:\n");
2394 db_print_unprefs(2, &unp->unp_refs);
2396 /* XXXRW: Would be nice to print the full address, if any. */
2397 db_printf("unp_addr: %p\n", unp->unp_addr);
2399 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2400 unp->unp_cc, unp->unp_mbcnt,
2401 (unsigned long long)unp->unp_gencnt);
2403 db_printf("unp_flags: %x (", unp->unp_flags);
2404 db_print_unpflags(unp->unp_flags);
2407 db_printf("unp_peercred:\n");
2408 db_print_xucred(2, &unp->unp_peercred);
2410 db_printf("unp_refcount: %u\n", unp->unp_refcount);