xref: /freebsd/sys/kern/uipc_usrreq.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
1 /*-
2  * Copyright 2004 Robert N. M. Watson
3  * Copyright (c) 1982, 1986, 1989, 1991, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_mac.h"
37 
38 #include <sys/param.h>
39 #include <sys/domain.h>
40 #include <sys/fcntl.h>
41 #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
42 #include <sys/file.h>
43 #include <sys/filedesc.h>
44 #include <sys/jail.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/mac.h>
48 #include <sys/mbuf.h>
49 #include <sys/mutex.h>
50 #include <sys/namei.h>
51 #include <sys/proc.h>
52 #include <sys/protosw.h>
53 #include <sys/resourcevar.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #include <sys/signalvar.h>
57 #include <sys/stat.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/systm.h>
61 #include <sys/un.h>
62 #include <sys/unpcb.h>
63 #include <sys/vnode.h>
64 
65 #include <vm/uma.h>
66 
67 static uma_zone_t unp_zone;
68 static	unp_gen_t unp_gencnt;
69 static	u_int unp_count;
70 
71 static	struct unp_head unp_shead, unp_dhead;
72 
73 /*
74  * Unix communications domain.
75  *
76  * TODO:
77  *	SEQPACKET, RDM
78  *	rethink name space problems
79  *	need a proper out-of-band
80  *	lock pushdown
81  */
82 static const struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
83 static ino_t	unp_ino;		/* prototype for fake inode numbers */
84 
85 /*
86  * Currently, UNIX domain sockets are protected by a single subsystem lock,
87  * which covers global data structures and variables, the contents of each
88  * per-socket unpcb structure, and the so_pcb field in sockets attached to
89  * the UNIX domain.  This provides for a moderate degree of paralellism, as
90  * receive operations on UNIX domain sockets do not need to acquire the
91  * subsystem lock.  Finer grained locking to permit send() without acquiring
92  * a global lock would be a logical next step.
93  *
94  * The UNIX domain socket lock preceds all socket layer locks, including the
95  * socket lock and socket buffer lock, permitting UNIX domain socket code to
96  * call into socket support routines without releasing its locks.
97  *
98  * Some caution is required in areas where the UNIX domain socket code enters
99  * VFS in order to create or find rendezvous points.  This results in
100  * dropping of the UNIX domain socket subsystem lock, acquisition of the
101  * Giant lock, and potential sleeping.  This increases the chances of races,
102  * and exposes weaknesses in the socket->protocol API by offering poor
103  * failure modes.
104  */
105 static struct mtx unp_mtx;
106 #define	UNP_LOCK_INIT() \
107 	mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
108 #define	UNP_LOCK()		mtx_lock(&unp_mtx)
109 #define	UNP_UNLOCK()		mtx_unlock(&unp_mtx)
110 #define	UNP_LOCK_ASSERT()	mtx_assert(&unp_mtx, MA_OWNED)
111 #define	UNP_UNLOCK_ASSERT()	mtx_assert(&unp_mtx, MA_NOTOWNED)
112 
113 static int     unp_attach(struct socket *);
114 static void    unp_detach(struct unpcb *);
115 static int     unp_bind(struct unpcb *,struct sockaddr *, struct thread *);
116 static int     unp_connect(struct socket *,struct sockaddr *, struct thread *);
117 static int     unp_connect2(struct socket *so, struct socket *so2);
118 static void    unp_disconnect(struct unpcb *);
119 static void    unp_shutdown(struct unpcb *);
120 static void    unp_drop(struct unpcb *, int);
121 static void    unp_gc(void);
122 static void    unp_scan(struct mbuf *, void (*)(struct file *));
123 static void    unp_mark(struct file *);
124 static void    unp_discard(struct file *);
125 static void    unp_freerights(struct file **, int);
126 static int     unp_internalize(struct mbuf **, struct thread *);
127 static int     unp_listen(struct unpcb *, struct thread *);
128 
129 static int
130 uipc_abort(struct socket *so)
131 {
132 	struct unpcb *unp;
133 
134 	UNP_LOCK();
135 	unp = sotounpcb(so);
136 	if (unp == NULL) {
137 		UNP_UNLOCK();
138 		return (EINVAL);
139 	}
140 	unp_drop(unp, ECONNABORTED);
141 	unp_detach(unp);
142 	UNP_UNLOCK_ASSERT();
143 	ACCEPT_LOCK();
144 	SOCK_LOCK(so);
145 	sotryfree(so);
146 	return (0);
147 }
148 
149 static int
150 uipc_accept(struct socket *so, struct sockaddr **nam)
151 {
152 	struct unpcb *unp;
153 	const struct sockaddr *sa;
154 
155 	/*
156 	 * Pass back name of connected socket,
157 	 * if it was bound and we are still connected
158 	 * (our peer may have closed already!).
159 	 */
160 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
161 	UNP_LOCK();
162 	unp = sotounpcb(so);
163 	if (unp == NULL) {
164 		UNP_UNLOCK();
165 		free(*nam, M_SONAME);
166 		*nam = NULL;
167 		return (EINVAL);
168 	}
169 	if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
170 		sa = (struct sockaddr *) unp->unp_conn->unp_addr;
171 	else
172 		sa = &sun_noname;
173 	bcopy(sa, *nam, sa->sa_len);
174 	UNP_UNLOCK();
175 	return (0);
176 }
177 
178 static int
179 uipc_attach(struct socket *so, int proto, struct thread *td)
180 {
181 	struct unpcb *unp = sotounpcb(so);
182 
183 	if (unp != NULL)
184 		return (EISCONN);
185 	return (unp_attach(so));
186 }
187 
188 static int
189 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
190 {
191 	struct unpcb *unp;
192 	int error;
193 
194 	UNP_LOCK();
195 	unp = sotounpcb(so);
196 	if (unp == NULL) {
197 		UNP_UNLOCK();
198 		return (EINVAL);
199 	}
200 	error = unp_bind(unp, nam, td);
201 	UNP_UNLOCK();
202 	return (error);
203 }
204 
205 static int
206 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
207 {
208 	struct unpcb *unp;
209 	int error;
210 
211 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
212 
213 	UNP_LOCK();
214 	unp = sotounpcb(so);
215 	if (unp == NULL) {
216 		UNP_UNLOCK();
217 		return (EINVAL);
218 	}
219 	error = unp_connect(so, nam, td);
220 	UNP_UNLOCK();
221 	return (error);
222 }
223 
224 int
225 uipc_connect2(struct socket *so1, struct socket *so2)
226 {
227 	struct unpcb *unp;
228 	int error;
229 
230 	UNP_LOCK();
231 	unp = sotounpcb(so1);
232 	if (unp == NULL) {
233 		UNP_UNLOCK();
234 		return (EINVAL);
235 	}
236 	error = unp_connect2(so1, so2);
237 	UNP_UNLOCK();
238 	return (error);
239 }
240 
241 /* control is EOPNOTSUPP */
242 
243 static int
244 uipc_detach(struct socket *so)
245 {
246 	struct unpcb *unp;
247 
248 	UNP_LOCK();
249 	unp = sotounpcb(so);
250 	if (unp == NULL) {
251 		UNP_UNLOCK();
252 		return (EINVAL);
253 	}
254 	unp_detach(unp);
255 	UNP_UNLOCK_ASSERT();
256 	return (0);
257 }
258 
259 static int
260 uipc_disconnect(struct socket *so)
261 {
262 	struct unpcb *unp;
263 
264 	UNP_LOCK();
265 	unp = sotounpcb(so);
266 	if (unp == NULL) {
267 		UNP_UNLOCK();
268 		return (EINVAL);
269 	}
270 	unp_disconnect(unp);
271 	UNP_UNLOCK();
272 	return (0);
273 }
274 
275 static int
276 uipc_listen(struct socket *so, struct thread *td)
277 {
278 	struct unpcb *unp;
279 	int error;
280 
281 	UNP_LOCK();
282 	unp = sotounpcb(so);
283 	if (unp == NULL || unp->unp_vnode == NULL) {
284 		UNP_UNLOCK();
285 		return (EINVAL);
286 	}
287 	error = unp_listen(unp, td);
288 	UNP_UNLOCK();
289 	return (error);
290 }
291 
292 static int
293 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
294 {
295 	struct unpcb *unp;
296 	const struct sockaddr *sa;
297 
298 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
299 	UNP_LOCK();
300 	unp = sotounpcb(so);
301 	if (unp == NULL) {
302 		UNP_UNLOCK();
303 		free(*nam, M_SONAME);
304 		*nam = NULL;
305 		return (EINVAL);
306 	}
307 	if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
308 		sa = (struct sockaddr *) unp->unp_conn->unp_addr;
309 	else {
310 		/*
311 		 * XXX: It seems that this test always fails even when
312 		 * connection is established.  So, this else clause is
313 		 * added as workaround to return PF_LOCAL sockaddr.
314 		 */
315 		sa = &sun_noname;
316 	}
317 	bcopy(sa, *nam, sa->sa_len);
318 	UNP_UNLOCK();
319 	return (0);
320 }
321 
322 static int
323 uipc_rcvd(struct socket *so, int flags)
324 {
325 	struct unpcb *unp;
326 	struct socket *so2;
327 	u_long newhiwat;
328 
329 	UNP_LOCK();
330 	unp = sotounpcb(so);
331 	if (unp == NULL) {
332 		UNP_UNLOCK();
333 		return (EINVAL);
334 	}
335 	switch (so->so_type) {
336 	case SOCK_DGRAM:
337 		panic("uipc_rcvd DGRAM?");
338 		/*NOTREACHED*/
339 
340 	case SOCK_STREAM:
341 		if (unp->unp_conn == NULL)
342 			break;
343 		so2 = unp->unp_conn->unp_socket;
344 		SOCKBUF_LOCK(&so2->so_snd);
345 		SOCKBUF_LOCK(&so->so_rcv);
346 		/*
347 		 * Adjust backpressure on sender
348 		 * and wakeup any waiting to write.
349 		 */
350 		so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
351 		unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
352 		newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
353 		    so->so_rcv.sb_cc;
354 		(void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
355 		    newhiwat, RLIM_INFINITY);
356 		unp->unp_cc = so->so_rcv.sb_cc;
357 		SOCKBUF_UNLOCK(&so->so_rcv);
358 		sowwakeup_locked(so2);
359 		break;
360 
361 	default:
362 		panic("uipc_rcvd unknown socktype");
363 	}
364 	UNP_UNLOCK();
365 	return (0);
366 }
367 
368 /* pru_rcvoob is EOPNOTSUPP */
369 
370 static int
371 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
372 	  struct mbuf *control, struct thread *td)
373 {
374 	int error = 0;
375 	struct unpcb *unp;
376 	struct socket *so2;
377 	u_long newhiwat;
378 
379 	unp = sotounpcb(so);
380 	if (unp == NULL) {
381 		error = EINVAL;
382 		goto release;
383 	}
384 	if (flags & PRUS_OOB) {
385 		error = EOPNOTSUPP;
386 		goto release;
387 	}
388 
389 	if (control != NULL && (error = unp_internalize(&control, td)))
390 		goto release;
391 
392 	UNP_LOCK();
393 	unp = sotounpcb(so);
394 	if (unp == NULL) {
395 		UNP_UNLOCK();
396 		error = EINVAL;
397 		goto dispose_release;
398 	}
399 
400 	switch (so->so_type) {
401 	case SOCK_DGRAM:
402 	{
403 		const struct sockaddr *from;
404 
405 		if (nam != NULL) {
406 			if (unp->unp_conn != NULL) {
407 				error = EISCONN;
408 				break;
409 			}
410 			error = unp_connect(so, nam, td);
411 			if (error)
412 				break;
413 		} else {
414 			if (unp->unp_conn == NULL) {
415 				error = ENOTCONN;
416 				break;
417 			}
418 		}
419 		so2 = unp->unp_conn->unp_socket;
420 		if (unp->unp_addr != NULL)
421 			from = (struct sockaddr *)unp->unp_addr;
422 		else
423 			from = &sun_noname;
424 		SOCKBUF_LOCK(&so2->so_rcv);
425 		if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
426 			sorwakeup_locked(so2);
427 			m = NULL;
428 			control = NULL;
429 		} else {
430 			SOCKBUF_UNLOCK(&so2->so_rcv);
431 			error = ENOBUFS;
432 		}
433 		if (nam != NULL)
434 			unp_disconnect(unp);
435 		break;
436 	}
437 
438 	case SOCK_STREAM:
439 		/* Connect if not connected yet. */
440 		/*
441 		 * Note: A better implementation would complain
442 		 * if not equal to the peer's address.
443 		 */
444 		if ((so->so_state & SS_ISCONNECTED) == 0) {
445 			if (nam != NULL) {
446 				error = unp_connect(so, nam, td);
447 				if (error)
448 					break;	/* XXX */
449 			} else {
450 				error = ENOTCONN;
451 				break;
452 			}
453 		}
454 
455 		SOCKBUF_LOCK(&so->so_snd);
456 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
457 			SOCKBUF_UNLOCK(&so->so_snd);
458 			error = EPIPE;
459 			break;
460 		}
461 		if (unp->unp_conn == NULL)
462 			panic("uipc_send connected but no connection?");
463 		so2 = unp->unp_conn->unp_socket;
464 		SOCKBUF_LOCK(&so2->so_rcv);
465 		/*
466 		 * Send to paired receive port, and then reduce
467 		 * send buffer hiwater marks to maintain backpressure.
468 		 * Wake up readers.
469 		 */
470 		if (control != NULL) {
471 			if (sbappendcontrol_locked(&so2->so_rcv, m, control))
472 				control = NULL;
473 		} else {
474 			sbappend_locked(&so2->so_rcv, m);
475 		}
476 		so->so_snd.sb_mbmax -=
477 			so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
478 		unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
479 		newhiwat = so->so_snd.sb_hiwat -
480 		    (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
481 		(void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
482 		    newhiwat, RLIM_INFINITY);
483 		SOCKBUF_UNLOCK(&so->so_snd);
484 		unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
485 		sorwakeup_locked(so2);
486 		m = NULL;
487 		break;
488 
489 	default:
490 		panic("uipc_send unknown socktype");
491 	}
492 
493 	/*
494 	 * SEND_EOF is equivalent to a SEND followed by
495 	 * a SHUTDOWN.
496 	 */
497 	if (flags & PRUS_EOF) {
498 		socantsendmore(so);
499 		unp_shutdown(unp);
500 	}
501 	UNP_UNLOCK();
502 
503 dispose_release:
504 	if (control != NULL && error != 0)
505 		unp_dispose(control);
506 
507 release:
508 	if (control != NULL)
509 		m_freem(control);
510 	if (m != NULL)
511 		m_freem(m);
512 	return (error);
513 }
514 
515 static int
516 uipc_sense(struct socket *so, struct stat *sb)
517 {
518 	struct unpcb *unp;
519 	struct socket *so2;
520 
521 	UNP_LOCK();
522 	unp = sotounpcb(so);
523 	if (unp == NULL) {
524 		UNP_UNLOCK();
525 		return (EINVAL);
526 	}
527 	sb->st_blksize = so->so_snd.sb_hiwat;
528 	if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
529 		so2 = unp->unp_conn->unp_socket;
530 		sb->st_blksize += so2->so_rcv.sb_cc;
531 	}
532 	sb->st_dev = NODEV;
533 	if (unp->unp_ino == 0)
534 		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
535 	sb->st_ino = unp->unp_ino;
536 	UNP_UNLOCK();
537 	return (0);
538 }
539 
540 static int
541 uipc_shutdown(struct socket *so)
542 {
543 	struct unpcb *unp;
544 
545 	UNP_LOCK();
546 	unp = sotounpcb(so);
547 	if (unp == NULL) {
548 		UNP_UNLOCK();
549 		return (EINVAL);
550 	}
551 	socantsendmore(so);
552 	unp_shutdown(unp);
553 	UNP_UNLOCK();
554 	return (0);
555 }
556 
557 static int
558 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
559 {
560 	struct unpcb *unp;
561 	const struct sockaddr *sa;
562 
563 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
564 	UNP_LOCK();
565 	unp = sotounpcb(so);
566 	if (unp == NULL) {
567 		UNP_UNLOCK();
568 		free(*nam, M_SONAME);
569 		*nam = NULL;
570 		return (EINVAL);
571 	}
572 	if (unp->unp_addr != NULL)
573 		sa = (struct sockaddr *) unp->unp_addr;
574 	else
575 		sa = &sun_noname;
576 	bcopy(sa, *nam, sa->sa_len);
577 	UNP_UNLOCK();
578 	return (0);
579 }
580 
581 struct pr_usrreqs uipc_usrreqs = {
582 	.pru_abort = 		uipc_abort,
583 	.pru_accept =		uipc_accept,
584 	.pru_attach =		uipc_attach,
585 	.pru_bind =		uipc_bind,
586 	.pru_connect =		uipc_connect,
587 	.pru_connect2 =		uipc_connect2,
588 	.pru_detach =		uipc_detach,
589 	.pru_disconnect =	uipc_disconnect,
590 	.pru_listen =		uipc_listen,
591 	.pru_peeraddr =		uipc_peeraddr,
592 	.pru_rcvd =		uipc_rcvd,
593 	.pru_send =		uipc_send,
594 	.pru_sense =		uipc_sense,
595 	.pru_shutdown =		uipc_shutdown,
596 	.pru_sockaddr =		uipc_sockaddr,
597 	.pru_sosend =		sosend,
598 	.pru_soreceive =	soreceive,
599 	.pru_sopoll =		sopoll,
600 };
601 
602 int
603 uipc_ctloutput(so, sopt)
604 	struct socket *so;
605 	struct sockopt *sopt;
606 {
607 	struct unpcb *unp;
608 	struct xucred xu;
609 	int error;
610 
611 	switch (sopt->sopt_dir) {
612 	case SOPT_GET:
613 		switch (sopt->sopt_name) {
614 		case LOCAL_PEERCRED:
615 			error = 0;
616 			UNP_LOCK();
617 			unp = sotounpcb(so);
618 			if (unp == NULL) {
619 				UNP_UNLOCK();
620 				error = EINVAL;
621 				break;
622 			}
623 			if (unp->unp_flags & UNP_HAVEPC)
624 				xu = unp->unp_peercred;
625 			else {
626 				if (so->so_type == SOCK_STREAM)
627 					error = ENOTCONN;
628 				else
629 					error = EINVAL;
630 			}
631 			UNP_UNLOCK();
632 			if (error == 0)
633 				error = sooptcopyout(sopt, &xu, sizeof(xu));
634 			break;
635 		default:
636 			error = EOPNOTSUPP;
637 			break;
638 		}
639 		break;
640 	case SOPT_SET:
641 	default:
642 		error = EOPNOTSUPP;
643 		break;
644 	}
645 	return (error);
646 }
647 
648 /*
649  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
650  * for stream sockets, although the total for sender and receiver is
651  * actually only PIPSIZ.
652  * Datagram sockets really use the sendspace as the maximum datagram size,
653  * and don't really want to reserve the sendspace.  Their recvspace should
654  * be large enough for at least one max-size datagram plus address.
655  */
656 #ifndef PIPSIZ
657 #define	PIPSIZ	8192
658 #endif
659 static u_long	unpst_sendspace = PIPSIZ;
660 static u_long	unpst_recvspace = PIPSIZ;
661 static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
662 static u_long	unpdg_recvspace = 4*1024;
663 
664 static int	unp_rights;			/* file descriptors in flight */
665 
666 SYSCTL_DECL(_net_local_stream);
667 SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
668 	   &unpst_sendspace, 0, "");
669 SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
670 	   &unpst_recvspace, 0, "");
671 SYSCTL_DECL(_net_local_dgram);
672 SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
673 	   &unpdg_sendspace, 0, "");
674 SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
675 	   &unpdg_recvspace, 0, "");
676 SYSCTL_DECL(_net_local);
677 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
678 
679 static int
680 unp_attach(so)
681 	struct socket *so;
682 {
683 	register struct unpcb *unp;
684 	int error;
685 
686 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
687 		switch (so->so_type) {
688 
689 		case SOCK_STREAM:
690 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
691 			break;
692 
693 		case SOCK_DGRAM:
694 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
695 			break;
696 
697 		default:
698 			panic("unp_attach");
699 		}
700 		if (error)
701 			return (error);
702 	}
703 	unp = uma_zalloc(unp_zone, M_WAITOK);
704 	if (unp == NULL)
705 		return (ENOBUFS);
706 	bzero(unp, sizeof *unp);
707 	LIST_INIT(&unp->unp_refs);
708 	unp->unp_socket = so;
709 
710 	UNP_LOCK();
711 	unp->unp_gencnt = ++unp_gencnt;
712 	unp_count++;
713 	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
714 			 : &unp_shead, unp, unp_link);
715 	so->so_pcb = unp;
716 	UNP_UNLOCK();
717 
718 	return (0);
719 }
720 
721 static void
722 unp_detach(unp)
723 	register struct unpcb *unp;
724 {
725 	struct vnode *vp;
726 
727 	UNP_LOCK_ASSERT();
728 
729 	LIST_REMOVE(unp, unp_link);
730 	unp->unp_gencnt = ++unp_gencnt;
731 	--unp_count;
732 	if ((vp = unp->unp_vnode) != NULL) {
733 		/*
734 		 * XXXRW: should v_socket be frobbed only while holding
735 		 * Giant?
736 		 */
737 		unp->unp_vnode->v_socket = NULL;
738 		unp->unp_vnode = NULL;
739 	}
740 	if (unp->unp_conn != NULL)
741 		unp_disconnect(unp);
742 	while (!LIST_EMPTY(&unp->unp_refs)) {
743 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
744 		unp_drop(ref, ECONNRESET);
745 	}
746 	soisdisconnected(unp->unp_socket);
747 	unp->unp_socket->so_pcb = NULL;
748 	if (unp_rights) {
749 		/*
750 		 * Normally the receive buffer is flushed later,
751 		 * in sofree, but if our receive buffer holds references
752 		 * to descriptors that are now garbage, we will dispose
753 		 * of those descriptor references after the garbage collector
754 		 * gets them (resulting in a "panic: closef: count < 0").
755 		 */
756 		sorflush(unp->unp_socket);
757 		unp_gc();	/* Will unlock UNP. */
758 	} else
759 		UNP_UNLOCK();
760 	UNP_UNLOCK_ASSERT();
761 	if (unp->unp_addr != NULL)
762 		FREE(unp->unp_addr, M_SONAME);
763 	uma_zfree(unp_zone, unp);
764 	if (vp) {
765 		mtx_lock(&Giant);
766 		vrele(vp);
767 		mtx_unlock(&Giant);
768 	}
769 }
770 
771 static int
772 unp_bind(unp, nam, td)
773 	struct unpcb *unp;
774 	struct sockaddr *nam;
775 	struct thread *td;
776 {
777 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
778 	struct vnode *vp;
779 	struct mount *mp;
780 	struct vattr vattr;
781 	int error, namelen;
782 	struct nameidata nd;
783 	char *buf;
784 
785 	UNP_LOCK_ASSERT();
786 
787 	/*
788 	 * XXXRW: This test-and-set of unp_vnode is non-atomic; the
789 	 * unlocked read here is fine, but the value of unp_vnode needs
790 	 * to be tested again after we do all the lookups to see if the
791 	 * pcb is still unbound?
792 	 */
793 	if (unp->unp_vnode != NULL)
794 		return (EINVAL);
795 
796 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
797 	if (namelen <= 0)
798 		return (EINVAL);
799 
800 	UNP_UNLOCK();
801 
802 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
803 	strlcpy(buf, soun->sun_path, namelen + 1);
804 
805 	mtx_lock(&Giant);
806 restart:
807 	mtx_assert(&Giant, MA_OWNED);
808 	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
809 	    buf, td);
810 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
811 	error = namei(&nd);
812 	if (error)
813 		goto done;
814 	vp = nd.ni_vp;
815 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
816 		NDFREE(&nd, NDF_ONLY_PNBUF);
817 		if (nd.ni_dvp == vp)
818 			vrele(nd.ni_dvp);
819 		else
820 			vput(nd.ni_dvp);
821 		if (vp != NULL) {
822 			vrele(vp);
823 			error = EADDRINUSE;
824 			goto done;
825 		}
826 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
827 		if (error)
828 			goto done;
829 		goto restart;
830 	}
831 	VATTR_NULL(&vattr);
832 	vattr.va_type = VSOCK;
833 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
834 #ifdef MAC
835 	error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
836 	    &vattr);
837 #endif
838 	if (error == 0) {
839 		VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
840 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
841 	}
842 	NDFREE(&nd, NDF_ONLY_PNBUF);
843 	vput(nd.ni_dvp);
844 	if (error)
845 		goto done;
846 	vp = nd.ni_vp;
847 	ASSERT_VOP_LOCKED(vp, "unp_bind");
848 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
849 	UNP_LOCK();
850 	vp->v_socket = unp->unp_socket;
851 	unp->unp_vnode = vp;
852 	unp->unp_addr = soun;
853 	UNP_UNLOCK();
854 	VOP_UNLOCK(vp, 0, td);
855 	vn_finished_write(mp);
856 done:
857 	mtx_unlock(&Giant);
858 	free(buf, M_TEMP);
859 	UNP_LOCK();
860 	return (error);
861 }
862 
863 static int
864 unp_connect(so, nam, td)
865 	struct socket *so;
866 	struct sockaddr *nam;
867 	struct thread *td;
868 {
869 	register struct sockaddr_un *soun = (struct sockaddr_un *)nam;
870 	register struct vnode *vp;
871 	register struct socket *so2, *so3;
872 	struct unpcb *unp, *unp2, *unp3;
873 	int error, len;
874 	struct nameidata nd;
875 	char buf[SOCK_MAXADDRLEN];
876 	struct sockaddr *sa;
877 
878 	UNP_LOCK_ASSERT();
879 	unp = sotounpcb(so);
880 
881 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
882 	if (len <= 0)
883 		return (EINVAL);
884 	strlcpy(buf, soun->sun_path, len + 1);
885 	UNP_UNLOCK();
886 	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
887 	mtx_lock(&Giant);
888 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
889 	error = namei(&nd);
890 	if (error)
891 		vp = NULL;
892 	else
893 		vp = nd.ni_vp;
894 	ASSERT_VOP_LOCKED(vp, "unp_connect");
895 	NDFREE(&nd, NDF_ONLY_PNBUF);
896 	if (error)
897 		goto bad;
898 
899 	if (vp->v_type != VSOCK) {
900 		error = ENOTSOCK;
901 		goto bad;
902 	}
903 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
904 	if (error)
905 		goto bad;
906 	mtx_unlock(&Giant);
907 	UNP_LOCK();
908 	unp = sotounpcb(so);
909 	if (unp == NULL) {
910 		error = EINVAL;
911 		goto bad2;
912 	}
913 	so2 = vp->v_socket;
914 	if (so2 == NULL) {
915 		error = ECONNREFUSED;
916 		goto bad2;
917 	}
918 	if (so->so_type != so2->so_type) {
919 		error = EPROTOTYPE;
920 		goto bad2;
921 	}
922 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
923 		if (so2->so_options & SO_ACCEPTCONN) {
924 			/*
925 			 * NB: drop locks here so unp_attach is entered
926 			 *     w/o locks; this avoids a recursive lock
927 			 *     of the head and holding sleep locks across
928 			 *     a (potentially) blocking malloc.
929 			 */
930 			UNP_UNLOCK();
931 			so3 = sonewconn(so2, 0);
932 			UNP_LOCK();
933 		} else
934 			so3 = NULL;
935 		if (so3 == NULL) {
936 			error = ECONNREFUSED;
937 			goto bad2;
938 		}
939 		unp = sotounpcb(so);
940 		unp2 = sotounpcb(so2);
941 		unp3 = sotounpcb(so3);
942 		if (unp2->unp_addr != NULL) {
943 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
944 			unp3->unp_addr = (struct sockaddr_un *) sa;
945 			sa = NULL;
946 		}
947 		/*
948 		 * unp_peercred management:
949 		 *
950 		 * The connecter's (client's) credentials are copied
951 		 * from its process structure at the time of connect()
952 		 * (which is now).
953 		 */
954 		cru2x(td->td_ucred, &unp3->unp_peercred);
955 		unp3->unp_flags |= UNP_HAVEPC;
956 		/*
957 		 * The receiver's (server's) credentials are copied
958 		 * from the unp_peercred member of socket on which the
959 		 * former called listen(); unp_listen() cached that
960 		 * process's credentials at that time so we can use
961 		 * them now.
962 		 */
963 		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
964 		    ("unp_connect: listener without cached peercred"));
965 		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
966 		    sizeof(unp->unp_peercred));
967 		unp->unp_flags |= UNP_HAVEPC;
968 #ifdef MAC
969 		SOCK_LOCK(so);
970 		mac_set_socket_peer_from_socket(so, so3);
971 		mac_set_socket_peer_from_socket(so3, so);
972 		SOCK_UNLOCK(so);
973 #endif
974 
975 		so2 = so3;
976 	}
977 	error = unp_connect2(so, so2);
978 bad2:
979 	UNP_UNLOCK();
980 	mtx_lock(&Giant);
981 bad:
982 	mtx_assert(&Giant, MA_OWNED);
983 	if (vp != NULL)
984 		vput(vp);
985 	mtx_unlock(&Giant);
986 	free(sa, M_SONAME);
987 	UNP_LOCK();
988 	return (error);
989 }
990 
991 static int
992 unp_connect2(so, so2)
993 	register struct socket *so;
994 	register struct socket *so2;
995 {
996 	register struct unpcb *unp = sotounpcb(so);
997 	register struct unpcb *unp2;
998 
999 	UNP_LOCK_ASSERT();
1000 
1001 	if (so2->so_type != so->so_type)
1002 		return (EPROTOTYPE);
1003 	unp2 = sotounpcb(so2);
1004 	unp->unp_conn = unp2;
1005 	switch (so->so_type) {
1006 
1007 	case SOCK_DGRAM:
1008 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1009 		soisconnected(so);
1010 		break;
1011 
1012 	case SOCK_STREAM:
1013 		unp2->unp_conn = unp;
1014 		soisconnected(so);
1015 		soisconnected(so2);
1016 		break;
1017 
1018 	default:
1019 		panic("unp_connect2");
1020 	}
1021 	return (0);
1022 }
1023 
1024 static void
1025 unp_disconnect(unp)
1026 	struct unpcb *unp;
1027 {
1028 	register struct unpcb *unp2 = unp->unp_conn;
1029 	struct socket *so;
1030 
1031 	UNP_LOCK_ASSERT();
1032 
1033 	if (unp2 == NULL)
1034 		return;
1035 	unp->unp_conn = NULL;
1036 	switch (unp->unp_socket->so_type) {
1037 
1038 	case SOCK_DGRAM:
1039 		LIST_REMOVE(unp, unp_reflink);
1040 		so = unp->unp_socket;
1041 		SOCK_LOCK(so);
1042 		so->so_state &= ~SS_ISCONNECTED;
1043 		SOCK_UNLOCK(so);
1044 		break;
1045 
1046 	case SOCK_STREAM:
1047 		soisdisconnected(unp->unp_socket);
1048 		unp2->unp_conn = NULL;
1049 		soisdisconnected(unp2->unp_socket);
1050 		break;
1051 	}
1052 }
1053 
1054 #ifdef notdef
1055 void
1056 unp_abort(unp)
1057 	struct unpcb *unp;
1058 {
1059 
1060 	unp_detach(unp);
1061 	UNP_UNLOCK_ASSERT();
1062 }
1063 #endif
1064 
1065 /*
1066  * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed
1067  * by the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers
1068  * are safe to reference.  It first scans the list of struct unpcb's to
1069  * generate a pointer list, then it rescans its list one entry at a time to
1070  * externalize and copyout.  It checks the generation number to see if a
1071  * struct unpcb has been reused, and will skip it if so.
1072  */
1073 static int
1074 unp_pcblist(SYSCTL_HANDLER_ARGS)
1075 {
1076 	int error, i, n;
1077 	struct unpcb *unp, **unp_list;
1078 	unp_gen_t gencnt;
1079 	struct xunpgen *xug;
1080 	struct unp_head *head;
1081 	struct xunpcb *xu;
1082 
1083 	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1084 
1085 	/*
1086 	 * The process of preparing the PCB list is too time-consuming and
1087 	 * resource-intensive to repeat twice on every request.
1088 	 */
1089 	if (req->oldptr == NULL) {
1090 		n = unp_count;
1091 		req->oldidx = 2 * (sizeof *xug)
1092 			+ (n + n/8) * sizeof(struct xunpcb);
1093 		return (0);
1094 	}
1095 
1096 	if (req->newptr != NULL)
1097 		return (EPERM);
1098 
1099 	/*
1100 	 * OK, now we're committed to doing something.
1101 	 */
1102 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1103 	UNP_LOCK();
1104 	gencnt = unp_gencnt;
1105 	n = unp_count;
1106 	UNP_UNLOCK();
1107 
1108 	xug->xug_len = sizeof *xug;
1109 	xug->xug_count = n;
1110 	xug->xug_gen = gencnt;
1111 	xug->xug_sogen = so_gencnt;
1112 	error = SYSCTL_OUT(req, xug, sizeof *xug);
1113 	if (error) {
1114 		free(xug, M_TEMP);
1115 		return (error);
1116 	}
1117 
1118 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1119 
1120 	UNP_LOCK();
1121 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1122 	     unp = LIST_NEXT(unp, unp_link)) {
1123 		if (unp->unp_gencnt <= gencnt) {
1124 			if (cr_cansee(req->td->td_ucred,
1125 			    unp->unp_socket->so_cred))
1126 				continue;
1127 			unp_list[i++] = unp;
1128 		}
1129 	}
1130 	UNP_UNLOCK();
1131 	n = i;			/* in case we lost some during malloc */
1132 
1133 	error = 0;
1134 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK);
1135 	for (i = 0; i < n; i++) {
1136 		unp = unp_list[i];
1137 		if (unp->unp_gencnt <= gencnt) {
1138 			xu->xu_len = sizeof *xu;
1139 			xu->xu_unpp = unp;
1140 			/*
1141 			 * XXX - need more locking here to protect against
1142 			 * connect/disconnect races for SMP.
1143 			 */
1144 			if (unp->unp_addr != NULL)
1145 				bcopy(unp->unp_addr, &xu->xu_addr,
1146 				      unp->unp_addr->sun_len);
1147 			if (unp->unp_conn != NULL &&
1148 			    unp->unp_conn->unp_addr != NULL)
1149 				bcopy(unp->unp_conn->unp_addr,
1150 				      &xu->xu_caddr,
1151 				      unp->unp_conn->unp_addr->sun_len);
1152 			bcopy(unp, &xu->xu_unp, sizeof *unp);
1153 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1154 			error = SYSCTL_OUT(req, xu, sizeof *xu);
1155 		}
1156 	}
1157 	free(xu, M_TEMP);
1158 	if (!error) {
1159 		/*
1160 		 * Give the user an updated idea of our state.
1161 		 * If the generation differs from what we told
1162 		 * her before, she knows that something happened
1163 		 * while we were processing this request, and it
1164 		 * might be necessary to retry.
1165 		 */
1166 		xug->xug_gen = unp_gencnt;
1167 		xug->xug_sogen = so_gencnt;
1168 		xug->xug_count = unp_count;
1169 		error = SYSCTL_OUT(req, xug, sizeof *xug);
1170 	}
1171 	free(unp_list, M_TEMP);
1172 	free(xug, M_TEMP);
1173 	return (error);
1174 }
1175 
1176 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1177 	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1178 	    "List of active local datagram sockets");
1179 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1180 	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1181 	    "List of active local stream sockets");
1182 
1183 static void
1184 unp_shutdown(unp)
1185 	struct unpcb *unp;
1186 {
1187 	struct socket *so;
1188 
1189 	UNP_LOCK_ASSERT();
1190 
1191 	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1192 	    (so = unp->unp_conn->unp_socket))
1193 		socantrcvmore(so);
1194 }
1195 
1196 static void
1197 unp_drop(unp, errno)
1198 	struct unpcb *unp;
1199 	int errno;
1200 {
1201 	struct socket *so = unp->unp_socket;
1202 
1203 	UNP_LOCK_ASSERT();
1204 
1205 	so->so_error = errno;
1206 	unp_disconnect(unp);
1207 }
1208 
1209 #ifdef notdef
1210 void
1211 unp_drain()
1212 {
1213 
1214 }
1215 #endif
1216 
1217 static void
1218 unp_freerights(rp, fdcount)
1219 	struct file **rp;
1220 	int fdcount;
1221 {
1222 	int i;
1223 	struct file *fp;
1224 
1225 	for (i = 0; i < fdcount; i++) {
1226 		fp = *rp;
1227 		/*
1228 		 * zero the pointer before calling
1229 		 * unp_discard since it may end up
1230 		 * in unp_gc()..
1231 		 */
1232 		*rp++ = 0;
1233 		unp_discard(fp);
1234 	}
1235 }
1236 
1237 int
1238 unp_externalize(control, controlp)
1239 	struct mbuf *control, **controlp;
1240 {
1241 	struct thread *td = curthread;		/* XXX */
1242 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1243 	int i;
1244 	int *fdp;
1245 	struct file **rp;
1246 	struct file *fp;
1247 	void *data;
1248 	socklen_t clen = control->m_len, datalen;
1249 	int error, newfds;
1250 	int f;
1251 	u_int newlen;
1252 
1253 	UNP_UNLOCK_ASSERT();
1254 
1255 	error = 0;
1256 	if (controlp != NULL) /* controlp == NULL => free control messages */
1257 		*controlp = NULL;
1258 
1259 	while (cm != NULL) {
1260 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1261 			error = EINVAL;
1262 			break;
1263 		}
1264 
1265 		data = CMSG_DATA(cm);
1266 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1267 
1268 		if (cm->cmsg_level == SOL_SOCKET
1269 		    && cm->cmsg_type == SCM_RIGHTS) {
1270 			newfds = datalen / sizeof(struct file *);
1271 			rp = data;
1272 
1273 			/* If we're not outputting the descriptors free them. */
1274 			if (error || controlp == NULL) {
1275 				unp_freerights(rp, newfds);
1276 				goto next;
1277 			}
1278 			FILEDESC_LOCK(td->td_proc->p_fd);
1279 			/* if the new FD's will not fit free them.  */
1280 			if (!fdavail(td, newfds)) {
1281 				FILEDESC_UNLOCK(td->td_proc->p_fd);
1282 				error = EMSGSIZE;
1283 				unp_freerights(rp, newfds);
1284 				goto next;
1285 			}
1286 			/*
1287 			 * now change each pointer to an fd in the global
1288 			 * table to an integer that is the index to the
1289 			 * local fd table entry that we set up to point
1290 			 * to the global one we are transferring.
1291 			 */
1292 			newlen = newfds * sizeof(int);
1293 			*controlp = sbcreatecontrol(NULL, newlen,
1294 			    SCM_RIGHTS, SOL_SOCKET);
1295 			if (*controlp == NULL) {
1296 				FILEDESC_UNLOCK(td->td_proc->p_fd);
1297 				error = E2BIG;
1298 				unp_freerights(rp, newfds);
1299 				goto next;
1300 			}
1301 
1302 			fdp = (int *)
1303 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1304 			for (i = 0; i < newfds; i++) {
1305 				if (fdalloc(td, 0, &f))
1306 					panic("unp_externalize fdalloc failed");
1307 				fp = *rp++;
1308 				td->td_proc->p_fd->fd_ofiles[f] = fp;
1309 				FILE_LOCK(fp);
1310 				fp->f_msgcount--;
1311 				FILE_UNLOCK(fp);
1312 				unp_rights--;
1313 				*fdp++ = f;
1314 			}
1315 			FILEDESC_UNLOCK(td->td_proc->p_fd);
1316 		} else { /* We can just copy anything else across */
1317 			if (error || controlp == NULL)
1318 				goto next;
1319 			*controlp = sbcreatecontrol(NULL, datalen,
1320 			    cm->cmsg_type, cm->cmsg_level);
1321 			if (*controlp == NULL) {
1322 				error = ENOBUFS;
1323 				goto next;
1324 			}
1325 			bcopy(data,
1326 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1327 			    datalen);
1328 		}
1329 
1330 		controlp = &(*controlp)->m_next;
1331 
1332 next:
1333 		if (CMSG_SPACE(datalen) < clen) {
1334 			clen -= CMSG_SPACE(datalen);
1335 			cm = (struct cmsghdr *)
1336 			    ((caddr_t)cm + CMSG_SPACE(datalen));
1337 		} else {
1338 			clen = 0;
1339 			cm = NULL;
1340 		}
1341 	}
1342 
1343 	m_freem(control);
1344 
1345 	return (error);
1346 }
1347 
1348 void
1349 unp_init(void)
1350 {
1351 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1352 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1353 	if (unp_zone == NULL)
1354 		panic("unp_init");
1355 	uma_zone_set_max(unp_zone, nmbclusters);
1356 	LIST_INIT(&unp_dhead);
1357 	LIST_INIT(&unp_shead);
1358 
1359 	UNP_LOCK_INIT();
1360 }
1361 
1362 static int
1363 unp_internalize(controlp, td)
1364 	struct mbuf **controlp;
1365 	struct thread *td;
1366 {
1367 	struct mbuf *control = *controlp;
1368 	struct proc *p = td->td_proc;
1369 	struct filedesc *fdescp = p->p_fd;
1370 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1371 	struct cmsgcred *cmcred;
1372 	struct file **rp;
1373 	struct file *fp;
1374 	struct timeval *tv;
1375 	int i, fd, *fdp;
1376 	void *data;
1377 	socklen_t clen = control->m_len, datalen;
1378 	int error, oldfds;
1379 	u_int newlen;
1380 
1381 	UNP_UNLOCK_ASSERT();
1382 
1383 	error = 0;
1384 	*controlp = NULL;
1385 
1386 	while (cm != NULL) {
1387 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1388 		    || cm->cmsg_len > clen) {
1389 			error = EINVAL;
1390 			goto out;
1391 		}
1392 
1393 		data = CMSG_DATA(cm);
1394 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1395 
1396 		switch (cm->cmsg_type) {
1397 		/*
1398 		 * Fill in credential information.
1399 		 */
1400 		case SCM_CREDS:
1401 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1402 			    SCM_CREDS, SOL_SOCKET);
1403 			if (*controlp == NULL) {
1404 				error = ENOBUFS;
1405 				goto out;
1406 			}
1407 
1408 			cmcred = (struct cmsgcred *)
1409 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1410 			cmcred->cmcred_pid = p->p_pid;
1411 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1412 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1413 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1414 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1415 							CMGROUP_MAX);
1416 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1417 				cmcred->cmcred_groups[i] =
1418 				    td->td_ucred->cr_groups[i];
1419 			break;
1420 
1421 		case SCM_RIGHTS:
1422 			oldfds = datalen / sizeof (int);
1423 			/*
1424 			 * check that all the FDs passed in refer to legal files
1425 			 * If not, reject the entire operation.
1426 			 */
1427 			fdp = data;
1428 			FILEDESC_LOCK(fdescp);
1429 			for (i = 0; i < oldfds; i++) {
1430 				fd = *fdp++;
1431 				if ((unsigned)fd >= fdescp->fd_nfiles ||
1432 				    fdescp->fd_ofiles[fd] == NULL) {
1433 					FILEDESC_UNLOCK(fdescp);
1434 					error = EBADF;
1435 					goto out;
1436 				}
1437 				fp = fdescp->fd_ofiles[fd];
1438 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1439 					FILEDESC_UNLOCK(fdescp);
1440 					error = EOPNOTSUPP;
1441 					goto out;
1442 				}
1443 
1444 			}
1445 			/*
1446 			 * Now replace the integer FDs with pointers to
1447 			 * the associated global file table entry..
1448 			 */
1449 			newlen = oldfds * sizeof(struct file *);
1450 			*controlp = sbcreatecontrol(NULL, newlen,
1451 			    SCM_RIGHTS, SOL_SOCKET);
1452 			if (*controlp == NULL) {
1453 				FILEDESC_UNLOCK(fdescp);
1454 				error = E2BIG;
1455 				goto out;
1456 			}
1457 
1458 			fdp = data;
1459 			rp = (struct file **)
1460 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1461 			for (i = 0; i < oldfds; i++) {
1462 				fp = fdescp->fd_ofiles[*fdp++];
1463 				*rp++ = fp;
1464 				FILE_LOCK(fp);
1465 				fp->f_count++;
1466 				fp->f_msgcount++;
1467 				FILE_UNLOCK(fp);
1468 				unp_rights++;
1469 			}
1470 			FILEDESC_UNLOCK(fdescp);
1471 			break;
1472 
1473 		case SCM_TIMESTAMP:
1474 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
1475 			    SCM_TIMESTAMP, SOL_SOCKET);
1476 			if (*controlp == NULL) {
1477 				error = ENOBUFS;
1478 				goto out;
1479 			}
1480 			tv = (struct timeval *)
1481 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1482 			microtime(tv);
1483 			break;
1484 
1485 		default:
1486 			error = EINVAL;
1487 			goto out;
1488 		}
1489 
1490 		controlp = &(*controlp)->m_next;
1491 
1492 		if (CMSG_SPACE(datalen) < clen) {
1493 			clen -= CMSG_SPACE(datalen);
1494 			cm = (struct cmsghdr *)
1495 			    ((caddr_t)cm + CMSG_SPACE(datalen));
1496 		} else {
1497 			clen = 0;
1498 			cm = NULL;
1499 		}
1500 	}
1501 
1502 out:
1503 	m_freem(control);
1504 
1505 	return (error);
1506 }
1507 
1508 /*
1509  * unp_defer is thread-local during garbage collection, and does not require
1510  * explicit synchronization.  unp_gcing prevents other threads from entering
1511  * garbage collection, and perhaps should be an sx lock instead.
1512  */
1513 static int	unp_defer, unp_gcing;
1514 
1515 static void
1516 unp_gc()
1517 {
1518 	register struct file *fp, *nextfp;
1519 	register struct socket *so;
1520 	struct file **extra_ref, **fpp;
1521 	int nunref, i;
1522 	int nfiles_snap;
1523 	int nfiles_slack = 20;
1524 
1525 	UNP_LOCK_ASSERT();
1526 
1527 	if (unp_gcing) {
1528 		UNP_UNLOCK();
1529 		return;
1530 	}
1531 	unp_gcing = 1;
1532 	unp_defer = 0;
1533 	UNP_UNLOCK();
1534 	/*
1535 	 * before going through all this, set all FDs to
1536 	 * be NOT defered and NOT externally accessible
1537 	 */
1538 	sx_slock(&filelist_lock);
1539 	LIST_FOREACH(fp, &filehead, f_list)
1540 		fp->f_gcflag &= ~(FMARK|FDEFER);
1541 	do {
1542 		LIST_FOREACH(fp, &filehead, f_list) {
1543 			FILE_LOCK(fp);
1544 			/*
1545 			 * If the file is not open, skip it
1546 			 */
1547 			if (fp->f_count == 0) {
1548 				FILE_UNLOCK(fp);
1549 				continue;
1550 			}
1551 			/*
1552 			 * If we already marked it as 'defer'  in a
1553 			 * previous pass, then try process it this time
1554 			 * and un-mark it
1555 			 */
1556 			if (fp->f_gcflag & FDEFER) {
1557 				fp->f_gcflag &= ~FDEFER;
1558 				unp_defer--;
1559 			} else {
1560 				/*
1561 				 * if it's not defered, then check if it's
1562 				 * already marked.. if so skip it
1563 				 */
1564 				if (fp->f_gcflag & FMARK) {
1565 					FILE_UNLOCK(fp);
1566 					continue;
1567 				}
1568 				/*
1569 				 * If all references are from messages
1570 				 * in transit, then skip it. it's not
1571 				 * externally accessible.
1572 				 */
1573 				if (fp->f_count == fp->f_msgcount) {
1574 					FILE_UNLOCK(fp);
1575 					continue;
1576 				}
1577 				/*
1578 				 * If it got this far then it must be
1579 				 * externally accessible.
1580 				 */
1581 				fp->f_gcflag |= FMARK;
1582 			}
1583 			/*
1584 			 * either it was defered, or it is externally
1585 			 * accessible and not already marked so.
1586 			 * Now check if it is possibly one of OUR sockets.
1587 			 */
1588 			if (fp->f_type != DTYPE_SOCKET ||
1589 			    (so = fp->f_data) == NULL) {
1590 				FILE_UNLOCK(fp);
1591 				continue;
1592 			}
1593 			FILE_UNLOCK(fp);
1594 			if (so->so_proto->pr_domain != &localdomain ||
1595 			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1596 				continue;
1597 #ifdef notdef
1598 			if (so->so_rcv.sb_flags & SB_LOCK) {
1599 				/*
1600 				 * This is problematical; it's not clear
1601 				 * we need to wait for the sockbuf to be
1602 				 * unlocked (on a uniprocessor, at least),
1603 				 * and it's also not clear what to do
1604 				 * if sbwait returns an error due to receipt
1605 				 * of a signal.  If sbwait does return
1606 				 * an error, we'll go into an infinite
1607 				 * loop.  Delete all of this for now.
1608 				 */
1609 				(void) sbwait(&so->so_rcv);
1610 				goto restart;
1611 			}
1612 #endif
1613 			/*
1614 			 * So, Ok, it's one of our sockets and it IS externally
1615 			 * accessible (or was defered). Now we look
1616 			 * to see if we hold any file descriptors in its
1617 			 * message buffers. Follow those links and mark them
1618 			 * as accessible too.
1619 			 */
1620 			SOCKBUF_LOCK(&so->so_rcv);
1621 			unp_scan(so->so_rcv.sb_mb, unp_mark);
1622 			SOCKBUF_UNLOCK(&so->so_rcv);
1623 		}
1624 	} while (unp_defer);
1625 	sx_sunlock(&filelist_lock);
1626 	/*
1627 	 * We grab an extra reference to each of the file table entries
1628 	 * that are not otherwise accessible and then free the rights
1629 	 * that are stored in messages on them.
1630 	 *
1631 	 * The bug in the orginal code is a little tricky, so I'll describe
1632 	 * what's wrong with it here.
1633 	 *
1634 	 * It is incorrect to simply unp_discard each entry for f_msgcount
1635 	 * times -- consider the case of sockets A and B that contain
1636 	 * references to each other.  On a last close of some other socket,
1637 	 * we trigger a gc since the number of outstanding rights (unp_rights)
1638 	 * is non-zero.  If during the sweep phase the gc code un_discards,
1639 	 * we end up doing a (full) closef on the descriptor.  A closef on A
1640 	 * results in the following chain.  Closef calls soo_close, which
1641 	 * calls soclose.   Soclose calls first (through the switch
1642 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1643 	 * returns because the previous instance had set unp_gcing, and
1644 	 * we return all the way back to soclose, which marks the socket
1645 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1646 	 * to free up the rights that are queued in messages on the socket A,
1647 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1648 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1649 	 * instance of unp_discard just calls closef on B.
1650 	 *
1651 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1652 	 * which results in another closef on A.  Unfortunately, A is already
1653 	 * being closed, and the descriptor has already been marked with
1654 	 * SS_NOFDREF, and soclose panics at this point.
1655 	 *
1656 	 * Here, we first take an extra reference to each inaccessible
1657 	 * descriptor.  Then, we call sorflush ourself, since we know
1658 	 * it is a Unix domain socket anyhow.  After we destroy all the
1659 	 * rights carried in messages, we do a last closef to get rid
1660 	 * of our extra reference.  This is the last close, and the
1661 	 * unp_detach etc will shut down the socket.
1662 	 *
1663 	 * 91/09/19, bsy@cs.cmu.edu
1664 	 */
1665 again:
1666 	nfiles_snap = openfiles + nfiles_slack;	/* some slack */
1667 	extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
1668 	    M_WAITOK);
1669 	sx_slock(&filelist_lock);
1670 	if (nfiles_snap < openfiles) {
1671 		sx_sunlock(&filelist_lock);
1672 		free(extra_ref, M_TEMP);
1673 		nfiles_slack += 20;
1674 		goto again;
1675 	}
1676 	for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1677 	    fp != NULL; fp = nextfp) {
1678 		nextfp = LIST_NEXT(fp, f_list);
1679 		FILE_LOCK(fp);
1680 		/*
1681 		 * If it's not open, skip it
1682 		 */
1683 		if (fp->f_count == 0) {
1684 			FILE_UNLOCK(fp);
1685 			continue;
1686 		}
1687 		/*
1688 		 * If all refs are from msgs, and it's not marked accessible
1689 		 * then it must be referenced from some unreachable cycle
1690 		 * of (shut-down) FDs, so include it in our
1691 		 * list of FDs to remove
1692 		 */
1693 		if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1694 			*fpp++ = fp;
1695 			nunref++;
1696 			fp->f_count++;
1697 		}
1698 		FILE_UNLOCK(fp);
1699 	}
1700 	sx_sunlock(&filelist_lock);
1701 	/*
1702 	 * for each FD on our hit list, do the following two things
1703 	 */
1704 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1705 		struct file *tfp = *fpp;
1706 		FILE_LOCK(tfp);
1707 		if (tfp->f_type == DTYPE_SOCKET &&
1708 		    tfp->f_data != NULL) {
1709 			FILE_UNLOCK(tfp);
1710 			sorflush(tfp->f_data);
1711 		} else {
1712 			FILE_UNLOCK(tfp);
1713 		}
1714 	}
1715 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1716 		closef(*fpp, (struct thread *) NULL);
1717 	free(extra_ref, M_TEMP);
1718 	unp_gcing = 0;
1719 
1720 	UNP_UNLOCK_ASSERT();
1721 }
1722 
1723 void
1724 unp_dispose(m)
1725 	struct mbuf *m;
1726 {
1727 
1728 	if (m)
1729 		unp_scan(m, unp_discard);
1730 }
1731 
1732 static int
1733 unp_listen(unp, td)
1734 	struct unpcb *unp;
1735 	struct thread *td;
1736 {
1737 	UNP_LOCK_ASSERT();
1738 
1739 	/*
1740 	 * XXXRW: Why populate the local peer cred with our own credential?
1741 	 */
1742 	cru2x(td->td_ucred, &unp->unp_peercred);
1743 	unp->unp_flags |= UNP_HAVEPCCACHED;
1744 	return (0);
1745 }
1746 
1747 static void
1748 unp_scan(m0, op)
1749 	register struct mbuf *m0;
1750 	void (*op)(struct file *);
1751 {
1752 	struct mbuf *m;
1753 	struct file **rp;
1754 	struct cmsghdr *cm;
1755 	void *data;
1756 	int i;
1757 	socklen_t clen, datalen;
1758 	int qfds;
1759 
1760 	while (m0 != NULL) {
1761 		for (m = m0; m; m = m->m_next) {
1762 			if (m->m_type != MT_CONTROL)
1763 				continue;
1764 
1765 			cm = mtod(m, struct cmsghdr *);
1766 			clen = m->m_len;
1767 
1768 			while (cm != NULL) {
1769 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1770 					break;
1771 
1772 				data = CMSG_DATA(cm);
1773 				datalen = (caddr_t)cm + cm->cmsg_len
1774 				    - (caddr_t)data;
1775 
1776 				if (cm->cmsg_level == SOL_SOCKET &&
1777 				    cm->cmsg_type == SCM_RIGHTS) {
1778 					qfds = datalen / sizeof (struct file *);
1779 					rp = data;
1780 					for (i = 0; i < qfds; i++)
1781 						(*op)(*rp++);
1782 				}
1783 
1784 				if (CMSG_SPACE(datalen) < clen) {
1785 					clen -= CMSG_SPACE(datalen);
1786 					cm = (struct cmsghdr *)
1787 					    ((caddr_t)cm + CMSG_SPACE(datalen));
1788 				} else {
1789 					clen = 0;
1790 					cm = NULL;
1791 				}
1792 			}
1793 		}
1794 		m0 = m0->m_act;
1795 	}
1796 }
1797 
1798 static void
1799 unp_mark(fp)
1800 	struct file *fp;
1801 {
1802 	if (fp->f_gcflag & FMARK)
1803 		return;
1804 	unp_defer++;
1805 	fp->f_gcflag |= (FMARK|FDEFER);
1806 }
1807 
1808 static void
1809 unp_discard(fp)
1810 	struct file *fp;
1811 {
1812 	FILE_LOCK(fp);
1813 	fp->f_msgcount--;
1814 	unp_rights--;
1815 	FILE_UNLOCK(fp);
1816 	(void) closef(fp, (struct thread *)NULL);
1817 }
1818