xref: /freebsd/sys/kern/uipc_usrreq.c (revision c0020399a650364d0134f79f3fa319f84064372d)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.
4  * Copyright (c) 2004-2009 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
32  */
33 
34 /*
35  * UNIX Domain (Local) Sockets
36  *
37  * This is an implementation of UNIX (local) domain sockets.  Each socket has
38  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
39  * may be connected to 0 or 1 other socket.  Datagram sockets may be
40  * connected to 0, 1, or many other sockets.  Sockets may be created and
41  * connected in pairs (socketpair(2)), or bound/connected to using the file
42  * system name space.  For most purposes, only the receive socket buffer is
43  * used, as sending on one socket delivers directly to the receive socket
44  * buffer of a second socket.
45  *
46  * The implementation is substantially complicated by the fact that
47  * "ancillary data", such as file descriptors or credentials, may be passed
48  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
49  * over other UNIX domain sockets requires the implementation of a simple
50  * garbage collector to find and tear down cycles of disconnected sockets.
51  *
52  * TODO:
53  *	SEQPACKET, RDM
54  *	rethink name space problems
55  *	need a proper out-of-band
56  */
57 
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
60 
61 #include "opt_ddb.h"
62 #include "opt_mac.h"
63 
64 #include <sys/param.h>
65 #include <sys/domain.h>
66 #include <sys/fcntl.h>
67 #include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
68 #include <sys/eventhandler.h>
69 #include <sys/file.h>
70 #include <sys/filedesc.h>
71 #include <sys/jail.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/mbuf.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
77 #include <sys/namei.h>
78 #include <sys/proc.h>
79 #include <sys/protosw.h>
80 #include <sys/resourcevar.h>
81 #include <sys/rwlock.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/signalvar.h>
85 #include <sys/stat.h>
86 #include <sys/sx.h>
87 #include <sys/sysctl.h>
88 #include <sys/systm.h>
89 #include <sys/taskqueue.h>
90 #include <sys/un.h>
91 #include <sys/unpcb.h>
92 #include <sys/vnode.h>
93 
94 #ifdef DDB
95 #include <ddb/ddb.h>
96 #endif
97 
98 #include <security/mac/mac_framework.h>
99 
100 #include <vm/uma.h>
101 
102 /*
103  * Locking key:
104  * (l)	Locked using list lock
105  * (g)	Locked using linkage lock
106  */
107 
108 static uma_zone_t	unp_zone;
109 static unp_gen_t	unp_gencnt;	/* (l) */
110 static u_int		unp_count;	/* (l) Count of local sockets. */
111 static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
112 static int		unp_rights;	/* (g) File descriptors in flight. */
113 static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
114 static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
115 
116 static const struct sockaddr	sun_noname = { sizeof(sun_noname), AF_LOCAL };
117 
118 /*
119  * Garbage collection of cyclic file descriptor/socket references occurs
120  * asynchronously in a taskqueue context in order to avoid recursion and
121  * reentrance in the UNIX domain socket, file descriptor, and socket layer
122  * code.  See unp_gc() for a full description.
123  */
124 static struct task	unp_gc_task;
125 
126 /*
127  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
128  * stream sockets, although the total for sender and receiver is actually
129  * only PIPSIZ.
130  *
131  * Datagram sockets really use the sendspace as the maximum datagram size,
132  * and don't really want to reserve the sendspace.  Their recvspace should be
133  * large enough for at least one max-size datagram plus address.
134  */
135 #ifndef PIPSIZ
136 #define	PIPSIZ	8192
137 #endif
138 static u_long	unpst_sendspace = PIPSIZ;
139 static u_long	unpst_recvspace = PIPSIZ;
140 static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
141 static u_long	unpdg_recvspace = 4*1024;
142 
143 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
144 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
145 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
146 
147 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
148 	   &unpst_sendspace, 0, "Default stream send space.");
149 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
150 	   &unpst_recvspace, 0, "Default stream receive space.");
151 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
152 	   &unpdg_sendspace, 0, "Default datagram send space.");
153 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
154 	   &unpdg_recvspace, 0, "Default datagram receive space.");
155 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
156     "File descriptors in flight.");
157 
158 /*-
159  * Locking and synchronization:
160  *
161  * Three types of locks exit in the local domain socket implementation: a
162  * global list mutex, a global linkage rwlock, and per-unpcb mutexes.  Of the
163  * global locks, the list lock protects the socket count, global generation
164  * number, and stream/datagram global lists.  The linkage lock protects the
165  * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
166  * held exclusively over the acquisition of multiple unpcb locks to prevent
167  * deadlock.
168  *
169  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
170  * allocated in pru_attach() and freed in pru_detach().  The validity of that
171  * pointer is an invariant, so no lock is required to dereference the so_pcb
172  * pointer if a valid socket reference is held by the caller.  In practice,
173  * this is always true during operations performed on a socket.  Each unpcb
174  * has a back-pointer to its socket, unp_socket, which will be stable under
175  * the same circumstances.
176  *
177  * This pointer may only be safely dereferenced as long as a valid reference
178  * to the unpcb is held.  Typically, this reference will be from the socket,
179  * or from another unpcb when the referring unpcb's lock is held (in order
180  * that the reference not be invalidated during use).  For example, to follow
181  * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
182  * as unp_socket remains valid as long as the reference to unp_conn is valid.
183  *
184  * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx.  Individual
185  * atomic reads without the lock may be performed "lockless", but more
186  * complex reads and read-modify-writes require the mutex to be held.  No
187  * lock order is defined between unpcb locks -- multiple unpcb locks may be
188  * acquired at the same time only when holding the linkage rwlock
189  * exclusively, which prevents deadlocks.
190  *
191  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
192  * protocols, bind() is a non-atomic operation, and connect() requires
193  * potential sleeping in the protocol, due to potentially waiting on local or
194  * distributed file systems.  We try to separate "lookup" operations, which
195  * may sleep, and the IPC operations themselves, which typically can occur
196  * with relative atomicity as locks can be held over the entire operation.
197  *
198  * Another tricky issue is simultaneous multi-threaded or multi-process
199  * access to a single UNIX domain socket.  These are handled by the flags
200  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
201  * binding, both of which involve dropping UNIX domain socket locks in order
202  * to perform namei() and other file system operations.
203  */
204 static struct rwlock	unp_link_rwlock;
205 static struct mtx	unp_list_lock;
206 
207 #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
208 					    "unp_link_rwlock")
209 
210 #define	UNP_LINK_LOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
211 					    RA_LOCKED)
212 #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
213 					    RA_UNLOCKED)
214 
215 #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
216 #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
217 #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
218 #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
219 #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
220 					    RA_WLOCKED)
221 
222 #define	UNP_LIST_LOCK_INIT()		mtx_init(&unp_list_lock,	\
223 					    "unp_list_lock", NULL, MTX_DEF)
224 #define	UNP_LIST_LOCK()			mtx_lock(&unp_list_lock)
225 #define	UNP_LIST_UNLOCK()		mtx_unlock(&unp_list_lock)
226 
227 #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
228 					    "unp_mtx", "unp_mtx",	\
229 					    MTX_DUPOK|MTX_DEF|MTX_RECURSE)
230 #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
231 #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
232 #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
233 #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
234 
235 static int	uipc_connect2(struct socket *, struct socket *);
236 static int	uipc_ctloutput(struct socket *, struct sockopt *);
237 static int	unp_connect(struct socket *, struct sockaddr *,
238 		    struct thread *);
239 static int	unp_connect2(struct socket *so, struct socket *so2, int);
240 static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
241 static void	unp_dispose(struct mbuf *);
242 static void	unp_shutdown(struct unpcb *);
243 static void	unp_drop(struct unpcb *, int);
244 static void	unp_gc(__unused void *, int);
245 static void	unp_scan(struct mbuf *, void (*)(struct file *));
246 static void	unp_discard(struct file *);
247 static void	unp_freerights(struct file **, int);
248 static void	unp_init(void);
249 static int	unp_internalize(struct mbuf **, struct thread *);
250 static void	unp_internalize_fp(struct file *);
251 static int	unp_externalize(struct mbuf *, struct mbuf **);
252 static void	unp_externalize_fp(struct file *);
253 static struct mbuf	*unp_addsockcred(struct thread *, struct mbuf *);
254 
255 /*
256  * Definitions of protocols supported in the LOCAL domain.
257  */
258 static struct domain localdomain;
259 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
260 static struct protosw localsw[] = {
261 {
262 	.pr_type =		SOCK_STREAM,
263 	.pr_domain =		&localdomain,
264 	.pr_flags =		PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
265 	.pr_ctloutput =		&uipc_ctloutput,
266 	.pr_usrreqs =		&uipc_usrreqs_stream
267 },
268 {
269 	.pr_type =		SOCK_DGRAM,
270 	.pr_domain =		&localdomain,
271 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_RIGHTS,
272 	.pr_usrreqs =		&uipc_usrreqs_dgram
273 },
274 };
275 
276 static struct domain localdomain = {
277 	.dom_family =		AF_LOCAL,
278 	.dom_name =		"local",
279 	.dom_init =		unp_init,
280 	.dom_externalize =	unp_externalize,
281 	.dom_dispose =		unp_dispose,
282 	.dom_protosw =		localsw,
283 	.dom_protoswNPROTOSW =	&localsw[sizeof(localsw)/sizeof(localsw[0])]
284 };
285 DOMAIN_SET(local);
286 
287 static void
288 uipc_abort(struct socket *so)
289 {
290 	struct unpcb *unp, *unp2;
291 
292 	unp = sotounpcb(so);
293 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
294 
295 	UNP_LINK_WLOCK();
296 	UNP_PCB_LOCK(unp);
297 	unp2 = unp->unp_conn;
298 	if (unp2 != NULL) {
299 		UNP_PCB_LOCK(unp2);
300 		unp_drop(unp2, ECONNABORTED);
301 		UNP_PCB_UNLOCK(unp2);
302 	}
303 	UNP_PCB_UNLOCK(unp);
304 	UNP_LINK_WUNLOCK();
305 }
306 
307 static int
308 uipc_accept(struct socket *so, struct sockaddr **nam)
309 {
310 	struct unpcb *unp, *unp2;
311 	const struct sockaddr *sa;
312 
313 	/*
314 	 * Pass back name of connected socket, if it was bound and we are
315 	 * still connected (our peer may have closed already!).
316 	 */
317 	unp = sotounpcb(so);
318 	KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
319 
320 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
321 	UNP_LINK_RLOCK();
322 	unp2 = unp->unp_conn;
323 	if (unp2 != NULL && unp2->unp_addr != NULL) {
324 		UNP_PCB_LOCK(unp2);
325 		sa = (struct sockaddr *) unp2->unp_addr;
326 		bcopy(sa, *nam, sa->sa_len);
327 		UNP_PCB_UNLOCK(unp2);
328 	} else {
329 		sa = &sun_noname;
330 		bcopy(sa, *nam, sa->sa_len);
331 	}
332 	UNP_LINK_RUNLOCK();
333 	return (0);
334 }
335 
336 static int
337 uipc_attach(struct socket *so, int proto, struct thread *td)
338 {
339 	u_long sendspace, recvspace;
340 	struct unpcb *unp;
341 	int error;
342 
343 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
344 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
345 		switch (so->so_type) {
346 		case SOCK_STREAM:
347 			sendspace = unpst_sendspace;
348 			recvspace = unpst_recvspace;
349 			break;
350 
351 		case SOCK_DGRAM:
352 			sendspace = unpdg_sendspace;
353 			recvspace = unpdg_recvspace;
354 			break;
355 
356 		default:
357 			panic("uipc_attach");
358 		}
359 		error = soreserve(so, sendspace, recvspace);
360 		if (error)
361 			return (error);
362 	}
363 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
364 	if (unp == NULL)
365 		return (ENOBUFS);
366 	LIST_INIT(&unp->unp_refs);
367 	UNP_PCB_LOCK_INIT(unp);
368 	unp->unp_socket = so;
369 	so->so_pcb = unp;
370 	unp->unp_refcount = 1;
371 
372 	UNP_LIST_LOCK();
373 	unp->unp_gencnt = ++unp_gencnt;
374 	unp_count++;
375 	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
376 	    unp, unp_link);
377 	UNP_LIST_UNLOCK();
378 
379 	return (0);
380 }
381 
382 static int
383 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
384 {
385 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
386 	struct vattr vattr;
387 	int error, namelen, vfslocked;
388 	struct nameidata nd;
389 	struct unpcb *unp;
390 	struct vnode *vp;
391 	struct mount *mp;
392 	char *buf;
393 
394 	unp = sotounpcb(so);
395 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
396 
397 	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
398 	if (namelen <= 0)
399 		return (EINVAL);
400 
401 	/*
402 	 * We don't allow simultaneous bind() calls on a single UNIX domain
403 	 * socket, so flag in-progress operations, and return an error if an
404 	 * operation is already in progress.
405 	 *
406 	 * Historically, we have not allowed a socket to be rebound, so this
407 	 * also returns an error.  Not allowing re-binding simplifies the
408 	 * implementation and avoids a great many possible failure modes.
409 	 */
410 	UNP_PCB_LOCK(unp);
411 	if (unp->unp_vnode != NULL) {
412 		UNP_PCB_UNLOCK(unp);
413 		return (EINVAL);
414 	}
415 	if (unp->unp_flags & UNP_BINDING) {
416 		UNP_PCB_UNLOCK(unp);
417 		return (EALREADY);
418 	}
419 	unp->unp_flags |= UNP_BINDING;
420 	UNP_PCB_UNLOCK(unp);
421 
422 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
423 	bcopy(soun->sun_path, buf, namelen);
424 	buf[namelen] = 0;
425 
426 restart:
427 	vfslocked = 0;
428 	NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
429 	    UIO_SYSSPACE, buf, td);
430 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
431 	error = namei(&nd);
432 	if (error)
433 		goto error;
434 	vp = nd.ni_vp;
435 	vfslocked = NDHASGIANT(&nd);
436 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
437 		NDFREE(&nd, NDF_ONLY_PNBUF);
438 		if (nd.ni_dvp == vp)
439 			vrele(nd.ni_dvp);
440 		else
441 			vput(nd.ni_dvp);
442 		if (vp != NULL) {
443 			vrele(vp);
444 			error = EADDRINUSE;
445 			goto error;
446 		}
447 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
448 		if (error)
449 			goto error;
450 		VFS_UNLOCK_GIANT(vfslocked);
451 		goto restart;
452 	}
453 	VATTR_NULL(&vattr);
454 	vattr.va_type = VSOCK;
455 	vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
456 #ifdef MAC
457 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
458 	    &vattr);
459 #endif
460 	if (error == 0)
461 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
462 	NDFREE(&nd, NDF_ONLY_PNBUF);
463 	vput(nd.ni_dvp);
464 	if (error) {
465 		vn_finished_write(mp);
466 		goto error;
467 	}
468 	vp = nd.ni_vp;
469 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
470 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
471 
472 	UNP_LINK_WLOCK();
473 	UNP_PCB_LOCK(unp);
474 	vp->v_socket = unp->unp_socket;
475 	unp->unp_vnode = vp;
476 	unp->unp_addr = soun;
477 	unp->unp_flags &= ~UNP_BINDING;
478 	UNP_PCB_UNLOCK(unp);
479 	UNP_LINK_WUNLOCK();
480 	VOP_UNLOCK(vp, 0);
481 	vn_finished_write(mp);
482 	VFS_UNLOCK_GIANT(vfslocked);
483 	free(buf, M_TEMP);
484 	return (0);
485 
486 error:
487 	VFS_UNLOCK_GIANT(vfslocked);
488 	UNP_PCB_LOCK(unp);
489 	unp->unp_flags &= ~UNP_BINDING;
490 	UNP_PCB_UNLOCK(unp);
491 	free(buf, M_TEMP);
492 	return (error);
493 }
494 
495 static int
496 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
497 {
498 	int error;
499 
500 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
501 	UNP_LINK_WLOCK();
502 	error = unp_connect(so, nam, td);
503 	UNP_LINK_WUNLOCK();
504 	return (error);
505 }
506 
507 static void
508 uipc_close(struct socket *so)
509 {
510 	struct unpcb *unp, *unp2;
511 
512 	unp = sotounpcb(so);
513 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
514 
515 	UNP_LINK_WLOCK();
516 	UNP_PCB_LOCK(unp);
517 	unp2 = unp->unp_conn;
518 	if (unp2 != NULL) {
519 		UNP_PCB_LOCK(unp2);
520 		unp_disconnect(unp, unp2);
521 		UNP_PCB_UNLOCK(unp2);
522 	}
523 	UNP_PCB_UNLOCK(unp);
524 	UNP_LINK_WUNLOCK();
525 }
526 
527 static int
528 uipc_connect2(struct socket *so1, struct socket *so2)
529 {
530 	struct unpcb *unp, *unp2;
531 	int error;
532 
533 	UNP_LINK_WLOCK();
534 	unp = so1->so_pcb;
535 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
536 	UNP_PCB_LOCK(unp);
537 	unp2 = so2->so_pcb;
538 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
539 	UNP_PCB_LOCK(unp2);
540 	error = unp_connect2(so1, so2, PRU_CONNECT2);
541 	UNP_PCB_UNLOCK(unp2);
542 	UNP_PCB_UNLOCK(unp);
543 	UNP_LINK_WUNLOCK();
544 	return (error);
545 }
546 
547 static void
548 uipc_detach(struct socket *so)
549 {
550 	struct unpcb *unp, *unp2;
551 	struct sockaddr_un *saved_unp_addr;
552 	struct vnode *vp;
553 	int freeunp, local_unp_rights;
554 
555 	unp = sotounpcb(so);
556 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
557 
558 	UNP_LINK_WLOCK();
559 	UNP_LIST_LOCK();
560 	UNP_PCB_LOCK(unp);
561 	LIST_REMOVE(unp, unp_link);
562 	unp->unp_gencnt = ++unp_gencnt;
563 	--unp_count;
564 	UNP_LIST_UNLOCK();
565 
566 	/*
567 	 * XXXRW: Should assert vp->v_socket == so.
568 	 */
569 	if ((vp = unp->unp_vnode) != NULL) {
570 		unp->unp_vnode->v_socket = NULL;
571 		unp->unp_vnode = NULL;
572 	}
573 	unp2 = unp->unp_conn;
574 	if (unp2 != NULL) {
575 		UNP_PCB_LOCK(unp2);
576 		unp_disconnect(unp, unp2);
577 		UNP_PCB_UNLOCK(unp2);
578 	}
579 
580 	/*
581 	 * We hold the linkage lock exclusively, so it's OK to acquire
582 	 * multiple pcb locks at a time.
583 	 */
584 	while (!LIST_EMPTY(&unp->unp_refs)) {
585 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
586 
587 		UNP_PCB_LOCK(ref);
588 		unp_drop(ref, ECONNRESET);
589 		UNP_PCB_UNLOCK(ref);
590 	}
591 	local_unp_rights = unp_rights;
592 	UNP_LINK_WUNLOCK();
593 	unp->unp_socket->so_pcb = NULL;
594 	saved_unp_addr = unp->unp_addr;
595 	unp->unp_addr = NULL;
596 	unp->unp_refcount--;
597 	freeunp = (unp->unp_refcount == 0);
598 	if (saved_unp_addr != NULL)
599 		free(saved_unp_addr, M_SONAME);
600 	if (freeunp) {
601 		UNP_PCB_LOCK_DESTROY(unp);
602 		uma_zfree(unp_zone, unp);
603 	} else
604 		UNP_PCB_UNLOCK(unp);
605 	if (vp) {
606 		int vfslocked;
607 
608 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
609 		vrele(vp);
610 		VFS_UNLOCK_GIANT(vfslocked);
611 	}
612 	if (local_unp_rights)
613 		taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
614 }
615 
616 static int
617 uipc_disconnect(struct socket *so)
618 {
619 	struct unpcb *unp, *unp2;
620 
621 	unp = sotounpcb(so);
622 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
623 
624 	UNP_LINK_WLOCK();
625 	UNP_PCB_LOCK(unp);
626 	unp2 = unp->unp_conn;
627 	if (unp2 != NULL) {
628 		UNP_PCB_LOCK(unp2);
629 		unp_disconnect(unp, unp2);
630 		UNP_PCB_UNLOCK(unp2);
631 	}
632 	UNP_PCB_UNLOCK(unp);
633 	UNP_LINK_WUNLOCK();
634 	return (0);
635 }
636 
637 static int
638 uipc_listen(struct socket *so, int backlog, struct thread *td)
639 {
640 	struct unpcb *unp;
641 	int error;
642 
643 	unp = sotounpcb(so);
644 	KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
645 
646 	UNP_PCB_LOCK(unp);
647 	if (unp->unp_vnode == NULL) {
648 		UNP_PCB_UNLOCK(unp);
649 		return (EINVAL);
650 	}
651 
652 	SOCK_LOCK(so);
653 	error = solisten_proto_check(so);
654 	if (error == 0) {
655 		cru2x(td->td_ucred, &unp->unp_peercred);
656 		unp->unp_flags |= UNP_HAVEPCCACHED;
657 		solisten_proto(so, backlog);
658 	}
659 	SOCK_UNLOCK(so);
660 	UNP_PCB_UNLOCK(unp);
661 	return (error);
662 }
663 
664 static int
665 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
666 {
667 	struct unpcb *unp, *unp2;
668 	const struct sockaddr *sa;
669 
670 	unp = sotounpcb(so);
671 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
672 
673 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
674 	UNP_PCB_LOCK(unp);
675 	/*
676 	 * XXX: It seems that this test always fails even when connection is
677 	 * established.  So, this else clause is added as workaround to
678 	 * return PF_LOCAL sockaddr.
679 	 */
680 	unp2 = unp->unp_conn;
681 	if (unp2 != NULL) {
682 		UNP_PCB_LOCK(unp2);
683 		if (unp2->unp_addr != NULL)
684 			sa = (struct sockaddr *) unp->unp_conn->unp_addr;
685 		else
686 			sa = &sun_noname;
687 		bcopy(sa, *nam, sa->sa_len);
688 		UNP_PCB_UNLOCK(unp2);
689 	} else {
690 		sa = &sun_noname;
691 		bcopy(sa, *nam, sa->sa_len);
692 	}
693 	UNP_PCB_UNLOCK(unp);
694 	return (0);
695 }
696 
697 static int
698 uipc_rcvd(struct socket *so, int flags)
699 {
700 	struct unpcb *unp, *unp2;
701 	struct socket *so2;
702 	u_int mbcnt, sbcc;
703 	u_long newhiwat;
704 
705 	unp = sotounpcb(so);
706 	KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
707 
708 	if (so->so_type == SOCK_DGRAM)
709 		panic("uipc_rcvd DGRAM?");
710 
711 	if (so->so_type != SOCK_STREAM)
712 		panic("uipc_rcvd unknown socktype");
713 
714 	/*
715 	 * Adjust backpressure on sender and wakeup any waiting to write.
716 	 *
717 	 * The unp lock is acquired to maintain the validity of the unp_conn
718 	 * pointer; no lock on unp2 is required as unp2->unp_socket will be
719 	 * static as long as we don't permit unp2 to disconnect from unp,
720 	 * which is prevented by the lock on unp.  We cache values from
721 	 * so_rcv to avoid holding the so_rcv lock over the entire
722 	 * transaction on the remote so_snd.
723 	 */
724 	SOCKBUF_LOCK(&so->so_rcv);
725 	mbcnt = so->so_rcv.sb_mbcnt;
726 	sbcc = so->so_rcv.sb_cc;
727 	SOCKBUF_UNLOCK(&so->so_rcv);
728 	UNP_PCB_LOCK(unp);
729 	unp2 = unp->unp_conn;
730 	if (unp2 == NULL) {
731 		UNP_PCB_UNLOCK(unp);
732 		return (0);
733 	}
734 	so2 = unp2->unp_socket;
735 	SOCKBUF_LOCK(&so2->so_snd);
736 	so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
737 	newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
738 	(void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
739 	    newhiwat, RLIM_INFINITY);
740 	sowwakeup_locked(so2);
741 	unp->unp_mbcnt = mbcnt;
742 	unp->unp_cc = sbcc;
743 	UNP_PCB_UNLOCK(unp);
744 	return (0);
745 }
746 
747 static int
748 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
749     struct mbuf *control, struct thread *td)
750 {
751 	struct unpcb *unp, *unp2;
752 	struct socket *so2;
753 	u_int mbcnt_delta, sbcc;
754 	u_long newhiwat;
755 	int error = 0;
756 
757 	unp = sotounpcb(so);
758 	KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
759 
760 	if (flags & PRUS_OOB) {
761 		error = EOPNOTSUPP;
762 		goto release;
763 	}
764 	if (control != NULL && (error = unp_internalize(&control, td)))
765 		goto release;
766 	if ((nam != NULL) || (flags & PRUS_EOF))
767 		UNP_LINK_WLOCK();
768 	else
769 		UNP_LINK_RLOCK();
770 	switch (so->so_type) {
771 	case SOCK_DGRAM:
772 	{
773 		const struct sockaddr *from;
774 
775 		unp2 = unp->unp_conn;
776 		if (nam != NULL) {
777 			UNP_LINK_WLOCK_ASSERT();
778 			if (unp2 != NULL) {
779 				error = EISCONN;
780 				break;
781 			}
782 			error = unp_connect(so, nam, td);
783 			if (error)
784 				break;
785 			unp2 = unp->unp_conn;
786 		}
787 
788 		/*
789 		 * Because connect() and send() are non-atomic in a sendto()
790 		 * with a target address, it's possible that the socket will
791 		 * have disconnected before the send() can run.  In that case
792 		 * return the slightly counter-intuitive but otherwise
793 		 * correct error that the socket is not connected.
794 		 */
795 		if (unp2 == NULL) {
796 			error = ENOTCONN;
797 			break;
798 		}
799 		/* Lockless read. */
800 		if (unp2->unp_flags & UNP_WANTCRED)
801 			control = unp_addsockcred(td, control);
802 		UNP_PCB_LOCK(unp);
803 		if (unp->unp_addr != NULL)
804 			from = (struct sockaddr *)unp->unp_addr;
805 		else
806 			from = &sun_noname;
807 		so2 = unp2->unp_socket;
808 		SOCKBUF_LOCK(&so2->so_rcv);
809 		if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
810 			sorwakeup_locked(so2);
811 			m = NULL;
812 			control = NULL;
813 		} else {
814 			SOCKBUF_UNLOCK(&so2->so_rcv);
815 			error = ENOBUFS;
816 		}
817 		if (nam != NULL) {
818 			UNP_LINK_WLOCK_ASSERT();
819 			UNP_PCB_LOCK(unp2);
820 			unp_disconnect(unp, unp2);
821 			UNP_PCB_UNLOCK(unp2);
822 		}
823 		UNP_PCB_UNLOCK(unp);
824 		break;
825 	}
826 
827 	case SOCK_STREAM:
828 		if ((so->so_state & SS_ISCONNECTED) == 0) {
829 			if (nam != NULL) {
830 				UNP_LINK_WLOCK_ASSERT();
831 				error = unp_connect(so, nam, td);
832 				if (error)
833 					break;	/* XXX */
834 			} else {
835 				error = ENOTCONN;
836 				break;
837 			}
838 		}
839 
840 		/* Lockless read. */
841 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
842 			error = EPIPE;
843 			break;
844 		}
845 
846 		/*
847 		 * Because connect() and send() are non-atomic in a sendto()
848 		 * with a target address, it's possible that the socket will
849 		 * have disconnected before the send() can run.  In that case
850 		 * return the slightly counter-intuitive but otherwise
851 		 * correct error that the socket is not connected.
852 		 *
853 		 * Locking here must be done carefully: the inkage lock
854 		 * prevents interconnections between unpcbs from changing, so
855 		 * we can traverse from unp to unp2 without acquiring unp's
856 		 * lock.  Socket buffer locks follow unpcb locks, so we can
857 		 * acquire both remote and lock socket buffer locks.
858 		 */
859 		unp2 = unp->unp_conn;
860 		if (unp2 == NULL) {
861 			error = ENOTCONN;
862 			break;
863 		}
864 		so2 = unp2->unp_socket;
865 		UNP_PCB_LOCK(unp2);
866 		SOCKBUF_LOCK(&so2->so_rcv);
867 		if (unp2->unp_flags & UNP_WANTCRED) {
868 			/*
869 			 * Credentials are passed only once on SOCK_STREAM.
870 			 */
871 			unp2->unp_flags &= ~UNP_WANTCRED;
872 			control = unp_addsockcred(td, control);
873 		}
874 		/*
875 		 * Send to paired receive port, and then reduce send buffer
876 		 * hiwater marks to maintain backpressure.  Wake up readers.
877 		 */
878 		if (control != NULL) {
879 			if (sbappendcontrol_locked(&so2->so_rcv, m, control))
880 				control = NULL;
881 		} else
882 			sbappend_locked(&so2->so_rcv, m);
883 		mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
884 		unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
885 		sbcc = so2->so_rcv.sb_cc;
886 		sorwakeup_locked(so2);
887 
888 		SOCKBUF_LOCK(&so->so_snd);
889 		newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
890 		(void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
891 		    newhiwat, RLIM_INFINITY);
892 		so->so_snd.sb_mbmax -= mbcnt_delta;
893 		SOCKBUF_UNLOCK(&so->so_snd);
894 		unp2->unp_cc = sbcc;
895 		UNP_PCB_UNLOCK(unp2);
896 		m = NULL;
897 		break;
898 
899 	default:
900 		panic("uipc_send unknown socktype");
901 	}
902 
903 	/*
904 	 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
905 	 */
906 	if (flags & PRUS_EOF) {
907 		UNP_PCB_LOCK(unp);
908 		socantsendmore(so);
909 		unp_shutdown(unp);
910 		UNP_PCB_UNLOCK(unp);
911 	}
912 
913 	if ((nam != NULL) || (flags & PRUS_EOF))
914 		UNP_LINK_WUNLOCK();
915 	else
916 		UNP_LINK_RUNLOCK();
917 
918 	if (control != NULL && error != 0)
919 		unp_dispose(control);
920 
921 release:
922 	if (control != NULL)
923 		m_freem(control);
924 	if (m != NULL)
925 		m_freem(m);
926 	return (error);
927 }
928 
929 static int
930 uipc_sense(struct socket *so, struct stat *sb)
931 {
932 	struct unpcb *unp, *unp2;
933 	struct socket *so2;
934 
935 	unp = sotounpcb(so);
936 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
937 
938 	sb->st_blksize = so->so_snd.sb_hiwat;
939 	UNP_LINK_RLOCK();
940 	UNP_PCB_LOCK(unp);
941 	unp2 = unp->unp_conn;
942 	if (so->so_type == SOCK_STREAM && unp2 != NULL) {
943 		so2 = unp2->unp_socket;
944 		sb->st_blksize += so2->so_rcv.sb_cc;
945 	}
946 	sb->st_dev = NODEV;
947 	if (unp->unp_ino == 0)
948 		unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
949 	sb->st_ino = unp->unp_ino;
950 	UNP_PCB_UNLOCK(unp);
951 	UNP_LINK_RUNLOCK();
952 	return (0);
953 }
954 
955 static int
956 uipc_shutdown(struct socket *so)
957 {
958 	struct unpcb *unp;
959 
960 	unp = sotounpcb(so);
961 	KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
962 
963 	UNP_LINK_WLOCK();
964 	UNP_PCB_LOCK(unp);
965 	socantsendmore(so);
966 	unp_shutdown(unp);
967 	UNP_PCB_UNLOCK(unp);
968 	UNP_LINK_WUNLOCK();
969 	return (0);
970 }
971 
972 static int
973 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
974 {
975 	struct unpcb *unp;
976 	const struct sockaddr *sa;
977 
978 	unp = sotounpcb(so);
979 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
980 
981 	*nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
982 	UNP_PCB_LOCK(unp);
983 	if (unp->unp_addr != NULL)
984 		sa = (struct sockaddr *) unp->unp_addr;
985 	else
986 		sa = &sun_noname;
987 	bcopy(sa, *nam, sa->sa_len);
988 	UNP_PCB_UNLOCK(unp);
989 	return (0);
990 }
991 
992 static struct pr_usrreqs uipc_usrreqs_dgram = {
993 	.pru_abort = 		uipc_abort,
994 	.pru_accept =		uipc_accept,
995 	.pru_attach =		uipc_attach,
996 	.pru_bind =		uipc_bind,
997 	.pru_connect =		uipc_connect,
998 	.pru_connect2 =		uipc_connect2,
999 	.pru_detach =		uipc_detach,
1000 	.pru_disconnect =	uipc_disconnect,
1001 	.pru_listen =		uipc_listen,
1002 	.pru_peeraddr =		uipc_peeraddr,
1003 	.pru_rcvd =		uipc_rcvd,
1004 	.pru_send =		uipc_send,
1005 	.pru_sense =		uipc_sense,
1006 	.pru_shutdown =		uipc_shutdown,
1007 	.pru_sockaddr =		uipc_sockaddr,
1008 	.pru_soreceive =	soreceive_dgram,
1009 	.pru_close =		uipc_close,
1010 };
1011 
1012 static struct pr_usrreqs uipc_usrreqs_stream = {
1013 	.pru_abort = 		uipc_abort,
1014 	.pru_accept =		uipc_accept,
1015 	.pru_attach =		uipc_attach,
1016 	.pru_bind =		uipc_bind,
1017 	.pru_connect =		uipc_connect,
1018 	.pru_connect2 =		uipc_connect2,
1019 	.pru_detach =		uipc_detach,
1020 	.pru_disconnect =	uipc_disconnect,
1021 	.pru_listen =		uipc_listen,
1022 	.pru_peeraddr =		uipc_peeraddr,
1023 	.pru_rcvd =		uipc_rcvd,
1024 	.pru_send =		uipc_send,
1025 	.pru_sense =		uipc_sense,
1026 	.pru_shutdown =		uipc_shutdown,
1027 	.pru_sockaddr =		uipc_sockaddr,
1028 	.pru_soreceive =	soreceive_generic,
1029 	.pru_close =		uipc_close,
1030 };
1031 
1032 static int
1033 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1034 {
1035 	struct unpcb *unp;
1036 	struct xucred xu;
1037 	int error, optval;
1038 
1039 	if (sopt->sopt_level != 0)
1040 		return (EINVAL);
1041 
1042 	unp = sotounpcb(so);
1043 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1044 	error = 0;
1045 	switch (sopt->sopt_dir) {
1046 	case SOPT_GET:
1047 		switch (sopt->sopt_name) {
1048 		case LOCAL_PEERCRED:
1049 			UNP_PCB_LOCK(unp);
1050 			if (unp->unp_flags & UNP_HAVEPC)
1051 				xu = unp->unp_peercred;
1052 			else {
1053 				if (so->so_type == SOCK_STREAM)
1054 					error = ENOTCONN;
1055 				else
1056 					error = EINVAL;
1057 			}
1058 			UNP_PCB_UNLOCK(unp);
1059 			if (error == 0)
1060 				error = sooptcopyout(sopt, &xu, sizeof(xu));
1061 			break;
1062 
1063 		case LOCAL_CREDS:
1064 			/* Unlocked read. */
1065 			optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1066 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1067 			break;
1068 
1069 		case LOCAL_CONNWAIT:
1070 			/* Unlocked read. */
1071 			optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1072 			error = sooptcopyout(sopt, &optval, sizeof(optval));
1073 			break;
1074 
1075 		default:
1076 			error = EOPNOTSUPP;
1077 			break;
1078 		}
1079 		break;
1080 
1081 	case SOPT_SET:
1082 		switch (sopt->sopt_name) {
1083 		case LOCAL_CREDS:
1084 		case LOCAL_CONNWAIT:
1085 			error = sooptcopyin(sopt, &optval, sizeof(optval),
1086 					    sizeof(optval));
1087 			if (error)
1088 				break;
1089 
1090 #define	OPTSET(bit) do {						\
1091 	UNP_PCB_LOCK(unp);						\
1092 	if (optval)							\
1093 		unp->unp_flags |= bit;					\
1094 	else								\
1095 		unp->unp_flags &= ~bit;					\
1096 	UNP_PCB_UNLOCK(unp);						\
1097 } while (0)
1098 
1099 			switch (sopt->sopt_name) {
1100 			case LOCAL_CREDS:
1101 				OPTSET(UNP_WANTCRED);
1102 				break;
1103 
1104 			case LOCAL_CONNWAIT:
1105 				OPTSET(UNP_CONNWAIT);
1106 				break;
1107 
1108 			default:
1109 				break;
1110 			}
1111 			break;
1112 #undef	OPTSET
1113 		default:
1114 			error = ENOPROTOOPT;
1115 			break;
1116 		}
1117 		break;
1118 
1119 	default:
1120 		error = EOPNOTSUPP;
1121 		break;
1122 	}
1123 	return (error);
1124 }
1125 
1126 static int
1127 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1128 {
1129 	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1130 	struct vnode *vp;
1131 	struct socket *so2, *so3;
1132 	struct unpcb *unp, *unp2, *unp3;
1133 	int error, len, vfslocked;
1134 	struct nameidata nd;
1135 	char buf[SOCK_MAXADDRLEN];
1136 	struct sockaddr *sa;
1137 
1138 	UNP_LINK_WLOCK_ASSERT();
1139 
1140 	unp = sotounpcb(so);
1141 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1142 
1143 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1144 	if (len <= 0)
1145 		return (EINVAL);
1146 	bcopy(soun->sun_path, buf, len);
1147 	buf[len] = 0;
1148 
1149 	UNP_PCB_LOCK(unp);
1150 	if (unp->unp_flags & UNP_CONNECTING) {
1151 		UNP_PCB_UNLOCK(unp);
1152 		return (EALREADY);
1153 	}
1154 	UNP_LINK_WUNLOCK();
1155 	unp->unp_flags |= UNP_CONNECTING;
1156 	UNP_PCB_UNLOCK(unp);
1157 
1158 	sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1159 	NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1160 	    td);
1161 	error = namei(&nd);
1162 	if (error)
1163 		vp = NULL;
1164 	else
1165 		vp = nd.ni_vp;
1166 	ASSERT_VOP_LOCKED(vp, "unp_connect");
1167 	vfslocked = NDHASGIANT(&nd);
1168 	NDFREE(&nd, NDF_ONLY_PNBUF);
1169 	if (error)
1170 		goto bad;
1171 
1172 	if (vp->v_type != VSOCK) {
1173 		error = ENOTSOCK;
1174 		goto bad;
1175 	}
1176 #ifdef MAC
1177 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1178 	if (error)
1179 		goto bad;
1180 #endif
1181 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1182 	if (error)
1183 		goto bad;
1184 	VFS_UNLOCK_GIANT(vfslocked);
1185 
1186 	unp = sotounpcb(so);
1187 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1188 
1189 	/*
1190 	 * Lock linkage lock for two reasons: make sure v_socket is stable,
1191 	 * and to protect simultaneous locking of multiple pcbs.
1192 	 */
1193 	UNP_LINK_WLOCK();
1194 	so2 = vp->v_socket;
1195 	if (so2 == NULL) {
1196 		error = ECONNREFUSED;
1197 		goto bad2;
1198 	}
1199 	if (so->so_type != so2->so_type) {
1200 		error = EPROTOTYPE;
1201 		goto bad2;
1202 	}
1203 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1204 		if (so2->so_options & SO_ACCEPTCONN) {
1205 			so3 = sonewconn(so2, 0);
1206 		} else
1207 			so3 = NULL;
1208 		if (so3 == NULL) {
1209 			error = ECONNREFUSED;
1210 			goto bad2;
1211 		}
1212 		unp = sotounpcb(so);
1213 		unp2 = sotounpcb(so2);
1214 		unp3 = sotounpcb(so3);
1215 		UNP_PCB_LOCK(unp);
1216 		UNP_PCB_LOCK(unp2);
1217 		UNP_PCB_LOCK(unp3);
1218 		if (unp2->unp_addr != NULL) {
1219 			bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1220 			unp3->unp_addr = (struct sockaddr_un *) sa;
1221 			sa = NULL;
1222 		}
1223 
1224 		/*
1225 		 * The connecter's (client's) credentials are copied from its
1226 		 * process structure at the time of connect() (which is now).
1227 		 */
1228 		cru2x(td->td_ucred, &unp3->unp_peercred);
1229 		unp3->unp_flags |= UNP_HAVEPC;
1230 
1231 		/*
1232 		 * The receiver's (server's) credentials are copied from the
1233 		 * unp_peercred member of socket on which the former called
1234 		 * listen(); uipc_listen() cached that process's credentials
1235 		 * at that time so we can use them now.
1236 		 */
1237 		KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1238 		    ("unp_connect: listener without cached peercred"));
1239 		memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1240 		    sizeof(unp->unp_peercred));
1241 		unp->unp_flags |= UNP_HAVEPC;
1242 		if (unp2->unp_flags & UNP_WANTCRED)
1243 			unp3->unp_flags |= UNP_WANTCRED;
1244 		UNP_PCB_UNLOCK(unp3);
1245 		UNP_PCB_UNLOCK(unp2);
1246 		UNP_PCB_UNLOCK(unp);
1247 #ifdef MAC
1248 		SOCK_LOCK(so);
1249 		mac_socketpeer_set_from_socket(so, so3);
1250 		mac_socketpeer_set_from_socket(so3, so);
1251 		SOCK_UNLOCK(so);
1252 #endif
1253 
1254 		so2 = so3;
1255 	}
1256 	unp = sotounpcb(so);
1257 	KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1258 	unp2 = sotounpcb(so2);
1259 	KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1260 	UNP_PCB_LOCK(unp);
1261 	UNP_PCB_LOCK(unp2);
1262 	error = unp_connect2(so, so2, PRU_CONNECT);
1263 	UNP_PCB_UNLOCK(unp2);
1264 	UNP_PCB_UNLOCK(unp);
1265 bad2:
1266 	UNP_LINK_WUNLOCK();
1267 	if (vfslocked)
1268 		/*
1269 		 * Giant has been previously acquired. This means filesystem
1270 		 * isn't MPSAFE.  Do it once again.
1271 		 */
1272 		mtx_lock(&Giant);
1273 bad:
1274 	if (vp != NULL)
1275 		vput(vp);
1276 	VFS_UNLOCK_GIANT(vfslocked);
1277 	free(sa, M_SONAME);
1278 	UNP_LINK_WLOCK();
1279 	UNP_PCB_LOCK(unp);
1280 	unp->unp_flags &= ~UNP_CONNECTING;
1281 	UNP_PCB_UNLOCK(unp);
1282 	return (error);
1283 }
1284 
1285 static int
1286 unp_connect2(struct socket *so, struct socket *so2, int req)
1287 {
1288 	struct unpcb *unp;
1289 	struct unpcb *unp2;
1290 
1291 	unp = sotounpcb(so);
1292 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1293 	unp2 = sotounpcb(so2);
1294 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1295 
1296 	UNP_LINK_WLOCK_ASSERT();
1297 	UNP_PCB_LOCK_ASSERT(unp);
1298 	UNP_PCB_LOCK_ASSERT(unp2);
1299 
1300 	if (so2->so_type != so->so_type)
1301 		return (EPROTOTYPE);
1302 	unp->unp_conn = unp2;
1303 
1304 	switch (so->so_type) {
1305 	case SOCK_DGRAM:
1306 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1307 		soisconnected(so);
1308 		break;
1309 
1310 	case SOCK_STREAM:
1311 		unp2->unp_conn = unp;
1312 		if (req == PRU_CONNECT &&
1313 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1314 			soisconnecting(so);
1315 		else
1316 			soisconnected(so);
1317 		soisconnected(so2);
1318 		break;
1319 
1320 	default:
1321 		panic("unp_connect2");
1322 	}
1323 	return (0);
1324 }
1325 
1326 static void
1327 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1328 {
1329 	struct socket *so;
1330 
1331 	KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1332 
1333 	UNP_LINK_WLOCK_ASSERT();
1334 	UNP_PCB_LOCK_ASSERT(unp);
1335 	UNP_PCB_LOCK_ASSERT(unp2);
1336 
1337 	unp->unp_conn = NULL;
1338 	switch (unp->unp_socket->so_type) {
1339 	case SOCK_DGRAM:
1340 		LIST_REMOVE(unp, unp_reflink);
1341 		so = unp->unp_socket;
1342 		SOCK_LOCK(so);
1343 		so->so_state &= ~SS_ISCONNECTED;
1344 		SOCK_UNLOCK(so);
1345 		break;
1346 
1347 	case SOCK_STREAM:
1348 		soisdisconnected(unp->unp_socket);
1349 		unp2->unp_conn = NULL;
1350 		soisdisconnected(unp2->unp_socket);
1351 		break;
1352 	}
1353 }
1354 
1355 /*
1356  * unp_pcblist() walks the global list of struct unpcb's to generate a
1357  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1358  * sequentially, validating the generation number on each to see if it has
1359  * been detached.  All of this is necessary because copyout() may sleep on
1360  * disk I/O.
1361  */
1362 static int
1363 unp_pcblist(SYSCTL_HANDLER_ARGS)
1364 {
1365 	int error, i, n;
1366 	int freeunp;
1367 	struct unpcb *unp, **unp_list;
1368 	unp_gen_t gencnt;
1369 	struct xunpgen *xug;
1370 	struct unp_head *head;
1371 	struct xunpcb *xu;
1372 
1373 	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1374 
1375 	/*
1376 	 * The process of preparing the PCB list is too time-consuming and
1377 	 * resource-intensive to repeat twice on every request.
1378 	 */
1379 	if (req->oldptr == NULL) {
1380 		n = unp_count;
1381 		req->oldidx = 2 * (sizeof *xug)
1382 			+ (n + n/8) * sizeof(struct xunpcb);
1383 		return (0);
1384 	}
1385 
1386 	if (req->newptr != NULL)
1387 		return (EPERM);
1388 
1389 	/*
1390 	 * OK, now we're committed to doing something.
1391 	 */
1392 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1393 	UNP_LIST_LOCK();
1394 	gencnt = unp_gencnt;
1395 	n = unp_count;
1396 	UNP_LIST_UNLOCK();
1397 
1398 	xug->xug_len = sizeof *xug;
1399 	xug->xug_count = n;
1400 	xug->xug_gen = gencnt;
1401 	xug->xug_sogen = so_gencnt;
1402 	error = SYSCTL_OUT(req, xug, sizeof *xug);
1403 	if (error) {
1404 		free(xug, M_TEMP);
1405 		return (error);
1406 	}
1407 
1408 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1409 
1410 	UNP_LIST_LOCK();
1411 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1412 	     unp = LIST_NEXT(unp, unp_link)) {
1413 		UNP_PCB_LOCK(unp);
1414 		if (unp->unp_gencnt <= gencnt) {
1415 			if (cr_cansee(req->td->td_ucred,
1416 			    unp->unp_socket->so_cred)) {
1417 				UNP_PCB_UNLOCK(unp);
1418 				continue;
1419 			}
1420 			unp_list[i++] = unp;
1421 			unp->unp_refcount++;
1422 		}
1423 		UNP_PCB_UNLOCK(unp);
1424 	}
1425 	UNP_LIST_UNLOCK();
1426 	n = i;			/* In case we lost some during malloc. */
1427 
1428 	error = 0;
1429 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1430 	for (i = 0; i < n; i++) {
1431 		unp = unp_list[i];
1432 		UNP_PCB_LOCK(unp);
1433 		unp->unp_refcount--;
1434 	        if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1435 			xu->xu_len = sizeof *xu;
1436 			xu->xu_unpp = unp;
1437 			/*
1438 			 * XXX - need more locking here to protect against
1439 			 * connect/disconnect races for SMP.
1440 			 */
1441 			if (unp->unp_addr != NULL)
1442 				bcopy(unp->unp_addr, &xu->xu_addr,
1443 				      unp->unp_addr->sun_len);
1444 			if (unp->unp_conn != NULL &&
1445 			    unp->unp_conn->unp_addr != NULL)
1446 				bcopy(unp->unp_conn->unp_addr,
1447 				      &xu->xu_caddr,
1448 				      unp->unp_conn->unp_addr->sun_len);
1449 			bcopy(unp, &xu->xu_unp, sizeof *unp);
1450 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
1451 			UNP_PCB_UNLOCK(unp);
1452 			error = SYSCTL_OUT(req, xu, sizeof *xu);
1453 		} else {
1454 			freeunp = (unp->unp_refcount == 0);
1455 			UNP_PCB_UNLOCK(unp);
1456 			if (freeunp) {
1457 				UNP_PCB_LOCK_DESTROY(unp);
1458 				uma_zfree(unp_zone, unp);
1459 			}
1460 		}
1461 	}
1462 	free(xu, M_TEMP);
1463 	if (!error) {
1464 		/*
1465 		 * Give the user an updated idea of our state.  If the
1466 		 * generation differs from what we told her before, she knows
1467 		 * that something happened while we were processing this
1468 		 * request, and it might be necessary to retry.
1469 		 */
1470 		xug->xug_gen = unp_gencnt;
1471 		xug->xug_sogen = so_gencnt;
1472 		xug->xug_count = unp_count;
1473 		error = SYSCTL_OUT(req, xug, sizeof *xug);
1474 	}
1475 	free(unp_list, M_TEMP);
1476 	free(xug, M_TEMP);
1477 	return (error);
1478 }
1479 
1480 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1481 	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1482 	    "List of active local datagram sockets");
1483 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1484 	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1485 	    "List of active local stream sockets");
1486 
1487 static void
1488 unp_shutdown(struct unpcb *unp)
1489 {
1490 	struct unpcb *unp2;
1491 	struct socket *so;
1492 
1493 	UNP_LINK_WLOCK_ASSERT();
1494 	UNP_PCB_LOCK_ASSERT(unp);
1495 
1496 	unp2 = unp->unp_conn;
1497 	if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1498 		so = unp2->unp_socket;
1499 		if (so != NULL)
1500 			socantrcvmore(so);
1501 	}
1502 }
1503 
1504 static void
1505 unp_drop(struct unpcb *unp, int errno)
1506 {
1507 	struct socket *so = unp->unp_socket;
1508 	struct unpcb *unp2;
1509 
1510 	UNP_LINK_WLOCK_ASSERT();
1511 	UNP_PCB_LOCK_ASSERT(unp);
1512 
1513 	so->so_error = errno;
1514 	unp2 = unp->unp_conn;
1515 	if (unp2 == NULL)
1516 		return;
1517 	UNP_PCB_LOCK(unp2);
1518 	unp_disconnect(unp, unp2);
1519 	UNP_PCB_UNLOCK(unp2);
1520 }
1521 
1522 static void
1523 unp_freerights(struct file **rp, int fdcount)
1524 {
1525 	int i;
1526 	struct file *fp;
1527 
1528 	for (i = 0; i < fdcount; i++) {
1529 		fp = *rp;
1530 		*rp++ = NULL;
1531 		unp_discard(fp);
1532 	}
1533 }
1534 
1535 static int
1536 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1537 {
1538 	struct thread *td = curthread;		/* XXX */
1539 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1540 	int i;
1541 	int *fdp;
1542 	struct file **rp;
1543 	struct file *fp;
1544 	void *data;
1545 	socklen_t clen = control->m_len, datalen;
1546 	int error, newfds;
1547 	int f;
1548 	u_int newlen;
1549 
1550 	UNP_LINK_UNLOCK_ASSERT();
1551 
1552 	error = 0;
1553 	if (controlp != NULL) /* controlp == NULL => free control messages */
1554 		*controlp = NULL;
1555 	while (cm != NULL) {
1556 		if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1557 			error = EINVAL;
1558 			break;
1559 		}
1560 		data = CMSG_DATA(cm);
1561 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1562 		if (cm->cmsg_level == SOL_SOCKET
1563 		    && cm->cmsg_type == SCM_RIGHTS) {
1564 			newfds = datalen / sizeof(struct file *);
1565 			rp = data;
1566 
1567 			/* If we're not outputting the descriptors free them. */
1568 			if (error || controlp == NULL) {
1569 				unp_freerights(rp, newfds);
1570 				goto next;
1571 			}
1572 			FILEDESC_XLOCK(td->td_proc->p_fd);
1573 			/* if the new FD's will not fit free them.  */
1574 			if (!fdavail(td, newfds)) {
1575 				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1576 				error = EMSGSIZE;
1577 				unp_freerights(rp, newfds);
1578 				goto next;
1579 			}
1580 
1581 			/*
1582 			 * Now change each pointer to an fd in the global
1583 			 * table to an integer that is the index to the local
1584 			 * fd table entry that we set up to point to the
1585 			 * global one we are transferring.
1586 			 */
1587 			newlen = newfds * sizeof(int);
1588 			*controlp = sbcreatecontrol(NULL, newlen,
1589 			    SCM_RIGHTS, SOL_SOCKET);
1590 			if (*controlp == NULL) {
1591 				FILEDESC_XUNLOCK(td->td_proc->p_fd);
1592 				error = E2BIG;
1593 				unp_freerights(rp, newfds);
1594 				goto next;
1595 			}
1596 
1597 			fdp = (int *)
1598 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1599 			for (i = 0; i < newfds; i++) {
1600 				if (fdalloc(td, 0, &f))
1601 					panic("unp_externalize fdalloc failed");
1602 				fp = *rp++;
1603 				td->td_proc->p_fd->fd_ofiles[f] = fp;
1604 				unp_externalize_fp(fp);
1605 				*fdp++ = f;
1606 			}
1607 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1608 		} else {
1609 			/* We can just copy anything else across. */
1610 			if (error || controlp == NULL)
1611 				goto next;
1612 			*controlp = sbcreatecontrol(NULL, datalen,
1613 			    cm->cmsg_type, cm->cmsg_level);
1614 			if (*controlp == NULL) {
1615 				error = ENOBUFS;
1616 				goto next;
1617 			}
1618 			bcopy(data,
1619 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1620 			    datalen);
1621 		}
1622 		controlp = &(*controlp)->m_next;
1623 
1624 next:
1625 		if (CMSG_SPACE(datalen) < clen) {
1626 			clen -= CMSG_SPACE(datalen);
1627 			cm = (struct cmsghdr *)
1628 			    ((caddr_t)cm + CMSG_SPACE(datalen));
1629 		} else {
1630 			clen = 0;
1631 			cm = NULL;
1632 		}
1633 	}
1634 
1635 	m_freem(control);
1636 	return (error);
1637 }
1638 
1639 static void
1640 unp_zone_change(void *tag)
1641 {
1642 
1643 	uma_zone_set_max(unp_zone, maxsockets);
1644 }
1645 
1646 static void
1647 unp_init(void)
1648 {
1649 
1650 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1651 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1652 	if (unp_zone == NULL)
1653 		panic("unp_init");
1654 	uma_zone_set_max(unp_zone, maxsockets);
1655 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1656 	    NULL, EVENTHANDLER_PRI_ANY);
1657 	LIST_INIT(&unp_dhead);
1658 	LIST_INIT(&unp_shead);
1659 	TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1660 	UNP_LINK_LOCK_INIT();
1661 	UNP_LIST_LOCK_INIT();
1662 }
1663 
1664 static int
1665 unp_internalize(struct mbuf **controlp, struct thread *td)
1666 {
1667 	struct mbuf *control = *controlp;
1668 	struct proc *p = td->td_proc;
1669 	struct filedesc *fdescp = p->p_fd;
1670 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1671 	struct cmsgcred *cmcred;
1672 	struct file **rp;
1673 	struct file *fp;
1674 	struct timeval *tv;
1675 	int i, fd, *fdp;
1676 	void *data;
1677 	socklen_t clen = control->m_len, datalen;
1678 	int error, oldfds;
1679 	u_int newlen;
1680 
1681 	UNP_LINK_UNLOCK_ASSERT();
1682 
1683 	error = 0;
1684 	*controlp = NULL;
1685 	while (cm != NULL) {
1686 		if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1687 		    || cm->cmsg_len > clen) {
1688 			error = EINVAL;
1689 			goto out;
1690 		}
1691 		data = CMSG_DATA(cm);
1692 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1693 
1694 		switch (cm->cmsg_type) {
1695 		/*
1696 		 * Fill in credential information.
1697 		 */
1698 		case SCM_CREDS:
1699 			*controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1700 			    SCM_CREDS, SOL_SOCKET);
1701 			if (*controlp == NULL) {
1702 				error = ENOBUFS;
1703 				goto out;
1704 			}
1705 			cmcred = (struct cmsgcred *)
1706 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1707 			cmcred->cmcred_pid = p->p_pid;
1708 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1709 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1710 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
1711 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1712 			    CMGROUP_MAX);
1713 			for (i = 0; i < cmcred->cmcred_ngroups; i++)
1714 				cmcred->cmcred_groups[i] =
1715 				    td->td_ucred->cr_groups[i];
1716 			break;
1717 
1718 		case SCM_RIGHTS:
1719 			oldfds = datalen / sizeof (int);
1720 			/*
1721 			 * Check that all the FDs passed in refer to legal
1722 			 * files.  If not, reject the entire operation.
1723 			 */
1724 			fdp = data;
1725 			FILEDESC_SLOCK(fdescp);
1726 			for (i = 0; i < oldfds; i++) {
1727 				fd = *fdp++;
1728 				if ((unsigned)fd >= fdescp->fd_nfiles ||
1729 				    fdescp->fd_ofiles[fd] == NULL) {
1730 					FILEDESC_SUNLOCK(fdescp);
1731 					error = EBADF;
1732 					goto out;
1733 				}
1734 				fp = fdescp->fd_ofiles[fd];
1735 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1736 					FILEDESC_SUNLOCK(fdescp);
1737 					error = EOPNOTSUPP;
1738 					goto out;
1739 				}
1740 
1741 			}
1742 
1743 			/*
1744 			 * Now replace the integer FDs with pointers to the
1745 			 * associated global file table entry..
1746 			 */
1747 			newlen = oldfds * sizeof(struct file *);
1748 			*controlp = sbcreatecontrol(NULL, newlen,
1749 			    SCM_RIGHTS, SOL_SOCKET);
1750 			if (*controlp == NULL) {
1751 				FILEDESC_SUNLOCK(fdescp);
1752 				error = E2BIG;
1753 				goto out;
1754 			}
1755 			fdp = data;
1756 			rp = (struct file **)
1757 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1758 			for (i = 0; i < oldfds; i++) {
1759 				fp = fdescp->fd_ofiles[*fdp++];
1760 				*rp++ = fp;
1761 				unp_internalize_fp(fp);
1762 			}
1763 			FILEDESC_SUNLOCK(fdescp);
1764 			break;
1765 
1766 		case SCM_TIMESTAMP:
1767 			*controlp = sbcreatecontrol(NULL, sizeof(*tv),
1768 			    SCM_TIMESTAMP, SOL_SOCKET);
1769 			if (*controlp == NULL) {
1770 				error = ENOBUFS;
1771 				goto out;
1772 			}
1773 			tv = (struct timeval *)
1774 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1775 			microtime(tv);
1776 			break;
1777 
1778 		default:
1779 			error = EINVAL;
1780 			goto out;
1781 		}
1782 
1783 		controlp = &(*controlp)->m_next;
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 out:
1795 	m_freem(control);
1796 	return (error);
1797 }
1798 
1799 static struct mbuf *
1800 unp_addsockcred(struct thread *td, struct mbuf *control)
1801 {
1802 	struct mbuf *m, *n, *n_prev;
1803 	struct sockcred *sc;
1804 	const struct cmsghdr *cm;
1805 	int ngroups;
1806 	int i;
1807 
1808 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1809 	m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1810 	if (m == NULL)
1811 		return (control);
1812 
1813 	sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1814 	sc->sc_uid = td->td_ucred->cr_ruid;
1815 	sc->sc_euid = td->td_ucred->cr_uid;
1816 	sc->sc_gid = td->td_ucred->cr_rgid;
1817 	sc->sc_egid = td->td_ucred->cr_gid;
1818 	sc->sc_ngroups = ngroups;
1819 	for (i = 0; i < sc->sc_ngroups; i++)
1820 		sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1821 
1822 	/*
1823 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1824 	 * created SCM_CREDS control message (struct sockcred) has another
1825 	 * format.
1826 	 */
1827 	if (control != NULL)
1828 		for (n = control, n_prev = NULL; n != NULL;) {
1829 			cm = mtod(n, struct cmsghdr *);
1830     			if (cm->cmsg_level == SOL_SOCKET &&
1831 			    cm->cmsg_type == SCM_CREDS) {
1832     				if (n_prev == NULL)
1833 					control = n->m_next;
1834 				else
1835 					n_prev->m_next = n->m_next;
1836 				n = m_free(n);
1837 			} else {
1838 				n_prev = n;
1839 				n = n->m_next;
1840 			}
1841 		}
1842 
1843 	/* Prepend it to the head. */
1844 	m->m_next = control;
1845 	return (m);
1846 }
1847 
1848 static struct unpcb *
1849 fptounp(struct file *fp)
1850 {
1851 	struct socket *so;
1852 
1853 	if (fp->f_type != DTYPE_SOCKET)
1854 		return (NULL);
1855 	if ((so = fp->f_data) == NULL)
1856 		return (NULL);
1857 	if (so->so_proto->pr_domain != &localdomain)
1858 		return (NULL);
1859 	return sotounpcb(so);
1860 }
1861 
1862 static void
1863 unp_discard(struct file *fp)
1864 {
1865 
1866 	unp_externalize_fp(fp);
1867 	(void) closef(fp, (struct thread *)NULL);
1868 }
1869 
1870 static void
1871 unp_internalize_fp(struct file *fp)
1872 {
1873 	struct unpcb *unp;
1874 
1875 	UNP_LINK_WLOCK();
1876 	if ((unp = fptounp(fp)) != NULL) {
1877 		unp->unp_file = fp;
1878 		unp->unp_msgcount++;
1879 	}
1880 	fhold(fp);
1881 	unp_rights++;
1882 	UNP_LINK_WUNLOCK();
1883 }
1884 
1885 static void
1886 unp_externalize_fp(struct file *fp)
1887 {
1888 	struct unpcb *unp;
1889 
1890 	UNP_LINK_WLOCK();
1891 	if ((unp = fptounp(fp)) != NULL)
1892 		unp->unp_msgcount--;
1893 	unp_rights--;
1894 	UNP_LINK_WUNLOCK();
1895 }
1896 
1897 /*
1898  * unp_defer indicates whether additional work has been defered for a future
1899  * pass through unp_gc().  It is thread local and does not require explicit
1900  * synchronization.
1901  */
1902 static int	unp_marked;
1903 static int	unp_unreachable;
1904 
1905 static void
1906 unp_accessable(struct file *fp)
1907 {
1908 	struct unpcb *unp;
1909 
1910 	if ((unp = fptounp(fp)) == NULL)
1911 		return;
1912 	if (unp->unp_gcflag & UNPGC_REF)
1913 		return;
1914 	unp->unp_gcflag &= ~UNPGC_DEAD;
1915 	unp->unp_gcflag |= UNPGC_REF;
1916 	unp_marked++;
1917 }
1918 
1919 static void
1920 unp_gc_process(struct unpcb *unp)
1921 {
1922 	struct socket *soa;
1923 	struct socket *so;
1924 	struct file *fp;
1925 
1926 	/* Already processed. */
1927 	if (unp->unp_gcflag & UNPGC_SCANNED)
1928 		return;
1929 	fp = unp->unp_file;
1930 
1931 	/*
1932 	 * Check for a socket potentially in a cycle.  It must be in a
1933 	 * queue as indicated by msgcount, and this must equal the file
1934 	 * reference count.  Note that when msgcount is 0 the file is NULL.
1935 	 */
1936 	if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
1937 	    unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
1938 		unp->unp_gcflag |= UNPGC_DEAD;
1939 		unp_unreachable++;
1940 		return;
1941 	}
1942 
1943 	/*
1944 	 * Mark all sockets we reference with RIGHTS.
1945 	 */
1946 	so = unp->unp_socket;
1947 	SOCKBUF_LOCK(&so->so_rcv);
1948 	unp_scan(so->so_rcv.sb_mb, unp_accessable);
1949 	SOCKBUF_UNLOCK(&so->so_rcv);
1950 
1951 	/*
1952 	 * Mark all sockets in our accept queue.
1953 	 */
1954 	ACCEPT_LOCK();
1955 	TAILQ_FOREACH(soa, &so->so_comp, so_list) {
1956 		SOCKBUF_LOCK(&soa->so_rcv);
1957 		unp_scan(soa->so_rcv.sb_mb, unp_accessable);
1958 		SOCKBUF_UNLOCK(&soa->so_rcv);
1959 	}
1960 	ACCEPT_UNLOCK();
1961 	unp->unp_gcflag |= UNPGC_SCANNED;
1962 }
1963 
1964 static int unp_recycled;
1965 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
1966     "Number of unreachable sockets claimed by the garbage collector.");
1967 
1968 static int unp_taskcount;
1969 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
1970     "Number of times the garbage collector has run.");
1971 
1972 static void
1973 unp_gc(__unused void *arg, int pending)
1974 {
1975 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
1976 	struct unp_head **head;
1977 	struct file **unref;
1978 	struct unpcb *unp;
1979 	int i;
1980 
1981 	unp_taskcount++;
1982 	UNP_LIST_LOCK();
1983 	/*
1984 	 * First clear all gc flags from previous runs.
1985 	 */
1986 	for (head = heads; *head != NULL; head++)
1987 		LIST_FOREACH(unp, *head, unp_link)
1988 			unp->unp_gcflag = 0;
1989 
1990 	/*
1991 	 * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
1992 	 * is reachable all of the sockets it references are reachable.
1993 	 * Stop the scan once we do a complete loop without discovering
1994 	 * a new reachable socket.
1995 	 */
1996 	do {
1997 		unp_unreachable = 0;
1998 		unp_marked = 0;
1999 		for (head = heads; *head != NULL; head++)
2000 			LIST_FOREACH(unp, *head, unp_link)
2001 				unp_gc_process(unp);
2002 	} while (unp_marked);
2003 	UNP_LIST_UNLOCK();
2004 	if (unp_unreachable == 0)
2005 		return;
2006 
2007 	/*
2008 	 * Allocate space for a local list of dead unpcbs.
2009 	 */
2010 	unref = malloc(unp_unreachable * sizeof(struct file *),
2011 	    M_TEMP, M_WAITOK);
2012 
2013 	/*
2014 	 * Iterate looking for sockets which have been specifically marked
2015 	 * as as unreachable and store them locally.
2016 	 */
2017 	UNP_LIST_LOCK();
2018 	for (i = 0, head = heads; *head != NULL; head++)
2019 		LIST_FOREACH(unp, *head, unp_link)
2020 			if (unp->unp_gcflag & UNPGC_DEAD) {
2021 				unref[i++] = unp->unp_file;
2022 				fhold(unp->unp_file);
2023 				KASSERT(unp->unp_file != NULL,
2024 				    ("unp_gc: Invalid unpcb."));
2025 				KASSERT(i <= unp_unreachable,
2026 				    ("unp_gc: incorrect unreachable count."));
2027 			}
2028 	UNP_LIST_UNLOCK();
2029 
2030 	/*
2031 	 * Now flush all sockets, free'ing rights.  This will free the
2032 	 * struct files associated with these sockets but leave each socket
2033 	 * with one remaining ref.
2034 	 */
2035 	for (i = 0; i < unp_unreachable; i++)
2036 		sorflush(unref[i]->f_data);
2037 
2038 	/*
2039 	 * And finally release the sockets so they can be reclaimed.
2040 	 */
2041 	for (i = 0; i < unp_unreachable; i++)
2042 		fdrop(unref[i], NULL);
2043 	unp_recycled += unp_unreachable;
2044 	free(unref, M_TEMP);
2045 }
2046 
2047 static void
2048 unp_dispose(struct mbuf *m)
2049 {
2050 
2051 	if (m)
2052 		unp_scan(m, unp_discard);
2053 }
2054 
2055 static void
2056 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2057 {
2058 	struct mbuf *m;
2059 	struct file **rp;
2060 	struct cmsghdr *cm;
2061 	void *data;
2062 	int i;
2063 	socklen_t clen, datalen;
2064 	int qfds;
2065 
2066 	while (m0 != NULL) {
2067 		for (m = m0; m; m = m->m_next) {
2068 			if (m->m_type != MT_CONTROL)
2069 				continue;
2070 
2071 			cm = mtod(m, struct cmsghdr *);
2072 			clen = m->m_len;
2073 
2074 			while (cm != NULL) {
2075 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2076 					break;
2077 
2078 				data = CMSG_DATA(cm);
2079 				datalen = (caddr_t)cm + cm->cmsg_len
2080 				    - (caddr_t)data;
2081 
2082 				if (cm->cmsg_level == SOL_SOCKET &&
2083 				    cm->cmsg_type == SCM_RIGHTS) {
2084 					qfds = datalen / sizeof (struct file *);
2085 					rp = data;
2086 					for (i = 0; i < qfds; i++)
2087 						(*op)(*rp++);
2088 				}
2089 
2090 				if (CMSG_SPACE(datalen) < clen) {
2091 					clen -= CMSG_SPACE(datalen);
2092 					cm = (struct cmsghdr *)
2093 					    ((caddr_t)cm + CMSG_SPACE(datalen));
2094 				} else {
2095 					clen = 0;
2096 					cm = NULL;
2097 				}
2098 			}
2099 		}
2100 		m0 = m0->m_act;
2101 	}
2102 }
2103 
2104 #ifdef DDB
2105 static void
2106 db_print_indent(int indent)
2107 {
2108 	int i;
2109 
2110 	for (i = 0; i < indent; i++)
2111 		db_printf(" ");
2112 }
2113 
2114 static void
2115 db_print_unpflags(int unp_flags)
2116 {
2117 	int comma;
2118 
2119 	comma = 0;
2120 	if (unp_flags & UNP_HAVEPC) {
2121 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2122 		comma = 1;
2123 	}
2124 	if (unp_flags & UNP_HAVEPCCACHED) {
2125 		db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2126 		comma = 1;
2127 	}
2128 	if (unp_flags & UNP_WANTCRED) {
2129 		db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2130 		comma = 1;
2131 	}
2132 	if (unp_flags & UNP_CONNWAIT) {
2133 		db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2134 		comma = 1;
2135 	}
2136 	if (unp_flags & UNP_CONNECTING) {
2137 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2138 		comma = 1;
2139 	}
2140 	if (unp_flags & UNP_BINDING) {
2141 		db_printf("%sUNP_BINDING", comma ? ", " : "");
2142 		comma = 1;
2143 	}
2144 }
2145 
2146 static void
2147 db_print_xucred(int indent, struct xucred *xu)
2148 {
2149 	int comma, i;
2150 
2151 	db_print_indent(indent);
2152 	db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2153 	    xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2154 	db_print_indent(indent);
2155 	db_printf("cr_groups: ");
2156 	comma = 0;
2157 	for (i = 0; i < xu->cr_ngroups; i++) {
2158 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2159 		comma = 1;
2160 	}
2161 	db_printf("\n");
2162 }
2163 
2164 static void
2165 db_print_unprefs(int indent, struct unp_head *uh)
2166 {
2167 	struct unpcb *unp;
2168 	int counter;
2169 
2170 	counter = 0;
2171 	LIST_FOREACH(unp, uh, unp_reflink) {
2172 		if (counter % 4 == 0)
2173 			db_print_indent(indent);
2174 		db_printf("%p  ", unp);
2175 		if (counter % 4 == 3)
2176 			db_printf("\n");
2177 		counter++;
2178 	}
2179 	if (counter != 0 && counter % 4 != 0)
2180 		db_printf("\n");
2181 }
2182 
2183 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2184 {
2185 	struct unpcb *unp;
2186 
2187         if (!have_addr) {
2188                 db_printf("usage: show unpcb <addr>\n");
2189                 return;
2190         }
2191         unp = (struct unpcb *)addr;
2192 
2193 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2194 	    unp->unp_vnode);
2195 
2196 	db_printf("unp_ino: %d   unp_conn: %p\n", unp->unp_ino,
2197 	    unp->unp_conn);
2198 
2199 	db_printf("unp_refs:\n");
2200 	db_print_unprefs(2, &unp->unp_refs);
2201 
2202 	/* XXXRW: Would be nice to print the full address, if any. */
2203 	db_printf("unp_addr: %p\n", unp->unp_addr);
2204 
2205 	db_printf("unp_cc: %d   unp_mbcnt: %d   unp_gencnt: %llu\n",
2206 	    unp->unp_cc, unp->unp_mbcnt,
2207 	    (unsigned long long)unp->unp_gencnt);
2208 
2209 	db_printf("unp_flags: %x (", unp->unp_flags);
2210 	db_print_unpflags(unp->unp_flags);
2211 	db_printf(")\n");
2212 
2213 	db_printf("unp_peercred:\n");
2214 	db_print_xucred(2, &unp->unp_peercred);
2215 
2216 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
2217 }
2218 #endif
2219