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