2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright 2004-2006 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. The implementation is substantially
45 * complicated by the fact that "ancillary data", such as file descriptors or
46 * credentials, may be passed across UNIX domain sockets. The potential for
47 * passing UNIX domain sockets over other UNIX domain sockets requires the
48 * implementation of a simple garbage collector to find and tear down cycles
49 * of disconnected sockets.
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
57 #include <sys/param.h>
58 #include <sys/domain.h>
59 #include <sys/fcntl.h>
60 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
61 #include <sys/eventhandler.h>
63 #include <sys/filedesc.h>
65 #include <sys/kernel.h>
69 #include <sys/mount.h>
70 #include <sys/mutex.h>
71 #include <sys/namei.h>
73 #include <sys/protosw.h>
74 #include <sys/resourcevar.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/signalvar.h>
80 #include <sys/sysctl.h>
81 #include <sys/systm.h>
82 #include <sys/taskqueue.h>
84 #include <sys/unpcb.h>
85 #include <sys/vnode.h>
89 static uma_zone_t unp_zone;
90 static unp_gen_t unp_gencnt;
91 static u_int unp_count;
93 static struct unp_head unp_shead, unp_dhead;
96 * Unix communications domain.
100 * rethink name space problems
101 * need a proper out-of-band
104 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
105 static ino_t unp_ino; /* prototype for fake inode numbers */
106 struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
109 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
110 * stream sockets, although the total for sender and receiver is actually
113 * Datagram sockets really use the sendspace as the maximum datagram size,
114 * and don't really want to reserve the sendspace. Their recvspace should be
115 * large enough for at least one max-size datagram plus address.
120 static u_long unpst_sendspace = PIPSIZ;
121 static u_long unpst_recvspace = PIPSIZ;
122 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
123 static u_long unpdg_recvspace = 4*1024;
125 static int unp_rights; /* file descriptors in flight */
127 SYSCTL_DECL(_net_local_stream);
128 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
129 &unpst_sendspace, 0, "");
130 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
131 &unpst_recvspace, 0, "");
132 SYSCTL_DECL(_net_local_dgram);
133 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
134 &unpdg_sendspace, 0, "");
135 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
136 &unpdg_recvspace, 0, "");
137 SYSCTL_DECL(_net_local);
138 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
141 * Currently, UNIX domain sockets are protected by a single subsystem lock,
142 * which covers global data structures and variables, the contents of each
143 * per-socket unpcb structure, and the so_pcb field in sockets attached to
144 * the UNIX domain. This provides for a moderate degree of paralellism, as
145 * receive operations on UNIX domain sockets do not need to acquire the
146 * subsystem lock. Finer grained locking to permit send() without acquiring
147 * a global lock would be a logical next step.
149 * The UNIX domain socket lock preceds all socket layer locks, including the
150 * socket lock and socket buffer lock, permitting UNIX domain socket code to
151 * call into socket support routines without releasing its locks.
153 * Some caution is required in areas where the UNIX domain socket code enters
154 * VFS in order to create or find rendezvous points. This results in
155 * dropping of the UNIX domain socket subsystem lock, acquisition of the
156 * Giant lock, and potential sleeping. This increases the chances of races,
157 * and exposes weaknesses in the socket->protocol API by offering poor
160 static struct mtx unp_mtx;
161 #define UNP_LOCK_INIT() \
162 mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
163 #define UNP_LOCK() mtx_lock(&unp_mtx)
164 #define UNP_UNLOCK() mtx_unlock(&unp_mtx)
165 #define UNP_LOCK_ASSERT() mtx_assert(&unp_mtx, MA_OWNED)
166 #define UNP_UNLOCK_ASSERT() mtx_assert(&unp_mtx, MA_NOTOWNED)
169 * Garbage collection of cyclic file descriptor/socket references occurs
170 * asynchronously in a taskqueue context in order to avoid recursion and
171 * reentrance in the UNIX domain socket, file descriptor, and socket layer
172 * code. See unp_gc() for a full description.
174 static struct task unp_gc_task;
176 static int unp_connect(struct socket *,struct sockaddr *, struct thread *);
177 static int unp_connect2(struct socket *so, struct socket *so2, int);
178 static void unp_disconnect(struct unpcb *);
179 static void unp_shutdown(struct unpcb *);
180 static void unp_drop(struct unpcb *, int);
181 static void unp_gc(__unused void *, int);
182 static void unp_scan(struct mbuf *, void (*)(struct file *));
183 static void unp_mark(struct file *);
184 static void unp_discard(struct file *);
185 static void unp_freerights(struct file **, int);
186 static int unp_internalize(struct mbuf **, struct thread *);
187 static int unp_listen(struct socket *, struct unpcb *, int,
191 uipc_abort(struct socket *so)
196 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
198 unp_drop(unp, ECONNABORTED);
203 uipc_accept(struct socket *so, struct sockaddr **nam)
206 const struct sockaddr *sa;
209 * Pass back name of connected socket, if it was bound and we are
210 * still connected (our peer may have closed already!).
213 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
214 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
216 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
217 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
220 bcopy(sa, *nam, sa->sa_len);
226 uipc_attach(struct socket *so, int proto, struct thread *td)
231 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
232 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
233 switch (so->so_type) {
236 error = soreserve(so, unpst_sendspace, unpst_recvspace);
240 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
249 unp = uma_zalloc(unp_zone, M_WAITOK | M_ZERO);
252 LIST_INIT(&unp->unp_refs);
253 unp->unp_socket = so;
257 unp->unp_gencnt = ++unp_gencnt;
259 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
260 : &unp_shead, unp, unp_link);
267 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
269 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
279 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
281 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
286 * We don't allow simultaneous bind() calls on a single UNIX domain
287 * socket, so flag in-progress operations, and return an error if an
288 * operation is already in progress.
290 * Historically, we have not allowed a socket to be rebound, so this
291 * also returns an error. Not allowing re-binding certainly
292 * simplifies the implementation and avoids a great many possible
296 if (unp->unp_vnode != NULL) {
300 if (unp->unp_flags & UNP_BINDING) {
304 unp->unp_flags |= UNP_BINDING;
307 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
308 strlcpy(buf, soun->sun_path, namelen + 1);
312 mtx_assert(&Giant, MA_OWNED);
313 NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
315 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
320 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
321 NDFREE(&nd, NDF_ONLY_PNBUF);
331 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
337 vattr.va_type = VSOCK;
338 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
340 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
344 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
345 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
347 NDFREE(&nd, NDF_ONLY_PNBUF);
350 vn_finished_write(mp);
354 ASSERT_VOP_LOCKED(vp, "uipc_bind");
355 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
357 vp->v_socket = unp->unp_socket;
359 unp->unp_addr = soun;
360 unp->unp_flags &= ~UNP_BINDING;
362 VOP_UNLOCK(vp, 0, td);
363 vn_finished_write(mp);
369 unp->unp_flags &= ~UNP_BINDING;
377 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
381 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
383 error = unp_connect(so, nam, td);
389 * XXXRW: Should also unbind?
392 uipc_close(struct socket *so)
397 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
404 uipc_connect2(struct socket *so1, struct socket *so2)
409 unp = sotounpcb(so1);
410 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
412 error = unp_connect2(so1, so2, PRU_CONNECT2);
417 /* control is EOPNOTSUPP */
420 uipc_detach(struct socket *so)
422 int local_unp_rights;
427 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
429 LIST_REMOVE(unp, unp_link);
430 unp->unp_gencnt = ++unp_gencnt;
432 if ((vp = unp->unp_vnode) != NULL) {
434 * XXXRW: should v_socket be frobbed only while holding
437 unp->unp_vnode->v_socket = NULL;
438 unp->unp_vnode = NULL;
440 if (unp->unp_conn != NULL)
442 while (!LIST_EMPTY(&unp->unp_refs)) {
443 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
444 unp_drop(ref, ECONNRESET);
446 unp->unp_socket->so_pcb = NULL;
447 local_unp_rights = unp_rights;
449 if (unp->unp_addr != NULL)
450 FREE(unp->unp_addr, M_SONAME);
451 uma_zfree(unp_zone, unp);
455 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
457 VFS_UNLOCK_GIANT(vfslocked);
459 if (local_unp_rights)
460 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
464 uipc_disconnect(struct socket *so)
469 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
477 uipc_listen(struct socket *so, int backlog, struct thread *td)
483 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
485 if (unp->unp_vnode == NULL) {
489 error = unp_listen(so, unp, backlog, td);
495 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
498 const struct sockaddr *sa;
501 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
502 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
504 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
505 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
508 * XXX: It seems that this test always fails even when
509 * connection is established. So, this else clause is
510 * added as workaround to return PF_LOCAL sockaddr.
514 bcopy(sa, *nam, sa->sa_len);
520 uipc_rcvd(struct socket *so, int flags)
528 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
529 switch (so->so_type) {
531 panic("uipc_rcvd DGRAM?");
536 * Adjust backpressure on sender and wakeup any waiting to
539 SOCKBUF_LOCK(&so->so_rcv);
540 mbcnt = so->so_rcv.sb_mbcnt;
541 sbcc = so->so_rcv.sb_cc;
542 SOCKBUF_UNLOCK(&so->so_rcv);
544 if (unp->unp_conn == NULL) {
548 so2 = unp->unp_conn->unp_socket;
549 SOCKBUF_LOCK(&so2->so_snd);
550 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
551 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
552 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
553 newhiwat, RLIM_INFINITY);
554 sowwakeup_locked(so2);
555 unp->unp_mbcnt = mbcnt;
561 panic("uipc_rcvd unknown socktype");
566 /* pru_rcvoob is EOPNOTSUPP */
569 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
570 struct mbuf *control, struct thread *td)
572 struct unpcb *unp, *unp2;
579 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
580 if (flags & PRUS_OOB) {
585 if (control != NULL && (error = unp_internalize(&control, td)))
589 switch (so->so_type) {
592 const struct sockaddr *from;
595 if (unp->unp_conn != NULL) {
599 error = unp_connect(so, nam, td);
603 if (unp->unp_conn == NULL) {
609 * Because connect() and send() are non-atomic in a sendto()
610 * with a target address, it's possible that the socket will
611 * have disconnected before the send() can run. In that case
612 * return the slightly counter-intuitive but otherwise
613 * correct error that the socket is not connected.
615 unp2 = unp->unp_conn;
620 so2 = unp2->unp_socket;
621 if (unp->unp_addr != NULL)
622 from = (struct sockaddr *)unp->unp_addr;
625 if (unp2->unp_flags & UNP_WANTCRED)
626 control = unp_addsockcred(td, control);
627 SOCKBUF_LOCK(&so2->so_rcv);
628 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
629 sorwakeup_locked(so2);
633 SOCKBUF_UNLOCK(&so2->so_rcv);
643 * Connect if not connected yet.
645 * Note: A better implementation would complain if not equal
646 * to the peer's address.
648 if ((so->so_state & SS_ISCONNECTED) == 0) {
650 error = unp_connect(so, nam, td);
660 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
665 * Because connect() and send() are non-atomic in a sendto()
666 * with a target address, it's possible that the socket will
667 * have disconnected before the send() can run. In that case
668 * return the slightly counter-intuitive but otherwise
669 * correct error that the socket is not connected.
671 unp2 = unp->unp_conn;
676 so2 = unp2->unp_socket;
677 SOCKBUF_LOCK(&so2->so_rcv);
678 if (unp2->unp_flags & UNP_WANTCRED) {
680 * Credentials are passed only once on
683 unp2->unp_flags &= ~UNP_WANTCRED;
684 control = unp_addsockcred(td, control);
687 * Send to paired receive port, and then reduce send buffer
688 * hiwater marks to maintain backpressure. Wake up readers.
690 if (control != NULL) {
691 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
694 sbappend_locked(&so2->so_rcv, m);
696 mbcnt = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
697 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
698 sbcc = so2->so_rcv.sb_cc;
699 sorwakeup_locked(so2);
701 SOCKBUF_LOCK(&so->so_snd);
702 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
703 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
704 newhiwat, RLIM_INFINITY);
705 so->so_snd.sb_mbmax -= mbcnt;
706 SOCKBUF_UNLOCK(&so->so_snd);
713 panic("uipc_send unknown socktype");
717 * SEND_EOF is equivalent to a SEND followed by
720 if (flags & PRUS_EOF) {
726 if (control != NULL && error != 0)
727 unp_dispose(control);
738 uipc_sense(struct socket *so, struct stat *sb)
744 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
746 sb->st_blksize = so->so_snd.sb_hiwat;
747 if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
748 so2 = unp->unp_conn->unp_socket;
749 sb->st_blksize += so2->so_rcv.sb_cc;
752 if (unp->unp_ino == 0)
753 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
754 sb->st_ino = unp->unp_ino;
760 uipc_shutdown(struct socket *so)
765 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
774 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
777 const struct sockaddr *sa;
780 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
781 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
783 if (unp->unp_addr != NULL)
784 sa = (struct sockaddr *) unp->unp_addr;
787 bcopy(sa, *nam, sa->sa_len);
792 struct pr_usrreqs uipc_usrreqs = {
793 .pru_abort = uipc_abort,
794 .pru_accept = uipc_accept,
795 .pru_attach = uipc_attach,
796 .pru_bind = uipc_bind,
797 .pru_connect = uipc_connect,
798 .pru_connect2 = uipc_connect2,
799 .pru_detach = uipc_detach,
800 .pru_disconnect = uipc_disconnect,
801 .pru_listen = uipc_listen,
802 .pru_peeraddr = uipc_peeraddr,
803 .pru_rcvd = uipc_rcvd,
804 .pru_send = uipc_send,
805 .pru_sense = uipc_sense,
806 .pru_shutdown = uipc_shutdown,
807 .pru_sockaddr = uipc_sockaddr,
808 .pru_sosend = sosend_generic,
809 .pru_soreceive = soreceive_generic,
810 .pru_sopoll = sopoll_generic,
811 .pru_close = uipc_close,
815 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
821 if (sopt->sopt_level != 0)
825 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
828 switch (sopt->sopt_dir) {
830 switch (sopt->sopt_name) {
832 if (unp->unp_flags & UNP_HAVEPC)
833 xu = unp->unp_peercred;
835 if (so->so_type == SOCK_STREAM)
841 error = sooptcopyout(sopt, &xu, sizeof(xu));
844 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
845 error = sooptcopyout(sopt, &optval, sizeof(optval));
848 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
849 error = sooptcopyout(sopt, &optval, sizeof(optval));
857 switch (sopt->sopt_name) {
860 error = sooptcopyin(sopt, &optval, sizeof(optval),
865 #define OPTSET(bit) \
867 unp->unp_flags |= bit; \
869 unp->unp_flags &= ~bit;
871 switch (sopt->sopt_name) {
873 OPTSET(UNP_WANTCRED);
876 OPTSET(UNP_CONNWAIT);
897 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
899 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
901 struct socket *so2, *so3;
902 struct unpcb *unp, *unp2, *unp3;
905 char buf[SOCK_MAXADDRLEN];
911 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
912 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
915 strlcpy(buf, soun->sun_path, len + 1);
916 if (unp->unp_flags & UNP_CONNECTING) {
921 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
923 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
929 ASSERT_VOP_LOCKED(vp, "unp_connect");
930 NDFREE(&nd, NDF_ONLY_PNBUF);
934 if (vp->v_type != VSOCK) {
938 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
944 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
947 error = ECONNREFUSED;
950 if (so->so_type != so2->so_type) {
954 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
955 if (so2->so_options & SO_ACCEPTCONN) {
957 * NB: drop locks here so unp_attach is entered w/o
958 * locks; this avoids a recursive lock of the head
959 * and holding sleep locks across a (potentially)
963 so3 = sonewconn(so2, 0);
968 error = ECONNREFUSED;
972 unp2 = sotounpcb(so2);
973 unp3 = sotounpcb(so3);
974 if (unp2->unp_addr != NULL) {
975 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
976 unp3->unp_addr = (struct sockaddr_un *) sa;
980 * unp_peercred management:
982 * The connecter's (client's) credentials are copied from its
983 * process structure at the time of connect() (which is now).
985 cru2x(td->td_ucred, &unp3->unp_peercred);
986 unp3->unp_flags |= UNP_HAVEPC;
988 * The receiver's (server's) credentials are copied from the
989 * unp_peercred member of socket on which the former called
990 * listen(); unp_listen() cached that process's credentials
991 * at that time so we can use them now.
993 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
994 ("unp_connect: listener without cached peercred"));
995 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
996 sizeof(unp->unp_peercred));
997 unp->unp_flags |= UNP_HAVEPC;
998 if (unp2->unp_flags & UNP_WANTCRED)
999 unp3->unp_flags |= UNP_WANTCRED;
1002 mac_set_socket_peer_from_socket(so, so3);
1003 mac_set_socket_peer_from_socket(so3, so);
1009 error = unp_connect2(so, so2, PRU_CONNECT);
1014 mtx_assert(&Giant, MA_OWNED);
1020 unp->unp_flags &= ~UNP_CONNECTING;
1025 unp_connect2(struct socket *so, struct socket *so2, int req)
1027 struct unpcb *unp = sotounpcb(so);
1032 if (so2->so_type != so->so_type)
1033 return (EPROTOTYPE);
1034 unp2 = sotounpcb(so2);
1035 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1036 unp->unp_conn = unp2;
1037 switch (so->so_type) {
1040 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1045 unp2->unp_conn = unp;
1046 if (req == PRU_CONNECT &&
1047 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1055 panic("unp_connect2");
1061 unp_disconnect(struct unpcb *unp)
1063 struct unpcb *unp2 = unp->unp_conn;
1070 unp->unp_conn = NULL;
1071 switch (unp->unp_socket->so_type) {
1073 LIST_REMOVE(unp, unp_reflink);
1074 so = unp->unp_socket;
1076 so->so_state &= ~SS_ISCONNECTED;
1081 soisdisconnected(unp->unp_socket);
1082 unp2->unp_conn = NULL;
1083 soisdisconnected(unp2->unp_socket);
1089 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed by
1090 * the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers are
1091 * safe to reference. It first scans the list of struct unpcb's to generate
1092 * a pointer list, then it rescans its list one entry at a time to
1093 * externalize and copyout. It checks the generation number to see if a
1094 * struct unpcb has been reused, and will skip it if so.
1097 unp_pcblist(SYSCTL_HANDLER_ARGS)
1100 struct unpcb *unp, **unp_list;
1102 struct xunpgen *xug;
1103 struct unp_head *head;
1106 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1109 * The process of preparing the PCB list is too time-consuming and
1110 * resource-intensive to repeat twice on every request.
1112 if (req->oldptr == NULL) {
1114 req->oldidx = 2 * (sizeof *xug)
1115 + (n + n/8) * sizeof(struct xunpcb);
1119 if (req->newptr != NULL)
1123 * OK, now we're committed to doing something.
1125 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1127 gencnt = unp_gencnt;
1131 xug->xug_len = sizeof *xug;
1133 xug->xug_gen = gencnt;
1134 xug->xug_sogen = so_gencnt;
1135 error = SYSCTL_OUT(req, xug, sizeof *xug);
1141 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1144 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1145 unp = LIST_NEXT(unp, unp_link)) {
1146 if (unp->unp_gencnt <= gencnt) {
1147 if (cr_cansee(req->td->td_ucred,
1148 unp->unp_socket->so_cred))
1150 unp_list[i++] = unp;
1154 n = i; /* In case we lost some during malloc. */
1157 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1158 for (i = 0; i < n; i++) {
1160 if (unp->unp_gencnt <= gencnt) {
1161 xu->xu_len = sizeof *xu;
1164 * XXX - need more locking here to protect against
1165 * connect/disconnect races for SMP.
1167 if (unp->unp_addr != NULL)
1168 bcopy(unp->unp_addr, &xu->xu_addr,
1169 unp->unp_addr->sun_len);
1170 if (unp->unp_conn != NULL &&
1171 unp->unp_conn->unp_addr != NULL)
1172 bcopy(unp->unp_conn->unp_addr,
1174 unp->unp_conn->unp_addr->sun_len);
1175 bcopy(unp, &xu->xu_unp, sizeof *unp);
1176 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1177 error = SYSCTL_OUT(req, xu, sizeof *xu);
1183 * Give the user an updated idea of our state. If the
1184 * generation differs from what we told her before, she knows
1185 * that something happened while we were processing this
1186 * request, and it might be necessary to retry.
1188 xug->xug_gen = unp_gencnt;
1189 xug->xug_sogen = so_gencnt;
1190 xug->xug_count = unp_count;
1191 error = SYSCTL_OUT(req, xug, sizeof *xug);
1193 free(unp_list, M_TEMP);
1198 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1199 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1200 "List of active local datagram sockets");
1201 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1202 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1203 "List of active local stream sockets");
1206 unp_shutdown(struct unpcb *unp)
1212 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1213 (so = unp->unp_conn->unp_socket))
1218 unp_drop(struct unpcb *unp, int errno)
1220 struct socket *so = unp->unp_socket;
1224 so->so_error = errno;
1225 unp_disconnect(unp);
1229 unp_freerights(struct file **rp, int fdcount)
1234 for (i = 0; i < fdcount; i++) {
1237 * Zero the pointer before calling unp_discard since it may
1238 * end up in unp_gc()..
1240 * XXXRW: This is less true than it used to be.
1248 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1250 struct thread *td = curthread; /* XXX */
1251 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1257 socklen_t clen = control->m_len, datalen;
1262 UNP_UNLOCK_ASSERT();
1265 if (controlp != NULL) /* controlp == NULL => free control messages */
1268 while (cm != NULL) {
1269 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1274 data = CMSG_DATA(cm);
1275 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1277 if (cm->cmsg_level == SOL_SOCKET
1278 && cm->cmsg_type == SCM_RIGHTS) {
1279 newfds = datalen / sizeof(struct file *);
1282 /* If we're not outputting the descriptors free them. */
1283 if (error || controlp == NULL) {
1284 unp_freerights(rp, newfds);
1287 FILEDESC_LOCK(td->td_proc->p_fd);
1288 /* if the new FD's will not fit free them. */
1289 if (!fdavail(td, newfds)) {
1290 FILEDESC_UNLOCK(td->td_proc->p_fd);
1292 unp_freerights(rp, newfds);
1296 * Now change each pointer to an fd in the global
1297 * table to an integer that is the index to the local
1298 * fd table entry that we set up to point to the
1299 * global one we are transferring.
1301 newlen = newfds * sizeof(int);
1302 *controlp = sbcreatecontrol(NULL, newlen,
1303 SCM_RIGHTS, SOL_SOCKET);
1304 if (*controlp == NULL) {
1305 FILEDESC_UNLOCK(td->td_proc->p_fd);
1307 unp_freerights(rp, newfds);
1312 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1313 for (i = 0; i < newfds; i++) {
1314 if (fdalloc(td, 0, &f))
1315 panic("unp_externalize fdalloc failed");
1317 td->td_proc->p_fd->fd_ofiles[f] = fp;
1324 FILEDESC_UNLOCK(td->td_proc->p_fd);
1326 /* We can just copy anything else across. */
1327 if (error || controlp == NULL)
1329 *controlp = sbcreatecontrol(NULL, datalen,
1330 cm->cmsg_type, cm->cmsg_level);
1331 if (*controlp == NULL) {
1336 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1340 controlp = &(*controlp)->m_next;
1343 if (CMSG_SPACE(datalen) < clen) {
1344 clen -= CMSG_SPACE(datalen);
1345 cm = (struct cmsghdr *)
1346 ((caddr_t)cm + CMSG_SPACE(datalen));
1359 unp_zone_change(void *tag)
1362 uma_zone_set_max(unp_zone, maxsockets);
1369 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1370 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1371 if (unp_zone == NULL)
1373 uma_zone_set_max(unp_zone, maxsockets);
1374 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1375 NULL, EVENTHANDLER_PRI_ANY);
1376 LIST_INIT(&unp_dhead);
1377 LIST_INIT(&unp_shead);
1378 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1383 unp_internalize(struct mbuf **controlp, struct thread *td)
1385 struct mbuf *control = *controlp;
1386 struct proc *p = td->td_proc;
1387 struct filedesc *fdescp = p->p_fd;
1388 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1389 struct cmsgcred *cmcred;
1395 socklen_t clen = control->m_len, datalen;
1399 UNP_UNLOCK_ASSERT();
1404 while (cm != NULL) {
1405 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1406 || cm->cmsg_len > clen) {
1411 data = CMSG_DATA(cm);
1412 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1414 switch (cm->cmsg_type) {
1416 * Fill in credential information.
1419 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1420 SCM_CREDS, SOL_SOCKET);
1421 if (*controlp == NULL) {
1426 cmcred = (struct cmsgcred *)
1427 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1428 cmcred->cmcred_pid = p->p_pid;
1429 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1430 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1431 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1432 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1434 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1435 cmcred->cmcred_groups[i] =
1436 td->td_ucred->cr_groups[i];
1440 oldfds = datalen / sizeof (int);
1442 * Check that all the FDs passed in refer to legal
1443 * files. If not, reject the entire operation.
1446 FILEDESC_LOCK(fdescp);
1447 for (i = 0; i < oldfds; i++) {
1449 if ((unsigned)fd >= fdescp->fd_nfiles ||
1450 fdescp->fd_ofiles[fd] == NULL) {
1451 FILEDESC_UNLOCK(fdescp);
1455 fp = fdescp->fd_ofiles[fd];
1456 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1457 FILEDESC_UNLOCK(fdescp);
1464 * Now replace the integer FDs with pointers to the
1465 * associated global file table entry..
1467 newlen = oldfds * sizeof(struct file *);
1468 *controlp = sbcreatecontrol(NULL, newlen,
1469 SCM_RIGHTS, SOL_SOCKET);
1470 if (*controlp == NULL) {
1471 FILEDESC_UNLOCK(fdescp);
1477 rp = (struct file **)
1478 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1479 for (i = 0; i < oldfds; i++) {
1480 fp = fdescp->fd_ofiles[*fdp++];
1488 FILEDESC_UNLOCK(fdescp);
1492 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1493 SCM_TIMESTAMP, SOL_SOCKET);
1494 if (*controlp == NULL) {
1498 tv = (struct timeval *)
1499 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1508 controlp = &(*controlp)->m_next;
1510 if (CMSG_SPACE(datalen) < clen) {
1511 clen -= CMSG_SPACE(datalen);
1512 cm = (struct cmsghdr *)
1513 ((caddr_t)cm + CMSG_SPACE(datalen));
1527 unp_addsockcred(struct thread *td, struct mbuf *control)
1529 struct mbuf *m, *n, *n_prev;
1530 struct sockcred *sc;
1531 const struct cmsghdr *cm;
1535 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1537 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1541 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1542 sc->sc_uid = td->td_ucred->cr_ruid;
1543 sc->sc_euid = td->td_ucred->cr_uid;
1544 sc->sc_gid = td->td_ucred->cr_rgid;
1545 sc->sc_egid = td->td_ucred->cr_gid;
1546 sc->sc_ngroups = ngroups;
1547 for (i = 0; i < sc->sc_ngroups; i++)
1548 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1551 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1552 * created SCM_CREDS control message (struct sockcred) has another
1555 if (control != NULL)
1556 for (n = control, n_prev = NULL; n != NULL;) {
1557 cm = mtod(n, struct cmsghdr *);
1558 if (cm->cmsg_level == SOL_SOCKET &&
1559 cm->cmsg_type == SCM_CREDS) {
1561 control = n->m_next;
1563 n_prev->m_next = n->m_next;
1571 /* Prepend it to the head. */
1572 m->m_next = control;
1578 * unp_defer indicates whether additional work has been defered for a future
1579 * pass through unp_gc(). It is thread local and does not require explicit
1582 static int unp_defer;
1584 static int unp_taskcount;
1585 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1587 static int unp_recycled;
1588 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1591 unp_gc(__unused void *arg, int pending)
1593 struct file *fp, *nextfp;
1595 struct file **extra_ref, **fpp;
1598 int nfiles_slack = 20;
1603 * Before going through all this, set all FDs to be NOT defered and
1604 * NOT externally accessible.
1606 sx_slock(&filelist_lock);
1607 LIST_FOREACH(fp, &filehead, f_list)
1608 fp->f_gcflag &= ~(FMARK|FDEFER);
1610 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1611 LIST_FOREACH(fp, &filehead, f_list) {
1614 * If the file is not open, skip it -- could be a
1615 * file in the process of being opened, or in the
1616 * process of being closed. If the file is
1617 * "closing", it may have been marked for deferred
1618 * consideration. Clear the flag now if so.
1620 if (fp->f_count == 0) {
1621 if (fp->f_gcflag & FDEFER)
1623 fp->f_gcflag &= ~(FMARK|FDEFER);
1628 * If we already marked it as 'defer' in a previous
1629 * pass, then try process it this time and un-mark
1632 if (fp->f_gcflag & FDEFER) {
1633 fp->f_gcflag &= ~FDEFER;
1637 * if it's not defered, then check if it's
1638 * already marked.. if so skip it
1640 if (fp->f_gcflag & FMARK) {
1645 * If all references are from messages in
1646 * transit, then skip it. it's not externally
1649 if (fp->f_count == fp->f_msgcount) {
1654 * If it got this far then it must be
1655 * externally accessible.
1657 fp->f_gcflag |= FMARK;
1660 * Either it was defered, or it is externally
1661 * accessible and not already marked so. Now check
1662 * if it is possibly one of OUR sockets.
1664 if (fp->f_type != DTYPE_SOCKET ||
1665 (so = fp->f_data) == NULL) {
1670 if (so->so_proto->pr_domain != &localdomain ||
1671 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1674 * So, Ok, it's one of our sockets and it IS
1675 * externally accessible (or was defered). Now we
1676 * look to see if we hold any file descriptors in its
1677 * message buffers. Follow those links and mark them
1678 * as accessible too.
1680 SOCKBUF_LOCK(&so->so_rcv);
1681 unp_scan(so->so_rcv.sb_mb, unp_mark);
1682 SOCKBUF_UNLOCK(&so->so_rcv);
1684 } while (unp_defer);
1685 sx_sunlock(&filelist_lock);
1687 * XXXRW: The following comments need updating for a post-SMPng and
1688 * deferred unp_gc() world, but are still generally accurate.
1690 * We grab an extra reference to each of the file table entries that
1691 * are not otherwise accessible and then free the rights that are
1692 * stored in messages on them.
1694 * The bug in the orginal code is a little tricky, so I'll describe
1695 * what's wrong with it here.
1697 * It is incorrect to simply unp_discard each entry for f_msgcount
1698 * times -- consider the case of sockets A and B that contain
1699 * references to each other. On a last close of some other socket,
1700 * we trigger a gc since the number of outstanding rights (unp_rights)
1701 * is non-zero. If during the sweep phase the gc code unp_discards,
1702 * we end up doing a (full) closef on the descriptor. A closef on A
1703 * results in the following chain. Closef calls soo_close, which
1704 * calls soclose. Soclose calls first (through the switch
1705 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1706 * returns because the previous instance had set unp_gcing, and we
1707 * return all the way back to soclose, which marks the socket with
1708 * SS_NOFDREF, and then calls sofree. Sofree calls sorflush to free
1709 * up the rights that are queued in messages on the socket A, i.e.,
1710 * the reference on B. The sorflush calls via the dom_dispose switch
1711 * unp_dispose, which unp_scans with unp_discard. This second
1712 * instance of unp_discard just calls closef on B.
1714 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1715 * which results in another closef on A. Unfortunately, A is already
1716 * being closed, and the descriptor has already been marked with
1717 * SS_NOFDREF, and soclose panics at this point.
1719 * Here, we first take an extra reference to each inaccessible
1720 * descriptor. Then, we call sorflush ourself, since we know it is a
1721 * Unix domain socket anyhow. After we destroy all the rights
1722 * carried in messages, we do a last closef to get rid of our extra
1723 * reference. This is the last close, and the unp_detach etc will
1724 * shut down the socket.
1726 * 91/09/19, bsy@cs.cmu.edu
1729 nfiles_snap = openfiles + nfiles_slack; /* some slack */
1730 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
1732 sx_slock(&filelist_lock);
1733 if (nfiles_snap < openfiles) {
1734 sx_sunlock(&filelist_lock);
1735 free(extra_ref, M_TEMP);
1739 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1740 fp != NULL; fp = nextfp) {
1741 nextfp = LIST_NEXT(fp, f_list);
1744 * If it's not open, skip it
1746 if (fp->f_count == 0) {
1751 * If all refs are from msgs, and it's not marked accessible
1752 * then it must be referenced from some unreachable cycle of
1753 * (shut-down) FDs, so include it in our list of FDs to
1756 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1763 sx_sunlock(&filelist_lock);
1765 * For each FD on our hit list, do the following two things:
1767 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1768 struct file *tfp = *fpp;
1770 if (tfp->f_type == DTYPE_SOCKET &&
1771 tfp->f_data != NULL) {
1773 sorflush(tfp->f_data);
1778 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1779 closef(*fpp, (struct thread *) NULL);
1782 free(extra_ref, M_TEMP);
1786 unp_dispose(struct mbuf *m)
1790 unp_scan(m, unp_discard);
1794 unp_listen(struct socket *so, struct unpcb *unp, int backlog,
1802 error = solisten_proto_check(so);
1804 cru2x(td->td_ucred, &unp->unp_peercred);
1805 unp->unp_flags |= UNP_HAVEPCCACHED;
1806 solisten_proto(so, backlog);
1813 unp_scan(struct mbuf *m0, void (*op)(struct file *))
1820 socklen_t clen, datalen;
1823 while (m0 != NULL) {
1824 for (m = m0; m; m = m->m_next) {
1825 if (m->m_type != MT_CONTROL)
1828 cm = mtod(m, struct cmsghdr *);
1831 while (cm != NULL) {
1832 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1835 data = CMSG_DATA(cm);
1836 datalen = (caddr_t)cm + cm->cmsg_len
1839 if (cm->cmsg_level == SOL_SOCKET &&
1840 cm->cmsg_type == SCM_RIGHTS) {
1841 qfds = datalen / sizeof (struct file *);
1843 for (i = 0; i < qfds; i++)
1847 if (CMSG_SPACE(datalen) < clen) {
1848 clen -= CMSG_SPACE(datalen);
1849 cm = (struct cmsghdr *)
1850 ((caddr_t)cm + CMSG_SPACE(datalen));
1862 unp_mark(struct file *fp)
1864 if (fp->f_gcflag & FMARK)
1867 fp->f_gcflag |= (FMARK|FDEFER);
1871 unp_discard(struct file *fp)
1879 (void) closef(fp, (struct thread *)NULL);