xref: /openbsd-src/sys/kern/uipc_usrreq.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /*	$OpenBSD: uipc_usrreq.c,v 1.123 2018/01/04 10:45:30 mpi 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 
54 void	uipc_setaddr(const struct unpcb *, struct mbuf *);
55 
56 /* list of all UNIX domain sockets, for unp_gc() */
57 LIST_HEAD(unp_head, unpcb) unp_head = LIST_HEAD_INITIALIZER(unp_head);
58 
59 /*
60  * Stack of sets of files that were passed over a socket but were
61  * not received and need to be closed.
62  */
63 struct	unp_deferral {
64 	SLIST_ENTRY(unp_deferral)	ud_link;
65 	int	ud_n;
66 	/* followed by ud_n struct fdpass */
67 	struct fdpass ud_fp[];
68 };
69 
70 void	unp_discard(struct fdpass *, int);
71 void	unp_mark(struct fdpass *, int);
72 void	unp_scan(struct mbuf *, void (*)(struct fdpass *, int));
73 int	unp_nam2sun(struct mbuf *, struct sockaddr_un **, size_t *);
74 
75 /* list of sets of files that were sent over sockets that are now closed */
76 SLIST_HEAD(,unp_deferral) unp_deferred = SLIST_HEAD_INITIALIZER(unp_deferred);
77 
78 struct task unp_gc_task = TASK_INITIALIZER(unp_gc, NULL);
79 
80 
81 /*
82  * Unix communications domain.
83  *
84  * TODO:
85  *	RDM
86  *	rethink name space problems
87  *	need a proper out-of-band
88  */
89 struct	sockaddr sun_noname = { sizeof(sun_noname), AF_UNIX };
90 ino_t	unp_ino;			/* prototype for fake inode numbers */
91 
92 void
93 uipc_setaddr(const struct unpcb *unp, struct mbuf *nam)
94 {
95 	if (unp != NULL && unp->unp_addr != NULL) {
96 		nam->m_len = unp->unp_addr->m_len;
97 		memcpy(mtod(nam, caddr_t), mtod(unp->unp_addr, caddr_t),
98 		    nam->m_len);
99 	} else {
100 		nam->m_len = sizeof(sun_noname);
101 		memcpy(mtod(nam, struct sockaddr *), &sun_noname,
102 		    nam->m_len);
103 	}
104 }
105 
106 int
107 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
108     struct mbuf *control, struct proc *p)
109 {
110 	struct unpcb *unp = sotounpcb(so);
111 	struct socket *so2;
112 	int error = 0;
113 
114 	if (req == PRU_CONTROL)
115 		return (EOPNOTSUPP);
116 	if (req != PRU_SEND && control && control->m_len) {
117 		error = EOPNOTSUPP;
118 		goto release;
119 	}
120 	if (unp == NULL) {
121 		error = EINVAL;
122 		goto release;
123 	}
124 
125 	NET_ASSERT_UNLOCKED();
126 
127 	switch (req) {
128 
129 	case PRU_BIND:
130 		error = unp_bind(unp, nam, p);
131 		break;
132 
133 	case PRU_LISTEN:
134 		if (unp->unp_vnode == NULL)
135 			error = EINVAL;
136 		break;
137 
138 	case PRU_CONNECT:
139 		error = unp_connect(so, nam, p);
140 		break;
141 
142 	case PRU_CONNECT2:
143 		error = unp_connect2(so, (struct socket *)nam);
144 		break;
145 
146 	case PRU_DISCONNECT:
147 		unp_disconnect(unp);
148 		break;
149 
150 	case PRU_ACCEPT:
151 		/*
152 		 * Pass back name of connected socket,
153 		 * if it was bound and we are still connected
154 		 * (our peer may have closed already!).
155 		 */
156 		uipc_setaddr(unp->unp_conn, nam);
157 		break;
158 
159 	case PRU_SHUTDOWN:
160 		socantsendmore(so);
161 		unp_shutdown(unp);
162 		break;
163 
164 	case PRU_RCVD:
165 		switch (so->so_type) {
166 
167 		case SOCK_DGRAM:
168 			panic("uipc 1");
169 			/*NOTREACHED*/
170 
171 		case SOCK_STREAM:
172 		case SOCK_SEQPACKET:
173 			if (unp->unp_conn == NULL)
174 				break;
175 			so2 = unp->unp_conn->unp_socket;
176 			/*
177 			 * Adjust backpressure on sender
178 			 * and wakeup any waiting to write.
179 			 */
180 			so2->so_snd.sb_mbcnt = so->so_rcv.sb_mbcnt;
181 			so2->so_snd.sb_cc = so->so_rcv.sb_cc;
182 			sowwakeup(so2);
183 			break;
184 
185 		default:
186 			panic("uipc 2");
187 		}
188 		break;
189 
190 	case PRU_SEND:
191 		if (control && (error = unp_internalize(control, p)))
192 			break;
193 		switch (so->so_type) {
194 
195 		case SOCK_DGRAM: {
196 			struct sockaddr *from;
197 
198 			if (nam) {
199 				if (unp->unp_conn) {
200 					error = EISCONN;
201 					break;
202 				}
203 				error = unp_connect(so, nam, p);
204 				if (error)
205 					break;
206 			} else {
207 				if (unp->unp_conn == NULL) {
208 					error = ENOTCONN;
209 					break;
210 				}
211 			}
212 			so2 = unp->unp_conn->unp_socket;
213 			if (unp->unp_addr)
214 				from = mtod(unp->unp_addr, struct sockaddr *);
215 			else
216 				from = &sun_noname;
217 			if (sbappendaddr(so2, &so2->so_rcv, from, m, control)) {
218 				sorwakeup(so2);
219 				m = NULL;
220 				control = NULL;
221 			} else
222 				error = ENOBUFS;
223 			if (nam)
224 				unp_disconnect(unp);
225 			break;
226 		}
227 
228 		case SOCK_STREAM:
229 		case SOCK_SEQPACKET:
230 			if (so->so_state & SS_CANTSENDMORE) {
231 				error = EPIPE;
232 				break;
233 			}
234 			if (unp->unp_conn == NULL) {
235 				error = ENOTCONN;
236 				break;
237 			}
238 			so2 = unp->unp_conn->unp_socket;
239 			/*
240 			 * Send to paired receive port, and then raise
241 			 * send buffer counts to maintain backpressure.
242 			 * Wake up readers.
243 			 */
244 			if (control) {
245 				if (sbappendcontrol(so2, &so2->so_rcv, m,
246 				    control)) {
247 					control = NULL;
248 				} else {
249 					error = ENOBUFS;
250 					break;
251 				}
252 			} else if (so->so_type == SOCK_SEQPACKET)
253 				sbappendrecord(so2, &so2->so_rcv, m);
254 			else
255 				sbappend(so2, &so2->so_rcv, m);
256 			so->so_snd.sb_mbcnt = so2->so_rcv.sb_mbcnt;
257 			so->so_snd.sb_cc = so2->so_rcv.sb_cc;
258 			sorwakeup(so2);
259 			m = NULL;
260 			break;
261 
262 		default:
263 			panic("uipc 4");
264 		}
265 		/* we need to undo unp_internalize in case of errors */
266 		if (control && error)
267 			unp_dispose(control);
268 		break;
269 
270 	case PRU_ABORT:
271 		unp_drop(unp, ECONNABORTED);
272 		break;
273 
274 	case PRU_SENSE: {
275 		struct stat *sb = (struct stat *)m;
276 
277 		sb->st_blksize = so->so_snd.sb_hiwat;
278 		sb->st_dev = NODEV;
279 		if (unp->unp_ino == 0)
280 			unp->unp_ino = unp_ino++;
281 		sb->st_atim.tv_sec =
282 		    sb->st_mtim.tv_sec =
283 		    sb->st_ctim.tv_sec = unp->unp_ctime.tv_sec;
284 		sb->st_atim.tv_nsec =
285 		    sb->st_mtim.tv_nsec =
286 		    sb->st_ctim.tv_nsec = unp->unp_ctime.tv_nsec;
287 		sb->st_ino = unp->unp_ino;
288 		return (0);
289 	}
290 
291 	case PRU_RCVOOB:
292 		return (EOPNOTSUPP);
293 
294 	case PRU_SENDOOB:
295 		error = EOPNOTSUPP;
296 		break;
297 
298 	case PRU_SOCKADDR:
299 		uipc_setaddr(unp, nam);
300 		break;
301 
302 	case PRU_PEERADDR:
303 		uipc_setaddr(unp->unp_conn, nam);
304 		break;
305 
306 	case PRU_SLOWTIMO:
307 		break;
308 
309 	default:
310 		panic("piusrreq");
311 	}
312 release:
313 	m_freem(control);
314 	m_freem(m);
315 	return (error);
316 }
317 
318 /*
319  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
320  * for stream sockets, although the total for sender and receiver is
321  * actually only PIPSIZ.
322  * Datagram sockets really use the sendspace as the maximum datagram size,
323  * and don't really want to reserve the sendspace.  Their recvspace should
324  * be large enough for at least one max-size datagram plus address.
325  */
326 #define	PIPSIZ	4096
327 u_long	unpst_sendspace = PIPSIZ;
328 u_long	unpst_recvspace = PIPSIZ;
329 u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
330 u_long	unpdg_recvspace = 4*1024;
331 
332 int	unp_rights;			/* file descriptors in flight */
333 
334 int
335 uipc_attach(struct socket *so, int proto)
336 {
337 	struct unpcb *unp;
338 	int error;
339 
340 	if (so->so_pcb)
341 		return EISCONN;
342 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
343 		switch (so->so_type) {
344 
345 		case SOCK_STREAM:
346 		case SOCK_SEQPACKET:
347 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
348 			break;
349 
350 		case SOCK_DGRAM:
351 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
352 			break;
353 
354 		default:
355 			panic("unp_attach");
356 		}
357 		if (error)
358 			return (error);
359 	}
360 	unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT|M_ZERO);
361 	if (unp == NULL)
362 		return (ENOBUFS);
363 	unp->unp_socket = so;
364 	so->so_pcb = unp;
365 	getnanotime(&unp->unp_ctime);
366 	LIST_INSERT_HEAD(&unp_head, unp, unp_link);
367 	return (0);
368 }
369 
370 int
371 uipc_detach(struct socket *so)
372 {
373 	struct unpcb *unp = sotounpcb(so);
374 
375 	if (unp == NULL)
376 		return (EINVAL);
377 
378 	NET_ASSERT_UNLOCKED();
379 
380 	unp_detach(unp);
381 
382 	return (0);
383 }
384 
385 void
386 unp_detach(struct unpcb *unp)
387 {
388 	struct vnode *vp;
389 
390 	LIST_REMOVE(unp, unp_link);
391 	if (unp->unp_vnode) {
392 		unp->unp_vnode->v_socket = NULL;
393 		vp = unp->unp_vnode;
394 		unp->unp_vnode = NULL;
395 		vrele(vp);
396 	}
397 	if (unp->unp_conn)
398 		unp_disconnect(unp);
399 	while (!SLIST_EMPTY(&unp->unp_refs))
400 		unp_drop(SLIST_FIRST(&unp->unp_refs), ECONNRESET);
401 	soisdisconnected(unp->unp_socket);
402 	unp->unp_socket->so_pcb = NULL;
403 	m_freem(unp->unp_addr);
404 	free(unp, M_PCB, sizeof *unp);
405 	if (unp_rights)
406 		task_add(systq, &unp_gc_task);
407 }
408 
409 int
410 unp_bind(struct unpcb *unp, struct mbuf *nam, struct proc *p)
411 {
412 	struct sockaddr_un *soun;
413 	struct mbuf *nam2;
414 	struct vnode *vp;
415 	struct vattr vattr;
416 	int error;
417 	struct nameidata nd;
418 	size_t pathlen;
419 
420 	if (unp->unp_vnode != NULL)
421 		return (EINVAL);
422 	if ((error = unp_nam2sun(nam, &soun, &pathlen)))
423 		return (error);
424 
425 	nam2 = m_getclr(M_WAITOK, MT_SONAME);
426 	nam2->m_len = sizeof(struct sockaddr_un);
427 	memcpy(mtod(nam2, struct sockaddr_un *), soun,
428 	    offsetof(struct sockaddr_un, sun_path) + pathlen);
429 	/* No need to NUL terminate: m_getclr() returns zero'd mbufs. */
430 
431 	soun = mtod(nam2, struct sockaddr_un *);
432 
433 	/* Fixup sun_len to keep it in sync with m_len. */
434 	soun->sun_len = nam2->m_len;
435 
436 	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT, UIO_SYSSPACE,
437 	    soun->sun_path, p);
438 	nd.ni_pledge = PLEDGE_UNIX;
439 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
440 	if ((error = namei(&nd)) != 0) {
441 		m_freem(nam2);
442 		return (error);
443 	}
444 	vp = nd.ni_vp;
445 	if (vp != NULL) {
446 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
447 		if (nd.ni_dvp == vp)
448 			vrele(nd.ni_dvp);
449 		else
450 			vput(nd.ni_dvp);
451 		vrele(vp);
452 		m_freem(nam2);
453 		return (EADDRINUSE);
454 	}
455 	VATTR_NULL(&vattr);
456 	vattr.va_type = VSOCK;
457 	vattr.va_mode = ACCESSPERMS &~ p->p_fd->fd_cmask;
458 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
459 	if (error) {
460 		m_freem(nam2);
461 		return (error);
462 	}
463 	unp->unp_addr = nam2;
464 	vp = nd.ni_vp;
465 	vp->v_socket = unp->unp_socket;
466 	unp->unp_vnode = vp;
467 	unp->unp_connid.uid = p->p_ucred->cr_uid;
468 	unp->unp_connid.gid = p->p_ucred->cr_gid;
469 	unp->unp_connid.pid = p->p_p->ps_pid;
470 	unp->unp_flags |= UNP_FEIDSBIND;
471 	VOP_UNLOCK(vp, p);
472 	return (0);
473 }
474 
475 int
476 unp_connect(struct socket *so, struct mbuf *nam, struct proc *p)
477 {
478 	struct sockaddr_un *soun;
479 	struct vnode *vp;
480 	struct socket *so2, *so3;
481 	struct unpcb *unp, *unp2, *unp3;
482 	struct nameidata nd;
483 	int error;
484 
485 	if ((error = unp_nam2sun(nam, &soun, NULL)))
486 		return (error);
487 
488 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, soun->sun_path, p);
489 	nd.ni_pledge = PLEDGE_UNIX;
490 	if ((error = namei(&nd)) != 0)
491 		return (error);
492 	vp = nd.ni_vp;
493 	if (vp->v_type != VSOCK) {
494 		error = ENOTSOCK;
495 		goto bad;
496 	}
497 	if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
498 		goto bad;
499 	so2 = vp->v_socket;
500 	if (so2 == NULL) {
501 		error = ECONNREFUSED;
502 		goto bad;
503 	}
504 	if (so->so_type != so2->so_type) {
505 		error = EPROTOTYPE;
506 		goto bad;
507 	}
508 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
509 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
510 		    (so3 = sonewconn(so2, 0)) == 0) {
511 			error = ECONNREFUSED;
512 			goto bad;
513 		}
514 		unp = sotounpcb(so);
515 		unp2 = sotounpcb(so2);
516 		unp3 = sotounpcb(so3);
517 		if (unp2->unp_addr)
518 			unp3->unp_addr =
519 			    m_copym(unp2->unp_addr, 0, M_COPYALL, M_NOWAIT);
520 		unp3->unp_connid.uid = p->p_ucred->cr_uid;
521 		unp3->unp_connid.gid = p->p_ucred->cr_gid;
522 		unp3->unp_connid.pid = p->p_p->ps_pid;
523 		unp3->unp_flags |= UNP_FEIDS;
524 		so2 = so3;
525 		if (unp2->unp_flags & UNP_FEIDSBIND) {
526 			unp->unp_connid = unp2->unp_connid;
527 			unp->unp_flags |= UNP_FEIDS;
528 		}
529 	}
530 	error = unp_connect2(so, so2);
531 bad:
532 	vput(vp);
533 	return (error);
534 }
535 
536 int
537 unp_connect2(struct socket *so, struct socket *so2)
538 {
539 	struct unpcb *unp = sotounpcb(so);
540 	struct unpcb *unp2;
541 
542 	if (so2->so_type != so->so_type)
543 		return (EPROTOTYPE);
544 	unp2 = sotounpcb(so2);
545 	unp->unp_conn = unp2;
546 	switch (so->so_type) {
547 
548 	case SOCK_DGRAM:
549 		SLIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_nextref);
550 		soisconnected(so);
551 		break;
552 
553 	case SOCK_STREAM:
554 	case SOCK_SEQPACKET:
555 		unp2->unp_conn = unp;
556 		soisconnected(so);
557 		soisconnected(so2);
558 		break;
559 
560 	default:
561 		panic("unp_connect2");
562 	}
563 	return (0);
564 }
565 
566 void
567 unp_disconnect(struct unpcb *unp)
568 {
569 	struct unpcb *unp2 = unp->unp_conn;
570 
571 	if (unp2 == NULL)
572 		return;
573 	unp->unp_conn = NULL;
574 	switch (unp->unp_socket->so_type) {
575 
576 	case SOCK_DGRAM:
577 		SLIST_REMOVE(&unp2->unp_refs, unp, unpcb, unp_nextref);
578 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
579 		break;
580 
581 	case SOCK_STREAM:
582 	case SOCK_SEQPACKET:
583 		unp->unp_socket->so_snd.sb_mbcnt = 0;
584 		unp->unp_socket->so_snd.sb_cc = 0;
585 		soisdisconnected(unp->unp_socket);
586 		unp2->unp_conn = NULL;
587 		unp2->unp_socket->so_snd.sb_mbcnt = 0;
588 		unp2->unp_socket->so_snd.sb_cc = 0;
589 		soisdisconnected(unp2->unp_socket);
590 		break;
591 	}
592 }
593 
594 void
595 unp_shutdown(struct unpcb *unp)
596 {
597 	struct socket *so;
598 
599 	switch (unp->unp_socket->so_type) {
600 	case SOCK_STREAM:
601 	case SOCK_SEQPACKET:
602 		if (unp->unp_conn && (so = unp->unp_conn->unp_socket))
603 			socantrcvmore(so);
604 		break;
605 	default:
606 		break;
607 	}
608 }
609 
610 void
611 unp_drop(struct unpcb *unp, int errno)
612 {
613 	struct socket *so = unp->unp_socket;
614 
615 	so->so_error = errno;
616 	unp_disconnect(unp);
617 	if (so->so_head) {
618 		so->so_pcb = NULL;
619 		sofree(so);
620 		m_freem(unp->unp_addr);
621 		free(unp, M_PCB, sizeof *unp);
622 	}
623 }
624 
625 #ifdef notdef
626 unp_drain(void)
627 {
628 
629 }
630 #endif
631 
632 extern	struct domain unixdomain;
633 
634 static struct unpcb *
635 fptounp(struct file *fp)
636 {
637 	struct socket *so;
638 
639 	if (fp->f_type != DTYPE_SOCKET)
640 		return (NULL);
641 	if ((so = fp->f_data) == NULL)
642 		return (NULL);
643 	if (so->so_proto->pr_domain != &unixdomain)
644 		return (NULL);
645 	return (sotounpcb(so));
646 }
647 
648 int
649 unp_externalize(struct mbuf *rights, socklen_t controllen, int flags)
650 {
651 	struct proc *p = curproc;		/* XXX */
652 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
653 	int i, *fdp = NULL;
654 	struct fdpass *rp;
655 	struct file *fp;
656 	int nfds, error = 0;
657 
658 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
659 	    sizeof(struct fdpass);
660 	if (controllen < CMSG_ALIGN(sizeof(struct cmsghdr)))
661 		controllen = 0;
662 	else
663 		controllen -= CMSG_ALIGN(sizeof(struct cmsghdr));
664 	if (nfds > controllen / sizeof(int)) {
665 		error = EMSGSIZE;
666 		goto restart;
667 	}
668 
669 	/* Make sure the recipient should be able to see the descriptors.. */
670 	rp = (struct fdpass *)CMSG_DATA(cm);
671 	for (i = 0; i < nfds; i++) {
672 		fp = rp->fp;
673 		rp++;
674 		error = pledge_recvfd(p, fp);
675 		if (error)
676 			break;
677 
678 		/*
679 		 * No to block devices.  If passing a directory,
680 		 * make sure that it is underneath the root.
681 		 */
682 		if (p->p_fd->fd_rdir != NULL && fp->f_type == DTYPE_VNODE) {
683 			struct vnode *vp = (struct vnode *)fp->f_data;
684 
685 			if (vp->v_type == VBLK ||
686 			    (vp->v_type == VDIR &&
687 			    !vn_isunder(vp, p->p_fd->fd_rdir, p))) {
688 				error = EPERM;
689 				break;
690 			}
691 		}
692 	}
693 
694 	fdp = mallocarray(nfds, sizeof(int), M_TEMP, M_WAITOK);
695 
696 restart:
697 	fdplock(p->p_fd);
698 	if (error != 0) {
699 		if (nfds > 0) {
700 			rp = ((struct fdpass *)CMSG_DATA(cm));
701 			unp_discard(rp, nfds);
702 		}
703 		goto out;
704 	}
705 
706 	/*
707 	 * First loop -- allocate file descriptor table slots for the
708 	 * new descriptors.
709 	 */
710 	rp = ((struct fdpass *)CMSG_DATA(cm));
711 	for (i = 0; i < nfds; i++) {
712 		if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
713 			/*
714 			 * Back out what we've done so far.
715 			 */
716 			for (--i; i >= 0; i--)
717 				fdremove(p->p_fd, fdp[i]);
718 
719 			if (error == ENOSPC) {
720 				fdexpand(p);
721 				error = 0;
722 			} else {
723 				/*
724 				 * This is the error that has historically
725 				 * been returned, and some callers may
726 				 * expect it.
727 				 */
728 				error = EMSGSIZE;
729 			}
730 			fdpunlock(p->p_fd);
731 			goto restart;
732 		}
733 
734 		/*
735 		 * Make the slot reference the descriptor so that
736 		 * fdalloc() works properly.. We finalize it all
737 		 * in the loop below.
738 		 */
739 		p->p_fd->fd_ofiles[fdp[i]] = rp->fp;
740 		p->p_fd->fd_ofileflags[fdp[i]] = (rp->flags & UF_PLEDGED);
741 		rp++;
742 
743 		if (flags & MSG_CMSG_CLOEXEC)
744 			p->p_fd->fd_ofileflags[fdp[i]] |= UF_EXCLOSE;
745 	}
746 
747 	/*
748 	 * Now that adding them has succeeded, update all of the
749 	 * descriptor passing state.
750 	 */
751 	rp = (struct fdpass *)CMSG_DATA(cm);
752 	for (i = 0; i < nfds; i++) {
753 		struct unpcb *unp;
754 
755 		fp = rp->fp;
756 		rp++;
757 		if ((unp = fptounp(fp)) != NULL)
758 			unp->unp_msgcount--;
759 		unp_rights--;
760 	}
761 
762 	/*
763 	 * Copy temporary array to message and adjust length, in case of
764 	 * transition from large struct file pointers to ints.
765 	 */
766 	memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
767 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
768 	rights->m_len = CMSG_LEN(nfds * sizeof(int));
769  out:
770 	fdpunlock(p->p_fd);
771 	if (fdp)
772 		free(fdp, M_TEMP, nfds * sizeof(int));
773 	return (error);
774 }
775 
776 int
777 unp_internalize(struct mbuf *control, struct proc *p)
778 {
779 	struct filedesc *fdp = p->p_fd;
780 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
781 	struct fdpass *rp;
782 	struct file *fp;
783 	struct unpcb *unp;
784 	int i, error;
785 	int nfds, *ip, fd, neededspace;
786 
787 	/*
788 	 * Check for two potential msg_controllen values because
789 	 * IETF stuck their nose in a place it does not belong.
790 	 */
791 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
792 	    !(cm->cmsg_len == control->m_len ||
793 	    control->m_len == CMSG_ALIGN(cm->cmsg_len)))
794 		return (EINVAL);
795 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof (int);
796 
797 	if (unp_rights + nfds > maxfiles / 10)
798 		return (EMFILE);
799 
800 	/* Make sure we have room for the struct file pointers */
801 morespace:
802 	neededspace = CMSG_SPACE(nfds * sizeof(struct fdpass)) -
803 	    control->m_len;
804 	if (neededspace > M_TRAILINGSPACE(control)) {
805 		char *tmp;
806 		/* if we already have a cluster, the message is just too big */
807 		if (control->m_flags & M_EXT)
808 			return (E2BIG);
809 
810 		/* copy cmsg data temporarily out of the mbuf */
811 		tmp = malloc(control->m_len, M_TEMP, M_WAITOK);
812 		memcpy(tmp, mtod(control, caddr_t), control->m_len);
813 
814 		/* allocate a cluster and try again */
815 		MCLGET(control, M_WAIT);
816 		if ((control->m_flags & M_EXT) == 0) {
817 			free(tmp, M_TEMP, control->m_len);
818 			return (ENOBUFS);       /* allocation failed */
819 		}
820 
821 		/* copy the data back into the cluster */
822 		cm = mtod(control, struct cmsghdr *);
823 		memcpy(cm, tmp, control->m_len);
824 		free(tmp, M_TEMP, control->m_len);
825 		goto morespace;
826 	}
827 
828 	/* adjust message & mbuf to note amount of space actually used. */
829 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct fdpass));
830 	control->m_len = CMSG_SPACE(nfds * sizeof(struct fdpass));
831 
832 	ip = ((int *)CMSG_DATA(cm)) + nfds - 1;
833 	rp = ((struct fdpass *)CMSG_DATA(cm)) + nfds - 1;
834 	for (i = 0; i < nfds; i++) {
835 		memcpy(&fd, ip, sizeof fd);
836 		ip--;
837 		if ((fp = fd_getfile(fdp, fd)) == NULL) {
838 			error = EBADF;
839 			goto fail;
840 		}
841 		if (fp->f_count == LONG_MAX-2) {
842 			error = EDEADLK;
843 			goto fail;
844 		}
845 		error = pledge_sendfd(p, fp);
846 		if (error)
847 			goto fail;
848 
849 		/* kqueue descriptors cannot be copied */
850 		if (fp->f_type == DTYPE_KQUEUE) {
851 			error = EINVAL;
852 			goto fail;
853 		}
854 		rp->fp = fp;
855 		rp->flags = fdp->fd_ofileflags[fd] & UF_PLEDGED;
856 		rp--;
857 		fp->f_count++;
858 		if ((unp = fptounp(fp)) != NULL) {
859 			unp->unp_file = fp;
860 			unp->unp_msgcount++;
861 		}
862 		unp_rights++;
863 	}
864 	return (0);
865 fail:
866 	/* Back out what we just did. */
867 	for ( ; i > 0; i--) {
868 		rp++;
869 		fp = rp->fp;
870 		fp->f_count--;
871 		if ((unp = fptounp(fp)) != NULL)
872 			unp->unp_msgcount--;
873 		unp_rights--;
874 	}
875 
876 	return (error);
877 }
878 
879 int	unp_defer, unp_gcing;
880 
881 void
882 unp_gc(void *arg __unused)
883 {
884 	struct unp_deferral *defer;
885 	struct file *fp;
886 	struct socket *so;
887 	struct unpcb *unp;
888 	int nunref, i;
889 
890 	if (unp_gcing)
891 		return;
892 	unp_gcing = 1;
893 
894 	/* close any fds on the deferred list */
895 	while ((defer = SLIST_FIRST(&unp_deferred)) != NULL) {
896 		SLIST_REMOVE_HEAD(&unp_deferred, ud_link);
897 		for (i = 0; i < defer->ud_n; i++) {
898 			fp = defer->ud_fp[i].fp;
899 			if (fp == NULL)
900 				continue;
901 			FREF(fp);
902 			if ((unp = fptounp(fp)) != NULL)
903 				unp->unp_msgcount--;
904 			unp_rights--;
905 			(void) closef(fp, NULL);
906 		}
907 		free(defer, M_TEMP, sizeof(*defer) +
908 		    sizeof(struct fdpass) * defer->ud_n);
909 	}
910 
911 	unp_defer = 0;
912 	LIST_FOREACH(unp, &unp_head, unp_link)
913 		unp->unp_flags &= ~(UNP_GCMARK | UNP_GCDEFER | UNP_GCDEAD);
914 	do {
915 		nunref = 0;
916 		LIST_FOREACH(unp, &unp_head, unp_link) {
917 			if (unp->unp_flags & UNP_GCDEFER) {
918 				/*
919 				 * This socket is referenced by another
920 				 * socket which is known to be live,
921 				 * so it's certainly live.
922 				 */
923 				unp->unp_flags &= ~UNP_GCDEFER;
924 				unp_defer--;
925 			} else if (unp->unp_flags & UNP_GCMARK) {
926 				/* marked as live in previous pass */
927 				continue;
928 			} else if ((fp = unp->unp_file) == NULL) {
929 				/* not being passed, so can't be in loop */
930 			} else if (fp->f_count == 0) {
931 				/*
932 				 * Already being closed, let normal close
933 				 * path take its course
934 				 */
935 			} else {
936 				/*
937 				 * Unreferenced by other sockets so far,
938 				 * so if all the references (f_count) are
939 				 * from passing (unp_msgcount) then this
940 				 * socket is prospectively dead
941 				 */
942 				if (fp->f_count == unp->unp_msgcount) {
943 					nunref++;
944 					unp->unp_flags |= UNP_GCDEAD;
945 					continue;
946 				}
947 			}
948 
949 			/*
950 			 * This is the first time we've seen this socket on
951 			 * the mark pass and known it has a live reference,
952 			 * so mark it, then scan its receive buffer for
953 			 * sockets and note them as deferred (== referenced,
954 			 * but not yet marked).
955 			 */
956 			unp->unp_flags |= UNP_GCMARK;
957 
958 			so = unp->unp_socket;
959 			unp_scan(so->so_rcv.sb_mb, unp_mark);
960 		}
961 	} while (unp_defer);
962 
963 	/*
964 	 * If there are any unreferenced sockets, then for each dispose
965 	 * of files in its receive buffer and then close it.
966 	 */
967 	if (nunref) {
968 		LIST_FOREACH(unp, &unp_head, unp_link) {
969 			if (unp->unp_flags & UNP_GCDEAD)
970 				unp_scan(unp->unp_socket->so_rcv.sb_mb,
971 				    unp_discard);
972 		}
973 	}
974 	unp_gcing = 0;
975 }
976 
977 void
978 unp_dispose(struct mbuf *m)
979 {
980 
981 	if (m)
982 		unp_scan(m, unp_discard);
983 }
984 
985 void
986 unp_scan(struct mbuf *m0, void (*op)(struct fdpass *, int))
987 {
988 	struct mbuf *m;
989 	struct fdpass *rp;
990 	struct cmsghdr *cm;
991 	int qfds;
992 
993 	while (m0) {
994 		for (m = m0; m; m = m->m_next) {
995 			if (m->m_type == MT_CONTROL &&
996 			    m->m_len >= sizeof(*cm)) {
997 				cm = mtod(m, struct cmsghdr *);
998 				if (cm->cmsg_level != SOL_SOCKET ||
999 				    cm->cmsg_type != SCM_RIGHTS)
1000 					continue;
1001 				qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof *cm))
1002 				    / sizeof(struct fdpass);
1003 				if (qfds > 0) {
1004 					rp = (struct fdpass *)CMSG_DATA(cm);
1005 					op(rp, qfds);
1006 				}
1007 				break;		/* XXX, but saves time */
1008 			}
1009 		}
1010 		m0 = m0->m_nextpkt;
1011 	}
1012 }
1013 
1014 void
1015 unp_mark(struct fdpass *rp, int nfds)
1016 {
1017 	struct unpcb *unp;
1018 	int i;
1019 
1020 	for (i = 0; i < nfds; i++) {
1021 		if (rp[i].fp == NULL)
1022 			continue;
1023 
1024 		unp = fptounp(rp[i].fp);
1025 		if (unp == NULL)
1026 			continue;
1027 
1028 		if (unp->unp_flags & (UNP_GCMARK|UNP_GCDEFER))
1029 			continue;
1030 
1031 		unp_defer++;
1032 		unp->unp_flags |= UNP_GCDEFER;
1033 		unp->unp_flags &= ~UNP_GCDEAD;
1034 	}
1035 }
1036 
1037 void
1038 unp_discard(struct fdpass *rp, int nfds)
1039 {
1040 	struct unp_deferral *defer;
1041 
1042 	/* copy the file pointers to a deferral structure */
1043 	defer = malloc(sizeof(*defer) + sizeof(*rp) * nfds, M_TEMP, M_WAITOK);
1044 	defer->ud_n = nfds;
1045 	memcpy(&defer->ud_fp[0], rp, sizeof(*rp) * nfds);
1046 	memset(rp, 0, sizeof(*rp) * nfds);
1047 	SLIST_INSERT_HEAD(&unp_deferred, defer, ud_link);
1048 
1049 	task_add(systq, &unp_gc_task);
1050 }
1051 
1052 int
1053 unp_nam2sun(struct mbuf *nam, struct sockaddr_un **sun, size_t *pathlen)
1054 {
1055 	struct sockaddr *sa = mtod(nam, struct sockaddr *);
1056 	size_t size, len;
1057 
1058 	if (nam->m_len < offsetof(struct sockaddr, sa_data))
1059 		return EINVAL;
1060 	if (sa->sa_family != AF_UNIX)
1061 		return EAFNOSUPPORT;
1062 	if (sa->sa_len != nam->m_len)
1063 		return EINVAL;
1064 	if (sa->sa_len > sizeof(struct sockaddr_un))
1065 		return EINVAL;
1066 	*sun = (struct sockaddr_un *)sa;
1067 
1068 	/* ensure that sun_path is NUL terminated and fits */
1069 	size = (*sun)->sun_len - offsetof(struct sockaddr_un, sun_path);
1070 	len = strnlen((*sun)->sun_path, size);
1071 	if (len == sizeof((*sun)->sun_path))
1072 		return EINVAL;
1073 	if (len == size) {
1074 		if (M_TRAILINGSPACE(nam) == 0)
1075 			return EINVAL;
1076 		nam->m_len++;
1077 		(*sun)->sun_len++;
1078 		(*sun)->sun_path[len] = '\0';
1079 	}
1080 	if (pathlen != NULL)
1081 		*pathlen = len;
1082 
1083 	return 0;
1084 }
1085