2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright 2004-2005 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
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
39 #include <sys/param.h>
40 #include <sys/domain.h>
41 #include <sys/fcntl.h>
42 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
44 #include <sys/filedesc.h>
46 #include <sys/kernel.h>
50 #include <sys/mutex.h>
51 #include <sys/namei.h>
53 #include <sys/protosw.h>
54 #include <sys/resourcevar.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/signalvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/systm.h>
62 #include <sys/taskqueue.h>
64 #include <sys/unpcb.h>
65 #include <sys/vnode.h>
69 static uma_zone_t unp_zone;
70 static unp_gen_t unp_gencnt;
71 static u_int unp_count;
73 static struct unp_head unp_shead, unp_dhead;
76 * Unix communications domain.
80 * rethink name space problems
81 * need a proper out-of-band
84 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
85 static ino_t unp_ino; /* prototype for fake inode numbers */
86 struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
89 * Currently, UNIX domain sockets are protected by a single subsystem lock,
90 * which covers global data structures and variables, the contents of each
91 * per-socket unpcb structure, and the so_pcb field in sockets attached to
92 * the UNIX domain. This provides for a moderate degree of paralellism, as
93 * receive operations on UNIX domain sockets do not need to acquire the
94 * subsystem lock. Finer grained locking to permit send() without acquiring
95 * a global lock would be a logical next step.
97 * The UNIX domain socket lock preceds all socket layer locks, including the
98 * socket lock and socket buffer lock, permitting UNIX domain socket code to
99 * call into socket support routines without releasing its locks.
101 * Some caution is required in areas where the UNIX domain socket code enters
102 * VFS in order to create or find rendezvous points. This results in
103 * dropping of the UNIX domain socket subsystem lock, acquisition of the
104 * Giant lock, and potential sleeping. This increases the chances of races,
105 * and exposes weaknesses in the socket->protocol API by offering poor
108 static struct mtx unp_mtx;
109 #define UNP_LOCK_INIT() \
110 mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
111 #define UNP_LOCK() mtx_lock(&unp_mtx)
112 #define UNP_UNLOCK() mtx_unlock(&unp_mtx)
113 #define UNP_LOCK_ASSERT() mtx_assert(&unp_mtx, MA_OWNED)
114 #define UNP_UNLOCK_ASSERT() mtx_assert(&unp_mtx, MA_NOTOWNED)
117 * Garbage collection of cyclic file descriptor/socket references occurs
118 * asynchronously in a taskqueue context in order to avoid recursion and
119 * reentrance in the UNIX domain socket, file descriptor, and socket layer
120 * code. See unp_gc() for a full description.
122 static struct task unp_gc_task;
124 static int unp_attach(struct socket *);
125 static void unp_detach(struct unpcb *);
126 static int unp_bind(struct unpcb *,struct sockaddr *, struct thread *);
127 static int unp_connect(struct socket *,struct sockaddr *, struct thread *);
128 static int unp_connect2(struct socket *so, struct socket *so2, int);
129 static void unp_disconnect(struct unpcb *);
130 static void unp_shutdown(struct unpcb *);
131 static void unp_drop(struct unpcb *, int);
132 static void unp_gc(__unused void *, int);
133 static void unp_scan(struct mbuf *, void (*)(struct file *));
134 static void unp_mark(struct file *);
135 static void unp_discard(struct file *);
136 static void unp_freerights(struct file **, int);
137 static int unp_internalize(struct mbuf **, struct thread *);
138 static int unp_listen(struct socket *, struct unpcb *, int,
142 uipc_abort(struct socket *so)
152 unp_drop(unp, ECONNABORTED);
162 uipc_accept(struct socket *so, struct sockaddr **nam)
165 const struct sockaddr *sa;
168 * Pass back name of connected socket,
169 * if it was bound and we are still connected
170 * (our peer may have closed already!).
172 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
177 free(*nam, M_SONAME);
181 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
182 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
185 bcopy(sa, *nam, sa->sa_len);
191 uipc_attach(struct socket *so, int proto, struct thread *td)
193 struct unpcb *unp = sotounpcb(so);
197 return (unp_attach(so));
201 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
212 error = unp_bind(unp, nam, td);
218 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
223 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
231 error = unp_connect(so, nam, td);
237 uipc_connect2(struct socket *so1, struct socket *so2)
243 unp = sotounpcb(so1);
248 error = unp_connect2(so1, so2, PRU_CONNECT2);
253 /* control is EOPNOTSUPP */
256 uipc_detach(struct socket *so)
272 uipc_disconnect(struct socket *so)
288 uipc_listen(struct socket *so, int backlog, struct thread *td)
295 if (unp == NULL || unp->unp_vnode == NULL) {
299 error = unp_listen(so, unp, backlog, td);
305 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
308 const struct sockaddr *sa;
310 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
315 free(*nam, M_SONAME);
319 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
320 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
323 * XXX: It seems that this test always fails even when
324 * connection is established. So, this else clause is
325 * added as workaround to return PF_LOCAL sockaddr.
329 bcopy(sa, *nam, sa->sa_len);
335 uipc_rcvd(struct socket *so, int flags)
347 switch (so->so_type) {
349 panic("uipc_rcvd DGRAM?");
353 if (unp->unp_conn == NULL)
355 so2 = unp->unp_conn->unp_socket;
356 SOCKBUF_LOCK(&so2->so_snd);
357 SOCKBUF_LOCK(&so->so_rcv);
359 * Adjust backpressure on sender
360 * and wakeup any waiting to write.
362 so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
363 unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
364 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
366 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
367 newhiwat, RLIM_INFINITY);
368 unp->unp_cc = so->so_rcv.sb_cc;
369 SOCKBUF_UNLOCK(&so->so_rcv);
370 sowwakeup_locked(so2);
374 panic("uipc_rcvd unknown socktype");
380 /* pru_rcvoob is EOPNOTSUPP */
383 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
384 struct mbuf *control, struct thread *td)
396 if (flags & PRUS_OOB) {
401 if (control != NULL && (error = unp_internalize(&control, td)))
409 goto dispose_release;
412 switch (so->so_type) {
415 const struct sockaddr *from;
418 if (unp->unp_conn != NULL) {
422 error = unp_connect(so, nam, td);
426 if (unp->unp_conn == NULL) {
431 so2 = unp->unp_conn->unp_socket;
432 if (unp->unp_addr != NULL)
433 from = (struct sockaddr *)unp->unp_addr;
436 if (unp->unp_conn->unp_flags & UNP_WANTCRED)
437 control = unp_addsockcred(td, control);
438 SOCKBUF_LOCK(&so2->so_rcv);
439 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
440 sorwakeup_locked(so2);
444 SOCKBUF_UNLOCK(&so2->so_rcv);
453 /* Connect if not connected yet. */
455 * Note: A better implementation would complain
456 * if not equal to the peer's address.
458 if ((so->so_state & SS_ISCONNECTED) == 0) {
460 error = unp_connect(so, nam, td);
469 SOCKBUF_LOCK(&so->so_snd);
470 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
471 SOCKBUF_UNLOCK(&so->so_snd);
475 if (unp->unp_conn == NULL)
476 panic("uipc_send connected but no connection?");
477 so2 = unp->unp_conn->unp_socket;
478 SOCKBUF_LOCK(&so2->so_rcv);
479 if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
481 * Credentials are passed only once on
484 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
485 control = unp_addsockcred(td, control);
488 * Send to paired receive port, and then reduce
489 * send buffer hiwater marks to maintain backpressure.
492 if (control != NULL) {
493 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
496 sbappend_locked(&so2->so_rcv, m);
498 so->so_snd.sb_mbmax -=
499 so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
500 unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
501 newhiwat = so->so_snd.sb_hiwat -
502 (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
503 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
504 newhiwat, RLIM_INFINITY);
505 SOCKBUF_UNLOCK(&so->so_snd);
506 unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
507 sorwakeup_locked(so2);
512 panic("uipc_send unknown socktype");
516 * SEND_EOF is equivalent to a SEND followed by
519 if (flags & PRUS_EOF) {
526 if (control != NULL && error != 0)
527 unp_dispose(control);
538 uipc_sense(struct socket *so, struct stat *sb)
549 sb->st_blksize = so->so_snd.sb_hiwat;
550 if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
551 so2 = unp->unp_conn->unp_socket;
552 sb->st_blksize += so2->so_rcv.sb_cc;
555 if (unp->unp_ino == 0)
556 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
557 sb->st_ino = unp->unp_ino;
563 uipc_shutdown(struct socket *so)
580 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
583 const struct sockaddr *sa;
585 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
590 free(*nam, M_SONAME);
594 if (unp->unp_addr != NULL)
595 sa = (struct sockaddr *) unp->unp_addr;
598 bcopy(sa, *nam, sa->sa_len);
603 struct pr_usrreqs uipc_usrreqs = {
604 .pru_abort = uipc_abort,
605 .pru_accept = uipc_accept,
606 .pru_attach = uipc_attach,
607 .pru_bind = uipc_bind,
608 .pru_connect = uipc_connect,
609 .pru_connect2 = uipc_connect2,
610 .pru_detach = uipc_detach,
611 .pru_disconnect = uipc_disconnect,
612 .pru_listen = uipc_listen,
613 .pru_peeraddr = uipc_peeraddr,
614 .pru_rcvd = uipc_rcvd,
615 .pru_send = uipc_send,
616 .pru_sense = uipc_sense,
617 .pru_shutdown = uipc_shutdown,
618 .pru_sockaddr = uipc_sockaddr,
619 .pru_sosend = sosend,
620 .pru_soreceive = soreceive,
621 .pru_sopoll = sopoll,
625 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
631 if (sopt->sopt_level != 0)
642 switch (sopt->sopt_dir) {
644 switch (sopt->sopt_name) {
646 if (unp->unp_flags & UNP_HAVEPC)
647 xu = unp->unp_peercred;
649 if (so->so_type == SOCK_STREAM)
655 error = sooptcopyout(sopt, &xu, sizeof(xu));
658 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
659 error = sooptcopyout(sopt, &optval, sizeof(optval));
662 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
663 error = sooptcopyout(sopt, &optval, sizeof(optval));
671 switch (sopt->sopt_name) {
674 error = sooptcopyin(sopt, &optval, sizeof(optval),
679 #define OPTSET(bit) \
681 unp->unp_flags |= bit; \
683 unp->unp_flags &= ~bit;
685 switch (sopt->sopt_name) {
687 OPTSET(UNP_WANTCRED);
690 OPTSET(UNP_CONNWAIT);
711 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
712 * for stream sockets, although the total for sender and receiver is
713 * actually only PIPSIZ.
714 * Datagram sockets really use the sendspace as the maximum datagram size,
715 * and don't really want to reserve the sendspace. Their recvspace should
716 * be large enough for at least one max-size datagram plus address.
721 static u_long unpst_sendspace = PIPSIZ;
722 static u_long unpst_recvspace = PIPSIZ;
723 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
724 static u_long unpdg_recvspace = 4*1024;
726 static int unp_rights; /* file descriptors in flight */
728 SYSCTL_DECL(_net_local_stream);
729 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
730 &unpst_sendspace, 0, "");
731 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
732 &unpst_recvspace, 0, "");
733 SYSCTL_DECL(_net_local_dgram);
734 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
735 &unpdg_sendspace, 0, "");
736 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
737 &unpdg_recvspace, 0, "");
738 SYSCTL_DECL(_net_local);
739 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
742 unp_attach(struct socket *so)
747 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
748 switch (so->so_type) {
751 error = soreserve(so, unpst_sendspace, unpst_recvspace);
755 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
764 unp = uma_zalloc(unp_zone, M_WAITOK | M_ZERO);
767 LIST_INIT(&unp->unp_refs);
768 unp->unp_socket = so;
772 unp->unp_gencnt = ++unp_gencnt;
774 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
775 : &unp_shead, unp, unp_link);
782 unp_detach(struct unpcb *unp)
785 int local_unp_rights;
789 LIST_REMOVE(unp, unp_link);
790 unp->unp_gencnt = ++unp_gencnt;
792 if ((vp = unp->unp_vnode) != NULL) {
794 * XXXRW: should v_socket be frobbed only while holding
797 unp->unp_vnode->v_socket = NULL;
798 unp->unp_vnode = NULL;
800 if (unp->unp_conn != NULL)
802 while (!LIST_EMPTY(&unp->unp_refs)) {
803 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
804 unp_drop(ref, ECONNRESET);
806 soisdisconnected(unp->unp_socket);
807 unp->unp_socket->so_pcb = NULL;
808 local_unp_rights = unp_rights;
810 if (unp->unp_addr != NULL)
811 FREE(unp->unp_addr, M_SONAME);
812 uma_zfree(unp_zone, unp);
818 if (local_unp_rights)
819 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
823 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
825 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
836 * XXXRW: This test-and-set of unp_vnode is non-atomic; the
837 * unlocked read here is fine, but the value of unp_vnode needs
838 * to be tested again after we do all the lookups to see if the
839 * pcb is still unbound?
841 if (unp->unp_vnode != NULL)
844 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
850 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
851 strlcpy(buf, soun->sun_path, namelen + 1);
855 mtx_assert(&Giant, MA_OWNED);
856 NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
858 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
863 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
864 NDFREE(&nd, NDF_ONLY_PNBUF);
874 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
880 vattr.va_type = VSOCK;
881 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
883 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
887 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
888 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
890 NDFREE(&nd, NDF_ONLY_PNBUF);
893 vn_finished_write(mp);
897 ASSERT_VOP_LOCKED(vp, "unp_bind");
898 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
900 vp->v_socket = unp->unp_socket;
902 unp->unp_addr = soun;
904 VOP_UNLOCK(vp, 0, td);
905 vn_finished_write(mp);
914 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
916 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
918 struct socket *so2, *so3;
919 struct unpcb *unp, *unp2, *unp3;
922 char buf[SOCK_MAXADDRLEN];
928 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
931 strlcpy(buf, soun->sun_path, len + 1);
933 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
935 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
941 ASSERT_VOP_LOCKED(vp, "unp_connect");
942 NDFREE(&nd, NDF_ONLY_PNBUF);
946 if (vp->v_type != VSOCK) {
950 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
962 error = ECONNREFUSED;
965 if (so->so_type != so2->so_type) {
969 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
970 if (so2->so_options & SO_ACCEPTCONN) {
972 * NB: drop locks here so unp_attach is entered
973 * w/o locks; this avoids a recursive lock
974 * of the head and holding sleep locks across
975 * a (potentially) blocking malloc.
978 so3 = sonewconn(so2, 0);
983 error = ECONNREFUSED;
987 unp2 = sotounpcb(so2);
988 unp3 = sotounpcb(so3);
989 if (unp2->unp_addr != NULL) {
990 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
991 unp3->unp_addr = (struct sockaddr_un *) sa;
995 * unp_peercred management:
997 * The connecter's (client's) credentials are copied
998 * from its process structure at the time of connect()
1001 cru2x(td->td_ucred, &unp3->unp_peercred);
1002 unp3->unp_flags |= UNP_HAVEPC;
1004 * The receiver's (server's) credentials are copied
1005 * from the unp_peercred member of socket on which the
1006 * former called listen(); unp_listen() cached that
1007 * process's credentials at that time so we can use
1010 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1011 ("unp_connect: listener without cached peercred"));
1012 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1013 sizeof(unp->unp_peercred));
1014 unp->unp_flags |= UNP_HAVEPC;
1017 mac_set_socket_peer_from_socket(so, so3);
1018 mac_set_socket_peer_from_socket(so3, so);
1024 error = unp_connect2(so, so2, PRU_CONNECT);
1029 mtx_assert(&Giant, MA_OWNED);
1039 unp_connect2(struct socket *so, struct socket *so2, int req)
1041 struct unpcb *unp = sotounpcb(so);
1046 if (so2->so_type != so->so_type)
1047 return (EPROTOTYPE);
1048 unp2 = sotounpcb(so2);
1049 unp->unp_conn = unp2;
1050 switch (so->so_type) {
1053 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1058 unp2->unp_conn = unp;
1059 if (req == PRU_CONNECT &&
1060 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1068 panic("unp_connect2");
1074 unp_disconnect(struct unpcb *unp)
1076 struct unpcb *unp2 = unp->unp_conn;
1083 unp->unp_conn = NULL;
1084 switch (unp->unp_socket->so_type) {
1087 LIST_REMOVE(unp, unp_reflink);
1088 so = unp->unp_socket;
1090 so->so_state &= ~SS_ISCONNECTED;
1095 soisdisconnected(unp->unp_socket);
1096 unp2->unp_conn = NULL;
1097 soisdisconnected(unp2->unp_socket);
1104 unp_abort(struct unpcb *unp)
1108 UNP_UNLOCK_ASSERT();
1113 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed
1114 * by the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers
1115 * are safe to reference. It first scans the list of struct unpcb's to
1116 * generate a pointer list, then it rescans its list one entry at a time to
1117 * externalize and copyout. It checks the generation number to see if a
1118 * struct unpcb has been reused, and will skip it if so.
1121 unp_pcblist(SYSCTL_HANDLER_ARGS)
1124 struct unpcb *unp, **unp_list;
1126 struct xunpgen *xug;
1127 struct unp_head *head;
1130 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1133 * The process of preparing the PCB list is too time-consuming and
1134 * resource-intensive to repeat twice on every request.
1136 if (req->oldptr == NULL) {
1138 req->oldidx = 2 * (sizeof *xug)
1139 + (n + n/8) * sizeof(struct xunpcb);
1143 if (req->newptr != NULL)
1147 * OK, now we're committed to doing something.
1149 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1151 gencnt = unp_gencnt;
1155 xug->xug_len = sizeof *xug;
1157 xug->xug_gen = gencnt;
1158 xug->xug_sogen = so_gencnt;
1159 error = SYSCTL_OUT(req, xug, sizeof *xug);
1165 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1168 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1169 unp = LIST_NEXT(unp, unp_link)) {
1170 if (unp->unp_gencnt <= gencnt) {
1171 if (cr_cansee(req->td->td_ucred,
1172 unp->unp_socket->so_cred))
1174 unp_list[i++] = unp;
1178 n = i; /* in case we lost some during malloc */
1181 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1182 for (i = 0; i < n; i++) {
1184 if (unp->unp_gencnt <= gencnt) {
1185 xu->xu_len = sizeof *xu;
1188 * XXX - need more locking here to protect against
1189 * connect/disconnect races for SMP.
1191 if (unp->unp_addr != NULL)
1192 bcopy(unp->unp_addr, &xu->xu_addr,
1193 unp->unp_addr->sun_len);
1194 if (unp->unp_conn != NULL &&
1195 unp->unp_conn->unp_addr != NULL)
1196 bcopy(unp->unp_conn->unp_addr,
1198 unp->unp_conn->unp_addr->sun_len);
1199 bcopy(unp, &xu->xu_unp, sizeof *unp);
1200 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1201 error = SYSCTL_OUT(req, xu, sizeof *xu);
1207 * Give the user an updated idea of our state.
1208 * If the generation differs from what we told
1209 * her before, she knows that something happened
1210 * while we were processing this request, and it
1211 * might be necessary to retry.
1213 xug->xug_gen = unp_gencnt;
1214 xug->xug_sogen = so_gencnt;
1215 xug->xug_count = unp_count;
1216 error = SYSCTL_OUT(req, xug, sizeof *xug);
1218 free(unp_list, M_TEMP);
1223 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1224 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1225 "List of active local datagram sockets");
1226 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1227 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1228 "List of active local stream sockets");
1231 unp_shutdown(struct unpcb *unp)
1237 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1238 (so = unp->unp_conn->unp_socket))
1243 unp_drop(struct unpcb *unp, int errno)
1245 struct socket *so = unp->unp_socket;
1249 so->so_error = errno;
1250 unp_disconnect(unp);
1262 unp_freerights(struct file **rp, int fdcount)
1267 for (i = 0; i < fdcount; i++) {
1270 * zero the pointer before calling
1271 * unp_discard since it may end up
1280 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1282 struct thread *td = curthread; /* XXX */
1283 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1289 socklen_t clen = control->m_len, datalen;
1294 UNP_UNLOCK_ASSERT();
1297 if (controlp != NULL) /* controlp == NULL => free control messages */
1300 while (cm != NULL) {
1301 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1306 data = CMSG_DATA(cm);
1307 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1309 if (cm->cmsg_level == SOL_SOCKET
1310 && cm->cmsg_type == SCM_RIGHTS) {
1311 newfds = datalen / sizeof(struct file *);
1314 /* If we're not outputting the descriptors free them. */
1315 if (error || controlp == NULL) {
1316 unp_freerights(rp, newfds);
1319 FILEDESC_LOCK(td->td_proc->p_fd);
1320 /* if the new FD's will not fit free them. */
1321 if (!fdavail(td, newfds)) {
1322 FILEDESC_UNLOCK(td->td_proc->p_fd);
1324 unp_freerights(rp, newfds);
1328 * now change each pointer to an fd in the global
1329 * table to an integer that is the index to the
1330 * local fd table entry that we set up to point
1331 * to the global one we are transferring.
1333 newlen = newfds * sizeof(int);
1334 *controlp = sbcreatecontrol(NULL, newlen,
1335 SCM_RIGHTS, SOL_SOCKET);
1336 if (*controlp == NULL) {
1337 FILEDESC_UNLOCK(td->td_proc->p_fd);
1339 unp_freerights(rp, newfds);
1344 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1345 for (i = 0; i < newfds; i++) {
1346 if (fdalloc(td, 0, &f))
1347 panic("unp_externalize fdalloc failed");
1349 td->td_proc->p_fd->fd_ofiles[f] = fp;
1356 FILEDESC_UNLOCK(td->td_proc->p_fd);
1357 } else { /* We can just copy anything else across */
1358 if (error || controlp == NULL)
1360 *controlp = sbcreatecontrol(NULL, datalen,
1361 cm->cmsg_type, cm->cmsg_level);
1362 if (*controlp == NULL) {
1367 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1371 controlp = &(*controlp)->m_next;
1374 if (CMSG_SPACE(datalen) < clen) {
1375 clen -= CMSG_SPACE(datalen);
1376 cm = (struct cmsghdr *)
1377 ((caddr_t)cm + CMSG_SPACE(datalen));
1392 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1393 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1394 if (unp_zone == NULL)
1396 uma_zone_set_max(unp_zone, nmbclusters);
1397 LIST_INIT(&unp_dhead);
1398 LIST_INIT(&unp_shead);
1399 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1404 unp_internalize(struct mbuf **controlp, struct thread *td)
1406 struct mbuf *control = *controlp;
1407 struct proc *p = td->td_proc;
1408 struct filedesc *fdescp = p->p_fd;
1409 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1410 struct cmsgcred *cmcred;
1416 socklen_t clen = control->m_len, datalen;
1420 UNP_UNLOCK_ASSERT();
1425 while (cm != NULL) {
1426 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1427 || cm->cmsg_len > clen) {
1432 data = CMSG_DATA(cm);
1433 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1435 switch (cm->cmsg_type) {
1437 * Fill in credential information.
1440 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1441 SCM_CREDS, SOL_SOCKET);
1442 if (*controlp == NULL) {
1447 cmcred = (struct cmsgcred *)
1448 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1449 cmcred->cmcred_pid = p->p_pid;
1450 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1451 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1452 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1453 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1455 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1456 cmcred->cmcred_groups[i] =
1457 td->td_ucred->cr_groups[i];
1461 oldfds = datalen / sizeof (int);
1463 * check that all the FDs passed in refer to legal files
1464 * If not, reject the entire operation.
1467 FILEDESC_LOCK(fdescp);
1468 for (i = 0; i < oldfds; i++) {
1470 if ((unsigned)fd >= fdescp->fd_nfiles ||
1471 fdescp->fd_ofiles[fd] == NULL) {
1472 FILEDESC_UNLOCK(fdescp);
1476 fp = fdescp->fd_ofiles[fd];
1477 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1478 FILEDESC_UNLOCK(fdescp);
1485 * Now replace the integer FDs with pointers to
1486 * the associated global file table entry..
1488 newlen = oldfds * sizeof(struct file *);
1489 *controlp = sbcreatecontrol(NULL, newlen,
1490 SCM_RIGHTS, SOL_SOCKET);
1491 if (*controlp == NULL) {
1492 FILEDESC_UNLOCK(fdescp);
1498 rp = (struct file **)
1499 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1500 for (i = 0; i < oldfds; i++) {
1501 fp = fdescp->fd_ofiles[*fdp++];
1509 FILEDESC_UNLOCK(fdescp);
1513 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1514 SCM_TIMESTAMP, SOL_SOCKET);
1515 if (*controlp == NULL) {
1519 tv = (struct timeval *)
1520 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1529 controlp = &(*controlp)->m_next;
1531 if (CMSG_SPACE(datalen) < clen) {
1532 clen -= CMSG_SPACE(datalen);
1533 cm = (struct cmsghdr *)
1534 ((caddr_t)cm + CMSG_SPACE(datalen));
1548 unp_addsockcred(struct thread *td, struct mbuf *control)
1551 struct sockcred *sc;
1555 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1557 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1562 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1563 sc->sc_uid = td->td_ucred->cr_ruid;
1564 sc->sc_euid = td->td_ucred->cr_uid;
1565 sc->sc_gid = td->td_ucred->cr_rgid;
1566 sc->sc_egid = td->td_ucred->cr_gid;
1567 sc->sc_ngroups = ngroups;
1568 for (i = 0; i < sc->sc_ngroups; i++)
1569 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1572 * If a control message already exists, append us to the end.
1574 if (control != NULL) {
1575 for (n = control; n->m_next != NULL; n = n->m_next)
1585 * unp_defer indicates whether additional work has been defered for a future
1586 * pass through unp_gc(). It is thread local and does not require explicit
1589 static int unp_defer;
1591 static int unp_taskcount;
1592 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1594 static int unp_recycled;
1595 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1598 unp_gc(__unused void *arg, int pending)
1600 struct file *fp, *nextfp;
1602 struct file **extra_ref, **fpp;
1605 int nfiles_slack = 20;
1610 * before going through all this, set all FDs to
1611 * be NOT defered and NOT externally accessible
1613 sx_slock(&filelist_lock);
1614 LIST_FOREACH(fp, &filehead, f_list)
1615 fp->f_gcflag &= ~(FMARK|FDEFER);
1617 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1618 LIST_FOREACH(fp, &filehead, f_list) {
1621 * If the file is not open, skip it -- could be a
1622 * file in the process of being opened, or in the
1623 * process of being closed. If the file is
1624 * "closing", it may have been marked for deferred
1625 * consideration. Clear the flag now if so.
1627 if (fp->f_count == 0) {
1628 if (fp->f_gcflag & FDEFER)
1630 fp->f_gcflag &= ~(FMARK|FDEFER);
1635 * If we already marked it as 'defer' in a
1636 * previous pass, then try process it this time
1639 if (fp->f_gcflag & FDEFER) {
1640 fp->f_gcflag &= ~FDEFER;
1644 * if it's not defered, then check if it's
1645 * already marked.. if so skip it
1647 if (fp->f_gcflag & FMARK) {
1652 * If all references are from messages
1653 * in transit, then skip it. it's not
1654 * externally accessible.
1656 if (fp->f_count == fp->f_msgcount) {
1661 * If it got this far then it must be
1662 * externally accessible.
1664 fp->f_gcflag |= FMARK;
1667 * either it was defered, or it is externally
1668 * accessible and not already marked so.
1669 * Now check if it is possibly one of OUR sockets.
1671 if (fp->f_type != DTYPE_SOCKET ||
1672 (so = fp->f_data) == NULL) {
1677 if (so->so_proto->pr_domain != &localdomain ||
1678 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1681 * So, Ok, it's one of our sockets and it IS externally
1682 * accessible (or was defered). Now we look
1683 * to see if we hold any file descriptors in its
1684 * message buffers. Follow those links and mark them
1685 * as accessible too.
1687 SOCKBUF_LOCK(&so->so_rcv);
1688 unp_scan(so->so_rcv.sb_mb, unp_mark);
1689 SOCKBUF_UNLOCK(&so->so_rcv);
1691 } while (unp_defer);
1692 sx_sunlock(&filelist_lock);
1694 * XXXRW: The following comments need updating for a post-SMPng and
1695 * deferred unp_gc() world, but are still generally accurate.
1697 * We grab an extra reference to each of the file table entries
1698 * that are not otherwise accessible and then free the rights
1699 * that are stored in messages on them.
1701 * The bug in the orginal code is a little tricky, so I'll describe
1702 * what's wrong with it here.
1704 * It is incorrect to simply unp_discard each entry for f_msgcount
1705 * times -- consider the case of sockets A and B that contain
1706 * references to each other. On a last close of some other socket,
1707 * we trigger a gc since the number of outstanding rights (unp_rights)
1708 * is non-zero. If during the sweep phase the gc code unp_discards,
1709 * we end up doing a (full) closef on the descriptor. A closef on A
1710 * results in the following chain. Closef calls soo_close, which
1711 * calls soclose. Soclose calls first (through the switch
1712 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1713 * returns because the previous instance had set unp_gcing, and
1714 * we return all the way back to soclose, which marks the socket
1715 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1716 * to free up the rights that are queued in messages on the socket A,
1717 * i.e., the reference on B. The sorflush calls via the dom_dispose
1718 * switch unp_dispose, which unp_scans with unp_discard. This second
1719 * instance of unp_discard just calls closef on B.
1721 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1722 * which results in another closef on A. Unfortunately, A is already
1723 * being closed, and the descriptor has already been marked with
1724 * SS_NOFDREF, and soclose panics at this point.
1726 * Here, we first take an extra reference to each inaccessible
1727 * descriptor. Then, we call sorflush ourself, since we know
1728 * it is a Unix domain socket anyhow. After we destroy all the
1729 * rights carried in messages, we do a last closef to get rid
1730 * of our extra reference. This is the last close, and the
1731 * unp_detach etc will shut down the socket.
1733 * 91/09/19, bsy@cs.cmu.edu
1736 nfiles_snap = openfiles + nfiles_slack; /* some slack */
1737 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
1739 sx_slock(&filelist_lock);
1740 if (nfiles_snap < openfiles) {
1741 sx_sunlock(&filelist_lock);
1742 free(extra_ref, M_TEMP);
1746 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1747 fp != NULL; fp = nextfp) {
1748 nextfp = LIST_NEXT(fp, f_list);
1751 * If it's not open, skip it
1753 if (fp->f_count == 0) {
1758 * If all refs are from msgs, and it's not marked accessible
1759 * then it must be referenced from some unreachable cycle
1760 * of (shut-down) FDs, so include it in our
1761 * list of FDs to remove
1763 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1770 sx_sunlock(&filelist_lock);
1772 * for each FD on our hit list, do the following two things
1774 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1775 struct file *tfp = *fpp;
1777 if (tfp->f_type == DTYPE_SOCKET &&
1778 tfp->f_data != NULL) {
1780 sorflush(tfp->f_data);
1785 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1786 closef(*fpp, (struct thread *) NULL);
1789 free(extra_ref, M_TEMP);
1793 unp_dispose(struct mbuf *m)
1797 unp_scan(m, unp_discard);
1801 unp_listen(struct socket *so, struct unpcb *unp, int backlog,
1809 error = solisten_proto_check(so);
1811 cru2x(td->td_ucred, &unp->unp_peercred);
1812 unp->unp_flags |= UNP_HAVEPCCACHED;
1813 solisten_proto(so, backlog);
1820 unp_scan(struct mbuf *m0, void (*op)(struct file *))
1827 socklen_t clen, datalen;
1830 while (m0 != NULL) {
1831 for (m = m0; m; m = m->m_next) {
1832 if (m->m_type != MT_CONTROL)
1835 cm = mtod(m, struct cmsghdr *);
1838 while (cm != NULL) {
1839 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1842 data = CMSG_DATA(cm);
1843 datalen = (caddr_t)cm + cm->cmsg_len
1846 if (cm->cmsg_level == SOL_SOCKET &&
1847 cm->cmsg_type == SCM_RIGHTS) {
1848 qfds = datalen / sizeof (struct file *);
1850 for (i = 0; i < qfds; i++)
1854 if (CMSG_SPACE(datalen) < clen) {
1855 clen -= CMSG_SPACE(datalen);
1856 cm = (struct cmsghdr *)
1857 ((caddr_t)cm + CMSG_SPACE(datalen));
1869 unp_mark(struct file *fp)
1871 if (fp->f_gcflag & FMARK)
1874 fp->f_gcflag |= (FMARK|FDEFER);
1878 unp_discard(struct file *fp)
1886 (void) closef(fp, (struct thread *)NULL);