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