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