uipc_usrreq.c revision 31016
1/*
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
20 *
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
31 * SUCH DAMAGE.
32 *
33 *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
34 *	$Id: uipc_usrreq.c,v 1.28 1997/10/12 20:24:18 phk Exp $
35 */
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/kernel.h>
40#include <sys/domain.h>
41#include <sys/fcntl.h>
42#include <sys/file.h>
43#include <sys/filedesc.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/namei.h>
47#include <sys/proc.h>
48#include <sys/protosw.h>
49#include <sys/socket.h>
50#include <sys/socketvar.h>
51#include <sys/stat.h>
52#include <sys/sysctl.h>
53#include <sys/un.h>
54#include <sys/vnode.h>
55
56MALLOC_DEFINE(M_FILE, "file", "Open file structure");
57
58/*
59 * Unix communications domain.
60 *
61 * TODO:
62 *	SEQPACKET, RDM
63 *	rethink name space problems
64 *	need a proper out-of-band
65 */
66static struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
67static ino_t	unp_ino;		/* prototype for fake inode numbers */
68
69static int     unp_attach __P((struct socket *));
70static void    unp_detach __P((struct unpcb *));
71static int     unp_bind __P((struct unpcb *,struct sockaddr *, struct proc *));
72static int     unp_connect __P((struct socket *,struct sockaddr *,
73				struct proc *));
74static void    unp_disconnect __P((struct unpcb *));
75static void    unp_shutdown __P((struct unpcb *));
76static void    unp_drop __P((struct unpcb *, int));
77static void    unp_gc __P((void));
78static void    unp_scan __P((struct mbuf *, void (*)(struct file *)));
79static void    unp_mark __P((struct file *));
80static void    unp_discard __P((struct file *));
81static int     unp_internalize __P((struct mbuf *, struct proc *));
82
83static int
84uipc_abort(struct socket *so)
85{
86	struct unpcb *unp = sotounpcb(so);
87
88	if (unp == 0)
89		return EINVAL;
90	unp_drop(unp, ECONNABORTED);
91	return 0;
92}
93
94static int
95uipc_accept(struct socket *so, struct sockaddr **nam)
96{
97	struct unpcb *unp = sotounpcb(so);
98
99	if (unp == 0)
100		return EINVAL;
101
102	/*
103	 * Pass back name of connected socket,
104	 * if it was bound and we are still connected
105	 * (our peer may have closed already!).
106	 */
107	if (unp->unp_conn && unp->unp_conn->unp_addr) {
108		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
109				    1);
110	} else {
111		*nam = dup_sockaddr((struct sockaddr *)&sun_noname, 1);
112	}
113	return 0;
114}
115
116static int
117uipc_attach(struct socket *so, int proto, struct proc *p)
118{
119	struct unpcb *unp = sotounpcb(so);
120
121	if (unp != 0)
122		return EISCONN;
123	return unp_attach(so);
124}
125
126static int
127uipc_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
128{
129	struct unpcb *unp = sotounpcb(so);
130
131	if (unp == 0)
132		return EINVAL;
133
134	return unp_bind(unp, nam, p);
135}
136
137static int
138uipc_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
139{
140	struct unpcb *unp = sotounpcb(so);
141
142	if (unp == 0)
143		return EINVAL;
144	return unp_connect(so, nam, curproc);
145}
146
147static int
148uipc_connect2(struct socket *so1, struct socket *so2)
149{
150	struct unpcb *unp = sotounpcb(so1);
151
152	if (unp == 0)
153		return EINVAL;
154
155	return unp_connect2(so1, so2);
156}
157
158/* control is EOPNOTSUPP */
159
160static int
161uipc_detach(struct socket *so)
162{
163	struct unpcb *unp = sotounpcb(so);
164
165	if (unp == 0)
166		return EINVAL;
167
168	unp_detach(unp);
169	return 0;
170}
171
172static int
173uipc_disconnect(struct socket *so)
174{
175	struct unpcb *unp = sotounpcb(so);
176
177	if (unp == 0)
178		return EINVAL;
179	unp_disconnect(unp);
180	return 0;
181}
182
183static int
184uipc_listen(struct socket *so, struct proc *p)
185{
186	struct unpcb *unp = sotounpcb(so);
187
188	if (unp == 0 || unp->unp_vnode == 0)
189		return EINVAL;
190	return 0;
191}
192
193static int
194uipc_peeraddr(struct socket *so, struct sockaddr **nam)
195{
196	struct unpcb *unp = sotounpcb(so);
197
198	if (unp == 0)
199		return EINVAL;
200	if (unp->unp_conn && unp->unp_conn->unp_addr)
201		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
202				    1);
203	return 0;
204}
205
206static int
207uipc_rcvd(struct socket *so, int flags)
208{
209	struct unpcb *unp = sotounpcb(so);
210	struct socket *so2;
211
212	if (unp == 0)
213		return EINVAL;
214	switch (so->so_type) {
215	case SOCK_DGRAM:
216		panic("uipc_rcvd DGRAM?");
217		/*NOTREACHED*/
218
219	case SOCK_STREAM:
220#define	rcv (&so->so_rcv)
221#define snd (&so2->so_snd)
222		if (unp->unp_conn == 0)
223			break;
224		so2 = unp->unp_conn->unp_socket;
225		/*
226		 * Adjust backpressure on sender
227		 * and wakeup any waiting to write.
228		 */
229		snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
230		unp->unp_mbcnt = rcv->sb_mbcnt;
231		snd->sb_hiwat += unp->unp_cc - rcv->sb_cc;
232		unp->unp_cc = rcv->sb_cc;
233		sowwakeup(so2);
234#undef snd
235#undef rcv
236		break;
237
238	default:
239		panic("uipc_rcvd unknown socktype");
240	}
241	return 0;
242}
243
244/* pru_rcvoob is EOPNOTSUPP */
245
246static int
247uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
248	  struct mbuf *control, struct proc *p)
249{
250	int error = 0;
251	struct unpcb *unp = sotounpcb(so);
252	struct socket *so2;
253
254	if (unp == 0) {
255		error = EINVAL;
256		goto release;
257	}
258	if (flags & PRUS_OOB) {
259		error = EOPNOTSUPP;
260		goto release;
261	}
262
263	if (control && (error = unp_internalize(control, p)))
264		goto release;
265
266	switch (so->so_type) {
267	case SOCK_DGRAM:
268	{
269		struct sockaddr *from;
270
271		if (nam) {
272			if (unp->unp_conn) {
273				error = EISCONN;
274				break;
275			}
276			error = unp_connect(so, nam, p);
277			if (error)
278				break;
279		} else {
280			if (unp->unp_conn == 0) {
281				error = ENOTCONN;
282				break;
283			}
284		}
285		so2 = unp->unp_conn->unp_socket;
286		if (unp->unp_addr)
287			from = (struct sockaddr *)unp->unp_addr;
288		else
289			from = &sun_noname;
290		if (sbappendaddr(&so2->so_rcv, from, m, control)) {
291			sorwakeup(so2);
292			m = 0;
293			control = 0;
294		} else
295			error = ENOBUFS;
296		if (nam)
297			unp_disconnect(unp);
298		break;
299	}
300
301	case SOCK_STREAM:
302#define	rcv (&so2->so_rcv)
303#define	snd (&so->so_snd)
304		/* Connect if not connected yet. */
305		/*
306		 * Note: A better implementation would complain
307		 * if not equal to the peer's address.
308		 */
309		if ((so->so_state & SS_ISCONNECTED) == 0) {
310			if (nam) {
311				error = unp_connect(so, nam, p);
312				if (error)
313					break;	/* XXX */
314			} else {
315				error = ENOTCONN;
316				break;
317			}
318		}
319
320		if (so->so_state & SS_CANTSENDMORE) {
321			error = EPIPE;
322			break;
323		}
324		if (unp->unp_conn == 0)
325			panic("uipc_send connected but no connection?");
326		so2 = unp->unp_conn->unp_socket;
327		/*
328		 * Send to paired receive port, and then reduce
329		 * send buffer hiwater marks to maintain backpressure.
330		 * Wake up readers.
331		 */
332		if (control) {
333			if (sbappendcontrol(rcv, m, control))
334				control = 0;
335		} else
336			sbappend(rcv, m);
337		snd->sb_mbmax -=
338			rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
339		unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
340		snd->sb_hiwat -= rcv->sb_cc - unp->unp_conn->unp_cc;
341		unp->unp_conn->unp_cc = rcv->sb_cc;
342		sorwakeup(so2);
343		m = 0;
344#undef snd
345#undef rcv
346		break;
347
348	default:
349		panic("uipc_send unknown socktype");
350	}
351
352	/*
353	 * SEND_EOF is equivalent to a SEND followed by
354	 * a SHUTDOWN.
355	 */
356	if (flags & PRUS_EOF) {
357		socantsendmore(so);
358		unp_shutdown(unp);
359	}
360
361release:
362	if (control)
363		m_freem(control);
364	if (m)
365		m_freem(m);
366	return error;
367}
368
369static int
370uipc_sense(struct socket *so, struct stat *sb)
371{
372	struct unpcb *unp = sotounpcb(so);
373	struct socket *so2;
374
375	if (unp == 0)
376		return EINVAL;
377	sb->st_blksize = so->so_snd.sb_hiwat;
378	if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
379		so2 = unp->unp_conn->unp_socket;
380		sb->st_blksize += so2->so_rcv.sb_cc;
381	}
382	sb->st_dev = NODEV;
383	if (unp->unp_ino == 0)
384		unp->unp_ino = unp_ino++;
385	sb->st_ino = unp->unp_ino;
386	return (0);
387}
388
389static int
390uipc_shutdown(struct socket *so)
391{
392	struct unpcb *unp = sotounpcb(so);
393
394	if (unp == 0)
395		return EINVAL;
396	socantsendmore(so);
397	unp_shutdown(unp);
398	return 0;
399}
400
401static int
402uipc_sockaddr(struct socket *so, struct sockaddr **nam)
403{
404	struct unpcb *unp = sotounpcb(so);
405
406	if (unp == 0)
407		return EINVAL;
408	if (unp->unp_addr)
409		*nam = dup_sockaddr((struct sockaddr *)unp->unp_addr, 1);
410	return 0;
411}
412
413struct pr_usrreqs uipc_usrreqs = {
414	uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
415	uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
416	uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
417	uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
418	sosend, soreceive, sopoll
419};
420
421/*
422 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
423 * for stream sockets, although the total for sender and receiver is
424 * actually only PIPSIZ.
425 * Datagram sockets really use the sendspace as the maximum datagram size,
426 * and don't really want to reserve the sendspace.  Their recvspace should
427 * be large enough for at least one max-size datagram plus address.
428 */
429#ifndef PIPSIZ
430#define	PIPSIZ	8192
431#endif
432static u_long	unpst_sendspace = PIPSIZ;
433static u_long	unpst_recvspace = PIPSIZ;
434static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
435static u_long	unpdg_recvspace = 4*1024;
436
437static int	unp_rights;			/* file descriptors in flight */
438
439SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
440	   &unpst_sendspace, 0, "");
441SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
442	   &unpst_recvspace, 0, "");
443SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
444	   &unpdg_sendspace, 0, "");
445SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
446	   &unpdg_recvspace, 0, "");
447SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
448
449static int
450unp_attach(so)
451	struct socket *so;
452{
453	register struct unpcb *unp;
454	int error;
455
456	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
457		switch (so->so_type) {
458
459		case SOCK_STREAM:
460			error = soreserve(so, unpst_sendspace, unpst_recvspace);
461			break;
462
463		case SOCK_DGRAM:
464			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
465			break;
466
467		default:
468			panic("unp_attach");
469		}
470		if (error)
471			return (error);
472	}
473	MALLOC(unp, struct unpcb *, sizeof *unp, M_PCB, M_NOWAIT);
474	if (unp == NULL)
475		return (ENOBUFS);
476	bzero(unp, sizeof *unp);
477	so->so_pcb = (caddr_t)unp;
478	unp->unp_socket = so;
479	return (0);
480}
481
482static void
483unp_detach(unp)
484	register struct unpcb *unp;
485{
486	if (unp->unp_vnode) {
487		unp->unp_vnode->v_socket = 0;
488		vrele(unp->unp_vnode);
489		unp->unp_vnode = 0;
490	}
491	if (unp->unp_conn)
492		unp_disconnect(unp);
493	while (unp->unp_refs)
494		unp_drop(unp->unp_refs, ECONNRESET);
495	soisdisconnected(unp->unp_socket);
496	unp->unp_socket->so_pcb = 0;
497	if (unp_rights) {
498		/*
499		 * Normally the receive buffer is flushed later,
500		 * in sofree, but if our receive buffer holds references
501		 * to descriptors that are now garbage, we will dispose
502		 * of those descriptor references after the garbage collector
503		 * gets them (resulting in a "panic: closef: count < 0").
504		 */
505		sorflush(unp->unp_socket);
506		unp_gc();
507	}
508	if (unp->unp_addr)
509		FREE(unp->unp_addr, M_SONAME);
510	FREE(unp, M_PCB);
511}
512
513static int
514unp_bind(unp, nam, p)
515	struct unpcb *unp;
516	struct sockaddr *nam;
517	struct proc *p;
518{
519	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
520	register struct vnode *vp;
521	struct vattr vattr;
522	int error, namelen;
523	struct nameidata nd;
524	char buf[SOCK_MAXADDRLEN];
525
526	if (unp->unp_vnode != NULL)
527		return (EINVAL);
528#define offsetof(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
529	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
530	if (namelen <= 0)
531		return EINVAL;
532	strncpy(buf, soun->sun_path, namelen);
533	buf[namelen] = 0;	/* null-terminate the string */
534	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
535	    buf, p);
536/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
537	error = namei(&nd);
538	if (error)
539		return (error);
540	vp = nd.ni_vp;
541	if (vp != NULL) {
542		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
543		if (nd.ni_dvp == vp)
544			vrele(nd.ni_dvp);
545		else
546			vput(nd.ni_dvp);
547		vrele(vp);
548		return (EADDRINUSE);
549	}
550	VATTR_NULL(&vattr);
551	vattr.va_type = VSOCK;
552	vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
553	VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
554	if (error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr))
555		return (error);
556	vp = nd.ni_vp;
557	vp->v_socket = unp->unp_socket;
558	unp->unp_vnode = vp;
559	unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam, 1);
560	VOP_UNLOCK(vp, 0, p);
561	return (0);
562}
563
564static int
565unp_connect(so, nam, p)
566	struct socket *so;
567	struct sockaddr *nam;
568	struct proc *p;
569{
570	register struct sockaddr_un *soun = (struct sockaddr_un *)nam;
571	register struct vnode *vp;
572	register struct socket *so2, *so3;
573	struct unpcb *unp2, *unp3;
574	int error, len;
575	struct nameidata nd;
576	char buf[SOCK_MAXADDRLEN];
577
578	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
579	if (len <= 0)
580		return EINVAL;
581	strncpy(buf, soun->sun_path, len);
582	buf[len] = 0;
583
584	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, p);
585	error = namei(&nd);
586	if (error)
587		return (error);
588	vp = nd.ni_vp;
589	if (vp->v_type != VSOCK) {
590		error = ENOTSOCK;
591		goto bad;
592	}
593	error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p);
594	if (error)
595		goto bad;
596	so2 = vp->v_socket;
597	if (so2 == 0) {
598		error = ECONNREFUSED;
599		goto bad;
600	}
601	if (so->so_type != so2->so_type) {
602		error = EPROTOTYPE;
603		goto bad;
604	}
605	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
606		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
607		    (so3 = sonewconn(so2, 0)) == 0) {
608			error = ECONNREFUSED;
609			goto bad;
610		}
611		unp2 = sotounpcb(so2);
612		unp3 = sotounpcb(so3);
613		if (unp2->unp_addr)
614			unp3->unp_addr = (struct sockaddr_un *)
615				dup_sockaddr((struct sockaddr *)
616					     unp2->unp_addr, 1);
617		so2 = so3;
618	}
619	error = unp_connect2(so, so2);
620bad:
621	vput(vp);
622	return (error);
623}
624
625int
626unp_connect2(so, so2)
627	register struct socket *so;
628	register struct socket *so2;
629{
630	register struct unpcb *unp = sotounpcb(so);
631	register struct unpcb *unp2;
632
633	if (so2->so_type != so->so_type)
634		return (EPROTOTYPE);
635	unp2 = sotounpcb(so2);
636	unp->unp_conn = unp2;
637	switch (so->so_type) {
638
639	case SOCK_DGRAM:
640		unp->unp_nextref = unp2->unp_refs;
641		unp2->unp_refs = unp;
642		soisconnected(so);
643		break;
644
645	case SOCK_STREAM:
646		unp2->unp_conn = unp;
647		soisconnected(so);
648		soisconnected(so2);
649		break;
650
651	default:
652		panic("unp_connect2");
653	}
654	return (0);
655}
656
657static void
658unp_disconnect(unp)
659	struct unpcb *unp;
660{
661	register struct unpcb *unp2 = unp->unp_conn;
662
663	if (unp2 == 0)
664		return;
665	unp->unp_conn = 0;
666	switch (unp->unp_socket->so_type) {
667
668	case SOCK_DGRAM:
669		if (unp2->unp_refs == unp)
670			unp2->unp_refs = unp->unp_nextref;
671		else {
672			unp2 = unp2->unp_refs;
673			for (;;) {
674				if (unp2 == 0)
675					panic("unp_disconnect");
676				if (unp2->unp_nextref == unp)
677					break;
678				unp2 = unp2->unp_nextref;
679			}
680			unp2->unp_nextref = unp->unp_nextref;
681		}
682		unp->unp_nextref = 0;
683		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
684		break;
685
686	case SOCK_STREAM:
687		soisdisconnected(unp->unp_socket);
688		unp2->unp_conn = 0;
689		soisdisconnected(unp2->unp_socket);
690		break;
691	}
692}
693
694#ifdef notdef
695void
696unp_abort(unp)
697	struct unpcb *unp;
698{
699
700	unp_detach(unp);
701}
702#endif
703
704static void
705unp_shutdown(unp)
706	struct unpcb *unp;
707{
708	struct socket *so;
709
710	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
711	    (so = unp->unp_conn->unp_socket))
712		socantrcvmore(so);
713}
714
715static void
716unp_drop(unp, errno)
717	struct unpcb *unp;
718	int errno;
719{
720	struct socket *so = unp->unp_socket;
721
722	so->so_error = errno;
723	unp_disconnect(unp);
724	if (so->so_head) {
725		so->so_pcb = (caddr_t) 0;
726		if (unp->unp_addr)
727			FREE(unp->unp_addr, M_SONAME);
728		FREE(unp, M_PCB);
729		sofree(so);
730	}
731}
732
733#ifdef notdef
734void
735unp_drain()
736{
737
738}
739#endif
740
741int
742unp_externalize(rights)
743	struct mbuf *rights;
744{
745	struct proc *p = curproc;		/* XXX */
746	register int i;
747	register struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
748	register struct file **rp = (struct file **)(cm + 1);
749	register struct file *fp;
750	int newfds = (cm->cmsg_len - sizeof(*cm)) / sizeof (int);
751	int f;
752
753	/*
754	 * if the new FD's will not fit, then we free them all
755	 */
756	if (!fdavail(p, newfds)) {
757		for (i = 0; i < newfds; i++) {
758			fp = *rp;
759			unp_discard(fp);
760			*rp++ = 0;
761		}
762		return (EMSGSIZE);
763	}
764	/*
765	 * now change each pointer to an fd in the global table to
766	 * an integer that is the index to the local fd table entry
767	 * that we set up to point to the global one we are transferring.
768	 * XXX this assumes a pointer and int are the same size...!
769	 */
770	for (i = 0; i < newfds; i++) {
771		if (fdalloc(p, 0, &f))
772			panic("unp_externalize");
773		fp = *rp;
774		p->p_fd->fd_ofiles[f] = fp;
775		fp->f_msgcount--;
776		unp_rights--;
777		*(int *)rp++ = f;
778	}
779	return (0);
780}
781
782#ifndef MIN
783#define	MIN(a,b) (((a)<(b))?(a):(b))
784#endif
785
786static int
787unp_internalize(control, p)
788	struct mbuf *control;
789	struct proc *p;
790{
791	struct filedesc *fdp = p->p_fd;
792	register struct cmsghdr *cm = mtod(control, struct cmsghdr *);
793	register struct file **rp;
794	register struct file *fp;
795	register int i, fd;
796	register struct cmsgcred *cmcred;
797	int oldfds;
798
799	if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
800	    cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
801		return (EINVAL);
802
803	/*
804	 * Fill in credential information.
805	 */
806	if (cm->cmsg_type == SCM_CREDS) {
807		cmcred = (struct cmsgcred *)(cm + 1);
808		cmcred->cmcred_pid = p->p_pid;
809		cmcred->cmcred_uid = p->p_cred->p_ruid;
810		cmcred->cmcred_gid = p->p_cred->p_rgid;
811		cmcred->cmcred_euid = p->p_ucred->cr_uid;
812		cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
813							CMGROUP_MAX);
814		for (i = 0; i < cmcred->cmcred_ngroups; i++)
815			cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
816		return(0);
817	}
818
819	oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
820	/*
821	 * check that all the FDs passed in refer to legal OPEN files
822	 * If not, reject the entire operation.
823	 */
824	rp = (struct file **)(cm + 1);
825	for (i = 0; i < oldfds; i++) {
826		fd = *(int *)rp++;
827		if ((unsigned)fd >= fdp->fd_nfiles ||
828		    fdp->fd_ofiles[fd] == NULL)
829			return (EBADF);
830	}
831	/*
832	 * Now replace the integer FDs with pointers to
833	 * the associated global file table entry..
834	 * XXX this assumes a pointer and an int are the same size!
835	 */
836	rp = (struct file **)(cm + 1);
837	for (i = 0; i < oldfds; i++) {
838		fp = fdp->fd_ofiles[*(int *)rp];
839		*rp++ = fp;
840		fp->f_count++;
841		fp->f_msgcount++;
842		unp_rights++;
843	}
844	return (0);
845}
846
847static int	unp_defer, unp_gcing;
848
849static void
850unp_gc()
851{
852	register struct file *fp, *nextfp;
853	register struct socket *so;
854	struct file **extra_ref, **fpp;
855	int nunref, i;
856
857	if (unp_gcing)
858		return;
859	unp_gcing = 1;
860	unp_defer = 0;
861	/*
862	 * before going through all this, set all FDs to
863	 * be NOT defered and NOT externally accessible
864	 */
865	for (fp = filehead.lh_first; fp != 0; fp = fp->f_list.le_next)
866		fp->f_flag &= ~(FMARK|FDEFER);
867	do {
868		for (fp = filehead.lh_first; fp != 0; fp = fp->f_list.le_next) {
869			/*
870			 * If the file is not open, skip it
871			 */
872			if (fp->f_count == 0)
873				continue;
874			/*
875			 * If we already marked it as 'defer'  in a
876			 * previous pass, then try process it this time
877			 * and un-mark it
878			 */
879			if (fp->f_flag & FDEFER) {
880				fp->f_flag &= ~FDEFER;
881				unp_defer--;
882			} else {
883				/*
884				 * if it's not defered, then check if it's
885				 * already marked.. if so skip it
886				 */
887				if (fp->f_flag & FMARK)
888					continue;
889				/*
890				 * If all references are from messages
891				 * in transit, then skip it. it's not
892				 * externally accessible.
893				 */
894				if (fp->f_count == fp->f_msgcount)
895					continue;
896				/*
897				 * If it got this far then it must be
898				 * externally accessible.
899				 */
900				fp->f_flag |= FMARK;
901			}
902			/*
903			 * either it was defered, or it is externally
904			 * accessible and not already marked so.
905			 * Now check if it is possibly one of OUR sockets.
906			 */
907			if (fp->f_type != DTYPE_SOCKET ||
908			    (so = (struct socket *)fp->f_data) == 0)
909				continue;
910			if (so->so_proto->pr_domain != &localdomain ||
911			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
912				continue;
913#ifdef notdef
914			if (so->so_rcv.sb_flags & SB_LOCK) {
915				/*
916				 * This is problematical; it's not clear
917				 * we need to wait for the sockbuf to be
918				 * unlocked (on a uniprocessor, at least),
919				 * and it's also not clear what to do
920				 * if sbwait returns an error due to receipt
921				 * of a signal.  If sbwait does return
922				 * an error, we'll go into an infinite
923				 * loop.  Delete all of this for now.
924				 */
925				(void) sbwait(&so->so_rcv);
926				goto restart;
927			}
928#endif
929			/*
930			 * So, Ok, it's one of our sockets and it IS externally
931			 * accessible (or was defered). Now we look
932			 * to see if we hold any file descriptors in it's
933			 * message buffers. Follow those links and mark them
934			 * as accessible too.
935			 */
936			unp_scan(so->so_rcv.sb_mb, unp_mark);
937		}
938	} while (unp_defer);
939	/*
940	 * We grab an extra reference to each of the file table entries
941	 * that are not otherwise accessible and then free the rights
942	 * that are stored in messages on them.
943	 *
944	 * The bug in the orginal code is a little tricky, so I'll describe
945	 * what's wrong with it here.
946	 *
947	 * It is incorrect to simply unp_discard each entry for f_msgcount
948	 * times -- consider the case of sockets A and B that contain
949	 * references to each other.  On a last close of some other socket,
950	 * we trigger a gc since the number of outstanding rights (unp_rights)
951	 * is non-zero.  If during the sweep phase the gc code un_discards,
952	 * we end up doing a (full) closef on the descriptor.  A closef on A
953	 * results in the following chain.  Closef calls soo_close, which
954	 * calls soclose.   Soclose calls first (through the switch
955	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
956	 * returns because the previous instance had set unp_gcing, and
957	 * we return all the way back to soclose, which marks the socket
958	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
959	 * to free up the rights that are queued in messages on the socket A,
960	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
961	 * switch unp_dispose, which unp_scans with unp_discard.  This second
962	 * instance of unp_discard just calls closef on B.
963	 *
964	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
965	 * which results in another closef on A.  Unfortunately, A is already
966	 * being closed, and the descriptor has already been marked with
967	 * SS_NOFDREF, and soclose panics at this point.
968	 *
969	 * Here, we first take an extra reference to each inaccessible
970	 * descriptor.  Then, we call sorflush ourself, since we know
971	 * it is a Unix domain socket anyhow.  After we destroy all the
972	 * rights carried in messages, we do a last closef to get rid
973	 * of our extra reference.  This is the last close, and the
974	 * unp_detach etc will shut down the socket.
975	 *
976	 * 91/09/19, bsy@cs.cmu.edu
977	 */
978	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
979	for (nunref = 0, fp = filehead.lh_first, fpp = extra_ref; fp != 0;
980	    fp = nextfp) {
981		nextfp = fp->f_list.le_next;
982		/*
983		 * If it's not open, skip it
984		 */
985		if (fp->f_count == 0)
986			continue;
987		/*
988		 * If all refs are from msgs, and it's not marked accessible
989		 * then it must be referenced from some unreachable cycle
990		 * of (shut-down) FDs, so include it in our
991		 * list of FDs to remove
992		 */
993		if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
994			*fpp++ = fp;
995			nunref++;
996			fp->f_count++;
997		}
998	}
999	/*
1000	 * for each FD on our hit list, do the following two things
1001	 */
1002	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1003		sorflush((struct socket *)(*fpp)->f_data);
1004	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1005		closef(*fpp, (struct proc *) NULL);
1006	free((caddr_t)extra_ref, M_FILE);
1007	unp_gcing = 0;
1008}
1009
1010void
1011unp_dispose(m)
1012	struct mbuf *m;
1013{
1014
1015	if (m)
1016		unp_scan(m, unp_discard);
1017}
1018
1019static void
1020unp_scan(m0, op)
1021	register struct mbuf *m0;
1022	void (*op) __P((struct file *));
1023{
1024	register struct mbuf *m;
1025	register struct file **rp;
1026	register struct cmsghdr *cm;
1027	register int i;
1028	int qfds;
1029
1030	while (m0) {
1031		for (m = m0; m; m = m->m_next)
1032			if (m->m_type == MT_CONTROL &&
1033			    m->m_len >= sizeof(*cm)) {
1034				cm = mtod(m, struct cmsghdr *);
1035				if (cm->cmsg_level != SOL_SOCKET ||
1036				    cm->cmsg_type != SCM_RIGHTS)
1037					continue;
1038				qfds = (cm->cmsg_len - sizeof *cm)
1039						/ sizeof (struct file *);
1040				rp = (struct file **)(cm + 1);
1041				for (i = 0; i < qfds; i++)
1042					(*op)(*rp++);
1043				break;		/* XXX, but saves time */
1044			}
1045		m0 = m0->m_act;
1046	}
1047}
1048
1049static void
1050unp_mark(fp)
1051	struct file *fp;
1052{
1053
1054	if (fp->f_flag & FMARK)
1055		return;
1056	unp_defer++;
1057	fp->f_flag |= (FMARK|FDEFER);
1058}
1059
1060static void
1061unp_discard(fp)
1062	struct file *fp;
1063{
1064
1065	fp->f_msgcount--;
1066	unp_rights--;
1067	(void) closef(fp, (struct proc *)NULL);
1068}
1069