xref: /freebsd/sys/kern/uipc_usrreq.c (revision ef5d438ed4bc17ad7ece3e40fe4d1f9baf3aadf7)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
34  *	$Id: uipc_usrreq.c,v 1.12 1995/08/31 01:39:31 dyson Exp $
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/proc.h>
40 #include <sys/filedesc.h>
41 #include <sys/domain.h>
42 #include <sys/protosw.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/unpcb.h>
47 #include <sys/un.h>
48 #include <sys/namei.h>
49 #include <sys/vnode.h>
50 #include <sys/file.h>
51 #include <sys/stat.h>
52 #include <sys/mbuf.h>
53 
54 /*
55  * Unix communications domain.
56  *
57  * TODO:
58  *	SEQPACKET, RDM
59  *	rethink name space problems
60  *	need a proper out-of-band
61  */
62 static struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
63 static ino_t	unp_ino;		/* prototype for fake inode numbers */
64 
65 static int     unp_attach __P((struct socket *));
66 static void    unp_detach __P((struct unpcb *));
67 static int     unp_bind __P((struct unpcb *,struct mbuf *, struct proc *));
68 static int     unp_connect __P((struct socket *,struct mbuf *, struct proc *));
69 static void    unp_disconnect __P((struct unpcb *));
70 static void    unp_shutdown __P((struct unpcb *));
71 static void    unp_drop __P((struct unpcb *, int));
72 static void    unp_gc __P((void));
73 static void    unp_scan __P((struct mbuf *, void (*)(struct file *)));
74 static void    unp_mark __P((struct file *));
75 static void    unp_discard __P((struct file *));
76 static int     unp_internalize __P((struct mbuf *, struct proc *));
77 
78 
79 /*ARGSUSED*/
80 int
81 uipc_usrreq(so, req, m, nam, control)
82 	struct socket *so;
83 	int req;
84 	struct mbuf *m, *nam, *control;
85 {
86 	struct unpcb *unp = sotounpcb(so);
87 	register struct socket *so2;
88 	register int error = 0;
89 	struct proc *p = curproc;	/* XXX */
90 
91 	if (req == PRU_CONTROL)
92 		return (EOPNOTSUPP);
93 	if (req != PRU_SEND && control && control->m_len) {
94 		error = EOPNOTSUPP;
95 		goto release;
96 	}
97 	if (unp == 0 && req != PRU_ATTACH) {
98 		error = EINVAL;
99 		goto release;
100 	}
101 	switch (req) {
102 
103 	case PRU_ATTACH:
104 		if (unp) {
105 			error = EISCONN;
106 			break;
107 		}
108 		error = unp_attach(so);
109 		break;
110 
111 	case PRU_DETACH:
112 		unp_detach(unp);
113 		break;
114 
115 	case PRU_BIND:
116 		error = unp_bind(unp, nam, p);
117 		break;
118 
119 	case PRU_LISTEN:
120 		if (unp->unp_vnode == 0)
121 			error = EINVAL;
122 		break;
123 
124 	case PRU_CONNECT:
125 		error = unp_connect(so, nam, p);
126 		break;
127 
128 	case PRU_CONNECT2:
129 		error = unp_connect2(so, (struct socket *)nam);
130 		break;
131 
132 	case PRU_DISCONNECT:
133 		unp_disconnect(unp);
134 		break;
135 
136 	case PRU_ACCEPT:
137 		/*
138 		 * Pass back name of connected socket,
139 		 * if it was bound and we are still connected
140 		 * (our peer may have closed already!).
141 		 */
142 		if (unp->unp_conn && unp->unp_conn->unp_addr) {
143 			nam->m_len = unp->unp_conn->unp_addr->m_len;
144 			bcopy(mtod(unp->unp_conn->unp_addr, caddr_t),
145 			    mtod(nam, caddr_t), (unsigned)nam->m_len);
146 		} else {
147 			nam->m_len = sizeof(sun_noname);
148 			*(mtod(nam, struct sockaddr *)) = sun_noname;
149 		}
150 		break;
151 
152 	case PRU_SHUTDOWN:
153 		socantsendmore(so);
154 		unp_shutdown(unp);
155 		break;
156 
157 	case PRU_RCVD:
158 		switch (so->so_type) {
159 
160 		case SOCK_DGRAM:
161 			panic("uipc 1");
162 			/*NOTREACHED*/
163 
164 		case SOCK_STREAM:
165 #define	rcv (&so->so_rcv)
166 #define snd (&so2->so_snd)
167 			if (unp->unp_conn == 0)
168 				break;
169 			so2 = unp->unp_conn->unp_socket;
170 			/*
171 			 * Adjust backpressure on sender
172 			 * and wakeup any waiting to write.
173 			 */
174 			snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
175 			unp->unp_mbcnt = rcv->sb_mbcnt;
176 			snd->sb_hiwat += unp->unp_cc - rcv->sb_cc;
177 			unp->unp_cc = rcv->sb_cc;
178 			sowwakeup(so2);
179 #undef snd
180 #undef rcv
181 			break;
182 
183 		default:
184 			panic("uipc 2");
185 		}
186 		break;
187 
188 	case PRU_SEND:
189 	case PRU_SEND_EOF:
190 		if (control && (error = unp_internalize(control, p)))
191 			break;
192 		switch (so->so_type) {
193 
194 		case SOCK_DGRAM: {
195 			struct sockaddr *from;
196 
197 			if (nam) {
198 				if (unp->unp_conn) {
199 					error = EISCONN;
200 					break;
201 				}
202 				error = unp_connect(so, nam, p);
203 				if (error)
204 					break;
205 			} else {
206 				if (unp->unp_conn == 0) {
207 					error = ENOTCONN;
208 					break;
209 				}
210 			}
211 			so2 = unp->unp_conn->unp_socket;
212 			if (unp->unp_addr)
213 				from = mtod(unp->unp_addr, struct sockaddr *);
214 			else
215 				from = &sun_noname;
216 			if (sbappendaddr(&so2->so_rcv, from, m, control)) {
217 				sorwakeup(so2);
218 				m = 0;
219 				control = 0;
220 			} else
221 				error = ENOBUFS;
222 			if (nam)
223 				unp_disconnect(unp);
224 			break;
225 		}
226 
227 		case SOCK_STREAM:
228 #define	rcv (&so2->so_rcv)
229 #define	snd (&so->so_snd)
230 			/* Connect if not connected yet. */
231 			/*
232 			 * Note: A better implementation would complain
233 			 * if not equal to the peer's address.
234 			 */
235 			if ((so->so_state & SS_ISCONNECTED) == 0) {
236 				if (nam) {
237 		    			error = unp_connect(so, nam, p);
238 					if (error)
239 						break;	/* XXX */
240 				} else {
241 					error = ENOTCONN;
242 					break;
243 				}
244 			}
245 
246 			if (so->so_state & SS_CANTSENDMORE) {
247 				error = EPIPE;
248 				break;
249 			}
250 			if (unp->unp_conn == 0)
251 				panic("uipc 3");
252 			so2 = unp->unp_conn->unp_socket;
253 			/*
254 			 * Send to paired receive port, and then reduce
255 			 * send buffer hiwater marks to maintain backpressure.
256 			 * Wake up readers.
257 			 */
258 			if (control) {
259 				if (sbappendcontrol(rcv, m, control))
260 					control = 0;
261 			} else
262 				sbappend(rcv, m);
263 			snd->sb_mbmax -=
264 			    rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
265 			unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
266 			snd->sb_hiwat -= rcv->sb_cc - unp->unp_conn->unp_cc;
267 			unp->unp_conn->unp_cc = rcv->sb_cc;
268 			sorwakeup(so2);
269 			m = 0;
270 #undef snd
271 #undef rcv
272 			break;
273 
274 		default:
275 			panic("uipc 4");
276 		}
277 		/*
278 		 * SEND_EOF is equivalent to a SEND followed by
279 		 * a SHUTDOWN.
280 		 */
281 		if (req == PRU_SEND_EOF) {
282 			socantsendmore(so);
283 			unp_shutdown(unp);
284 		}
285 		break;
286 
287 	case PRU_ABORT:
288 		unp_drop(unp, ECONNABORTED);
289 		break;
290 
291 	case PRU_SENSE:
292 		((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
293 		if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
294 			so2 = unp->unp_conn->unp_socket;
295 			((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
296 		}
297 		((struct stat *) m)->st_dev = NODEV;
298 		if (unp->unp_ino == 0)
299 			unp->unp_ino = unp_ino++;
300 		((struct stat *) m)->st_ino = unp->unp_ino;
301 		return (0);
302 
303 	case PRU_RCVOOB:
304 		return (EOPNOTSUPP);
305 
306 	case PRU_SENDOOB:
307 		error = EOPNOTSUPP;
308 		break;
309 
310 	case PRU_SOCKADDR:
311 		if (unp->unp_addr) {
312 			nam->m_len = unp->unp_addr->m_len;
313 			bcopy(mtod(unp->unp_addr, caddr_t),
314 			    mtod(nam, caddr_t), (unsigned)nam->m_len);
315 		} else
316 			nam->m_len = 0;
317 		break;
318 
319 	case PRU_PEERADDR:
320 		if (unp->unp_conn && unp->unp_conn->unp_addr) {
321 			nam->m_len = unp->unp_conn->unp_addr->m_len;
322 			bcopy(mtod(unp->unp_conn->unp_addr, caddr_t),
323 			    mtod(nam, caddr_t), (unsigned)nam->m_len);
324 		} else
325 			nam->m_len = 0;
326 		break;
327 
328 	case PRU_SLOWTIMO:
329 		break;
330 
331 	default:
332 		panic("piusrreq");
333 	}
334 release:
335 	if (control)
336 		m_freem(control);
337 	if (m)
338 		m_freem(m);
339 	return (error);
340 }
341 
342 /*
343  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
344  * for stream sockets, although the total for sender and receiver is
345  * actually only PIPSIZ.
346  * Datagram sockets really use the sendspace as the maximum datagram size,
347  * and don't really want to reserve the sendspace.  Their recvspace should
348  * be large enough for at least one max-size datagram plus address.
349  */
350 #ifndef PIPSIZ
351 #define	PIPSIZ	8192
352 #endif
353 static u_long	unpst_sendspace = PIPSIZ;
354 static u_long	unpst_recvspace = PIPSIZ;
355 static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
356 static u_long	unpdg_recvspace = 4*1024;
357 
358 static int	unp_rights;			/* file descriptors in flight */
359 
360 static int
361 unp_attach(so)
362 	struct socket *so;
363 {
364 	register struct mbuf *m;
365 	register struct unpcb *unp;
366 	int error;
367 
368 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
369 		switch (so->so_type) {
370 
371 		case SOCK_STREAM:
372 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
373 			break;
374 
375 		case SOCK_DGRAM:
376 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
377 			break;
378 
379 		default:
380 			panic("unp_attach");
381 		}
382 		if (error)
383 			return (error);
384 	}
385 	m = m_getclr(M_DONTWAIT, MT_PCB);
386 	if (m == NULL)
387 		return (ENOBUFS);
388 	unp = mtod(m, struct unpcb *);
389 	so->so_pcb = (caddr_t)unp;
390 	unp->unp_socket = so;
391 	return (0);
392 }
393 
394 static void
395 unp_detach(unp)
396 	register struct unpcb *unp;
397 {
398 
399 	if (unp->unp_vnode) {
400 		unp->unp_vnode->v_socket = 0;
401 		vrele(unp->unp_vnode);
402 		unp->unp_vnode = 0;
403 	}
404 	if (unp->unp_conn)
405 		unp_disconnect(unp);
406 	while (unp->unp_refs)
407 		unp_drop(unp->unp_refs, ECONNRESET);
408 	soisdisconnected(unp->unp_socket);
409 	unp->unp_socket->so_pcb = 0;
410 	if (unp_rights) {
411 		/*
412 		 * Normally the receive buffer is flushed later,
413 		 * in sofree, but if our receive buffer holds references
414 		 * to descriptors that are now garbage, we will dispose
415 		 * of those descriptor references after the garbage collector
416 		 * gets them (resulting in a "panic: closef: count < 0").
417 		 */
418 		sorflush(unp->unp_socket);
419 		unp_gc();
420 	}
421 	m_freem(unp->unp_addr);
422 	(void) m_free(dtom(unp));
423 }
424 
425 static int
426 unp_bind(unp, nam, p)
427 	struct unpcb *unp;
428 	struct mbuf *nam;
429 	struct proc *p;
430 {
431 	struct sockaddr_un *soun = mtod(nam, struct sockaddr_un *);
432 	register struct vnode *vp;
433 	struct vattr vattr;
434 	int error;
435 	struct nameidata nd;
436 
437 	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
438 		soun->sun_path, p);
439 	if (unp->unp_vnode != NULL)
440 		return (EINVAL);
441 	if (nam->m_len == MLEN) {
442 		if (*(mtod(nam, caddr_t) + nam->m_len - 1) != 0)
443 			return (EINVAL);
444 	} else
445 		*(mtod(nam, caddr_t) + nam->m_len) = 0;
446 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
447 	error = namei(&nd);
448 	if (error)
449 		return (error);
450 	vp = nd.ni_vp;
451 	if (vp != NULL) {
452 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
453 		if (nd.ni_dvp == vp)
454 			vrele(nd.ni_dvp);
455 		else
456 			vput(nd.ni_dvp);
457 		vrele(vp);
458 		return (EADDRINUSE);
459 	}
460 	VATTR_NULL(&vattr);
461 	vattr.va_type = VSOCK;
462 	vattr.va_mode = ACCESSPERMS;
463 	LEASE_CHECK(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
464 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
465 	if (error)
466 		return (error);
467 	vp = nd.ni_vp;
468 	vp->v_socket = unp->unp_socket;
469 	unp->unp_vnode = vp;
470 	unp->unp_addr = m_copy(nam, 0, (int)M_COPYALL);
471 	VOP_UNLOCK(vp);
472 	return (0);
473 }
474 
475 static int
476 unp_connect(so, nam, p)
477 	struct socket *so;
478 	struct mbuf *nam;
479 	struct proc *p;
480 {
481 	register struct sockaddr_un *soun = mtod(nam, struct sockaddr_un *);
482 	register struct vnode *vp;
483 	register struct socket *so2, *so3;
484 	struct unpcb *unp2, *unp3;
485 	int error;
486 	struct nameidata nd;
487 
488 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, soun->sun_path, p);
489 	if (nam->m_data + nam->m_len == &nam->m_dat[MLEN]) {	/* XXX */
490 		if (*(mtod(nam, caddr_t) + nam->m_len - 1) != 0)
491 			return (EMSGSIZE);
492 	} else
493 		*(mtod(nam, caddr_t) + nam->m_len) = 0;
494 	error = namei(&nd);
495 	if (error)
496 		return (error);
497 	vp = nd.ni_vp;
498 	if (vp->v_type != VSOCK) {
499 		error = ENOTSOCK;
500 		goto bad;
501 	}
502 	error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p);
503 	if (error)
504 		goto bad;
505 	so2 = vp->v_socket;
506 	if (so2 == 0) {
507 		error = ECONNREFUSED;
508 		goto bad;
509 	}
510 	if (so->so_type != so2->so_type) {
511 		error = EPROTOTYPE;
512 		goto bad;
513 	}
514 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
515 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
516 		    (so3 = sonewconn(so2, 0)) == 0) {
517 			error = ECONNREFUSED;
518 			goto bad;
519 		}
520 		unp2 = sotounpcb(so2);
521 		unp3 = sotounpcb(so3);
522 		if (unp2->unp_addr)
523 			unp3->unp_addr =
524 				  m_copy(unp2->unp_addr, 0, (int)M_COPYALL);
525 		so2 = so3;
526 	}
527 	error = unp_connect2(so, so2);
528 bad:
529 	vput(vp);
530 	return (error);
531 }
532 
533 int
534 unp_connect2(so, so2)
535 	register struct socket *so;
536 	register struct socket *so2;
537 {
538 	register struct unpcb *unp = sotounpcb(so);
539 	register struct unpcb *unp2;
540 
541 	if (so2->so_type != so->so_type)
542 		return (EPROTOTYPE);
543 	unp2 = sotounpcb(so2);
544 	unp->unp_conn = unp2;
545 	switch (so->so_type) {
546 
547 	case SOCK_DGRAM:
548 		unp->unp_nextref = unp2->unp_refs;
549 		unp2->unp_refs = unp;
550 		soisconnected(so);
551 		break;
552 
553 	case SOCK_STREAM:
554 		unp2->unp_conn = unp;
555 		soisconnected(so);
556 		soisconnected(so2);
557 		break;
558 
559 	default:
560 		panic("unp_connect2");
561 	}
562 	return (0);
563 }
564 
565 static void
566 unp_disconnect(unp)
567 	struct unpcb *unp;
568 {
569 	register struct unpcb *unp2 = unp->unp_conn;
570 
571 	if (unp2 == 0)
572 		return;
573 	unp->unp_conn = 0;
574 	switch (unp->unp_socket->so_type) {
575 
576 	case SOCK_DGRAM:
577 		if (unp2->unp_refs == unp)
578 			unp2->unp_refs = unp->unp_nextref;
579 		else {
580 			unp2 = unp2->unp_refs;
581 			for (;;) {
582 				if (unp2 == 0)
583 					panic("unp_disconnect");
584 				if (unp2->unp_nextref == unp)
585 					break;
586 				unp2 = unp2->unp_nextref;
587 			}
588 			unp2->unp_nextref = unp->unp_nextref;
589 		}
590 		unp->unp_nextref = 0;
591 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
592 		break;
593 
594 	case SOCK_STREAM:
595 		soisdisconnected(unp->unp_socket);
596 		unp2->unp_conn = 0;
597 		soisdisconnected(unp2->unp_socket);
598 		break;
599 	}
600 }
601 
602 #ifdef notdef
603 void
604 unp_abort(unp)
605 	struct unpcb *unp;
606 {
607 
608 	unp_detach(unp);
609 }
610 #endif
611 
612 static void
613 unp_shutdown(unp)
614 	struct unpcb *unp;
615 {
616 	struct socket *so;
617 
618 	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
619 	    (so = unp->unp_conn->unp_socket))
620 		socantrcvmore(so);
621 }
622 
623 static void
624 unp_drop(unp, errno)
625 	struct unpcb *unp;
626 	int errno;
627 {
628 	struct socket *so = unp->unp_socket;
629 
630 	so->so_error = errno;
631 	unp_disconnect(unp);
632 	if (so->so_head) {
633 		so->so_pcb = (caddr_t) 0;
634 		m_freem(unp->unp_addr);
635 		(void) m_free(dtom(unp));
636 		sofree(so);
637 	}
638 }
639 
640 #ifdef notdef
641 void
642 unp_drain()
643 {
644 
645 }
646 #endif
647 
648 int
649 unp_externalize(rights)
650 	struct mbuf *rights;
651 {
652 	struct proc *p = curproc;		/* XXX */
653 	register int i;
654 	register struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
655 	register struct file **rp = (struct file **)(cm + 1);
656 	register struct file *fp;
657 	int newfds = (cm->cmsg_len - sizeof(*cm)) / sizeof (int);
658 	int f;
659 
660 	if (!fdavail(p, newfds)) {
661 		for (i = 0; i < newfds; i++) {
662 			fp = *rp;
663 			unp_discard(fp);
664 			*rp++ = 0;
665 		}
666 		return (EMSGSIZE);
667 	}
668 	for (i = 0; i < newfds; i++) {
669 		if (fdalloc(p, 0, &f))
670 			panic("unp_externalize");
671 		fp = *rp;
672 		p->p_fd->fd_ofiles[f] = fp;
673 		fp->f_msgcount--;
674 		unp_rights--;
675 		*(int *)rp++ = f;
676 	}
677 	return (0);
678 }
679 
680 static int
681 unp_internalize(control, p)
682 	struct mbuf *control;
683 	struct proc *p;
684 {
685 	struct filedesc *fdp = p->p_fd;
686 	register struct cmsghdr *cm = mtod(control, struct cmsghdr *);
687 	register struct file **rp;
688 	register struct file *fp;
689 	register int i, fd;
690 	int oldfds;
691 
692 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
693 	    cm->cmsg_len != control->m_len)
694 		return (EINVAL);
695 	oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
696 	rp = (struct file **)(cm + 1);
697 	for (i = 0; i < oldfds; i++) {
698 		fd = *(int *)rp++;
699 		if ((unsigned)fd >= fdp->fd_nfiles ||
700 		    fdp->fd_ofiles[fd] == NULL)
701 			return (EBADF);
702 	}
703 	rp = (struct file **)(cm + 1);
704 	for (i = 0; i < oldfds; i++) {
705 		fp = fdp->fd_ofiles[*(int *)rp];
706 		*rp++ = fp;
707 		fp->f_count++;
708 		fp->f_msgcount++;
709 		unp_rights++;
710 	}
711 	return (0);
712 }
713 
714 static int	unp_defer, unp_gcing;
715 
716 static void
717 unp_gc()
718 {
719 	register struct file *fp, *nextfp;
720 	register struct socket *so;
721 	struct file **extra_ref, **fpp;
722 	int nunref, i;
723 
724 	if (unp_gcing)
725 		return;
726 	unp_gcing = 1;
727 	unp_defer = 0;
728 	for (fp = filehead; fp; fp = fp->f_filef)
729 		fp->f_flag &= ~(FMARK|FDEFER);
730 	do {
731 		for (fp = filehead; fp; fp = fp->f_filef) {
732 			if (fp->f_count == 0)
733 				continue;
734 			if (fp->f_flag & FDEFER) {
735 				fp->f_flag &= ~FDEFER;
736 				unp_defer--;
737 			} else {
738 				if (fp->f_flag & FMARK)
739 					continue;
740 				if (fp->f_count == fp->f_msgcount)
741 					continue;
742 				fp->f_flag |= FMARK;
743 			}
744 			if (fp->f_type != DTYPE_SOCKET ||
745 			    (so = (struct socket *)fp->f_data) == 0)
746 				continue;
747 			if (so->so_proto->pr_domain != &localdomain ||
748 			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
749 				continue;
750 #ifdef notdef
751 			if (so->so_rcv.sb_flags & SB_LOCK) {
752 				/*
753 				 * This is problematical; it's not clear
754 				 * we need to wait for the sockbuf to be
755 				 * unlocked (on a uniprocessor, at least),
756 				 * and it's also not clear what to do
757 				 * if sbwait returns an error due to receipt
758 				 * of a signal.  If sbwait does return
759 				 * an error, we'll go into an infinite
760 				 * loop.  Delete all of this for now.
761 				 */
762 				(void) sbwait(&so->so_rcv);
763 				goto restart;
764 			}
765 #endif
766 			unp_scan(so->so_rcv.sb_mb, unp_mark);
767 		}
768 	} while (unp_defer);
769 	/*
770 	 * We grab an extra reference to each of the file table entries
771 	 * that are not otherwise accessible and then free the rights
772 	 * that are stored in messages on them.
773 	 *
774 	 * The bug in the orginal code is a little tricky, so I'll describe
775 	 * what's wrong with it here.
776 	 *
777 	 * It is incorrect to simply unp_discard each entry for f_msgcount
778 	 * times -- consider the case of sockets A and B that contain
779 	 * references to each other.  On a last close of some other socket,
780 	 * we trigger a gc since the number of outstanding rights (unp_rights)
781 	 * is non-zero.  If during the sweep phase the gc code un_discards,
782 	 * we end up doing a (full) closef on the descriptor.  A closef on A
783 	 * results in the following chain.  Closef calls soo_close, which
784 	 * calls soclose.   Soclose calls first (through the switch
785 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
786 	 * returns because the previous instance had set unp_gcing, and
787 	 * we return all the way back to soclose, which marks the socket
788 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
789 	 * to free up the rights that are queued in messages on the socket A,
790 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
791 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
792 	 * instance of unp_discard just calls closef on B.
793 	 *
794 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
795 	 * which results in another closef on A.  Unfortunately, A is already
796 	 * being closed, and the descriptor has already been marked with
797 	 * SS_NOFDREF, and soclose panics at this point.
798 	 *
799 	 * Here, we first take an extra reference to each inaccessible
800 	 * descriptor.  Then, we call sorflush ourself, since we know
801 	 * it is a Unix domain socket anyhow.  After we destroy all the
802 	 * rights carried in messages, we do a last closef to get rid
803 	 * of our extra reference.  This is the last close, and the
804 	 * unp_detach etc will shut down the socket.
805 	 *
806 	 * 91/09/19, bsy@cs.cmu.edu
807 	 */
808 	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
809 	for (nunref = 0, fp = filehead, fpp = extra_ref; fp; fp = nextfp) {
810 		nextfp = fp->f_filef;
811 		if (fp->f_count == 0)
812 			continue;
813 		if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
814 			*fpp++ = fp;
815 			nunref++;
816 			fp->f_count++;
817 		}
818 	}
819 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
820 		sorflush((struct socket *)(*fpp)->f_data);
821 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
822 		closef(*fpp,(struct proc*) NULL);
823 	free((caddr_t)extra_ref, M_FILE);
824 	unp_gcing = 0;
825 }
826 
827 void
828 unp_dispose(m)
829 	struct mbuf *m;
830 {
831 	if (m)
832 		unp_scan(m, unp_discard);
833 }
834 
835 static void
836 unp_scan(m0, op)
837 	register struct mbuf *m0;
838 	void (*op)(struct file *);
839 {
840 	register struct mbuf *m;
841 	register struct file **rp;
842 	register struct cmsghdr *cm;
843 	register int i;
844 	int qfds;
845 
846 	while (m0) {
847 		for (m = m0; m; m = m->m_next)
848 			if (m->m_type == MT_CONTROL &&
849 			    m->m_len >= sizeof(*cm)) {
850 				cm = mtod(m, struct cmsghdr *);
851 				if (cm->cmsg_level != SOL_SOCKET ||
852 				    cm->cmsg_type != SCM_RIGHTS)
853 					continue;
854 				qfds = (cm->cmsg_len - sizeof *cm)
855 						/ sizeof (struct file *);
856 				rp = (struct file **)(cm + 1);
857 				for (i = 0; i < qfds; i++)
858 					(*op)(*rp++);
859 				break;		/* XXX, but saves time */
860 			}
861 		m0 = m0->m_act;
862 	}
863 }
864 
865 static void
866 unp_mark(fp)
867 	struct file *fp;
868 {
869 
870 	if (fp->f_flag & FMARK)
871 		return;
872 	unp_defer++;
873 	fp->f_flag |= (FMARK|FDEFER);
874 }
875 
876 static void
877 unp_discard(fp)
878 	struct file *fp;
879 {
880 
881 	fp->f_msgcount--;
882 	unp_rights--;
883 	(void) closef(fp, (struct proc *)NULL);
884 }
885