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