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