xref: /freebsd/sys/kern/uipc_usrreq.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
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  * $FreeBSD$
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/domain.h>
41 #include <sys/fcntl.h>
42 #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
43 #include <sys/file.h>
44 #include <sys/filedesc.h>
45 #include <sys/mbuf.h>
46 #include <sys/namei.h>
47 #include <sys/proc.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/stat.h>
52 #include <sys/sysctl.h>
53 #include <sys/un.h>
54 #include <sys/unpcb.h>
55 #include <sys/vnode.h>
56 
57 #include <vm/vm_zone.h>
58 
59 static	struct vm_zone *unp_zone;
60 static	unp_gen_t unp_gencnt;
61 static	u_int unp_count;
62 
63 static	struct unp_head unp_shead, unp_dhead;
64 
65 /*
66  * Unix communications domain.
67  *
68  * TODO:
69  *	SEQPACKET, RDM
70  *	rethink name space problems
71  *	need a proper out-of-band
72  *	lock pushdown
73  */
74 static struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
75 static ino_t	unp_ino;		/* prototype for fake inode numbers */
76 
77 static int     unp_attach __P((struct socket *));
78 static void    unp_detach __P((struct unpcb *));
79 static int     unp_bind __P((struct unpcb *,struct sockaddr *, struct proc *));
80 static int     unp_connect __P((struct socket *,struct sockaddr *,
81 				struct proc *));
82 static void    unp_disconnect __P((struct unpcb *));
83 static void    unp_shutdown __P((struct unpcb *));
84 static void    unp_drop __P((struct unpcb *, int));
85 static void    unp_gc __P((void));
86 static void    unp_scan __P((struct mbuf *, void (*)(struct file *)));
87 static void    unp_mark __P((struct file *));
88 static void    unp_discard __P((struct file *));
89 static int     unp_internalize __P((struct mbuf *, struct proc *));
90 
91 static int
92 uipc_abort(struct socket *so)
93 {
94 	struct unpcb *unp = sotounpcb(so);
95 
96 	if (unp == 0)
97 		return EINVAL;
98 	unp_drop(unp, ECONNABORTED);
99 	return 0;
100 }
101 
102 static int
103 uipc_accept(struct socket *so, struct sockaddr **nam)
104 {
105 	struct unpcb *unp = sotounpcb(so);
106 
107 	if (unp == 0)
108 		return EINVAL;
109 
110 	/*
111 	 * Pass back name of connected socket,
112 	 * if it was bound and we are still connected
113 	 * (our peer may have closed already!).
114 	 */
115 	if (unp->unp_conn && unp->unp_conn->unp_addr) {
116 		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
117 				    1);
118 	} else {
119 		*nam = dup_sockaddr((struct sockaddr *)&sun_noname, 1);
120 	}
121 	return 0;
122 }
123 
124 static int
125 uipc_attach(struct socket *so, int proto, struct proc *p)
126 {
127 	struct unpcb *unp = sotounpcb(so);
128 
129 	if (unp != 0)
130 		return EISCONN;
131 	return unp_attach(so);
132 }
133 
134 static int
135 uipc_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
136 {
137 	struct unpcb *unp = sotounpcb(so);
138 
139 	if (unp == 0)
140 		return EINVAL;
141 
142 	return unp_bind(unp, nam, p);
143 }
144 
145 static int
146 uipc_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
147 {
148 	struct unpcb *unp = sotounpcb(so);
149 
150 	if (unp == 0)
151 		return EINVAL;
152 	return unp_connect(so, nam, curproc);
153 }
154 
155 static int
156 uipc_connect2(struct socket *so1, struct socket *so2)
157 {
158 	struct unpcb *unp = sotounpcb(so1);
159 
160 	if (unp == 0)
161 		return EINVAL;
162 
163 	return unp_connect2(so1, so2);
164 }
165 
166 /* control is EOPNOTSUPP */
167 
168 static int
169 uipc_detach(struct socket *so)
170 {
171 	struct unpcb *unp = sotounpcb(so);
172 
173 	if (unp == 0)
174 		return EINVAL;
175 
176 	unp_detach(unp);
177 	return 0;
178 }
179 
180 static int
181 uipc_disconnect(struct socket *so)
182 {
183 	struct unpcb *unp = sotounpcb(so);
184 
185 	if (unp == 0)
186 		return EINVAL;
187 	unp_disconnect(unp);
188 	return 0;
189 }
190 
191 static int
192 uipc_listen(struct socket *so, struct proc *p)
193 {
194 	struct unpcb *unp = sotounpcb(so);
195 
196 	if (unp == 0 || unp->unp_vnode == 0)
197 		return EINVAL;
198 	return 0;
199 }
200 
201 static int
202 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
203 {
204 	struct unpcb *unp = sotounpcb(so);
205 
206 	if (unp == 0)
207 		return EINVAL;
208 	if (unp->unp_conn && unp->unp_conn->unp_addr)
209 		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
210 				    1);
211 	return 0;
212 }
213 
214 static int
215 uipc_rcvd(struct socket *so, int flags)
216 {
217 	struct unpcb *unp = sotounpcb(so);
218 	struct socket *so2;
219 
220 	if (unp == 0)
221 		return EINVAL;
222 	switch (so->so_type) {
223 	case SOCK_DGRAM:
224 		panic("uipc_rcvd DGRAM?");
225 		/*NOTREACHED*/
226 
227 	case SOCK_STREAM:
228 		if (unp->unp_conn == 0)
229 			break;
230 		so2 = unp->unp_conn->unp_socket;
231 		/*
232 		 * Adjust backpressure on sender
233 		 * and wakeup any waiting to write.
234 		 */
235 		so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
236 		unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
237 		so2->so_snd.sb_hiwat += unp->unp_cc - so->so_rcv.sb_cc;
238 		(void)chgsbsize(so2->so_cred->cr_uid,
239 		    (rlim_t)unp->unp_cc - so->so_rcv.sb_cc);
240 		unp->unp_cc = so->so_rcv.sb_cc;
241 		sowwakeup(so2);
242 		break;
243 
244 	default:
245 		panic("uipc_rcvd unknown socktype");
246 	}
247 	return 0;
248 }
249 
250 /* pru_rcvoob is EOPNOTSUPP */
251 
252 static int
253 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
254 	  struct mbuf *control, struct proc *p)
255 {
256 	int error = 0;
257 	struct unpcb *unp = sotounpcb(so);
258 	struct socket *so2;
259 
260 	if (unp == 0) {
261 		error = EINVAL;
262 		goto release;
263 	}
264 	if (flags & PRUS_OOB) {
265 		error = EOPNOTSUPP;
266 		goto release;
267 	}
268 
269 	if (control && (error = unp_internalize(control, p)))
270 		goto release;
271 
272 	switch (so->so_type) {
273 	case SOCK_DGRAM:
274 	{
275 		struct sockaddr *from;
276 
277 		if (nam) {
278 			if (unp->unp_conn) {
279 				error = EISCONN;
280 				break;
281 			}
282 			error = unp_connect(so, nam, p);
283 			if (error)
284 				break;
285 		} else {
286 			if (unp->unp_conn == 0) {
287 				error = ENOTCONN;
288 				break;
289 			}
290 		}
291 		so2 = unp->unp_conn->unp_socket;
292 		if (unp->unp_addr)
293 			from = (struct sockaddr *)unp->unp_addr;
294 		else
295 			from = &sun_noname;
296 		if (sbappendaddr(&so2->so_rcv, from, m, control)) {
297 			sorwakeup(so2);
298 			m = 0;
299 			control = 0;
300 		} else
301 			error = ENOBUFS;
302 		if (nam)
303 			unp_disconnect(unp);
304 		break;
305 	}
306 
307 	case SOCK_STREAM:
308 		/* Connect if not connected yet. */
309 		/*
310 		 * Note: A better implementation would complain
311 		 * if not equal to the peer's address.
312 		 */
313 		if ((so->so_state & SS_ISCONNECTED) == 0) {
314 			if (nam) {
315 				error = unp_connect(so, nam, p);
316 				if (error)
317 					break;	/* XXX */
318 			} else {
319 				error = ENOTCONN;
320 				break;
321 			}
322 		}
323 
324 		if (so->so_state & SS_CANTSENDMORE) {
325 			error = EPIPE;
326 			break;
327 		}
328 		if (unp->unp_conn == 0)
329 			panic("uipc_send connected but no connection?");
330 		so2 = unp->unp_conn->unp_socket;
331 		/*
332 		 * Send to paired receive port, and then reduce
333 		 * send buffer hiwater marks to maintain backpressure.
334 		 * Wake up readers.
335 		 */
336 		if (control) {
337 			if (sbappendcontrol(&so2->so_rcv, m, control))
338 				control = 0;
339 		} else
340 			sbappend(&so2->so_rcv, m);
341 		so->so_snd.sb_mbmax -=
342 			so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
343 		unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
344 		so->so_snd.sb_hiwat -=
345 		    so2->so_rcv.sb_cc - unp->unp_conn->unp_cc;
346 		(void)chgsbsize(so->so_cred->cr_uid,
347 		    (rlim_t)unp->unp_conn->unp_cc - so2->so_rcv.sb_cc);
348 		unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
349 		sorwakeup(so2);
350 		m = 0;
351 		break;
352 
353 	default:
354 		panic("uipc_send unknown socktype");
355 	}
356 
357 	/*
358 	 * SEND_EOF is equivalent to a SEND followed by
359 	 * a SHUTDOWN.
360 	 */
361 	if (flags & PRUS_EOF) {
362 		socantsendmore(so);
363 		unp_shutdown(unp);
364 	}
365 
366 	if (control && error != 0)
367 		unp_dispose(control);
368 
369 release:
370 	if (control)
371 		m_freem(control);
372 	if (m)
373 		m_freem(m);
374 	return error;
375 }
376 
377 static int
378 uipc_sense(struct socket *so, struct stat *sb)
379 {
380 	struct unpcb *unp = sotounpcb(so);
381 	struct socket *so2;
382 
383 	if (unp == 0)
384 		return EINVAL;
385 	sb->st_blksize = so->so_snd.sb_hiwat;
386 	if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
387 		so2 = unp->unp_conn->unp_socket;
388 		sb->st_blksize += so2->so_rcv.sb_cc;
389 	}
390 	sb->st_dev = NOUDEV;
391 	if (unp->unp_ino == 0)
392 		unp->unp_ino = unp_ino++;
393 	sb->st_ino = unp->unp_ino;
394 	return (0);
395 }
396 
397 static int
398 uipc_shutdown(struct socket *so)
399 {
400 	struct unpcb *unp = sotounpcb(so);
401 
402 	if (unp == 0)
403 		return EINVAL;
404 	socantsendmore(so);
405 	unp_shutdown(unp);
406 	return 0;
407 }
408 
409 static int
410 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
411 {
412 	struct unpcb *unp = sotounpcb(so);
413 
414 	if (unp == 0)
415 		return EINVAL;
416 	if (unp->unp_addr)
417 		*nam = dup_sockaddr((struct sockaddr *)unp->unp_addr, 1);
418 	return 0;
419 }
420 
421 struct pr_usrreqs uipc_usrreqs = {
422 	uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
423 	uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
424 	uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
425 	uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
426 	sosend, soreceive, sopoll
427 };
428 
429 /*
430  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
431  * for stream sockets, although the total for sender and receiver is
432  * actually only PIPSIZ.
433  * Datagram sockets really use the sendspace as the maximum datagram size,
434  * and don't really want to reserve the sendspace.  Their recvspace should
435  * be large enough for at least one max-size datagram plus address.
436  */
437 #ifndef PIPSIZ
438 #define	PIPSIZ	8192
439 #endif
440 static u_long	unpst_sendspace = PIPSIZ;
441 static u_long	unpst_recvspace = PIPSIZ;
442 static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
443 static u_long	unpdg_recvspace = 4*1024;
444 
445 static int	unp_rights;			/* file descriptors in flight */
446 
447 SYSCTL_DECL(_net_local_stream);
448 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
449 	   &unpst_sendspace, 0, "");
450 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
451 	   &unpst_recvspace, 0, "");
452 SYSCTL_DECL(_net_local_dgram);
453 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
454 	   &unpdg_sendspace, 0, "");
455 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
456 	   &unpdg_recvspace, 0, "");
457 SYSCTL_DECL(_net_local);
458 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
459 
460 static int
461 unp_attach(so)
462 	struct socket *so;
463 {
464 	register struct unpcb *unp;
465 	int error;
466 
467 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
468 		switch (so->so_type) {
469 
470 		case SOCK_STREAM:
471 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
472 			break;
473 
474 		case SOCK_DGRAM:
475 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
476 			break;
477 
478 		default:
479 			panic("unp_attach");
480 		}
481 		if (error)
482 			return (error);
483 	}
484 	unp = zalloc(unp_zone);
485 	if (unp == NULL)
486 		return (ENOBUFS);
487 	bzero(unp, sizeof *unp);
488 	unp->unp_gencnt = ++unp_gencnt;
489 	unp_count++;
490 	LIST_INIT(&unp->unp_refs);
491 	unp->unp_socket = so;
492 	unp->unp_rvnode = curproc->p_fd->fd_rdir;
493 	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
494 			 : &unp_shead, unp, unp_link);
495 	so->so_pcb = (caddr_t)unp;
496 	return (0);
497 }
498 
499 static void
500 unp_detach(unp)
501 	register struct unpcb *unp;
502 {
503 	LIST_REMOVE(unp, unp_link);
504 	unp->unp_gencnt = ++unp_gencnt;
505 	--unp_count;
506 	if (unp->unp_vnode) {
507 		unp->unp_vnode->v_socket = 0;
508 		vrele(unp->unp_vnode);
509 		unp->unp_vnode = 0;
510 	}
511 	if (unp->unp_conn)
512 		unp_disconnect(unp);
513 	while (!LIST_EMPTY(&unp->unp_refs))
514 		unp_drop(LIST_FIRST(&unp->unp_refs), ECONNRESET);
515 	soisdisconnected(unp->unp_socket);
516 	unp->unp_socket->so_pcb = 0;
517 	if (unp_rights) {
518 		/*
519 		 * Normally the receive buffer is flushed later,
520 		 * in sofree, but if our receive buffer holds references
521 		 * to descriptors that are now garbage, we will dispose
522 		 * of those descriptor references after the garbage collector
523 		 * gets them (resulting in a "panic: closef: count < 0").
524 		 */
525 		sorflush(unp->unp_socket);
526 		unp_gc();
527 	}
528 	if (unp->unp_addr)
529 		FREE(unp->unp_addr, M_SONAME);
530 	zfree(unp_zone, unp);
531 }
532 
533 static int
534 unp_bind(unp, nam, p)
535 	struct unpcb *unp;
536 	struct sockaddr *nam;
537 	struct proc *p;
538 {
539 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
540 	register struct vnode *vp;
541 	struct vattr vattr;
542 	int error, namelen;
543 	struct nameidata nd;
544 	char buf[SOCK_MAXADDRLEN];
545 
546 	if (unp->unp_vnode != NULL)
547 		return (EINVAL);
548 #define offsetof(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
549 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
550 	if (namelen <= 0)
551 		return EINVAL;
552 	strncpy(buf, soun->sun_path, namelen);
553 	buf[namelen] = 0;	/* null-terminate the string */
554 	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT, UIO_SYSSPACE,
555 	    buf, p);
556 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
557 	error = namei(&nd);
558 	if (error)
559 		return (error);
560 	vp = nd.ni_vp;
561 	if (vp != NULL) {
562 		NDFREE(&nd, NDF_ONLY_PNBUF);
563 		if (nd.ni_dvp == vp)
564 			vrele(nd.ni_dvp);
565 		else
566 			vput(nd.ni_dvp);
567 		vrele(vp);
568 		return (EADDRINUSE);
569 	}
570 	VATTR_NULL(&vattr);
571 	vattr.va_type = VSOCK;
572 	vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
573 	VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
574 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
575 	NDFREE(&nd, NDF_ONLY_PNBUF);
576 	vput(nd.ni_dvp);
577 	if (error)
578 		return (error);
579 	vp = nd.ni_vp;
580 	vp->v_socket = unp->unp_socket;
581 	unp->unp_vnode = vp;
582 	unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam, 1);
583 	VOP_UNLOCK(vp, 0, p);
584 	return (0);
585 }
586 
587 static int
588 unp_connect(so, nam, p)
589 	struct socket *so;
590 	struct sockaddr *nam;
591 	struct proc *p;
592 {
593 	register struct sockaddr_un *soun = (struct sockaddr_un *)nam;
594 	register struct vnode *vp;
595 	register struct socket *so2, *so3;
596 	struct unpcb *unp2, *unp3;
597 	int error, len;
598 	struct nameidata nd;
599 	char buf[SOCK_MAXADDRLEN];
600 
601 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
602 	if (len <= 0)
603 		return EINVAL;
604 	strncpy(buf, soun->sun_path, len);
605 	buf[len] = 0;
606 
607 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, p);
608 	error = namei(&nd);
609 	if (error)
610 		return (error);
611 	vp = nd.ni_vp;
612 	NDFREE(&nd, NDF_ONLY_PNBUF);
613 	if (vp->v_type != VSOCK) {
614 		error = ENOTSOCK;
615 		goto bad;
616 	}
617 	error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p);
618 	if (error)
619 		goto bad;
620 	so2 = vp->v_socket;
621 	if (so2 == 0) {
622 		error = ECONNREFUSED;
623 		goto bad;
624 	}
625 	if (so->so_type != so2->so_type) {
626 		error = EPROTOTYPE;
627 		goto bad;
628 	}
629 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
630 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
631 		    (so3 = sonewconn3(so2, 0, p)) == 0) {
632 			error = ECONNREFUSED;
633 			goto bad;
634 		}
635 		unp2 = sotounpcb(so2);
636 		unp3 = sotounpcb(so3);
637 		if (unp2->unp_addr)
638 			unp3->unp_addr = (struct sockaddr_un *)
639 				dup_sockaddr((struct sockaddr *)
640 					     unp2->unp_addr, 1);
641 		so2 = so3;
642 	}
643 	error = unp_connect2(so, so2);
644 bad:
645 	vput(vp);
646 	return (error);
647 }
648 
649 int
650 unp_connect2(so, so2)
651 	register struct socket *so;
652 	register struct socket *so2;
653 {
654 	register struct unpcb *unp = sotounpcb(so);
655 	register struct unpcb *unp2;
656 
657 	if (so2->so_type != so->so_type)
658 		return (EPROTOTYPE);
659 	unp2 = sotounpcb(so2);
660 	unp->unp_conn = unp2;
661 	switch (so->so_type) {
662 
663 	case SOCK_DGRAM:
664 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
665 		soisconnected(so);
666 		break;
667 
668 	case SOCK_STREAM:
669 		unp2->unp_conn = unp;
670 		soisconnected(so);
671 		soisconnected(so2);
672 		break;
673 
674 	default:
675 		panic("unp_connect2");
676 	}
677 	return (0);
678 }
679 
680 static void
681 unp_disconnect(unp)
682 	struct unpcb *unp;
683 {
684 	register struct unpcb *unp2 = unp->unp_conn;
685 
686 	if (unp2 == 0)
687 		return;
688 	unp->unp_conn = 0;
689 	switch (unp->unp_socket->so_type) {
690 
691 	case SOCK_DGRAM:
692 		LIST_REMOVE(unp, unp_reflink);
693 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
694 		break;
695 
696 	case SOCK_STREAM:
697 		soisdisconnected(unp->unp_socket);
698 		unp2->unp_conn = 0;
699 		soisdisconnected(unp2->unp_socket);
700 		break;
701 	}
702 }
703 
704 #ifdef notdef
705 void
706 unp_abort(unp)
707 	struct unpcb *unp;
708 {
709 
710 	unp_detach(unp);
711 }
712 #endif
713 
714 static int
715 prison_unpcb(struct proc *p, struct unpcb *unp)
716 {
717 	if (!p->p_prison)
718 		return (0);
719 	if (p->p_fd->fd_rdir == unp->unp_rvnode)
720 		return (0);
721 	return (1);
722 }
723 
724 static int
725 unp_pcblist SYSCTL_HANDLER_ARGS
726 {
727 	int error, i, n;
728 	struct unpcb *unp, **unp_list;
729 	unp_gen_t gencnt;
730 	struct xunpgen xug;
731 	struct unp_head *head;
732 
733 	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
734 
735 	/*
736 	 * The process of preparing the PCB list is too time-consuming and
737 	 * resource-intensive to repeat twice on every request.
738 	 */
739 	if (req->oldptr == 0) {
740 		n = unp_count;
741 		req->oldidx = 2 * (sizeof xug)
742 			+ (n + n/8) * sizeof(struct xunpcb);
743 		return 0;
744 	}
745 
746 	if (req->newptr != 0)
747 		return EPERM;
748 
749 	/*
750 	 * OK, now we're committed to doing something.
751 	 */
752 	gencnt = unp_gencnt;
753 	n = unp_count;
754 
755 	xug.xug_len = sizeof xug;
756 	xug.xug_count = n;
757 	xug.xug_gen = gencnt;
758 	xug.xug_sogen = so_gencnt;
759 	error = SYSCTL_OUT(req, &xug, sizeof xug);
760 	if (error)
761 		return error;
762 
763 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
764 	if (unp_list == 0)
765 		return ENOMEM;
766 
767 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
768 	     unp = LIST_NEXT(unp, unp_link)) {
769 		if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->p, unp))
770 			unp_list[i++] = unp;
771 	}
772 	n = i;			/* in case we lost some during malloc */
773 
774 	error = 0;
775 	for (i = 0; i < n; i++) {
776 		unp = unp_list[i];
777 		if (unp->unp_gencnt <= gencnt) {
778 			struct xunpcb xu;
779 			xu.xu_len = sizeof xu;
780 			xu.xu_unpp = unp;
781 			/*
782 			 * XXX - need more locking here to protect against
783 			 * connect/disconnect races for SMP.
784 			 */
785 			if (unp->unp_addr)
786 				bcopy(unp->unp_addr, &xu.xu_addr,
787 				      unp->unp_addr->sun_len);
788 			if (unp->unp_conn && unp->unp_conn->unp_addr)
789 				bcopy(unp->unp_conn->unp_addr,
790 				      &xu.xu_caddr,
791 				      unp->unp_conn->unp_addr->sun_len);
792 			bcopy(unp, &xu.xu_unp, sizeof *unp);
793 			sotoxsocket(unp->unp_socket, &xu.xu_socket);
794 			error = SYSCTL_OUT(req, &xu, sizeof xu);
795 		}
796 	}
797 	if (!error) {
798 		/*
799 		 * Give the user an updated idea of our state.
800 		 * If the generation differs from what we told
801 		 * her before, she knows that something happened
802 		 * while we were processing this request, and it
803 		 * might be necessary to retry.
804 		 */
805 		xug.xug_gen = unp_gencnt;
806 		xug.xug_sogen = so_gencnt;
807 		xug.xug_count = unp_count;
808 		error = SYSCTL_OUT(req, &xug, sizeof xug);
809 	}
810 	free(unp_list, M_TEMP);
811 	return error;
812 }
813 
814 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
815 	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
816 	    "List of active local datagram sockets");
817 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
818 	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
819 	    "List of active local stream sockets");
820 
821 static void
822 unp_shutdown(unp)
823 	struct unpcb *unp;
824 {
825 	struct socket *so;
826 
827 	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
828 	    (so = unp->unp_conn->unp_socket))
829 		socantrcvmore(so);
830 }
831 
832 static void
833 unp_drop(unp, errno)
834 	struct unpcb *unp;
835 	int errno;
836 {
837 	struct socket *so = unp->unp_socket;
838 
839 	so->so_error = errno;
840 	unp_disconnect(unp);
841 	if (so->so_head) {
842 		LIST_REMOVE(unp, unp_link);
843 		unp->unp_gencnt = ++unp_gencnt;
844 		unp_count--;
845 		so->so_pcb = (caddr_t) 0;
846 		if (unp->unp_addr)
847 			FREE(unp->unp_addr, M_SONAME);
848 		zfree(unp_zone, unp);
849 		sofree(so);
850 	}
851 }
852 
853 #ifdef notdef
854 void
855 unp_drain()
856 {
857 
858 }
859 #endif
860 
861 int
862 unp_externalize(rights)
863 	struct mbuf *rights;
864 {
865 	struct proc *p = curproc;		/* XXX */
866 	register int i;
867 	register struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
868 	register int *fdp;
869 	register struct file **rp;
870 	register struct file *fp;
871 	int newfds = (cm->cmsg_len - (CMSG_DATA(cm) - (u_char *)cm))
872 		/ sizeof (struct file *);
873 	int f;
874 
875 	/*
876 	 * if the new FD's will not fit, then we free them all
877 	 */
878 	if (!fdavail(p, newfds)) {
879 		rp = (struct file **)CMSG_DATA(cm);
880 		for (i = 0; i < newfds; i++) {
881 			fp = *rp;
882 			/*
883 			 * zero the pointer before calling unp_discard,
884 			 * since it may end up in unp_gc()..
885 			 */
886 			*rp++ = 0;
887 			unp_discard(fp);
888 		}
889 		return (EMSGSIZE);
890 	}
891 	/*
892 	 * now change each pointer to an fd in the global table to
893 	 * an integer that is the index to the local fd table entry
894 	 * that we set up to point to the global one we are transferring.
895 	 * If sizeof (struct file *) is bigger than or equal to sizeof int,
896 	 * then do it in forward order. In that case, an integer will
897 	 * always come in the same place or before its corresponding
898 	 * struct file pointer.
899 	 * If sizeof (struct file *) is smaller than sizeof int, then
900 	 * do it in reverse order.
901 	 */
902 	if (sizeof (struct file *) >= sizeof (int)) {
903 		fdp = (int *)(cm + 1);
904 		rp = (struct file **)CMSG_DATA(cm);
905 		for (i = 0; i < newfds; i++) {
906 			if (fdalloc(p, 0, &f))
907 				panic("unp_externalize");
908 			fp = *rp++;
909 			p->p_fd->fd_ofiles[f] = fp;
910 			fp->f_msgcount--;
911 			unp_rights--;
912 			*fdp++ = f;
913 		}
914 	} else {
915 		fdp = (int *)(cm + 1) + newfds - 1;
916 		rp = (struct file **)CMSG_DATA(cm) + newfds - 1;
917 		for (i = 0; i < newfds; i++) {
918 			if (fdalloc(p, 0, &f))
919 				panic("unp_externalize");
920 			fp = *rp--;
921 			p->p_fd->fd_ofiles[f] = fp;
922 			fp->f_msgcount--;
923 			unp_rights--;
924 			*fdp-- = f;
925 		}
926 	}
927 
928 	/*
929 	 * Adjust length, in case sizeof(struct file *) and sizeof(int)
930 	 * differs.
931 	 */
932 	cm->cmsg_len = CMSG_LEN(newfds * sizeof(int));
933 	rights->m_len = cm->cmsg_len;
934 	return (0);
935 }
936 
937 void
938 unp_init(void)
939 {
940 	unp_zone = zinit("unpcb", sizeof(struct unpcb), nmbclusters, 0, 0);
941 	if (unp_zone == 0)
942 		panic("unp_init");
943 	LIST_INIT(&unp_dhead);
944 	LIST_INIT(&unp_shead);
945 }
946 
947 #ifndef MIN
948 #define	MIN(a,b) (((a)<(b))?(a):(b))
949 #endif
950 
951 static int
952 unp_internalize(control, p)
953 	struct mbuf *control;
954 	struct proc *p;
955 {
956 	struct filedesc *fdescp = p->p_fd;
957 	register struct cmsghdr *cm = mtod(control, struct cmsghdr *);
958 	register struct file **rp;
959 	register struct file *fp;
960 	register int i, fd, *fdp;
961 	register struct cmsgcred *cmcred;
962 	int oldfds;
963 	u_int newlen;
964 
965 	if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
966 	    cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
967 		return (EINVAL);
968 
969 	/*
970 	 * Fill in credential information.
971 	 */
972 	if (cm->cmsg_type == SCM_CREDS) {
973 		cmcred = (struct cmsgcred *)(cm + 1);
974 		cmcred->cmcred_pid = p->p_pid;
975 		cmcred->cmcred_uid = p->p_cred->p_ruid;
976 		cmcred->cmcred_gid = p->p_cred->p_rgid;
977 		cmcred->cmcred_euid = p->p_ucred->cr_uid;
978 		cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
979 							CMGROUP_MAX);
980 		for (i = 0; i < cmcred->cmcred_ngroups; i++)
981 			cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
982 		return(0);
983 	}
984 
985 	oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
986 	/*
987 	 * check that all the FDs passed in refer to legal OPEN files
988 	 * If not, reject the entire operation.
989 	 */
990 	fdp = (int *)(cm + 1);
991 	for (i = 0; i < oldfds; i++) {
992 		fd = *fdp++;
993 		if ((unsigned)fd >= fdescp->fd_nfiles ||
994 		    fdescp->fd_ofiles[fd] == NULL)
995 			return (EBADF);
996 	}
997 	/*
998 	 * Now replace the integer FDs with pointers to
999 	 * the associated global file table entry..
1000 	 * Allocate a bigger buffer as necessary. But if an cluster is not
1001 	 * enough, return E2BIG.
1002 	 */
1003 	newlen = CMSG_LEN(oldfds * sizeof(struct file *));
1004 	if (newlen > MCLBYTES)
1005 		return (E2BIG);
1006 	if (newlen - control->m_len > M_TRAILINGSPACE(control)) {
1007 		if (control->m_flags & M_EXT)
1008 			return (E2BIG);
1009 		MCLGET(control, M_WAIT);
1010 		if ((control->m_flags & M_EXT) == 0)
1011 			return (ENOBUFS);
1012 
1013 		/* copy the data to the cluster */
1014 		memcpy(mtod(control, char *), cm, cm->cmsg_len);
1015 		cm = mtod(control, struct cmsghdr *);
1016 	}
1017 
1018 	/*
1019 	 * Adjust length, in case sizeof(struct file *) and sizeof(int)
1020 	 * differs.
1021 	 */
1022 	control->m_len = cm->cmsg_len = newlen;
1023 
1024 	/*
1025 	 * Transform the file descriptors into struct file pointers.
1026 	 * If sizeof (struct file *) is bigger than or equal to sizeof int,
1027 	 * then do it in reverse order so that the int won't get until
1028 	 * we're done.
1029 	 * If sizeof (struct file *) is smaller than sizeof int, then
1030 	 * do it in forward order.
1031 	 */
1032 	if (sizeof (struct file *) >= sizeof (int)) {
1033 		fdp = (int *)(cm + 1) + oldfds - 1;
1034 		rp = (struct file **)CMSG_DATA(cm) + oldfds - 1;
1035 		for (i = 0; i < oldfds; i++) {
1036 			fp = fdescp->fd_ofiles[*fdp--];
1037 			*rp-- = fp;
1038 			fp->f_count++;
1039 			fp->f_msgcount++;
1040 			unp_rights++;
1041 		}
1042 	} else {
1043 		fdp = (int *)(cm + 1);
1044 		rp = (struct file **)CMSG_DATA(cm);
1045 		for (i = 0; i < oldfds; i++) {
1046 			fp = fdescp->fd_ofiles[*fdp++];
1047 			*rp++ = fp;
1048 			fp->f_count++;
1049 			fp->f_msgcount++;
1050 			unp_rights++;
1051 		}
1052 	}
1053 	return (0);
1054 }
1055 
1056 static int	unp_defer, unp_gcing;
1057 
1058 static void
1059 unp_gc()
1060 {
1061 	register struct file *fp, *nextfp;
1062 	register struct socket *so;
1063 	struct file **extra_ref, **fpp;
1064 	int nunref, i;
1065 
1066 	if (unp_gcing)
1067 		return;
1068 	unp_gcing = 1;
1069 	unp_defer = 0;
1070 	/*
1071 	 * before going through all this, set all FDs to
1072 	 * be NOT defered and NOT externally accessible
1073 	 */
1074 	LIST_FOREACH(fp, &filehead, f_list)
1075 		fp->f_flag &= ~(FMARK|FDEFER);
1076 	do {
1077 		LIST_FOREACH(fp, &filehead, f_list) {
1078 			/*
1079 			 * If the file is not open, skip it
1080 			 */
1081 			if (fp->f_count == 0)
1082 				continue;
1083 			/*
1084 			 * If we already marked it as 'defer'  in a
1085 			 * previous pass, then try process it this time
1086 			 * and un-mark it
1087 			 */
1088 			if (fp->f_flag & FDEFER) {
1089 				fp->f_flag &= ~FDEFER;
1090 				unp_defer--;
1091 			} else {
1092 				/*
1093 				 * if it's not defered, then check if it's
1094 				 * already marked.. if so skip it
1095 				 */
1096 				if (fp->f_flag & FMARK)
1097 					continue;
1098 				/*
1099 				 * If all references are from messages
1100 				 * in transit, then skip it. it's not
1101 				 * externally accessible.
1102 				 */
1103 				if (fp->f_count == fp->f_msgcount)
1104 					continue;
1105 				/*
1106 				 * If it got this far then it must be
1107 				 * externally accessible.
1108 				 */
1109 				fp->f_flag |= FMARK;
1110 			}
1111 			/*
1112 			 * either it was defered, or it is externally
1113 			 * accessible and not already marked so.
1114 			 * Now check if it is possibly one of OUR sockets.
1115 			 */
1116 			if (fp->f_type != DTYPE_SOCKET ||
1117 			    (so = (struct socket *)fp->f_data) == 0)
1118 				continue;
1119 			if (so->so_proto->pr_domain != &localdomain ||
1120 			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1121 				continue;
1122 #ifdef notdef
1123 			if (so->so_rcv.sb_flags & SB_LOCK) {
1124 				/*
1125 				 * This is problematical; it's not clear
1126 				 * we need to wait for the sockbuf to be
1127 				 * unlocked (on a uniprocessor, at least),
1128 				 * and it's also not clear what to do
1129 				 * if sbwait returns an error due to receipt
1130 				 * of a signal.  If sbwait does return
1131 				 * an error, we'll go into an infinite
1132 				 * loop.  Delete all of this for now.
1133 				 */
1134 				(void) sbwait(&so->so_rcv);
1135 				goto restart;
1136 			}
1137 #endif
1138 			/*
1139 			 * So, Ok, it's one of our sockets and it IS externally
1140 			 * accessible (or was defered). Now we look
1141 			 * to see if we hold any file descriptors in its
1142 			 * message buffers. Follow those links and mark them
1143 			 * as accessible too.
1144 			 */
1145 			unp_scan(so->so_rcv.sb_mb, unp_mark);
1146 		}
1147 	} while (unp_defer);
1148 	/*
1149 	 * We grab an extra reference to each of the file table entries
1150 	 * that are not otherwise accessible and then free the rights
1151 	 * that are stored in messages on them.
1152 	 *
1153 	 * The bug in the orginal code is a little tricky, so I'll describe
1154 	 * what's wrong with it here.
1155 	 *
1156 	 * It is incorrect to simply unp_discard each entry for f_msgcount
1157 	 * times -- consider the case of sockets A and B that contain
1158 	 * references to each other.  On a last close of some other socket,
1159 	 * we trigger a gc since the number of outstanding rights (unp_rights)
1160 	 * is non-zero.  If during the sweep phase the gc code un_discards,
1161 	 * we end up doing a (full) closef on the descriptor.  A closef on A
1162 	 * results in the following chain.  Closef calls soo_close, which
1163 	 * calls soclose.   Soclose calls first (through the switch
1164 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1165 	 * returns because the previous instance had set unp_gcing, and
1166 	 * we return all the way back to soclose, which marks the socket
1167 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1168 	 * to free up the rights that are queued in messages on the socket A,
1169 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1170 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1171 	 * instance of unp_discard just calls closef on B.
1172 	 *
1173 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1174 	 * which results in another closef on A.  Unfortunately, A is already
1175 	 * being closed, and the descriptor has already been marked with
1176 	 * SS_NOFDREF, and soclose panics at this point.
1177 	 *
1178 	 * Here, we first take an extra reference to each inaccessible
1179 	 * descriptor.  Then, we call sorflush ourself, since we know
1180 	 * it is a Unix domain socket anyhow.  After we destroy all the
1181 	 * rights carried in messages, we do a last closef to get rid
1182 	 * of our extra reference.  This is the last close, and the
1183 	 * unp_detach etc will shut down the socket.
1184 	 *
1185 	 * 91/09/19, bsy@cs.cmu.edu
1186 	 */
1187 	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1188 	for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
1189 	    fp = nextfp) {
1190 		nextfp = LIST_NEXT(fp, f_list);
1191 		/*
1192 		 * If it's not open, skip it
1193 		 */
1194 		if (fp->f_count == 0)
1195 			continue;
1196 		/*
1197 		 * If all refs are from msgs, and it's not marked accessible
1198 		 * then it must be referenced from some unreachable cycle
1199 		 * of (shut-down) FDs, so include it in our
1200 		 * list of FDs to remove
1201 		 */
1202 		if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1203 			*fpp++ = fp;
1204 			nunref++;
1205 			fp->f_count++;
1206 		}
1207 	}
1208 	/*
1209 	 * for each FD on our hit list, do the following two things
1210 	 */
1211 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1212 		struct file *tfp = *fpp;
1213 		if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1214 			sorflush((struct socket *)(tfp->f_data));
1215 	}
1216 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1217 		closef(*fpp, (struct proc *) NULL);
1218 	free((caddr_t)extra_ref, M_FILE);
1219 	unp_gcing = 0;
1220 }
1221 
1222 void
1223 unp_dispose(m)
1224 	struct mbuf *m;
1225 {
1226 
1227 	if (m)
1228 		unp_scan(m, unp_discard);
1229 }
1230 
1231 static void
1232 unp_scan(m0, op)
1233 	register struct mbuf *m0;
1234 	void (*op) __P((struct file *));
1235 {
1236 	register struct mbuf *m;
1237 	register struct file **rp;
1238 	register struct cmsghdr *cm;
1239 	register int i;
1240 	int qfds;
1241 
1242 	while (m0) {
1243 		for (m = m0; m; m = m->m_next)
1244 			if (m->m_type == MT_CONTROL &&
1245 			    m->m_len >= sizeof(*cm)) {
1246 				cm = mtod(m, struct cmsghdr *);
1247 				if (cm->cmsg_level != SOL_SOCKET ||
1248 				    cm->cmsg_type != SCM_RIGHTS)
1249 					continue;
1250 				qfds = (cm->cmsg_len -
1251 					(CMSG_DATA(cm) - (u_char *)cm))
1252 						/ sizeof (struct file *);
1253 				rp = (struct file **)CMSG_DATA(cm);
1254 				for (i = 0; i < qfds; i++)
1255 					(*op)(*rp++);
1256 				break;		/* XXX, but saves time */
1257 			}
1258 		m0 = m0->m_act;
1259 	}
1260 }
1261 
1262 static void
1263 unp_mark(fp)
1264 	struct file *fp;
1265 {
1266 
1267 	if (fp->f_flag & FMARK)
1268 		return;
1269 	unp_defer++;
1270 	fp->f_flag |= (FMARK|FDEFER);
1271 }
1272 
1273 static void
1274 unp_discard(fp)
1275 	struct file *fp;
1276 {
1277 
1278 	fp->f_msgcount--;
1279 	unp_rights--;
1280 	(void) closef(fp, (struct proc *)NULL);
1281 }
1282