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