xref: /netbsd-src/sys/kern/uipc_usrreq.c (revision 48fb7bfab72acd4281a53bbee5ccf3f809019e75)
1 /*	$NetBSD: uipc_usrreq.c,v 1.150 2014/01/23 10:13:56 hannken Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2000, 2004, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center, and by Andrew Doran.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1989, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
62  */
63 
64 /*
65  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
66  *
67  * Redistribution and use in source and binary forms, with or without
68  * modification, are permitted provided that the following conditions
69  * are met:
70  * 1. Redistributions of source code must retain the above copyright
71  *    notice, this list of conditions and the following disclaimer.
72  * 2. Redistributions in binary form must reproduce the above copyright
73  *    notice, this list of conditions and the following disclaimer in the
74  *    documentation and/or other materials provided with the distribution.
75  * 3. All advertising materials mentioning features or use of this software
76  *    must display the following acknowledgement:
77  *	This product includes software developed by the University of
78  *	California, Berkeley and its contributors.
79  * 4. Neither the name of the University nor the names of its contributors
80  *    may be used to endorse or promote products derived from this software
81  *    without specific prior written permission.
82  *
83  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
84  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
85  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
86  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
87  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
88  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
89  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
90  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
91  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
92  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
93  * SUCH DAMAGE.
94  *
95  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
96  */
97 
98 #include <sys/cdefs.h>
99 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.150 2014/01/23 10:13:56 hannken Exp $");
100 
101 #include <sys/param.h>
102 #include <sys/systm.h>
103 #include <sys/proc.h>
104 #include <sys/filedesc.h>
105 #include <sys/domain.h>
106 #include <sys/protosw.h>
107 #include <sys/socket.h>
108 #include <sys/socketvar.h>
109 #include <sys/unpcb.h>
110 #include <sys/un.h>
111 #include <sys/namei.h>
112 #include <sys/vnode.h>
113 #include <sys/file.h>
114 #include <sys/stat.h>
115 #include <sys/mbuf.h>
116 #include <sys/kauth.h>
117 #include <sys/kmem.h>
118 #include <sys/atomic.h>
119 #include <sys/uidinfo.h>
120 #include <sys/kernel.h>
121 #include <sys/kthread.h>
122 
123 /*
124  * Unix communications domain.
125  *
126  * TODO:
127  *	RDM
128  *	rethink name space problems
129  *	need a proper out-of-band
130  *
131  * Notes on locking:
132  *
133  * The generic rules noted in uipc_socket2.c apply.  In addition:
134  *
135  * o We have a global lock, uipc_lock.
136  *
137  * o All datagram sockets are locked by uipc_lock.
138  *
139  * o For stream socketpairs, the two endpoints are created sharing the same
140  *   independent lock.  Sockets presented to PRU_CONNECT2 must already have
141  *   matching locks.
142  *
143  * o Stream sockets created via socket() start life with their own
144  *   independent lock.
145  *
146  * o Stream connections to a named endpoint are slightly more complicated.
147  *   Sockets that have called listen() have their lock pointer mutated to
148  *   the global uipc_lock.  When establishing a connection, the connecting
149  *   socket also has its lock mutated to uipc_lock, which matches the head
150  *   (listening socket).  We create a new socket for accept() to return, and
151  *   that also shares the head's lock.  Until the connection is completely
152  *   done on both ends, all three sockets are locked by uipc_lock.  Once the
153  *   connection is complete, the association with the head's lock is broken.
154  *   The connecting socket and the socket returned from accept() have their
155  *   lock pointers mutated away from uipc_lock, and back to the connecting
156  *   socket's original, independent lock.  The head continues to be locked
157  *   by uipc_lock.
158  *
159  * o If uipc_lock is determined to be a significant source of contention,
160  *   it could easily be hashed out.  It is difficult to simply make it an
161  *   independent lock because of visibility / garbage collection issues:
162  *   if a socket has been associated with a lock at any point, that lock
163  *   must remain valid until the socket is no longer visible in the system.
164  *   The lock must not be freed or otherwise destroyed until any sockets
165  *   that had referenced it have also been destroyed.
166  */
167 const struct sockaddr_un sun_noname = {
168 	.sun_len = offsetof(struct sockaddr_un, sun_path),
169 	.sun_family = AF_LOCAL,
170 };
171 ino_t	unp_ino;			/* prototype for fake inode numbers */
172 
173 struct mbuf *unp_addsockcred(struct lwp *, struct mbuf *);
174 static void unp_mark(file_t *);
175 static void unp_scan(struct mbuf *, void (*)(file_t *), int);
176 static void unp_discard_now(file_t *);
177 static void unp_discard_later(file_t *);
178 static void unp_thread(void *);
179 static void unp_thread_kick(void);
180 static kmutex_t *uipc_lock;
181 
182 static kcondvar_t unp_thread_cv;
183 static lwp_t *unp_thread_lwp;
184 static SLIST_HEAD(,file) unp_thread_discard;
185 static int unp_defer;
186 
187 /*
188  * Initialize Unix protocols.
189  */
190 void
191 uipc_init(void)
192 {
193 	int error;
194 
195 	uipc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
196 	cv_init(&unp_thread_cv, "unpgc");
197 
198 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, unp_thread,
199 	    NULL, &unp_thread_lwp, "unpgc");
200 	if (error != 0)
201 		panic("uipc_init %d", error);
202 }
203 
204 /*
205  * A connection succeeded: disassociate both endpoints from the head's
206  * lock, and make them share their own lock.  There is a race here: for
207  * a very brief time one endpoint will be locked by a different lock
208  * than the other end.  However, since the current thread holds the old
209  * lock (the listening socket's lock, the head) access can still only be
210  * made to one side of the connection.
211  */
212 static void
213 unp_setpeerlocks(struct socket *so, struct socket *so2)
214 {
215 	struct unpcb *unp;
216 	kmutex_t *lock;
217 
218 	KASSERT(solocked2(so, so2));
219 
220 	/*
221 	 * Bail out if either end of the socket is not yet fully
222 	 * connected or accepted.  We only break the lock association
223 	 * with the head when the pair of sockets stand completely
224 	 * on their own.
225 	 */
226 	KASSERT(so->so_head == NULL);
227 	if (so2->so_head != NULL)
228 		return;
229 
230 	/*
231 	 * Drop references to old lock.  A third reference (from the
232 	 * queue head) must be held as we still hold its lock.  Bonus:
233 	 * we don't need to worry about garbage collecting the lock.
234 	 */
235 	lock = so->so_lock;
236 	KASSERT(lock == uipc_lock);
237 	mutex_obj_free(lock);
238 	mutex_obj_free(lock);
239 
240 	/*
241 	 * Grab stream lock from the initiator and share between the two
242 	 * endpoints.  Issue memory barrier to ensure all modifications
243 	 * become globally visible before the lock change.  so2 is
244 	 * assumed not to have a stream lock, because it was created
245 	 * purely for the server side to accept this connection and
246 	 * started out life using the domain-wide lock.
247 	 */
248 	unp = sotounpcb(so);
249 	KASSERT(unp->unp_streamlock != NULL);
250 	KASSERT(sotounpcb(so2)->unp_streamlock == NULL);
251 	lock = unp->unp_streamlock;
252 	unp->unp_streamlock = NULL;
253 	mutex_obj_hold(lock);
254 	membar_exit();
255 	/*
256 	 * possible race if lock is not held - see comment in
257 	 * uipc_usrreq(PRU_ACCEPT).
258 	 */
259 	KASSERT(mutex_owned(lock));
260 	solockreset(so, lock);
261 	solockreset(so2, lock);
262 }
263 
264 /*
265  * Reset a socket's lock back to the domain-wide lock.
266  */
267 static void
268 unp_resetlock(struct socket *so)
269 {
270 	kmutex_t *olock, *nlock;
271 	struct unpcb *unp;
272 
273 	KASSERT(solocked(so));
274 
275 	olock = so->so_lock;
276 	nlock = uipc_lock;
277 	if (olock == nlock)
278 		return;
279 	unp = sotounpcb(so);
280 	KASSERT(unp->unp_streamlock == NULL);
281 	unp->unp_streamlock = olock;
282 	mutex_obj_hold(nlock);
283 	mutex_enter(nlock);
284 	solockreset(so, nlock);
285 	mutex_exit(olock);
286 }
287 
288 static void
289 unp_free(struct unpcb *unp)
290 {
291 
292 	if (unp->unp_addr)
293 		free(unp->unp_addr, M_SONAME);
294 	if (unp->unp_streamlock != NULL)
295 		mutex_obj_free(unp->unp_streamlock);
296 	free(unp, M_PCB);
297 }
298 
299 int
300 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp,
301 	struct lwp *l)
302 {
303 	struct socket *so2;
304 	const struct sockaddr_un *sun;
305 
306 	so2 = unp->unp_conn->unp_socket;
307 
308 	KASSERT(solocked(so2));
309 
310 	if (unp->unp_addr)
311 		sun = unp->unp_addr;
312 	else
313 		sun = &sun_noname;
314 	if (unp->unp_conn->unp_flags & UNP_WANTCRED)
315 		control = unp_addsockcred(l, control);
316 	if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m,
317 	    control) == 0) {
318 		so2->so_rcv.sb_overflowed++;
319 		unp_dispose(control);
320 		m_freem(control);
321 		m_freem(m);
322 		return (ENOBUFS);
323 	} else {
324 		sorwakeup(so2);
325 		return (0);
326 	}
327 }
328 
329 void
330 unp_setaddr(struct socket *so, struct mbuf *nam, bool peeraddr)
331 {
332 	const struct sockaddr_un *sun;
333 	struct unpcb *unp;
334 	bool ext;
335 
336 	KASSERT(solocked(so));
337 	unp = sotounpcb(so);
338 	ext = false;
339 
340 	for (;;) {
341 		sun = NULL;
342 		if (peeraddr) {
343 			if (unp->unp_conn && unp->unp_conn->unp_addr)
344 				sun = unp->unp_conn->unp_addr;
345 		} else {
346 			if (unp->unp_addr)
347 				sun = unp->unp_addr;
348 		}
349 		if (sun == NULL)
350 			sun = &sun_noname;
351 		nam->m_len = sun->sun_len;
352 		if (nam->m_len > MLEN && !ext) {
353 			sounlock(so);
354 			MEXTMALLOC(nam, MAXPATHLEN * 2, M_WAITOK);
355 			solock(so);
356 			ext = true;
357 		} else {
358 			KASSERT(nam->m_len <= MAXPATHLEN * 2);
359 			memcpy(mtod(nam, void *), sun, (size_t)nam->m_len);
360 			break;
361 		}
362 	}
363 }
364 
365 /*ARGSUSED*/
366 int
367 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
368 	struct mbuf *control, struct lwp *l)
369 {
370 	struct unpcb *unp = sotounpcb(so);
371 	struct socket *so2;
372 	u_int newhiwat;
373 	int error = 0;
374 
375 	if (req == PRU_CONTROL)
376 		return (EOPNOTSUPP);
377 
378 #ifdef DIAGNOSTIC
379 	if (req != PRU_SEND && req != PRU_SENDOOB && control)
380 		panic("uipc_usrreq: unexpected control mbuf");
381 #endif
382 	if (req != PRU_ATTACH) {
383 		if (unp == NULL) {
384 			error = EINVAL;
385 			goto release;
386 		}
387 		KASSERT(solocked(so));
388 	}
389 
390 	switch (req) {
391 
392 	case PRU_ATTACH:
393 		if (unp != NULL) {
394 			error = EISCONN;
395 			break;
396 		}
397 		error = unp_attach(so);
398 		break;
399 
400 	case PRU_DETACH:
401 		unp_detach(unp);
402 		break;
403 
404 	case PRU_BIND:
405 		KASSERT(l != NULL);
406 		error = unp_bind(so, nam, l);
407 		break;
408 
409 	case PRU_LISTEN:
410 		/*
411 		 * If the socket can accept a connection, it must be
412 		 * locked by uipc_lock.
413 		 */
414 		unp_resetlock(so);
415 		if (unp->unp_vnode == NULL)
416 			error = EINVAL;
417 		break;
418 
419 	case PRU_CONNECT:
420 		KASSERT(l != NULL);
421 		error = unp_connect(so, nam, l);
422 		break;
423 
424 	case PRU_CONNECT2:
425 		error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
426 		break;
427 
428 	case PRU_DISCONNECT:
429 		unp_disconnect(unp);
430 		break;
431 
432 	case PRU_ACCEPT:
433 		KASSERT(so->so_lock == uipc_lock);
434 		/*
435 		 * Mark the initiating STREAM socket as connected *ONLY*
436 		 * after it's been accepted.  This prevents a client from
437 		 * overrunning a server and receiving ECONNREFUSED.
438 		 */
439 		if (unp->unp_conn == NULL) {
440 			/*
441 			 * This will use the empty socket and will not
442 			 * allocate.
443 			 */
444 			unp_setaddr(so, nam, true);
445 			break;
446 		}
447 		so2 = unp->unp_conn->unp_socket;
448 		if (so2->so_state & SS_ISCONNECTING) {
449 			KASSERT(solocked2(so, so->so_head));
450 			KASSERT(solocked2(so2, so->so_head));
451 			soisconnected(so2);
452 		}
453 		/*
454 		 * If the connection is fully established, break the
455 		 * association with uipc_lock and give the connected
456 		 * pair a seperate lock to share.
457 		 * There is a race here: sotounpcb(so2)->unp_streamlock
458 		 * is not locked, so when changing so2->so_lock
459 		 * another thread can grab it while so->so_lock is still
460 		 * pointing to the (locked) uipc_lock.
461 		 * this should be harmless, except that this makes
462 		 * solocked2() and solocked() unreliable.
463 		 * Another problem is that unp_setaddr() expects the
464 		 * the socket locked. Grabing sotounpcb(so2)->unp_streamlock
465 		 * fixes both issues.
466 		 */
467 		mutex_enter(sotounpcb(so2)->unp_streamlock);
468 		unp_setpeerlocks(so2, so);
469 		/*
470 		 * Only now return peer's address, as we may need to
471 		 * block in order to allocate memory.
472 		 *
473 		 * XXX Minor race: connection can be broken while
474 		 * lock is dropped in unp_setaddr().  We will return
475 		 * error == 0 and sun_noname as the peer address.
476 		 */
477 		unp_setaddr(so, nam, true);
478 		/* so_lock now points to unp_streamlock */
479 		mutex_exit(so2->so_lock);
480 		break;
481 
482 	case PRU_SHUTDOWN:
483 		socantsendmore(so);
484 		unp_shutdown(unp);
485 		break;
486 
487 	case PRU_RCVD:
488 		switch (so->so_type) {
489 
490 		case SOCK_DGRAM:
491 			panic("uipc 1");
492 			/*NOTREACHED*/
493 
494 		case SOCK_SEQPACKET: /* FALLTHROUGH */
495 		case SOCK_STREAM:
496 #define	rcv (&so->so_rcv)
497 #define snd (&so2->so_snd)
498 			if (unp->unp_conn == 0)
499 				break;
500 			so2 = unp->unp_conn->unp_socket;
501 			KASSERT(solocked2(so, so2));
502 			/*
503 			 * Adjust backpressure on sender
504 			 * and wakeup any waiting to write.
505 			 */
506 			snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
507 			unp->unp_mbcnt = rcv->sb_mbcnt;
508 			newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
509 			(void)chgsbsize(so2->so_uidinfo,
510 			    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
511 			unp->unp_cc = rcv->sb_cc;
512 			sowwakeup(so2);
513 #undef snd
514 #undef rcv
515 			break;
516 
517 		default:
518 			panic("uipc 2");
519 		}
520 		break;
521 
522 	case PRU_SEND:
523 		/*
524 		 * Note: unp_internalize() rejects any control message
525 		 * other than SCM_RIGHTS, and only allows one.  This
526 		 * has the side-effect of preventing a caller from
527 		 * forging SCM_CREDS.
528 		 */
529 		if (control) {
530 			sounlock(so);
531 			error = unp_internalize(&control);
532 			solock(so);
533 			if (error != 0) {
534 				m_freem(control);
535 				m_freem(m);
536 				break;
537 			}
538 		}
539 		switch (so->so_type) {
540 
541 		case SOCK_DGRAM: {
542 			KASSERT(so->so_lock == uipc_lock);
543 			if (nam) {
544 				if ((so->so_state & SS_ISCONNECTED) != 0)
545 					error = EISCONN;
546 				else {
547 					/*
548 					 * Note: once connected, the
549 					 * socket's lock must not be
550 					 * dropped until we have sent
551 					 * the message and disconnected.
552 					 * This is necessary to prevent
553 					 * intervening control ops, like
554 					 * another connection.
555 					 */
556 					error = unp_connect(so, nam, l);
557 				}
558 			} else {
559 				if ((so->so_state & SS_ISCONNECTED) == 0)
560 					error = ENOTCONN;
561 			}
562 			if (error) {
563 				unp_dispose(control);
564 				m_freem(control);
565 				m_freem(m);
566 				break;
567 			}
568 			KASSERT(l != NULL);
569 			error = unp_output(m, control, unp, l);
570 			if (nam)
571 				unp_disconnect(unp);
572 			break;
573 		}
574 
575 		case SOCK_SEQPACKET: /* FALLTHROUGH */
576 		case SOCK_STREAM:
577 #define	rcv (&so2->so_rcv)
578 #define	snd (&so->so_snd)
579 			if (unp->unp_conn == NULL) {
580 				error = ENOTCONN;
581 				break;
582 			}
583 			so2 = unp->unp_conn->unp_socket;
584 			KASSERT(solocked2(so, so2));
585 			if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
586 				/*
587 				 * Credentials are passed only once on
588 				 * SOCK_STREAM and SOCK_SEQPACKET.
589 				 */
590 				unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
591 				control = unp_addsockcred(l, control);
592 			}
593 			/*
594 			 * Send to paired receive port, and then reduce
595 			 * send buffer hiwater marks to maintain backpressure.
596 			 * Wake up readers.
597 			 */
598 			if (control) {
599 				if (sbappendcontrol(rcv, m, control) != 0)
600 					control = NULL;
601 			} else {
602 				switch(so->so_type) {
603 				case SOCK_SEQPACKET:
604 					sbappendrecord(rcv, m);
605 					break;
606 				case SOCK_STREAM:
607 					sbappend(rcv, m);
608 					break;
609 				default:
610 					panic("uipc_usrreq");
611 					break;
612 				}
613 			}
614 			snd->sb_mbmax -=
615 			    rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
616 			unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
617 			newhiwat = snd->sb_hiwat -
618 			    (rcv->sb_cc - unp->unp_conn->unp_cc);
619 			(void)chgsbsize(so->so_uidinfo,
620 			    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
621 			unp->unp_conn->unp_cc = rcv->sb_cc;
622 			sorwakeup(so2);
623 #undef snd
624 #undef rcv
625 			if (control != NULL) {
626 				unp_dispose(control);
627 				m_freem(control);
628 			}
629 			break;
630 
631 		default:
632 			panic("uipc 4");
633 		}
634 		break;
635 
636 	case PRU_ABORT:
637 		(void)unp_drop(unp, ECONNABORTED);
638 
639 		KASSERT(so->so_head == NULL);
640 #ifdef DIAGNOSTIC
641 		if (so->so_pcb == NULL)
642 			panic("uipc 5: drop killed pcb");
643 #endif
644 		unp_detach(unp);
645 		break;
646 
647 	case PRU_SENSE:
648 		((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
649 		switch (so->so_type) {
650 		case SOCK_SEQPACKET: /* FALLTHROUGH */
651 		case SOCK_STREAM:
652 			if (unp->unp_conn == 0)
653 				break;
654 
655 			so2 = unp->unp_conn->unp_socket;
656 			KASSERT(solocked2(so, so2));
657 			((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
658 			break;
659 		default:
660 			break;
661 		}
662 		((struct stat *) m)->st_dev = NODEV;
663 		if (unp->unp_ino == 0)
664 			unp->unp_ino = unp_ino++;
665 		((struct stat *) m)->st_atimespec =
666 		    ((struct stat *) m)->st_mtimespec =
667 		    ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
668 		((struct stat *) m)->st_ino = unp->unp_ino;
669 		return (0);
670 
671 	case PRU_RCVOOB:
672 		error = EOPNOTSUPP;
673 		break;
674 
675 	case PRU_SENDOOB:
676 		m_freem(control);
677 		m_freem(m);
678 		error = EOPNOTSUPP;
679 		break;
680 
681 	case PRU_SOCKADDR:
682 		unp_setaddr(so, nam, false);
683 		break;
684 
685 	case PRU_PEERADDR:
686 		unp_setaddr(so, nam, true);
687 		break;
688 
689 	default:
690 		panic("piusrreq");
691 	}
692 
693 release:
694 	return (error);
695 }
696 
697 /*
698  * Unix domain socket option processing.
699  */
700 int
701 uipc_ctloutput(int op, struct socket *so, struct sockopt *sopt)
702 {
703 	struct unpcb *unp = sotounpcb(so);
704 	int optval = 0, error = 0;
705 
706 	KASSERT(solocked(so));
707 
708 	if (sopt->sopt_level != 0) {
709 		error = ENOPROTOOPT;
710 	} else switch (op) {
711 
712 	case PRCO_SETOPT:
713 		switch (sopt->sopt_name) {
714 		case LOCAL_CREDS:
715 		case LOCAL_CONNWAIT:
716 			error = sockopt_getint(sopt, &optval);
717 			if (error)
718 				break;
719 			switch (sopt->sopt_name) {
720 #define	OPTSET(bit) \
721 	if (optval) \
722 		unp->unp_flags |= (bit); \
723 	else \
724 		unp->unp_flags &= ~(bit);
725 
726 			case LOCAL_CREDS:
727 				OPTSET(UNP_WANTCRED);
728 				break;
729 			case LOCAL_CONNWAIT:
730 				OPTSET(UNP_CONNWAIT);
731 				break;
732 			}
733 			break;
734 #undef OPTSET
735 
736 		default:
737 			error = ENOPROTOOPT;
738 			break;
739 		}
740 		break;
741 
742 	case PRCO_GETOPT:
743 		sounlock(so);
744 		switch (sopt->sopt_name) {
745 		case LOCAL_PEEREID:
746 			if (unp->unp_flags & UNP_EIDSVALID) {
747 				error = sockopt_set(sopt,
748 				    &unp->unp_connid, sizeof(unp->unp_connid));
749 			} else {
750 				error = EINVAL;
751 			}
752 			break;
753 		case LOCAL_CREDS:
754 #define	OPTBIT(bit)	(unp->unp_flags & (bit) ? 1 : 0)
755 
756 			optval = OPTBIT(UNP_WANTCRED);
757 			error = sockopt_setint(sopt, optval);
758 			break;
759 #undef OPTBIT
760 
761 		default:
762 			error = ENOPROTOOPT;
763 			break;
764 		}
765 		solock(so);
766 		break;
767 	}
768 	return (error);
769 }
770 
771 /*
772  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
773  * for stream sockets, although the total for sender and receiver is
774  * actually only PIPSIZ.
775  * Datagram sockets really use the sendspace as the maximum datagram size,
776  * and don't really want to reserve the sendspace.  Their recvspace should
777  * be large enough for at least one max-size datagram plus address.
778  */
779 #define	PIPSIZ	4096
780 u_long	unpst_sendspace = PIPSIZ;
781 u_long	unpst_recvspace = PIPSIZ;
782 u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
783 u_long	unpdg_recvspace = 4*1024;
784 
785 u_int	unp_rights;			/* files in flight */
786 u_int	unp_rights_ratio = 2;		/* limit, fraction of maxfiles */
787 
788 int
789 unp_attach(struct socket *so)
790 {
791 	struct unpcb *unp;
792 	int error;
793 
794 	switch (so->so_type) {
795 	case SOCK_SEQPACKET: /* FALLTHROUGH */
796 	case SOCK_STREAM:
797 		if (so->so_lock == NULL) {
798 			/*
799 			 * XXX Assuming that no socket locks are held,
800 			 * as this call may sleep.
801 			 */
802 			so->so_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
803 			solock(so);
804 		}
805 		if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
806 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
807 			if (error != 0)
808 				return (error);
809 		}
810 		break;
811 
812 	case SOCK_DGRAM:
813 		if (so->so_lock == NULL) {
814 			mutex_obj_hold(uipc_lock);
815 			so->so_lock = uipc_lock;
816 			solock(so);
817 		}
818 		if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
819 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
820 			if (error != 0)
821 				return (error);
822 		}
823 		break;
824 
825 	default:
826 		panic("unp_attach");
827 	}
828 	KASSERT(solocked(so));
829 	unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
830 	if (unp == NULL)
831 		return (ENOBUFS);
832 	memset(unp, 0, sizeof(*unp));
833 	unp->unp_socket = so;
834 	so->so_pcb = unp;
835 	nanotime(&unp->unp_ctime);
836 	return (0);
837 }
838 
839 void
840 unp_detach(struct unpcb *unp)
841 {
842 	struct socket *so;
843 	vnode_t *vp;
844 
845 	so = unp->unp_socket;
846 
847  retry:
848 	if ((vp = unp->unp_vnode) != NULL) {
849 		sounlock(so);
850 		/* Acquire v_interlock to protect against unp_connect(). */
851 		/* XXXAD racy */
852 		mutex_enter(vp->v_interlock);
853 		vp->v_socket = NULL;
854 		mutex_exit(vp->v_interlock);
855 		vrele(vp);
856 		solock(so);
857 		unp->unp_vnode = NULL;
858 	}
859 	if (unp->unp_conn)
860 		unp_disconnect(unp);
861 	while (unp->unp_refs) {
862 		KASSERT(solocked2(so, unp->unp_refs->unp_socket));
863 		if (unp_drop(unp->unp_refs, ECONNRESET)) {
864 			solock(so);
865 			goto retry;
866 		}
867 	}
868 	soisdisconnected(so);
869 	so->so_pcb = NULL;
870 	if (unp_rights) {
871 		/*
872 		 * Normally the receive buffer is flushed later, in sofree,
873 		 * but if our receive buffer holds references to files that
874 		 * are now garbage, we will enqueue those file references to
875 		 * the garbage collector and kick it into action.
876 		 */
877 		sorflush(so);
878 		unp_free(unp);
879 		unp_thread_kick();
880 	} else
881 		unp_free(unp);
882 }
883 
884 /*
885  * Allocate the new sockaddr.  We have to allocate one
886  * extra byte so that we can ensure that the pathname
887  * is nul-terminated. Note that unlike linux, we don't
888  * include in the address length the NUL in the path
889  * component, because doing so, would exceed sizeof(sockaddr_un)
890  * for fully occupied pathnames. Linux is also inconsistent,
891  * because it does not include the NUL in the length of
892  * what it calls "abstract" unix sockets.
893  */
894 static struct sockaddr_un *
895 makeun(struct mbuf *nam, size_t *addrlen) {
896 	struct sockaddr_un *sun;
897 
898 	*addrlen = nam->m_len + 1;
899 	sun = malloc(*addrlen, M_SONAME, M_WAITOK);
900 	m_copydata(nam, 0, nam->m_len, (void *)sun);
901 	*(((char *)sun) + nam->m_len) = '\0';
902 	sun->sun_len = strlen(sun->sun_path) +
903 	    offsetof(struct sockaddr_un, sun_path);
904 	return sun;
905 }
906 
907 int
908 unp_bind(struct socket *so, struct mbuf *nam, struct lwp *l)
909 {
910 	struct sockaddr_un *sun;
911 	struct unpcb *unp;
912 	vnode_t *vp;
913 	struct vattr vattr;
914 	size_t addrlen;
915 	int error;
916 	struct pathbuf *pb;
917 	struct nameidata nd;
918 	proc_t *p;
919 
920 	unp = sotounpcb(so);
921 	if (unp->unp_vnode != NULL)
922 		return (EINVAL);
923 	if ((unp->unp_flags & UNP_BUSY) != 0) {
924 		/*
925 		 * EALREADY may not be strictly accurate, but since this
926 		 * is a major application error it's hardly a big deal.
927 		 */
928 		return (EALREADY);
929 	}
930 	unp->unp_flags |= UNP_BUSY;
931 	sounlock(so);
932 
933 	p = l->l_proc;
934 	sun = makeun(nam, &addrlen);
935 
936 	pb = pathbuf_create(sun->sun_path);
937 	if (pb == NULL) {
938 		error = ENOMEM;
939 		goto bad;
940 	}
941 	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT | TRYEMULROOT, pb);
942 
943 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
944 	if ((error = namei(&nd)) != 0) {
945 		pathbuf_destroy(pb);
946 		goto bad;
947 	}
948 	vp = nd.ni_vp;
949 	if (vp != NULL) {
950 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
951 		if (nd.ni_dvp == vp)
952 			vrele(nd.ni_dvp);
953 		else
954 			vput(nd.ni_dvp);
955 		vrele(vp);
956 		pathbuf_destroy(pb);
957 		error = EADDRINUSE;
958 		goto bad;
959 	}
960 	vattr_null(&vattr);
961 	vattr.va_type = VSOCK;
962 	vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
963 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
964 	if (error) {
965 		vput(nd.ni_dvp);
966 		pathbuf_destroy(pb);
967 		goto bad;
968 	}
969 	vp = nd.ni_vp;
970 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
971 	solock(so);
972 	vp->v_socket = unp->unp_socket;
973 	unp->unp_vnode = vp;
974 	unp->unp_addrlen = addrlen;
975 	unp->unp_addr = sun;
976 	unp->unp_connid.unp_pid = p->p_pid;
977 	unp->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
978 	unp->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
979 	unp->unp_flags |= UNP_EIDSBIND;
980 	VOP_UNLOCK(vp);
981 	vput(nd.ni_dvp);
982 	unp->unp_flags &= ~UNP_BUSY;
983 	pathbuf_destroy(pb);
984 	return (0);
985 
986  bad:
987 	free(sun, M_SONAME);
988 	solock(so);
989 	unp->unp_flags &= ~UNP_BUSY;
990 	return (error);
991 }
992 
993 int
994 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
995 {
996 	struct sockaddr_un *sun;
997 	vnode_t *vp;
998 	struct socket *so2, *so3;
999 	struct unpcb *unp, *unp2, *unp3;
1000 	size_t addrlen;
1001 	int error;
1002 	struct pathbuf *pb;
1003 	struct nameidata nd;
1004 
1005 	unp = sotounpcb(so);
1006 	if ((unp->unp_flags & UNP_BUSY) != 0) {
1007 		/*
1008 		 * EALREADY may not be strictly accurate, but since this
1009 		 * is a major application error it's hardly a big deal.
1010 		 */
1011 		return (EALREADY);
1012 	}
1013 	unp->unp_flags |= UNP_BUSY;
1014 	sounlock(so);
1015 
1016 	sun = makeun(nam, &addrlen);
1017 	pb = pathbuf_create(sun->sun_path);
1018 	if (pb == NULL) {
1019 		error = ENOMEM;
1020 		goto bad2;
1021 	}
1022 
1023 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
1024 
1025 	if ((error = namei(&nd)) != 0) {
1026 		pathbuf_destroy(pb);
1027 		goto bad2;
1028 	}
1029 	vp = nd.ni_vp;
1030 	if (vp->v_type != VSOCK) {
1031 		error = ENOTSOCK;
1032 		goto bad;
1033 	}
1034 	pathbuf_destroy(pb);
1035 	if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred)) != 0)
1036 		goto bad;
1037 	/* Acquire v_interlock to protect against unp_detach(). */
1038 	mutex_enter(vp->v_interlock);
1039 	so2 = vp->v_socket;
1040 	if (so2 == NULL) {
1041 		mutex_exit(vp->v_interlock);
1042 		error = ECONNREFUSED;
1043 		goto bad;
1044 	}
1045 	if (so->so_type != so2->so_type) {
1046 		mutex_exit(vp->v_interlock);
1047 		error = EPROTOTYPE;
1048 		goto bad;
1049 	}
1050 	solock(so);
1051 	unp_resetlock(so);
1052 	mutex_exit(vp->v_interlock);
1053 	if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
1054 		/*
1055 		 * This may seem somewhat fragile but is OK: if we can
1056 		 * see SO_ACCEPTCONN set on the endpoint, then it must
1057 		 * be locked by the domain-wide uipc_lock.
1058 		 */
1059 		KASSERT((so2->so_options & SO_ACCEPTCONN) == 0 ||
1060 		    so2->so_lock == uipc_lock);
1061 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
1062 		    (so3 = sonewconn(so2, false)) == NULL) {
1063 			error = ECONNREFUSED;
1064 			sounlock(so);
1065 			goto bad;
1066 		}
1067 		unp2 = sotounpcb(so2);
1068 		unp3 = sotounpcb(so3);
1069 		if (unp2->unp_addr) {
1070 			unp3->unp_addr = malloc(unp2->unp_addrlen,
1071 			    M_SONAME, M_WAITOK);
1072 			memcpy(unp3->unp_addr, unp2->unp_addr,
1073 			    unp2->unp_addrlen);
1074 			unp3->unp_addrlen = unp2->unp_addrlen;
1075 		}
1076 		unp3->unp_flags = unp2->unp_flags;
1077 		unp3->unp_connid.unp_pid = l->l_proc->p_pid;
1078 		unp3->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
1079 		unp3->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
1080 		unp3->unp_flags |= UNP_EIDSVALID;
1081 		if (unp2->unp_flags & UNP_EIDSBIND) {
1082 			unp->unp_connid = unp2->unp_connid;
1083 			unp->unp_flags |= UNP_EIDSVALID;
1084 		}
1085 		so2 = so3;
1086 	}
1087 	error = unp_connect2(so, so2, PRU_CONNECT);
1088 	sounlock(so);
1089  bad:
1090 	vput(vp);
1091  bad2:
1092 	free(sun, M_SONAME);
1093 	solock(so);
1094 	unp->unp_flags &= ~UNP_BUSY;
1095 	return (error);
1096 }
1097 
1098 int
1099 unp_connect2(struct socket *so, struct socket *so2, int req)
1100 {
1101 	struct unpcb *unp = sotounpcb(so);
1102 	struct unpcb *unp2;
1103 
1104 	if (so2->so_type != so->so_type)
1105 		return (EPROTOTYPE);
1106 
1107 	/*
1108 	 * All three sockets involved must be locked by same lock:
1109 	 *
1110 	 * local endpoint (so)
1111 	 * remote endpoint (so2)
1112 	 * queue head (so2->so_head, only if PR_CONNREQUIRED)
1113 	 */
1114 	KASSERT(solocked2(so, so2));
1115 	KASSERT(so->so_head == NULL);
1116 	if (so2->so_head != NULL) {
1117 		KASSERT(so2->so_lock == uipc_lock);
1118 		KASSERT(solocked2(so2, so2->so_head));
1119 	}
1120 
1121 	unp2 = sotounpcb(so2);
1122 	unp->unp_conn = unp2;
1123 	switch (so->so_type) {
1124 
1125 	case SOCK_DGRAM:
1126 		unp->unp_nextref = unp2->unp_refs;
1127 		unp2->unp_refs = unp;
1128 		soisconnected(so);
1129 		break;
1130 
1131 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1132 	case SOCK_STREAM:
1133 		unp2->unp_conn = unp;
1134 		if (req == PRU_CONNECT &&
1135 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1136 			soisconnecting(so);
1137 		else
1138 			soisconnected(so);
1139 		soisconnected(so2);
1140 		/*
1141 		 * If the connection is fully established, break the
1142 		 * association with uipc_lock and give the connected
1143 		 * pair a seperate lock to share.  For CONNECT2, we
1144 		 * require that the locks already match (the sockets
1145 		 * are created that way).
1146 		 */
1147 		if (req == PRU_CONNECT) {
1148 			KASSERT(so2->so_head != NULL);
1149 			unp_setpeerlocks(so, so2);
1150 		}
1151 		break;
1152 
1153 	default:
1154 		panic("unp_connect2");
1155 	}
1156 	return (0);
1157 }
1158 
1159 void
1160 unp_disconnect(struct unpcb *unp)
1161 {
1162 	struct unpcb *unp2 = unp->unp_conn;
1163 	struct socket *so;
1164 
1165 	if (unp2 == 0)
1166 		return;
1167 	unp->unp_conn = 0;
1168 	so = unp->unp_socket;
1169 	switch (so->so_type) {
1170 	case SOCK_DGRAM:
1171 		if (unp2->unp_refs == unp)
1172 			unp2->unp_refs = unp->unp_nextref;
1173 		else {
1174 			unp2 = unp2->unp_refs;
1175 			for (;;) {
1176 				KASSERT(solocked2(so, unp2->unp_socket));
1177 				if (unp2 == 0)
1178 					panic("unp_disconnect");
1179 				if (unp2->unp_nextref == unp)
1180 					break;
1181 				unp2 = unp2->unp_nextref;
1182 			}
1183 			unp2->unp_nextref = unp->unp_nextref;
1184 		}
1185 		unp->unp_nextref = 0;
1186 		so->so_state &= ~SS_ISCONNECTED;
1187 		break;
1188 
1189 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1190 	case SOCK_STREAM:
1191 		KASSERT(solocked2(so, unp2->unp_socket));
1192 		soisdisconnected(so);
1193 		unp2->unp_conn = 0;
1194 		soisdisconnected(unp2->unp_socket);
1195 		break;
1196 	}
1197 }
1198 
1199 #ifdef notdef
1200 unp_abort(struct unpcb *unp)
1201 {
1202 	unp_detach(unp);
1203 }
1204 #endif
1205 
1206 void
1207 unp_shutdown(struct unpcb *unp)
1208 {
1209 	struct socket *so;
1210 
1211 	switch(unp->unp_socket->so_type) {
1212 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1213 	case SOCK_STREAM:
1214 		if (unp->unp_conn && (so = unp->unp_conn->unp_socket))
1215 			socantrcvmore(so);
1216 		break;
1217 	default:
1218 		break;
1219 	}
1220 }
1221 
1222 bool
1223 unp_drop(struct unpcb *unp, int errno)
1224 {
1225 	struct socket *so = unp->unp_socket;
1226 
1227 	KASSERT(solocked(so));
1228 
1229 	so->so_error = errno;
1230 	unp_disconnect(unp);
1231 	if (so->so_head) {
1232 		so->so_pcb = NULL;
1233 		/* sofree() drops the socket lock */
1234 		sofree(so);
1235 		unp_free(unp);
1236 		return true;
1237 	}
1238 	return false;
1239 }
1240 
1241 #ifdef notdef
1242 unp_drain(void)
1243 {
1244 
1245 }
1246 #endif
1247 
1248 int
1249 unp_externalize(struct mbuf *rights, struct lwp *l, int flags)
1250 {
1251 	struct cmsghdr * const cm = mtod(rights, struct cmsghdr *);
1252 	struct proc * const p = l->l_proc;
1253 	file_t **rp;
1254 	int error = 0;
1255 
1256 	const size_t nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
1257 	    sizeof(file_t *);
1258 	if (nfds == 0)
1259 		goto noop;
1260 
1261 	int * const fdp = kmem_alloc(nfds * sizeof(int), KM_SLEEP);
1262 	rw_enter(&p->p_cwdi->cwdi_lock, RW_READER);
1263 
1264 	/* Make sure the recipient should be able to see the files.. */
1265 	rp = (file_t **)CMSG_DATA(cm);
1266 	for (size_t i = 0; i < nfds; i++) {
1267 		file_t * const fp = *rp++;
1268 		if (fp == NULL) {
1269 			error = EINVAL;
1270 			goto out;
1271 		}
1272 		/*
1273 		 * If we are in a chroot'ed directory, and
1274 		 * someone wants to pass us a directory, make
1275 		 * sure it's inside the subtree we're allowed
1276 		 * to access.
1277 		 */
1278 		if (p->p_cwdi->cwdi_rdir != NULL && fp->f_type == DTYPE_VNODE) {
1279 			vnode_t *vp = (vnode_t *)fp->f_data;
1280 			if ((vp->v_type == VDIR) &&
1281 			    !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
1282 				error = EPERM;
1283 				goto out;
1284 			}
1285 		}
1286 	}
1287 
1288  restart:
1289 	/*
1290 	 * First loop -- allocate file descriptor table slots for the
1291 	 * new files.
1292 	 */
1293 	for (size_t i = 0; i < nfds; i++) {
1294 		if ((error = fd_alloc(p, 0, &fdp[i])) != 0) {
1295 			/*
1296 			 * Back out what we've done so far.
1297 			 */
1298 			while (i-- > 0) {
1299 				fd_abort(p, NULL, fdp[i]);
1300 			}
1301 			if (error == ENOSPC) {
1302 				fd_tryexpand(p);
1303 				error = 0;
1304 				goto restart;
1305 			}
1306 			/*
1307 			 * This is the error that has historically
1308 			 * been returned, and some callers may
1309 			 * expect it.
1310 			 */
1311 			error = EMSGSIZE;
1312 			goto out;
1313 		}
1314 	}
1315 
1316 	/*
1317 	 * Now that adding them has succeeded, update all of the
1318 	 * file passing state and affix the descriptors.
1319 	 */
1320 	rp = (file_t **)CMSG_DATA(cm);
1321 	int *ofdp = (int *)CMSG_DATA(cm);
1322 	for (size_t i = 0; i < nfds; i++) {
1323 		file_t * const fp = *rp++;
1324 		const int fd = fdp[i];
1325 		atomic_dec_uint(&unp_rights);
1326 		fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
1327 		fd_affix(p, fp, fd);
1328 		/*
1329 		 * Done with this file pointer, replace it with a fd;
1330 		 */
1331 		*ofdp++ = fd;
1332 		mutex_enter(&fp->f_lock);
1333 		fp->f_msgcount--;
1334 		mutex_exit(&fp->f_lock);
1335 		/*
1336 		 * Note that fd_affix() adds a reference to the file.
1337 		 * The file may already have been closed by another
1338 		 * LWP in the process, so we must drop the reference
1339 		 * added by unp_internalize() with closef().
1340 		 */
1341 		closef(fp);
1342 	}
1343 
1344 	/*
1345 	 * Adjust length, in case of transition from large file_t
1346 	 * pointers to ints.
1347 	 */
1348 	if (sizeof(file_t *) != sizeof(int)) {
1349 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
1350 		rights->m_len = CMSG_SPACE(nfds * sizeof(int));
1351 	}
1352  out:
1353 	if (__predict_false(error != 0)) {
1354 		file_t **const fpp = (file_t **)CMSG_DATA(cm);
1355 		for (size_t i = 0; i < nfds; i++)
1356 			unp_discard_now(fpp[i]);
1357 		/*
1358 		 * Truncate the array so that nobody will try to interpret
1359 		 * what is now garbage in it.
1360 		 */
1361 		cm->cmsg_len = CMSG_LEN(0);
1362 		rights->m_len = CMSG_SPACE(0);
1363 	}
1364 	rw_exit(&p->p_cwdi->cwdi_lock);
1365 	kmem_free(fdp, nfds * sizeof(int));
1366 
1367  noop:
1368 	/*
1369 	 * Don't disclose kernel memory in the alignment space.
1370 	 */
1371 	KASSERT(cm->cmsg_len <= rights->m_len);
1372 	memset(&mtod(rights, char *)[cm->cmsg_len], 0, rights->m_len -
1373 	    cm->cmsg_len);
1374 	return error;
1375 }
1376 
1377 int
1378 unp_internalize(struct mbuf **controlp)
1379 {
1380 	filedesc_t *fdescp = curlwp->l_fd;
1381 	struct mbuf *control = *controlp;
1382 	struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
1383 	file_t **rp, **files;
1384 	file_t *fp;
1385 	int i, fd, *fdp;
1386 	int nfds, error;
1387 	u_int maxmsg;
1388 
1389 	error = 0;
1390 	newcm = NULL;
1391 
1392 	/* Sanity check the control message header. */
1393 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
1394 	    cm->cmsg_len > control->m_len ||
1395 	    cm->cmsg_len < CMSG_ALIGN(sizeof(*cm)))
1396 		return (EINVAL);
1397 
1398 	/*
1399 	 * Verify that the file descriptors are valid, and acquire
1400 	 * a reference to each.
1401 	 */
1402 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
1403 	fdp = (int *)CMSG_DATA(cm);
1404 	maxmsg = maxfiles / unp_rights_ratio;
1405 	for (i = 0; i < nfds; i++) {
1406 		fd = *fdp++;
1407 		if (atomic_inc_uint_nv(&unp_rights) > maxmsg) {
1408 			atomic_dec_uint(&unp_rights);
1409 			nfds = i;
1410 			error = EAGAIN;
1411 			goto out;
1412 		}
1413 		if ((fp = fd_getfile(fd)) == NULL
1414 		    || fp->f_type == DTYPE_KQUEUE) {
1415 		    	if (fp)
1416 		    		fd_putfile(fd);
1417 			atomic_dec_uint(&unp_rights);
1418 			nfds = i;
1419 			error = EBADF;
1420 			goto out;
1421 		}
1422 	}
1423 
1424 	/* Allocate new space and copy header into it. */
1425 	newcm = malloc(CMSG_SPACE(nfds * sizeof(file_t *)), M_MBUF, M_WAITOK);
1426 	if (newcm == NULL) {
1427 		error = E2BIG;
1428 		goto out;
1429 	}
1430 	memcpy(newcm, cm, sizeof(struct cmsghdr));
1431 	files = (file_t **)CMSG_DATA(newcm);
1432 
1433 	/*
1434 	 * Transform the file descriptors into file_t pointers, in
1435 	 * reverse order so that if pointers are bigger than ints, the
1436 	 * int won't get until we're done.  No need to lock, as we have
1437 	 * already validated the descriptors with fd_getfile().
1438 	 */
1439 	fdp = (int *)CMSG_DATA(cm) + nfds;
1440 	rp = files + nfds;
1441 	for (i = 0; i < nfds; i++) {
1442 		fp = fdescp->fd_dt->dt_ff[*--fdp]->ff_file;
1443 		KASSERT(fp != NULL);
1444 		mutex_enter(&fp->f_lock);
1445 		*--rp = fp;
1446 		fp->f_count++;
1447 		fp->f_msgcount++;
1448 		mutex_exit(&fp->f_lock);
1449 	}
1450 
1451  out:
1452  	/* Release descriptor references. */
1453 	fdp = (int *)CMSG_DATA(cm);
1454 	for (i = 0; i < nfds; i++) {
1455 		fd_putfile(*fdp++);
1456 		if (error != 0) {
1457 			atomic_dec_uint(&unp_rights);
1458 		}
1459 	}
1460 
1461 	if (error == 0) {
1462 		if (control->m_flags & M_EXT) {
1463 			m_freem(control);
1464 			*controlp = control = m_get(M_WAIT, MT_CONTROL);
1465 		}
1466 		MEXTADD(control, newcm, CMSG_SPACE(nfds * sizeof(file_t *)),
1467 		    M_MBUF, NULL, NULL);
1468 		cm = newcm;
1469 		/*
1470 		 * Adjust message & mbuf to note amount of space
1471 		 * actually used.
1472 		 */
1473 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(file_t *));
1474 		control->m_len = CMSG_SPACE(nfds * sizeof(file_t *));
1475 	}
1476 
1477 	return error;
1478 }
1479 
1480 struct mbuf *
1481 unp_addsockcred(struct lwp *l, struct mbuf *control)
1482 {
1483 	struct sockcred *sc;
1484 	struct mbuf *m;
1485 	void *p;
1486 
1487 	m = sbcreatecontrol1(&p, SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)),
1488 		SCM_CREDS, SOL_SOCKET, M_WAITOK);
1489 	if (m == NULL)
1490 		return control;
1491 
1492 	sc = p;
1493 	sc->sc_uid = kauth_cred_getuid(l->l_cred);
1494 	sc->sc_euid = kauth_cred_geteuid(l->l_cred);
1495 	sc->sc_gid = kauth_cred_getgid(l->l_cred);
1496 	sc->sc_egid = kauth_cred_getegid(l->l_cred);
1497 	sc->sc_ngroups = kauth_cred_ngroups(l->l_cred);
1498 
1499 	for (int i = 0; i < sc->sc_ngroups; i++)
1500 		sc->sc_groups[i] = kauth_cred_group(l->l_cred, i);
1501 
1502 	return m_add(control, m);
1503 }
1504 
1505 /*
1506  * Do a mark-sweep GC of files in the system, to free up any which are
1507  * caught in flight to an about-to-be-closed socket.  Additionally,
1508  * process deferred file closures.
1509  */
1510 static void
1511 unp_gc(file_t *dp)
1512 {
1513 	extern	struct domain unixdomain;
1514 	file_t *fp, *np;
1515 	struct socket *so, *so1;
1516 	u_int i, old, new;
1517 	bool didwork;
1518 
1519 	KASSERT(curlwp == unp_thread_lwp);
1520 	KASSERT(mutex_owned(&filelist_lock));
1521 
1522 	/*
1523 	 * First, process deferred file closures.
1524 	 */
1525 	while (!SLIST_EMPTY(&unp_thread_discard)) {
1526 		fp = SLIST_FIRST(&unp_thread_discard);
1527 		KASSERT(fp->f_unpcount > 0);
1528 		KASSERT(fp->f_count > 0);
1529 		KASSERT(fp->f_msgcount > 0);
1530 		KASSERT(fp->f_count >= fp->f_unpcount);
1531 		KASSERT(fp->f_count >= fp->f_msgcount);
1532 		KASSERT(fp->f_msgcount >= fp->f_unpcount);
1533 		SLIST_REMOVE_HEAD(&unp_thread_discard, f_unplist);
1534 		i = fp->f_unpcount;
1535 		fp->f_unpcount = 0;
1536 		mutex_exit(&filelist_lock);
1537 		for (; i != 0; i--) {
1538 			unp_discard_now(fp);
1539 		}
1540 		mutex_enter(&filelist_lock);
1541 	}
1542 
1543 	/*
1544 	 * Clear mark bits.  Ensure that we don't consider new files
1545 	 * entering the file table during this loop (they will not have
1546 	 * FSCAN set).
1547 	 */
1548 	unp_defer = 0;
1549 	LIST_FOREACH(fp, &filehead, f_list) {
1550 		for (old = fp->f_flag;; old = new) {
1551 			new = atomic_cas_uint(&fp->f_flag, old,
1552 			    (old | FSCAN) & ~(FMARK|FDEFER));
1553 			if (__predict_true(old == new)) {
1554 				break;
1555 			}
1556 		}
1557 	}
1558 
1559 	/*
1560 	 * Iterate over the set of sockets, marking ones believed (based on
1561 	 * refcount) to be referenced from a process, and marking for rescan
1562 	 * sockets which are queued on a socket.  Recan continues descending
1563 	 * and searching for sockets referenced by sockets (FDEFER), until
1564 	 * there are no more socket->socket references to be discovered.
1565 	 */
1566 	do {
1567 		didwork = false;
1568 		for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
1569 			KASSERT(mutex_owned(&filelist_lock));
1570 			np = LIST_NEXT(fp, f_list);
1571 			mutex_enter(&fp->f_lock);
1572 			if ((fp->f_flag & FDEFER) != 0) {
1573 				atomic_and_uint(&fp->f_flag, ~FDEFER);
1574 				unp_defer--;
1575 				KASSERT(fp->f_count != 0);
1576 			} else {
1577 				if (fp->f_count == 0 ||
1578 				    (fp->f_flag & FMARK) != 0 ||
1579 				    fp->f_count == fp->f_msgcount ||
1580 				    fp->f_unpcount != 0) {
1581 					mutex_exit(&fp->f_lock);
1582 					continue;
1583 				}
1584 			}
1585 			atomic_or_uint(&fp->f_flag, FMARK);
1586 
1587 			if (fp->f_type != DTYPE_SOCKET ||
1588 			    (so = fp->f_data) == NULL ||
1589 			    so->so_proto->pr_domain != &unixdomain ||
1590 			    (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1591 				mutex_exit(&fp->f_lock);
1592 				continue;
1593 			}
1594 
1595 			/* Gain file ref, mark our position, and unlock. */
1596 			didwork = true;
1597 			LIST_INSERT_AFTER(fp, dp, f_list);
1598 			fp->f_count++;
1599 			mutex_exit(&fp->f_lock);
1600 			mutex_exit(&filelist_lock);
1601 
1602 			/*
1603 			 * Mark files referenced from sockets queued on the
1604 			 * accept queue as well.
1605 			 */
1606 			solock(so);
1607 			unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
1608 			if ((so->so_options & SO_ACCEPTCONN) != 0) {
1609 				TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
1610 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1611 				}
1612 				TAILQ_FOREACH(so1, &so->so_q, so_qe) {
1613 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1614 				}
1615 			}
1616 			sounlock(so);
1617 
1618 			/* Re-lock and restart from where we left off. */
1619 			closef(fp);
1620 			mutex_enter(&filelist_lock);
1621 			np = LIST_NEXT(dp, f_list);
1622 			LIST_REMOVE(dp, f_list);
1623 		}
1624 		/*
1625 		 * Bail early if we did nothing in the loop above.  Could
1626 		 * happen because of concurrent activity causing unp_defer
1627 		 * to get out of sync.
1628 		 */
1629 	} while (unp_defer != 0 && didwork);
1630 
1631 	/*
1632 	 * Sweep pass.
1633 	 *
1634 	 * We grab an extra reference to each of the files that are
1635 	 * not otherwise accessible and then free the rights that are
1636 	 * stored in messages on them.
1637 	 */
1638 	for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
1639 		KASSERT(mutex_owned(&filelist_lock));
1640 		np = LIST_NEXT(fp, f_list);
1641 		mutex_enter(&fp->f_lock);
1642 
1643 		/*
1644 		 * Ignore non-sockets.
1645 		 * Ignore dead sockets, or sockets with pending close.
1646 		 * Ignore sockets obviously referenced elsewhere.
1647 		 * Ignore sockets marked as referenced by our scan.
1648 		 * Ignore new sockets that did not exist during the scan.
1649 		 */
1650 		if (fp->f_type != DTYPE_SOCKET ||
1651 		    fp->f_count == 0 || fp->f_unpcount != 0 ||
1652 		    fp->f_count != fp->f_msgcount ||
1653 		    (fp->f_flag & (FMARK | FSCAN)) != FSCAN) {
1654 			mutex_exit(&fp->f_lock);
1655 			continue;
1656 		}
1657 
1658 		/* Gain file ref, mark our position, and unlock. */
1659 		LIST_INSERT_AFTER(fp, dp, f_list);
1660 		fp->f_count++;
1661 		mutex_exit(&fp->f_lock);
1662 		mutex_exit(&filelist_lock);
1663 
1664 		/*
1665 		 * Flush all data from the socket's receive buffer.
1666 		 * This will cause files referenced only by the
1667 		 * socket to be queued for close.
1668 		 */
1669 		so = fp->f_data;
1670 		solock(so);
1671 		sorflush(so);
1672 		sounlock(so);
1673 
1674 		/* Re-lock and restart from where we left off. */
1675 		closef(fp);
1676 		mutex_enter(&filelist_lock);
1677 		np = LIST_NEXT(dp, f_list);
1678 		LIST_REMOVE(dp, f_list);
1679 	}
1680 }
1681 
1682 /*
1683  * Garbage collector thread.  While SCM_RIGHTS messages are in transit,
1684  * wake once per second to garbage collect.  Run continually while we
1685  * have deferred closes to process.
1686  */
1687 static void
1688 unp_thread(void *cookie)
1689 {
1690 	file_t *dp;
1691 
1692 	/* Allocate a dummy file for our scans. */
1693 	if ((dp = fgetdummy()) == NULL) {
1694 		panic("unp_thread");
1695 	}
1696 
1697 	mutex_enter(&filelist_lock);
1698 	for (;;) {
1699 		KASSERT(mutex_owned(&filelist_lock));
1700 		if (SLIST_EMPTY(&unp_thread_discard)) {
1701 			if (unp_rights != 0) {
1702 				(void)cv_timedwait(&unp_thread_cv,
1703 				    &filelist_lock, hz);
1704 			} else {
1705 				cv_wait(&unp_thread_cv, &filelist_lock);
1706 			}
1707 		}
1708 		unp_gc(dp);
1709 	}
1710 	/* NOTREACHED */
1711 }
1712 
1713 /*
1714  * Kick the garbage collector into action if there is something for
1715  * it to process.
1716  */
1717 static void
1718 unp_thread_kick(void)
1719 {
1720 
1721 	if (!SLIST_EMPTY(&unp_thread_discard) || unp_rights != 0) {
1722 		mutex_enter(&filelist_lock);
1723 		cv_signal(&unp_thread_cv);
1724 		mutex_exit(&filelist_lock);
1725 	}
1726 }
1727 
1728 void
1729 unp_dispose(struct mbuf *m)
1730 {
1731 
1732 	if (m)
1733 		unp_scan(m, unp_discard_later, 1);
1734 }
1735 
1736 void
1737 unp_scan(struct mbuf *m0, void (*op)(file_t *), int discard)
1738 {
1739 	struct mbuf *m;
1740 	file_t **rp, *fp;
1741 	struct cmsghdr *cm;
1742 	int i, qfds;
1743 
1744 	while (m0) {
1745 		for (m = m0; m; m = m->m_next) {
1746 			if (m->m_type != MT_CONTROL ||
1747 			    m->m_len < sizeof(*cm)) {
1748 			    	continue;
1749 			}
1750 			cm = mtod(m, struct cmsghdr *);
1751 			if (cm->cmsg_level != SOL_SOCKET ||
1752 			    cm->cmsg_type != SCM_RIGHTS)
1753 				continue;
1754 			qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
1755 			    / sizeof(file_t *);
1756 			rp = (file_t **)CMSG_DATA(cm);
1757 			for (i = 0; i < qfds; i++) {
1758 				fp = *rp;
1759 				if (discard) {
1760 					*rp = 0;
1761 				}
1762 				(*op)(fp);
1763 				rp++;
1764 			}
1765 		}
1766 		m0 = m0->m_nextpkt;
1767 	}
1768 }
1769 
1770 void
1771 unp_mark(file_t *fp)
1772 {
1773 
1774 	if (fp == NULL)
1775 		return;
1776 
1777 	/* If we're already deferred, don't screw up the defer count */
1778 	mutex_enter(&fp->f_lock);
1779 	if (fp->f_flag & (FMARK | FDEFER)) {
1780 		mutex_exit(&fp->f_lock);
1781 		return;
1782 	}
1783 
1784 	/*
1785 	 * Minimize the number of deferrals...  Sockets are the only type of
1786 	 * file which can hold references to another file, so just mark
1787 	 * other files, and defer unmarked sockets for the next pass.
1788 	 */
1789 	if (fp->f_type == DTYPE_SOCKET) {
1790 		unp_defer++;
1791 		KASSERT(fp->f_count != 0);
1792 		atomic_or_uint(&fp->f_flag, FDEFER);
1793 	} else {
1794 		atomic_or_uint(&fp->f_flag, FMARK);
1795 	}
1796 	mutex_exit(&fp->f_lock);
1797 }
1798 
1799 static void
1800 unp_discard_now(file_t *fp)
1801 {
1802 
1803 	if (fp == NULL)
1804 		return;
1805 
1806 	KASSERT(fp->f_count > 0);
1807 	KASSERT(fp->f_msgcount > 0);
1808 
1809 	mutex_enter(&fp->f_lock);
1810 	fp->f_msgcount--;
1811 	mutex_exit(&fp->f_lock);
1812 	atomic_dec_uint(&unp_rights);
1813 	(void)closef(fp);
1814 }
1815 
1816 static void
1817 unp_discard_later(file_t *fp)
1818 {
1819 
1820 	if (fp == NULL)
1821 		return;
1822 
1823 	KASSERT(fp->f_count > 0);
1824 	KASSERT(fp->f_msgcount > 0);
1825 
1826 	mutex_enter(&filelist_lock);
1827 	if (fp->f_unpcount++ == 0) {
1828 		SLIST_INSERT_HEAD(&unp_thread_discard, fp, f_unplist);
1829 	}
1830 	mutex_exit(&filelist_lock);
1831 }
1832