xref: /openbsd-src/sys/kern/uipc_usrreq.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /*	$OpenBSD: uipc_usrreq.c,v 1.199 2023/03/31 12:35:24 jsg Exp $	*/
2 /*	$NetBSD: uipc_usrreq.c,v 1.18 1996/02/09 19:00:50 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/proc.h>
38 #include <sys/filedesc.h>
39 #include <sys/domain.h>
40 #include <sys/protosw.h>
41 #include <sys/queue.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/unpcb.h>
45 #include <sys/un.h>
46 #include <sys/namei.h>
47 #include <sys/vnode.h>
48 #include <sys/file.h>
49 #include <sys/stat.h>
50 #include <sys/mbuf.h>
51 #include <sys/task.h>
52 #include <sys/pledge.h>
53 #include <sys/pool.h>
54 #include <sys/rwlock.h>
55 #include <sys/mutex.h>
56 #include <sys/sysctl.h>
57 #include <sys/lock.h>
58 #include <sys/refcnt.h>
59 
60 #include "kcov.h"
61 #if NKCOV > 0
62 #include <sys/kcov.h>
63 #endif
64 
65 /*
66  * Locks used to protect global data and struct members:
67  *      I       immutable after creation
68  *      D       unp_df_lock
69  *      G       unp_gc_lock
70  *      M       unp_ino_mtx
71  *      R       unp_rights_mtx
72  *      a       atomic
73  *      s       socket lock
74  */
75 
76 struct rwlock unp_df_lock = RWLOCK_INITIALIZER("unpdflk");
77 struct rwlock unp_gc_lock = RWLOCK_INITIALIZER("unpgclk");
78 
79 struct mutex unp_rights_mtx = MUTEX_INITIALIZER(IPL_SOFTNET);
80 struct mutex unp_ino_mtx = MUTEX_INITIALIZER(IPL_SOFTNET);
81 
82 /*
83  * Stack of sets of files that were passed over a socket but were
84  * not received and need to be closed.
85  */
86 struct	unp_deferral {
87 	SLIST_ENTRY(unp_deferral)	ud_link;	/* [D] */
88 	int				ud_n;		/* [I] */
89 	/* followed by ud_n struct fdpass */
90 	struct fdpass			ud_fp[];	/* [I] */
91 };
92 
93 void	uipc_setaddr(const struct unpcb *, struct mbuf *);
94 void	unp_discard(struct fdpass *, int);
95 void	unp_remove_gcrefs(struct fdpass *, int);
96 void	unp_restore_gcrefs(struct fdpass *, int);
97 void	unp_scan(struct mbuf *, void (*)(struct fdpass *, int));
98 int	unp_nam2sun(struct mbuf *, struct sockaddr_un **, size_t *);
99 static inline void unp_ref(struct unpcb *);
100 static inline void unp_rele(struct unpcb *);
101 struct socket *unp_solock_peer(struct socket *);
102 
103 struct pool unpcb_pool;
104 struct task unp_gc_task = TASK_INITIALIZER(unp_gc, NULL);
105 
106 /*
107  * Unix communications domain.
108  *
109  * TODO:
110  *	RDM
111  *	rethink name space problems
112  *	need a proper out-of-band
113  */
114 const struct	sockaddr sun_noname = { sizeof(sun_noname), AF_UNIX };
115 
116 /* [G] list of all UNIX domain sockets, for unp_gc() */
117 LIST_HEAD(unp_head, unpcb)	unp_head =
118 	LIST_HEAD_INITIALIZER(unp_head);
119 /* [D] list of sets of files that were sent over sockets that are now closed */
120 SLIST_HEAD(,unp_deferral)	unp_deferred =
121 	SLIST_HEAD_INITIALIZER(unp_deferred);
122 
123 ino_t	unp_ino;	/* [U] prototype for fake inode numbers */
124 int	unp_rights;	/* [R] file descriptors in flight */
125 int	unp_defer;	/* [G] number of deferred fp to close by the GC task */
126 int	unp_gcing;	/* [G] GC task currently running */
127 
128 const struct pr_usrreqs uipc_usrreqs = {
129 	.pru_attach	= uipc_attach,
130 	.pru_detach	= uipc_detach,
131 	.pru_bind	= uipc_bind,
132 	.pru_listen	= uipc_listen,
133 	.pru_connect	= uipc_connect,
134 	.pru_accept	= uipc_accept,
135 	.pru_disconnect	= uipc_disconnect,
136 	.pru_shutdown	= uipc_shutdown,
137 	.pru_rcvd	= uipc_rcvd,
138 	.pru_send	= uipc_send,
139 	.pru_abort	= uipc_abort,
140 	.pru_sense	= uipc_sense,
141 	.pru_sockaddr	= uipc_sockaddr,
142 	.pru_peeraddr	= uipc_peeraddr,
143 	.pru_connect2	= uipc_connect2,
144 };
145 
146 const struct pr_usrreqs uipc_dgram_usrreqs = {
147 	.pru_attach	= uipc_attach,
148 	.pru_detach	= uipc_detach,
149 	.pru_bind	= uipc_bind,
150 	.pru_listen	= uipc_listen,
151 	.pru_connect	= uipc_connect,
152 	.pru_disconnect	= uipc_disconnect,
153 	.pru_shutdown	= uipc_dgram_shutdown,
154 	.pru_send	= uipc_dgram_send,
155 	.pru_sense	= uipc_sense,
156 	.pru_sockaddr	= uipc_sockaddr,
157 	.pru_peeraddr	= uipc_peeraddr,
158 	.pru_connect2	= uipc_connect2,
159 };
160 
161 void
162 unp_init(void)
163 {
164 	pool_init(&unpcb_pool, sizeof(struct unpcb), 0,
165 	    IPL_SOFTNET, 0, "unpcb", NULL);
166 }
167 
168 static inline void
169 unp_ref(struct unpcb *unp)
170 {
171 	refcnt_take(&unp->unp_refcnt);
172 }
173 
174 static inline void
175 unp_rele(struct unpcb *unp)
176 {
177 	refcnt_rele_wake(&unp->unp_refcnt);
178 }
179 
180 struct socket *
181 unp_solock_peer(struct socket *so)
182 {
183 	struct unpcb *unp, *unp2;
184 	struct socket *so2;
185 
186 	unp = so->so_pcb;
187 
188 again:
189 	if ((unp2 = unp->unp_conn) == NULL)
190 		return NULL;
191 
192 	so2 = unp2->unp_socket;
193 
194 	if (so < so2)
195 		solock(so2);
196 	else if (so > so2) {
197 		unp_ref(unp2);
198 		sounlock(so);
199 		solock(so2);
200 		solock(so);
201 
202 		/* Datagram socket could be reconnected due to re-lock. */
203 		if (unp->unp_conn != unp2) {
204 			sounlock(so2);
205 			unp_rele(unp2);
206 			goto again;
207 		}
208 
209 		unp_rele(unp2);
210 	}
211 
212 	return so2;
213 }
214 
215 void
216 uipc_setaddr(const struct unpcb *unp, struct mbuf *nam)
217 {
218 	if (unp != NULL && unp->unp_addr != NULL) {
219 		nam->m_len = unp->unp_addr->m_len;
220 		memcpy(mtod(nam, caddr_t), mtod(unp->unp_addr, caddr_t),
221 		    nam->m_len);
222 	} else {
223 		nam->m_len = sizeof(sun_noname);
224 		memcpy(mtod(nam, struct sockaddr *), &sun_noname,
225 		    nam->m_len);
226 	}
227 }
228 
229 /*
230  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
231  * for stream sockets, although the total for sender and receiver is
232  * actually only PIPSIZ.
233  * Datagram sockets really use the sendspace as the maximum datagram size,
234  * and don't really want to reserve the sendspace.  Their recvspace should
235  * be large enough for at least one max-size datagram plus address.
236  */
237 #define	PIPSIZ	8192
238 u_int	unpst_sendspace = PIPSIZ;
239 u_int	unpst_recvspace = PIPSIZ;
240 u_int	unpsq_sendspace = PIPSIZ;
241 u_int	unpsq_recvspace = PIPSIZ;
242 u_int	unpdg_sendspace = 2*1024;	/* really max datagram size */
243 u_int	unpdg_recvspace = 16*1024;
244 
245 const struct sysctl_bounded_args unpstctl_vars[] = {
246 	{ UNPCTL_RECVSPACE, &unpst_recvspace, 0, SB_MAX },
247 	{ UNPCTL_SENDSPACE, &unpst_sendspace, 0, SB_MAX },
248 };
249 const struct sysctl_bounded_args unpsqctl_vars[] = {
250 	{ UNPCTL_RECVSPACE, &unpsq_recvspace, 0, SB_MAX },
251 	{ UNPCTL_SENDSPACE, &unpsq_sendspace, 0, SB_MAX },
252 };
253 const struct sysctl_bounded_args unpdgctl_vars[] = {
254 	{ UNPCTL_RECVSPACE, &unpdg_recvspace, 0, SB_MAX },
255 	{ UNPCTL_SENDSPACE, &unpdg_sendspace, 0, SB_MAX },
256 };
257 
258 int
259 uipc_attach(struct socket *so, int proto, int wait)
260 {
261 	struct unpcb *unp;
262 	int error;
263 
264 	if (so->so_pcb)
265 		return EISCONN;
266 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
267 		switch (so->so_type) {
268 
269 		case SOCK_STREAM:
270 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
271 			break;
272 
273 		case SOCK_SEQPACKET:
274 			error = soreserve(so, unpsq_sendspace, unpsq_recvspace);
275 			break;
276 
277 		case SOCK_DGRAM:
278 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
279 			break;
280 
281 		default:
282 			panic("unp_attach");
283 		}
284 		if (error)
285 			return (error);
286 	}
287 	unp = pool_get(&unpcb_pool, (wait == M_WAIT ? PR_WAITOK : PR_NOWAIT) |
288 	    PR_ZERO);
289 	if (unp == NULL)
290 		return (ENOBUFS);
291 	refcnt_init(&unp->unp_refcnt);
292 	unp->unp_socket = so;
293 	so->so_pcb = unp;
294 	getnanotime(&unp->unp_ctime);
295 
296 	/*
297 	 * Enforce `unp_gc_lock' -> `solock()' lock order.
298 	 */
299 	sounlock(so);
300 	rw_enter_write(&unp_gc_lock);
301 	LIST_INSERT_HEAD(&unp_head, unp, unp_link);
302 	rw_exit_write(&unp_gc_lock);
303 	solock(so);
304 	return (0);
305 }
306 
307 int
308 uipc_detach(struct socket *so)
309 {
310 	struct unpcb *unp = sotounpcb(so);
311 
312 	if (unp == NULL)
313 		return (EINVAL);
314 
315 	unp_detach(unp);
316 
317 	return (0);
318 }
319 
320 int
321 uipc_bind(struct socket *so, struct mbuf *nam, struct proc *p)
322 {
323 	struct unpcb *unp = sotounpcb(so);
324 	struct sockaddr_un *soun;
325 	struct mbuf *nam2;
326 	struct vnode *vp;
327 	struct vattr vattr;
328 	int error;
329 	struct nameidata nd;
330 	size_t pathlen;
331 
332 	if (unp->unp_flags & (UNP_BINDING | UNP_CONNECTING))
333 		return (EINVAL);
334 	if (unp->unp_vnode != NULL)
335 		return (EINVAL);
336 	if ((error = unp_nam2sun(nam, &soun, &pathlen)))
337 		return (error);
338 
339 	unp->unp_flags |= UNP_BINDING;
340 
341 	/*
342 	 * Enforce `i_lock' -> `solock' because fifo subsystem
343 	 * requires it. The socket can't be closed concurrently
344 	 * because the file descriptor reference is still held.
345 	 */
346 
347 	sounlock(unp->unp_socket);
348 
349 	nam2 = m_getclr(M_WAITOK, MT_SONAME);
350 	nam2->m_len = sizeof(struct sockaddr_un);
351 	memcpy(mtod(nam2, struct sockaddr_un *), soun,
352 	    offsetof(struct sockaddr_un, sun_path) + pathlen);
353 	/* No need to NUL terminate: m_getclr() returns zero'd mbufs. */
354 
355 	soun = mtod(nam2, struct sockaddr_un *);
356 
357 	/* Fixup sun_len to keep it in sync with m_len. */
358 	soun->sun_len = nam2->m_len;
359 
360 	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT, UIO_SYSSPACE,
361 	    soun->sun_path, p);
362 	nd.ni_pledge = PLEDGE_UNIX;
363 	nd.ni_unveil = UNVEIL_CREATE;
364 
365 	KERNEL_LOCK();
366 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
367 	error = namei(&nd);
368 	if (error != 0) {
369 		m_freem(nam2);
370 		solock(unp->unp_socket);
371 		goto out;
372 	}
373 	vp = nd.ni_vp;
374 	if (vp != NULL) {
375 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
376 		if (nd.ni_dvp == vp)
377 			vrele(nd.ni_dvp);
378 		else
379 			vput(nd.ni_dvp);
380 		vrele(vp);
381 		m_freem(nam2);
382 		error = EADDRINUSE;
383 		solock(unp->unp_socket);
384 		goto out;
385 	}
386 	VATTR_NULL(&vattr);
387 	vattr.va_type = VSOCK;
388 	vattr.va_mode = ACCESSPERMS &~ p->p_fd->fd_cmask;
389 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
390 	vput(nd.ni_dvp);
391 	if (error) {
392 		m_freem(nam2);
393 		solock(unp->unp_socket);
394 		goto out;
395 	}
396 	solock(unp->unp_socket);
397 	unp->unp_addr = nam2;
398 	vp = nd.ni_vp;
399 	vp->v_socket = unp->unp_socket;
400 	unp->unp_vnode = vp;
401 	unp->unp_connid.uid = p->p_ucred->cr_uid;
402 	unp->unp_connid.gid = p->p_ucred->cr_gid;
403 	unp->unp_connid.pid = p->p_p->ps_pid;
404 	unp->unp_flags |= UNP_FEIDSBIND;
405 	VOP_UNLOCK(vp);
406 out:
407 	KERNEL_UNLOCK();
408 	unp->unp_flags &= ~UNP_BINDING;
409 
410 	return (error);
411 }
412 
413 int
414 uipc_listen(struct socket *so)
415 {
416 	struct unpcb *unp = sotounpcb(so);
417 
418 	if (unp->unp_vnode == NULL)
419 		return (EINVAL);
420 	return (0);
421 }
422 
423 int
424 uipc_connect(struct socket *so, struct mbuf *nam)
425 {
426 	return unp_connect(so, nam, curproc);
427 }
428 
429 int
430 uipc_accept(struct socket *so, struct mbuf *nam)
431 {
432 	struct socket *so2;
433 	struct unpcb *unp = sotounpcb(so);
434 
435 	/*
436 	 * Pass back name of connected socket, if it was bound and
437 	 * we are still connected (our peer may have closed already!).
438 	 */
439 	so2 = unp_solock_peer(so);
440 	uipc_setaddr(unp->unp_conn, nam);
441 
442 	if (so2 != NULL && so2 != so)
443 		sounlock(so2);
444 	return (0);
445 }
446 
447 int
448 uipc_disconnect(struct socket *so)
449 {
450 	struct unpcb *unp = sotounpcb(so);
451 
452 	unp_disconnect(unp);
453 	return (0);
454 }
455 
456 int
457 uipc_shutdown(struct socket *so)
458 {
459 	struct unpcb *unp = sotounpcb(so);
460 	struct socket *so2;
461 
462 	socantsendmore(so);
463 
464 	if ((so2 = unp_solock_peer(unp->unp_socket))){
465 		socantrcvmore(so2);
466 		sounlock(so2);
467 	}
468 
469 	return (0);
470 }
471 
472 int
473 uipc_dgram_shutdown(struct socket *so)
474 {
475 	socantsendmore(so);
476 	return (0);
477 }
478 
479 void
480 uipc_rcvd(struct socket *so)
481 {
482 	struct socket *so2;
483 
484 	if ((so2 = unp_solock_peer(so)) == NULL)
485 		return;
486 	/*
487 	 * Adjust backpressure on sender
488 	 * and wakeup any waiting to write.
489 	 */
490 	so2->so_snd.sb_mbcnt = so->so_rcv.sb_mbcnt;
491 	so2->so_snd.sb_cc = so->so_rcv.sb_cc;
492 	sowwakeup(so2);
493 	sounlock(so2);
494 }
495 
496 int
497 uipc_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
498     struct mbuf *control)
499 {
500 	struct socket *so2;
501 	int error = 0;
502 
503 	if (control) {
504 		sounlock(so);
505 		error = unp_internalize(control, curproc);
506 		solock(so);
507 		if (error)
508 			goto out;
509 	}
510 
511 	if (so->so_snd.sb_state & SS_CANTSENDMORE) {
512 		error = EPIPE;
513 		goto dispose;
514 	}
515 	if ((so2 = unp_solock_peer(so)) == NULL) {
516 		error = ENOTCONN;
517 		goto dispose;
518 	}
519 
520 	/*
521 	 * Send to paired receive port, and then raise
522 	 * send buffer counts to maintain backpressure.
523 	 * Wake up readers.
524 	 */
525 	if (control) {
526 		if (sbappendcontrol(so2, &so2->so_rcv, m, control)) {
527 			control = NULL;
528 		} else {
529 			sounlock(so2);
530 			error = ENOBUFS;
531 			goto dispose;
532 		}
533 	} else if (so->so_type == SOCK_SEQPACKET)
534 		sbappendrecord(so2, &so2->so_rcv, m);
535 	else
536 		sbappend(so2, &so2->so_rcv, m);
537 	so->so_snd.sb_mbcnt = so2->so_rcv.sb_mbcnt;
538 	so->so_snd.sb_cc = so2->so_rcv.sb_cc;
539 	if (so2->so_rcv.sb_cc > 0)
540 		sorwakeup(so2);
541 
542 	sounlock(so2);
543 	m = NULL;
544 
545 dispose:
546 	/* we need to undo unp_internalize in case of errors */
547 	if (control && error)
548 		unp_dispose(control);
549 
550 out:
551 	m_freem(control);
552 	m_freem(m);
553 
554 	return (error);
555 }
556 
557 int
558 uipc_dgram_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
559     struct mbuf *control)
560 {
561 	struct unpcb *unp = sotounpcb(so);
562 	struct socket *so2;
563 	const struct sockaddr *from;
564 	int error = 0;
565 
566 	if (control) {
567 		sounlock(so);
568 		error = unp_internalize(control, curproc);
569 		solock(so);
570 		if (error)
571 			goto out;
572 	}
573 
574 	if (nam) {
575 		if (unp->unp_conn) {
576 			error = EISCONN;
577 			goto dispose;
578 		}
579 		error = unp_connect(so, nam, curproc);
580 		if (error)
581 			goto dispose;
582 	}
583 
584 	if ((so2 = unp_solock_peer(so)) == NULL) {
585 		if (nam != NULL)
586 			error = ECONNREFUSED;
587 		else
588 			error = ENOTCONN;
589 		goto dispose;
590 	}
591 
592 	if (unp->unp_addr)
593 		from = mtod(unp->unp_addr, struct sockaddr *);
594 	else
595 		from = &sun_noname;
596 	if (sbappendaddr(so2, &so2->so_rcv, from, m, control)) {
597 		sorwakeup(so2);
598 		m = NULL;
599 		control = NULL;
600 	} else
601 		error = ENOBUFS;
602 
603 	if (so2 != so)
604 		sounlock(so2);
605 
606 	if (nam)
607 		unp_disconnect(unp);
608 
609 dispose:
610 	/* we need to undo unp_internalize in case of errors */
611 	if (control && error)
612 		unp_dispose(control);
613 
614 out:
615 	m_freem(control);
616 	m_freem(m);
617 
618 	return (error);
619 }
620 
621 void
622 uipc_abort(struct socket *so)
623 {
624 	struct unpcb *unp = sotounpcb(so);
625 
626 	unp_detach(unp);
627 	sofree(so, 0);
628 }
629 
630 int
631 uipc_sense(struct socket *so, struct stat *sb)
632 {
633 	struct unpcb *unp = sotounpcb(so);
634 
635 	sb->st_blksize = so->so_snd.sb_hiwat;
636 	sb->st_dev = NODEV;
637 	mtx_enter(&unp_ino_mtx);
638 	if (unp->unp_ino == 0)
639 		unp->unp_ino = unp_ino++;
640 	mtx_leave(&unp_ino_mtx);
641 	sb->st_atim.tv_sec =
642 	    sb->st_mtim.tv_sec =
643 	    sb->st_ctim.tv_sec = unp->unp_ctime.tv_sec;
644 	sb->st_atim.tv_nsec =
645 	    sb->st_mtim.tv_nsec =
646 	    sb->st_ctim.tv_nsec = unp->unp_ctime.tv_nsec;
647 	sb->st_ino = unp->unp_ino;
648 
649 	return (0);
650 }
651 
652 int
653 uipc_sockaddr(struct socket *so, struct mbuf *nam)
654 {
655 	struct unpcb *unp = sotounpcb(so);
656 
657 	uipc_setaddr(unp, nam);
658 	return (0);
659 }
660 
661 int
662 uipc_peeraddr(struct socket *so, struct mbuf *nam)
663 {
664 	struct unpcb *unp = sotounpcb(so);
665 	struct socket *so2;
666 
667 	so2 = unp_solock_peer(so);
668 	uipc_setaddr(unp->unp_conn, nam);
669 	if (so2 != NULL && so2 != so)
670 		sounlock(so2);
671 	return (0);
672 }
673 
674 int
675 uipc_connect2(struct socket *so, struct socket *so2)
676 {
677 	struct unpcb *unp = sotounpcb(so), *unp2;
678 	int error;
679 
680 	if ((error = unp_connect2(so, so2)))
681 		return (error);
682 
683 	unp->unp_connid.uid = curproc->p_ucred->cr_uid;
684 	unp->unp_connid.gid = curproc->p_ucred->cr_gid;
685 	unp->unp_connid.pid = curproc->p_p->ps_pid;
686 	unp->unp_flags |= UNP_FEIDS;
687 	unp2 = sotounpcb(so2);
688 	unp2->unp_connid.uid = curproc->p_ucred->cr_uid;
689 	unp2->unp_connid.gid = curproc->p_ucred->cr_gid;
690 	unp2->unp_connid.pid = curproc->p_p->ps_pid;
691 	unp2->unp_flags |= UNP_FEIDS;
692 
693 	return (0);
694 }
695 
696 int
697 uipc_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
698     size_t newlen)
699 {
700 	int *valp = &unp_defer;
701 
702 	/* All sysctl names at this level are terminal. */
703 	switch (name[0]) {
704 	case SOCK_STREAM:
705 		if (namelen != 2)
706 			return (ENOTDIR);
707 		return sysctl_bounded_arr(unpstctl_vars, nitems(unpstctl_vars),
708 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
709 	case SOCK_SEQPACKET:
710 		if (namelen != 2)
711 			return (ENOTDIR);
712 		return sysctl_bounded_arr(unpsqctl_vars, nitems(unpsqctl_vars),
713 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
714 	case SOCK_DGRAM:
715 		if (namelen != 2)
716 			return (ENOTDIR);
717 		return sysctl_bounded_arr(unpdgctl_vars, nitems(unpdgctl_vars),
718 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
719 	case NET_UNIX_INFLIGHT:
720 		valp = &unp_rights;
721 		/* FALLTHOUGH */
722 	case NET_UNIX_DEFERRED:
723 		if (namelen != 1)
724 			return (ENOTDIR);
725 		return sysctl_rdint(oldp, oldlenp, newp, *valp);
726 	default:
727 		return (ENOPROTOOPT);
728 	}
729 }
730 
731 void
732 unp_detach(struct unpcb *unp)
733 {
734 	struct socket *so = unp->unp_socket;
735 	struct vnode *vp = unp->unp_vnode;
736 	struct unpcb *unp2;
737 
738 	unp->unp_vnode = NULL;
739 
740 	/*
741 	 * Enforce `unp_gc_lock' -> `solock()' lock order.
742 	 * Enforce `i_lock' -> `solock()' lock order.
743 	 */
744 	sounlock(so);
745 
746 	rw_enter_write(&unp_gc_lock);
747 	LIST_REMOVE(unp, unp_link);
748 	rw_exit_write(&unp_gc_lock);
749 
750 	if (vp != NULL) {
751 		VOP_LOCK(vp, LK_EXCLUSIVE);
752 		vp->v_socket = NULL;
753 
754 		KERNEL_LOCK();
755 		vput(vp);
756 		KERNEL_UNLOCK();
757 	}
758 
759 	solock(so);
760 
761 	if (unp->unp_conn != NULL) {
762 		/*
763 		 * Datagram socket could be connected to itself.
764 		 * Such socket will be disconnected here.
765 		 */
766 		unp_disconnect(unp);
767 	}
768 
769 	while ((unp2 = SLIST_FIRST(&unp->unp_refs)) != NULL) {
770 		struct socket *so2 = unp2->unp_socket;
771 
772 		if (so < so2)
773 			solock(so2);
774 		else {
775 			unp_ref(unp2);
776 			sounlock(so);
777 			solock(so2);
778 			solock(so);
779 
780 			if (unp2->unp_conn != unp) {
781 				/* `unp2' was disconnected due to re-lock. */
782 				sounlock(so2);
783 				unp_rele(unp2);
784 				continue;
785 			}
786 
787 			unp_rele(unp2);
788 		}
789 
790 		unp2->unp_conn = NULL;
791 		SLIST_REMOVE(&unp->unp_refs, unp2, unpcb, unp_nextref);
792 		so2->so_error = ECONNRESET;
793 		so2->so_state &= ~SS_ISCONNECTED;
794 
795 		sounlock(so2);
796 	}
797 
798 	sounlock(so);
799 	refcnt_finalize(&unp->unp_refcnt, "unpfinal");
800 	solock(so);
801 
802 	soisdisconnected(so);
803 	so->so_pcb = NULL;
804 	m_freem(unp->unp_addr);
805 	pool_put(&unpcb_pool, unp);
806 	if (unp_rights)
807 		task_add(systqmp, &unp_gc_task);
808 }
809 
810 int
811 unp_connect(struct socket *so, struct mbuf *nam, struct proc *p)
812 {
813 	struct sockaddr_un *soun;
814 	struct vnode *vp;
815 	struct socket *so2, *so3;
816 	struct unpcb *unp, *unp2, *unp3;
817 	struct nameidata nd;
818 	int error;
819 
820 	unp = sotounpcb(so);
821 	if (unp->unp_flags & (UNP_BINDING | UNP_CONNECTING))
822 		return (EISCONN);
823 	if ((error = unp_nam2sun(nam, &soun, NULL)))
824 		return (error);
825 
826 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, soun->sun_path, p);
827 	nd.ni_pledge = PLEDGE_UNIX;
828 	nd.ni_unveil = UNVEIL_WRITE;
829 
830 	unp->unp_flags |= UNP_CONNECTING;
831 
832 	/*
833 	 * Enforce `i_lock' -> `solock' because fifo subsystem
834 	 * requires it. The socket can't be closed concurrently
835 	 * because the file descriptor reference is still held.
836 	 */
837 
838 	sounlock(so);
839 
840 	KERNEL_LOCK();
841 	error = namei(&nd);
842 	if (error != 0)
843 		goto unlock;
844 	vp = nd.ni_vp;
845 	if (vp->v_type != VSOCK) {
846 		error = ENOTSOCK;
847 		goto put;
848 	}
849 	if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
850 		goto put;
851 	so2 = vp->v_socket;
852 	if (so2 == NULL) {
853 		error = ECONNREFUSED;
854 		goto put;
855 	}
856 	if (so->so_type != so2->so_type) {
857 		error = EPROTOTYPE;
858 		goto put;
859 	}
860 
861 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
862 		solock(so2);
863 
864 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
865 		    (so3 = sonewconn(so2, 0, M_WAIT)) == NULL) {
866 			error = ECONNREFUSED;
867 		}
868 
869 		sounlock(so2);
870 
871 		if (error != 0)
872 			goto put;
873 
874 		/*
875 		 * Since `so2' is protected by vnode(9) lock, `so3'
876 		 * can't be PRU_ABORT'ed here.
877 		 */
878 		solock_pair(so, so3);
879 
880 		unp2 = sotounpcb(so2);
881 		unp3 = sotounpcb(so3);
882 
883 		/*
884 		 * `unp_addr', `unp_connid' and 'UNP_FEIDSBIND' flag
885 		 * are immutable since we set them in uipc_bind().
886 		 */
887 		if (unp2->unp_addr)
888 			unp3->unp_addr =
889 			    m_copym(unp2->unp_addr, 0, M_COPYALL, M_NOWAIT);
890 		unp3->unp_connid.uid = p->p_ucred->cr_uid;
891 		unp3->unp_connid.gid = p->p_ucred->cr_gid;
892 		unp3->unp_connid.pid = p->p_p->ps_pid;
893 		unp3->unp_flags |= UNP_FEIDS;
894 
895 		if (unp2->unp_flags & UNP_FEIDSBIND) {
896 			unp->unp_connid = unp2->unp_connid;
897 			unp->unp_flags |= UNP_FEIDS;
898 		}
899 
900 		so2 = so3;
901 	} else {
902 		if (so2 != so)
903 			solock_pair(so, so2);
904 		else
905 			solock(so);
906 	}
907 
908 	error = unp_connect2(so, so2);
909 
910 	sounlock(so);
911 
912 	/*
913 	 * `so2' can't be PRU_ABORT'ed concurrently
914 	 */
915 	if (so2 != so)
916 		sounlock(so2);
917 put:
918 	vput(vp);
919 unlock:
920 	KERNEL_UNLOCK();
921 	solock(so);
922 	unp->unp_flags &= ~UNP_CONNECTING;
923 
924 	/*
925 	 * The peer socket could be closed by concurrent thread
926 	 * when `so' and `vp' are unlocked.
927 	 */
928 	if (error == 0 && unp->unp_conn == NULL)
929 		error = ECONNREFUSED;
930 
931 	return (error);
932 }
933 
934 int
935 unp_connect2(struct socket *so, struct socket *so2)
936 {
937 	struct unpcb *unp = sotounpcb(so);
938 	struct unpcb *unp2;
939 
940 	soassertlocked(so);
941 	soassertlocked(so2);
942 
943 	if (so2->so_type != so->so_type)
944 		return (EPROTOTYPE);
945 	unp2 = sotounpcb(so2);
946 	unp->unp_conn = unp2;
947 	switch (so->so_type) {
948 
949 	case SOCK_DGRAM:
950 		SLIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_nextref);
951 		soisconnected(so);
952 		break;
953 
954 	case SOCK_STREAM:
955 	case SOCK_SEQPACKET:
956 		unp2->unp_conn = unp;
957 		soisconnected(so);
958 		soisconnected(so2);
959 		break;
960 
961 	default:
962 		panic("unp_connect2");
963 	}
964 	return (0);
965 }
966 
967 void
968 unp_disconnect(struct unpcb *unp)
969 {
970 	struct socket *so2;
971 	struct unpcb *unp2;
972 
973 	if ((so2 = unp_solock_peer(unp->unp_socket)) == NULL)
974 		return;
975 
976 	unp2 = unp->unp_conn;
977 	unp->unp_conn = NULL;
978 
979 	switch (unp->unp_socket->so_type) {
980 
981 	case SOCK_DGRAM:
982 		SLIST_REMOVE(&unp2->unp_refs, unp, unpcb, unp_nextref);
983 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
984 		break;
985 
986 	case SOCK_STREAM:
987 	case SOCK_SEQPACKET:
988 		unp->unp_socket->so_snd.sb_mbcnt = 0;
989 		unp->unp_socket->so_snd.sb_cc = 0;
990 		soisdisconnected(unp->unp_socket);
991 		unp2->unp_conn = NULL;
992 		unp2->unp_socket->so_snd.sb_mbcnt = 0;
993 		unp2->unp_socket->so_snd.sb_cc = 0;
994 		soisdisconnected(unp2->unp_socket);
995 		break;
996 	}
997 
998 	if (so2 != unp->unp_socket)
999 		sounlock(so2);
1000 }
1001 
1002 static struct unpcb *
1003 fptounp(struct file *fp)
1004 {
1005 	struct socket *so;
1006 
1007 	if (fp->f_type != DTYPE_SOCKET)
1008 		return (NULL);
1009 	if ((so = fp->f_data) == NULL)
1010 		return (NULL);
1011 	if (so->so_proto->pr_domain != &unixdomain)
1012 		return (NULL);
1013 	return (sotounpcb(so));
1014 }
1015 
1016 int
1017 unp_externalize(struct mbuf *rights, socklen_t controllen, int flags)
1018 {
1019 	struct proc *p = curproc;		/* XXX */
1020 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1021 	struct filedesc *fdp = p->p_fd;
1022 	int i, *fds = NULL;
1023 	struct fdpass *rp;
1024 	struct file *fp;
1025 	int nfds, error = 0;
1026 
1027 	/*
1028 	 * This code only works because SCM_RIGHTS is the only supported
1029 	 * control message type on unix sockets. Enforce this here.
1030 	 */
1031 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET)
1032 		return EINVAL;
1033 
1034 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
1035 	    sizeof(struct fdpass);
1036 	if (controllen < CMSG_ALIGN(sizeof(struct cmsghdr)))
1037 		controllen = 0;
1038 	else
1039 		controllen -= CMSG_ALIGN(sizeof(struct cmsghdr));
1040 	if (nfds > controllen / sizeof(int)) {
1041 		error = EMSGSIZE;
1042 		goto out;
1043 	}
1044 
1045 	/* Make sure the recipient should be able to see the descriptors.. */
1046 	rp = (struct fdpass *)CMSG_DATA(cm);
1047 
1048 	/* fdp->fd_rdir requires KERNEL_LOCK() */
1049 	KERNEL_LOCK();
1050 
1051 	for (i = 0; i < nfds; i++) {
1052 		fp = rp->fp;
1053 		rp++;
1054 		error = pledge_recvfd(p, fp);
1055 		if (error)
1056 			break;
1057 
1058 		/*
1059 		 * No to block devices.  If passing a directory,
1060 		 * make sure that it is underneath the root.
1061 		 */
1062 		if (fdp->fd_rdir != NULL && fp->f_type == DTYPE_VNODE) {
1063 			struct vnode *vp = (struct vnode *)fp->f_data;
1064 
1065 			if (vp->v_type == VBLK ||
1066 			    (vp->v_type == VDIR &&
1067 			    !vn_isunder(vp, fdp->fd_rdir, p))) {
1068 				error = EPERM;
1069 				break;
1070 			}
1071 		}
1072 	}
1073 
1074 	KERNEL_UNLOCK();
1075 
1076 	if (error)
1077 		goto out;
1078 
1079 	fds = mallocarray(nfds, sizeof(int), M_TEMP, M_WAITOK);
1080 
1081 	fdplock(fdp);
1082 restart:
1083 	/*
1084 	 * First loop -- allocate file descriptor table slots for the
1085 	 * new descriptors.
1086 	 */
1087 	rp = ((struct fdpass *)CMSG_DATA(cm));
1088 	for (i = 0; i < nfds; i++) {
1089 		if ((error = fdalloc(p, 0, &fds[i])) != 0) {
1090 			/*
1091 			 * Back out what we've done so far.
1092 			 */
1093 			for (--i; i >= 0; i--)
1094 				fdremove(fdp, fds[i]);
1095 
1096 			if (error == ENOSPC) {
1097 				fdexpand(p);
1098 				goto restart;
1099 			}
1100 
1101 			fdpunlock(fdp);
1102 
1103 			/*
1104 			 * This is the error that has historically
1105 			 * been returned, and some callers may
1106 			 * expect it.
1107 			 */
1108 
1109 			error = EMSGSIZE;
1110 			goto out;
1111 		}
1112 
1113 		/*
1114 		 * Make the slot reference the descriptor so that
1115 		 * fdalloc() works properly.. We finalize it all
1116 		 * in the loop below.
1117 		 */
1118 		mtx_enter(&fdp->fd_fplock);
1119 		KASSERT(fdp->fd_ofiles[fds[i]] == NULL);
1120 		fdp->fd_ofiles[fds[i]] = rp->fp;
1121 		mtx_leave(&fdp->fd_fplock);
1122 
1123 		fdp->fd_ofileflags[fds[i]] = (rp->flags & UF_PLEDGED);
1124 		if (flags & MSG_CMSG_CLOEXEC)
1125 			fdp->fd_ofileflags[fds[i]] |= UF_EXCLOSE;
1126 
1127 		rp++;
1128 	}
1129 
1130 	/*
1131 	 * Keep `fdp' locked to prevent concurrent close() of just
1132 	 * inserted descriptors. Such descriptors could have the only
1133 	 * `f_count' reference which is now shared between control
1134 	 * message and `fdp'.
1135 	 */
1136 
1137 	/*
1138 	 * Now that adding them has succeeded, update all of the
1139 	 * descriptor passing state.
1140 	 */
1141 	rp = (struct fdpass *)CMSG_DATA(cm);
1142 
1143 	for (i = 0; i < nfds; i++) {
1144 		struct unpcb *unp;
1145 
1146 		fp = rp->fp;
1147 		rp++;
1148 		if ((unp = fptounp(fp)) != NULL) {
1149 			rw_enter_write(&unp_gc_lock);
1150 			unp->unp_msgcount--;
1151 			rw_exit_write(&unp_gc_lock);
1152 		}
1153 	}
1154 	fdpunlock(fdp);
1155 
1156 	mtx_enter(&unp_rights_mtx);
1157 	unp_rights -= nfds;
1158 	mtx_leave(&unp_rights_mtx);
1159 
1160 	/*
1161 	 * Copy temporary array to message and adjust length, in case of
1162 	 * transition from large struct file pointers to ints.
1163 	 */
1164 	memcpy(CMSG_DATA(cm), fds, nfds * sizeof(int));
1165 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
1166 	rights->m_len = CMSG_LEN(nfds * sizeof(int));
1167  out:
1168 	if (fds != NULL)
1169 		free(fds, M_TEMP, nfds * sizeof(int));
1170 
1171 	if (error) {
1172 		if (nfds > 0) {
1173 			/*
1174 			 * No lock required. We are the only `cm' holder.
1175 			 */
1176 			rp = ((struct fdpass *)CMSG_DATA(cm));
1177 			unp_discard(rp, nfds);
1178 		}
1179 	}
1180 
1181 	return (error);
1182 }
1183 
1184 int
1185 unp_internalize(struct mbuf *control, struct proc *p)
1186 {
1187 	struct filedesc *fdp = p->p_fd;
1188 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1189 	struct fdpass *rp;
1190 	struct file *fp;
1191 	struct unpcb *unp;
1192 	int i, error;
1193 	int nfds, *ip, fd, neededspace;
1194 
1195 	/*
1196 	 * Check for two potential msg_controllen values because
1197 	 * IETF stuck their nose in a place it does not belong.
1198 	 */
1199 	if (control->m_len < CMSG_LEN(0) || cm->cmsg_len < CMSG_LEN(0))
1200 		return (EINVAL);
1201 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
1202 	    !(cm->cmsg_len == control->m_len ||
1203 	    control->m_len == CMSG_ALIGN(cm->cmsg_len)))
1204 		return (EINVAL);
1205 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof (int);
1206 
1207 	mtx_enter(&unp_rights_mtx);
1208 	if (unp_rights + nfds > maxfiles / 10) {
1209 		mtx_leave(&unp_rights_mtx);
1210 		return (EMFILE);
1211 	}
1212 	unp_rights += nfds;
1213 	mtx_leave(&unp_rights_mtx);
1214 
1215 	/* Make sure we have room for the struct file pointers */
1216 morespace:
1217 	neededspace = CMSG_SPACE(nfds * sizeof(struct fdpass)) -
1218 	    control->m_len;
1219 	if (neededspace > m_trailingspace(control)) {
1220 		char *tmp;
1221 		/* if we already have a cluster, the message is just too big */
1222 		if (control->m_flags & M_EXT) {
1223 			error = E2BIG;
1224 			goto nospace;
1225 		}
1226 
1227 		/* copy cmsg data temporarily out of the mbuf */
1228 		tmp = malloc(control->m_len, M_TEMP, M_WAITOK);
1229 		memcpy(tmp, mtod(control, caddr_t), control->m_len);
1230 
1231 		/* allocate a cluster and try again */
1232 		MCLGET(control, M_WAIT);
1233 		if ((control->m_flags & M_EXT) == 0) {
1234 			free(tmp, M_TEMP, control->m_len);
1235 			error = ENOBUFS;       /* allocation failed */
1236 			goto nospace;
1237 		}
1238 
1239 		/* copy the data back into the cluster */
1240 		cm = mtod(control, struct cmsghdr *);
1241 		memcpy(cm, tmp, control->m_len);
1242 		free(tmp, M_TEMP, control->m_len);
1243 		goto morespace;
1244 	}
1245 
1246 	/* adjust message & mbuf to note amount of space actually used. */
1247 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct fdpass));
1248 	control->m_len = CMSG_SPACE(nfds * sizeof(struct fdpass));
1249 
1250 	ip = ((int *)CMSG_DATA(cm)) + nfds - 1;
1251 	rp = ((struct fdpass *)CMSG_DATA(cm)) + nfds - 1;
1252 	fdplock(fdp);
1253 	for (i = 0; i < nfds; i++) {
1254 		memcpy(&fd, ip, sizeof fd);
1255 		ip--;
1256 		if ((fp = fd_getfile(fdp, fd)) == NULL) {
1257 			error = EBADF;
1258 			goto fail;
1259 		}
1260 		if (fp->f_count >= FDUP_MAX_COUNT) {
1261 			error = EDEADLK;
1262 			goto fail;
1263 		}
1264 		error = pledge_sendfd(p, fp);
1265 		if (error)
1266 			goto fail;
1267 
1268 		/* kqueue descriptors cannot be copied */
1269 		if (fp->f_type == DTYPE_KQUEUE) {
1270 			error = EINVAL;
1271 			goto fail;
1272 		}
1273 #if NKCOV > 0
1274 		/* kcov descriptors cannot be copied */
1275 		if (fp->f_type == DTYPE_VNODE && kcov_vnode(fp->f_data)) {
1276 			error = EINVAL;
1277 			goto fail;
1278 		}
1279 #endif
1280 		rp->fp = fp;
1281 		rp->flags = fdp->fd_ofileflags[fd] & UF_PLEDGED;
1282 		rp--;
1283 		if ((unp = fptounp(fp)) != NULL) {
1284 			rw_enter_write(&unp_gc_lock);
1285 			unp->unp_msgcount++;
1286 			unp->unp_file = fp;
1287 			rw_exit_write(&unp_gc_lock);
1288 		}
1289 	}
1290 	fdpunlock(fdp);
1291 	return (0);
1292 fail:
1293 	fdpunlock(fdp);
1294 	if (fp != NULL)
1295 		FRELE(fp, p);
1296 	/* Back out what we just did. */
1297 	for ( ; i > 0; i--) {
1298 		rp++;
1299 		fp = rp->fp;
1300 		if ((unp = fptounp(fp)) != NULL) {
1301 			rw_enter_write(&unp_gc_lock);
1302 			unp->unp_msgcount--;
1303 			rw_exit_write(&unp_gc_lock);
1304 		}
1305 		FRELE(fp, p);
1306 	}
1307 
1308 nospace:
1309 	mtx_enter(&unp_rights_mtx);
1310 	unp_rights -= nfds;
1311 	mtx_leave(&unp_rights_mtx);
1312 
1313 	return (error);
1314 }
1315 
1316 void
1317 unp_gc(void *arg __unused)
1318 {
1319 	struct unp_deferral *defer;
1320 	struct file *fp;
1321 	struct socket *so;
1322 	struct unpcb *unp;
1323 	int nunref, i;
1324 
1325 	rw_enter_write(&unp_gc_lock);
1326 	if (unp_gcing)
1327 		goto unlock;
1328 	unp_gcing = 1;
1329 	rw_exit_write(&unp_gc_lock);
1330 
1331 	rw_enter_write(&unp_df_lock);
1332 	/* close any fds on the deferred list */
1333 	while ((defer = SLIST_FIRST(&unp_deferred)) != NULL) {
1334 		SLIST_REMOVE_HEAD(&unp_deferred, ud_link);
1335 		rw_exit_write(&unp_df_lock);
1336 		for (i = 0; i < defer->ud_n; i++) {
1337 			fp = defer->ud_fp[i].fp;
1338 			if (fp == NULL)
1339 				continue;
1340 			if ((unp = fptounp(fp)) != NULL) {
1341 				rw_enter_write(&unp_gc_lock);
1342 				unp->unp_msgcount--;
1343 				rw_exit_write(&unp_gc_lock);
1344 			}
1345 			mtx_enter(&unp_rights_mtx);
1346 			unp_rights--;
1347 			mtx_leave(&unp_rights_mtx);
1348 			 /* closef() expects a refcount of 2 */
1349 			FREF(fp);
1350 			(void) closef(fp, NULL);
1351 		}
1352 		free(defer, M_TEMP, sizeof(*defer) +
1353 		    sizeof(struct fdpass) * defer->ud_n);
1354 		rw_enter_write(&unp_df_lock);
1355 	}
1356 	rw_exit_write(&unp_df_lock);
1357 
1358 	nunref = 0;
1359 
1360 	rw_enter_write(&unp_gc_lock);
1361 
1362 	/*
1363 	 * Determine sockets which may be prospectively dead. Such
1364 	 * sockets have their `unp_msgcount' equal to the `f_count'.
1365 	 * If `unp_msgcount' is 0, the socket has not been passed
1366 	 * and can't be unreferenced.
1367 	 */
1368 	LIST_FOREACH(unp, &unp_head, unp_link) {
1369 		unp->unp_gcflags = 0;
1370 
1371 		if (unp->unp_msgcount == 0)
1372 			continue;
1373 		if ((fp = unp->unp_file) == NULL)
1374 			continue;
1375 		if (fp->f_count == unp->unp_msgcount) {
1376 			unp->unp_gcflags |= UNP_GCDEAD;
1377 			unp->unp_gcrefs = unp->unp_msgcount;
1378 			nunref++;
1379 		}
1380 	}
1381 
1382 	/*
1383 	 * Scan all sockets previously marked as dead. Remove
1384 	 * the `unp_gcrefs' reference each socket holds on any
1385 	 * dead socket in its buffer.
1386 	 */
1387 	LIST_FOREACH(unp, &unp_head, unp_link) {
1388 		if ((unp->unp_gcflags & UNP_GCDEAD) == 0)
1389 			continue;
1390 		so = unp->unp_socket;
1391 		solock(so);
1392 		unp_scan(so->so_rcv.sb_mb, unp_remove_gcrefs);
1393 		sounlock(so);
1394 	}
1395 
1396 	/*
1397 	 * If the dead socket has `unp_gcrefs' reference counter
1398 	 * greater than 0, it can't be unreferenced. Mark it as
1399 	 * alive and increment the `unp_gcrefs' reference for each
1400 	 * dead socket within its buffer. Repeat this until we
1401 	 * have no new alive sockets found.
1402 	 */
1403 	do {
1404 		unp_defer = 0;
1405 
1406 		LIST_FOREACH(unp, &unp_head, unp_link) {
1407 			if ((unp->unp_gcflags & UNP_GCDEAD) == 0)
1408 				continue;
1409 			if (unp->unp_gcrefs == 0)
1410 				continue;
1411 
1412 			unp->unp_gcflags &= ~UNP_GCDEAD;
1413 
1414 			so = unp->unp_socket;
1415 			solock(so);
1416 			unp_scan(so->so_rcv.sb_mb, unp_restore_gcrefs);
1417 			sounlock(so);
1418 
1419 			KASSERT(nunref > 0);
1420 			nunref--;
1421 		}
1422 	} while (unp_defer > 0);
1423 
1424 	/*
1425 	 * If there are any unreferenced sockets, then for each dispose
1426 	 * of files in its receive buffer and then close it.
1427 	 */
1428 	if (nunref) {
1429 		LIST_FOREACH(unp, &unp_head, unp_link) {
1430 			if (unp->unp_gcflags & UNP_GCDEAD) {
1431 				/*
1432 				 * This socket could still be connected
1433 				 * and if so it's `so_rcv' is still
1434 				 * accessible by concurrent PRU_SEND
1435 				 * thread.
1436 				 */
1437 				so = unp->unp_socket;
1438 				solock(so);
1439 				unp_scan(so->so_rcv.sb_mb, unp_discard);
1440 				sounlock(so);
1441 			}
1442 		}
1443 	}
1444 
1445 	unp_gcing = 0;
1446 unlock:
1447 	rw_exit_write(&unp_gc_lock);
1448 }
1449 
1450 void
1451 unp_dispose(struct mbuf *m)
1452 {
1453 
1454 	if (m)
1455 		unp_scan(m, unp_discard);
1456 }
1457 
1458 void
1459 unp_scan(struct mbuf *m0, void (*op)(struct fdpass *, int))
1460 {
1461 	struct mbuf *m;
1462 	struct fdpass *rp;
1463 	struct cmsghdr *cm;
1464 	int qfds;
1465 
1466 	while (m0) {
1467 		for (m = m0; m; m = m->m_next) {
1468 			if (m->m_type == MT_CONTROL &&
1469 			    m->m_len >= sizeof(*cm)) {
1470 				cm = mtod(m, struct cmsghdr *);
1471 				if (cm->cmsg_level != SOL_SOCKET ||
1472 				    cm->cmsg_type != SCM_RIGHTS)
1473 					continue;
1474 				qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof *cm))
1475 				    / sizeof(struct fdpass);
1476 				if (qfds > 0) {
1477 					rp = (struct fdpass *)CMSG_DATA(cm);
1478 					op(rp, qfds);
1479 				}
1480 				break;		/* XXX, but saves time */
1481 			}
1482 		}
1483 		m0 = m0->m_nextpkt;
1484 	}
1485 }
1486 
1487 void
1488 unp_discard(struct fdpass *rp, int nfds)
1489 {
1490 	struct unp_deferral *defer;
1491 
1492 	/* copy the file pointers to a deferral structure */
1493 	defer = malloc(sizeof(*defer) + sizeof(*rp) * nfds, M_TEMP, M_WAITOK);
1494 	defer->ud_n = nfds;
1495 	memcpy(&defer->ud_fp[0], rp, sizeof(*rp) * nfds);
1496 	memset(rp, 0, sizeof(*rp) * nfds);
1497 
1498 	rw_enter_write(&unp_df_lock);
1499 	SLIST_INSERT_HEAD(&unp_deferred, defer, ud_link);
1500 	rw_exit_write(&unp_df_lock);
1501 
1502 	task_add(systqmp, &unp_gc_task);
1503 }
1504 
1505 void
1506 unp_remove_gcrefs(struct fdpass *rp, int nfds)
1507 {
1508 	struct unpcb *unp;
1509 	int i;
1510 
1511 	rw_assert_wrlock(&unp_gc_lock);
1512 
1513 	for (i = 0; i < nfds; i++) {
1514 		if (rp[i].fp == NULL)
1515 			continue;
1516 		if ((unp = fptounp(rp[i].fp)) == NULL)
1517 			continue;
1518 		if (unp->unp_gcflags & UNP_GCDEAD) {
1519 			KASSERT(unp->unp_gcrefs > 0);
1520 			unp->unp_gcrefs--;
1521 		}
1522 	}
1523 }
1524 
1525 void
1526 unp_restore_gcrefs(struct fdpass *rp, int nfds)
1527 {
1528 	struct unpcb *unp;
1529 	int i;
1530 
1531 	rw_assert_wrlock(&unp_gc_lock);
1532 
1533 	for (i = 0; i < nfds; i++) {
1534 		if (rp[i].fp == NULL)
1535 			continue;
1536 		if ((unp = fptounp(rp[i].fp)) == NULL)
1537 			continue;
1538 		if (unp->unp_gcflags & UNP_GCDEAD) {
1539 			unp->unp_gcrefs++;
1540 			unp_defer++;
1541 		}
1542 	}
1543 }
1544 
1545 int
1546 unp_nam2sun(struct mbuf *nam, struct sockaddr_un **sun, size_t *pathlen)
1547 {
1548 	struct sockaddr *sa = mtod(nam, struct sockaddr *);
1549 	size_t size, len;
1550 
1551 	if (nam->m_len < offsetof(struct sockaddr, sa_data))
1552 		return EINVAL;
1553 	if (sa->sa_family != AF_UNIX)
1554 		return EAFNOSUPPORT;
1555 	if (sa->sa_len != nam->m_len)
1556 		return EINVAL;
1557 	if (sa->sa_len > sizeof(struct sockaddr_un))
1558 		return EINVAL;
1559 	*sun = (struct sockaddr_un *)sa;
1560 
1561 	/* ensure that sun_path is NUL terminated and fits */
1562 	size = (*sun)->sun_len - offsetof(struct sockaddr_un, sun_path);
1563 	len = strnlen((*sun)->sun_path, size);
1564 	if (len == sizeof((*sun)->sun_path))
1565 		return EINVAL;
1566 	if (len == size) {
1567 		if (m_trailingspace(nam) == 0)
1568 			return EINVAL;
1569 		nam->m_len++;
1570 		(*sun)->sun_len++;
1571 		(*sun)->sun_path[len] = '\0';
1572 	}
1573 	if (pathlen != NULL)
1574 		*pathlen = len;
1575 
1576 	return 0;
1577 }
1578