uipc_usrreq.c revision 130820
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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/kern/uipc_usrreq.c 130820 2004-06-20 21:43:13Z rwatson $");
34
35#include "opt_mac.h"
36
37#include <sys/param.h>
38#include <sys/domain.h>
39#include <sys/fcntl.h>
40#include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
41#include <sys/file.h>
42#include <sys/filedesc.h>
43#include <sys/jail.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/mac.h>
47#include <sys/mbuf.h>
48#include <sys/mutex.h>
49#include <sys/namei.h>
50#include <sys/proc.h>
51#include <sys/protosw.h>
52#include <sys/resourcevar.h>
53#include <sys/socket.h>
54#include <sys/socketvar.h>
55#include <sys/signalvar.h>
56#include <sys/stat.h>
57#include <sys/sx.h>
58#include <sys/sysctl.h>
59#include <sys/systm.h>
60#include <sys/un.h>
61#include <sys/unpcb.h>
62#include <sys/vnode.h>
63
64#include <vm/uma.h>
65
66static uma_zone_t unp_zone;
67static	unp_gen_t unp_gencnt;
68static	u_int unp_count;
69
70static	struct unp_head unp_shead, unp_dhead;
71
72/*
73 * Unix communications domain.
74 *
75 * TODO:
76 *	SEQPACKET, RDM
77 *	rethink name space problems
78 *	need a proper out-of-band
79 *	lock pushdown
80 */
81static const struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
82static ino_t	unp_ino;		/* prototype for fake inode numbers */
83
84static struct mtx unp_mtx;
85#define	UNP_LOCK_INIT() \
86	mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
87#define	UNP_LOCK()		mtx_lock(&unp_mtx)
88#define	UNP_UNLOCK()		mtx_unlock(&unp_mtx)
89#define	UNP_LOCK_ASSERT()	mtx_assert(&unp_mtx, MA_OWNED)
90
91static int     unp_attach(struct socket *);
92static void    unp_detach(struct unpcb *);
93static int     unp_bind(struct unpcb *,struct sockaddr *, struct thread *);
94static int     unp_connect(struct socket *,struct sockaddr *, struct thread *);
95static int     unp_connect2(struct socket *so, struct socket *so2);
96static void    unp_disconnect(struct unpcb *);
97static void    unp_shutdown(struct unpcb *);
98static void    unp_drop(struct unpcb *, int);
99static void    unp_gc(void);
100static void    unp_scan(struct mbuf *, void (*)(struct file *));
101static void    unp_mark(struct file *);
102static void    unp_discard(struct file *);
103static void    unp_freerights(struct file **, int);
104static int     unp_internalize(struct mbuf **, struct thread *);
105static int     unp_listen(struct unpcb *, struct thread *);
106
107static int
108uipc_abort(struct socket *so)
109{
110	struct unpcb *unp = sotounpcb(so);
111
112	if (unp == NULL)
113		return (EINVAL);
114	UNP_LOCK();
115	unp_drop(unp, ECONNABORTED);
116	unp_detach(unp);	/* NB: unlocks */
117	SOCK_LOCK(so);
118	sotryfree(so);
119	return (0);
120}
121
122static int
123uipc_accept(struct socket *so, struct sockaddr **nam)
124{
125	struct unpcb *unp = sotounpcb(so);
126	const struct sockaddr *sa;
127
128	if (unp == NULL)
129		return (EINVAL);
130
131	/*
132	 * Pass back name of connected socket,
133	 * if it was bound and we are still connected
134	 * (our peer may have closed already!).
135	 */
136	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
137	UNP_LOCK();
138	if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
139		sa = (struct sockaddr *) unp->unp_conn->unp_addr;
140	else
141		sa = &sun_noname;
142	bcopy(sa, *nam, sa->sa_len);
143	UNP_UNLOCK();
144	return (0);
145}
146
147static int
148uipc_attach(struct socket *so, int proto, struct thread *td)
149{
150	struct unpcb *unp = sotounpcb(so);
151
152	if (unp != NULL)
153		return (EISCONN);
154	return (unp_attach(so));
155}
156
157static int
158uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
159{
160	struct unpcb *unp = sotounpcb(so);
161
162	if (unp == NULL)
163		return (EINVAL);
164
165	return (unp_bind(unp, nam, td));
166}
167
168static int
169uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
170{
171	struct unpcb *unp = sotounpcb(so);
172	int error;
173
174	if (unp == NULL)
175		return (EINVAL);
176	UNP_LOCK();
177	error = unp_connect(so, nam, curthread);
178	UNP_UNLOCK();
179	return (error);
180}
181
182int
183uipc_connect2(struct socket *so1, struct socket *so2)
184{
185	struct unpcb *unp = sotounpcb(so1);
186	int error;
187
188	if (unp == NULL)
189		return (EINVAL);
190
191	UNP_LOCK();
192	error = unp_connect2(so1, so2);
193	UNP_UNLOCK();
194	return (error);
195}
196
197/* control is EOPNOTSUPP */
198
199static int
200uipc_detach(struct socket *so)
201{
202	struct unpcb *unp = sotounpcb(so);
203
204	if (unp == NULL)
205		return (EINVAL);
206
207	UNP_LOCK();
208	unp_detach(unp);	/* NB: unlocks unp */
209	return (0);
210}
211
212static int
213uipc_disconnect(struct socket *so)
214{
215	struct unpcb *unp = sotounpcb(so);
216
217	if (unp == NULL)
218		return (EINVAL);
219	UNP_LOCK();
220	unp_disconnect(unp);
221	UNP_UNLOCK();
222	return (0);
223}
224
225static int
226uipc_listen(struct socket *so, struct thread *td)
227{
228	struct unpcb *unp = sotounpcb(so);
229	int error;
230
231	if (unp == NULL || unp->unp_vnode == NULL)
232		return (EINVAL);
233	UNP_LOCK();
234	error = unp_listen(unp, td);
235	UNP_UNLOCK();
236	return (error);
237}
238
239static int
240uipc_peeraddr(struct socket *so, struct sockaddr **nam)
241{
242	struct unpcb *unp = sotounpcb(so);
243	const struct sockaddr *sa;
244
245	if (unp == NULL)
246		return (EINVAL);
247	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
248	UNP_LOCK();
249	if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
250		sa = (struct sockaddr *) unp->unp_conn->unp_addr;
251	else {
252		/*
253		 * XXX: It seems that this test always fails even when
254		 * connection is established.  So, this else clause is
255		 * added as workaround to return PF_LOCAL sockaddr.
256		 */
257		sa = &sun_noname;
258	}
259	bcopy(sa, *nam, sa->sa_len);
260	UNP_UNLOCK();
261	return (0);
262}
263
264static int
265uipc_rcvd(struct socket *so, int flags)
266{
267	struct unpcb *unp = sotounpcb(so);
268	struct socket *so2;
269	u_long newhiwat;
270
271	if (unp == NULL)
272		return (EINVAL);
273	UNP_LOCK();
274	switch (so->so_type) {
275	case SOCK_DGRAM:
276		panic("uipc_rcvd DGRAM?");
277		/*NOTREACHED*/
278
279	case SOCK_STREAM:
280		if (unp->unp_conn == NULL)
281			break;
282		so2 = unp->unp_conn->unp_socket;
283		SOCKBUF_LOCK(&so2->so_snd);
284		SOCKBUF_LOCK(&so->so_rcv);
285		/*
286		 * Adjust backpressure on sender
287		 * and wakeup any waiting to write.
288		 */
289		so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
290		unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
291		newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
292		    so->so_rcv.sb_cc;
293		(void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
294		    newhiwat, RLIM_INFINITY);
295		unp->unp_cc = so->so_rcv.sb_cc;
296		SOCKBUF_UNLOCK(&so->so_rcv);
297		SOCKBUF_UNLOCK(&so2->so_snd);
298		sowwakeup(so2);
299		break;
300
301	default:
302		panic("uipc_rcvd unknown socktype");
303	}
304	UNP_UNLOCK();
305	return (0);
306}
307
308/* pru_rcvoob is EOPNOTSUPP */
309
310static int
311uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
312	  struct mbuf *control, struct thread *td)
313{
314	int error = 0;
315	struct unpcb *unp = sotounpcb(so);
316	struct socket *so2;
317	u_long newhiwat;
318
319	if (unp == NULL) {
320		error = EINVAL;
321		goto release;
322	}
323	if (flags & PRUS_OOB) {
324		error = EOPNOTSUPP;
325		goto release;
326	}
327
328	if (control != NULL && (error = unp_internalize(&control, td)))
329		goto release;
330
331	UNP_LOCK();
332	switch (so->so_type) {
333	case SOCK_DGRAM:
334	{
335		const struct sockaddr *from;
336
337		if (nam != NULL) {
338			if (unp->unp_conn != NULL) {
339				error = EISCONN;
340				break;
341			}
342			error = unp_connect(so, nam, td);
343			if (error)
344				break;
345		} else {
346			if (unp->unp_conn == NULL) {
347				error = ENOTCONN;
348				break;
349			}
350		}
351		so2 = unp->unp_conn->unp_socket;
352		if (unp->unp_addr != NULL)
353			from = (struct sockaddr *)unp->unp_addr;
354		else
355			from = &sun_noname;
356		if (sbappendaddr(&so2->so_rcv, from, m, control)) {
357			sorwakeup(so2);
358			m = NULL;
359			control = NULL;
360		} else {
361			error = ENOBUFS;
362		}
363		if (nam != NULL)
364			unp_disconnect(unp);
365		break;
366	}
367
368	case SOCK_STREAM:
369		/* Connect if not connected yet. */
370		/*
371		 * Note: A better implementation would complain
372		 * if not equal to the peer's address.
373		 */
374		if ((so->so_state & SS_ISCONNECTED) == 0) {
375			if (nam != NULL) {
376				error = unp_connect(so, nam, td);
377				if (error)
378					break;	/* XXX */
379			} else {
380				error = ENOTCONN;
381				break;
382			}
383		}
384
385		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
386			error = EPIPE;
387			break;
388		}
389		if (unp->unp_conn == NULL)
390			panic("uipc_send connected but no connection?");
391		so2 = unp->unp_conn->unp_socket;
392		/*
393		 * Send to paired receive port, and then reduce
394		 * send buffer hiwater marks to maintain backpressure.
395		 * Wake up readers.
396		 */
397		if (control != NULL) {
398			if (sbappendcontrol(&so2->so_rcv, m, control))
399				control = NULL;
400		} else {
401			sbappend(&so2->so_rcv, m);
402		}
403		so->so_snd.sb_mbmax -=
404			so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
405		unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
406		newhiwat = so->so_snd.sb_hiwat -
407		    (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
408		(void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
409		    newhiwat, RLIM_INFINITY);
410		unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
411		sorwakeup(so2);
412		m = NULL;
413		break;
414
415	default:
416		panic("uipc_send unknown socktype");
417	}
418
419	/*
420	 * SEND_EOF is equivalent to a SEND followed by
421	 * a SHUTDOWN.
422	 */
423	if (flags & PRUS_EOF) {
424		socantsendmore(so);
425		unp_shutdown(unp);
426	}
427	UNP_UNLOCK();
428
429	if (control != NULL && error != 0)
430		unp_dispose(control);
431
432release:
433	if (control != NULL)
434		m_freem(control);
435	if (m != NULL)
436		m_freem(m);
437	return (error);
438}
439
440static int
441uipc_sense(struct socket *so, struct stat *sb)
442{
443	struct unpcb *unp = sotounpcb(so);
444	struct socket *so2;
445
446	if (unp == NULL)
447		return (EINVAL);
448	UNP_LOCK();
449	sb->st_blksize = so->so_snd.sb_hiwat;
450	if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
451		so2 = unp->unp_conn->unp_socket;
452		sb->st_blksize += so2->so_rcv.sb_cc;
453	}
454	sb->st_dev = NODEV;
455	if (unp->unp_ino == 0)
456		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
457	sb->st_ino = unp->unp_ino;
458	UNP_UNLOCK();
459	return (0);
460}
461
462static int
463uipc_shutdown(struct socket *so)
464{
465	struct unpcb *unp = sotounpcb(so);
466
467	if (unp == NULL)
468		return (EINVAL);
469	UNP_LOCK();
470	socantsendmore(so);
471	unp_shutdown(unp);
472	UNP_UNLOCK();
473	return (0);
474}
475
476static int
477uipc_sockaddr(struct socket *so, struct sockaddr **nam)
478{
479	struct unpcb *unp = sotounpcb(so);
480	const struct sockaddr *sa;
481
482	if (unp == NULL)
483		return (EINVAL);
484	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
485	UNP_LOCK();
486	if (unp->unp_addr != NULL)
487		sa = (struct sockaddr *) unp->unp_addr;
488	else
489		sa = &sun_noname;
490	bcopy(sa, *nam, sa->sa_len);
491	UNP_UNLOCK();
492	return (0);
493}
494
495struct pr_usrreqs uipc_usrreqs = {
496	uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
497	uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
498	uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
499	uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
500	sosend, soreceive, sopoll, pru_sosetlabel_null
501};
502
503int
504uipc_ctloutput(so, sopt)
505	struct socket *so;
506	struct sockopt *sopt;
507{
508	struct unpcb *unp = sotounpcb(so);
509	struct xucred xu;
510	int error;
511
512	switch (sopt->sopt_dir) {
513	case SOPT_GET:
514		switch (sopt->sopt_name) {
515		case LOCAL_PEERCRED:
516			error = 0;
517			UNP_LOCK();
518			if (unp->unp_flags & UNP_HAVEPC)
519				xu = unp->unp_peercred;
520			else {
521				if (so->so_type == SOCK_STREAM)
522					error = ENOTCONN;
523				else
524					error = EINVAL;
525			}
526			UNP_UNLOCK();
527			if (error == 0)
528				error = sooptcopyout(sopt, &xu, sizeof(xu));
529			break;
530		default:
531			error = EOPNOTSUPP;
532			break;
533		}
534		break;
535	case SOPT_SET:
536	default:
537		error = EOPNOTSUPP;
538		break;
539	}
540	return (error);
541}
542
543/*
544 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
545 * for stream sockets, although the total for sender and receiver is
546 * actually only PIPSIZ.
547 * Datagram sockets really use the sendspace as the maximum datagram size,
548 * and don't really want to reserve the sendspace.  Their recvspace should
549 * be large enough for at least one max-size datagram plus address.
550 */
551#ifndef PIPSIZ
552#define	PIPSIZ	8192
553#endif
554static u_long	unpst_sendspace = PIPSIZ;
555static u_long	unpst_recvspace = PIPSIZ;
556static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
557static u_long	unpdg_recvspace = 4*1024;
558
559static int	unp_rights;			/* file descriptors in flight */
560
561SYSCTL_DECL(_net_local_stream);
562SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
563	   &unpst_sendspace, 0, "");
564SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
565	   &unpst_recvspace, 0, "");
566SYSCTL_DECL(_net_local_dgram);
567SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
568	   &unpdg_sendspace, 0, "");
569SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
570	   &unpdg_recvspace, 0, "");
571SYSCTL_DECL(_net_local);
572SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
573
574static int
575unp_attach(so)
576	struct socket *so;
577{
578	register struct unpcb *unp;
579	int error;
580
581	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
582		switch (so->so_type) {
583
584		case SOCK_STREAM:
585			error = soreserve(so, unpst_sendspace, unpst_recvspace);
586			break;
587
588		case SOCK_DGRAM:
589			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
590			break;
591
592		default:
593			panic("unp_attach");
594		}
595		if (error)
596			return (error);
597	}
598	unp = uma_zalloc(unp_zone, M_WAITOK);
599	if (unp == NULL)
600		return (ENOBUFS);
601	bzero(unp, sizeof *unp);
602	LIST_INIT(&unp->unp_refs);
603	unp->unp_socket = so;
604
605	UNP_LOCK();
606	unp->unp_gencnt = ++unp_gencnt;
607	unp_count++;
608	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
609			 : &unp_shead, unp, unp_link);
610	UNP_UNLOCK();
611
612	so->so_pcb = unp;
613	return (0);
614}
615
616static void
617unp_detach(unp)
618	register struct unpcb *unp;
619{
620	struct vnode *vp;
621
622	UNP_LOCK_ASSERT();
623
624	LIST_REMOVE(unp, unp_link);
625	unp->unp_gencnt = ++unp_gencnt;
626	--unp_count;
627	if ((vp = unp->unp_vnode) != NULL) {
628		/*
629		 * XXXRW: should v_socket be frobbed only while holding
630		 * Giant?
631		 */
632		unp->unp_vnode->v_socket = NULL;
633		unp->unp_vnode = NULL;
634	}
635	if (unp->unp_conn != NULL)
636		unp_disconnect(unp);
637	while (!LIST_EMPTY(&unp->unp_refs)) {
638		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
639		unp_drop(ref, ECONNRESET);
640	}
641	soisdisconnected(unp->unp_socket);
642	unp->unp_socket->so_pcb = NULL;
643	if (unp_rights) {
644		/*
645		 * Normally the receive buffer is flushed later,
646		 * in sofree, but if our receive buffer holds references
647		 * to descriptors that are now garbage, we will dispose
648		 * of those descriptor references after the garbage collector
649		 * gets them (resulting in a "panic: closef: count < 0").
650		 */
651		sorflush(unp->unp_socket);
652		unp_gc();
653	}
654	if (unp->unp_addr != NULL)
655		FREE(unp->unp_addr, M_SONAME);
656	UNP_UNLOCK();
657	uma_zfree(unp_zone, unp);
658	if (vp) {
659		mtx_lock(&Giant);
660		vrele(vp);
661		mtx_unlock(&Giant);
662	}
663}
664
665static int
666unp_bind(unp, nam, td)
667	struct unpcb *unp;
668	struct sockaddr *nam;
669	struct thread *td;
670{
671	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
672	struct vnode *vp;
673	struct mount *mp;
674	struct vattr vattr;
675	int error, namelen;
676	struct nameidata nd;
677	char *buf;
678
679	/*
680	 * XXXRW: This test-and-set of unp_vnode is non-atomic; the
681	 * unlocked read here is fine, but the value of unp_vnode needs
682	 * to be tested again after we do all the lookups to see if the
683	 * pcb is still unbound?
684	 */
685	if (unp->unp_vnode != NULL)
686		return (EINVAL);
687
688	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
689	if (namelen <= 0)
690		return (EINVAL);
691
692	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
693	strlcpy(buf, soun->sun_path, namelen + 1);
694
695	mtx_lock(&Giant);
696restart:
697	mtx_assert(&Giant, MA_OWNED);
698	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
699	    buf, td);
700/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
701	error = namei(&nd);
702	if (error)
703		goto done;
704	vp = nd.ni_vp;
705	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
706		NDFREE(&nd, NDF_ONLY_PNBUF);
707		if (nd.ni_dvp == vp)
708			vrele(nd.ni_dvp);
709		else
710			vput(nd.ni_dvp);
711		if (vp != NULL) {
712			vrele(vp);
713			error = EADDRINUSE;
714			goto done;
715		}
716		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
717		if (error)
718			goto done;
719		goto restart;
720	}
721	VATTR_NULL(&vattr);
722	vattr.va_type = VSOCK;
723	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
724#ifdef MAC
725	error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
726	    &vattr);
727#endif
728	if (error == 0) {
729		VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
730		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
731	}
732	NDFREE(&nd, NDF_ONLY_PNBUF);
733	vput(nd.ni_dvp);
734	if (error)
735		goto done;
736	vp = nd.ni_vp;
737	ASSERT_VOP_LOCKED(vp, "unp_bind");
738	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
739	UNP_LOCK();
740	vp->v_socket = unp->unp_socket;
741	unp->unp_vnode = vp;
742	unp->unp_addr = soun;
743	UNP_UNLOCK();
744	VOP_UNLOCK(vp, 0, td);
745	vn_finished_write(mp);
746done:
747	mtx_unlock(&Giant);
748	free(buf, M_TEMP);
749	return (error);
750}
751
752static int
753unp_connect(so, nam, td)
754	struct socket *so;
755	struct sockaddr *nam;
756	struct thread *td;
757{
758	register struct sockaddr_un *soun = (struct sockaddr_un *)nam;
759	register struct vnode *vp;
760	register struct socket *so2, *so3;
761	struct unpcb *unp = sotounpcb(so);
762	struct unpcb *unp2, *unp3;
763	int error, len;
764	struct nameidata nd;
765	char buf[SOCK_MAXADDRLEN];
766	struct sockaddr *sa;
767
768	UNP_LOCK_ASSERT();
769
770	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
771	if (len <= 0)
772		return (EINVAL);
773	strlcpy(buf, soun->sun_path, len + 1);
774	UNP_UNLOCK();
775	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
776	mtx_lock(&Giant);
777	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
778	error = namei(&nd);
779	if (error)
780		vp = NULL;
781	else
782		vp = nd.ni_vp;
783	ASSERT_VOP_LOCKED(vp, "unp_connect");
784	NDFREE(&nd, NDF_ONLY_PNBUF);
785	if (error)
786		goto bad;
787
788	if (vp->v_type != VSOCK) {
789		error = ENOTSOCK;
790		goto bad;
791	}
792	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
793	if (error)
794		goto bad;
795	so2 = vp->v_socket;
796	if (so2 == NULL) {
797		error = ECONNREFUSED;
798		goto bad;
799	}
800	if (so->so_type != so2->so_type) {
801		error = EPROTOTYPE;
802		goto bad;
803	}
804	mtx_unlock(&Giant);
805	UNP_LOCK();
806	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
807		if (so2->so_options & SO_ACCEPTCONN) {
808			/*
809			 * NB: drop locks here so unp_attach is entered
810			 *     w/o locks; this avoids a recursive lock
811			 *     of the head and holding sleep locks across
812			 *     a (potentially) blocking malloc.
813			 */
814			UNP_UNLOCK();
815			so3 = sonewconn(so2, 0);
816			UNP_LOCK();
817		} else
818			so3 = NULL;
819		if (so3 == NULL) {
820			error = ECONNREFUSED;
821			goto bad2;
822		}
823		unp = sotounpcb(so);
824		unp2 = sotounpcb(so2);
825		unp3 = sotounpcb(so3);
826		if (unp2->unp_addr != NULL) {
827			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
828			unp3->unp_addr = (struct sockaddr_un *) sa;
829			sa = NULL;
830		}
831		/*
832		 * unp_peercred management:
833		 *
834		 * The connecter's (client's) credentials are copied
835		 * from its process structure at the time of connect()
836		 * (which is now).
837		 */
838		cru2x(td->td_ucred, &unp3->unp_peercred);
839		unp3->unp_flags |= UNP_HAVEPC;
840		/*
841		 * The receiver's (server's) credentials are copied
842		 * from the unp_peercred member of socket on which the
843		 * former called listen(); unp_listen() cached that
844		 * process's credentials at that time so we can use
845		 * them now.
846		 */
847		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
848		    ("unp_connect: listener without cached peercred"));
849		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
850		    sizeof(unp->unp_peercred));
851		unp->unp_flags |= UNP_HAVEPC;
852#ifdef MAC
853		SOCK_LOCK(so);
854		mac_set_socket_peer_from_socket(so, so3);
855		mac_set_socket_peer_from_socket(so3, so);
856		SOCK_UNLOCK(so);
857#endif
858
859		so2 = so3;
860	}
861	error = unp_connect2(so, so2);
862bad2:
863	UNP_UNLOCK();
864	mtx_lock(&Giant);
865bad:
866	mtx_assert(&Giant, MA_OWNED);
867	if (vp != NULL)
868		vput(vp);
869	mtx_unlock(&Giant);
870	free(sa, M_SONAME);
871	UNP_LOCK();
872	return (error);
873}
874
875static int
876unp_connect2(so, so2)
877	register struct socket *so;
878	register struct socket *so2;
879{
880	register struct unpcb *unp = sotounpcb(so);
881	register struct unpcb *unp2;
882
883	UNP_LOCK_ASSERT();
884
885	if (so2->so_type != so->so_type)
886		return (EPROTOTYPE);
887	unp2 = sotounpcb(so2);
888	unp->unp_conn = unp2;
889	switch (so->so_type) {
890
891	case SOCK_DGRAM:
892		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
893		soisconnected(so);
894		break;
895
896	case SOCK_STREAM:
897		unp2->unp_conn = unp;
898		soisconnected(so);
899		soisconnected(so2);
900		break;
901
902	default:
903		panic("unp_connect2");
904	}
905	return (0);
906}
907
908static void
909unp_disconnect(unp)
910	struct unpcb *unp;
911{
912	register struct unpcb *unp2 = unp->unp_conn;
913	struct socket *so;
914
915	UNP_LOCK_ASSERT();
916
917	if (unp2 == NULL)
918		return;
919	unp->unp_conn = NULL;
920	switch (unp->unp_socket->so_type) {
921
922	case SOCK_DGRAM:
923		LIST_REMOVE(unp, unp_reflink);
924		so = unp->unp_socket;
925		SOCK_LOCK(so);
926		so->so_state &= ~SS_ISCONNECTED;
927		SOCK_UNLOCK(so);
928		break;
929
930	case SOCK_STREAM:
931		soisdisconnected(unp->unp_socket);
932		unp2->unp_conn = NULL;
933		soisdisconnected(unp2->unp_socket);
934		break;
935	}
936}
937
938#ifdef notdef
939void
940unp_abort(unp)
941	struct unpcb *unp;
942{
943
944	unp_detach(unp);
945}
946#endif
947
948/*
949 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed
950 * by the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers
951 * are safe to reference.  It first scans the list of struct unpcb's to
952 * generate a pointer list, then it rescans its list one entry at a time to
953 * externalize and copyout.  It checks the generation number to see if a
954 * struct unpcb has been reused, and will skip it if so.
955 */
956static int
957unp_pcblist(SYSCTL_HANDLER_ARGS)
958{
959	int error, i, n;
960	struct unpcb *unp, **unp_list;
961	unp_gen_t gencnt;
962	struct xunpgen *xug;
963	struct unp_head *head;
964	struct xunpcb *xu;
965
966	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
967
968	/*
969	 * The process of preparing the PCB list is too time-consuming and
970	 * resource-intensive to repeat twice on every request.
971	 */
972	if (req->oldptr == NULL) {
973		n = unp_count;
974		req->oldidx = 2 * (sizeof *xug)
975			+ (n + n/8) * sizeof(struct xunpcb);
976		return (0);
977	}
978
979	if (req->newptr != NULL)
980		return (EPERM);
981
982	/*
983	 * OK, now we're committed to doing something.
984	 */
985	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
986	UNP_LOCK();
987	gencnt = unp_gencnt;
988	n = unp_count;
989	UNP_UNLOCK();
990
991	xug->xug_len = sizeof *xug;
992	xug->xug_count = n;
993	xug->xug_gen = gencnt;
994	xug->xug_sogen = so_gencnt;
995	error = SYSCTL_OUT(req, xug, sizeof *xug);
996	if (error) {
997		free(xug, M_TEMP);
998		return (error);
999	}
1000
1001	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1002
1003	UNP_LOCK();
1004	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1005	     unp = LIST_NEXT(unp, unp_link)) {
1006		if (unp->unp_gencnt <= gencnt) {
1007			if (cr_cansee(req->td->td_ucred,
1008			    unp->unp_socket->so_cred))
1009				continue;
1010			unp_list[i++] = unp;
1011		}
1012	}
1013	UNP_UNLOCK();
1014	n = i;			/* in case we lost some during malloc */
1015
1016	error = 0;
1017	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK);
1018	for (i = 0; i < n; i++) {
1019		unp = unp_list[i];
1020		if (unp->unp_gencnt <= gencnt) {
1021			xu->xu_len = sizeof *xu;
1022			xu->xu_unpp = unp;
1023			/*
1024			 * XXX - need more locking here to protect against
1025			 * connect/disconnect races for SMP.
1026			 */
1027			if (unp->unp_addr != NULL)
1028				bcopy(unp->unp_addr, &xu->xu_addr,
1029				      unp->unp_addr->sun_len);
1030			if (unp->unp_conn != NULL &&
1031			    unp->unp_conn->unp_addr != NULL)
1032				bcopy(unp->unp_conn->unp_addr,
1033				      &xu->xu_caddr,
1034				      unp->unp_conn->unp_addr->sun_len);
1035			bcopy(unp, &xu->xu_unp, sizeof *unp);
1036			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1037			error = SYSCTL_OUT(req, xu, sizeof *xu);
1038		}
1039	}
1040	free(xu, M_TEMP);
1041	if (!error) {
1042		/*
1043		 * Give the user an updated idea of our state.
1044		 * If the generation differs from what we told
1045		 * her before, she knows that something happened
1046		 * while we were processing this request, and it
1047		 * might be necessary to retry.
1048		 */
1049		xug->xug_gen = unp_gencnt;
1050		xug->xug_sogen = so_gencnt;
1051		xug->xug_count = unp_count;
1052		error = SYSCTL_OUT(req, xug, sizeof *xug);
1053	}
1054	free(unp_list, M_TEMP);
1055	free(xug, M_TEMP);
1056	return (error);
1057}
1058
1059SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1060	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1061	    "List of active local datagram sockets");
1062SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1063	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1064	    "List of active local stream sockets");
1065
1066static void
1067unp_shutdown(unp)
1068	struct unpcb *unp;
1069{
1070	struct socket *so;
1071
1072	UNP_LOCK_ASSERT();
1073
1074	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1075	    (so = unp->unp_conn->unp_socket))
1076		socantrcvmore(so);
1077}
1078
1079static void
1080unp_drop(unp, errno)
1081	struct unpcb *unp;
1082	int errno;
1083{
1084	struct socket *so = unp->unp_socket;
1085
1086	UNP_LOCK_ASSERT();
1087
1088	so->so_error = errno;
1089	unp_disconnect(unp);
1090}
1091
1092#ifdef notdef
1093void
1094unp_drain()
1095{
1096
1097}
1098#endif
1099
1100static void
1101unp_freerights(rp, fdcount)
1102	struct file **rp;
1103	int fdcount;
1104{
1105	int i;
1106	struct file *fp;
1107
1108	for (i = 0; i < fdcount; i++) {
1109		fp = *rp;
1110		/*
1111		 * zero the pointer before calling
1112		 * unp_discard since it may end up
1113		 * in unp_gc()..
1114		 */
1115		*rp++ = 0;
1116		unp_discard(fp);
1117	}
1118}
1119
1120int
1121unp_externalize(control, controlp)
1122	struct mbuf *control, **controlp;
1123{
1124	struct thread *td = curthread;		/* XXX */
1125	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1126	int i;
1127	int *fdp;
1128	struct file **rp;
1129	struct file *fp;
1130	void *data;
1131	socklen_t clen = control->m_len, datalen;
1132	int error, newfds;
1133	int f;
1134	u_int newlen;
1135
1136	error = 0;
1137	if (controlp != NULL) /* controlp == NULL => free control messages */
1138		*controlp = NULL;
1139
1140	while (cm != NULL) {
1141		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1142			error = EINVAL;
1143			break;
1144		}
1145
1146		data = CMSG_DATA(cm);
1147		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1148
1149		if (cm->cmsg_level == SOL_SOCKET
1150		    && cm->cmsg_type == SCM_RIGHTS) {
1151			newfds = datalen / sizeof(struct file *);
1152			rp = data;
1153
1154			/* If we're not outputting the descriptors free them. */
1155			if (error || controlp == NULL) {
1156				unp_freerights(rp, newfds);
1157				goto next;
1158			}
1159			FILEDESC_LOCK(td->td_proc->p_fd);
1160			/* if the new FD's will not fit free them.  */
1161			if (!fdavail(td, newfds)) {
1162				FILEDESC_UNLOCK(td->td_proc->p_fd);
1163				error = EMSGSIZE;
1164				unp_freerights(rp, newfds);
1165				goto next;
1166			}
1167			/*
1168			 * now change each pointer to an fd in the global
1169			 * table to an integer that is the index to the
1170			 * local fd table entry that we set up to point
1171			 * to the global one we are transferring.
1172			 */
1173			newlen = newfds * sizeof(int);
1174			*controlp = sbcreatecontrol(NULL, newlen,
1175			    SCM_RIGHTS, SOL_SOCKET);
1176			if (*controlp == NULL) {
1177				FILEDESC_UNLOCK(td->td_proc->p_fd);
1178				error = E2BIG;
1179				unp_freerights(rp, newfds);
1180				goto next;
1181			}
1182
1183			fdp = (int *)
1184			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1185			for (i = 0; i < newfds; i++) {
1186				if (fdalloc(td, 0, &f))
1187					panic("unp_externalize fdalloc failed");
1188				fp = *rp++;
1189				td->td_proc->p_fd->fd_ofiles[f] = fp;
1190				FILE_LOCK(fp);
1191				fp->f_msgcount--;
1192				FILE_UNLOCK(fp);
1193				unp_rights--;
1194				*fdp++ = f;
1195			}
1196			FILEDESC_UNLOCK(td->td_proc->p_fd);
1197		} else { /* We can just copy anything else across */
1198			if (error || controlp == NULL)
1199				goto next;
1200			*controlp = sbcreatecontrol(NULL, datalen,
1201			    cm->cmsg_type, cm->cmsg_level);
1202			if (*controlp == NULL) {
1203				error = ENOBUFS;
1204				goto next;
1205			}
1206			bcopy(data,
1207			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1208			    datalen);
1209		}
1210
1211		controlp = &(*controlp)->m_next;
1212
1213next:
1214		if (CMSG_SPACE(datalen) < clen) {
1215			clen -= CMSG_SPACE(datalen);
1216			cm = (struct cmsghdr *)
1217			    ((caddr_t)cm + CMSG_SPACE(datalen));
1218		} else {
1219			clen = 0;
1220			cm = NULL;
1221		}
1222	}
1223
1224	m_freem(control);
1225
1226	return (error);
1227}
1228
1229void
1230unp_init(void)
1231{
1232	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1233	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1234	if (unp_zone == NULL)
1235		panic("unp_init");
1236	uma_zone_set_max(unp_zone, nmbclusters);
1237	LIST_INIT(&unp_dhead);
1238	LIST_INIT(&unp_shead);
1239
1240	UNP_LOCK_INIT();
1241}
1242
1243static int
1244unp_internalize(controlp, td)
1245	struct mbuf **controlp;
1246	struct thread *td;
1247{
1248	struct mbuf *control = *controlp;
1249	struct proc *p = td->td_proc;
1250	struct filedesc *fdescp = p->p_fd;
1251	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1252	struct cmsgcred *cmcred;
1253	struct file **rp;
1254	struct file *fp;
1255	struct timeval *tv;
1256	int i, fd, *fdp;
1257	void *data;
1258	socklen_t clen = control->m_len, datalen;
1259	int error, oldfds;
1260	u_int newlen;
1261
1262	error = 0;
1263	*controlp = NULL;
1264
1265	while (cm != NULL) {
1266		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1267		    || cm->cmsg_len > clen) {
1268			error = EINVAL;
1269			goto out;
1270		}
1271
1272		data = CMSG_DATA(cm);
1273		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1274
1275		switch (cm->cmsg_type) {
1276		/*
1277		 * Fill in credential information.
1278		 */
1279		case SCM_CREDS:
1280			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1281			    SCM_CREDS, SOL_SOCKET);
1282			if (*controlp == NULL) {
1283				error = ENOBUFS;
1284				goto out;
1285			}
1286
1287			cmcred = (struct cmsgcred *)
1288			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1289			cmcred->cmcred_pid = p->p_pid;
1290			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1291			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1292			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1293			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1294							CMGROUP_MAX);
1295			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1296				cmcred->cmcred_groups[i] =
1297				    td->td_ucred->cr_groups[i];
1298			break;
1299
1300		case SCM_RIGHTS:
1301			oldfds = datalen / sizeof (int);
1302			/*
1303			 * check that all the FDs passed in refer to legal files
1304			 * If not, reject the entire operation.
1305			 */
1306			fdp = data;
1307			FILEDESC_LOCK(fdescp);
1308			for (i = 0; i < oldfds; i++) {
1309				fd = *fdp++;
1310				if ((unsigned)fd >= fdescp->fd_nfiles ||
1311				    fdescp->fd_ofiles[fd] == NULL) {
1312					FILEDESC_UNLOCK(fdescp);
1313					error = EBADF;
1314					goto out;
1315				}
1316				fp = fdescp->fd_ofiles[fd];
1317				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1318					FILEDESC_UNLOCK(fdescp);
1319					error = EOPNOTSUPP;
1320					goto out;
1321				}
1322
1323			}
1324			/*
1325			 * Now replace the integer FDs with pointers to
1326			 * the associated global file table entry..
1327			 */
1328			newlen = oldfds * sizeof(struct file *);
1329			*controlp = sbcreatecontrol(NULL, newlen,
1330			    SCM_RIGHTS, SOL_SOCKET);
1331			if (*controlp == NULL) {
1332				FILEDESC_UNLOCK(fdescp);
1333				error = E2BIG;
1334				goto out;
1335			}
1336
1337			fdp = data;
1338			rp = (struct file **)
1339			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1340			for (i = 0; i < oldfds; i++) {
1341				fp = fdescp->fd_ofiles[*fdp++];
1342				*rp++ = fp;
1343				FILE_LOCK(fp);
1344				fp->f_count++;
1345				fp->f_msgcount++;
1346				FILE_UNLOCK(fp);
1347				unp_rights++;
1348			}
1349			FILEDESC_UNLOCK(fdescp);
1350			break;
1351
1352		case SCM_TIMESTAMP:
1353			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
1354			    SCM_TIMESTAMP, SOL_SOCKET);
1355			if (*controlp == NULL) {
1356				error = ENOBUFS;
1357				goto out;
1358			}
1359			tv = (struct timeval *)
1360			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1361			microtime(tv);
1362			break;
1363
1364		default:
1365			error = EINVAL;
1366			goto out;
1367		}
1368
1369		controlp = &(*controlp)->m_next;
1370
1371		if (CMSG_SPACE(datalen) < clen) {
1372			clen -= CMSG_SPACE(datalen);
1373			cm = (struct cmsghdr *)
1374			    ((caddr_t)cm + CMSG_SPACE(datalen));
1375		} else {
1376			clen = 0;
1377			cm = NULL;
1378		}
1379	}
1380
1381out:
1382	m_freem(control);
1383
1384	return (error);
1385}
1386
1387static int	unp_defer, unp_gcing;
1388
1389static void
1390unp_gc()
1391{
1392	register struct file *fp, *nextfp;
1393	register struct socket *so;
1394	struct file **extra_ref, **fpp;
1395	int nunref, i;
1396
1397	UNP_LOCK_ASSERT();
1398
1399	if (unp_gcing)
1400		return;
1401	unp_gcing = 1;
1402	unp_defer = 0;
1403	/*
1404	 * before going through all this, set all FDs to
1405	 * be NOT defered and NOT externally accessible
1406	 */
1407	/*
1408	 * XXXRW: Acquiring a sleep lock while holding UNP
1409	 * mutex cannot be a good thing.
1410	 */
1411	sx_slock(&filelist_lock);
1412	LIST_FOREACH(fp, &filehead, f_list)
1413		fp->f_gcflag &= ~(FMARK|FDEFER);
1414	do {
1415		LIST_FOREACH(fp, &filehead, f_list) {
1416			FILE_LOCK(fp);
1417			/*
1418			 * If the file is not open, skip it
1419			 */
1420			if (fp->f_count == 0) {
1421				FILE_UNLOCK(fp);
1422				continue;
1423			}
1424			/*
1425			 * If we already marked it as 'defer'  in a
1426			 * previous pass, then try process it this time
1427			 * and un-mark it
1428			 */
1429			if (fp->f_gcflag & FDEFER) {
1430				fp->f_gcflag &= ~FDEFER;
1431				unp_defer--;
1432			} else {
1433				/*
1434				 * if it's not defered, then check if it's
1435				 * already marked.. if so skip it
1436				 */
1437				if (fp->f_gcflag & FMARK) {
1438					FILE_UNLOCK(fp);
1439					continue;
1440				}
1441				/*
1442				 * If all references are from messages
1443				 * in transit, then skip it. it's not
1444				 * externally accessible.
1445				 */
1446				if (fp->f_count == fp->f_msgcount) {
1447					FILE_UNLOCK(fp);
1448					continue;
1449				}
1450				/*
1451				 * If it got this far then it must be
1452				 * externally accessible.
1453				 */
1454				fp->f_gcflag |= FMARK;
1455			}
1456			/*
1457			 * either it was defered, or it is externally
1458			 * accessible and not already marked so.
1459			 * Now check if it is possibly one of OUR sockets.
1460			 */
1461			if (fp->f_type != DTYPE_SOCKET ||
1462			    (so = fp->f_data) == NULL) {
1463				FILE_UNLOCK(fp);
1464				continue;
1465			}
1466			FILE_UNLOCK(fp);
1467			if (so->so_proto->pr_domain != &localdomain ||
1468			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1469				continue;
1470#ifdef notdef
1471			if (so->so_rcv.sb_flags & SB_LOCK) {
1472				/*
1473				 * This is problematical; it's not clear
1474				 * we need to wait for the sockbuf to be
1475				 * unlocked (on a uniprocessor, at least),
1476				 * and it's also not clear what to do
1477				 * if sbwait returns an error due to receipt
1478				 * of a signal.  If sbwait does return
1479				 * an error, we'll go into an infinite
1480				 * loop.  Delete all of this for now.
1481				 */
1482				(void) sbwait(&so->so_rcv);
1483				goto restart;
1484			}
1485#endif
1486			/*
1487			 * So, Ok, it's one of our sockets and it IS externally
1488			 * accessible (or was defered). Now we look
1489			 * to see if we hold any file descriptors in its
1490			 * message buffers. Follow those links and mark them
1491			 * as accessible too.
1492			 */
1493			unp_scan(so->so_rcv.sb_mb, unp_mark);
1494		}
1495	} while (unp_defer);
1496	sx_sunlock(&filelist_lock);
1497	/*
1498	 * We grab an extra reference to each of the file table entries
1499	 * that are not otherwise accessible and then free the rights
1500	 * that are stored in messages on them.
1501	 *
1502	 * The bug in the orginal code is a little tricky, so I'll describe
1503	 * what's wrong with it here.
1504	 *
1505	 * It is incorrect to simply unp_discard each entry for f_msgcount
1506	 * times -- consider the case of sockets A and B that contain
1507	 * references to each other.  On a last close of some other socket,
1508	 * we trigger a gc since the number of outstanding rights (unp_rights)
1509	 * is non-zero.  If during the sweep phase the gc code un_discards,
1510	 * we end up doing a (full) closef on the descriptor.  A closef on A
1511	 * results in the following chain.  Closef calls soo_close, which
1512	 * calls soclose.   Soclose calls first (through the switch
1513	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1514	 * returns because the previous instance had set unp_gcing, and
1515	 * we return all the way back to soclose, which marks the socket
1516	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1517	 * to free up the rights that are queued in messages on the socket A,
1518	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1519	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1520	 * instance of unp_discard just calls closef on B.
1521	 *
1522	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1523	 * which results in another closef on A.  Unfortunately, A is already
1524	 * being closed, and the descriptor has already been marked with
1525	 * SS_NOFDREF, and soclose panics at this point.
1526	 *
1527	 * Here, we first take an extra reference to each inaccessible
1528	 * descriptor.  Then, we call sorflush ourself, since we know
1529	 * it is a Unix domain socket anyhow.  After we destroy all the
1530	 * rights carried in messages, we do a last closef to get rid
1531	 * of our extra reference.  This is the last close, and the
1532	 * unp_detach etc will shut down the socket.
1533	 *
1534	 * 91/09/19, bsy@cs.cmu.edu
1535	 */
1536	extra_ref = malloc(nfiles * sizeof(struct file *), M_TEMP, M_WAITOK);
1537	sx_slock(&filelist_lock);
1538	for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1539	    fp != NULL; fp = nextfp) {
1540		nextfp = LIST_NEXT(fp, f_list);
1541		FILE_LOCK(fp);
1542		/*
1543		 * If it's not open, skip it
1544		 */
1545		if (fp->f_count == 0) {
1546			FILE_UNLOCK(fp);
1547			continue;
1548		}
1549		/*
1550		 * If all refs are from msgs, and it's not marked accessible
1551		 * then it must be referenced from some unreachable cycle
1552		 * of (shut-down) FDs, so include it in our
1553		 * list of FDs to remove
1554		 */
1555		if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1556			*fpp++ = fp;
1557			nunref++;
1558			fp->f_count++;
1559		}
1560		FILE_UNLOCK(fp);
1561	}
1562	sx_sunlock(&filelist_lock);
1563	/*
1564	 * for each FD on our hit list, do the following two things
1565	 */
1566	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1567		struct file *tfp = *fpp;
1568		FILE_LOCK(tfp);
1569		if (tfp->f_type == DTYPE_SOCKET &&
1570		    tfp->f_data != NULL) {
1571			FILE_UNLOCK(tfp);
1572			sorflush(tfp->f_data);
1573		} else {
1574			FILE_UNLOCK(tfp);
1575		}
1576	}
1577	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1578		closef(*fpp, (struct thread *) NULL);
1579	free(extra_ref, M_TEMP);
1580	unp_gcing = 0;
1581}
1582
1583void
1584unp_dispose(m)
1585	struct mbuf *m;
1586{
1587
1588	if (m)
1589		unp_scan(m, unp_discard);
1590}
1591
1592static int
1593unp_listen(unp, td)
1594	struct unpcb *unp;
1595	struct thread *td;
1596{
1597	UNP_LOCK_ASSERT();
1598
1599	/*
1600	 * XXXRW: Why populate the local peer cred with our own credential?
1601	 */
1602	cru2x(td->td_ucred, &unp->unp_peercred);
1603	unp->unp_flags |= UNP_HAVEPCCACHED;
1604	return (0);
1605}
1606
1607static void
1608unp_scan(m0, op)
1609	register struct mbuf *m0;
1610	void (*op)(struct file *);
1611{
1612	struct mbuf *m;
1613	struct file **rp;
1614	struct cmsghdr *cm;
1615	void *data;
1616	int i;
1617	socklen_t clen, datalen;
1618	int qfds;
1619
1620	while (m0 != NULL) {
1621		for (m = m0; m; m = m->m_next) {
1622			if (m->m_type != MT_CONTROL)
1623				continue;
1624
1625			cm = mtod(m, struct cmsghdr *);
1626			clen = m->m_len;
1627
1628			while (cm != NULL) {
1629				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1630					break;
1631
1632				data = CMSG_DATA(cm);
1633				datalen = (caddr_t)cm + cm->cmsg_len
1634				    - (caddr_t)data;
1635
1636				if (cm->cmsg_level == SOL_SOCKET &&
1637				    cm->cmsg_type == SCM_RIGHTS) {
1638					qfds = datalen / sizeof (struct file *);
1639					rp = data;
1640					for (i = 0; i < qfds; i++)
1641						(*op)(*rp++);
1642				}
1643
1644				if (CMSG_SPACE(datalen) < clen) {
1645					clen -= CMSG_SPACE(datalen);
1646					cm = (struct cmsghdr *)
1647					    ((caddr_t)cm + CMSG_SPACE(datalen));
1648				} else {
1649					clen = 0;
1650					cm = NULL;
1651				}
1652			}
1653		}
1654		m0 = m0->m_act;
1655	}
1656}
1657
1658static void
1659unp_mark(fp)
1660	struct file *fp;
1661{
1662	if (fp->f_gcflag & FMARK)
1663		return;
1664	unp_defer++;
1665	fp->f_gcflag |= (FMARK|FDEFER);
1666}
1667
1668static void
1669unp_discard(fp)
1670	struct file *fp;
1671{
1672	FILE_LOCK(fp);
1673	fp->f_msgcount--;
1674	unp_rights--;
1675	FILE_UNLOCK(fp);
1676	(void) closef(fp, (struct thread *)NULL);
1677}
1678