2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
34 * $FreeBSD: src/sys/kern/uipc_usrreq.c,v 1.54.2.10 2003/03/04 17:28:09 nectar Exp $
35 * $DragonFly: src/sys/kern/uipc_usrreq.c,v 1.44 2008/09/06 05:44:58 dillon Exp $
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/domain.h>
42 #include <sys/fcntl.h>
43 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
46 #include <sys/filedesc.h>
48 #include <sys/nlookup.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/resourcevar.h>
54 #include <sys/mount.h>
55 #include <sys/sysctl.h>
57 #include <sys/unpcb.h>
58 #include <sys/vnode.h>
59 #include <sys/file2.h>
60 #include <sys/spinlock2.h>
63 static MALLOC_DEFINE(M_UNPCB, "unpcb", "unpcb struct");
64 static unp_gen_t unp_gencnt;
65 static u_int unp_count;
67 static struct unp_head unp_shead, unp_dhead;
70 * Unix communications domain.
74 * rethink name space problems
75 * need a proper out-of-band
78 static struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
79 static ino_t unp_ino = 1; /* prototype for fake inode numbers */
80 static struct spinlock unp_ino_spin = SPINLOCK_INITIALIZER(&unp_ino_spin);
82 static int unp_attach (struct socket *, struct pru_attach_info *);
83 static void unp_detach (struct unpcb *);
84 static int unp_bind (struct unpcb *,struct sockaddr *, struct thread *);
85 static int unp_connect (struct socket *,struct sockaddr *,
87 static void unp_disconnect (struct unpcb *);
88 static void unp_shutdown (struct unpcb *);
89 static void unp_drop (struct unpcb *, int);
90 static void unp_gc (void);
91 static int unp_gc_clearmarks(struct file *, void *);
92 static int unp_gc_checkmarks(struct file *, void *);
93 static int unp_gc_checkrefs(struct file *, void *);
94 static int unp_revoke_gc_check(struct file *, void *);
95 static void unp_scan (struct mbuf *, void (*)(struct file *, void *),
97 static void unp_mark (struct file *, void *data);
98 static void unp_discard (struct file *, void *);
99 static int unp_internalize (struct mbuf *, struct thread *);
100 static int unp_listen (struct unpcb *, struct thread *);
101 static void unp_fp_externalize(struct proc *p, struct file *fp, int fd);
104 uipc_abort(struct socket *so)
106 struct unpcb *unp = so->so_pcb;
110 unp_drop(unp, ECONNABORTED);
117 uipc_accept(struct socket *so, struct sockaddr **nam)
119 struct unpcb *unp = so->so_pcb;
125 * Pass back name of connected socket,
126 * if it was bound and we are still connected
127 * (our peer may have closed already!).
129 if (unp->unp_conn && unp->unp_conn->unp_addr) {
130 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
132 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
138 uipc_attach(struct socket *so, int proto, struct pru_attach_info *ai)
140 struct unpcb *unp = so->so_pcb;
144 return unp_attach(so, ai);
148 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
150 struct unpcb *unp = so->so_pcb;
154 return unp_bind(unp, nam, td);
158 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
160 struct unpcb *unp = so->so_pcb;
164 return unp_connect(so, nam, td);
168 uipc_connect2(struct socket *so1, struct socket *so2)
170 struct unpcb *unp = so1->so_pcb;
175 return unp_connect2(so1, so2);
178 /* control is EOPNOTSUPP */
181 uipc_detach(struct socket *so)
183 struct unpcb *unp = so->so_pcb;
193 uipc_disconnect(struct socket *so)
195 struct unpcb *unp = so->so_pcb;
204 uipc_listen(struct socket *so, struct thread *td)
206 struct unpcb *unp = so->so_pcb;
208 if (unp == NULL || unp->unp_vnode == NULL)
210 return unp_listen(unp, td);
214 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
216 struct unpcb *unp = so->so_pcb;
220 if (unp->unp_conn && unp->unp_conn->unp_addr)
221 *nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr);
224 * XXX: It seems that this test always fails even when
225 * connection is established. So, this else clause is
226 * added as workaround to return PF_LOCAL sockaddr.
228 *nam = dup_sockaddr((struct sockaddr *)&sun_noname);
234 uipc_rcvd(struct socket *so, int flags)
236 struct unpcb *unp = so->so_pcb;
241 switch (so->so_type) {
243 panic("uipc_rcvd DGRAM?");
248 if (unp->unp_conn == NULL)
251 * Because we are transfering mbufs directly to the
252 * peer socket we have to use SSB_STOP on the sender
253 * to prevent it from building up infinite mbufs.
255 so2 = unp->unp_conn->unp_socket;
256 if (so->so_rcv.ssb_cc < so2->so_snd.ssb_hiwat &&
257 so->so_rcv.ssb_mbcnt < so2->so_snd.ssb_mbmax
259 so2->so_snd.ssb_flags &= ~SSB_STOP;
265 panic("uipc_rcvd unknown socktype");
270 /* pru_rcvoob is EOPNOTSUPP */
273 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
274 struct mbuf *control, struct thread *td)
277 struct unpcb *unp = so->so_pcb;
284 if (flags & PRUS_OOB) {
289 if (control && (error = unp_internalize(control, td)))
292 switch (so->so_type) {
295 struct sockaddr *from;
302 error = unp_connect(so, nam, td);
306 if (unp->unp_conn == NULL) {
311 so2 = unp->unp_conn->unp_socket;
313 from = (struct sockaddr *)unp->unp_addr;
316 if (ssb_appendaddr(&so2->so_rcv, from, m, control)) {
330 /* Connect if not connected yet. */
332 * Note: A better implementation would complain
333 * if not equal to the peer's address.
335 if (!(so->so_state & SS_ISCONNECTED)) {
337 error = unp_connect(so, nam, td);
346 if (so->so_state & SS_CANTSENDMORE) {
350 if (unp->unp_conn == NULL)
351 panic("uipc_send connected but no connection?");
352 so2 = unp->unp_conn->unp_socket;
354 * Send to paired receive port, and then reduce
355 * send buffer hiwater marks to maintain backpressure.
359 if (ssb_appendcontrol(&so2->so_rcv, m, control)) {
363 } else if (so->so_type == SOCK_SEQPACKET) {
364 sbappendrecord(&so2->so_rcv.sb, m);
367 sbappend(&so2->so_rcv.sb, m);
372 * Because we are transfering mbufs directly to the
373 * peer socket we have to use SSB_STOP on the sender
374 * to prevent it from building up infinite mbufs.
376 if (so2->so_rcv.ssb_cc >= so->so_snd.ssb_hiwat ||
377 so2->so_rcv.ssb_mbcnt >= so->so_snd.ssb_mbmax
379 so->so_snd.ssb_flags |= SSB_STOP;
385 panic("uipc_send unknown socktype");
389 * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
391 if (flags & PRUS_EOF) {
396 if (control && error != 0)
397 unp_dispose(control);
411 uipc_sense(struct socket *so, struct stat *sb)
413 struct unpcb *unp = so->so_pcb;
417 sb->st_blksize = so->so_snd.ssb_hiwat;
419 if (unp->unp_ino == 0) { /* make up a non-zero inode number */
420 spin_lock_wr(&unp_ino_spin);
421 unp->unp_ino = unp_ino++;
422 spin_unlock_wr(&unp_ino_spin);
424 sb->st_ino = unp->unp_ino;
429 uipc_shutdown(struct socket *so)
431 struct unpcb *unp = so->so_pcb;
441 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
443 struct unpcb *unp = so->so_pcb;
448 *nam = dup_sockaddr((struct sockaddr *)unp->unp_addr);
452 struct pr_usrreqs uipc_usrreqs = {
453 .pru_abort = uipc_abort,
454 .pru_accept = uipc_accept,
455 .pru_attach = uipc_attach,
456 .pru_bind = uipc_bind,
457 .pru_connect = uipc_connect,
458 .pru_connect2 = uipc_connect2,
459 .pru_control = pru_control_notsupp,
460 .pru_detach = uipc_detach,
461 .pru_disconnect = uipc_disconnect,
462 .pru_listen = uipc_listen,
463 .pru_peeraddr = uipc_peeraddr,
464 .pru_rcvd = uipc_rcvd,
465 .pru_rcvoob = pru_rcvoob_notsupp,
466 .pru_send = uipc_send,
467 .pru_sense = uipc_sense,
468 .pru_shutdown = uipc_shutdown,
469 .pru_sockaddr = uipc_sockaddr,
470 .pru_sosend = sosend,
471 .pru_soreceive = soreceive,
476 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
478 struct unpcb *unp = so->so_pcb;
481 switch (sopt->sopt_dir) {
483 switch (sopt->sopt_name) {
485 if (unp->unp_flags & UNP_HAVEPC)
486 soopt_from_kbuf(sopt, &unp->unp_peercred,
487 sizeof(unp->unp_peercred));
489 if (so->so_type == SOCK_STREAM)
491 else if (so->so_type == SOCK_SEQPACKET)
511 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
512 * for stream sockets, although the total for sender and receiver is
513 * actually only PIPSIZ.
515 * Datagram sockets really use the sendspace as the maximum datagram size,
516 * and don't really want to reserve the sendspace. Their recvspace should
517 * be large enough for at least one max-size datagram plus address.
519 * We want the local send/recv space to be significant larger then lo0's
525 static u_long unpst_sendspace = PIPSIZ;
526 static u_long unpst_recvspace = PIPSIZ;
527 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
528 static u_long unpdg_recvspace = 4*1024;
530 static int unp_rights; /* file descriptors in flight */
531 static struct spinlock unp_spin = SPINLOCK_INITIALIZER(&unp_spin);
533 SYSCTL_DECL(_net_local_seqpacket);
534 SYSCTL_DECL(_net_local_stream);
535 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
536 &unpst_sendspace, 0, "");
537 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
538 &unpst_recvspace, 0, "");
540 SYSCTL_DECL(_net_local_dgram);
541 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
542 &unpdg_sendspace, 0, "");
543 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
544 &unpdg_recvspace, 0, "");
546 SYSCTL_DECL(_net_local);
547 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
550 unp_attach(struct socket *so, struct pru_attach_info *ai)
555 if (so->so_snd.ssb_hiwat == 0 || so->so_rcv.ssb_hiwat == 0) {
556 switch (so->so_type) {
560 error = soreserve(so, unpst_sendspace, unpst_recvspace,
565 error = soreserve(so, unpdg_sendspace, unpdg_recvspace,
575 unp = kmalloc(sizeof(*unp), M_UNPCB, M_NOWAIT|M_ZERO);
578 unp->unp_gencnt = ++unp_gencnt;
580 LIST_INIT(&unp->unp_refs);
581 unp->unp_socket = so;
582 unp->unp_rvnode = ai->fd_rdir; /* jail cruft XXX JH */
583 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
584 : &unp_shead, unp, unp_link);
585 so->so_pcb = (caddr_t)unp;
590 unp_detach(struct unpcb *unp)
592 LIST_REMOVE(unp, unp_link);
593 unp->unp_gencnt = ++unp_gencnt;
595 if (unp->unp_vnode) {
596 unp->unp_vnode->v_socket = NULL;
597 vrele(unp->unp_vnode);
598 unp->unp_vnode = NULL;
602 while (!LIST_EMPTY(&unp->unp_refs))
603 unp_drop(LIST_FIRST(&unp->unp_refs), ECONNRESET);
604 soisdisconnected(unp->unp_socket);
605 unp->unp_socket->so_pcb = NULL;
608 * Normally the receive buffer is flushed later,
609 * in sofree, but if our receive buffer holds references
610 * to descriptors that are now garbage, we will dispose
611 * of those descriptor references after the garbage collector
612 * gets them (resulting in a "panic: closef: count < 0").
614 sorflush(unp->unp_socket);
618 kfree(unp->unp_addr, M_SONAME);
623 unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
625 struct proc *p = td->td_proc;
626 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
630 struct nlookupdata nd;
631 char buf[SOCK_MAXADDRLEN];
633 if (unp->unp_vnode != NULL)
635 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
638 strncpy(buf, soun->sun_path, namelen);
639 buf[namelen] = 0; /* null-terminate the string */
640 error = nlookup_init(&nd, buf, UIO_SYSSPACE,
641 NLC_LOCKVP | NLC_CREATE | NLC_REFDVP);
643 error = nlookup(&nd);
644 if (error == 0 && nd.nl_nch.ncp->nc_vp != NULL)
650 vattr.va_type = VSOCK;
651 vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
652 error = VOP_NCREATE(&nd.nl_nch, nd.nl_dvp, &vp, nd.nl_cred, &vattr);
654 vp->v_socket = unp->unp_socket;
656 unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam);
665 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
667 struct proc *p = td->td_proc;
668 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
670 struct socket *so2, *so3;
671 struct unpcb *unp, *unp2, *unp3;
673 struct nlookupdata nd;
674 char buf[SOCK_MAXADDRLEN];
678 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
681 strncpy(buf, soun->sun_path, len);
685 error = nlookup_init(&nd, buf, UIO_SYSSPACE, NLC_FOLLOW);
687 error = nlookup(&nd);
689 error = cache_vget(&nd.nl_nch, nd.nl_cred, LK_EXCLUSIVE, &vp);
694 if (vp->v_type != VSOCK) {
698 error = VOP_ACCESS(vp, VWRITE, p->p_ucred);
703 error = ECONNREFUSED;
706 if (so->so_type != so2->so_type) {
710 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
711 if (!(so2->so_options & SO_ACCEPTCONN) ||
712 (so3 = sonewconn(so2, 0)) == NULL) {
713 error = ECONNREFUSED;
720 unp3->unp_addr = (struct sockaddr_un *)
721 dup_sockaddr((struct sockaddr *)unp2->unp_addr);
724 * unp_peercred management:
726 * The connecter's (client's) credentials are copied
727 * from its process structure at the time of connect()
730 cru2x(p->p_ucred, &unp3->unp_peercred);
731 unp3->unp_flags |= UNP_HAVEPC;
733 * The receiver's (server's) credentials are copied
734 * from the unp_peercred member of socket on which the
735 * former called listen(); unp_listen() cached that
736 * process's credentials at that time so we can use
739 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
740 ("unp_connect: listener without cached peercred"));
741 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
742 sizeof(unp->unp_peercred));
743 unp->unp_flags |= UNP_HAVEPC;
747 error = unp_connect2(so, so2);
754 unp_connect2(struct socket *so, struct socket *so2)
756 struct unpcb *unp = so->so_pcb;
759 if (so2->so_type != so->so_type)
762 unp->unp_conn = unp2;
763 switch (so->so_type) {
766 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
772 unp2->unp_conn = unp;
778 panic("unp_connect2");
784 unp_disconnect(struct unpcb *unp)
786 struct unpcb *unp2 = unp->unp_conn;
791 unp->unp_conn = NULL;
793 switch (unp->unp_socket->so_type) {
795 LIST_REMOVE(unp, unp_reflink);
796 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
800 soisdisconnected(unp->unp_socket);
801 unp2->unp_conn = NULL;
802 soisdisconnected(unp2->unp_socket);
809 unp_abort(struct unpcb *unp)
817 prison_unpcb(struct thread *td, struct unpcb *unp)
823 if ((p = td->td_proc) == NULL)
825 if (!p->p_ucred->cr_prison)
827 if (p->p_fd->fd_rdir == unp->unp_rvnode)
833 unp_pcblist(SYSCTL_HANDLER_ARGS)
836 struct unpcb *unp, **unp_list;
838 struct unp_head *head;
840 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
842 KKASSERT(curproc != NULL);
845 * The process of preparing the PCB list is too time-consuming and
846 * resource-intensive to repeat twice on every request.
848 if (req->oldptr == NULL) {
850 req->oldidx = (n + n/8) * sizeof(struct xunpcb);
854 if (req->newptr != NULL)
858 * OK, now we're committed to doing something.
863 unp_list = kmalloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
865 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
866 unp = LIST_NEXT(unp, unp_link)) {
867 if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->td, unp))
870 n = i; /* in case we lost some during malloc */
873 for (i = 0; i < n; i++) {
875 if (unp->unp_gencnt <= gencnt) {
877 xu.xu_len = sizeof xu;
880 * XXX - need more locking here to protect against
881 * connect/disconnect races for SMP.
884 bcopy(unp->unp_addr, &xu.xu_addr,
885 unp->unp_addr->sun_len);
886 if (unp->unp_conn && unp->unp_conn->unp_addr)
887 bcopy(unp->unp_conn->unp_addr,
889 unp->unp_conn->unp_addr->sun_len);
890 bcopy(unp, &xu.xu_unp, sizeof *unp);
891 sotoxsocket(unp->unp_socket, &xu.xu_socket);
892 error = SYSCTL_OUT(req, &xu, sizeof xu);
895 kfree(unp_list, M_TEMP);
899 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
900 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
901 "List of active local datagram sockets");
902 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
903 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
904 "List of active local stream sockets");
905 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, CTLFLAG_RD,
906 (caddr_t)(long)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
907 "List of active local seqpacket stream sockets");
910 unp_shutdown(struct unpcb *unp)
914 if ((unp->unp_socket->so_type == SOCK_STREAM ||
915 unp->unp_socket->so_type == SOCK_SEQPACKET) &&
916 unp->unp_conn != NULL && (so = unp->unp_conn->unp_socket)) {
922 unp_drop(struct unpcb *unp, int err)
924 struct socket *so = unp->unp_socket;
939 unp_externalize(struct mbuf *rights)
941 struct proc *p = curproc; /* XXX */
943 struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
947 int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
948 / sizeof (struct file *);
952 * if the new FD's will not fit, then we free them all
954 if (!fdavail(p, newfds)) {
955 rp = (struct file **)CMSG_DATA(cm);
956 for (i = 0; i < newfds; i++) {
959 * zero the pointer before calling unp_discard,
960 * since it may end up in unp_gc()..
963 unp_discard(fp, NULL);
969 * now change each pointer to an fd in the global table to
970 * an integer that is the index to the local fd table entry
971 * that we set up to point to the global one we are transferring.
972 * If sizeof (struct file *) is bigger than or equal to sizeof int,
973 * then do it in forward order. In that case, an integer will
974 * always come in the same place or before its corresponding
975 * struct file pointer.
976 * If sizeof (struct file *) is smaller than sizeof int, then
977 * do it in reverse order.
979 if (sizeof (struct file *) >= sizeof (int)) {
980 fdp = (int *)(cm + 1);
981 rp = (struct file **)CMSG_DATA(cm);
982 for (i = 0; i < newfds; i++) {
983 if (fdalloc(p, 0, &f))
984 panic("unp_externalize");
986 unp_fp_externalize(p, fp, f);
990 fdp = (int *)(cm + 1) + newfds - 1;
991 rp = (struct file **)CMSG_DATA(cm) + newfds - 1;
992 for (i = 0; i < newfds; i++) {
993 if (fdalloc(p, 0, &f))
994 panic("unp_externalize");
996 unp_fp_externalize(p, fp, f);
1002 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1005 cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
1006 rights->m_len = cm->cmsg_len;
1011 unp_fp_externalize(struct proc *p, struct file *fp, int fd)
1018 if (fp->f_flag & FREVOKED) {
1019 kprintf("Warning: revoked fp exiting unix socket\n");
1021 error = falloc(p, &fx, NULL);
1025 fsetfd(p, NULL, fd);
1031 spin_lock_wr(&unp_spin);
1034 spin_unlock_wr(&unp_spin);
1042 LIST_INIT(&unp_dhead);
1043 LIST_INIT(&unp_shead);
1044 spin_init(&unp_spin);
1048 unp_internalize(struct mbuf *control, struct thread *td)
1050 struct proc *p = td->td_proc;
1051 struct filedesc *fdescp;
1052 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1056 struct cmsgcred *cmcred;
1062 if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
1063 cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
1067 * Fill in credential information.
1069 if (cm->cmsg_type == SCM_CREDS) {
1070 cmcred = (struct cmsgcred *)(cm + 1);
1071 cmcred->cmcred_pid = p->p_pid;
1072 cmcred->cmcred_uid = p->p_ucred->cr_ruid;
1073 cmcred->cmcred_gid = p->p_ucred->cr_rgid;
1074 cmcred->cmcred_euid = p->p_ucred->cr_uid;
1075 cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
1077 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1078 cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
1082 oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
1084 * check that all the FDs passed in refer to legal OPEN files
1085 * If not, reject the entire operation.
1087 fdp = (int *)(cm + 1);
1088 for (i = 0; i < oldfds; i++) {
1090 if ((unsigned)fd >= fdescp->fd_nfiles ||
1091 fdescp->fd_files[fd].fp == NULL)
1093 if (fdescp->fd_files[fd].fp->f_type == DTYPE_KQUEUE)
1094 return (EOPNOTSUPP);
1097 * Now replace the integer FDs with pointers to
1098 * the associated global file table entry..
1099 * Allocate a bigger buffer as necessary. But if an cluster is not
1100 * enough, return E2BIG.
1102 newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1103 if (newlen > MCLBYTES)
1105 if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1106 if (control->m_flags & M_EXT)
1108 MCLGET(control, MB_WAIT);
1109 if (!(control->m_flags & M_EXT))
1112 /* copy the data to the cluster */
1113 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1114 cm = mtod(control, struct cmsghdr *);
1118 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1121 control->m_len = cm->cmsg_len = newlen;
1124 * Transform the file descriptors into struct file pointers.
1125 * If sizeof (struct file *) is bigger than or equal to sizeof int,
1126 * then do it in reverse order so that the int won't get until
1128 * If sizeof (struct file *) is smaller than sizeof int, then
1129 * do it in forward order.
1131 if (sizeof (struct file *) >= sizeof (int)) {
1132 fdp = (int *)(cm + 1) + oldfds - 1;
1133 rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1134 for (i = 0; i < oldfds; i++) {
1135 fp = fdescp->fd_files[*fdp--].fp;
1138 spin_lock_wr(&unp_spin);
1141 spin_unlock_wr(&unp_spin);
1144 fdp = (int *)(cm + 1);
1145 rp = (struct file **)CMSG_DATA(cm);
1146 for (i = 0; i < oldfds; i++) {
1147 fp = fdescp->fd_files[*fdp++].fp;
1150 spin_lock_wr(&unp_spin);
1153 spin_unlock_wr(&unp_spin);
1160 * Garbage collect in-transit file descriptors that get lost due to
1161 * loops (i.e. when a socket is sent to another process over itself,
1162 * and more complex situations).
1164 * NOT MPSAFE - TODO socket flush code and maybe closef. Rest is MPSAFE.
1167 struct unp_gc_info {
1168 struct file **extra_ref;
1169 struct file *locked_fp;
1178 struct unp_gc_info info;
1179 static boolean_t unp_gcing;
1183 spin_lock_wr(&unp_spin);
1185 spin_unlock_wr(&unp_spin);
1189 spin_unlock_wr(&unp_spin);
1192 * before going through all this, set all FDs to
1193 * be NOT defered and NOT externally accessible
1196 allfiles_scan_exclusive(unp_gc_clearmarks, NULL);
1198 allfiles_scan_exclusive(unp_gc_checkmarks, &info);
1199 } while (info.defer);
1202 * We grab an extra reference to each of the file table entries
1203 * that are not otherwise accessible and then free the rights
1204 * that are stored in messages on them.
1206 * The bug in the orginal code is a little tricky, so I'll describe
1207 * what's wrong with it here.
1209 * It is incorrect to simply unp_discard each entry for f_msgcount
1210 * times -- consider the case of sockets A and B that contain
1211 * references to each other. On a last close of some other socket,
1212 * we trigger a gc since the number of outstanding rights (unp_rights)
1213 * is non-zero. If during the sweep phase the gc code un_discards,
1214 * we end up doing a (full) closef on the descriptor. A closef on A
1215 * results in the following chain. Closef calls soo_close, which
1216 * calls soclose. Soclose calls first (through the switch
1217 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1218 * returns because the previous instance had set unp_gcing, and
1219 * we return all the way back to soclose, which marks the socket
1220 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1221 * to free up the rights that are queued in messages on the socket A,
1222 * i.e., the reference on B. The sorflush calls via the dom_dispose
1223 * switch unp_dispose, which unp_scans with unp_discard. This second
1224 * instance of unp_discard just calls closef on B.
1226 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1227 * which results in another closef on A. Unfortunately, A is already
1228 * being closed, and the descriptor has already been marked with
1229 * SS_NOFDREF, and soclose panics at this point.
1231 * Here, we first take an extra reference to each inaccessible
1232 * descriptor. Then, we call sorflush ourself, since we know
1233 * it is a Unix domain socket anyhow. After we destroy all the
1234 * rights carried in messages, we do a last closef to get rid
1235 * of our extra reference. This is the last close, and the
1236 * unp_detach etc will shut down the socket.
1238 * 91/09/19, bsy@cs.cmu.edu
1240 info.extra_ref = kmalloc(256 * sizeof(struct file *), M_FILE, M_WAITOK);
1241 info.maxindex = 256;
1248 allfiles_scan_exclusive(unp_gc_checkrefs, &info);
1251 * For each FD on our hit list, do the following two things
1253 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp) {
1254 struct file *tfp = *fpp;
1255 if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1256 sorflush((struct socket *)(tfp->f_data));
1258 for (i = info.index, fpp = info.extra_ref; --i >= 0; ++fpp)
1260 } while (info.index == info.maxindex);
1261 kfree((caddr_t)info.extra_ref, M_FILE);
1266 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1269 unp_gc_checkrefs(struct file *fp, void *data)
1271 struct unp_gc_info *info = data;
1273 if (fp->f_count == 0)
1275 if (info->index == info->maxindex)
1279 * If all refs are from msgs, and it's not marked accessible
1280 * then it must be referenced from some unreachable cycle
1281 * of (shut-down) FDs, so include it in our
1282 * list of FDs to remove
1284 if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1285 info->extra_ref[info->index++] = fp;
1292 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1295 unp_gc_clearmarks(struct file *fp, void *data __unused)
1297 atomic_clear_int(&fp->f_flag, FMARK | FDEFER);
1302 * MPSAFE - NOTE: filehead list and file pointer spinlocked on entry
1305 unp_gc_checkmarks(struct file *fp, void *data)
1307 struct unp_gc_info *info = data;
1311 * If the file is not open, skip it
1313 if (fp->f_count == 0)
1316 * If we already marked it as 'defer' in a
1317 * previous pass, then try process it this time
1320 if (fp->f_flag & FDEFER) {
1321 atomic_clear_int(&fp->f_flag, FDEFER);
1325 * if it's not defered, then check if it's
1326 * already marked.. if so skip it
1328 if (fp->f_flag & FMARK)
1331 * If all references are from messages
1332 * in transit, then skip it. it's not
1333 * externally accessible.
1335 if (fp->f_count == fp->f_msgcount)
1338 * If it got this far then it must be
1339 * externally accessible.
1341 atomic_set_int(&fp->f_flag, FMARK);
1345 * either it was defered, or it is externally
1346 * accessible and not already marked so.
1347 * Now check if it is possibly one of OUR sockets.
1349 if (fp->f_type != DTYPE_SOCKET ||
1350 (so = (struct socket *)fp->f_data) == NULL)
1352 if (so->so_proto->pr_domain != &localdomain ||
1353 !(so->so_proto->pr_flags & PR_RIGHTS))
1356 if (so->so_rcv.ssb_flags & SSB_LOCK) {
1358 * This is problematical; it's not clear
1359 * we need to wait for the sockbuf to be
1360 * unlocked (on a uniprocessor, at least),
1361 * and it's also not clear what to do
1362 * if sbwait returns an error due to receipt
1363 * of a signal. If sbwait does return
1364 * an error, we'll go into an infinite
1365 * loop. Delete all of this for now.
1367 sbwait(&so->so_rcv);
1372 * So, Ok, it's one of our sockets and it IS externally
1373 * accessible (or was defered). Now we look
1374 * to see if we hold any file descriptors in its
1375 * message buffers. Follow those links and mark them
1376 * as accessible too.
1378 info->locked_fp = fp;
1379 /* spin_lock_wr(&so->so_rcv.sb_spin); */
1380 unp_scan(so->so_rcv.ssb_mb, unp_mark, info);
1381 /* spin_unlock_wr(&so->so_rcv.sb_spin);*/
1386 * Scan all unix domain sockets and replace any revoked file pointers
1387 * found with the dummy file pointer fx. We don't worry about races
1388 * against file pointers being read out as those are handled in the
1392 #define REVOKE_GC_MAXFILES 32
1394 struct unp_revoke_gc_info {
1396 struct file *fary[REVOKE_GC_MAXFILES];
1401 unp_revoke_gc(struct file *fx)
1403 struct unp_revoke_gc_info info;
1409 allfiles_scan_exclusive(unp_revoke_gc_check, &info);
1410 for (i = 0; i < info.fcount; ++i)
1411 unp_fp_externalize(NULL, info.fary[i], -1);
1412 } while (info.fcount == REVOKE_GC_MAXFILES);
1416 * Check for and replace revoked descriptors.
1418 * WARNING: This routine is not allowed to block.
1421 unp_revoke_gc_check(struct file *fps, void *vinfo)
1423 struct unp_revoke_gc_info *info = vinfo;
1434 * Is this a unix domain socket with rights-passing abilities?
1436 if (fps->f_type != DTYPE_SOCKET)
1438 if ((so = (struct socket *)fps->f_data) == NULL)
1440 if (so->so_proto->pr_domain != &localdomain)
1442 if ((so->so_proto->pr_flags & PR_RIGHTS) == 0)
1446 * Scan the mbufs for control messages and replace any revoked
1447 * descriptors we find.
1449 m0 = so->so_rcv.ssb_mb;
1451 for (m = m0; m; m = m->m_next) {
1452 if (m->m_type != MT_CONTROL)
1454 if (m->m_len < sizeof(*cm))
1456 cm = mtod(m, struct cmsghdr *);
1457 if (cm->cmsg_level != SOL_SOCKET ||
1458 cm->cmsg_type != SCM_RIGHTS) {
1461 qfds = (cm->cmsg_len -
1462 (CMSG_DATA(cm) - (u_char *)cm))
1463 / sizeof (struct file *);
1464 rp = (struct file **)CMSG_DATA(cm);
1465 for (i = 0; i < qfds; i++) {
1467 if (fp->f_flag & FREVOKED) {
1468 kprintf("Warning: Removing revoked fp from unix domain socket queue\n");
1470 info->fx->f_msgcount++;
1473 info->fary[info->fcount++] = fp;
1475 if (info->fcount == REVOKE_GC_MAXFILES)
1478 if (info->fcount == REVOKE_GC_MAXFILES)
1482 if (info->fcount == REVOKE_GC_MAXFILES)
1487 * Stop the scan if we filled up our array.
1489 if (info->fcount == REVOKE_GC_MAXFILES)
1495 unp_dispose(struct mbuf *m)
1498 unp_scan(m, unp_discard, NULL);
1502 unp_listen(struct unpcb *unp, struct thread *td)
1504 struct proc *p = td->td_proc;
1507 cru2x(p->p_ucred, &unp->unp_peercred);
1508 unp->unp_flags |= UNP_HAVEPCCACHED;
1513 unp_scan(struct mbuf *m0, void (*op)(struct file *, void *), void *data)
1522 for (m = m0; m; m = m->m_next) {
1523 if (m->m_type == MT_CONTROL &&
1524 m->m_len >= sizeof(*cm)) {
1525 cm = mtod(m, struct cmsghdr *);
1526 if (cm->cmsg_level != SOL_SOCKET ||
1527 cm->cmsg_type != SCM_RIGHTS)
1529 qfds = (cm->cmsg_len -
1530 (CMSG_DATA(cm) - (u_char *)cm))
1531 / sizeof (struct file *);
1532 rp = (struct file **)CMSG_DATA(cm);
1533 for (i = 0; i < qfds; i++)
1535 break; /* XXX, but saves time */
1543 unp_mark(struct file *fp, void *data)
1545 struct unp_gc_info *info = data;
1547 if ((fp->f_flag & FMARK) == 0) {
1549 atomic_set_int(&fp->f_flag, FMARK | FDEFER);
1554 unp_discard(struct file *fp, void *data __unused)
1556 spin_lock_wr(&unp_spin);
1559 spin_unlock_wr(&unp_spin);