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