xref: /netbsd-src/sys/kern/uipc_usrreq.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: uipc_usrreq.c,v 1.148 2013/10/29 09:53:51 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.148 2013/10/29 09:53:51 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 		pathbuf_destroy(pb);
966 		goto bad;
967 	}
968 	vp = nd.ni_vp;
969 	solock(so);
970 	vp->v_socket = unp->unp_socket;
971 	unp->unp_vnode = vp;
972 	unp->unp_addrlen = addrlen;
973 	unp->unp_addr = sun;
974 	unp->unp_connid.unp_pid = p->p_pid;
975 	unp->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
976 	unp->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
977 	unp->unp_flags |= UNP_EIDSBIND;
978 	VOP_UNLOCK(vp);
979 	unp->unp_flags &= ~UNP_BUSY;
980 	pathbuf_destroy(pb);
981 	return (0);
982 
983  bad:
984 	free(sun, M_SONAME);
985 	solock(so);
986 	unp->unp_flags &= ~UNP_BUSY;
987 	return (error);
988 }
989 
990 int
991 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
992 {
993 	struct sockaddr_un *sun;
994 	vnode_t *vp;
995 	struct socket *so2, *so3;
996 	struct unpcb *unp, *unp2, *unp3;
997 	size_t addrlen;
998 	int error;
999 	struct pathbuf *pb;
1000 	struct nameidata nd;
1001 
1002 	unp = sotounpcb(so);
1003 	if ((unp->unp_flags & UNP_BUSY) != 0) {
1004 		/*
1005 		 * EALREADY may not be strictly accurate, but since this
1006 		 * is a major application error it's hardly a big deal.
1007 		 */
1008 		return (EALREADY);
1009 	}
1010 	unp->unp_flags |= UNP_BUSY;
1011 	sounlock(so);
1012 
1013 	sun = makeun(nam, &addrlen);
1014 	pb = pathbuf_create(sun->sun_path);
1015 	if (pb == NULL) {
1016 		error = ENOMEM;
1017 		goto bad2;
1018 	}
1019 
1020 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
1021 
1022 	if ((error = namei(&nd)) != 0) {
1023 		pathbuf_destroy(pb);
1024 		goto bad2;
1025 	}
1026 	vp = nd.ni_vp;
1027 	if (vp->v_type != VSOCK) {
1028 		error = ENOTSOCK;
1029 		goto bad;
1030 	}
1031 	pathbuf_destroy(pb);
1032 	if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred)) != 0)
1033 		goto bad;
1034 	/* Acquire v_interlock to protect against unp_detach(). */
1035 	mutex_enter(vp->v_interlock);
1036 	so2 = vp->v_socket;
1037 	if (so2 == NULL) {
1038 		mutex_exit(vp->v_interlock);
1039 		error = ECONNREFUSED;
1040 		goto bad;
1041 	}
1042 	if (so->so_type != so2->so_type) {
1043 		mutex_exit(vp->v_interlock);
1044 		error = EPROTOTYPE;
1045 		goto bad;
1046 	}
1047 	solock(so);
1048 	unp_resetlock(so);
1049 	mutex_exit(vp->v_interlock);
1050 	if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
1051 		/*
1052 		 * This may seem somewhat fragile but is OK: if we can
1053 		 * see SO_ACCEPTCONN set on the endpoint, then it must
1054 		 * be locked by the domain-wide uipc_lock.
1055 		 */
1056 		KASSERT((so2->so_options & SO_ACCEPTCONN) == 0 ||
1057 		    so2->so_lock == uipc_lock);
1058 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
1059 		    (so3 = sonewconn(so2, false)) == NULL) {
1060 			error = ECONNREFUSED;
1061 			sounlock(so);
1062 			goto bad;
1063 		}
1064 		unp2 = sotounpcb(so2);
1065 		unp3 = sotounpcb(so3);
1066 		if (unp2->unp_addr) {
1067 			unp3->unp_addr = malloc(unp2->unp_addrlen,
1068 			    M_SONAME, M_WAITOK);
1069 			memcpy(unp3->unp_addr, unp2->unp_addr,
1070 			    unp2->unp_addrlen);
1071 			unp3->unp_addrlen = unp2->unp_addrlen;
1072 		}
1073 		unp3->unp_flags = unp2->unp_flags;
1074 		unp3->unp_connid.unp_pid = l->l_proc->p_pid;
1075 		unp3->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred);
1076 		unp3->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred);
1077 		unp3->unp_flags |= UNP_EIDSVALID;
1078 		if (unp2->unp_flags & UNP_EIDSBIND) {
1079 			unp->unp_connid = unp2->unp_connid;
1080 			unp->unp_flags |= UNP_EIDSVALID;
1081 		}
1082 		so2 = so3;
1083 	}
1084 	error = unp_connect2(so, so2, PRU_CONNECT);
1085 	sounlock(so);
1086  bad:
1087 	vput(vp);
1088  bad2:
1089 	free(sun, M_SONAME);
1090 	solock(so);
1091 	unp->unp_flags &= ~UNP_BUSY;
1092 	return (error);
1093 }
1094 
1095 int
1096 unp_connect2(struct socket *so, struct socket *so2, int req)
1097 {
1098 	struct unpcb *unp = sotounpcb(so);
1099 	struct unpcb *unp2;
1100 
1101 	if (so2->so_type != so->so_type)
1102 		return (EPROTOTYPE);
1103 
1104 	/*
1105 	 * All three sockets involved must be locked by same lock:
1106 	 *
1107 	 * local endpoint (so)
1108 	 * remote endpoint (so2)
1109 	 * queue head (so2->so_head, only if PR_CONNREQUIRED)
1110 	 */
1111 	KASSERT(solocked2(so, so2));
1112 	KASSERT(so->so_head == NULL);
1113 	if (so2->so_head != NULL) {
1114 		KASSERT(so2->so_lock == uipc_lock);
1115 		KASSERT(solocked2(so2, so2->so_head));
1116 	}
1117 
1118 	unp2 = sotounpcb(so2);
1119 	unp->unp_conn = unp2;
1120 	switch (so->so_type) {
1121 
1122 	case SOCK_DGRAM:
1123 		unp->unp_nextref = unp2->unp_refs;
1124 		unp2->unp_refs = unp;
1125 		soisconnected(so);
1126 		break;
1127 
1128 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1129 	case SOCK_STREAM:
1130 		unp2->unp_conn = unp;
1131 		if (req == PRU_CONNECT &&
1132 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1133 			soisconnecting(so);
1134 		else
1135 			soisconnected(so);
1136 		soisconnected(so2);
1137 		/*
1138 		 * If the connection is fully established, break the
1139 		 * association with uipc_lock and give the connected
1140 		 * pair a seperate lock to share.  For CONNECT2, we
1141 		 * require that the locks already match (the sockets
1142 		 * are created that way).
1143 		 */
1144 		if (req == PRU_CONNECT) {
1145 			KASSERT(so2->so_head != NULL);
1146 			unp_setpeerlocks(so, so2);
1147 		}
1148 		break;
1149 
1150 	default:
1151 		panic("unp_connect2");
1152 	}
1153 	return (0);
1154 }
1155 
1156 void
1157 unp_disconnect(struct unpcb *unp)
1158 {
1159 	struct unpcb *unp2 = unp->unp_conn;
1160 	struct socket *so;
1161 
1162 	if (unp2 == 0)
1163 		return;
1164 	unp->unp_conn = 0;
1165 	so = unp->unp_socket;
1166 	switch (so->so_type) {
1167 	case SOCK_DGRAM:
1168 		if (unp2->unp_refs == unp)
1169 			unp2->unp_refs = unp->unp_nextref;
1170 		else {
1171 			unp2 = unp2->unp_refs;
1172 			for (;;) {
1173 				KASSERT(solocked2(so, unp2->unp_socket));
1174 				if (unp2 == 0)
1175 					panic("unp_disconnect");
1176 				if (unp2->unp_nextref == unp)
1177 					break;
1178 				unp2 = unp2->unp_nextref;
1179 			}
1180 			unp2->unp_nextref = unp->unp_nextref;
1181 		}
1182 		unp->unp_nextref = 0;
1183 		so->so_state &= ~SS_ISCONNECTED;
1184 		break;
1185 
1186 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1187 	case SOCK_STREAM:
1188 		KASSERT(solocked2(so, unp2->unp_socket));
1189 		soisdisconnected(so);
1190 		unp2->unp_conn = 0;
1191 		soisdisconnected(unp2->unp_socket);
1192 		break;
1193 	}
1194 }
1195 
1196 #ifdef notdef
1197 unp_abort(struct unpcb *unp)
1198 {
1199 	unp_detach(unp);
1200 }
1201 #endif
1202 
1203 void
1204 unp_shutdown(struct unpcb *unp)
1205 {
1206 	struct socket *so;
1207 
1208 	switch(unp->unp_socket->so_type) {
1209 	case SOCK_SEQPACKET: /* FALLTHROUGH */
1210 	case SOCK_STREAM:
1211 		if (unp->unp_conn && (so = unp->unp_conn->unp_socket))
1212 			socantrcvmore(so);
1213 		break;
1214 	default:
1215 		break;
1216 	}
1217 }
1218 
1219 bool
1220 unp_drop(struct unpcb *unp, int errno)
1221 {
1222 	struct socket *so = unp->unp_socket;
1223 
1224 	KASSERT(solocked(so));
1225 
1226 	so->so_error = errno;
1227 	unp_disconnect(unp);
1228 	if (so->so_head) {
1229 		so->so_pcb = NULL;
1230 		/* sofree() drops the socket lock */
1231 		sofree(so);
1232 		unp_free(unp);
1233 		return true;
1234 	}
1235 	return false;
1236 }
1237 
1238 #ifdef notdef
1239 unp_drain(void)
1240 {
1241 
1242 }
1243 #endif
1244 
1245 int
1246 unp_externalize(struct mbuf *rights, struct lwp *l, int flags)
1247 {
1248 	struct cmsghdr * const cm = mtod(rights, struct cmsghdr *);
1249 	struct proc * const p = l->l_proc;
1250 	file_t **rp;
1251 	int error = 0;
1252 
1253 	const size_t nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
1254 	    sizeof(file_t *);
1255 	if (nfds == 0)
1256 		goto noop;
1257 
1258 	int * const fdp = kmem_alloc(nfds * sizeof(int), KM_SLEEP);
1259 	rw_enter(&p->p_cwdi->cwdi_lock, RW_READER);
1260 
1261 	/* Make sure the recipient should be able to see the files.. */
1262 	rp = (file_t **)CMSG_DATA(cm);
1263 	for (size_t i = 0; i < nfds; i++) {
1264 		file_t * const fp = *rp++;
1265 		if (fp == NULL) {
1266 			error = EINVAL;
1267 			goto out;
1268 		}
1269 		/*
1270 		 * If we are in a chroot'ed directory, and
1271 		 * someone wants to pass us a directory, make
1272 		 * sure it's inside the subtree we're allowed
1273 		 * to access.
1274 		 */
1275 		if (p->p_cwdi->cwdi_rdir != NULL && fp->f_type == DTYPE_VNODE) {
1276 			vnode_t *vp = (vnode_t *)fp->f_data;
1277 			if ((vp->v_type == VDIR) &&
1278 			    !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
1279 				error = EPERM;
1280 				goto out;
1281 			}
1282 		}
1283 	}
1284 
1285  restart:
1286 	/*
1287 	 * First loop -- allocate file descriptor table slots for the
1288 	 * new files.
1289 	 */
1290 	for (size_t i = 0; i < nfds; i++) {
1291 		if ((error = fd_alloc(p, 0, &fdp[i])) != 0) {
1292 			/*
1293 			 * Back out what we've done so far.
1294 			 */
1295 			while (i-- > 0) {
1296 				fd_abort(p, NULL, fdp[i]);
1297 			}
1298 			if (error == ENOSPC) {
1299 				fd_tryexpand(p);
1300 				error = 0;
1301 				goto restart;
1302 			}
1303 			/*
1304 			 * This is the error that has historically
1305 			 * been returned, and some callers may
1306 			 * expect it.
1307 			 */
1308 			error = EMSGSIZE;
1309 			goto out;
1310 		}
1311 	}
1312 
1313 	/*
1314 	 * Now that adding them has succeeded, update all of the
1315 	 * file passing state and affix the descriptors.
1316 	 */
1317 	rp = (file_t **)CMSG_DATA(cm);
1318 	int *ofdp = (int *)CMSG_DATA(cm);
1319 	for (size_t i = 0; i < nfds; i++) {
1320 		file_t * const fp = *rp++;
1321 		const int fd = fdp[i];
1322 		atomic_dec_uint(&unp_rights);
1323 		fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
1324 		fd_affix(p, fp, fd);
1325 		/*
1326 		 * Done with this file pointer, replace it with a fd;
1327 		 */
1328 		*ofdp++ = fd;
1329 		mutex_enter(&fp->f_lock);
1330 		fp->f_msgcount--;
1331 		mutex_exit(&fp->f_lock);
1332 		/*
1333 		 * Note that fd_affix() adds a reference to the file.
1334 		 * The file may already have been closed by another
1335 		 * LWP in the process, so we must drop the reference
1336 		 * added by unp_internalize() with closef().
1337 		 */
1338 		closef(fp);
1339 	}
1340 
1341 	/*
1342 	 * Adjust length, in case of transition from large file_t
1343 	 * pointers to ints.
1344 	 */
1345 	if (sizeof(file_t *) != sizeof(int)) {
1346 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
1347 		rights->m_len = CMSG_SPACE(nfds * sizeof(int));
1348 	}
1349  out:
1350 	if (__predict_false(error != 0)) {
1351 		file_t **const fpp = (file_t **)CMSG_DATA(cm);
1352 		for (size_t i = 0; i < nfds; i++)
1353 			unp_discard_now(fpp[i]);
1354 		/*
1355 		 * Truncate the array so that nobody will try to interpret
1356 		 * what is now garbage in it.
1357 		 */
1358 		cm->cmsg_len = CMSG_LEN(0);
1359 		rights->m_len = CMSG_SPACE(0);
1360 	}
1361 	rw_exit(&p->p_cwdi->cwdi_lock);
1362 	kmem_free(fdp, nfds * sizeof(int));
1363 
1364  noop:
1365 	/*
1366 	 * Don't disclose kernel memory in the alignment space.
1367 	 */
1368 	KASSERT(cm->cmsg_len <= rights->m_len);
1369 	memset(&mtod(rights, char *)[cm->cmsg_len], 0, rights->m_len -
1370 	    cm->cmsg_len);
1371 	return error;
1372 }
1373 
1374 int
1375 unp_internalize(struct mbuf **controlp)
1376 {
1377 	filedesc_t *fdescp = curlwp->l_fd;
1378 	struct mbuf *control = *controlp;
1379 	struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
1380 	file_t **rp, **files;
1381 	file_t *fp;
1382 	int i, fd, *fdp;
1383 	int nfds, error;
1384 	u_int maxmsg;
1385 
1386 	error = 0;
1387 	newcm = NULL;
1388 
1389 	/* Sanity check the control message header. */
1390 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
1391 	    cm->cmsg_len > control->m_len ||
1392 	    cm->cmsg_len < CMSG_ALIGN(sizeof(*cm)))
1393 		return (EINVAL);
1394 
1395 	/*
1396 	 * Verify that the file descriptors are valid, and acquire
1397 	 * a reference to each.
1398 	 */
1399 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
1400 	fdp = (int *)CMSG_DATA(cm);
1401 	maxmsg = maxfiles / unp_rights_ratio;
1402 	for (i = 0; i < nfds; i++) {
1403 		fd = *fdp++;
1404 		if (atomic_inc_uint_nv(&unp_rights) > maxmsg) {
1405 			atomic_dec_uint(&unp_rights);
1406 			nfds = i;
1407 			error = EAGAIN;
1408 			goto out;
1409 		}
1410 		if ((fp = fd_getfile(fd)) == NULL
1411 		    || fp->f_type == DTYPE_KQUEUE) {
1412 		    	if (fp)
1413 		    		fd_putfile(fd);
1414 			atomic_dec_uint(&unp_rights);
1415 			nfds = i;
1416 			error = EBADF;
1417 			goto out;
1418 		}
1419 	}
1420 
1421 	/* Allocate new space and copy header into it. */
1422 	newcm = malloc(CMSG_SPACE(nfds * sizeof(file_t *)), M_MBUF, M_WAITOK);
1423 	if (newcm == NULL) {
1424 		error = E2BIG;
1425 		goto out;
1426 	}
1427 	memcpy(newcm, cm, sizeof(struct cmsghdr));
1428 	files = (file_t **)CMSG_DATA(newcm);
1429 
1430 	/*
1431 	 * Transform the file descriptors into file_t pointers, in
1432 	 * reverse order so that if pointers are bigger than ints, the
1433 	 * int won't get until we're done.  No need to lock, as we have
1434 	 * already validated the descriptors with fd_getfile().
1435 	 */
1436 	fdp = (int *)CMSG_DATA(cm) + nfds;
1437 	rp = files + nfds;
1438 	for (i = 0; i < nfds; i++) {
1439 		fp = fdescp->fd_dt->dt_ff[*--fdp]->ff_file;
1440 		KASSERT(fp != NULL);
1441 		mutex_enter(&fp->f_lock);
1442 		*--rp = fp;
1443 		fp->f_count++;
1444 		fp->f_msgcount++;
1445 		mutex_exit(&fp->f_lock);
1446 	}
1447 
1448  out:
1449  	/* Release descriptor references. */
1450 	fdp = (int *)CMSG_DATA(cm);
1451 	for (i = 0; i < nfds; i++) {
1452 		fd_putfile(*fdp++);
1453 		if (error != 0) {
1454 			atomic_dec_uint(&unp_rights);
1455 		}
1456 	}
1457 
1458 	if (error == 0) {
1459 		if (control->m_flags & M_EXT) {
1460 			m_freem(control);
1461 			*controlp = control = m_get(M_WAIT, MT_CONTROL);
1462 		}
1463 		MEXTADD(control, newcm, CMSG_SPACE(nfds * sizeof(file_t *)),
1464 		    M_MBUF, NULL, NULL);
1465 		cm = newcm;
1466 		/*
1467 		 * Adjust message & mbuf to note amount of space
1468 		 * actually used.
1469 		 */
1470 		cm->cmsg_len = CMSG_LEN(nfds * sizeof(file_t *));
1471 		control->m_len = CMSG_SPACE(nfds * sizeof(file_t *));
1472 	}
1473 
1474 	return error;
1475 }
1476 
1477 struct mbuf *
1478 unp_addsockcred(struct lwp *l, struct mbuf *control)
1479 {
1480 	struct sockcred *sc;
1481 	struct mbuf *m;
1482 	void *p;
1483 
1484 	m = sbcreatecontrol1(&p, SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)),
1485 		SCM_CREDS, SOL_SOCKET, M_WAITOK);
1486 	if (m == NULL)
1487 		return control;
1488 
1489 	sc = p;
1490 	sc->sc_uid = kauth_cred_getuid(l->l_cred);
1491 	sc->sc_euid = kauth_cred_geteuid(l->l_cred);
1492 	sc->sc_gid = kauth_cred_getgid(l->l_cred);
1493 	sc->sc_egid = kauth_cred_getegid(l->l_cred);
1494 	sc->sc_ngroups = kauth_cred_ngroups(l->l_cred);
1495 
1496 	for (int i = 0; i < sc->sc_ngroups; i++)
1497 		sc->sc_groups[i] = kauth_cred_group(l->l_cred, i);
1498 
1499 	return m_add(control, m);
1500 }
1501 
1502 /*
1503  * Do a mark-sweep GC of files in the system, to free up any which are
1504  * caught in flight to an about-to-be-closed socket.  Additionally,
1505  * process deferred file closures.
1506  */
1507 static void
1508 unp_gc(file_t *dp)
1509 {
1510 	extern	struct domain unixdomain;
1511 	file_t *fp, *np;
1512 	struct socket *so, *so1;
1513 	u_int i, old, new;
1514 	bool didwork;
1515 
1516 	KASSERT(curlwp == unp_thread_lwp);
1517 	KASSERT(mutex_owned(&filelist_lock));
1518 
1519 	/*
1520 	 * First, process deferred file closures.
1521 	 */
1522 	while (!SLIST_EMPTY(&unp_thread_discard)) {
1523 		fp = SLIST_FIRST(&unp_thread_discard);
1524 		KASSERT(fp->f_unpcount > 0);
1525 		KASSERT(fp->f_count > 0);
1526 		KASSERT(fp->f_msgcount > 0);
1527 		KASSERT(fp->f_count >= fp->f_unpcount);
1528 		KASSERT(fp->f_count >= fp->f_msgcount);
1529 		KASSERT(fp->f_msgcount >= fp->f_unpcount);
1530 		SLIST_REMOVE_HEAD(&unp_thread_discard, f_unplist);
1531 		i = fp->f_unpcount;
1532 		fp->f_unpcount = 0;
1533 		mutex_exit(&filelist_lock);
1534 		for (; i != 0; i--) {
1535 			unp_discard_now(fp);
1536 		}
1537 		mutex_enter(&filelist_lock);
1538 	}
1539 
1540 	/*
1541 	 * Clear mark bits.  Ensure that we don't consider new files
1542 	 * entering the file table during this loop (they will not have
1543 	 * FSCAN set).
1544 	 */
1545 	unp_defer = 0;
1546 	LIST_FOREACH(fp, &filehead, f_list) {
1547 		for (old = fp->f_flag;; old = new) {
1548 			new = atomic_cas_uint(&fp->f_flag, old,
1549 			    (old | FSCAN) & ~(FMARK|FDEFER));
1550 			if (__predict_true(old == new)) {
1551 				break;
1552 			}
1553 		}
1554 	}
1555 
1556 	/*
1557 	 * Iterate over the set of sockets, marking ones believed (based on
1558 	 * refcount) to be referenced from a process, and marking for rescan
1559 	 * sockets which are queued on a socket.  Recan continues descending
1560 	 * and searching for sockets referenced by sockets (FDEFER), until
1561 	 * there are no more socket->socket references to be discovered.
1562 	 */
1563 	do {
1564 		didwork = false;
1565 		for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
1566 			KASSERT(mutex_owned(&filelist_lock));
1567 			np = LIST_NEXT(fp, f_list);
1568 			mutex_enter(&fp->f_lock);
1569 			if ((fp->f_flag & FDEFER) != 0) {
1570 				atomic_and_uint(&fp->f_flag, ~FDEFER);
1571 				unp_defer--;
1572 				KASSERT(fp->f_count != 0);
1573 			} else {
1574 				if (fp->f_count == 0 ||
1575 				    (fp->f_flag & FMARK) != 0 ||
1576 				    fp->f_count == fp->f_msgcount ||
1577 				    fp->f_unpcount != 0) {
1578 					mutex_exit(&fp->f_lock);
1579 					continue;
1580 				}
1581 			}
1582 			atomic_or_uint(&fp->f_flag, FMARK);
1583 
1584 			if (fp->f_type != DTYPE_SOCKET ||
1585 			    (so = fp->f_data) == NULL ||
1586 			    so->so_proto->pr_domain != &unixdomain ||
1587 			    (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1588 				mutex_exit(&fp->f_lock);
1589 				continue;
1590 			}
1591 
1592 			/* Gain file ref, mark our position, and unlock. */
1593 			didwork = true;
1594 			LIST_INSERT_AFTER(fp, dp, f_list);
1595 			fp->f_count++;
1596 			mutex_exit(&fp->f_lock);
1597 			mutex_exit(&filelist_lock);
1598 
1599 			/*
1600 			 * Mark files referenced from sockets queued on the
1601 			 * accept queue as well.
1602 			 */
1603 			solock(so);
1604 			unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
1605 			if ((so->so_options & SO_ACCEPTCONN) != 0) {
1606 				TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
1607 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1608 				}
1609 				TAILQ_FOREACH(so1, &so->so_q, so_qe) {
1610 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1611 				}
1612 			}
1613 			sounlock(so);
1614 
1615 			/* Re-lock and restart from where we left off. */
1616 			closef(fp);
1617 			mutex_enter(&filelist_lock);
1618 			np = LIST_NEXT(dp, f_list);
1619 			LIST_REMOVE(dp, f_list);
1620 		}
1621 		/*
1622 		 * Bail early if we did nothing in the loop above.  Could
1623 		 * happen because of concurrent activity causing unp_defer
1624 		 * to get out of sync.
1625 		 */
1626 	} while (unp_defer != 0 && didwork);
1627 
1628 	/*
1629 	 * Sweep pass.
1630 	 *
1631 	 * We grab an extra reference to each of the files that are
1632 	 * not otherwise accessible and then free the rights that are
1633 	 * stored in messages on them.
1634 	 */
1635 	for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) {
1636 		KASSERT(mutex_owned(&filelist_lock));
1637 		np = LIST_NEXT(fp, f_list);
1638 		mutex_enter(&fp->f_lock);
1639 
1640 		/*
1641 		 * Ignore non-sockets.
1642 		 * Ignore dead sockets, or sockets with pending close.
1643 		 * Ignore sockets obviously referenced elsewhere.
1644 		 * Ignore sockets marked as referenced by our scan.
1645 		 * Ignore new sockets that did not exist during the scan.
1646 		 */
1647 		if (fp->f_type != DTYPE_SOCKET ||
1648 		    fp->f_count == 0 || fp->f_unpcount != 0 ||
1649 		    fp->f_count != fp->f_msgcount ||
1650 		    (fp->f_flag & (FMARK | FSCAN)) != FSCAN) {
1651 			mutex_exit(&fp->f_lock);
1652 			continue;
1653 		}
1654 
1655 		/* Gain file ref, mark our position, and unlock. */
1656 		LIST_INSERT_AFTER(fp, dp, f_list);
1657 		fp->f_count++;
1658 		mutex_exit(&fp->f_lock);
1659 		mutex_exit(&filelist_lock);
1660 
1661 		/*
1662 		 * Flush all data from the socket's receive buffer.
1663 		 * This will cause files referenced only by the
1664 		 * socket to be queued for close.
1665 		 */
1666 		so = fp->f_data;
1667 		solock(so);
1668 		sorflush(so);
1669 		sounlock(so);
1670 
1671 		/* Re-lock and restart from where we left off. */
1672 		closef(fp);
1673 		mutex_enter(&filelist_lock);
1674 		np = LIST_NEXT(dp, f_list);
1675 		LIST_REMOVE(dp, f_list);
1676 	}
1677 }
1678 
1679 /*
1680  * Garbage collector thread.  While SCM_RIGHTS messages are in transit,
1681  * wake once per second to garbage collect.  Run continually while we
1682  * have deferred closes to process.
1683  */
1684 static void
1685 unp_thread(void *cookie)
1686 {
1687 	file_t *dp;
1688 
1689 	/* Allocate a dummy file for our scans. */
1690 	if ((dp = fgetdummy()) == NULL) {
1691 		panic("unp_thread");
1692 	}
1693 
1694 	mutex_enter(&filelist_lock);
1695 	for (;;) {
1696 		KASSERT(mutex_owned(&filelist_lock));
1697 		if (SLIST_EMPTY(&unp_thread_discard)) {
1698 			if (unp_rights != 0) {
1699 				(void)cv_timedwait(&unp_thread_cv,
1700 				    &filelist_lock, hz);
1701 			} else {
1702 				cv_wait(&unp_thread_cv, &filelist_lock);
1703 			}
1704 		}
1705 		unp_gc(dp);
1706 	}
1707 	/* NOTREACHED */
1708 }
1709 
1710 /*
1711  * Kick the garbage collector into action if there is something for
1712  * it to process.
1713  */
1714 static void
1715 unp_thread_kick(void)
1716 {
1717 
1718 	if (!SLIST_EMPTY(&unp_thread_discard) || unp_rights != 0) {
1719 		mutex_enter(&filelist_lock);
1720 		cv_signal(&unp_thread_cv);
1721 		mutex_exit(&filelist_lock);
1722 	}
1723 }
1724 
1725 void
1726 unp_dispose(struct mbuf *m)
1727 {
1728 
1729 	if (m)
1730 		unp_scan(m, unp_discard_later, 1);
1731 }
1732 
1733 void
1734 unp_scan(struct mbuf *m0, void (*op)(file_t *), int discard)
1735 {
1736 	struct mbuf *m;
1737 	file_t **rp, *fp;
1738 	struct cmsghdr *cm;
1739 	int i, qfds;
1740 
1741 	while (m0) {
1742 		for (m = m0; m; m = m->m_next) {
1743 			if (m->m_type != MT_CONTROL ||
1744 			    m->m_len < sizeof(*cm)) {
1745 			    	continue;
1746 			}
1747 			cm = mtod(m, struct cmsghdr *);
1748 			if (cm->cmsg_level != SOL_SOCKET ||
1749 			    cm->cmsg_type != SCM_RIGHTS)
1750 				continue;
1751 			qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
1752 			    / sizeof(file_t *);
1753 			rp = (file_t **)CMSG_DATA(cm);
1754 			for (i = 0; i < qfds; i++) {
1755 				fp = *rp;
1756 				if (discard) {
1757 					*rp = 0;
1758 				}
1759 				(*op)(fp);
1760 				rp++;
1761 			}
1762 		}
1763 		m0 = m0->m_nextpkt;
1764 	}
1765 }
1766 
1767 void
1768 unp_mark(file_t *fp)
1769 {
1770 
1771 	if (fp == NULL)
1772 		return;
1773 
1774 	/* If we're already deferred, don't screw up the defer count */
1775 	mutex_enter(&fp->f_lock);
1776 	if (fp->f_flag & (FMARK | FDEFER)) {
1777 		mutex_exit(&fp->f_lock);
1778 		return;
1779 	}
1780 
1781 	/*
1782 	 * Minimize the number of deferrals...  Sockets are the only type of
1783 	 * file which can hold references to another file, so just mark
1784 	 * other files, and defer unmarked sockets for the next pass.
1785 	 */
1786 	if (fp->f_type == DTYPE_SOCKET) {
1787 		unp_defer++;
1788 		KASSERT(fp->f_count != 0);
1789 		atomic_or_uint(&fp->f_flag, FDEFER);
1790 	} else {
1791 		atomic_or_uint(&fp->f_flag, FMARK);
1792 	}
1793 	mutex_exit(&fp->f_lock);
1794 }
1795 
1796 static void
1797 unp_discard_now(file_t *fp)
1798 {
1799 
1800 	if (fp == NULL)
1801 		return;
1802 
1803 	KASSERT(fp->f_count > 0);
1804 	KASSERT(fp->f_msgcount > 0);
1805 
1806 	mutex_enter(&fp->f_lock);
1807 	fp->f_msgcount--;
1808 	mutex_exit(&fp->f_lock);
1809 	atomic_dec_uint(&unp_rights);
1810 	(void)closef(fp);
1811 }
1812 
1813 static void
1814 unp_discard_later(file_t *fp)
1815 {
1816 
1817 	if (fp == NULL)
1818 		return;
1819 
1820 	KASSERT(fp->f_count > 0);
1821 	KASSERT(fp->f_msgcount > 0);
1822 
1823 	mutex_enter(&filelist_lock);
1824 	if (fp->f_unpcount++ == 0) {
1825 		SLIST_INSERT_HEAD(&unp_thread_discard, fp, f_unplist);
1826 	}
1827 	mutex_exit(&filelist_lock);
1828 }
1829