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