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