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