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/capability.h>
66 #include <sys/domain.h>
67 #include <sys/fcntl.h>
68 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
69 #include <sys/eventhandler.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
77 #include <sys/namei.h>
79 #include <sys/protosw.h>
80 #include <sys/queue.h>
81 #include <sys/resourcevar.h>
82 #include <sys/rwlock.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/signalvar.h>
88 #include <sys/sysctl.h>
89 #include <sys/systm.h>
90 #include <sys/taskqueue.h>
92 #include <sys/unpcb.h>
93 #include <sys/vnode.h>
101 #include <security/mac/mac_framework.h>
105 MALLOC_DECLARE(M_FILECAPS);
109 * (l) Locked using list lock
110 * (g) Locked using linkage lock
113 static uma_zone_t unp_zone;
114 static unp_gen_t unp_gencnt; /* (l) */
115 static u_int unp_count; /* (l) Count of local sockets. */
116 static ino_t unp_ino; /* Prototype for fake inode numbers. */
117 static int unp_rights; /* (g) File descriptors in flight. */
118 static struct unp_head unp_shead; /* (l) List of stream sockets. */
119 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
120 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
123 SLIST_ENTRY(unp_defer) ud_link;
126 static SLIST_HEAD(, unp_defer) unp_defers;
127 static int unp_defers_count;
129 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
132 * Garbage collection of cyclic file descriptor/socket references occurs
133 * asynchronously in a taskqueue context in order to avoid recursion and
134 * reentrance in the UNIX domain socket, file descriptor, and socket layer
135 * code. See unp_gc() for a full description.
137 static struct timeout_task unp_gc_task;
140 * The close of unix domain sockets attached as SCM_RIGHTS is
141 * postponed to the taskqueue, to avoid arbitrary recursion depth.
142 * The attached sockets might have another sockets attached.
144 static struct task unp_defer_task;
147 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
148 * stream sockets, although the total for sender and receiver is actually
151 * Datagram sockets really use the sendspace as the maximum datagram size,
152 * and don't really want to reserve the sendspace. Their recvspace should be
153 * large enough for at least one max-size datagram plus address.
158 static u_long unpst_sendspace = PIPSIZ;
159 static u_long unpst_recvspace = PIPSIZ;
160 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
161 static u_long unpdg_recvspace = 4*1024;
162 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
163 static u_long unpsp_recvspace = PIPSIZ;
165 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
166 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
168 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
169 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
172 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
173 &unpst_sendspace, 0, "Default stream send space.");
174 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
175 &unpst_recvspace, 0, "Default stream receive space.");
176 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
177 &unpdg_sendspace, 0, "Default datagram send space.");
178 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
179 &unpdg_recvspace, 0, "Default datagram receive space.");
180 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
181 &unpsp_sendspace, 0, "Default seqpacket send space.");
182 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
183 &unpsp_recvspace, 0, "Default seqpacket receive space.");
184 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
185 "File descriptors in flight.");
186 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
187 &unp_defers_count, 0,
188 "File descriptors deferred to taskqueue for close.");
191 * Locking and synchronization:
193 * Three types of locks exit in the local domain socket implementation: a
194 * global list mutex, a global linkage rwlock, and per-unpcb mutexes. Of the
195 * global locks, the list lock protects the socket count, global generation
196 * number, and stream/datagram global lists. The linkage lock protects the
197 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
198 * held exclusively over the acquisition of multiple unpcb locks to prevent
201 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
202 * allocated in pru_attach() and freed in pru_detach(). The validity of that
203 * pointer is an invariant, so no lock is required to dereference the so_pcb
204 * pointer if a valid socket reference is held by the caller. In practice,
205 * this is always true during operations performed on a socket. Each unpcb
206 * has a back-pointer to its socket, unp_socket, which will be stable under
207 * the same circumstances.
209 * This pointer may only be safely dereferenced as long as a valid reference
210 * to the unpcb is held. Typically, this reference will be from the socket,
211 * or from another unpcb when the referring unpcb's lock is held (in order
212 * that the reference not be invalidated during use). For example, to follow
213 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
214 * as unp_socket remains valid as long as the reference to unp_conn is valid.
216 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
217 * atomic reads without the lock may be performed "lockless", but more
218 * complex reads and read-modify-writes require the mutex to be held. No
219 * lock order is defined between unpcb locks -- multiple unpcb locks may be
220 * acquired at the same time only when holding the linkage rwlock
221 * exclusively, which prevents deadlocks.
223 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
224 * protocols, bind() is a non-atomic operation, and connect() requires
225 * potential sleeping in the protocol, due to potentially waiting on local or
226 * distributed file systems. We try to separate "lookup" operations, which
227 * may sleep, and the IPC operations themselves, which typically can occur
228 * with relative atomicity as locks can be held over the entire operation.
230 * Another tricky issue is simultaneous multi-threaded or multi-process
231 * access to a single UNIX domain socket. These are handled by the flags
232 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
233 * binding, both of which involve dropping UNIX domain socket locks in order
234 * to perform namei() and other file system operations.
236 static struct rwlock unp_link_rwlock;
237 static struct mtx unp_list_lock;
238 static struct mtx unp_defers_lock;
240 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
243 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
245 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
248 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
249 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
250 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
251 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
252 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
255 #define UNP_LIST_LOCK_INIT() mtx_init(&unp_list_lock, \
256 "unp_list_lock", NULL, MTX_DEF)
257 #define UNP_LIST_LOCK() mtx_lock(&unp_list_lock)
258 #define UNP_LIST_UNLOCK() mtx_unlock(&unp_list_lock)
260 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
261 "unp_defer", NULL, MTX_DEF)
262 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
263 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
265 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
266 "unp_mtx", "unp_mtx", \
267 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
268 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
269 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
270 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
271 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
273 static int uipc_connect2(struct socket *, struct socket *);
274 static int uipc_ctloutput(struct socket *, struct sockopt *);
275 static int unp_connect(struct socket *, struct sockaddr *,
277 static int unp_connectat(int, struct socket *, struct sockaddr *,
279 static int unp_connect2(struct socket *so, struct socket *so2, int);
280 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
281 static void unp_dispose(struct mbuf *);
282 static void unp_shutdown(struct unpcb *);
283 static void unp_drop(struct unpcb *, int);
284 static void unp_gc(__unused void *, int);
285 static void unp_scan(struct mbuf *, void (*)(struct file *));
286 static void unp_discard(struct file *);
287 static void unp_freerights(struct filedescent **, int);
288 static void unp_init(void);
289 static int unp_internalize(struct mbuf **, struct thread *);
290 static void unp_internalize_fp(struct file *);
291 static int unp_externalize(struct mbuf *, struct mbuf **);
292 static int unp_externalize_fp(struct file *);
293 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
294 static void unp_process_defers(void * __unused, int);
297 * Definitions of protocols supported in the LOCAL domain.
299 static struct domain localdomain;
300 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
301 static struct pr_usrreqs uipc_usrreqs_seqpacket;
302 static struct protosw localsw[] = {
304 .pr_type = SOCK_STREAM,
305 .pr_domain = &localdomain,
306 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
307 .pr_ctloutput = &uipc_ctloutput,
308 .pr_usrreqs = &uipc_usrreqs_stream
311 .pr_type = SOCK_DGRAM,
312 .pr_domain = &localdomain,
313 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
314 .pr_ctloutput = &uipc_ctloutput,
315 .pr_usrreqs = &uipc_usrreqs_dgram
318 .pr_type = SOCK_SEQPACKET,
319 .pr_domain = &localdomain,
322 * XXXRW: For now, PR_ADDR because soreceive will bump into them
323 * due to our use of sbappendaddr. A new sbappend variants is needed
324 * that supports both atomic record writes and control data.
326 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
328 .pr_usrreqs = &uipc_usrreqs_seqpacket,
332 static struct domain localdomain = {
333 .dom_family = AF_LOCAL,
335 .dom_init = unp_init,
336 .dom_externalize = unp_externalize,
337 .dom_dispose = unp_dispose,
338 .dom_protosw = localsw,
339 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
344 uipc_abort(struct socket *so)
346 struct unpcb *unp, *unp2;
349 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
353 unp2 = unp->unp_conn;
356 unp_drop(unp2, ECONNABORTED);
357 UNP_PCB_UNLOCK(unp2);
364 uipc_accept(struct socket *so, struct sockaddr **nam)
366 struct unpcb *unp, *unp2;
367 const struct sockaddr *sa;
370 * Pass back name of connected socket, if it was bound and we are
371 * still connected (our peer may have closed already!).
374 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
376 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
378 unp2 = unp->unp_conn;
379 if (unp2 != NULL && unp2->unp_addr != NULL) {
381 sa = (struct sockaddr *) unp2->unp_addr;
382 bcopy(sa, *nam, sa->sa_len);
383 UNP_PCB_UNLOCK(unp2);
386 bcopy(sa, *nam, sa->sa_len);
393 uipc_attach(struct socket *so, int proto, struct thread *td)
395 u_long sendspace, recvspace;
399 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
400 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
401 switch (so->so_type) {
403 sendspace = unpst_sendspace;
404 recvspace = unpst_recvspace;
408 sendspace = unpdg_sendspace;
409 recvspace = unpdg_recvspace;
413 sendspace = unpsp_sendspace;
414 recvspace = unpsp_recvspace;
418 panic("uipc_attach");
420 error = soreserve(so, sendspace, recvspace);
424 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
427 LIST_INIT(&unp->unp_refs);
428 UNP_PCB_LOCK_INIT(unp);
429 unp->unp_socket = so;
431 unp->unp_refcount = 1;
434 unp->unp_gencnt = ++unp_gencnt;
436 switch (so->so_type) {
438 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
442 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
446 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
450 panic("uipc_attach");
458 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
460 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
470 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
472 if (soun->sun_len > sizeof(struct sockaddr_un))
474 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
479 * We don't allow simultaneous bind() calls on a single UNIX domain
480 * socket, so flag in-progress operations, and return an error if an
481 * operation is already in progress.
483 * Historically, we have not allowed a socket to be rebound, so this
484 * also returns an error. Not allowing re-binding simplifies the
485 * implementation and avoids a great many possible failure modes.
488 if (unp->unp_vnode != NULL) {
492 if (unp->unp_flags & UNP_BINDING) {
496 unp->unp_flags |= UNP_BINDING;
499 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
500 bcopy(soun->sun_path, buf, namelen);
504 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME,
505 UIO_SYSSPACE, buf, fd, CAP_BINDAT, td);
506 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
511 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
512 NDFREE(&nd, NDF_ONLY_PNBUF);
522 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
528 vattr.va_type = VSOCK;
529 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
531 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
535 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
536 NDFREE(&nd, NDF_ONLY_PNBUF);
539 vn_finished_write(mp);
543 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
544 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
548 VOP_UNP_BIND(vp, unp->unp_socket);
550 unp->unp_addr = soun;
551 unp->unp_flags &= ~UNP_BINDING;
555 vn_finished_write(mp);
561 unp->unp_flags &= ~UNP_BINDING;
568 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
571 return (uipc_bindat(AT_FDCWD, so, nam, td));
575 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
579 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
581 error = unp_connect(so, nam, td);
587 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
592 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
594 error = unp_connectat(fd, so, nam, td);
600 uipc_close(struct socket *so)
602 struct unpcb *unp, *unp2;
605 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
609 unp2 = unp->unp_conn;
612 unp_disconnect(unp, unp2);
613 UNP_PCB_UNLOCK(unp2);
620 uipc_connect2(struct socket *so1, struct socket *so2)
622 struct unpcb *unp, *unp2;
627 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
630 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
632 error = unp_connect2(so1, so2, PRU_CONNECT2);
633 UNP_PCB_UNLOCK(unp2);
640 uipc_detach(struct socket *so)
642 struct unpcb *unp, *unp2;
643 struct sockaddr_un *saved_unp_addr;
645 int freeunp, local_unp_rights;
648 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
653 LIST_REMOVE(unp, unp_link);
654 unp->unp_gencnt = ++unp_gencnt;
659 * XXXRW: Should assert vp->v_socket == so.
661 if ((vp = unp->unp_vnode) != NULL) {
663 unp->unp_vnode = NULL;
665 unp2 = unp->unp_conn;
668 unp_disconnect(unp, unp2);
669 UNP_PCB_UNLOCK(unp2);
673 * We hold the linkage lock exclusively, so it's OK to acquire
674 * multiple pcb locks at a time.
676 while (!LIST_EMPTY(&unp->unp_refs)) {
677 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
680 unp_drop(ref, ECONNRESET);
683 local_unp_rights = unp_rights;
685 unp->unp_socket->so_pcb = NULL;
686 saved_unp_addr = unp->unp_addr;
687 unp->unp_addr = NULL;
689 freeunp = (unp->unp_refcount == 0);
690 if (saved_unp_addr != NULL)
691 free(saved_unp_addr, M_SONAME);
693 UNP_PCB_LOCK_DESTROY(unp);
694 uma_zfree(unp_zone, unp);
699 if (local_unp_rights)
700 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
704 uipc_disconnect(struct socket *so)
706 struct unpcb *unp, *unp2;
709 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
713 unp2 = unp->unp_conn;
716 unp_disconnect(unp, unp2);
717 UNP_PCB_UNLOCK(unp2);
725 uipc_listen(struct socket *so, int backlog, struct thread *td)
731 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
734 if (unp->unp_vnode == NULL) {
740 error = solisten_proto_check(so);
742 cru2x(td->td_ucred, &unp->unp_peercred);
743 unp->unp_flags |= UNP_HAVEPCCACHED;
744 solisten_proto(so, backlog);
752 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
754 struct unpcb *unp, *unp2;
755 const struct sockaddr *sa;
758 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
760 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
763 * XXX: It seems that this test always fails even when connection is
764 * established. So, this else clause is added as workaround to
765 * return PF_LOCAL sockaddr.
767 unp2 = unp->unp_conn;
770 if (unp2->unp_addr != NULL)
771 sa = (struct sockaddr *) unp2->unp_addr;
774 bcopy(sa, *nam, sa->sa_len);
775 UNP_PCB_UNLOCK(unp2);
778 bcopy(sa, *nam, sa->sa_len);
785 uipc_rcvd(struct socket *so, int flags)
787 struct unpcb *unp, *unp2;
793 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
795 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
796 panic("uipc_rcvd socktype %d", so->so_type);
799 * Adjust backpressure on sender and wakeup any waiting to write.
801 * The unp lock is acquired to maintain the validity of the unp_conn
802 * pointer; no lock on unp2 is required as unp2->unp_socket will be
803 * static as long as we don't permit unp2 to disconnect from unp,
804 * which is prevented by the lock on unp. We cache values from
805 * so_rcv to avoid holding the so_rcv lock over the entire
806 * transaction on the remote so_snd.
808 SOCKBUF_LOCK(&so->so_rcv);
809 mbcnt = so->so_rcv.sb_mbcnt;
810 sbcc = so->so_rcv.sb_cc;
811 SOCKBUF_UNLOCK(&so->so_rcv);
813 unp2 = unp->unp_conn;
818 so2 = unp2->unp_socket;
819 SOCKBUF_LOCK(&so2->so_snd);
820 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
821 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
822 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
823 newhiwat, RLIM_INFINITY);
824 sowwakeup_locked(so2);
825 unp->unp_mbcnt = mbcnt;
832 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
833 struct mbuf *control, struct thread *td)
835 struct unpcb *unp, *unp2;
837 u_int mbcnt_delta, sbcc;
842 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
844 if (flags & PRUS_OOB) {
848 if (control != NULL && (error = unp_internalize(&control, td)))
850 if ((nam != NULL) || (flags & PRUS_EOF))
854 switch (so->so_type) {
857 const struct sockaddr *from;
859 unp2 = unp->unp_conn;
861 UNP_LINK_WLOCK_ASSERT();
866 error = unp_connect(so, nam, td);
869 unp2 = unp->unp_conn;
873 * Because connect() and send() are non-atomic in a sendto()
874 * with a target address, it's possible that the socket will
875 * have disconnected before the send() can run. In that case
876 * return the slightly counter-intuitive but otherwise
877 * correct error that the socket is not connected.
884 if (unp2->unp_flags & UNP_WANTCRED)
885 control = unp_addsockcred(td, control);
887 if (unp->unp_addr != NULL)
888 from = (struct sockaddr *)unp->unp_addr;
891 so2 = unp2->unp_socket;
892 SOCKBUF_LOCK(&so2->so_rcv);
893 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
894 sorwakeup_locked(so2);
898 SOCKBUF_UNLOCK(&so2->so_rcv);
902 UNP_LINK_WLOCK_ASSERT();
904 unp_disconnect(unp, unp2);
905 UNP_PCB_UNLOCK(unp2);
913 if ((so->so_state & SS_ISCONNECTED) == 0) {
915 UNP_LINK_WLOCK_ASSERT();
916 error = unp_connect(so, nam, td);
926 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
932 * Because connect() and send() are non-atomic in a sendto()
933 * with a target address, it's possible that the socket will
934 * have disconnected before the send() can run. In that case
935 * return the slightly counter-intuitive but otherwise
936 * correct error that the socket is not connected.
938 * Locking here must be done carefully: the linkage lock
939 * prevents interconnections between unpcbs from changing, so
940 * we can traverse from unp to unp2 without acquiring unp's
941 * lock. Socket buffer locks follow unpcb locks, so we can
942 * acquire both remote and lock socket buffer locks.
944 unp2 = unp->unp_conn;
949 so2 = unp2->unp_socket;
951 SOCKBUF_LOCK(&so2->so_rcv);
952 if (unp2->unp_flags & UNP_WANTCRED) {
954 * Credentials are passed only once on SOCK_STREAM
955 * and SOCK_SEQPACKET.
957 unp2->unp_flags &= ~UNP_WANTCRED;
958 control = unp_addsockcred(td, control);
961 * Send to paired receive port, and then reduce send buffer
962 * hiwater marks to maintain backpressure. Wake up readers.
964 switch (so->so_type) {
966 if (control != NULL) {
967 if (sbappendcontrol_locked(&so2->so_rcv, m,
971 sbappend_locked(&so2->so_rcv, m);
974 case SOCK_SEQPACKET: {
975 const struct sockaddr *from;
978 if (sbappendaddr_locked(&so2->so_rcv, from, m,
986 * XXXRW: While fine for SOCK_STREAM, this conflates maximum
987 * datagram size and back-pressure for SOCK_SEQPACKET, which
988 * can lead to undesired return of EMSGSIZE on send instead
989 * of more desirable blocking.
991 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
992 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
993 sbcc = so2->so_rcv.sb_cc;
994 sorwakeup_locked(so2);
996 SOCKBUF_LOCK(&so->so_snd);
997 if ((int)so->so_snd.sb_hiwat >= (int)(sbcc - unp2->unp_cc))
998 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
1001 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
1002 newhiwat, RLIM_INFINITY);
1003 so->so_snd.sb_mbmax -= mbcnt_delta;
1004 SOCKBUF_UNLOCK(&so->so_snd);
1005 unp2->unp_cc = sbcc;
1006 UNP_PCB_UNLOCK(unp2);
1011 panic("uipc_send unknown socktype");
1015 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1017 if (flags & PRUS_EOF) {
1021 UNP_PCB_UNLOCK(unp);
1024 if ((nam != NULL) || (flags & PRUS_EOF))
1029 if (control != NULL && error != 0)
1030 unp_dispose(control);
1033 if (control != NULL)
1041 uipc_sense(struct socket *so, struct stat *sb)
1043 struct unpcb *unp, *unp2;
1046 unp = sotounpcb(so);
1047 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1049 sb->st_blksize = so->so_snd.sb_hiwat;
1052 unp2 = unp->unp_conn;
1053 if ((so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) &&
1055 so2 = unp2->unp_socket;
1056 sb->st_blksize += so2->so_rcv.sb_cc;
1059 if (unp->unp_ino == 0)
1060 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1061 sb->st_ino = unp->unp_ino;
1062 UNP_PCB_UNLOCK(unp);
1068 uipc_shutdown(struct socket *so)
1072 unp = sotounpcb(so);
1073 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1079 UNP_PCB_UNLOCK(unp);
1085 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1088 const struct sockaddr *sa;
1090 unp = sotounpcb(so);
1091 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1093 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1095 if (unp->unp_addr != NULL)
1096 sa = (struct sockaddr *) unp->unp_addr;
1099 bcopy(sa, *nam, sa->sa_len);
1100 UNP_PCB_UNLOCK(unp);
1104 static struct pr_usrreqs uipc_usrreqs_dgram = {
1105 .pru_abort = uipc_abort,
1106 .pru_accept = uipc_accept,
1107 .pru_attach = uipc_attach,
1108 .pru_bind = uipc_bind,
1109 .pru_bindat = uipc_bindat,
1110 .pru_connect = uipc_connect,
1111 .pru_connectat = uipc_connectat,
1112 .pru_connect2 = uipc_connect2,
1113 .pru_detach = uipc_detach,
1114 .pru_disconnect = uipc_disconnect,
1115 .pru_listen = uipc_listen,
1116 .pru_peeraddr = uipc_peeraddr,
1117 .pru_rcvd = uipc_rcvd,
1118 .pru_send = uipc_send,
1119 .pru_sense = uipc_sense,
1120 .pru_shutdown = uipc_shutdown,
1121 .pru_sockaddr = uipc_sockaddr,
1122 .pru_soreceive = soreceive_dgram,
1123 .pru_close = uipc_close,
1126 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1127 .pru_abort = uipc_abort,
1128 .pru_accept = uipc_accept,
1129 .pru_attach = uipc_attach,
1130 .pru_bind = uipc_bind,
1131 .pru_bindat = uipc_bindat,
1132 .pru_connect = uipc_connect,
1133 .pru_connectat = uipc_connectat,
1134 .pru_connect2 = uipc_connect2,
1135 .pru_detach = uipc_detach,
1136 .pru_disconnect = uipc_disconnect,
1137 .pru_listen = uipc_listen,
1138 .pru_peeraddr = uipc_peeraddr,
1139 .pru_rcvd = uipc_rcvd,
1140 .pru_send = uipc_send,
1141 .pru_sense = uipc_sense,
1142 .pru_shutdown = uipc_shutdown,
1143 .pru_sockaddr = uipc_sockaddr,
1144 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1145 .pru_close = uipc_close,
1148 static struct pr_usrreqs uipc_usrreqs_stream = {
1149 .pru_abort = uipc_abort,
1150 .pru_accept = uipc_accept,
1151 .pru_attach = uipc_attach,
1152 .pru_bind = uipc_bind,
1153 .pru_bindat = uipc_bindat,
1154 .pru_connect = uipc_connect,
1155 .pru_connectat = uipc_connectat,
1156 .pru_connect2 = uipc_connect2,
1157 .pru_detach = uipc_detach,
1158 .pru_disconnect = uipc_disconnect,
1159 .pru_listen = uipc_listen,
1160 .pru_peeraddr = uipc_peeraddr,
1161 .pru_rcvd = uipc_rcvd,
1162 .pru_send = uipc_send,
1163 .pru_sense = uipc_sense,
1164 .pru_shutdown = uipc_shutdown,
1165 .pru_sockaddr = uipc_sockaddr,
1166 .pru_soreceive = soreceive_generic,
1167 .pru_close = uipc_close,
1171 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1177 if (sopt->sopt_level != 0)
1180 unp = sotounpcb(so);
1181 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1183 switch (sopt->sopt_dir) {
1185 switch (sopt->sopt_name) {
1186 case LOCAL_PEERCRED:
1188 if (unp->unp_flags & UNP_HAVEPC)
1189 xu = unp->unp_peercred;
1191 if (so->so_type == SOCK_STREAM)
1196 UNP_PCB_UNLOCK(unp);
1198 error = sooptcopyout(sopt, &xu, sizeof(xu));
1202 /* Unlocked read. */
1203 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1204 error = sooptcopyout(sopt, &optval, sizeof(optval));
1207 case LOCAL_CONNWAIT:
1208 /* Unlocked read. */
1209 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1210 error = sooptcopyout(sopt, &optval, sizeof(optval));
1220 switch (sopt->sopt_name) {
1222 case LOCAL_CONNWAIT:
1223 error = sooptcopyin(sopt, &optval, sizeof(optval),
1228 #define OPTSET(bit) do { \
1229 UNP_PCB_LOCK(unp); \
1231 unp->unp_flags |= bit; \
1233 unp->unp_flags &= ~bit; \
1234 UNP_PCB_UNLOCK(unp); \
1237 switch (sopt->sopt_name) {
1239 OPTSET(UNP_WANTCRED);
1242 case LOCAL_CONNWAIT:
1243 OPTSET(UNP_CONNWAIT);
1252 error = ENOPROTOOPT;
1265 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1268 return (unp_connectat(AT_FDCWD, so, nam, td));
1272 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1275 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1277 struct socket *so2, *so3;
1278 struct unpcb *unp, *unp2, *unp3;
1280 struct nameidata nd;
1281 char buf[SOCK_MAXADDRLEN];
1282 struct sockaddr *sa;
1284 UNP_LINK_WLOCK_ASSERT();
1286 unp = sotounpcb(so);
1287 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1289 if (nam->sa_len > sizeof(struct sockaddr_un))
1291 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1294 bcopy(soun->sun_path, buf, len);
1298 if (unp->unp_flags & UNP_CONNECTING) {
1299 UNP_PCB_UNLOCK(unp);
1303 unp->unp_flags |= UNP_CONNECTING;
1304 UNP_PCB_UNLOCK(unp);
1306 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1307 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1308 UIO_SYSSPACE, buf, fd, CAP_CONNECTAT, td);
1314 ASSERT_VOP_LOCKED(vp, "unp_connect");
1315 NDFREE(&nd, NDF_ONLY_PNBUF);
1319 if (vp->v_type != VSOCK) {
1324 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1328 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1332 unp = sotounpcb(so);
1333 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1336 * Lock linkage lock for two reasons: make sure v_socket is stable,
1337 * and to protect simultaneous locking of multiple pcbs.
1340 VOP_UNP_CONNECT(vp, &so2);
1342 error = ECONNREFUSED;
1345 if (so->so_type != so2->so_type) {
1349 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1350 if (so2->so_options & SO_ACCEPTCONN) {
1351 CURVNET_SET(so2->so_vnet);
1352 so3 = sonewconn(so2, 0);
1357 error = ECONNREFUSED;
1360 unp = sotounpcb(so);
1361 unp2 = sotounpcb(so2);
1362 unp3 = sotounpcb(so3);
1366 if (unp2->unp_addr != NULL) {
1367 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1368 unp3->unp_addr = (struct sockaddr_un *) sa;
1373 * The connecter's (client's) credentials are copied from its
1374 * process structure at the time of connect() (which is now).
1376 cru2x(td->td_ucred, &unp3->unp_peercred);
1377 unp3->unp_flags |= UNP_HAVEPC;
1380 * The receiver's (server's) credentials are copied from the
1381 * unp_peercred member of socket on which the former called
1382 * listen(); uipc_listen() cached that process's credentials
1383 * at that time so we can use them now.
1385 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1386 ("unp_connect: listener without cached peercred"));
1387 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1388 sizeof(unp->unp_peercred));
1389 unp->unp_flags |= UNP_HAVEPC;
1390 if (unp2->unp_flags & UNP_WANTCRED)
1391 unp3->unp_flags |= UNP_WANTCRED;
1392 UNP_PCB_UNLOCK(unp3);
1393 UNP_PCB_UNLOCK(unp2);
1394 UNP_PCB_UNLOCK(unp);
1396 mac_socketpeer_set_from_socket(so, so3);
1397 mac_socketpeer_set_from_socket(so3, so);
1402 unp = sotounpcb(so);
1403 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1404 unp2 = sotounpcb(so2);
1405 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1408 error = unp_connect2(so, so2, PRU_CONNECT);
1409 UNP_PCB_UNLOCK(unp2);
1410 UNP_PCB_UNLOCK(unp);
1419 unp->unp_flags &= ~UNP_CONNECTING;
1420 UNP_PCB_UNLOCK(unp);
1425 unp_connect2(struct socket *so, struct socket *so2, int req)
1430 unp = sotounpcb(so);
1431 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1432 unp2 = sotounpcb(so2);
1433 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1435 UNP_LINK_WLOCK_ASSERT();
1436 UNP_PCB_LOCK_ASSERT(unp);
1437 UNP_PCB_LOCK_ASSERT(unp2);
1439 if (so2->so_type != so->so_type)
1440 return (EPROTOTYPE);
1441 unp->unp_conn = unp2;
1443 switch (so->so_type) {
1445 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1450 case SOCK_SEQPACKET:
1451 unp2->unp_conn = unp;
1452 if (req == PRU_CONNECT &&
1453 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1461 panic("unp_connect2");
1467 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1471 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1473 UNP_LINK_WLOCK_ASSERT();
1474 UNP_PCB_LOCK_ASSERT(unp);
1475 UNP_PCB_LOCK_ASSERT(unp2);
1477 unp->unp_conn = NULL;
1478 switch (unp->unp_socket->so_type) {
1480 LIST_REMOVE(unp, unp_reflink);
1481 so = unp->unp_socket;
1483 so->so_state &= ~SS_ISCONNECTED;
1488 case SOCK_SEQPACKET:
1489 soisdisconnected(unp->unp_socket);
1490 unp2->unp_conn = NULL;
1491 soisdisconnected(unp2->unp_socket);
1497 * unp_pcblist() walks the global list of struct unpcb's to generate a
1498 * pointer list, bumping the refcount on each unpcb. It then copies them out
1499 * sequentially, validating the generation number on each to see if it has
1500 * been detached. All of this is necessary because copyout() may sleep on
1504 unp_pcblist(SYSCTL_HANDLER_ARGS)
1508 struct unpcb *unp, **unp_list;
1510 struct xunpgen *xug;
1511 struct unp_head *head;
1514 switch ((intptr_t)arg1) {
1523 case SOCK_SEQPACKET:
1528 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1532 * The process of preparing the PCB list is too time-consuming and
1533 * resource-intensive to repeat twice on every request.
1535 if (req->oldptr == NULL) {
1537 req->oldidx = 2 * (sizeof *xug)
1538 + (n + n/8) * sizeof(struct xunpcb);
1542 if (req->newptr != NULL)
1546 * OK, now we're committed to doing something.
1548 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1550 gencnt = unp_gencnt;
1554 xug->xug_len = sizeof *xug;
1556 xug->xug_gen = gencnt;
1557 xug->xug_sogen = so_gencnt;
1558 error = SYSCTL_OUT(req, xug, sizeof *xug);
1564 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1567 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1568 unp = LIST_NEXT(unp, unp_link)) {
1570 if (unp->unp_gencnt <= gencnt) {
1571 if (cr_cansee(req->td->td_ucred,
1572 unp->unp_socket->so_cred)) {
1573 UNP_PCB_UNLOCK(unp);
1576 unp_list[i++] = unp;
1577 unp->unp_refcount++;
1579 UNP_PCB_UNLOCK(unp);
1582 n = i; /* In case we lost some during malloc. */
1585 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1586 for (i = 0; i < n; i++) {
1589 unp->unp_refcount--;
1590 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1591 xu->xu_len = sizeof *xu;
1594 * XXX - need more locking here to protect against
1595 * connect/disconnect races for SMP.
1597 if (unp->unp_addr != NULL)
1598 bcopy(unp->unp_addr, &xu->xu_addr,
1599 unp->unp_addr->sun_len);
1600 if (unp->unp_conn != NULL &&
1601 unp->unp_conn->unp_addr != NULL)
1602 bcopy(unp->unp_conn->unp_addr,
1604 unp->unp_conn->unp_addr->sun_len);
1605 bcopy(unp, &xu->xu_unp, sizeof *unp);
1606 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1607 UNP_PCB_UNLOCK(unp);
1608 error = SYSCTL_OUT(req, xu, sizeof *xu);
1610 freeunp = (unp->unp_refcount == 0);
1611 UNP_PCB_UNLOCK(unp);
1613 UNP_PCB_LOCK_DESTROY(unp);
1614 uma_zfree(unp_zone, unp);
1621 * Give the user an updated idea of our state. If the
1622 * generation differs from what we told her before, she knows
1623 * that something happened while we were processing this
1624 * request, and it might be necessary to retry.
1626 xug->xug_gen = unp_gencnt;
1627 xug->xug_sogen = so_gencnt;
1628 xug->xug_count = unp_count;
1629 error = SYSCTL_OUT(req, xug, sizeof *xug);
1631 free(unp_list, M_TEMP);
1636 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1637 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1638 "List of active local datagram sockets");
1639 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1640 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1641 "List of active local stream sockets");
1642 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1643 CTLTYPE_OPAQUE | CTLFLAG_RD,
1644 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1645 "List of active local seqpacket sockets");
1648 unp_shutdown(struct unpcb *unp)
1653 UNP_LINK_WLOCK_ASSERT();
1654 UNP_PCB_LOCK_ASSERT(unp);
1656 unp2 = unp->unp_conn;
1657 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1658 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1659 so = unp2->unp_socket;
1666 unp_drop(struct unpcb *unp, int errno)
1668 struct socket *so = unp->unp_socket;
1671 UNP_LINK_WLOCK_ASSERT();
1672 UNP_PCB_LOCK_ASSERT(unp);
1674 so->so_error = errno;
1675 unp2 = unp->unp_conn;
1679 unp_disconnect(unp, unp2);
1680 UNP_PCB_UNLOCK(unp2);
1684 unp_freerights(struct filedescent **fdep, int fdcount)
1689 for (i = 0; i < fdcount; i++) {
1690 fp = fdep[i]->fde_file;
1691 filecaps_free(&fdep[i]->fde_caps);
1694 free(fdep[0], M_FILECAPS);
1698 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1700 struct thread *td = curthread; /* XXX */
1701 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1704 struct filedesc *fdesc = td->td_proc->p_fd;
1705 struct filedescent *fde, **fdep;
1707 socklen_t clen = control->m_len, datalen;
1712 UNP_LINK_UNLOCK_ASSERT();
1715 if (controlp != NULL) /* controlp == NULL => free control messages */
1717 while (cm != NULL) {
1718 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1722 data = CMSG_DATA(cm);
1723 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1724 if (cm->cmsg_level == SOL_SOCKET
1725 && cm->cmsg_type == SCM_RIGHTS) {
1726 newfds = datalen / sizeof(*fdep);
1729 /* If we're not outputting the descriptors free them. */
1730 if (error || controlp == NULL) {
1731 unp_freerights(fdep, newfds);
1734 FILEDESC_XLOCK(fdesc);
1735 /* if the new FD's will not fit free them. */
1736 if (!fdavail(td, newfds)) {
1737 FILEDESC_XUNLOCK(fdesc);
1739 unp_freerights(fdep, newfds);
1744 * Now change each pointer to an fd in the global
1745 * table to an integer that is the index to the local
1746 * fd table entry that we set up to point to the
1747 * global one we are transferring.
1749 newlen = newfds * sizeof(int);
1750 *controlp = sbcreatecontrol(NULL, newlen,
1751 SCM_RIGHTS, SOL_SOCKET);
1752 if (*controlp == NULL) {
1753 FILEDESC_XUNLOCK(fdesc);
1755 unp_freerights(fdep, newfds);
1760 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1761 for (i = 0; i < newfds; i++, fdp++) {
1762 if (fdalloc(td, 0, &f))
1763 panic("unp_externalize fdalloc failed");
1764 fde = &fdesc->fd_ofiles[f];
1765 fde->fde_file = fdep[0]->fde_file;
1766 filecaps_move(&fdep[0]->fde_caps,
1768 unp_externalize_fp(fde->fde_file);
1771 FILEDESC_XUNLOCK(fdesc);
1772 free(fdep[0], M_FILECAPS);
1774 /* We can just copy anything else across. */
1775 if (error || controlp == NULL)
1777 *controlp = sbcreatecontrol(NULL, datalen,
1778 cm->cmsg_type, cm->cmsg_level);
1779 if (*controlp == NULL) {
1784 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1787 controlp = &(*controlp)->m_next;
1790 if (CMSG_SPACE(datalen) < clen) {
1791 clen -= CMSG_SPACE(datalen);
1792 cm = (struct cmsghdr *)
1793 ((caddr_t)cm + CMSG_SPACE(datalen));
1805 unp_zone_change(void *tag)
1808 uma_zone_set_max(unp_zone, maxsockets);
1816 if (!IS_DEFAULT_VNET(curvnet))
1819 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1820 NULL, NULL, UMA_ALIGN_PTR, 0);
1821 if (unp_zone == NULL)
1823 uma_zone_set_max(unp_zone, maxsockets);
1824 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
1825 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1826 NULL, EVENTHANDLER_PRI_ANY);
1827 LIST_INIT(&unp_dhead);
1828 LIST_INIT(&unp_shead);
1829 LIST_INIT(&unp_sphead);
1830 SLIST_INIT(&unp_defers);
1831 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
1832 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1833 UNP_LINK_LOCK_INIT();
1834 UNP_LIST_LOCK_INIT();
1835 UNP_DEFERRED_LOCK_INIT();
1839 unp_internalize(struct mbuf **controlp, struct thread *td)
1841 struct mbuf *control = *controlp;
1842 struct proc *p = td->td_proc;
1843 struct filedesc *fdesc = p->p_fd;
1845 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1846 struct cmsgcred *cmcred;
1847 struct filedescent *fde, **fdep, *fdev;
1852 socklen_t clen = control->m_len, datalen;
1856 UNP_LINK_UNLOCK_ASSERT();
1860 while (cm != NULL) {
1861 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1862 || cm->cmsg_len > clen) {
1866 data = CMSG_DATA(cm);
1867 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1869 switch (cm->cmsg_type) {
1871 * Fill in credential information.
1874 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1875 SCM_CREDS, SOL_SOCKET);
1876 if (*controlp == NULL) {
1880 cmcred = (struct cmsgcred *)
1881 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1882 cmcred->cmcred_pid = p->p_pid;
1883 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1884 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1885 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1886 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1888 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1889 cmcred->cmcred_groups[i] =
1890 td->td_ucred->cr_groups[i];
1894 oldfds = datalen / sizeof (int);
1896 * Check that all the FDs passed in refer to legal
1897 * files. If not, reject the entire operation.
1900 FILEDESC_SLOCK(fdesc);
1901 for (i = 0; i < oldfds; i++) {
1903 if (fget_locked(fdesc, fd) == NULL) {
1904 FILEDESC_SUNLOCK(fdesc);
1908 fp = fdesc->fd_ofiles[fd].fde_file;
1909 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1910 FILEDESC_SUNLOCK(fdesc);
1918 * Now replace the integer FDs with pointers to the
1919 * file structure and capability rights.
1921 newlen = oldfds * sizeof(fdep[0]);
1922 *controlp = sbcreatecontrol(NULL, newlen,
1923 SCM_RIGHTS, SOL_SOCKET);
1924 if (*controlp == NULL) {
1925 FILEDESC_SUNLOCK(fdesc);
1930 fdep = (struct filedescent **)
1931 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1932 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
1934 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
1935 fde = &fdesc->fd_ofiles[*fdp];
1937 fdep[i]->fde_file = fde->fde_file;
1938 filecaps_copy(&fde->fde_caps,
1939 &fdep[i]->fde_caps);
1940 unp_internalize_fp(fdep[i]->fde_file);
1942 FILEDESC_SUNLOCK(fdesc);
1946 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1947 SCM_TIMESTAMP, SOL_SOCKET);
1948 if (*controlp == NULL) {
1952 tv = (struct timeval *)
1953 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1958 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
1959 SCM_BINTIME, SOL_SOCKET);
1960 if (*controlp == NULL) {
1964 bt = (struct bintime *)
1965 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1974 controlp = &(*controlp)->m_next;
1975 if (CMSG_SPACE(datalen) < clen) {
1976 clen -= CMSG_SPACE(datalen);
1977 cm = (struct cmsghdr *)
1978 ((caddr_t)cm + CMSG_SPACE(datalen));
1990 static struct mbuf *
1991 unp_addsockcred(struct thread *td, struct mbuf *control)
1993 struct mbuf *m, *n, *n_prev;
1994 struct sockcred *sc;
1995 const struct cmsghdr *cm;
1999 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2000 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2004 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2005 sc->sc_uid = td->td_ucred->cr_ruid;
2006 sc->sc_euid = td->td_ucred->cr_uid;
2007 sc->sc_gid = td->td_ucred->cr_rgid;
2008 sc->sc_egid = td->td_ucred->cr_gid;
2009 sc->sc_ngroups = ngroups;
2010 for (i = 0; i < sc->sc_ngroups; i++)
2011 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2014 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2015 * created SCM_CREDS control message (struct sockcred) has another
2018 if (control != NULL)
2019 for (n = control, n_prev = NULL; n != NULL;) {
2020 cm = mtod(n, struct cmsghdr *);
2021 if (cm->cmsg_level == SOL_SOCKET &&
2022 cm->cmsg_type == SCM_CREDS) {
2024 control = n->m_next;
2026 n_prev->m_next = n->m_next;
2034 /* Prepend it to the head. */
2035 m->m_next = control;
2039 static struct unpcb *
2040 fptounp(struct file *fp)
2044 if (fp->f_type != DTYPE_SOCKET)
2046 if ((so = fp->f_data) == NULL)
2048 if (so->so_proto->pr_domain != &localdomain)
2050 return sotounpcb(so);
2054 unp_discard(struct file *fp)
2056 struct unp_defer *dr;
2058 if (unp_externalize_fp(fp)) {
2059 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2061 UNP_DEFERRED_LOCK();
2062 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2063 UNP_DEFERRED_UNLOCK();
2064 atomic_add_int(&unp_defers_count, 1);
2065 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2067 (void) closef(fp, (struct thread *)NULL);
2071 unp_process_defers(void *arg __unused, int pending)
2073 struct unp_defer *dr;
2074 SLIST_HEAD(, unp_defer) drl;
2079 UNP_DEFERRED_LOCK();
2080 if (SLIST_FIRST(&unp_defers) == NULL) {
2081 UNP_DEFERRED_UNLOCK();
2084 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2085 UNP_DEFERRED_UNLOCK();
2087 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2088 SLIST_REMOVE_HEAD(&drl, ud_link);
2089 closef(dr->ud_fp, NULL);
2093 atomic_add_int(&unp_defers_count, -count);
2098 unp_internalize_fp(struct file *fp)
2103 if ((unp = fptounp(fp)) != NULL) {
2105 unp->unp_msgcount++;
2113 unp_externalize_fp(struct file *fp)
2119 if ((unp = fptounp(fp)) != NULL) {
2120 unp->unp_msgcount--;
2130 * unp_defer indicates whether additional work has been defered for a future
2131 * pass through unp_gc(). It is thread local and does not require explicit
2134 static int unp_marked;
2135 static int unp_unreachable;
2138 unp_accessable(struct file *fp)
2142 if ((unp = fptounp(fp)) == NULL)
2144 if (unp->unp_gcflag & UNPGC_REF)
2146 unp->unp_gcflag &= ~UNPGC_DEAD;
2147 unp->unp_gcflag |= UNPGC_REF;
2152 unp_gc_process(struct unpcb *unp)
2158 /* Already processed. */
2159 if (unp->unp_gcflag & UNPGC_SCANNED)
2164 * Check for a socket potentially in a cycle. It must be in a
2165 * queue as indicated by msgcount, and this must equal the file
2166 * reference count. Note that when msgcount is 0 the file is NULL.
2168 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2169 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2170 unp->unp_gcflag |= UNPGC_DEAD;
2176 * Mark all sockets we reference with RIGHTS.
2178 so = unp->unp_socket;
2179 SOCKBUF_LOCK(&so->so_rcv);
2180 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2181 SOCKBUF_UNLOCK(&so->so_rcv);
2184 * Mark all sockets in our accept queue.
2187 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2188 SOCKBUF_LOCK(&soa->so_rcv);
2189 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2190 SOCKBUF_UNLOCK(&soa->so_rcv);
2193 unp->unp_gcflag |= UNPGC_SCANNED;
2196 static int unp_recycled;
2197 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2198 "Number of unreachable sockets claimed by the garbage collector.");
2200 static int unp_taskcount;
2201 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2202 "Number of times the garbage collector has run.");
2205 unp_gc(__unused void *arg, int pending)
2207 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2209 struct unp_head **head;
2210 struct file *f, **unref;
2217 * First clear all gc flags from previous runs.
2219 for (head = heads; *head != NULL; head++)
2220 LIST_FOREACH(unp, *head, unp_link)
2221 unp->unp_gcflag = 0;
2224 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2225 * is reachable all of the sockets it references are reachable.
2226 * Stop the scan once we do a complete loop without discovering
2227 * a new reachable socket.
2230 unp_unreachable = 0;
2232 for (head = heads; *head != NULL; head++)
2233 LIST_FOREACH(unp, *head, unp_link)
2234 unp_gc_process(unp);
2235 } while (unp_marked);
2237 if (unp_unreachable == 0)
2241 * Allocate space for a local list of dead unpcbs.
2243 unref = malloc(unp_unreachable * sizeof(struct file *),
2247 * Iterate looking for sockets which have been specifically marked
2248 * as as unreachable and store them locally.
2252 for (total = 0, head = heads; *head != NULL; head++)
2253 LIST_FOREACH(unp, *head, unp_link)
2254 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2256 if (unp->unp_msgcount == 0 || f == NULL ||
2257 f->f_count != unp->unp_msgcount)
2261 KASSERT(total <= unp_unreachable,
2262 ("unp_gc: incorrect unreachable count."));
2268 * Now flush all sockets, free'ing rights. This will free the
2269 * struct files associated with these sockets but leave each socket
2270 * with one remaining ref.
2272 for (i = 0; i < total; i++) {
2275 so = unref[i]->f_data;
2276 CURVNET_SET(so->so_vnet);
2282 * And finally release the sockets so they can be reclaimed.
2284 for (i = 0; i < total; i++)
2285 fdrop(unref[i], NULL);
2286 unp_recycled += total;
2287 free(unref, M_TEMP);
2291 unp_dispose(struct mbuf *m)
2295 unp_scan(m, unp_discard);
2299 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2302 struct filedescent **fdep;
2306 socklen_t clen, datalen;
2309 while (m0 != NULL) {
2310 for (m = m0; m; m = m->m_next) {
2311 if (m->m_type != MT_CONTROL)
2314 cm = mtod(m, struct cmsghdr *);
2317 while (cm != NULL) {
2318 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2321 data = CMSG_DATA(cm);
2322 datalen = (caddr_t)cm + cm->cmsg_len
2325 if (cm->cmsg_level == SOL_SOCKET &&
2326 cm->cmsg_type == SCM_RIGHTS) {
2327 qfds = datalen / sizeof(*fdep);
2329 for (i = 0; i < qfds; i++)
2330 (*op)(fdep[i]->fde_file);
2333 if (CMSG_SPACE(datalen) < clen) {
2334 clen -= CMSG_SPACE(datalen);
2335 cm = (struct cmsghdr *)
2336 ((caddr_t)cm + CMSG_SPACE(datalen));
2348 * A helper function called by VFS before socket-type vnode reclamation.
2349 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2353 vfs_unp_reclaim(struct vnode *vp)
2359 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2360 KASSERT(vp->v_type == VSOCK,
2361 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2365 VOP_UNP_CONNECT(vp, &so);
2368 unp = sotounpcb(so);
2372 if (unp->unp_vnode == vp) {
2374 unp->unp_vnode = NULL;
2377 UNP_PCB_UNLOCK(unp);
2386 db_print_indent(int indent)
2390 for (i = 0; i < indent; i++)
2395 db_print_unpflags(int unp_flags)
2400 if (unp_flags & UNP_HAVEPC) {
2401 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2404 if (unp_flags & UNP_HAVEPCCACHED) {
2405 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2408 if (unp_flags & UNP_WANTCRED) {
2409 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2412 if (unp_flags & UNP_CONNWAIT) {
2413 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2416 if (unp_flags & UNP_CONNECTING) {
2417 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2420 if (unp_flags & UNP_BINDING) {
2421 db_printf("%sUNP_BINDING", comma ? ", " : "");
2427 db_print_xucred(int indent, struct xucred *xu)
2431 db_print_indent(indent);
2432 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2433 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2434 db_print_indent(indent);
2435 db_printf("cr_groups: ");
2437 for (i = 0; i < xu->cr_ngroups; i++) {
2438 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2445 db_print_unprefs(int indent, struct unp_head *uh)
2451 LIST_FOREACH(unp, uh, unp_reflink) {
2452 if (counter % 4 == 0)
2453 db_print_indent(indent);
2454 db_printf("%p ", unp);
2455 if (counter % 4 == 3)
2459 if (counter != 0 && counter % 4 != 0)
2463 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2468 db_printf("usage: show unpcb <addr>\n");
2471 unp = (struct unpcb *)addr;
2473 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2476 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2479 db_printf("unp_refs:\n");
2480 db_print_unprefs(2, &unp->unp_refs);
2482 /* XXXRW: Would be nice to print the full address, if any. */
2483 db_printf("unp_addr: %p\n", unp->unp_addr);
2485 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2486 unp->unp_cc, unp->unp_mbcnt,
2487 (unsigned long long)unp->unp_gencnt);
2489 db_printf("unp_flags: %x (", unp->unp_flags);
2490 db_print_unpflags(unp->unp_flags);
2493 db_printf("unp_peercred:\n");
2494 db_print_xucred(2, &unp->unp_peercred);
2496 db_printf("unp_refcount: %u\n", unp->unp_refcount);