xref: /openbsd-src/sys/kern/uipc_usrreq.c (revision d1ea0a7c7de994c94e080237116e3e91989b4d68)
1 /*	$OpenBSD: uipc_usrreq.c,v 1.201 2024/03/17 19:47:08 mvs 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_flags & (UNP_BINDING | UNP_CONNECTING))
419 		return (EINVAL);
420 	if (unp->unp_vnode == NULL)
421 		return (EINVAL);
422 	return (0);
423 }
424 
425 int
426 uipc_connect(struct socket *so, struct mbuf *nam)
427 {
428 	return unp_connect(so, nam, curproc);
429 }
430 
431 int
432 uipc_accept(struct socket *so, struct mbuf *nam)
433 {
434 	struct socket *so2;
435 	struct unpcb *unp = sotounpcb(so);
436 
437 	/*
438 	 * Pass back name of connected socket, if it was bound and
439 	 * we are still connected (our peer may have closed already!).
440 	 */
441 	so2 = unp_solock_peer(so);
442 	uipc_setaddr(unp->unp_conn, nam);
443 
444 	if (so2 != NULL && so2 != so)
445 		sounlock(so2);
446 	return (0);
447 }
448 
449 int
450 uipc_disconnect(struct socket *so)
451 {
452 	struct unpcb *unp = sotounpcb(so);
453 
454 	unp_disconnect(unp);
455 	return (0);
456 }
457 
458 int
459 uipc_shutdown(struct socket *so)
460 {
461 	struct unpcb *unp = sotounpcb(so);
462 	struct socket *so2;
463 
464 	socantsendmore(so);
465 
466 	if ((so2 = unp_solock_peer(unp->unp_socket))){
467 		socantrcvmore(so2);
468 		sounlock(so2);
469 	}
470 
471 	return (0);
472 }
473 
474 int
475 uipc_dgram_shutdown(struct socket *so)
476 {
477 	socantsendmore(so);
478 	return (0);
479 }
480 
481 void
482 uipc_rcvd(struct socket *so)
483 {
484 	struct socket *so2;
485 
486 	if ((so2 = unp_solock_peer(so)) == NULL)
487 		return;
488 	/*
489 	 * Adjust backpressure on sender
490 	 * and wakeup any waiting to write.
491 	 */
492 	so2->so_snd.sb_mbcnt = so->so_rcv.sb_mbcnt;
493 	so2->so_snd.sb_cc = so->so_rcv.sb_cc;
494 	sowwakeup(so2);
495 	sounlock(so2);
496 }
497 
498 int
499 uipc_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
500     struct mbuf *control)
501 {
502 	struct socket *so2;
503 	int error = 0;
504 
505 	if (control) {
506 		sounlock(so);
507 		error = unp_internalize(control, curproc);
508 		solock(so);
509 		if (error)
510 			goto out;
511 	}
512 
513 	if (so->so_snd.sb_state & SS_CANTSENDMORE) {
514 		error = EPIPE;
515 		goto dispose;
516 	}
517 	if ((so2 = unp_solock_peer(so)) == NULL) {
518 		error = ENOTCONN;
519 		goto dispose;
520 	}
521 
522 	/*
523 	 * Send to paired receive port, and then raise
524 	 * send buffer counts to maintain backpressure.
525 	 * Wake up readers.
526 	 */
527 	if (control) {
528 		if (sbappendcontrol(so2, &so2->so_rcv, m, control)) {
529 			control = NULL;
530 		} else {
531 			sounlock(so2);
532 			error = ENOBUFS;
533 			goto dispose;
534 		}
535 	} else if (so->so_type == SOCK_SEQPACKET)
536 		sbappendrecord(so2, &so2->so_rcv, m);
537 	else
538 		sbappend(so2, &so2->so_rcv, m);
539 	so->so_snd.sb_mbcnt = so2->so_rcv.sb_mbcnt;
540 	so->so_snd.sb_cc = so2->so_rcv.sb_cc;
541 	if (so2->so_rcv.sb_cc > 0)
542 		sorwakeup(so2);
543 
544 	sounlock(so2);
545 	m = NULL;
546 
547 dispose:
548 	/* we need to undo unp_internalize in case of errors */
549 	if (control && error)
550 		unp_dispose(control);
551 
552 out:
553 	m_freem(control);
554 	m_freem(m);
555 
556 	return (error);
557 }
558 
559 int
560 uipc_dgram_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
561     struct mbuf *control)
562 {
563 	struct unpcb *unp = sotounpcb(so);
564 	struct socket *so2;
565 	const struct sockaddr *from;
566 	int error = 0;
567 
568 	if (control) {
569 		sounlock(so);
570 		error = unp_internalize(control, curproc);
571 		solock(so);
572 		if (error)
573 			goto out;
574 	}
575 
576 	if (nam) {
577 		if (unp->unp_conn) {
578 			error = EISCONN;
579 			goto dispose;
580 		}
581 		error = unp_connect(so, nam, curproc);
582 		if (error)
583 			goto dispose;
584 	}
585 
586 	if ((so2 = unp_solock_peer(so)) == NULL) {
587 		if (nam != NULL)
588 			error = ECONNREFUSED;
589 		else
590 			error = ENOTCONN;
591 		goto dispose;
592 	}
593 
594 	if (unp->unp_addr)
595 		from = mtod(unp->unp_addr, struct sockaddr *);
596 	else
597 		from = &sun_noname;
598 	if (sbappendaddr(so2, &so2->so_rcv, from, m, control)) {
599 		sorwakeup(so2);
600 		m = NULL;
601 		control = NULL;
602 	} else
603 		error = ENOBUFS;
604 
605 	if (so2 != so)
606 		sounlock(so2);
607 
608 	if (nam)
609 		unp_disconnect(unp);
610 
611 dispose:
612 	/* we need to undo unp_internalize in case of errors */
613 	if (control && error)
614 		unp_dispose(control);
615 
616 out:
617 	m_freem(control);
618 	m_freem(m);
619 
620 	return (error);
621 }
622 
623 void
624 uipc_abort(struct socket *so)
625 {
626 	struct unpcb *unp = sotounpcb(so);
627 
628 	unp_detach(unp);
629 	sofree(so, 0);
630 }
631 
632 int
633 uipc_sense(struct socket *so, struct stat *sb)
634 {
635 	struct unpcb *unp = sotounpcb(so);
636 
637 	sb->st_blksize = so->so_snd.sb_hiwat;
638 	sb->st_dev = NODEV;
639 	mtx_enter(&unp_ino_mtx);
640 	if (unp->unp_ino == 0)
641 		unp->unp_ino = unp_ino++;
642 	mtx_leave(&unp_ino_mtx);
643 	sb->st_atim.tv_sec =
644 	    sb->st_mtim.tv_sec =
645 	    sb->st_ctim.tv_sec = unp->unp_ctime.tv_sec;
646 	sb->st_atim.tv_nsec =
647 	    sb->st_mtim.tv_nsec =
648 	    sb->st_ctim.tv_nsec = unp->unp_ctime.tv_nsec;
649 	sb->st_ino = unp->unp_ino;
650 
651 	return (0);
652 }
653 
654 int
655 uipc_sockaddr(struct socket *so, struct mbuf *nam)
656 {
657 	struct unpcb *unp = sotounpcb(so);
658 
659 	uipc_setaddr(unp, nam);
660 	return (0);
661 }
662 
663 int
664 uipc_peeraddr(struct socket *so, struct mbuf *nam)
665 {
666 	struct unpcb *unp = sotounpcb(so);
667 	struct socket *so2;
668 
669 	so2 = unp_solock_peer(so);
670 	uipc_setaddr(unp->unp_conn, nam);
671 	if (so2 != NULL && so2 != so)
672 		sounlock(so2);
673 	return (0);
674 }
675 
676 int
677 uipc_connect2(struct socket *so, struct socket *so2)
678 {
679 	struct unpcb *unp = sotounpcb(so), *unp2;
680 	int error;
681 
682 	if ((error = unp_connect2(so, so2)))
683 		return (error);
684 
685 	unp->unp_connid.uid = curproc->p_ucred->cr_uid;
686 	unp->unp_connid.gid = curproc->p_ucred->cr_gid;
687 	unp->unp_connid.pid = curproc->p_p->ps_pid;
688 	unp->unp_flags |= UNP_FEIDS;
689 	unp2 = sotounpcb(so2);
690 	unp2->unp_connid.uid = curproc->p_ucred->cr_uid;
691 	unp2->unp_connid.gid = curproc->p_ucred->cr_gid;
692 	unp2->unp_connid.pid = curproc->p_p->ps_pid;
693 	unp2->unp_flags |= UNP_FEIDS;
694 
695 	return (0);
696 }
697 
698 int
699 uipc_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
700     size_t newlen)
701 {
702 	int *valp = &unp_defer;
703 
704 	/* All sysctl names at this level are terminal. */
705 	switch (name[0]) {
706 	case SOCK_STREAM:
707 		if (namelen != 2)
708 			return (ENOTDIR);
709 		return sysctl_bounded_arr(unpstctl_vars, nitems(unpstctl_vars),
710 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
711 	case SOCK_SEQPACKET:
712 		if (namelen != 2)
713 			return (ENOTDIR);
714 		return sysctl_bounded_arr(unpsqctl_vars, nitems(unpsqctl_vars),
715 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
716 	case SOCK_DGRAM:
717 		if (namelen != 2)
718 			return (ENOTDIR);
719 		return sysctl_bounded_arr(unpdgctl_vars, nitems(unpdgctl_vars),
720 		    name + 1, namelen - 1, oldp, oldlenp, newp, newlen);
721 	case NET_UNIX_INFLIGHT:
722 		valp = &unp_rights;
723 		/* FALLTHROUGH */
724 	case NET_UNIX_DEFERRED:
725 		if (namelen != 1)
726 			return (ENOTDIR);
727 		return sysctl_rdint(oldp, oldlenp, newp, *valp);
728 	default:
729 		return (ENOPROTOOPT);
730 	}
731 }
732 
733 void
734 unp_detach(struct unpcb *unp)
735 {
736 	struct socket *so = unp->unp_socket;
737 	struct vnode *vp = unp->unp_vnode;
738 	struct unpcb *unp2;
739 
740 	unp->unp_vnode = NULL;
741 
742 	/*
743 	 * Enforce `unp_gc_lock' -> `solock()' lock order.
744 	 * Enforce `i_lock' -> `solock()' lock order.
745 	 */
746 	sounlock(so);
747 
748 	rw_enter_write(&unp_gc_lock);
749 	LIST_REMOVE(unp, unp_link);
750 	rw_exit_write(&unp_gc_lock);
751 
752 	if (vp != NULL) {
753 		VOP_LOCK(vp, LK_EXCLUSIVE);
754 		vp->v_socket = NULL;
755 
756 		KERNEL_LOCK();
757 		vput(vp);
758 		KERNEL_UNLOCK();
759 	}
760 
761 	solock(so);
762 
763 	if (unp->unp_conn != NULL) {
764 		/*
765 		 * Datagram socket could be connected to itself.
766 		 * Such socket will be disconnected here.
767 		 */
768 		unp_disconnect(unp);
769 	}
770 
771 	while ((unp2 = SLIST_FIRST(&unp->unp_refs)) != NULL) {
772 		struct socket *so2 = unp2->unp_socket;
773 
774 		if (so < so2)
775 			solock(so2);
776 		else {
777 			unp_ref(unp2);
778 			sounlock(so);
779 			solock(so2);
780 			solock(so);
781 
782 			if (unp2->unp_conn != unp) {
783 				/* `unp2' was disconnected due to re-lock. */
784 				sounlock(so2);
785 				unp_rele(unp2);
786 				continue;
787 			}
788 
789 			unp_rele(unp2);
790 		}
791 
792 		unp2->unp_conn = NULL;
793 		SLIST_REMOVE(&unp->unp_refs, unp2, unpcb, unp_nextref);
794 		so2->so_error = ECONNRESET;
795 		so2->so_state &= ~SS_ISCONNECTED;
796 
797 		sounlock(so2);
798 	}
799 
800 	sounlock(so);
801 	refcnt_finalize(&unp->unp_refcnt, "unpfinal");
802 	solock(so);
803 
804 	soisdisconnected(so);
805 	so->so_pcb = NULL;
806 	m_freem(unp->unp_addr);
807 	pool_put(&unpcb_pool, unp);
808 	if (unp_rights)
809 		task_add(systqmp, &unp_gc_task);
810 }
811 
812 int
813 unp_connect(struct socket *so, struct mbuf *nam, struct proc *p)
814 {
815 	struct sockaddr_un *soun;
816 	struct vnode *vp;
817 	struct socket *so2, *so3;
818 	struct unpcb *unp, *unp2, *unp3;
819 	struct nameidata nd;
820 	int error;
821 
822 	unp = sotounpcb(so);
823 	if (unp->unp_flags & (UNP_BINDING | UNP_CONNECTING))
824 		return (EISCONN);
825 	if ((error = unp_nam2sun(nam, &soun, NULL)))
826 		return (error);
827 
828 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, soun->sun_path, p);
829 	nd.ni_pledge = PLEDGE_UNIX;
830 	nd.ni_unveil = UNVEIL_WRITE;
831 
832 	unp->unp_flags |= UNP_CONNECTING;
833 
834 	/*
835 	 * Enforce `i_lock' -> `solock' because fifo subsystem
836 	 * requires it. The socket can't be closed concurrently
837 	 * because the file descriptor reference is still held.
838 	 */
839 
840 	sounlock(so);
841 
842 	KERNEL_LOCK();
843 	error = namei(&nd);
844 	if (error != 0)
845 		goto unlock;
846 	vp = nd.ni_vp;
847 	if (vp->v_type != VSOCK) {
848 		error = ENOTSOCK;
849 		goto put;
850 	}
851 	if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
852 		goto put;
853 	so2 = vp->v_socket;
854 	if (so2 == NULL) {
855 		error = ECONNREFUSED;
856 		goto put;
857 	}
858 	if (so->so_type != so2->so_type) {
859 		error = EPROTOTYPE;
860 		goto put;
861 	}
862 
863 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
864 		solock(so2);
865 
866 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
867 		    (so3 = sonewconn(so2, 0, M_WAIT)) == NULL) {
868 			error = ECONNREFUSED;
869 		}
870 
871 		sounlock(so2);
872 
873 		if (error != 0)
874 			goto put;
875 
876 		/*
877 		 * Since `so2' is protected by vnode(9) lock, `so3'
878 		 * can't be PRU_ABORT'ed here.
879 		 */
880 		solock_pair(so, so3);
881 
882 		unp2 = sotounpcb(so2);
883 		unp3 = sotounpcb(so3);
884 
885 		/*
886 		 * `unp_addr', `unp_connid' and 'UNP_FEIDSBIND' flag
887 		 * are immutable since we set them in uipc_bind().
888 		 */
889 		if (unp2->unp_addr)
890 			unp3->unp_addr =
891 			    m_copym(unp2->unp_addr, 0, M_COPYALL, M_NOWAIT);
892 		unp3->unp_connid.uid = p->p_ucred->cr_uid;
893 		unp3->unp_connid.gid = p->p_ucred->cr_gid;
894 		unp3->unp_connid.pid = p->p_p->ps_pid;
895 		unp3->unp_flags |= UNP_FEIDS;
896 
897 		if (unp2->unp_flags & UNP_FEIDSBIND) {
898 			unp->unp_connid = unp2->unp_connid;
899 			unp->unp_flags |= UNP_FEIDS;
900 		}
901 
902 		so2 = so3;
903 	} else {
904 		if (so2 != so)
905 			solock_pair(so, so2);
906 		else
907 			solock(so);
908 	}
909 
910 	error = unp_connect2(so, so2);
911 
912 	sounlock(so);
913 
914 	/*
915 	 * `so2' can't be PRU_ABORT'ed concurrently
916 	 */
917 	if (so2 != so)
918 		sounlock(so2);
919 put:
920 	vput(vp);
921 unlock:
922 	KERNEL_UNLOCK();
923 	solock(so);
924 	unp->unp_flags &= ~UNP_CONNECTING;
925 
926 	/*
927 	 * The peer socket could be closed by concurrent thread
928 	 * when `so' and `vp' are unlocked.
929 	 */
930 	if (error == 0 && unp->unp_conn == NULL)
931 		error = ECONNREFUSED;
932 
933 	return (error);
934 }
935 
936 int
937 unp_connect2(struct socket *so, struct socket *so2)
938 {
939 	struct unpcb *unp = sotounpcb(so);
940 	struct unpcb *unp2;
941 
942 	soassertlocked(so);
943 	soassertlocked(so2);
944 
945 	if (so2->so_type != so->so_type)
946 		return (EPROTOTYPE);
947 	unp2 = sotounpcb(so2);
948 	unp->unp_conn = unp2;
949 	switch (so->so_type) {
950 
951 	case SOCK_DGRAM:
952 		SLIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_nextref);
953 		soisconnected(so);
954 		break;
955 
956 	case SOCK_STREAM:
957 	case SOCK_SEQPACKET:
958 		unp2->unp_conn = unp;
959 		soisconnected(so);
960 		soisconnected(so2);
961 		break;
962 
963 	default:
964 		panic("unp_connect2");
965 	}
966 	return (0);
967 }
968 
969 void
970 unp_disconnect(struct unpcb *unp)
971 {
972 	struct socket *so2;
973 	struct unpcb *unp2;
974 
975 	if ((so2 = unp_solock_peer(unp->unp_socket)) == NULL)
976 		return;
977 
978 	unp2 = unp->unp_conn;
979 	unp->unp_conn = NULL;
980 
981 	switch (unp->unp_socket->so_type) {
982 
983 	case SOCK_DGRAM:
984 		SLIST_REMOVE(&unp2->unp_refs, unp, unpcb, unp_nextref);
985 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
986 		break;
987 
988 	case SOCK_STREAM:
989 	case SOCK_SEQPACKET:
990 		unp->unp_socket->so_snd.sb_mbcnt = 0;
991 		unp->unp_socket->so_snd.sb_cc = 0;
992 		soisdisconnected(unp->unp_socket);
993 		unp2->unp_conn = NULL;
994 		unp2->unp_socket->so_snd.sb_mbcnt = 0;
995 		unp2->unp_socket->so_snd.sb_cc = 0;
996 		soisdisconnected(unp2->unp_socket);
997 		break;
998 	}
999 
1000 	if (so2 != unp->unp_socket)
1001 		sounlock(so2);
1002 }
1003 
1004 static struct unpcb *
1005 fptounp(struct file *fp)
1006 {
1007 	struct socket *so;
1008 
1009 	if (fp->f_type != DTYPE_SOCKET)
1010 		return (NULL);
1011 	if ((so = fp->f_data) == NULL)
1012 		return (NULL);
1013 	if (so->so_proto->pr_domain != &unixdomain)
1014 		return (NULL);
1015 	return (sotounpcb(so));
1016 }
1017 
1018 int
1019 unp_externalize(struct mbuf *rights, socklen_t controllen, int flags)
1020 {
1021 	struct proc *p = curproc;		/* XXX */
1022 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
1023 	struct filedesc *fdp = p->p_fd;
1024 	int i, *fds = NULL;
1025 	struct fdpass *rp;
1026 	struct file *fp;
1027 	int nfds, error = 0;
1028 
1029 	/*
1030 	 * This code only works because SCM_RIGHTS is the only supported
1031 	 * control message type on unix sockets. Enforce this here.
1032 	 */
1033 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET)
1034 		return EINVAL;
1035 
1036 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
1037 	    sizeof(struct fdpass);
1038 	if (controllen < CMSG_ALIGN(sizeof(struct cmsghdr)))
1039 		controllen = 0;
1040 	else
1041 		controllen -= CMSG_ALIGN(sizeof(struct cmsghdr));
1042 	if (nfds > controllen / sizeof(int)) {
1043 		error = EMSGSIZE;
1044 		goto out;
1045 	}
1046 
1047 	/* Make sure the recipient should be able to see the descriptors.. */
1048 	rp = (struct fdpass *)CMSG_DATA(cm);
1049 
1050 	/* fdp->fd_rdir requires KERNEL_LOCK() */
1051 	KERNEL_LOCK();
1052 
1053 	for (i = 0; i < nfds; i++) {
1054 		fp = rp->fp;
1055 		rp++;
1056 		error = pledge_recvfd(p, fp);
1057 		if (error)
1058 			break;
1059 
1060 		/*
1061 		 * No to block devices.  If passing a directory,
1062 		 * make sure that it is underneath the root.
1063 		 */
1064 		if (fdp->fd_rdir != NULL && fp->f_type == DTYPE_VNODE) {
1065 			struct vnode *vp = (struct vnode *)fp->f_data;
1066 
1067 			if (vp->v_type == VBLK ||
1068 			    (vp->v_type == VDIR &&
1069 			    !vn_isunder(vp, fdp->fd_rdir, p))) {
1070 				error = EPERM;
1071 				break;
1072 			}
1073 		}
1074 	}
1075 
1076 	KERNEL_UNLOCK();
1077 
1078 	if (error)
1079 		goto out;
1080 
1081 	fds = mallocarray(nfds, sizeof(int), M_TEMP, M_WAITOK);
1082 
1083 	fdplock(fdp);
1084 restart:
1085 	/*
1086 	 * First loop -- allocate file descriptor table slots for the
1087 	 * new descriptors.
1088 	 */
1089 	rp = ((struct fdpass *)CMSG_DATA(cm));
1090 	for (i = 0; i < nfds; i++) {
1091 		if ((error = fdalloc(p, 0, &fds[i])) != 0) {
1092 			/*
1093 			 * Back out what we've done so far.
1094 			 */
1095 			for (--i; i >= 0; i--)
1096 				fdremove(fdp, fds[i]);
1097 
1098 			if (error == ENOSPC) {
1099 				fdexpand(p);
1100 				goto restart;
1101 			}
1102 
1103 			fdpunlock(fdp);
1104 
1105 			/*
1106 			 * This is the error that has historically
1107 			 * been returned, and some callers may
1108 			 * expect it.
1109 			 */
1110 
1111 			error = EMSGSIZE;
1112 			goto out;
1113 		}
1114 
1115 		/*
1116 		 * Make the slot reference the descriptor so that
1117 		 * fdalloc() works properly.. We finalize it all
1118 		 * in the loop below.
1119 		 */
1120 		mtx_enter(&fdp->fd_fplock);
1121 		KASSERT(fdp->fd_ofiles[fds[i]] == NULL);
1122 		fdp->fd_ofiles[fds[i]] = rp->fp;
1123 		mtx_leave(&fdp->fd_fplock);
1124 
1125 		fdp->fd_ofileflags[fds[i]] = (rp->flags & UF_PLEDGED);
1126 		if (flags & MSG_CMSG_CLOEXEC)
1127 			fdp->fd_ofileflags[fds[i]] |= UF_EXCLOSE;
1128 
1129 		rp++;
1130 	}
1131 
1132 	/*
1133 	 * Keep `fdp' locked to prevent concurrent close() of just
1134 	 * inserted descriptors. Such descriptors could have the only
1135 	 * `f_count' reference which is now shared between control
1136 	 * message and `fdp'.
1137 	 */
1138 
1139 	/*
1140 	 * Now that adding them has succeeded, update all of the
1141 	 * descriptor passing state.
1142 	 */
1143 	rp = (struct fdpass *)CMSG_DATA(cm);
1144 
1145 	for (i = 0; i < nfds; i++) {
1146 		struct unpcb *unp;
1147 
1148 		fp = rp->fp;
1149 		rp++;
1150 		if ((unp = fptounp(fp)) != NULL) {
1151 			rw_enter_write(&unp_gc_lock);
1152 			unp->unp_msgcount--;
1153 			rw_exit_write(&unp_gc_lock);
1154 		}
1155 	}
1156 	fdpunlock(fdp);
1157 
1158 	mtx_enter(&unp_rights_mtx);
1159 	unp_rights -= nfds;
1160 	mtx_leave(&unp_rights_mtx);
1161 
1162 	/*
1163 	 * Copy temporary array to message and adjust length, in case of
1164 	 * transition from large struct file pointers to ints.
1165 	 */
1166 	memcpy(CMSG_DATA(cm), fds, nfds * sizeof(int));
1167 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
1168 	rights->m_len = CMSG_LEN(nfds * sizeof(int));
1169  out:
1170 	if (fds != NULL)
1171 		free(fds, M_TEMP, nfds * sizeof(int));
1172 
1173 	if (error) {
1174 		if (nfds > 0) {
1175 			/*
1176 			 * No lock required. We are the only `cm' holder.
1177 			 */
1178 			rp = ((struct fdpass *)CMSG_DATA(cm));
1179 			unp_discard(rp, nfds);
1180 		}
1181 	}
1182 
1183 	return (error);
1184 }
1185 
1186 int
1187 unp_internalize(struct mbuf *control, struct proc *p)
1188 {
1189 	struct filedesc *fdp = p->p_fd;
1190 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1191 	struct fdpass *rp;
1192 	struct file *fp;
1193 	struct unpcb *unp;
1194 	int i, error;
1195 	int nfds, *ip, fd, neededspace;
1196 
1197 	/*
1198 	 * Check for two potential msg_controllen values because
1199 	 * IETF stuck their nose in a place it does not belong.
1200 	 */
1201 	if (control->m_len < CMSG_LEN(0) || cm->cmsg_len < CMSG_LEN(0))
1202 		return (EINVAL);
1203 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
1204 	    !(cm->cmsg_len == control->m_len ||
1205 	    control->m_len == CMSG_ALIGN(cm->cmsg_len)))
1206 		return (EINVAL);
1207 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof (int);
1208 
1209 	mtx_enter(&unp_rights_mtx);
1210 	if (unp_rights + nfds > maxfiles / 10) {
1211 		mtx_leave(&unp_rights_mtx);
1212 		return (EMFILE);
1213 	}
1214 	unp_rights += nfds;
1215 	mtx_leave(&unp_rights_mtx);
1216 
1217 	/* Make sure we have room for the struct file pointers */
1218 morespace:
1219 	neededspace = CMSG_SPACE(nfds * sizeof(struct fdpass)) -
1220 	    control->m_len;
1221 	if (neededspace > m_trailingspace(control)) {
1222 		char *tmp;
1223 		/* if we already have a cluster, the message is just too big */
1224 		if (control->m_flags & M_EXT) {
1225 			error = E2BIG;
1226 			goto nospace;
1227 		}
1228 
1229 		/* copy cmsg data temporarily out of the mbuf */
1230 		tmp = malloc(control->m_len, M_TEMP, M_WAITOK);
1231 		memcpy(tmp, mtod(control, caddr_t), control->m_len);
1232 
1233 		/* allocate a cluster and try again */
1234 		MCLGET(control, M_WAIT);
1235 		if ((control->m_flags & M_EXT) == 0) {
1236 			free(tmp, M_TEMP, control->m_len);
1237 			error = ENOBUFS;       /* allocation failed */
1238 			goto nospace;
1239 		}
1240 
1241 		/* copy the data back into the cluster */
1242 		cm = mtod(control, struct cmsghdr *);
1243 		memcpy(cm, tmp, control->m_len);
1244 		free(tmp, M_TEMP, control->m_len);
1245 		goto morespace;
1246 	}
1247 
1248 	/* adjust message & mbuf to note amount of space actually used. */
1249 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct fdpass));
1250 	control->m_len = CMSG_SPACE(nfds * sizeof(struct fdpass));
1251 
1252 	ip = ((int *)CMSG_DATA(cm)) + nfds - 1;
1253 	rp = ((struct fdpass *)CMSG_DATA(cm)) + nfds - 1;
1254 	fdplock(fdp);
1255 	for (i = 0; i < nfds; i++) {
1256 		memcpy(&fd, ip, sizeof fd);
1257 		ip--;
1258 		if ((fp = fd_getfile(fdp, fd)) == NULL) {
1259 			error = EBADF;
1260 			goto fail;
1261 		}
1262 		if (fp->f_count >= FDUP_MAX_COUNT) {
1263 			error = EDEADLK;
1264 			goto fail;
1265 		}
1266 		error = pledge_sendfd(p, fp);
1267 		if (error)
1268 			goto fail;
1269 
1270 		/* kqueue descriptors cannot be copied */
1271 		if (fp->f_type == DTYPE_KQUEUE) {
1272 			error = EINVAL;
1273 			goto fail;
1274 		}
1275 #if NKCOV > 0
1276 		/* kcov descriptors cannot be copied */
1277 		if (fp->f_type == DTYPE_VNODE && kcov_vnode(fp->f_data)) {
1278 			error = EINVAL;
1279 			goto fail;
1280 		}
1281 #endif
1282 		rp->fp = fp;
1283 		rp->flags = fdp->fd_ofileflags[fd] & UF_PLEDGED;
1284 		rp--;
1285 		if ((unp = fptounp(fp)) != NULL) {
1286 			rw_enter_write(&unp_gc_lock);
1287 			unp->unp_msgcount++;
1288 			unp->unp_file = fp;
1289 			rw_exit_write(&unp_gc_lock);
1290 		}
1291 	}
1292 	fdpunlock(fdp);
1293 	return (0);
1294 fail:
1295 	fdpunlock(fdp);
1296 	if (fp != NULL)
1297 		FRELE(fp, p);
1298 	/* Back out what we just did. */
1299 	for ( ; i > 0; i--) {
1300 		rp++;
1301 		fp = rp->fp;
1302 		if ((unp = fptounp(fp)) != NULL) {
1303 			rw_enter_write(&unp_gc_lock);
1304 			unp->unp_msgcount--;
1305 			rw_exit_write(&unp_gc_lock);
1306 		}
1307 		FRELE(fp, p);
1308 	}
1309 
1310 nospace:
1311 	mtx_enter(&unp_rights_mtx);
1312 	unp_rights -= nfds;
1313 	mtx_leave(&unp_rights_mtx);
1314 
1315 	return (error);
1316 }
1317 
1318 void
1319 unp_gc(void *arg __unused)
1320 {
1321 	struct unp_deferral *defer;
1322 	struct file *fp;
1323 	struct socket *so;
1324 	struct unpcb *unp;
1325 	int nunref, i;
1326 
1327 	rw_enter_write(&unp_gc_lock);
1328 	if (unp_gcing)
1329 		goto unlock;
1330 	unp_gcing = 1;
1331 	rw_exit_write(&unp_gc_lock);
1332 
1333 	rw_enter_write(&unp_df_lock);
1334 	/* close any fds on the deferred list */
1335 	while ((defer = SLIST_FIRST(&unp_deferred)) != NULL) {
1336 		SLIST_REMOVE_HEAD(&unp_deferred, ud_link);
1337 		rw_exit_write(&unp_df_lock);
1338 		for (i = 0; i < defer->ud_n; i++) {
1339 			fp = defer->ud_fp[i].fp;
1340 			if (fp == NULL)
1341 				continue;
1342 			if ((unp = fptounp(fp)) != NULL) {
1343 				rw_enter_write(&unp_gc_lock);
1344 				unp->unp_msgcount--;
1345 				rw_exit_write(&unp_gc_lock);
1346 			}
1347 			mtx_enter(&unp_rights_mtx);
1348 			unp_rights--;
1349 			mtx_leave(&unp_rights_mtx);
1350 			 /* closef() expects a refcount of 2 */
1351 			FREF(fp);
1352 			(void) closef(fp, NULL);
1353 		}
1354 		free(defer, M_TEMP, sizeof(*defer) +
1355 		    sizeof(struct fdpass) * defer->ud_n);
1356 		rw_enter_write(&unp_df_lock);
1357 	}
1358 	rw_exit_write(&unp_df_lock);
1359 
1360 	nunref = 0;
1361 
1362 	rw_enter_write(&unp_gc_lock);
1363 
1364 	/*
1365 	 * Determine sockets which may be prospectively dead. Such
1366 	 * sockets have their `unp_msgcount' equal to the `f_count'.
1367 	 * If `unp_msgcount' is 0, the socket has not been passed
1368 	 * and can't be unreferenced.
1369 	 */
1370 	LIST_FOREACH(unp, &unp_head, unp_link) {
1371 		unp->unp_gcflags = 0;
1372 
1373 		if (unp->unp_msgcount == 0)
1374 			continue;
1375 		if ((fp = unp->unp_file) == NULL)
1376 			continue;
1377 		if (fp->f_count == unp->unp_msgcount) {
1378 			unp->unp_gcflags |= UNP_GCDEAD;
1379 			unp->unp_gcrefs = unp->unp_msgcount;
1380 			nunref++;
1381 		}
1382 	}
1383 
1384 	/*
1385 	 * Scan all sockets previously marked as dead. Remove
1386 	 * the `unp_gcrefs' reference each socket holds on any
1387 	 * dead socket in its buffer.
1388 	 */
1389 	LIST_FOREACH(unp, &unp_head, unp_link) {
1390 		if ((unp->unp_gcflags & UNP_GCDEAD) == 0)
1391 			continue;
1392 		so = unp->unp_socket;
1393 		solock(so);
1394 		unp_scan(so->so_rcv.sb_mb, unp_remove_gcrefs);
1395 		sounlock(so);
1396 	}
1397 
1398 	/*
1399 	 * If the dead socket has `unp_gcrefs' reference counter
1400 	 * greater than 0, it can't be unreferenced. Mark it as
1401 	 * alive and increment the `unp_gcrefs' reference for each
1402 	 * dead socket within its buffer. Repeat this until we
1403 	 * have no new alive sockets found.
1404 	 */
1405 	do {
1406 		unp_defer = 0;
1407 
1408 		LIST_FOREACH(unp, &unp_head, unp_link) {
1409 			if ((unp->unp_gcflags & UNP_GCDEAD) == 0)
1410 				continue;
1411 			if (unp->unp_gcrefs == 0)
1412 				continue;
1413 
1414 			unp->unp_gcflags &= ~UNP_GCDEAD;
1415 
1416 			so = unp->unp_socket;
1417 			solock(so);
1418 			unp_scan(so->so_rcv.sb_mb, unp_restore_gcrefs);
1419 			sounlock(so);
1420 
1421 			KASSERT(nunref > 0);
1422 			nunref--;
1423 		}
1424 	} while (unp_defer > 0);
1425 
1426 	/*
1427 	 * If there are any unreferenced sockets, then for each dispose
1428 	 * of files in its receive buffer and then close it.
1429 	 */
1430 	if (nunref) {
1431 		LIST_FOREACH(unp, &unp_head, unp_link) {
1432 			if (unp->unp_gcflags & UNP_GCDEAD) {
1433 				/*
1434 				 * This socket could still be connected
1435 				 * and if so it's `so_rcv' is still
1436 				 * accessible by concurrent PRU_SEND
1437 				 * thread.
1438 				 */
1439 				so = unp->unp_socket;
1440 				solock(so);
1441 				unp_scan(so->so_rcv.sb_mb, unp_discard);
1442 				sounlock(so);
1443 			}
1444 		}
1445 	}
1446 
1447 	unp_gcing = 0;
1448 unlock:
1449 	rw_exit_write(&unp_gc_lock);
1450 }
1451 
1452 void
1453 unp_dispose(struct mbuf *m)
1454 {
1455 
1456 	if (m)
1457 		unp_scan(m, unp_discard);
1458 }
1459 
1460 void
1461 unp_scan(struct mbuf *m0, void (*op)(struct fdpass *, int))
1462 {
1463 	struct mbuf *m;
1464 	struct fdpass *rp;
1465 	struct cmsghdr *cm;
1466 	int qfds;
1467 
1468 	while (m0) {
1469 		for (m = m0; m; m = m->m_next) {
1470 			if (m->m_type == MT_CONTROL &&
1471 			    m->m_len >= sizeof(*cm)) {
1472 				cm = mtod(m, struct cmsghdr *);
1473 				if (cm->cmsg_level != SOL_SOCKET ||
1474 				    cm->cmsg_type != SCM_RIGHTS)
1475 					continue;
1476 				qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof *cm))
1477 				    / sizeof(struct fdpass);
1478 				if (qfds > 0) {
1479 					rp = (struct fdpass *)CMSG_DATA(cm);
1480 					op(rp, qfds);
1481 				}
1482 				break;		/* XXX, but saves time */
1483 			}
1484 		}
1485 		m0 = m0->m_nextpkt;
1486 	}
1487 }
1488 
1489 void
1490 unp_discard(struct fdpass *rp, int nfds)
1491 {
1492 	struct unp_deferral *defer;
1493 
1494 	/* copy the file pointers to a deferral structure */
1495 	defer = malloc(sizeof(*defer) + sizeof(*rp) * nfds, M_TEMP, M_WAITOK);
1496 	defer->ud_n = nfds;
1497 	memcpy(&defer->ud_fp[0], rp, sizeof(*rp) * nfds);
1498 	memset(rp, 0, sizeof(*rp) * nfds);
1499 
1500 	rw_enter_write(&unp_df_lock);
1501 	SLIST_INSERT_HEAD(&unp_deferred, defer, ud_link);
1502 	rw_exit_write(&unp_df_lock);
1503 
1504 	task_add(systqmp, &unp_gc_task);
1505 }
1506 
1507 void
1508 unp_remove_gcrefs(struct fdpass *rp, int nfds)
1509 {
1510 	struct unpcb *unp;
1511 	int i;
1512 
1513 	rw_assert_wrlock(&unp_gc_lock);
1514 
1515 	for (i = 0; i < nfds; i++) {
1516 		if (rp[i].fp == NULL)
1517 			continue;
1518 		if ((unp = fptounp(rp[i].fp)) == NULL)
1519 			continue;
1520 		if (unp->unp_gcflags & UNP_GCDEAD) {
1521 			KASSERT(unp->unp_gcrefs > 0);
1522 			unp->unp_gcrefs--;
1523 		}
1524 	}
1525 }
1526 
1527 void
1528 unp_restore_gcrefs(struct fdpass *rp, int nfds)
1529 {
1530 	struct unpcb *unp;
1531 	int i;
1532 
1533 	rw_assert_wrlock(&unp_gc_lock);
1534 
1535 	for (i = 0; i < nfds; i++) {
1536 		if (rp[i].fp == NULL)
1537 			continue;
1538 		if ((unp = fptounp(rp[i].fp)) == NULL)
1539 			continue;
1540 		if (unp->unp_gcflags & UNP_GCDEAD) {
1541 			unp->unp_gcrefs++;
1542 			unp_defer++;
1543 		}
1544 	}
1545 }
1546 
1547 int
1548 unp_nam2sun(struct mbuf *nam, struct sockaddr_un **sun, size_t *pathlen)
1549 {
1550 	struct sockaddr *sa = mtod(nam, struct sockaddr *);
1551 	size_t size, len;
1552 
1553 	if (nam->m_len < offsetof(struct sockaddr, sa_data))
1554 		return EINVAL;
1555 	if (sa->sa_family != AF_UNIX)
1556 		return EAFNOSUPPORT;
1557 	if (sa->sa_len != nam->m_len)
1558 		return EINVAL;
1559 	if (sa->sa_len > sizeof(struct sockaddr_un))
1560 		return EINVAL;
1561 	*sun = (struct sockaddr_un *)sa;
1562 
1563 	/* ensure that sun_path is NUL terminated and fits */
1564 	size = (*sun)->sun_len - offsetof(struct sockaddr_un, sun_path);
1565 	len = strnlen((*sun)->sun_path, size);
1566 	if (len == sizeof((*sun)->sun_path))
1567 		return EINVAL;
1568 	if (len == size) {
1569 		if (m_trailingspace(nam) == 0)
1570 			return EINVAL;
1571 		nam->m_len++;
1572 		(*sun)->sun_len++;
1573 		(*sun)->sun_path[len] = '\0';
1574 	}
1575 	if (pathlen != NULL)
1576 		*pathlen = len;
1577 
1578 	return 0;
1579 }
1580