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