xref: /freebsd/sys/kern/uipc_usrreq.c (revision 44b83210c8ad21e907de61584cfeb2752abee19b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California. All Rights Reserved.
6  * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7  * Copyright (c) 2018 Matthew Macy
8  * Copyright (c) 2022-2025 Gleb Smirnoff <glebius@FreeBSD.org>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * UNIX Domain (Local) Sockets
37  *
38  * This is an implementation of UNIX (local) domain sockets.  Each socket has
39  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
40  * may be connected to 0 or 1 other socket.  Datagram sockets may be
41  * connected to 0, 1, or many other sockets.  Sockets may be created and
42  * connected in pairs (socketpair(2)), or bound/connected to using the file
43  * system name space.  For most purposes, only the receive socket buffer is
44  * used, as sending on one socket delivers directly to the receive socket
45  * buffer of a second socket.
46  *
47  * The implementation is substantially complicated by the fact that
48  * "ancillary data", such as file descriptors or credentials, may be passed
49  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
50  * over other UNIX domain sockets requires the implementation of a simple
51  * garbage collector to find and tear down cycles of disconnected sockets.
52  *
53  * TODO:
54  *	RDM
55  *	rethink name space problems
56  *	need a proper out-of-band
57  */
58 
59 #include "opt_ddb.h"
60 
61 #include <sys/param.h>
62 #include <sys/capsicum.h>
63 #include <sys/domain.h>
64 #include <sys/eventhandler.h>
65 #include <sys/fcntl.h>
66 #include <sys/file.h>
67 #include <sys/filedesc.h>
68 #include <sys/jail.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
76 #include <sys/poll.h>
77 #include <sys/proc.h>
78 #include <sys/protosw.h>
79 #include <sys/queue.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/sysent.h>
87 #include <sys/sx.h>
88 #include <sys/sysctl.h>
89 #include <sys/systm.h>
90 #include <sys/taskqueue.h>
91 #include <sys/un.h>
92 #include <sys/unpcb.h>
93 #include <sys/vnode.h>
94 
95 #include <net/vnet.h>
96 
97 #ifdef DDB
98 #include <ddb/ddb.h>
99 #endif
100 
101 #include <security/mac/mac_framework.h>
102 
103 #include <vm/uma.h>
104 
105 MALLOC_DECLARE(M_FILECAPS);
106 
107 static struct domain localdomain;
108 
109 static uma_zone_t	unp_zone;
110 static unp_gen_t	unp_gencnt;	/* (l) */
111 static u_int		unp_count;	/* (l) Count of local sockets. */
112 static ino_t		unp_ino;	/* Prototype for fake inode numbers. */
113 static int		unp_rights;	/* (g) File descriptors in flight. */
114 static struct unp_head	unp_shead;	/* (l) List of stream sockets. */
115 static struct unp_head	unp_dhead;	/* (l) List of datagram sockets. */
116 static struct unp_head	unp_sphead;	/* (l) List of seqpacket sockets. */
117 static struct mtx_pool	*unp_vp_mtxpool;
118 
119 struct unp_defer {
120 	SLIST_ENTRY(unp_defer) ud_link;
121 	struct file *ud_fp;
122 };
123 static SLIST_HEAD(, unp_defer) unp_defers;
124 static int unp_defers_count;
125 
126 static const struct sockaddr	sun_noname = {
127 	.sa_len = sizeof(sun_noname),
128 	.sa_family = AF_LOCAL,
129 };
130 
131 /*
132  * Garbage collection of cyclic file descriptor/socket references occurs
133  * asynchronously in a taskqueue context in order to avoid recursion and
134  * reentrance in the UNIX domain socket, file descriptor, and socket layer
135  * code.  See unp_gc() for a full description.
136  */
137 static struct timeout_task unp_gc_task;
138 
139 /*
140  * The close of unix domain sockets attached as SCM_RIGHTS is
141  * postponed to the taskqueue, to avoid arbitrary recursion depth.
142  * The attached sockets might have another sockets attached.
143  */
144 static struct task	unp_defer_task;
145 
146 /*
147  * SOCK_STREAM and SOCK_SEQPACKET unix(4) sockets fully bypass the send buffer,
148  * however the notion of send buffer still makes sense with them.  Its size is
149  * the amount of space that a send(2) syscall may copyin(9) before checking
150  * with the receive buffer of a peer.  Although not linked anywhere yet,
151  * pointed to by a stack variable, effectively it is a buffer that needs to be
152  * sized.
153  *
154  * SOCK_DGRAM sockets really use the sendspace as the maximum datagram size,
155  * and don't really want to reserve the sendspace.  Their recvspace should be
156  * large enough for at least one max-size datagram plus address.
157  */
158 static u_long	unpst_sendspace = 64*1024;
159 static u_long	unpst_recvspace = 64*1024;
160 static u_long	unpdg_maxdgram = 8*1024;	/* support 8KB syslog msgs */
161 static u_long	unpdg_recvspace = 16*1024;
162 static u_long	unpsp_sendspace = 64*1024;
163 static u_long	unpsp_recvspace = 64*1024;
164 
165 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
166     "Local domain");
167 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
168     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
169     "SOCK_STREAM");
170 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
171     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172     "SOCK_DGRAM");
173 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
174     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
175     "SOCK_SEQPACKET");
176 
177 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
178 	   &unpst_sendspace, 0, "Default stream send space.");
179 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
180 	   &unpst_recvspace, 0, "Default stream receive space.");
181 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
182 	   &unpdg_maxdgram, 0, "Maximum datagram size.");
183 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
184 	   &unpdg_recvspace, 0, "Default datagram receive space.");
185 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
186 	   &unpsp_sendspace, 0, "Default seqpacket send space.");
187 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
188 	   &unpsp_recvspace, 0, "Default seqpacket receive space.");
189 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
190     "File descriptors in flight.");
191 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
192     &unp_defers_count, 0,
193     "File descriptors deferred to taskqueue for close.");
194 
195 /*
196  * Locking and synchronization:
197  *
198  * Several types of locks exist in the local domain socket implementation:
199  * - a global linkage lock
200  * - a global connection list lock
201  * - the mtxpool lock
202  * - per-unpcb mutexes
203  *
204  * The linkage lock protects the global socket lists, the generation number
205  * counter and garbage collector state.
206  *
207  * The connection list lock protects the list of referring sockets in a datagram
208  * socket PCB.  This lock is also overloaded to protect a global list of
209  * sockets whose buffers contain socket references in the form of SCM_RIGHTS
210  * messages.  To avoid recursion, such references are released by a dedicated
211  * thread.
212  *
213  * The mtxpool lock protects the vnode from being modified while referenced.
214  * Lock ordering rules require that it be acquired before any PCB locks.
215  *
216  * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
217  * unpcb.  This includes the unp_conn field, which either links two connected
218  * PCBs together (for connected socket types) or points at the destination
219  * socket (for connectionless socket types).  The operations of creating or
220  * destroying a connection therefore involve locking multiple PCBs.  To avoid
221  * lock order reversals, in some cases this involves dropping a PCB lock and
222  * using a reference counter to maintain liveness.
223  *
224  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
225  * allocated in pr_attach() and freed in pr_detach().  The validity of that
226  * pointer is an invariant, so no lock is required to dereference the so_pcb
227  * pointer if a valid socket reference is held by the caller.  In practice,
228  * this is always true during operations performed on a socket.  Each unpcb
229  * has a back-pointer to its socket, unp_socket, which will be stable under
230  * the same circumstances.
231  *
232  * This pointer may only be safely dereferenced as long as a valid reference
233  * to the unpcb is held.  Typically, this reference will be from the socket,
234  * or from another unpcb when the referring unpcb's lock is held (in order
235  * that the reference not be invalidated during use).  For example, to follow
236  * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
237  * that detach is not run clearing unp_socket.
238  *
239  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
240  * protocols, bind() is a non-atomic operation, and connect() requires
241  * potential sleeping in the protocol, due to potentially waiting on local or
242  * distributed file systems.  We try to separate "lookup" operations, which
243  * may sleep, and the IPC operations themselves, which typically can occur
244  * with relative atomicity as locks can be held over the entire operation.
245  *
246  * Another tricky issue is simultaneous multi-threaded or multi-process
247  * access to a single UNIX domain socket.  These are handled by the flags
248  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
249  * binding, both of which involve dropping UNIX domain socket locks in order
250  * to perform namei() and other file system operations.
251  */
252 static struct rwlock	unp_link_rwlock;
253 static struct mtx	unp_defers_lock;
254 
255 #define	UNP_LINK_LOCK_INIT()		rw_init(&unp_link_rwlock,	\
256 					    "unp_link_rwlock")
257 
258 #define	UNP_LINK_LOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
259 					    RA_LOCKED)
260 #define	UNP_LINK_UNLOCK_ASSERT()	rw_assert(&unp_link_rwlock,	\
261 					    RA_UNLOCKED)
262 
263 #define	UNP_LINK_RLOCK()		rw_rlock(&unp_link_rwlock)
264 #define	UNP_LINK_RUNLOCK()		rw_runlock(&unp_link_rwlock)
265 #define	UNP_LINK_WLOCK()		rw_wlock(&unp_link_rwlock)
266 #define	UNP_LINK_WUNLOCK()		rw_wunlock(&unp_link_rwlock)
267 #define	UNP_LINK_WLOCK_ASSERT()		rw_assert(&unp_link_rwlock,	\
268 					    RA_WLOCKED)
269 #define	UNP_LINK_WOWNED()		rw_wowned(&unp_link_rwlock)
270 
271 #define	UNP_DEFERRED_LOCK_INIT()	mtx_init(&unp_defers_lock, \
272 					    "unp_defer", NULL, MTX_DEF)
273 #define	UNP_DEFERRED_LOCK()		mtx_lock(&unp_defers_lock)
274 #define	UNP_DEFERRED_UNLOCK()		mtx_unlock(&unp_defers_lock)
275 
276 #define UNP_REF_LIST_LOCK()		UNP_DEFERRED_LOCK();
277 #define UNP_REF_LIST_UNLOCK()		UNP_DEFERRED_UNLOCK();
278 
279 #define UNP_PCB_LOCK_INIT(unp)		mtx_init(&(unp)->unp_mtx,	\
280 					    "unp", "unp",	\
281 					    MTX_DUPOK|MTX_DEF)
282 #define	UNP_PCB_LOCK_DESTROY(unp)	mtx_destroy(&(unp)->unp_mtx)
283 #define	UNP_PCB_LOCKPTR(unp)		(&(unp)->unp_mtx)
284 #define	UNP_PCB_LOCK(unp)		mtx_lock(&(unp)->unp_mtx)
285 #define	UNP_PCB_TRYLOCK(unp)		mtx_trylock(&(unp)->unp_mtx)
286 #define	UNP_PCB_UNLOCK(unp)		mtx_unlock(&(unp)->unp_mtx)
287 #define	UNP_PCB_OWNED(unp)		mtx_owned(&(unp)->unp_mtx)
288 #define	UNP_PCB_LOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_OWNED)
289 #define	UNP_PCB_UNLOCK_ASSERT(unp)	mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
290 
291 static int	uipc_connect2(struct socket *, struct socket *);
292 static int	uipc_ctloutput(struct socket *, struct sockopt *);
293 static int	unp_connectat(int, struct socket *, const char *, int,
294 		    struct thread *, struct socket **);
295 static int	unp_connect_peer(struct socket *, struct unpcb *,
296 		    struct sockaddr **, struct thread *, bool);
297 static int	unp_connectat_peer(struct thread *, int, const char *,
298 		    struct socket **, struct mtx **, struct vnode **);
299 static int	unp_vnode_peer(struct vnode *, struct thread *,
300 		    struct socket **, struct mtx **, struct vnode **);
301 static void	unp_connect2(struct socket *, struct socket *, bool);
302 static void	unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
303 static void	unp_dispose(struct socket *so);
304 static void	unp_drop(struct unpcb *);
305 static void	unp_gc(__unused void *, int);
306 static void	unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
307 static void	unp_discard(struct file *);
308 static void	unp_freerights(struct filedescent **, int);
309 static int	unp_internalize(struct mbuf *, struct mchain *,
310 		    struct thread *, int *);
311 static void	unp_internalize_fp(struct file *);
312 static int	unp_externalize(const struct socket *, struct mbuf *,
313 		    struct mbuf **, int);
314 static int	unp_externalize_fp(struct file *);
315 static void	unp_addsockcred(struct thread *, struct mchain *, int);
316 static void	unp_process_defers(void * __unused, int);
317 
318 static void	uipc_wrknl_lock(void *);
319 static void	uipc_wrknl_unlock(void *);
320 static void	uipc_wrknl_assert_lock(void *, int);
321 
322 static void
unp_pcb_hold(struct unpcb * unp)323 unp_pcb_hold(struct unpcb *unp)
324 {
325 	u_int old __unused;
326 
327 	old = refcount_acquire(&unp->unp_refcount);
328 	KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
329 }
330 
331 static __result_use_check bool
unp_pcb_rele(struct unpcb * unp)332 unp_pcb_rele(struct unpcb *unp)
333 {
334 	bool ret;
335 
336 	UNP_PCB_LOCK_ASSERT(unp);
337 
338 	if ((ret = refcount_release(&unp->unp_refcount))) {
339 		UNP_PCB_UNLOCK(unp);
340 		UNP_PCB_LOCK_DESTROY(unp);
341 		uma_zfree(unp_zone, unp);
342 	}
343 	return (ret);
344 }
345 
346 static void
unp_pcb_rele_notlast(struct unpcb * unp)347 unp_pcb_rele_notlast(struct unpcb *unp)
348 {
349 	bool ret __unused;
350 
351 	ret = refcount_release(&unp->unp_refcount);
352 	KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
353 }
354 
355 static void
unp_pcb_lock_pair(struct unpcb * unp,struct unpcb * unp2)356 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
357 {
358 	UNP_PCB_UNLOCK_ASSERT(unp);
359 	UNP_PCB_UNLOCK_ASSERT(unp2);
360 
361 	if (unp == unp2) {
362 		UNP_PCB_LOCK(unp);
363 	} else if ((uintptr_t)unp2 > (uintptr_t)unp) {
364 		UNP_PCB_LOCK(unp);
365 		UNP_PCB_LOCK(unp2);
366 	} else {
367 		UNP_PCB_LOCK(unp2);
368 		UNP_PCB_LOCK(unp);
369 	}
370 }
371 
372 static void
unp_pcb_unlock_pair(struct unpcb * unp,struct unpcb * unp2)373 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
374 {
375 	UNP_PCB_UNLOCK(unp);
376 	if (unp != unp2)
377 		UNP_PCB_UNLOCK(unp2);
378 }
379 
380 /*
381  * Try to lock the connected peer of an already locked socket.  In some cases
382  * this requires that we unlock the current socket.  The pairbusy counter is
383  * used to block concurrent connection attempts while the lock is dropped.  The
384  * caller must be careful to revalidate PCB state.
385  */
386 static struct unpcb *
unp_pcb_lock_peer(struct unpcb * unp)387 unp_pcb_lock_peer(struct unpcb *unp)
388 {
389 	struct unpcb *unp2;
390 
391 	UNP_PCB_LOCK_ASSERT(unp);
392 	unp2 = unp->unp_conn;
393 	if (unp2 == NULL)
394 		return (NULL);
395 	if (__predict_false(unp == unp2))
396 		return (unp);
397 
398 	UNP_PCB_UNLOCK_ASSERT(unp2);
399 
400 	if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
401 		return (unp2);
402 	if ((uintptr_t)unp2 > (uintptr_t)unp) {
403 		UNP_PCB_LOCK(unp2);
404 		return (unp2);
405 	}
406 	unp->unp_pairbusy++;
407 	unp_pcb_hold(unp2);
408 	UNP_PCB_UNLOCK(unp);
409 
410 	UNP_PCB_LOCK(unp2);
411 	UNP_PCB_LOCK(unp);
412 	KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
413 	    ("%s: socket %p was reconnected", __func__, unp));
414 	if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
415 		unp->unp_flags &= ~UNP_WAITING;
416 		wakeup(unp);
417 	}
418 	if (unp_pcb_rele(unp2)) {
419 		/* unp2 is unlocked. */
420 		return (NULL);
421 	}
422 	if (unp->unp_conn == NULL) {
423 		UNP_PCB_UNLOCK(unp2);
424 		return (NULL);
425 	}
426 	return (unp2);
427 }
428 
429 /*
430  * Try to lock peer of our socket for purposes of sending data to it.
431  */
432 static int
uipc_lock_peer(struct socket * so,struct unpcb ** unp2)433 uipc_lock_peer(struct socket *so, struct unpcb **unp2)
434 {
435 	struct unpcb *unp;
436 	int error;
437 
438 	unp = sotounpcb(so);
439 	UNP_PCB_LOCK(unp);
440 	*unp2 = unp_pcb_lock_peer(unp);
441 	if (__predict_false(so->so_error != 0)) {
442 		error = so->so_error;
443 		so->so_error = 0;
444 		UNP_PCB_UNLOCK(unp);
445 		if (*unp2 != NULL)
446 			UNP_PCB_UNLOCK(*unp2);
447 		return (error);
448 	}
449 	if (__predict_false(*unp2 == NULL)) {
450 		/*
451 		 * Different error code for a previously connected socket and
452 		 * a never connected one.  The SS_ISDISCONNECTED is set in the
453 		 * unp_soisdisconnected() and is synchronized by the pcb lock.
454 		 */
455 		error = so->so_state & SS_ISDISCONNECTED ? EPIPE : ENOTCONN;
456 		UNP_PCB_UNLOCK(unp);
457 		return (error);
458 	}
459 	UNP_PCB_UNLOCK(unp);
460 
461 	return (0);
462 }
463 
464 static void
uipc_abort(struct socket * so)465 uipc_abort(struct socket *so)
466 {
467 	struct unpcb *unp, *unp2;
468 
469 	unp = sotounpcb(so);
470 	KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
471 	UNP_PCB_UNLOCK_ASSERT(unp);
472 
473 	UNP_PCB_LOCK(unp);
474 	unp2 = unp->unp_conn;
475 	if (unp2 != NULL) {
476 		unp_pcb_hold(unp2);
477 		UNP_PCB_UNLOCK(unp);
478 		unp_drop(unp2);
479 	} else
480 		UNP_PCB_UNLOCK(unp);
481 }
482 
483 static int
uipc_attach(struct socket * so,int proto,struct thread * td)484 uipc_attach(struct socket *so, int proto, struct thread *td)
485 {
486 	u_long sendspace, recvspace;
487 	struct unpcb *unp;
488 	int error, rcvmtxopts;
489 	bool locked;
490 
491 	KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
492 	switch (so->so_type) {
493 	case SOCK_DGRAM:
494 		STAILQ_INIT(&so->so_rcv.uxdg_mb);
495 		STAILQ_INIT(&so->so_snd.uxdg_mb);
496 		TAILQ_INIT(&so->so_rcv.uxdg_conns);
497 		/*
498 		 * Since send buffer is either bypassed or is a part
499 		 * of one-to-many receive buffer, we assign both space
500 		 * limits to unpdg_recvspace.
501 		 */
502 		sendspace = recvspace = unpdg_recvspace;
503 		rcvmtxopts = 0;
504 		break;
505 
506 	case SOCK_STREAM:
507 		sendspace = unpst_sendspace;
508 		recvspace = unpst_recvspace;
509 		goto common;
510 
511 	case SOCK_SEQPACKET:
512 		sendspace = unpsp_sendspace;
513 		recvspace = unpsp_recvspace;
514 common:
515 		rcvmtxopts = MTX_DUPOK;
516 		knlist_init(&so->so_wrsel.si_note, so, uipc_wrknl_lock,
517 		    uipc_wrknl_unlock, uipc_wrknl_assert_lock);
518 		STAILQ_INIT(&so->so_rcv.uxst_mbq);
519 		break;
520 	default:
521 		panic("uipc_attach");
522 	}
523 	mtx_init(&so->so_rcv_mtx, "unix so_rcv", NULL, MTX_DEF | rcvmtxopts);
524 	mtx_init(&so->so_snd_mtx, "unix so_snd", NULL, MTX_DEF);
525 	error = soreserve(so, sendspace, recvspace);
526 	if (error)
527 		return (error);
528 	unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
529 	if (unp == NULL)
530 		return (ENOBUFS);
531 	LIST_INIT(&unp->unp_refs);
532 	UNP_PCB_LOCK_INIT(unp);
533 	unp->unp_socket = so;
534 	so->so_pcb = unp;
535 	so->so_options |= SO_PASSRIGHTS;
536 	refcount_init(&unp->unp_refcount, 1);
537 	unp->unp_mode = ACCESSPERMS;
538 
539 	if ((locked = UNP_LINK_WOWNED()) == false)
540 		UNP_LINK_WLOCK();
541 
542 	unp->unp_gencnt = ++unp_gencnt;
543 	unp->unp_ino = ++unp_ino;
544 	unp_count++;
545 	switch (so->so_type) {
546 	case SOCK_STREAM:
547 		LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
548 		break;
549 
550 	case SOCK_DGRAM:
551 		LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
552 		break;
553 
554 	case SOCK_SEQPACKET:
555 		LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
556 		break;
557 
558 	default:
559 		panic("uipc_attach");
560 	}
561 
562 	if (locked == false)
563 		UNP_LINK_WUNLOCK();
564 
565 	return (0);
566 }
567 
568 /*
569  * Validate a bind/connect address as AF_UNIX and hand back its sun_path
570  * and the path length.
571  *
572  * Rejects a wrong family (EAFNOSUPPORT) or a malformed sa_len (EINVAL).
573  */
574 static int
unp_sun_path(const struct sockaddr * nam,const char ** pathp,int * lenp)575 unp_sun_path(const struct sockaddr *nam, const char **pathp, int *lenp)
576 {
577 	const struct sockaddr_un *soun;
578 	int len;
579 
580 	if (nam->sa_family != AF_UNIX)
581 		return (EAFNOSUPPORT);
582 	if (nam->sa_len > sizeof(struct sockaddr_un))
583 		return (EINVAL);
584 	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
585 	if (len < 0)
586 		return (EINVAL);
587 	soun = (const struct sockaddr_un *)nam;
588 	*pathp = soun->sun_path;
589 	*lenp = len;
590 	return (0);
591 }
592 
593 static int
uipc_bindat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td)594 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
595 {
596 	struct sockaddr_un *soun;
597 	struct vattr vattr;
598 	int error, namelen;
599 	struct nameidata nd;
600 	struct unpcb *unp;
601 	struct vnode *vp;
602 	struct mount *mp;
603 	cap_rights_t rights;
604 	const char *path;
605 	char *buf;
606 	mode_t mode;
607 
608 	error = unp_sun_path(nam, &path, &namelen);
609 	if (error != 0)
610 		return (error);
611 	if (namelen == 0)
612 		return (EINVAL);
613 
614 	unp = sotounpcb(so);
615 	KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
616 
617 	/*
618 	 * We don't allow simultaneous bind() calls on a single UNIX domain
619 	 * socket, so flag in-progress operations, and return an error if an
620 	 * operation is already in progress.
621 	 *
622 	 * Historically, we have not allowed a socket to be rebound, so this
623 	 * also returns an error.  Not allowing re-binding simplifies the
624 	 * implementation and avoids a great many possible failure modes.
625 	 */
626 	UNP_PCB_LOCK(unp);
627 	if (unp->unp_vnode != NULL) {
628 		UNP_PCB_UNLOCK(unp);
629 		return (EINVAL);
630 	}
631 	if (unp->unp_flags & UNP_BINDING) {
632 		UNP_PCB_UNLOCK(unp);
633 		return (EALREADY);
634 	}
635 	unp->unp_flags |= UNP_BINDING;
636 	mode = unp->unp_mode & ~td->td_proc->p_pd->pd_cmask;
637 	UNP_PCB_UNLOCK(unp);
638 
639 	buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
640 	bcopy(path, buf, namelen);
641 	buf[namelen] = 0;
642 
643 restart:
644 	NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
645 	    UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
646 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
647 	error = namei(&nd);
648 	if (error)
649 		goto error;
650 	vp = nd.ni_vp;
651 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
652 		NDFREE_PNBUF(&nd);
653 		if (nd.ni_dvp == vp)
654 			vrele(nd.ni_dvp);
655 		else
656 			vput(nd.ni_dvp);
657 		if (vp != NULL) {
658 			vrele(vp);
659 			error = EADDRINUSE;
660 			goto error;
661 		}
662 		error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
663 		if (error)
664 			goto error;
665 		goto restart;
666 	}
667 	VATTR_NULL(&vattr);
668 	vattr.va_type = VSOCK;
669 	vattr.va_mode = mode;
670 #ifdef MAC
671 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
672 	    &vattr);
673 #endif
674 	if (error == 0) {
675 		/*
676 		 * The prior lookup may have left LK_SHARED in cn_lkflags,
677 		 * and VOP_CREATE technically only requires the new vnode to
678 		 * be locked shared. Most filesystems will return the new vnode
679 		 * locked exclusive regardless, but we should explicitly
680 		 * specify that here since we require it and assert to that
681 		 * effect below.
682 		 */
683 		nd.ni_cnd.cn_lkflags = (nd.ni_cnd.cn_lkflags & ~LK_SHARED) |
684 		    LK_EXCLUSIVE;
685 		error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
686 	}
687 	NDFREE_PNBUF(&nd);
688 	if (error) {
689 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
690 		vn_finished_write(mp);
691 		if (error == ERELOOKUP)
692 			goto restart;
693 		goto error;
694 	}
695 	vp = nd.ni_vp;
696 	ASSERT_VOP_ELOCKED(vp, "uipc_bind");
697 	soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
698 
699 	UNP_PCB_LOCK(unp);
700 	VOP_UNP_BIND(vp, unp);
701 	unp->unp_vnode = vp;
702 	unp->unp_addr = soun;
703 	unp->unp_flags &= ~UNP_BINDING;
704 	UNP_PCB_UNLOCK(unp);
705 	vref(vp);
706 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
707 	vn_finished_write(mp);
708 	free(buf, M_TEMP);
709 	return (0);
710 
711 error:
712 	UNP_PCB_LOCK(unp);
713 	unp->unp_flags &= ~UNP_BINDING;
714 	UNP_PCB_UNLOCK(unp);
715 	free(buf, M_TEMP);
716 	return (error);
717 }
718 
719 static int
uipc_bind(struct socket * so,struct sockaddr * nam,struct thread * td)720 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
721 {
722 
723 	return (uipc_bindat(AT_FDCWD, so, nam, td));
724 }
725 
726 static int
uipc_connect(struct socket * so,struct sockaddr * nam,struct thread * td)727 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
728 {
729 	const char *path;
730 	int error, len;
731 
732 	KASSERT(td == curthread, ("uipc_connect: td != curthread"));
733 
734 	error = unp_sun_path(nam, &path, &len);
735 	if (error != 0)
736 		return (error);
737 	/*
738 	 * unp_connectat() does not early exit on empty paths, because that is
739 	 * explicitly supported when naming the peer by file descriptor, but
740 	 * connect(2) only ever passes AT_FDCWD, so reject it here. This
741 	 * preserves historical behavior.
742 	 */
743 	if (len == 0)
744 		return (EINVAL);
745 	return (unp_connectat(AT_FDCWD, so, path, len, td, NULL));
746 }
747 
748 static int
uipc_connectat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td)749 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
750     struct thread *td)
751 {
752 	const char *path;
753 	int error, len;
754 
755 	KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
756 
757 	error = unp_sun_path(nam, &path, &len);
758 	if (error != 0)
759 		return (error);
760 	return (unp_connectat(fd, so, path, len, td, NULL));
761 }
762 
763 static void
uipc_close(struct socket * so)764 uipc_close(struct socket *so)
765 {
766 	struct unpcb *unp, *unp2;
767 	struct vnode *vp = NULL;
768 	struct mtx *vplock;
769 
770 	unp = sotounpcb(so);
771 	KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
772 
773 	vplock = NULL;
774 	if ((vp = unp->unp_vnode) != NULL) {
775 		vplock = mtx_pool_find(unp_vp_mtxpool, vp);
776 		mtx_lock(vplock);
777 	}
778 	UNP_PCB_LOCK(unp);
779 	if (vp && unp->unp_vnode == NULL) {
780 		mtx_unlock(vplock);
781 		vp = NULL;
782 	}
783 	if (vp != NULL) {
784 		VOP_UNP_DETACH(vp);
785 		unp->unp_vnode = NULL;
786 	}
787 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
788 		unp_disconnect(unp, unp2);
789 	else
790 		UNP_PCB_UNLOCK(unp);
791 	if (vp) {
792 		mtx_unlock(vplock);
793 		vrele(vp);
794 	}
795 }
796 
797 static int
uipc_chmod(struct socket * so,mode_t mode,struct ucred * cred __unused,struct thread * td __unused)798 uipc_chmod(struct socket *so, mode_t mode, struct ucred *cred __unused,
799     struct thread *td __unused)
800 {
801 	struct unpcb *unp;
802 	int error;
803 
804 	if ((mode & ~ACCESSPERMS) != 0)
805 		return (EINVAL);
806 
807 	error = 0;
808 	unp = sotounpcb(so);
809 	UNP_PCB_LOCK(unp);
810 	if (unp->unp_vnode != NULL || (unp->unp_flags & UNP_BINDING) != 0)
811 		error = EINVAL;
812 	else
813 		unp->unp_mode = mode;
814 	UNP_PCB_UNLOCK(unp);
815 	return (error);
816 }
817 
818 static int
uipc_connect2(struct socket * so1,struct socket * so2)819 uipc_connect2(struct socket *so1, struct socket *so2)
820 {
821 	struct unpcb *unp, *unp2;
822 
823 	if (so1->so_type != so2->so_type)
824 		return (EPROTOTYPE);
825 
826 	unp = so1->so_pcb;
827 	KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
828 	unp2 = so2->so_pcb;
829 	KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
830 	unp_pcb_lock_pair(unp, unp2);
831 	unp_connect2(so1, so2, false);
832 	unp_pcb_unlock_pair(unp, unp2);
833 
834 	return (0);
835 }
836 
837 static void
maybe_schedule_gc(void)838 maybe_schedule_gc(void)
839 {
840 	if (atomic_load_int(&unp_rights) != 0)
841 		taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
842 }
843 
844 static void
uipc_detach(struct socket * so)845 uipc_detach(struct socket *so)
846 {
847 	struct unpcb *unp, *unp2;
848 
849 	unp = sotounpcb(so);
850 	KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
851 
852 	if (!SOLISTENING(so))
853 		unp_dispose(so);
854 
855 	UNP_LINK_WLOCK();
856 	LIST_REMOVE(unp, unp_link);
857 	if (unp->unp_gcflag & UNPGC_DEAD)
858 		LIST_REMOVE(unp, unp_dead);
859 	unp->unp_gencnt = ++unp_gencnt;
860 	--unp_count;
861 	UNP_LINK_WUNLOCK();
862 
863 	UNP_PCB_LOCK(unp);
864 	KASSERT(unp->unp_vnode == NULL,
865 	    ("%s: unp %p has vnode", __func__, unp));
866 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
867 		unp_disconnect(unp, unp2);
868 	else
869 		UNP_PCB_UNLOCK(unp);
870 
871 	UNP_REF_LIST_LOCK();
872 	while (!LIST_EMPTY(&unp->unp_refs)) {
873 		struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
874 
875 		unp_pcb_hold(ref);
876 		UNP_REF_LIST_UNLOCK();
877 
878 		MPASS(ref != unp);
879 		UNP_PCB_UNLOCK_ASSERT(ref);
880 		unp_drop(ref);
881 		UNP_REF_LIST_LOCK();
882 	}
883 	UNP_REF_LIST_UNLOCK();
884 
885 	UNP_PCB_LOCK(unp);
886 	unp->unp_socket->so_pcb = NULL;
887 	unp->unp_socket = NULL;
888 	free(unp->unp_addr, M_SONAME);
889 	unp->unp_addr = NULL;
890 	if (!unp_pcb_rele(unp))
891 		UNP_PCB_UNLOCK(unp);
892 
893 	maybe_schedule_gc();
894 
895 	switch (so->so_type) {
896 	case SOCK_STREAM:
897 	case SOCK_SEQPACKET:
898 		MPASS(SOLISTENING(so) || (STAILQ_EMPTY(&so->so_rcv.uxst_mbq) &&
899 		    so->so_rcv.uxst_peer == NULL));
900 		break;
901 	case SOCK_DGRAM:
902 		/*
903 		 * Everything should have been unlinked/freed by unp_dispose()
904 		 * and/or unp_disconnect().
905 		 */
906 		MPASS(so->so_rcv.uxdg_peeked == NULL);
907 		MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
908 		MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
909 		MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
910 	}
911 
912 	mtx_destroy(&so->so_snd_mtx);
913 	mtx_destroy(&so->so_rcv_mtx);
914 }
915 
916 static int
uipc_disconnect(struct socket * so)917 uipc_disconnect(struct socket *so)
918 {
919 	struct unpcb *unp, *unp2;
920 
921 	unp = sotounpcb(so);
922 	KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
923 
924 	UNP_PCB_LOCK(unp);
925 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
926 		unp_disconnect(unp, unp2);
927 	else
928 		UNP_PCB_UNLOCK(unp);
929 	return (0);
930 }
931 
932 static void
uipc_fdclose(struct socket * so __unused)933 uipc_fdclose(struct socket *so __unused)
934 {
935 	/*
936 	 * Ensure that userspace can't create orphaned file descriptors without
937 	 * triggering garbage collection.  Triggering GC from uipc_detach() is
938 	 * not sufficient, since that's only closed once a socket reference
939 	 * count drops to zero.
940 	 */
941 	maybe_schedule_gc();
942 }
943 
944 static int
uipc_listen(struct socket * so,int backlog,struct thread * td)945 uipc_listen(struct socket *so, int backlog, struct thread *td)
946 {
947 	struct unpcb *unp;
948 	int error;
949 
950 	MPASS(so->so_type != SOCK_DGRAM);
951 
952 	/*
953 	 * Synchronize with concurrent connection attempts.
954 	 *
955 	 * An unbound socket may listen: connectat(2) can name it by descriptor,
956 	 * so it is reachable without a pathname.  It may also be bound
957 	 * afterwards, which lets a listener be published only once it is ready
958 	 * to accept, rather than leaving a window where the pathname exists but
959 	 * connections are refused.
960 	 */
961 	error = 0;
962 	unp = sotounpcb(so);
963 	UNP_PCB_LOCK(unp);
964 	if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
965 		error = EINVAL;
966 	if (error != 0) {
967 		UNP_PCB_UNLOCK(unp);
968 		return (error);
969 	}
970 
971 	SOCK_LOCK(so);
972 	error = solisten_proto_check(so);
973 	if (error == 0) {
974 		cru2xt(td, &unp->unp_peercred);
975 		if (!SOLISTENING(so)) {
976 			(void)chgsbsize(so->so_cred->cr_uidinfo,
977 			    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
978 			(void)chgsbsize(so->so_cred->cr_uidinfo,
979 			    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
980 		}
981 		solisten_proto(so, backlog);
982 	}
983 	SOCK_UNLOCK(so);
984 	UNP_PCB_UNLOCK(unp);
985 	return (error);
986 }
987 
988 static int
uipc_peeraddr(struct socket * so,struct sockaddr * ret)989 uipc_peeraddr(struct socket *so, struct sockaddr *ret)
990 {
991 	struct unpcb *unp, *unp2;
992 	const struct sockaddr *sa;
993 
994 	unp = sotounpcb(so);
995 	KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
996 
997 	UNP_PCB_LOCK(unp);
998 	unp2 = unp_pcb_lock_peer(unp);
999 	if (unp2 != NULL) {
1000 		if (unp2->unp_addr != NULL)
1001 			sa = (struct sockaddr *)unp2->unp_addr;
1002 		else
1003 			sa = &sun_noname;
1004 		bcopy(sa, ret, sa->sa_len);
1005 		unp_pcb_unlock_pair(unp, unp2);
1006 	} else {
1007 		UNP_PCB_UNLOCK(unp);
1008 		sa = &sun_noname;
1009 		bcopy(sa, ret, sa->sa_len);
1010 	}
1011 	return (0);
1012 }
1013 
1014 /*
1015  * pr_sosend() called with mbuf instead of uio is a kernel thread.  NFS,
1016  * netgraph(4) and other subsystems can call into socket code.  The
1017  * function will condition the mbuf so that it can be safely put onto socket
1018  * buffer and calculate its char count and mbuf count.
1019  *
1020  * Note: we don't support receiving control data from a kernel thread.  Our
1021  * pr_sosend methods have MPASS() to check that.  This may change.
1022  */
1023 static void
uipc_reset_kernel_mbuf(struct mbuf * m,struct mchain * mc)1024 uipc_reset_kernel_mbuf(struct mbuf *m, struct mchain *mc)
1025 {
1026 
1027 	M_ASSERTPKTHDR(m);
1028 
1029 	m_clrprotoflags(m);
1030 	m_tag_delete_chain(m, NULL);
1031 	m->m_pkthdr.rcvif = NULL;
1032 	m->m_pkthdr.flowid = 0;
1033 	m->m_pkthdr.csum_flags = 0;
1034 	m->m_pkthdr.fibnum = 0;
1035 	m->m_pkthdr.rsstype = 0;
1036 
1037 	mc_init_m(mc, m);
1038 	MPASS(m->m_pkthdr.len == mc->mc_len);
1039 }
1040 
1041 #ifdef SOCKBUF_DEBUG
1042 static inline void
uipc_stream_sbcheck(struct sockbuf * sb)1043 uipc_stream_sbcheck(struct sockbuf *sb)
1044 {
1045 	struct mbuf *d;
1046 	u_int dacc, dccc, dctl, dmbcnt;
1047 	bool notready = false;
1048 
1049 	dacc = dccc = dctl = dmbcnt = 0;
1050 	STAILQ_FOREACH(d, &sb->uxst_mbq, m_stailq) {
1051 		if (d == sb->uxst_fnrdy) {
1052 			MPASS(d->m_flags & M_NOTREADY);
1053 			notready = true;
1054 		}
1055 		if (d->m_type == MT_CONTROL)
1056 			dctl += d->m_len;
1057 		else if (d->m_type == MT_DATA) {
1058 			dccc +=  d->m_len;
1059 			if (!notready)
1060 				dacc += d->m_len;
1061 		} else
1062 			MPASS(0);
1063 		dmbcnt += MSIZE;
1064 		if (d->m_flags & M_EXT)
1065 			dmbcnt += d->m_ext.ext_size;
1066 		if (d->m_stailq.stqe_next == NULL)
1067 			MPASS(sb->uxst_mbq.stqh_last == &d->m_stailq.stqe_next);
1068 	}
1069 	MPASS(sb->uxst_fnrdy == NULL || notready);
1070 	MPASS(dacc == sb->sb_acc);
1071 	MPASS(dccc == sb->sb_ccc);
1072 	MPASS(dctl == sb->sb_ctl);
1073 	MPASS(dmbcnt == sb->sb_mbcnt);
1074 	(void)STAILQ_EMPTY(&sb->uxst_mbq);
1075 }
1076 #define	UIPC_STREAM_SBCHECK(sb)	uipc_stream_sbcheck(sb)
1077 #else
1078 #define	UIPC_STREAM_SBCHECK(sb)	do {} while (0)
1079 #endif
1080 
1081 /*
1082  * uipc_stream_sbspace() returns how much a writer can send, limited by char
1083  * count or mbuf memory use, whatever ends first.
1084  *
1085  * An obvious and legitimate reason for a socket having more data than allowed,
1086  * is lowering the limit with setsockopt(SO_RCVBUF) on already full buffer.
1087  * Also, sb_mbcnt may overcommit sb_mbmax in case if previous write observed
1088  * 'space < mbspace', but mchain allocated to hold 'space' bytes of data ended
1089  * up with 'mc_mlen > mbspace'.  A typical scenario would be a full buffer with
1090  * writer trying to push in a large write, and a slow reader, that reads just
1091  * a few bytes at a time.  In that case writer will keep creating new mbufs
1092  * with mc_split().  These mbufs will carry little chars, but will all point at
1093  * the same cluster, thus each adding cluster size to sb_mbcnt.  This means we
1094  * will count same cluster many times potentially underutilizing socket buffer.
1095  * We aren't optimizing towards ineffective readers.  Classic socket buffer had
1096  * the same "feature".
1097  */
1098 static inline u_int
uipc_stream_sbspace(struct sockbuf * sb)1099 uipc_stream_sbspace(struct sockbuf *sb)
1100 {
1101 	u_int space, mbspace;
1102 
1103 	if (__predict_true(sb->sb_hiwat >= sb->sb_ccc + sb->sb_ctl))
1104 		space = sb->sb_hiwat - sb->sb_ccc - sb->sb_ctl;
1105 	else
1106 		return (0);
1107 	if (__predict_true(sb->sb_mbmax >= sb->sb_mbcnt))
1108 		mbspace = sb->sb_mbmax - sb->sb_mbcnt;
1109 	else
1110 		return (0);
1111 
1112 	return (min(space, mbspace));
1113 }
1114 
1115 /*
1116  * UNIX version of generic sbwait() for writes.  We wait on peer's receive
1117  * buffer, using our timeout.
1118  */
1119 static int
uipc_stream_sbwait(struct socket * so,sbintime_t timeo)1120 uipc_stream_sbwait(struct socket *so, sbintime_t timeo)
1121 {
1122 	struct sockbuf *sb = &so->so_rcv;
1123 
1124 	SOCK_RECVBUF_LOCK_ASSERT(so);
1125 	sb->sb_flags |= SB_WAIT;
1126 	return (msleep_sbt(&sb->sb_acc, SOCK_RECVBUF_MTX(so), PSOCK | PCATCH,
1127 	    "sbwait", timeo, 0, 0));
1128 }
1129 
1130 static int
uipc_sosend_stream_or_seqpacket(struct socket * so,struct sockaddr * addr,struct uio * uio0,struct mbuf * m,struct mbuf * c,int flags,struct thread * td)1131 uipc_sosend_stream_or_seqpacket(struct socket *so, struct sockaddr *addr,
1132     struct uio *uio0, struct mbuf *m, struct mbuf *c, int flags,
1133     struct thread *td)
1134 {
1135 	struct unpcb *unp2;
1136 	struct socket *so2;
1137 	struct sockbuf *sb;
1138 	struct uio *uio;
1139 	struct mchain mc, cmc;
1140 	size_t resid, sent;
1141 	bool nonblock, eor, aio;
1142 	int error, needsopts;
1143 
1144 	MPASS((uio0 != NULL && m == NULL) || (m != NULL && uio0 == NULL));
1145 	MPASS(m == NULL || c == NULL);
1146 
1147 	if (__predict_false(flags & MSG_OOB))
1148 		return (EOPNOTSUPP);
1149 
1150 	nonblock = (so->so_state & SS_NBIO) ||
1151 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
1152 	eor = flags & MSG_EOR;
1153 
1154 	mc = MCHAIN_INITIALIZER(&mc);
1155 	cmc = MCHAIN_INITIALIZER(&cmc);
1156 	sent = 0;
1157 	aio = false;
1158 	needsopts = 0;
1159 
1160 	if (m == NULL) {
1161 		if (c != NULL &&
1162 		    (error = unp_internalize(c, &cmc, td, &needsopts)))
1163 			goto out;
1164 		/*
1165 		 * This function may read more data from the uio than it would
1166 		 * then place on socket.  That would leave uio inconsistent
1167 		 * upon return.  Normally uio is allocated on the stack of the
1168 		 * syscall thread and we don't care about leaving it consistent.
1169 		 * However, aio(9) will allocate a uio as part of job and will
1170 		 * use it to track progress.  We detect aio(9) checking the
1171 		 * SB_AIO_RUNNING flag.  It is safe to check it without lock
1172 		 * cause it is set and cleared in the same taskqueue thread.
1173 		 *
1174 		 * This check can also produce a false positive: there is
1175 		 * aio(9) job and also there is a syscall we are serving now.
1176 		 * No sane software does that, it would leave to a mess in
1177 		 * the socket buffer, as aio(9) doesn't grab the I/O sx(9).
1178 		 * But syzkaller can create this mess.  For such false positive
1179 		 * our goal is just don't panic or leak memory.
1180 		 */
1181 		if (__predict_false(so->so_snd.sb_flags & SB_AIO_RUNNING)) {
1182 			uio = cloneuio(uio0);
1183 			aio = true;
1184 		} else {
1185 			uio = uio0;
1186 			resid = uio->uio_resid;
1187 		}
1188 		/*
1189 		 * Optimization for a case when our send fits into the receive
1190 		 * buffer - do the copyin before taking any locks, sized to our
1191 		 * send buffer.  Later copyins will also take into account
1192 		 * space in the peer's receive buffer.
1193 		 */
1194 		error = mc_uiotomc(&mc, uio, so->so_snd.sb_hiwat, 0, M_WAITOK,
1195 		    eor ? M_EOR : 0);
1196 		if (__predict_false(error))
1197 			goto out2;
1198 	} else {
1199 		uio = NULL;
1200 		uipc_reset_kernel_mbuf(m, &mc);
1201 	}
1202 
1203 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1204 	if (error)
1205 		goto out2;
1206 
1207 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
1208 		goto out3;
1209 
1210 	/* Check for SO_PASS* flags */
1211 	so2 = unp2->unp_socket;
1212 	if ((atomic_load_int(&so2->so_options) & needsopts) != needsopts) {
1213 		error = EPERM;
1214 		UNP_PCB_UNLOCK(unp2);
1215 		goto out3;
1216 	}
1217 
1218 	if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1219 		/*
1220 		 * Credentials are passed only once on SOCK_STREAM and
1221 		 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1222 		 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1223 		 */
1224 		unp_addsockcred(td, &cmc, unp2->unp_flags);
1225 		unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1226 	}
1227 
1228 	/*
1229 	 * Cycle through the data to send and available space in the peer's
1230 	 * receive buffer.  Put a reference on the peer socket, so that it
1231 	 * doesn't get freed while we sbwait().  If peer goes away, we will
1232 	 * observe the SBS_CANTRCVMORE and our sorele() will finalize peer's
1233 	 * socket destruction.
1234 	 */
1235 	soref(so2);
1236 	UNP_PCB_UNLOCK(unp2);
1237 	sb = &so2->so_rcv;
1238 	while (mc.mc_len + cmc.mc_len > 0) {
1239 		struct mchain mcnext = MCHAIN_INITIALIZER(&mcnext);
1240 		u_int space;
1241 
1242 		SOCK_RECVBUF_LOCK(so2);
1243 restart:
1244 		UIPC_STREAM_SBCHECK(sb);
1245 		if (__predict_false(cmc.mc_len > sb->sb_hiwat)) {
1246 			SOCK_RECVBUF_UNLOCK(so2);
1247 			error = EMSGSIZE;
1248 			goto out4;
1249 		}
1250 		if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) {
1251 			SOCK_RECVBUF_UNLOCK(so2);
1252 			error = EPIPE;
1253 			goto out4;
1254 		}
1255 		/*
1256 		 * Wait on the peer socket receive buffer until we have enough
1257 		 * space to put at least control.  The data is a stream and can
1258 		 * be put partially, but control is really a datagram.
1259 		 */
1260 		space = uipc_stream_sbspace(sb);
1261 		if (space < sb->sb_lowat || space < cmc.mc_len) {
1262 			if (nonblock) {
1263 				if (aio)
1264 					sb->uxst_flags |= UXST_PEER_AIO;
1265 				SOCK_RECVBUF_UNLOCK(so2);
1266 				if (aio) {
1267 					SOCK_SENDBUF_LOCK(so);
1268 					so->so_snd.sb_ccc =
1269 					    so->so_snd.sb_hiwat - space;
1270 					SOCK_SENDBUF_UNLOCK(so);
1271 				}
1272 				error = EWOULDBLOCK;
1273 				goto out4;
1274 			}
1275 			if ((error = uipc_stream_sbwait(so2,
1276 			    so->so_snd.sb_timeo)) != 0) {
1277 				SOCK_RECVBUF_UNLOCK(so2);
1278 				goto out4;
1279 			} else
1280 				goto restart;
1281 		}
1282 		MPASS(space >= cmc.mc_len);
1283 		space -= cmc.mc_len;
1284 		if (space == 0) {
1285 			/* There is space only to send control. */
1286 			MPASS(!STAILQ_EMPTY(&cmc.mc_q));
1287 			mc_init(&mcnext);
1288 			mc_concat(&mcnext, &mc);
1289 		} else if (space < mc.mc_len) {
1290 			/* Not enough space. */
1291 			if (__predict_false(mc_split(&mc, &mcnext, space,
1292 			    M_NOWAIT) == ENOMEM)) {
1293 				/*
1294 				 * If allocation failed use M_WAITOK and merge
1295 				 * the chain back.  Next time mc_split() will
1296 				 * easily split at the same place.  Only if we
1297 				 * race with setsockopt(SO_RCVBUF) shrinking
1298 				 * sb_hiwat can this happen more than once.
1299 				 */
1300 				SOCK_RECVBUF_UNLOCK(so2);
1301 				(void)mc_split(&mc, &mcnext, space, M_WAITOK);
1302 				mc_concat(&mc, &mcnext);
1303 				SOCK_RECVBUF_LOCK(so2);
1304 				goto restart;
1305 			}
1306 			MPASS(mc.mc_len == space);
1307 		}
1308 		if (!STAILQ_EMPTY(&cmc.mc_q)) {
1309 			STAILQ_CONCAT(&sb->uxst_mbq, &cmc.mc_q);
1310 			sb->sb_ctl += cmc.mc_len;
1311 			sb->sb_mbcnt += cmc.mc_mlen;
1312 			cmc.mc_len = 0;
1313 		}
1314 		sent += mc.mc_len;
1315 		if (sb->uxst_fnrdy == NULL)
1316 			sb->sb_acc += mc.mc_len;
1317 		sb->sb_ccc += mc.mc_len;
1318 		sb->sb_mbcnt += mc.mc_mlen;
1319 		STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q);
1320 		UIPC_STREAM_SBCHECK(sb);
1321 		space = uipc_stream_sbspace(sb);
1322 		sorwakeup_locked(so2);
1323 		if (!STAILQ_EMPTY(&mcnext.mc_q)) {
1324 			/*
1325 			 * Such assignment is unsafe in general, but it is
1326 			 * safe with !STAILQ_EMPTY(&mcnext.mc_q).  In C++ we
1327 			 * could reload = for STAILQs :)
1328 			 */
1329 			mc = mcnext;
1330 		} else if (uio != NULL && uio->uio_resid > 0) {
1331 			/*
1332 			 * Copyin sum of peer's receive buffer space and our
1333 			 * sb_hiwat, which is our virtual send buffer size.
1334 			 * See comment above unpst_sendspace declaration.
1335 			 * We are reading sb_hiwat locklessly, cause a) we
1336 			 * don't care about an application that does send(2)
1337 			 * and setsockopt(2) racing internally, and for an
1338 			 * application that does this in sequence we will see
1339 			 * the correct value cause sbsetopt() uses buffer lock
1340 			 * and we also have already acquired it at least once.
1341 			 */
1342 			error = mc_uiotomc(&mc, uio, space +
1343 			    atomic_load_int(&so->so_snd.sb_hiwat), 0, M_WAITOK,
1344 			    eor ? M_EOR : 0);
1345 			if (__predict_false(error))
1346 				goto out4;
1347 		} else
1348 			mc = MCHAIN_INITIALIZER(&mc);
1349 	}
1350 
1351 	MPASS(STAILQ_EMPTY(&mc.mc_q));
1352 
1353 	td->td_ru.ru_msgsnd++;
1354 out4:
1355 	sorele(so2);
1356 out3:
1357 	SOCK_IO_SEND_UNLOCK(so);
1358 out2:
1359 	if (aio) {
1360 		freeuio(uio);
1361 		uioadvance(uio0, sent);
1362 	} else if (uio != NULL)
1363 		uio->uio_resid = resid - sent;
1364 	if (!mc_empty(&cmc))
1365 		unp_scan(mc_first(&cmc), unp_freerights);
1366 out:
1367 	mc_freem(&mc);
1368 	mc_freem(&cmc);
1369 
1370 	return (error);
1371 }
1372 
1373 /*
1374  * Wakeup a writer, used by recv(2) and shutdown(2).
1375  *
1376  * @param so	Points to a connected stream socket with receive buffer locked
1377  *
1378  * In a blocking mode peer is sleeping on our receive buffer, and we need just
1379  * wakeup(9) on it.  But to wake up various event engines, we need to reach
1380  * over to peer's selinfo.  This can be safely done as the socket buffer
1381  * receive lock is protecting us from the peer going away.
1382  */
1383 static void
uipc_wakeup_writer(struct socket * so)1384 uipc_wakeup_writer(struct socket *so)
1385 {
1386 	struct sockbuf *sb = &so->so_rcv;
1387 	struct selinfo *sel;
1388 
1389 	SOCK_RECVBUF_LOCK_ASSERT(so);
1390 	MPASS(sb->uxst_peer != NULL);
1391 
1392 	sel = &sb->uxst_peer->so_wrsel;
1393 
1394 	if (sb->uxst_flags & UXST_PEER_SEL) {
1395 		selwakeuppri(sel, PSOCK);
1396 		/*
1397 		 * XXXGL: sowakeup() does SEL_WAITING() without locks.
1398 		 */
1399 		if (!SEL_WAITING(sel))
1400 			sb->uxst_flags &= ~UXST_PEER_SEL;
1401 	}
1402 	if (sb->sb_flags & SB_WAIT) {
1403 		sb->sb_flags &= ~SB_WAIT;
1404 		wakeup(&sb->sb_acc);
1405 	}
1406 	KNOTE_LOCKED(&sel->si_note, 0);
1407 	SOCK_RECVBUF_UNLOCK(so);
1408 }
1409 
1410 static void
uipc_cantrcvmore(struct socket * so)1411 uipc_cantrcvmore(struct socket *so)
1412 {
1413 
1414 	SOCK_RECVBUF_LOCK(so);
1415 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
1416 	selwakeuppri(&so->so_rdsel, PSOCK);
1417 	KNOTE_LOCKED(&so->so_rdsel.si_note, 0);
1418 	if (so->so_rcv.uxst_peer != NULL)
1419 		uipc_wakeup_writer(so);
1420 	else
1421 		SOCK_RECVBUF_UNLOCK(so);
1422 }
1423 
1424 static int
uipc_soreceive_stream_or_seqpacket(struct socket * so,struct sockaddr ** psa,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)1425 uipc_soreceive_stream_or_seqpacket(struct socket *so, struct sockaddr **psa,
1426     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1427 {
1428 	struct sockbuf *sb = &so->so_rcv;
1429 	struct mbuf *control, *m, *first, *part, *next;
1430 	u_int ctl, space, datalen, mbcnt, partlen;
1431 	int error, flags;
1432 	bool nonblock, waitall, peek;
1433 
1434 	MPASS(mp0 == NULL);
1435 
1436 	if (psa != NULL)
1437 		*psa = NULL;
1438 	if (controlp != NULL)
1439 		*controlp = NULL;
1440 
1441 	flags = flagsp != NULL ? *flagsp : 0;
1442 	nonblock = (so->so_state & SS_NBIO) ||
1443 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
1444 	peek = flags & MSG_PEEK;
1445 	waitall = (flags & MSG_WAITALL) && !peek;
1446 
1447 	/*
1448 	 * This check may fail only on a socket that never went through
1449 	 * connect(2).  We can check this locklessly, cause: a) for a new born
1450 	 * socket we don't care about applications that may race internally
1451 	 * between connect(2) and recv(2), and b) for a dying socket if we
1452 	 * miss update by unp_sosidisconnected(), we would still get the check
1453 	 * correct.  For dying socket we would observe SBS_CANTRCVMORE later.
1454 	 */
1455 	if (__predict_false((atomic_load_short(&so->so_state) &
1456 	    (SS_ISCONNECTED|SS_ISDISCONNECTED)) == 0))
1457 		return (ENOTCONN);
1458 
1459 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1460 	if (__predict_false(error))
1461 		return (error);
1462 
1463 restart:
1464 	SOCK_RECVBUF_LOCK(so);
1465 	UIPC_STREAM_SBCHECK(sb);
1466 	while (sb->sb_acc < sb->sb_lowat &&
1467 	    (sb->sb_ctl == 0 || controlp == NULL)) {
1468 		if (so->so_error) {
1469 			error = so->so_error;
1470 			if (!peek)
1471 				so->so_error = 0;
1472 			SOCK_RECVBUF_UNLOCK(so);
1473 			SOCK_IO_RECV_UNLOCK(so);
1474 			return (error);
1475 		}
1476 		if (sb->sb_state & SBS_CANTRCVMORE) {
1477 			SOCK_RECVBUF_UNLOCK(so);
1478 			SOCK_IO_RECV_UNLOCK(so);
1479 			return (0);
1480 		}
1481 		if (nonblock) {
1482 			SOCK_RECVBUF_UNLOCK(so);
1483 			SOCK_IO_RECV_UNLOCK(so);
1484 			return (EWOULDBLOCK);
1485 		}
1486 		error = sbwait(so, SO_RCV);
1487 		if (error) {
1488 			SOCK_RECVBUF_UNLOCK(so);
1489 			SOCK_IO_RECV_UNLOCK(so);
1490 			return (error);
1491 		}
1492 	}
1493 
1494 	MPASS(STAILQ_FIRST(&sb->uxst_mbq));
1495 	MPASS(sb->sb_acc > 0 || sb->sb_ctl > 0);
1496 
1497 	mbcnt = 0;
1498 	ctl = 0;
1499 	first = STAILQ_FIRST(&sb->uxst_mbq);
1500 	if (first->m_type == MT_CONTROL) {
1501 		struct mbuf *prev;
1502 
1503 		control = first;
1504 		prev = NULL;
1505 
1506 		/*
1507 		 * Unlink control messages from the socket buffer.  The head of
1508 		 * the socket buffer queue is updated below.
1509 		 */
1510 		STAILQ_FOREACH_FROM(first, &sb->uxst_mbq, m_stailq) {
1511 			if (first->m_type != MT_CONTROL) {
1512 				if (!peek && prev != NULL)
1513 					STAILQ_NEXT(prev, m_stailq) = NULL;
1514 				break;
1515 			}
1516 			ctl += first->m_len;
1517 			mbcnt += MSIZE;
1518 			if (first->m_flags & M_EXT)
1519 				mbcnt += first->m_ext.ext_size;
1520 			prev = first;
1521 		}
1522 	} else
1523 		control = NULL;
1524 
1525 	/*
1526 	 * Find split point for the next copyout.  On exit from the loop,
1527 	 * 'next' points to the new head of the buffer STAILQ and 'datalen'
1528 	 * contains the amount of data we will copy out at the end.  The
1529 	 * copyout is protected by the I/O lock only, as writers can only
1530 	 * append to the buffer.  We need to record the socket buffer state
1531 	 * and do all length adjustments before dropping the socket buffer lock.
1532 	 */
1533 	for (space = uio->uio_resid, m = next = first, part = NULL, datalen = 0;
1534 	     space > 0 && m != sb->uxst_fnrdy && m->m_type == MT_DATA;
1535 	     m = STAILQ_NEXT(m, m_stailq)) {
1536 		if (space >= m->m_len) {
1537 			space -= m->m_len;
1538 			datalen += m->m_len;
1539 			mbcnt += MSIZE;
1540 			if (m->m_flags & M_EXT)
1541 				mbcnt += m->m_ext.ext_size;
1542 			if (m->m_flags & M_EOR) {
1543 				flags |= MSG_EOR;
1544 				next = STAILQ_NEXT(m, m_stailq);
1545 				break;
1546 			}
1547 		} else {
1548 			datalen += space;
1549 			partlen = space;
1550 			if (!peek) {
1551 				m->m_len -= partlen;
1552 				m->m_data += partlen;
1553 			}
1554 			next = part = m;
1555 			break;
1556 		}
1557 		next = STAILQ_NEXT(m, m_stailq);
1558 	}
1559 
1560 	if (!peek) {
1561 		if (next == NULL)
1562 			STAILQ_INIT(&sb->uxst_mbq);
1563 		else
1564 			STAILQ_FIRST(&sb->uxst_mbq) = next;
1565 		MPASS(sb->sb_acc >= datalen);
1566 		sb->sb_acc -= datalen;
1567 		sb->sb_ccc -= datalen;
1568 		MPASS(sb->sb_ctl >= ctl);
1569 		sb->sb_ctl -= ctl;
1570 		MPASS(sb->sb_mbcnt >= mbcnt);
1571 		sb->sb_mbcnt -= mbcnt;
1572 		UIPC_STREAM_SBCHECK(sb);
1573 		if (__predict_true(sb->uxst_peer != NULL)) {
1574 			struct unpcb *unp2;
1575 			bool aio;
1576 
1577 			if ((aio = sb->uxst_flags & UXST_PEER_AIO))
1578 				sb->uxst_flags &= ~UXST_PEER_AIO;
1579 
1580 			uipc_wakeup_writer(so);
1581 			/*
1582 			 * XXXGL: need to go through uipc_lock_peer() after
1583 			 * the receive buffer lock dropped, it was protecting
1584 			 * us from unp_soisdisconnected().  The aio workarounds
1585 			 * should be refactored to the aio(4) side.
1586 			 */
1587 			if (aio && uipc_lock_peer(so, &unp2) == 0) {
1588 				struct socket *so2 = unp2->unp_socket;
1589 
1590 				SOCK_SENDBUF_LOCK(so2);
1591 				so2->so_snd.sb_ccc -= datalen;
1592 				sowakeup_aio(so2, SO_SND);
1593 				SOCK_SENDBUF_UNLOCK(so2);
1594 				UNP_PCB_UNLOCK(unp2);
1595 			}
1596 		} else
1597 			SOCK_RECVBUF_UNLOCK(so);
1598 	} else
1599 		SOCK_RECVBUF_UNLOCK(so);
1600 
1601 	while (control != NULL && control->m_type == MT_CONTROL) {
1602 		if (!peek) {
1603 			/*
1604 			 * unp_externalize() failure must abort entire read(2).
1605 			 * Such failure should also free the problematic
1606 			 * control, but link back the remaining data to the head
1607 			 * of the buffer, so that socket is not left in a state
1608 			 * where it can't progress forward with reading.
1609 			 * Probability of such a failure is really low, so it
1610 			 * is fine that we need to perform pretty complex
1611 			 * operation here to reconstruct the buffer.
1612 			 */
1613 			error = unp_externalize(so, control, controlp, flags);
1614 			control = m_free(control);
1615 			if (__predict_false(error != 0)) {
1616 				struct mchain cmc;
1617 
1618 				/*
1619 				 * Build an mbuf chain containing the remainder
1620 				 * of the control messages and the subsequent
1621 				 * data, to be prepended back to the socket
1622 				 * buffer.
1623 				 */
1624 				if (control != NULL)
1625 					mc_init_m(&cmc, control);
1626 				else
1627 					mc_init(&cmc);
1628 				for (m = first; datalen > 0 && m != part;
1629 				    m = next) {
1630 					datalen -= m->m_len;
1631 					next = STAILQ_NEXT(m, m_stailq);
1632 					mc_append(&cmc, m);
1633 				}
1634 
1635 				SOCK_RECVBUF_LOCK(so);
1636 				if (__predict_false(
1637 				    (sb->sb_state & SBS_CANTRCVMORE) ||
1638 				    cmc.mc_len + sb->sb_ccc + sb->sb_ctl >
1639 				    sb->sb_hiwat)) {
1640 					/*
1641 					 * While the lock was dropped and we
1642 					 * were failing in unp_externalize(),
1643 					 * the peer could have a) disconnected,
1644 					 * b) filled the buffer so that we
1645 					 * can't prepend data back.
1646 					 * These are two edge conditions that
1647 					 * we just can't handle, so lose the
1648 					 * data and return the error.
1649 					 */
1650 					SOCK_RECVBUF_UNLOCK(so);
1651 					SOCK_IO_RECV_UNLOCK(so);
1652 					unp_scan(mc_first(&cmc),
1653 					    unp_freerights);
1654 					mc_freem(&cmc);
1655 					return (error);
1656 				}
1657 
1658 				UIPC_STREAM_SBCHECK(sb);
1659 				/* XXXGL: STAILQ_PREPEND */
1660 				STAILQ_CONCAT(&cmc.mc_q, &sb->uxst_mbq);
1661 				STAILQ_SWAP(&cmc.mc_q, &sb->uxst_mbq, mbuf);
1662 
1663 				sb->sb_ctl = sb->sb_acc = sb->sb_ccc =
1664 				    sb->sb_mbcnt = 0;
1665 				STAILQ_FOREACH(m, &sb->uxst_mbq, m_stailq) {
1666 					if (m->m_type == MT_DATA) {
1667 						if (m == part) {
1668 							m->m_len += partlen;
1669 							m->m_data -= partlen;
1670 						}
1671 						sb->sb_acc += m->m_len;
1672 						sb->sb_ccc += m->m_len;
1673 					} else {
1674 						sb->sb_ctl += m->m_len;
1675 					}
1676 					sb->sb_mbcnt += MSIZE;
1677 					if (m->m_flags & M_EXT)
1678 						sb->sb_mbcnt +=
1679 						    m->m_ext.ext_size;
1680 				}
1681 				UIPC_STREAM_SBCHECK(sb);
1682 				SOCK_RECVBUF_UNLOCK(so);
1683 				SOCK_IO_RECV_UNLOCK(so);
1684 				return (error);
1685 			}
1686 			if (controlp != NULL) {
1687 				while (*controlp != NULL)
1688 					controlp = &(*controlp)->m_next;
1689 			}
1690 		} else {
1691 			/*
1692 			 * XXXGL
1693 			 *
1694 			 * In MSG_PEEK case control is not externalized.  This
1695 			 * means we are leaking some kernel pointers to the
1696 			 * userland.  They are useless to a law-abiding
1697 			 * application, but may be useful to a malware.  This
1698 			 * is what the historical implementation in the
1699 			 * soreceive_generic() did. To be improved?
1700 			 */
1701 			if (controlp != NULL) {
1702 				*controlp = m_copym(control, 0, control->m_len,
1703 				    M_WAITOK);
1704 				controlp = &(*controlp)->m_next;
1705 			}
1706 			control = STAILQ_NEXT(control, m_stailq);
1707 		}
1708 	}
1709 
1710 	for (m = first; datalen > 0; m = next) {
1711 		void *data;
1712 		u_int len;
1713 
1714 		next = STAILQ_NEXT(m, m_stailq);
1715 		if (m == part) {
1716 			data = peek ?
1717 			    mtod(m, char *) : mtod(m, char *) - partlen;
1718 			len = partlen;
1719 		} else {
1720 			data = mtod(m, char *);
1721 			len = m->m_len;
1722 		}
1723 		error = uiomove(data, len, uio);
1724 		if (__predict_false(error)) {
1725 			if (!peek)
1726 				for (; m != part && datalen > 0; m = next) {
1727 					next = STAILQ_NEXT(m, m_stailq);
1728 					MPASS(datalen >= m->m_len);
1729 					datalen -= m->m_len;
1730 					m_free(m);
1731 				}
1732 			SOCK_IO_RECV_UNLOCK(so);
1733 			return (error);
1734 		}
1735 		datalen -= len;
1736 		if (!peek && m != part)
1737 			m_free(m);
1738 	}
1739 	if (waitall && !(flags & MSG_EOR) && uio->uio_resid > 0)
1740 		goto restart;
1741 	SOCK_IO_RECV_UNLOCK(so);
1742 
1743 	if (flagsp != NULL)
1744 		*flagsp |= flags;
1745 
1746 	uio->uio_td->td_ru.ru_msgrcv++;
1747 
1748 	return (0);
1749 }
1750 
1751 static int
uipc_sopoll_stream_or_seqpacket(struct socket * so,int events,struct thread * td)1752 uipc_sopoll_stream_or_seqpacket(struct socket *so, int events,
1753     struct thread *td)
1754 {
1755 	struct unpcb *unp = sotounpcb(so);
1756 	int revents;
1757 
1758 	UNP_PCB_LOCK(unp);
1759 	if (SOLISTENING(so)) {
1760 		/* The above check is safe, since conversion to listening uses
1761 		 * both protocol and socket lock.
1762 		 */
1763 		SOCK_LOCK(so);
1764 		if (!(events & (POLLIN | POLLRDNORM)))
1765 			revents = 0;
1766 		else if (!TAILQ_EMPTY(&so->sol_comp))
1767 			revents = events & (POLLIN | POLLRDNORM);
1768 		else if (so->so_error)
1769 			revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
1770 		else {
1771 			selrecord(td, &so->so_rdsel);
1772 			revents = 0;
1773 		}
1774 		SOCK_UNLOCK(so);
1775 	} else {
1776 		if (so->so_state & SS_ISDISCONNECTED)
1777 			revents = POLLHUP;
1778 		else
1779 			revents = 0;
1780 		if (events & (POLLIN | POLLRDNORM | POLLRDHUP)) {
1781 			SOCK_RECVBUF_LOCK(so);
1782 			if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat ||
1783 			    so->so_error || so->so_rerror)
1784 				revents |= events & (POLLIN | POLLRDNORM);
1785 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
1786 				revents |= events &
1787 				    (POLLIN | POLLRDNORM | POLLRDHUP);
1788 			if (!(revents & (POLLIN | POLLRDNORM | POLLRDHUP))) {
1789 				selrecord(td, &so->so_rdsel);
1790 				so->so_rcv.sb_flags |= SB_SEL;
1791 			}
1792 			SOCK_RECVBUF_UNLOCK(so);
1793 		}
1794 		if (events & (POLLOUT | POLLWRNORM)) {
1795 			struct socket *so2 = so->so_rcv.uxst_peer;
1796 
1797 			if (so2 != NULL) {
1798 				struct sockbuf *sb = &so2->so_rcv;
1799 
1800 				SOCK_RECVBUF_LOCK(so2);
1801 				if (uipc_stream_sbspace(sb) >= sb->sb_lowat)
1802 					revents |= events &
1803 					    (POLLOUT | POLLWRNORM);
1804 				if (sb->sb_state & SBS_CANTRCVMORE)
1805 					revents |= POLLHUP;
1806 				if (!(revents & (POLLOUT | POLLWRNORM))) {
1807 					so2->so_rcv.uxst_flags |= UXST_PEER_SEL;
1808 					selrecord(td, &so->so_wrsel);
1809 				}
1810 				SOCK_RECVBUF_UNLOCK(so2);
1811 			} else
1812 				selrecord(td, &so->so_wrsel);
1813 		}
1814 	}
1815 	UNP_PCB_UNLOCK(unp);
1816 	return (revents);
1817 }
1818 
1819 static void
uipc_wrknl_lock(void * arg)1820 uipc_wrknl_lock(void *arg)
1821 {
1822 	struct socket *so = arg;
1823 	struct unpcb *unp = sotounpcb(so);
1824 
1825 retry:
1826 	if (SOLISTENING(so)) {
1827 		SOLISTEN_LOCK(so);
1828 	} else {
1829 		UNP_PCB_LOCK(unp);
1830 		if (__predict_false(SOLISTENING(so))) {
1831 			UNP_PCB_UNLOCK(unp);
1832 			goto retry;
1833 		}
1834 		if (so->so_rcv.uxst_peer != NULL)
1835 			SOCK_RECVBUF_LOCK(so->so_rcv.uxst_peer);
1836 	}
1837 }
1838 
1839 static void
uipc_wrknl_unlock(void * arg)1840 uipc_wrknl_unlock(void *arg)
1841 {
1842 	struct socket *so = arg;
1843 	struct unpcb *unp = sotounpcb(so);
1844 
1845 	if (SOLISTENING(so))
1846 		SOLISTEN_UNLOCK(so);
1847 	else {
1848 		if (so->so_rcv.uxst_peer != NULL)
1849 			SOCK_RECVBUF_UNLOCK(so->so_rcv.uxst_peer);
1850 		UNP_PCB_UNLOCK(unp);
1851 	}
1852 }
1853 
1854 static void
uipc_wrknl_assert_lock(void * arg,int what)1855 uipc_wrknl_assert_lock(void *arg, int what)
1856 {
1857 	struct socket *so = arg;
1858 
1859 	if (SOLISTENING(so)) {
1860 		if (what == LA_LOCKED)
1861 			SOLISTEN_LOCK_ASSERT(so);
1862 		else
1863 			SOLISTEN_UNLOCK_ASSERT(so);
1864 	} else {
1865 		/*
1866 		 * The pr_soreceive method will put a note without owning the
1867 		 * unp lock, so we can't assert it here.  But we can safely
1868 		 * dereference uxst_peer pointer, since receive buffer lock
1869 		 * is assumed to be held here.
1870 		 */
1871 		if (what == LA_LOCKED && so->so_rcv.uxst_peer != NULL)
1872 			SOCK_RECVBUF_LOCK_ASSERT(so->so_rcv.uxst_peer);
1873 	}
1874 }
1875 
1876 static void
uipc_filt_sowdetach(struct knote * kn)1877 uipc_filt_sowdetach(struct knote *kn)
1878 {
1879 	struct socket *so = kn->kn_fp->f_data;
1880 
1881 	uipc_wrknl_lock(so);
1882 	knlist_remove(&so->so_wrsel.si_note, kn, 1);
1883 	uipc_wrknl_unlock(so);
1884 }
1885 
1886 static int
uipc_filt_sowrite(struct knote * kn,long hint)1887 uipc_filt_sowrite(struct knote *kn, long hint)
1888 {
1889 	struct socket *so = kn->kn_fp->f_data, *so2;
1890 	struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn;
1891 
1892 	if (SOLISTENING(so))
1893 		return (0);
1894 
1895 	if (unp2 == NULL) {
1896 		if (so->so_state & SS_ISDISCONNECTED) {
1897 			kn->kn_flags |= EV_EOF;
1898 			kn->kn_fflags = so->so_error;
1899 			return (1);
1900 		} else
1901 			return (0);
1902 	}
1903 
1904 	so2 = unp2->unp_socket;
1905 	SOCK_RECVBUF_LOCK_ASSERT(so2);
1906 	kn->kn_data = uipc_stream_sbspace(&so2->so_rcv);
1907 
1908 	if (so2->so_rcv.sb_state & SBS_CANTRCVMORE) {
1909 		kn->kn_flags |= EV_EOF;
1910 		return (1);
1911 	} else if (kn->kn_sfflags & NOTE_LOWAT)
1912 		return (kn->kn_data >= kn->kn_sdata);
1913 	else
1914 		return (kn->kn_data >= so2->so_rcv.sb_lowat);
1915 }
1916 
1917 static int
uipc_filt_soempty(struct knote * kn,long hint)1918 uipc_filt_soempty(struct knote *kn, long hint)
1919 {
1920 	struct socket *so = kn->kn_fp->f_data, *so2;
1921 	struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn;
1922 
1923 	if (SOLISTENING(so) || unp2 == NULL)
1924 		return (1);
1925 
1926 	so2 = unp2->unp_socket;
1927 	SOCK_RECVBUF_LOCK_ASSERT(so2);
1928 	kn->kn_data = uipc_stream_sbspace(&so2->so_rcv);
1929 
1930 	return (kn->kn_data == 0 ? 1 : 0);
1931 }
1932 
1933 static const struct filterops uipc_write_filtops = {
1934 	.f_isfd = 1,
1935 	.f_detach = uipc_filt_sowdetach,
1936 	.f_event = uipc_filt_sowrite,
1937 	.f_copy = knote_triv_copy,
1938 };
1939 static const struct filterops uipc_empty_filtops = {
1940 	.f_isfd = 1,
1941 	.f_detach = uipc_filt_sowdetach,
1942 	.f_event = uipc_filt_soempty,
1943 	.f_copy = knote_triv_copy,
1944 };
1945 
1946 static int
uipc_kqfilter_stream_or_seqpacket(struct socket * so,struct knote * kn)1947 uipc_kqfilter_stream_or_seqpacket(struct socket *so, struct knote *kn)
1948 {
1949 	struct unpcb *unp = sotounpcb(so);
1950 	struct knlist *knl;
1951 
1952 	switch (kn->kn_filter) {
1953 	case EVFILT_READ:
1954 		return (sokqfilter_generic(so, kn));
1955 	case EVFILT_WRITE:
1956 		kn->kn_fop = &uipc_write_filtops;
1957 		break;
1958 	case EVFILT_EMPTY:
1959 		kn->kn_fop = &uipc_empty_filtops;
1960 		break;
1961 	default:
1962 		return (EINVAL);
1963 	}
1964 
1965 	knl = &so->so_wrsel.si_note;
1966 	UNP_PCB_LOCK(unp);
1967 	if (SOLISTENING(so)) {
1968 		SOLISTEN_LOCK(so);
1969 		knlist_add(knl, kn, 1);
1970 		SOLISTEN_UNLOCK(so);
1971 	} else {
1972 		struct socket *so2 = so->so_rcv.uxst_peer;
1973 
1974 		if (so2 != NULL)
1975 			SOCK_RECVBUF_LOCK(so2);
1976 		knlist_add(knl, kn, 1);
1977 		if (so2 != NULL)
1978 			SOCK_RECVBUF_UNLOCK(so2);
1979 	}
1980 	UNP_PCB_UNLOCK(unp);
1981 	return (0);
1982 }
1983 
1984 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1985 static inline bool
uipc_dgram_sbspace(struct sockbuf * sb,u_int cc,u_int mbcnt)1986 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1987 {
1988 	u_int bleft, mleft;
1989 
1990 	/*
1991 	 * Negative space may happen if send(2) is followed by
1992 	 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1993 	 */
1994 	if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1995 	    sb->sb_mbmax < sb->uxdg_mbcnt))
1996 		return (false);
1997 
1998 	if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1999 		return (false);
2000 
2001 	bleft = sb->sb_hiwat - sb->uxdg_cc;
2002 	mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
2003 
2004 	return (bleft >= cc && mleft >= mbcnt);
2005 }
2006 
2007 /*
2008  * PF_UNIX/SOCK_DGRAM send
2009  *
2010  * Allocate a record consisting of 3 mbufs in the sequence of
2011  * from -> control -> data and append it to the socket buffer.
2012  *
2013  * The first mbuf carries sender's name and is a pkthdr that stores
2014  * overall length of datagram, its memory consumption and control length.
2015  */
2016 #define	ctllen	PH_loc.thirtytwo[1]
2017 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
2018     offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
2019 static int
uipc_sosend_dgram(struct socket * so,struct sockaddr * addr,struct uio * uio,struct mbuf * m,struct mbuf * c,int flags,struct thread * td)2020 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
2021     struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
2022 {
2023 	struct unpcb *unp, *unp2;
2024 	const struct sockaddr *from;
2025 	struct socket *so2, *peer;
2026 	struct sockbuf *sb;
2027 	struct mchain cmc = MCHAIN_INITIALIZER(&cmc);
2028 	struct mbuf *f;
2029 	u_int cc, ctl, mbcnt;
2030 	u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
2031 	int error, needsopts;
2032 
2033 	MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
2034 
2035 	error = needsopts = 0;
2036 	f = NULL;
2037 
2038 	if (__predict_false(flags & MSG_OOB)) {
2039 		error = EOPNOTSUPP;
2040 		goto out;
2041 	}
2042 	if (m == NULL) {
2043 		if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
2044 			error = EMSGSIZE;
2045 			goto out;
2046 		}
2047 		m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
2048 		if (__predict_false(m == NULL)) {
2049 			error = EFAULT;
2050 			goto out;
2051 		}
2052 		f = m_gethdr(M_WAITOK, MT_SONAME);
2053 		cc = m->m_pkthdr.len;
2054 		mbcnt = MSIZE + m->m_pkthdr.memlen;
2055 		if (c != NULL &&
2056 		    (error = unp_internalize(c, &cmc, td, &needsopts)))
2057 			goto out;
2058 	} else {
2059 		struct mchain mc;
2060 
2061 		uipc_reset_kernel_mbuf(m, &mc);
2062 		cc = mc.mc_len;
2063 		mbcnt = mc.mc_mlen;
2064 		if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
2065 			error = EMSGSIZE;
2066 			goto out;
2067 		}
2068 		if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
2069 			error = ENOBUFS;
2070 			goto out;
2071 		}
2072 	}
2073 
2074 	unp = sotounpcb(so);
2075 	MPASS(unp);
2076 
2077 	/*
2078 	 * XXXGL: would be cool to fully remove so_snd out of the equation
2079 	 * and avoid this lock, which is not only extraneous, but also being
2080 	 * released, thus still leaving possibility for a race.  We can easily
2081 	 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
2082 	 * is more difficult to invent something to handle so_error.
2083 	 */
2084 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
2085 	if (error)
2086 		goto out2;
2087 	SOCK_SENDBUF_LOCK(so);
2088 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2089 		SOCK_SENDBUF_UNLOCK(so);
2090 		error = EPIPE;
2091 		goto out3;
2092 	}
2093 	if (so->so_error != 0) {
2094 		error = so->so_error;
2095 		so->so_error = 0;
2096 		SOCK_SENDBUF_UNLOCK(so);
2097 		goto out3;
2098 	}
2099 	if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
2100 		SOCK_SENDBUF_UNLOCK(so);
2101 		error = EDESTADDRREQ;
2102 		goto out3;
2103 	}
2104 	SOCK_SENDBUF_UNLOCK(so);
2105 
2106 	if (addr != NULL) {
2107 		const char *path;
2108 		int len;
2109 
2110 		if ((error = unp_sun_path(addr, &path, &len)))
2111 			goto out3;
2112 		if ((error = unp_connectat(AT_FDCWD, so, path, len, td, &peer)))
2113 			goto out3;
2114 		UNP_PCB_LOCK_ASSERT(unp);
2115 		unp2 = unp->unp_conn;
2116 		UNP_PCB_LOCK_ASSERT(unp2);
2117 	} else {
2118 		UNP_PCB_LOCK(unp);
2119 		unp2 = unp_pcb_lock_peer(unp);
2120 		if (unp2 == NULL) {
2121 			UNP_PCB_UNLOCK(unp);
2122 			error = ENOTCONN;
2123 			goto out3;
2124 		}
2125 	}
2126 
2127 	/* Check for SO_PASS* flags */
2128 	so2 = unp2->unp_socket;
2129 	if ((atomic_load_int(&so2->so_options) & needsopts) != needsopts) {
2130 		error = EPERM;
2131 		goto out4;
2132 	}
2133 
2134 	if (unp2->unp_flags & UNP_WANTCRED_MASK)
2135 		unp_addsockcred(td, &cmc, unp2->unp_flags);
2136 	if (unp->unp_addr != NULL)
2137 		from = (struct sockaddr *)unp->unp_addr;
2138 	else
2139 		from = &sun_noname;
2140 	f->m_len = from->sa_len;
2141 	MPASS(from->sa_len <= MLEN);
2142 	bcopy(from, mtod(f, void *), from->sa_len);
2143 
2144 	/*
2145 	 * Concatenate mbufs: from -> control -> data.
2146 	 * Save overall cc and mbcnt in "from" mbuf.
2147 	 */
2148 	if (!STAILQ_EMPTY(&cmc.mc_q)) {
2149 		f->m_next = mc_first(&cmc);
2150 		mc_last(&cmc)->m_next = m;
2151 		/* XXXGL: This is dirty as well as rollback after ENOBUFS. */
2152 		STAILQ_INIT(&cmc.mc_q);
2153 	} else
2154 		f->m_next = m;
2155 	m = NULL;
2156 	ctl = f->m_len + cmc.mc_len;
2157 	mbcnt += cmc.mc_mlen;
2158 #ifdef INVARIANTS
2159 	dcc = dctl = dmbcnt = 0;
2160 	for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
2161 		if (mb->m_type == MT_DATA)
2162 			dcc += mb->m_len;
2163 		else
2164 			dctl += mb->m_len;
2165 		dmbcnt += MSIZE;
2166 		if (mb->m_flags & M_EXT)
2167 			dmbcnt += mb->m_ext.ext_size;
2168 	}
2169 	MPASS(dcc == cc);
2170 	MPASS(dctl == ctl);
2171 	MPASS(dmbcnt == mbcnt);
2172 #endif
2173 	f->m_pkthdr.len = cc + ctl;
2174 	f->m_pkthdr.memlen = mbcnt;
2175 	f->m_pkthdr.ctllen = ctl;
2176 
2177 	/*
2178 	 * Destination socket buffer selection.
2179 	 *
2180 	 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
2181 	 * destination address is supplied, create a temporary connection for
2182 	 * the run time of the function (see call to unp_connectat() above and
2183 	 * to unp_disconnect() below).  We distinguish them by condition of
2184 	 * (addr != NULL).  We intentionally avoid adding 'bool connected' for
2185 	 * that condition, since, again, through the run time of this code we
2186 	 * are always connected.  For such "unconnected" sends, the destination
2187 	 * buffer would be the receive buffer of destination socket so2.
2188 	 *
2189 	 * For connected sends, data lands on the send buffer of the sender's
2190 	 * socket "so".  Then, if we just added the very first datagram
2191 	 * on this send buffer, we need to add the send buffer on to the
2192 	 * receiving socket's buffer list.  We put ourselves on top of the
2193 	 * list.  Such logic gives infrequent senders priority over frequent
2194 	 * senders.
2195 	 *
2196 	 * Note on byte count management. As long as event methods kevent(2),
2197 	 * select(2) are not protocol specific (yet), we need to maintain
2198 	 * meaningful values on the receive buffer.  So, the receive buffer
2199 	 * would accumulate counters from all connected buffers potentially
2200 	 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
2201 	 */
2202 	sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
2203 	SOCK_RECVBUF_LOCK(so2);
2204 	if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
2205 		if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
2206 			TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
2207 			    uxdg_clist);
2208 		STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
2209 		sb->uxdg_cc += cc + ctl;
2210 		sb->uxdg_ctl += ctl;
2211 		sb->uxdg_mbcnt += mbcnt;
2212 		so2->so_rcv.sb_acc += cc + ctl;
2213 		so2->so_rcv.sb_ccc += cc + ctl;
2214 		so2->so_rcv.sb_ctl += ctl;
2215 		so2->so_rcv.sb_mbcnt += mbcnt;
2216 		sorwakeup_locked(so2);
2217 		f = NULL;
2218 	} else {
2219 		soroverflow_locked(so2);
2220 		error = ENOBUFS;
2221 		if (f->m_next->m_type == MT_CONTROL) {
2222 			STAILQ_FIRST(&cmc.mc_q) = f->m_next;
2223 			f->m_next = NULL;
2224 		}
2225 	}
2226 
2227 out4:
2228 	if (addr != NULL) {
2229 		unp_disconnect(unp, unp2);
2230 		sorele(peer);
2231 	} else
2232 		unp_pcb_unlock_pair(unp, unp2);
2233 
2234 	td->td_ru.ru_msgsnd++;
2235 
2236 out3:
2237 	SOCK_IO_SEND_UNLOCK(so);
2238 out2:
2239 	if (!mc_empty(&cmc))
2240 		unp_scan(mc_first(&cmc), unp_freerights);
2241 out:
2242 	if (f)
2243 		m_freem(f);
2244 	mc_freem(&cmc);
2245 	if (m)
2246 		m_freem(m);
2247 
2248 	return (error);
2249 }
2250 
2251 /*
2252  * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
2253  * The mbuf has already been unlinked from the uxdg_mb of socket buffer
2254  * and needs to be linked onto uxdg_peeked of receive socket buffer.
2255  */
2256 static int
uipc_peek_dgram(struct socket * so,struct mbuf * m,struct sockaddr ** psa,struct uio * uio,struct mbuf ** controlp,int * flagsp)2257 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
2258     struct uio *uio, struct mbuf **controlp, int *flagsp)
2259 {
2260 	ssize_t len = 0;
2261 	int error;
2262 
2263 	so->so_rcv.uxdg_peeked = m;
2264 	so->so_rcv.uxdg_cc += m->m_pkthdr.len;
2265 	so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
2266 	so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
2267 	SOCK_RECVBUF_UNLOCK(so);
2268 
2269 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2270 	if (psa != NULL)
2271 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2272 
2273 	m = m->m_next;
2274 	KASSERT(m, ("%s: no data or control after soname", __func__));
2275 
2276 	/*
2277 	 * With MSG_PEEK the control isn't executed, just copied.
2278 	 */
2279 	while (m != NULL && m->m_type == MT_CONTROL) {
2280 		if (controlp != NULL) {
2281 			*controlp = m_copym(m, 0, m->m_len, M_WAITOK);
2282 			controlp = &(*controlp)->m_next;
2283 		}
2284 		m = m->m_next;
2285 	}
2286 	KASSERT(m == NULL || m->m_type == MT_DATA,
2287 	    ("%s: not MT_DATA mbuf %p", __func__, m));
2288 	while (m != NULL && uio->uio_resid > 0) {
2289 		len = uio->uio_resid;
2290 		if (len > m->m_len)
2291 			len = m->m_len;
2292 		error = uiomove(mtod(m, char *), (int)len, uio);
2293 		if (error) {
2294 			SOCK_IO_RECV_UNLOCK(so);
2295 			return (error);
2296 		}
2297 		if (len == m->m_len)
2298 			m = m->m_next;
2299 	}
2300 	SOCK_IO_RECV_UNLOCK(so);
2301 
2302 	if (flagsp != NULL) {
2303 		if (m != NULL) {
2304 			if (*flagsp & MSG_TRUNC) {
2305 				/* Report real length of the packet */
2306 				uio->uio_resid -= m_length(m, NULL) - len;
2307 			}
2308 			*flagsp |= MSG_TRUNC;
2309 		} else
2310 			*flagsp &= ~MSG_TRUNC;
2311 	}
2312 
2313 	return (0);
2314 }
2315 
2316 /*
2317  * PF_UNIX/SOCK_DGRAM receive
2318  */
2319 static int
uipc_soreceive_dgram(struct socket * so,struct sockaddr ** psa,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)2320 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2321     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2322 {
2323 	struct sockbuf *sb = NULL;
2324 	struct mbuf *m;
2325 	int flags, error;
2326 	ssize_t len = 0;
2327 	bool nonblock;
2328 
2329 	MPASS(mp0 == NULL);
2330 
2331 	if (psa != NULL)
2332 		*psa = NULL;
2333 	if (controlp != NULL)
2334 		*controlp = NULL;
2335 
2336 	flags = flagsp != NULL ? *flagsp : 0;
2337 	nonblock = (so->so_state & SS_NBIO) ||
2338 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
2339 
2340 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2341 	if (__predict_false(error))
2342 		return (error);
2343 
2344 	/*
2345 	 * Loop blocking while waiting for a datagram.  Prioritize connected
2346 	 * peers over unconnected sends.  Set sb to selected socket buffer
2347 	 * containing an mbuf on exit from the wait loop.  A datagram that
2348 	 * had already been peeked at has top priority.
2349 	 */
2350 	SOCK_RECVBUF_LOCK(so);
2351 	while ((m = so->so_rcv.uxdg_peeked) == NULL &&
2352 	    (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
2353 	    (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
2354 		if (so->so_error) {
2355 			error = so->so_error;
2356 			if (!(flags & MSG_PEEK))
2357 				so->so_error = 0;
2358 			SOCK_RECVBUF_UNLOCK(so);
2359 			SOCK_IO_RECV_UNLOCK(so);
2360 			return (error);
2361 		}
2362 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2363 		    uio->uio_resid == 0) {
2364 			SOCK_RECVBUF_UNLOCK(so);
2365 			SOCK_IO_RECV_UNLOCK(so);
2366 			return (0);
2367 		}
2368 		if (nonblock) {
2369 			SOCK_RECVBUF_UNLOCK(so);
2370 			SOCK_IO_RECV_UNLOCK(so);
2371 			return (EWOULDBLOCK);
2372 		}
2373 		error = sbwait(so, SO_RCV);
2374 		if (error) {
2375 			SOCK_RECVBUF_UNLOCK(so);
2376 			SOCK_IO_RECV_UNLOCK(so);
2377 			return (error);
2378 		}
2379 	}
2380 
2381 	if (sb == NULL)
2382 		sb = &so->so_rcv;
2383 	else if (m == NULL)
2384 		m = STAILQ_FIRST(&sb->uxdg_mb);
2385 	else
2386 		MPASS(m == so->so_rcv.uxdg_peeked);
2387 
2388 	MPASS(sb->uxdg_cc > 0);
2389 	M_ASSERTPKTHDR(m);
2390 	KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2391 
2392 	if (uio->uio_td)
2393 		uio->uio_td->td_ru.ru_msgrcv++;
2394 
2395 	if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
2396 		STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
2397 		if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
2398 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
2399 	} else
2400 		so->so_rcv.uxdg_peeked = NULL;
2401 
2402 	sb->uxdg_cc -= m->m_pkthdr.len;
2403 	sb->uxdg_ctl -= m->m_pkthdr.ctllen;
2404 	sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
2405 
2406 	if (__predict_false(flags & MSG_PEEK))
2407 		return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
2408 
2409 	so->so_rcv.sb_acc -= m->m_pkthdr.len;
2410 	so->so_rcv.sb_ccc -= m->m_pkthdr.len;
2411 	so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
2412 	so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
2413 	SOCK_RECVBUF_UNLOCK(so);
2414 
2415 	if (psa != NULL)
2416 		*psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2417 	m = m_free(m);
2418 	KASSERT(m, ("%s: no data or control after soname", __func__));
2419 
2420 	/*
2421 	 * Packet to copyout() is now in 'm' and it is disconnected from the
2422 	 * queue.
2423 	 *
2424 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2425 	 * in the first mbuf chain on the socket buffer.  We call into the
2426 	 * unp_externalize() to perform externalization (or freeing if
2427 	 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
2428 	 * without MT_DATA mbufs.
2429 	 */
2430 	while (m != NULL && m->m_type == MT_CONTROL) {
2431 		error = unp_externalize(so, m, controlp, flags);
2432 		m = m_free(m);
2433 		if (error != 0) {
2434 			SOCK_IO_RECV_UNLOCK(so);
2435 			unp_scan(m, unp_freerights);
2436 			m_freem(m);
2437 			return (error);
2438 		}
2439 		if (controlp != NULL) {
2440 			while (*controlp != NULL)
2441 				controlp = &(*controlp)->m_next;
2442 		}
2443 	}
2444 	KASSERT(m == NULL || m->m_type == MT_DATA,
2445 	    ("%s: not MT_DATA mbuf %p", __func__, m));
2446 	while (m != NULL && uio->uio_resid > 0) {
2447 		len = uio->uio_resid;
2448 		if (len > m->m_len)
2449 			len = m->m_len;
2450 		error = uiomove(mtod(m, char *), (int)len, uio);
2451 		if (error) {
2452 			SOCK_IO_RECV_UNLOCK(so);
2453 			m_freem(m);
2454 			return (error);
2455 		}
2456 		if (len == m->m_len)
2457 			m = m_free(m);
2458 		else {
2459 			m->m_data += len;
2460 			m->m_len -= len;
2461 		}
2462 	}
2463 	SOCK_IO_RECV_UNLOCK(so);
2464 
2465 	if (m != NULL) {
2466 		if (flagsp != NULL) {
2467 			if (flags & MSG_TRUNC) {
2468 				/* Report real length of the packet */
2469 				uio->uio_resid -= m_length(m, NULL);
2470 			}
2471 			*flagsp |= MSG_TRUNC;
2472 		}
2473 		m_freem(m);
2474 	} else if (flagsp != NULL)
2475 		*flagsp &= ~MSG_TRUNC;
2476 
2477 	return (0);
2478 }
2479 
2480 static int
uipc_sendfile_wait(struct socket * so,off_t need,int * space)2481 uipc_sendfile_wait(struct socket *so, off_t need, int *space)
2482 {
2483 	struct unpcb *unp2;
2484 	struct socket *so2;
2485 	struct sockbuf *sb;
2486 	bool nonblock, sockref;
2487 	int error;
2488 
2489 	MPASS(so->so_type == SOCK_STREAM);
2490 	MPASS(need > 0);
2491 	MPASS(space != NULL);
2492 
2493 	nonblock = so->so_state & SS_NBIO;
2494 	sockref = false;
2495 
2496 	if (__predict_false((so->so_state & SS_ISCONNECTED) == 0))
2497 		return (ENOTCONN);
2498 
2499 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2500 		return (error);
2501 
2502 	so2 = unp2->unp_socket;
2503 	sb = &so2->so_rcv;
2504 	SOCK_RECVBUF_LOCK(so2);
2505 	UNP_PCB_UNLOCK(unp2);
2506 	while ((*space = uipc_stream_sbspace(sb)) < need &&
2507 	    (*space < so->so_snd.sb_hiwat / 2)) {
2508 		UIPC_STREAM_SBCHECK(sb);
2509 		if (nonblock) {
2510 			SOCK_RECVBUF_UNLOCK(so2);
2511 			return (EAGAIN);
2512 		}
2513 		if (!sockref) {
2514 			soref(so2);
2515 			sockref = true;
2516 		}
2517 		error = uipc_stream_sbwait(so2, so->so_snd.sb_timeo);
2518 		if (error == 0 &&
2519 		    __predict_false(sb->sb_state & SBS_CANTRCVMORE))
2520 			error = EPIPE;
2521 		if (error) {
2522 			SOCK_RECVBUF_UNLOCK(so2);
2523 			sorele(so2);
2524 			return (error);
2525 		}
2526 	}
2527 	UIPC_STREAM_SBCHECK(sb);
2528 	SOCK_RECVBUF_UNLOCK(so2);
2529 	if (sockref)
2530 		sorele(so2);
2531 
2532 	return (0);
2533 }
2534 
2535 /*
2536  * Although this is a pr_send method, for unix(4) it is called only via
2537  * sendfile(2) path.  This means we can be sure that mbufs are clear of
2538  * any extra flags and don't require any conditioning.
2539  */
2540 static int
uipc_sendfile(struct socket * so,int flags,struct mbuf * m,struct sockaddr * from,struct mbuf * control,struct thread * td)2541 uipc_sendfile(struct socket *so, int flags, struct mbuf *m,
2542     struct sockaddr *from, struct mbuf *control, struct thread *td)
2543 {
2544 	struct mchain mc;
2545 	struct unpcb *unp2;
2546 	struct socket *so2;
2547 	struct sockbuf *sb;
2548 	bool notready, wakeup;
2549 	int error;
2550 
2551 	MPASS(so->so_type == SOCK_STREAM);
2552 	MPASS(from == NULL && control == NULL);
2553 	KASSERT(!(m->m_flags & M_EXTPG),
2554 	    ("unix(4): TLS sendfile(2) not supported"));
2555 
2556 	notready = flags & PRUS_NOTREADY;
2557 
2558 	if (__predict_false((so->so_state & SS_ISCONNECTED) == 0)) {
2559 		error = ENOTCONN;
2560 		goto out;
2561 	}
2562 
2563 	if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2564 		goto out;
2565 
2566 	mc_init_m(&mc, m);
2567 
2568 	so2 = unp2->unp_socket;
2569 	sb = &so2->so_rcv;
2570 	SOCK_RECVBUF_LOCK(so2);
2571 	UNP_PCB_UNLOCK(unp2);
2572 	UIPC_STREAM_SBCHECK(sb);
2573 	sb->sb_ccc += mc.mc_len;
2574 	sb->sb_mbcnt += mc.mc_mlen;
2575 	if (sb->uxst_fnrdy == NULL) {
2576 		if (notready) {
2577 			wakeup = false;
2578 			STAILQ_FOREACH(m, &mc.mc_q, m_stailq) {
2579 				if (m->m_flags & M_NOTREADY) {
2580 					sb->uxst_fnrdy = m;
2581 					break;
2582 				} else {
2583 					sb->sb_acc += m->m_len;
2584 					wakeup = true;
2585 				}
2586 			}
2587 		} else {
2588 			wakeup = true;
2589 			sb->sb_acc += mc.mc_len;
2590 		}
2591 	} else {
2592 		wakeup = false;
2593 	}
2594 	STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q);
2595 	UIPC_STREAM_SBCHECK(sb);
2596 	if (wakeup)
2597 		sorwakeup_locked(so2);
2598 	else
2599 		SOCK_RECVBUF_UNLOCK(so2);
2600 
2601 	return (0);
2602 out:
2603 	/*
2604 	 * In case of not ready data, uipc_ready() is responsible
2605 	 * for freeing memory.
2606 	 */
2607 	if (m != NULL && !notready)
2608 		m_freem(m);
2609 
2610 	return (error);
2611 }
2612 
2613 static int
uipc_sbready(struct sockbuf * sb,struct mbuf * m,int count)2614 uipc_sbready(struct sockbuf *sb, struct mbuf *m, int count)
2615 {
2616 	bool blocker;
2617 
2618 	/* assert locked */
2619 
2620 	blocker = (sb->uxst_fnrdy == m);
2621 	STAILQ_FOREACH_FROM(m, &sb->uxst_mbq, m_stailq) {
2622 		if (count > 0) {
2623 			MPASS(m->m_flags & M_NOTREADY);
2624 			m->m_flags &= ~M_NOTREADY;
2625 			if (blocker)
2626 				sb->sb_acc += m->m_len;
2627 			count--;
2628 		} else if (m->m_flags & M_NOTREADY)
2629 			break;
2630 		else if (blocker)
2631 			sb->sb_acc += m->m_len;
2632 	}
2633 	if (blocker) {
2634 		sb->uxst_fnrdy = m;
2635 		return (0);
2636 	} else
2637 		return (EINPROGRESS);
2638 }
2639 
2640 static bool
uipc_ready_scan(struct socket * so,struct mbuf * m,int count,int * errorp)2641 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
2642 {
2643 	struct mbuf *mb;
2644 	struct sockbuf *sb;
2645 
2646 	SOCK_LOCK(so);
2647 	if (SOLISTENING(so)) {
2648 		SOCK_UNLOCK(so);
2649 		return (false);
2650 	}
2651 	mb = NULL;
2652 	sb = &so->so_rcv;
2653 	SOCK_RECVBUF_LOCK(so);
2654 	if (sb->uxst_fnrdy != NULL) {
2655 		STAILQ_FOREACH(mb, &sb->uxst_mbq, m_stailq) {
2656 			if (mb == m) {
2657 				*errorp = uipc_sbready(sb, m, count);
2658 				break;
2659 			}
2660 		}
2661 	}
2662 	SOCK_RECVBUF_UNLOCK(so);
2663 	SOCK_UNLOCK(so);
2664 	return (mb != NULL);
2665 }
2666 
2667 static int
uipc_ready(struct socket * so,struct mbuf * m,int count)2668 uipc_ready(struct socket *so, struct mbuf *m, int count)
2669 {
2670 	struct unpcb *unp, *unp2;
2671 	int error;
2672 
2673 	MPASS(so->so_type == SOCK_STREAM);
2674 
2675 	if (__predict_true(uipc_lock_peer(so, &unp2) == 0)) {
2676 		struct socket *so2;
2677 		struct sockbuf *sb;
2678 
2679 		so2 = unp2->unp_socket;
2680 		sb = &so2->so_rcv;
2681 		SOCK_RECVBUF_LOCK(so2);
2682 		UNP_PCB_UNLOCK(unp2);
2683 		UIPC_STREAM_SBCHECK(sb);
2684 		error = uipc_sbready(sb, m, count);
2685 		UIPC_STREAM_SBCHECK(sb);
2686 		if (error == 0)
2687 			sorwakeup_locked(so2);
2688 		else
2689 			SOCK_RECVBUF_UNLOCK(so2);
2690 	} else {
2691 		/*
2692 		 * The receiving socket has been disconnected, but may still
2693 		 * be valid.  In this case, the not-ready mbufs are still
2694 		 * present in its socket buffer, so perform an exhaustive
2695 		 * search before giving up and freeing the mbufs.
2696 		 */
2697 		UNP_LINK_RLOCK();
2698 		LIST_FOREACH(unp, &unp_shead, unp_link) {
2699 			if (uipc_ready_scan(unp->unp_socket, m, count, &error))
2700 				break;
2701 		}
2702 		UNP_LINK_RUNLOCK();
2703 
2704 		if (unp == NULL) {
2705 			for (int i = 0; i < count; i++)
2706 				m = m_free(m);
2707 			return (ECONNRESET);
2708 		}
2709 	}
2710 	return (error);
2711 }
2712 
2713 static int
uipc_sense(struct socket * so,struct stat * sb)2714 uipc_sense(struct socket *so, struct stat *sb)
2715 {
2716 	struct unpcb *unp;
2717 
2718 	unp = sotounpcb(so);
2719 	KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
2720 
2721 	sb->st_blksize = so->so_snd.sb_hiwat;
2722 	sb->st_dev = NODEV;
2723 	sb->st_ino = unp->unp_ino;
2724 	return (0);
2725 }
2726 
2727 static int
uipc_shutdown(struct socket * so,enum shutdown_how how)2728 uipc_shutdown(struct socket *so, enum shutdown_how how)
2729 {
2730 	struct unpcb *unp = sotounpcb(so);
2731 	int error;
2732 
2733 	SOCK_LOCK(so);
2734 	if (SOLISTENING(so)) {
2735 		if (how != SHUT_WR) {
2736 			so->so_error = ECONNABORTED;
2737 			solisten_wakeup(so);    /* unlocks so */
2738 		} else
2739 			SOCK_UNLOCK(so);
2740 		return (ENOTCONN);
2741 	} else if ((so->so_state &
2742 	    (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2743 		/*
2744 		 * POSIX mandates us to just return ENOTCONN when shutdown(2) is
2745 		 * invoked on a datagram sockets, however historically we would
2746 		 * actually tear socket down.  This is known to be leveraged by
2747 		 * some applications to unblock process waiting in recv(2) by
2748 		 * other process that it shares that socket with.  Try to meet
2749 		 * both backward-compatibility and POSIX requirements by forcing
2750 		 * ENOTCONN but still flushing buffers and performing wakeup(9).
2751 		 *
2752 		 * XXXGL: it remains unknown what applications expect this
2753 		 * behavior and is this isolated to unix/dgram or inet/dgram or
2754 		 * both.  See: D10351, D3039.
2755 		 */
2756 		error = ENOTCONN;
2757 		if (so->so_type != SOCK_DGRAM) {
2758 			SOCK_UNLOCK(so);
2759 			return (error);
2760 		}
2761 	} else
2762 		error = 0;
2763 	SOCK_UNLOCK(so);
2764 
2765 	switch (how) {
2766 	case SHUT_RD:
2767 		if (so->so_type == SOCK_DGRAM)
2768 			socantrcvmore(so);
2769 		else
2770 			uipc_cantrcvmore(so);
2771 		unp_dispose(so);
2772 		break;
2773 	case SHUT_RDWR:
2774 		if (so->so_type == SOCK_DGRAM)
2775 			socantrcvmore(so);
2776 		else
2777 			uipc_cantrcvmore(so);
2778 		unp_dispose(so);
2779 		/* FALLTHROUGH */
2780 	case SHUT_WR:
2781 		if (so->so_type == SOCK_DGRAM) {
2782 			socantsendmore(so);
2783 		} else {
2784 			UNP_PCB_LOCK(unp);
2785 			if (unp->unp_conn != NULL)
2786 				uipc_cantrcvmore(unp->unp_conn->unp_socket);
2787 			UNP_PCB_UNLOCK(unp);
2788 		}
2789 	}
2790 	wakeup(&so->so_timeo);
2791 
2792 	return (error);
2793 }
2794 
2795 static int
uipc_sockaddr(struct socket * so,struct sockaddr * ret)2796 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
2797 {
2798 	struct unpcb *unp;
2799 	const struct sockaddr *sa;
2800 
2801 	unp = sotounpcb(so);
2802 	KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
2803 
2804 	UNP_PCB_LOCK(unp);
2805 	if (unp->unp_addr != NULL)
2806 		sa = (struct sockaddr *) unp->unp_addr;
2807 	else
2808 		sa = &sun_noname;
2809 	bcopy(sa, ret, sa->sa_len);
2810 	UNP_PCB_UNLOCK(unp);
2811 	return (0);
2812 }
2813 
2814 static int
uipc_ctloutput(struct socket * so,struct sockopt * sopt)2815 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
2816 {
2817 	struct unpcb *unp;
2818 	struct xucred xu;
2819 	int error, optval;
2820 
2821 	if (sopt->sopt_level != SOL_LOCAL)
2822 		return (EINVAL);
2823 
2824 	unp = sotounpcb(so);
2825 	KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
2826 	error = 0;
2827 	switch (sopt->sopt_dir) {
2828 	case SOPT_GET:
2829 		switch (sopt->sopt_name) {
2830 		case LOCAL_PEERCRED:
2831 			UNP_PCB_LOCK(unp);
2832 			if (unp->unp_flags & UNP_HAVEPC)
2833 				xu = unp->unp_peercred;
2834 			else {
2835 				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2836 					error = ENOTCONN;
2837 				else
2838 					error = EINVAL;
2839 			}
2840 			UNP_PCB_UNLOCK(unp);
2841 			if (error != 0)
2842 				break;
2843 #ifdef COMPAT_FREEBSD32
2844 			if (sopt->sopt_td &&
2845 			    SV_PROC_FLAG(sopt->sopt_td->td_proc, SV_ILP32))
2846 			{
2847 				struct xucred32 xu32 = {};
2848 				int i;
2849 
2850 				xu32.cr_version = xu.cr_version;
2851 				xu32.cr_uid = xu.cr_uid;
2852 				xu32.cr_ngroups = xu.cr_ngroups;
2853 				for (i = 0; i < XU_NGROUPS; i++)
2854 					xu32.cr_groups[i] = xu.cr_groups[i];
2855 				xu32.cr_pid = xu.cr_pid;
2856 				error = sooptcopyout(sopt, &xu32, sizeof(xu32));
2857 				break;
2858 			}
2859 #endif
2860 			error = sooptcopyout(sopt, &xu, sizeof(xu));
2861 			break;
2862 
2863 		case LOCAL_CREDS:
2864 			/* Unlocked read. */
2865 			optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
2866 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2867 			break;
2868 
2869 		case LOCAL_CREDS_PERSISTENT:
2870 			/* Unlocked read. */
2871 			optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
2872 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2873 			break;
2874 
2875 		default:
2876 			error = EOPNOTSUPP;
2877 			break;
2878 		}
2879 		break;
2880 
2881 	case SOPT_SET:
2882 		switch (sopt->sopt_name) {
2883 		case LOCAL_CREDS:
2884 		case LOCAL_CREDS_PERSISTENT:
2885 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2886 					    sizeof(optval));
2887 			if (error)
2888 				break;
2889 
2890 #define	OPTSET(bit, exclusive) do {					\
2891 	UNP_PCB_LOCK(unp);						\
2892 	if (optval) {							\
2893 		if ((unp->unp_flags & (exclusive)) != 0) {		\
2894 			UNP_PCB_UNLOCK(unp);				\
2895 			error = EINVAL;					\
2896 			break;						\
2897 		}							\
2898 		unp->unp_flags |= (bit);				\
2899 	} else								\
2900 		unp->unp_flags &= ~(bit);				\
2901 	UNP_PCB_UNLOCK(unp);						\
2902 } while (0)
2903 
2904 			switch (sopt->sopt_name) {
2905 			case LOCAL_CREDS:
2906 				OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
2907 				break;
2908 
2909 			case LOCAL_CREDS_PERSISTENT:
2910 				OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
2911 				break;
2912 
2913 			default:
2914 				break;
2915 			}
2916 			break;
2917 #undef	OPTSET
2918 		default:
2919 			error = ENOPROTOOPT;
2920 			break;
2921 		}
2922 		break;
2923 
2924 	default:
2925 		error = EOPNOTSUPP;
2926 		break;
2927 	}
2928 	return (error);
2929 }
2930 
2931 /*
2932  * Connect socket 'so' to the unix-domain peer named by the 'len'-byte 'path'
2933  * (an empty path names the peer directly by descriptor), resolved relative to
2934  * descriptor 'fd' (AT_FDCWD for connect(2)).
2935  *
2936  * 'referenced_peerp' selects how the peer is returned.  If NULL, on exit the
2937  * peer's PCB is unlocked and the peer is unreferenced, symmetrically releasing
2938  * the resources acquired within the function.  If non-NULL, the peer's PCB is
2939  * returned locked and '*referenced_peerp' receives the referenced peer socket;
2940  * the caller is then responsible for first unlocking the peer's PCB and
2941  * afterwards releasing the socket.
2942  *
2943  * The reference is handed back rather than released in the return-unlocked
2944  * case, because releasing the last one under the PCB lock could cause
2945  * uipc_close() to try to re-acquire that lock.
2946  *
2947  * Note: the referenced_peerp mechanism is here only for the datagram fast-send
2948  * path, which enqueues under the peer's PCB lock.
2949  */
2950 static int
unp_connectat(int fd,struct socket * so,const char * path,int len,struct thread * td,struct socket ** referenced_peerp)2951 unp_connectat(int fd, struct socket *so, const char *path, int len,
2952     struct thread *td, struct socket **referenced_peerp)
2953 {
2954 	struct socket *so2;
2955 	struct unpcb *unp;
2956 	char buf[SOCK_MAXADDRLEN];
2957 	struct sockaddr *sa;
2958 	struct mtx *mtxp;
2959 	struct vnode *vp;
2960 	int error;
2961 	bool connreq;
2962 
2963 	CURVNET_ASSERT_SET();
2964 
2965 	bcopy(path, buf, len);
2966 	buf[len] = 0;
2967 
2968 	error = 0;
2969 	unp = sotounpcb(so);
2970 	UNP_PCB_LOCK(unp);
2971 	for (;;) {
2972 		/*
2973 		 * Wait for connection state to stabilize.  If a connection
2974 		 * already exists, give up.  For datagram sockets, which permit
2975 		 * multiple consecutive connect(2) calls, upper layers are
2976 		 * responsible for disconnecting in advance of a subsequent
2977 		 * connect(2), but this is not synchronized with PCB connection
2978 		 * state.
2979 		 *
2980 		 * Also make sure that no threads are currently attempting to
2981 		 * lock the peer socket, to ensure that unp_conn cannot
2982 		 * transition between two valid sockets while locks are dropped.
2983 		 */
2984 		if (SOLISTENING(so))
2985 			error = EOPNOTSUPP;
2986 		else if (unp->unp_conn != NULL)
2987 			error = EISCONN;
2988 		else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
2989 			error = EALREADY;
2990 		}
2991 		if (error != 0) {
2992 			UNP_PCB_UNLOCK(unp);
2993 			return (error);
2994 		}
2995 		if (unp->unp_pairbusy > 0) {
2996 			unp->unp_flags |= UNP_WAITING;
2997 			mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
2998 			continue;
2999 		}
3000 		break;
3001 	}
3002 	unp->unp_flags |= UNP_CONNECTING;
3003 	UNP_PCB_UNLOCK(unp);
3004 
3005 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
3006 	if (connreq)
3007 		sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
3008 	else
3009 		sa = NULL;
3010 
3011 	/*
3012 	 * Find the peer socket we're connecting to, and connect to it.
3013 	 *
3014 	 * If the peer is bound to a name in the filesystem, then we hold
3015 	 * the vnode pool lock until the connection is established, so as to
3016 	 * avoid racing with a close of the peer listening socket.  If the peer
3017 	 * is referenced by a file descriptor, then that reference prevents the
3018 	 * race, so no extra synchronization is needed.
3019 	 */
3020 	error = unp_connectat_peer(td, fd, buf, &so2, &mtxp, &vp);
3021 	if (error == 0) {
3022 		error = unp_connect_peer(so, sotounpcb(so2), &sa, td,
3023 		    referenced_peerp != NULL);
3024 		if (error == 0 && referenced_peerp != NULL) {
3025 			*referenced_peerp = so2;
3026 			so2 = NULL;
3027 		}
3028 
3029 		/*
3030 		 * Release references only after the pool lock is dropped in
3031 		 * order to avoid potential lock ordering issues.
3032 		 */
3033 		if (mtxp != NULL) {
3034 			mtx_unlock(mtxp);
3035 			vput(vp);
3036 		}
3037 		if (so2 != NULL)
3038 			sorele(so2);
3039 	}
3040 
3041 	free(sa, M_SONAME);
3042 	if (__predict_false(error)) {
3043 		UNP_PCB_LOCK(unp);
3044 		KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
3045 		    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
3046 		unp->unp_flags &= ~UNP_CONNECTING;
3047 		UNP_PCB_UNLOCK(unp);
3048 	}
3049 	return (error);
3050 }
3051 
3052 /*
3053  * Resolve descriptor 'fd' to the referenced unix-domain socket it *is* (as
3054  * opposed to one it names through the file system) in '*so2p'.  Returns
3055  * ENOTSOCK if 'fd' is not a socket -- letting an empty-path caller fall back to
3056  * a vnode lookup -- or EPROTOTYPE if it is a socket of another domain.  The
3057  * caller must release the returned socket with sorele().
3058  */
3059 static int
unp_socket_fd_peer(struct thread * td,int fd,struct socket ** so2p)3060 unp_socket_fd_peer(struct thread *td, int fd, struct socket **so2p)
3061 {
3062 	struct socket *so2;
3063 	struct file *fp;
3064 	cap_rights_t rights;
3065 	int error;
3066 
3067 	error = getsock(td, fd, cap_rights_init_one(&rights, CAP_CONNECTAT),
3068 	    &fp);
3069 	if (error != 0)
3070 		return (error);
3071 	so2 = fp->f_data;
3072 	if (so2->so_proto->pr_domain->dom_family != AF_UNIX)
3073 		error = EPROTOTYPE;
3074 	else {
3075 		soref(so2);
3076 		*so2p = so2;
3077 	}
3078 	fdrop(fp, td);
3079 	return (error);
3080 }
3081 
3082 /*
3083  * Resolve a synthetic descriptor vnode -- as fdescfs fabricates for a /dev/fd/N
3084  * path -- to the peer socket named by the descriptor it stands for.
3085  *
3086  * Such a node has no object of its own; VOP_OPEN reports the underlying
3087  * descriptor in td_dupfd and fails with ENODEV, the same convention open(2)
3088  * follows via dupfdopen() for /dev/fd.  We honour it here and resolve that
3089  * descriptor as the peer, so a plain connect(2) to /dev/fd/N reaches the
3090  * socket.  Consumes the vnode reference.
3091  */
3092 static int
unp_dupfd_peer(struct vnode * vp,struct thread * td,struct socket ** so2p)3093 unp_dupfd_peer(struct vnode *vp, struct thread *td, struct socket **so2p)
3094 {
3095 	int dupfd, error;
3096 
3097 	ASSERT_VOP_LOCKED(vp, __func__);
3098 
3099 	td->td_dupfd = -1;
3100 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
3101 	dupfd = td->td_dupfd;
3102 	td->td_dupfd = 0;
3103 	if (error == ENODEV && dupfd >= 0) {
3104 		error = unp_socket_fd_peer(td, dupfd, so2p);
3105 	} else if (error == 0) {
3106 		/* Not the dupfd convention: an openable node is not a peer. */
3107 		(void)VOP_CLOSE(vp, FREAD, td->td_ucred, td);
3108 		error = ECONNREFUSED;
3109 	}
3110 	vput(vp);
3111 	return (error);
3112 }
3113 
3114 /*
3115  * Resolve a connectat(2) target -- descriptor 'fd' together with the pathname
3116  * in 'buf' (null when len == 0) -- to a referenced peer unix socket in
3117  * '*so2p', covering all four ways a peer can be named:
3118  *
3119  *	empty path + socket fd		the descriptor is the peer socket
3120  *	empty path + O_PATH vnode	EMPTYPATH resolves the socket's vnode
3121  *	/dev/fd/N pathname		fdescfs names a descriptor
3122  *	ordinary pathname		a bound socket looked up by path
3123  *
3124  * The caller must release the returned socket with sorele().  If the mutex
3125  * and vnode pointers are filled, they must be released as well.
3126  */
3127 static int
unp_connectat_peer(struct thread * td,int fd,const char * buf,struct socket ** so2p,struct mtx ** mtxp,struct vnode ** vpp)3128 unp_connectat_peer(struct thread *td, int fd, const char *buf,
3129     struct socket **so2p, struct mtx **mtxp, struct vnode **vpp)
3130 {
3131 	struct nameidata nd;
3132 	cap_rights_t rights;
3133 	int error;
3134 
3135 	*so2p = NULL;
3136 	*mtxp = NULL;
3137 	*vpp = NULL;
3138 
3139 	/*
3140 	 * An empty sun_path means 'fd' names the peer directly.  If it is a
3141 	 * socket, it is the peer, so return success (or its error) with no
3142 	 * fallback; if not, it may be an O_PATH handle for a bound socket's
3143 	 * vnode, so fall through to an EMPTYPATH lookup.
3144 	 */
3145 	if (*buf == '\0' && fd != AT_FDCWD) {
3146 		error = unp_socket_fd_peer(td, fd, so2p);
3147 		if (error != ENOTSOCK)
3148 			return (error);
3149 	}
3150 
3151 	/* Resolve the path to a vnode. */
3152 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF |
3153 	    (fd == AT_FDCWD ? 0 : EMPTYPATH), UIO_SYSSPACE, buf, fd,
3154 	    cap_rights_init_one(&rights, CAP_CONNECTAT));
3155 	error = namei(&nd);
3156 	if (error != 0)
3157 		return (error);
3158 	NDFREE_PNBUF(&nd);
3159 
3160 	/*
3161 	 * Find our peer socket.  If it comes from a socket on the filesystem,
3162 	 * then we hold on to the vnode pool lock so as to interlock with a
3163 	 * close of the listening socket.  If the peer comes to us via an fd,
3164 	 * then the fd reference itself keeps the peer stable.
3165 	 *
3166 	 * A synthetic descriptor node -- as fdescfs fabricates for a /dev/fd/N
3167 	 * path -- carries no type of its own (VNON); opening it yields the
3168 	 * descriptor it stands for, which we resolve as the peer socket.
3169 	 * Otherwise the path must name a bound socket's vnode (VSOCK), which
3170 	 * unp_vnode_peer() connects to, rejecting any other type with ENOTSOCK.
3171 	 *
3172 	 * unp_dupfd_peer() resolves that descriptor exactly once: if it is not
3173 	 * a socket the connect fails, so this does *not* recur through a chain
3174 	 * of O_PATH handles of /dev/fd nodes, which could be arbitrarily long.
3175 	 */
3176 	if (nd.ni_vp->v_type == VNON)
3177 		error = unp_dupfd_peer(nd.ni_vp, td, so2p);
3178 	else
3179 		error = unp_vnode_peer(nd.ni_vp, td, so2p, mtxp, vpp);
3180 	return (error);
3181 }
3182 
3183 /*
3184  * Resolve locked vnode 'vp' to the unix-domain socket it names and return a
3185  * referenced peer socket in '*so2p'.  As the connect(2)-time resolution, this
3186  * enforces the caller's authorization to reach the socket -- filesystem
3187  * permission (VOP_ACCESS) and MAC (mac_vnode_check_open) -- which bare readers
3188  * of the vnode->pcb binding, such as vfs_unp_reclaim(), deliberately skip.
3189  */
3190 static int
unp_vnode_peer(struct vnode * vp,struct thread * td,struct socket ** so2p,struct mtx ** mtxp,struct vnode ** vpp)3191 unp_vnode_peer(struct vnode *vp, struct thread *td, struct socket **so2p,
3192     struct mtx **mtxp, struct vnode **vpp)
3193 {
3194 	struct mtx *vplock;
3195 	struct unpcb *unp2;
3196 	int error;
3197 
3198 	ASSERT_VOP_LOCKED(vp, __func__);
3199 
3200 	if (vp->v_type != VSOCK) {
3201 		error = ENOTSOCK;
3202 		goto fail;
3203 	}
3204 #ifdef MAC
3205 	error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
3206 	if (error != 0)
3207 		goto fail;
3208 #endif
3209 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
3210 	if (error != 0)
3211 		goto fail;
3212 
3213 	vplock = mtx_pool_find(unp_vp_mtxpool, vp);
3214 	mtx_lock(vplock);
3215 	VOP_UNP_CONNECT(vp, &unp2);
3216 	if (unp2 == NULL) {
3217 		mtx_unlock(vplock);
3218 		error = ECONNREFUSED;
3219 		goto fail;
3220 	}
3221 	soref(*so2p = unp2->unp_socket);
3222 	*mtxp = vplock;
3223 	*vpp = vp;
3224 	return (0);
3225 
3226 fail:
3227 	vput(vp);
3228 	return (error);
3229 }
3230 
3231 /*
3232  * Second half of connecting a unix socket: 'so' is our connecting socket,
3233  * with UNP_CONNECTING set, and 'unp2' is the PCB of the peer named by the
3234  * caller, which must guarantee its stability (by holding a reference on the
3235  * peer socket, or the vnode lock plus unp_vp_mtxpool lock for a peer found
3236  * via VOP_UNP_CONNECT()).
3237  *
3238  * For connection-oriented sockets '*sap' points to a buffer to hold the
3239  * listener's address; it is consumed (set to NULL) if used.  On success
3240  * UNP_CONNECTING is cleared; on error the caller must clear it.
3241  */
3242 static int
unp_connect_peer(struct socket * so,struct unpcb * unp2,struct sockaddr ** sap,struct thread * td,bool return_locked)3243 unp_connect_peer(struct socket *so, struct unpcb *unp2, struct sockaddr **sap,
3244     struct thread *td, bool return_locked)
3245 {
3246 	struct socket *so2;
3247 	struct unpcb *unp, *unp3;
3248 	int error;
3249 	bool connreq;
3250 
3251 	unp = sotounpcb(so);
3252 	KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
3253 	connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
3254 
3255 	so2 = unp2->unp_socket;
3256 	if (so->so_type != so2->so_type)
3257 		return (EPROTOTYPE);
3258 	if (connreq) {
3259 		if (SOLISTENING(so2))
3260 			so2 = solisten_clone(so2);
3261 		else
3262 			so2 = NULL;
3263 		if (so2 == NULL)
3264 			return (ECONNREFUSED);
3265 		if ((error = uipc_attach(so2, 0, NULL)) != 0) {
3266 			sodealloc(so2);
3267 			return (error);
3268 		}
3269 		unp3 = sotounpcb(so2);
3270 		unp_pcb_lock_pair(unp2, unp3);
3271 		if (unp2->unp_addr != NULL) {
3272 			bcopy(unp2->unp_addr, *sap, unp2->unp_addr->sun_len);
3273 			unp3->unp_addr = (struct sockaddr_un *)*sap;
3274 			*sap = NULL;
3275 		}
3276 
3277 		unp_copy_peercred(td, unp3, unp, unp2);
3278 
3279 		UNP_PCB_UNLOCK(unp2);
3280 		unp2 = unp3;
3281 
3282 		/*
3283 		 * It is safe to block on the PCB lock here since unp2 is
3284 		 * nascent and cannot be connected to any other sockets.
3285 		 */
3286 		UNP_PCB_LOCK(unp);
3287 #ifdef MAC
3288 		mac_socketpeer_set_from_socket(so, so2);
3289 		mac_socketpeer_set_from_socket(so2, so);
3290 #endif
3291 	} else {
3292 		unp_pcb_lock_pair(unp, unp2);
3293 	}
3294 	KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
3295 	    sotounpcb(so2) == unp2,
3296 	    ("%s: unp2 %p so2 %p", __func__, unp2, so2));
3297 	unp_connect2(so, so2, connreq);
3298 	if (connreq)
3299 		(void)solisten_enqueue(so2, SS_ISCONNECTED);
3300 	KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
3301 	    ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
3302 	unp->unp_flags &= ~UNP_CONNECTING;
3303 	if (!return_locked)
3304 		unp_pcb_unlock_pair(unp, unp2);
3305 	return (0);
3306 }
3307 
3308 /*
3309  * Set socket peer credentials at connection time.
3310  *
3311  * The client's PCB credentials are copied from its process structure.  The
3312  * server's PCB credentials are copied from the socket on which it called
3313  * listen(2).  uipc_listen cached that process's credentials at the time.
3314  */
3315 void
unp_copy_peercred(struct thread * td,struct unpcb * client_unp,struct unpcb * server_unp,struct unpcb * listen_unp)3316 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
3317     struct unpcb *server_unp, struct unpcb *listen_unp)
3318 {
3319 	cru2xt(td, &client_unp->unp_peercred);
3320 	client_unp->unp_flags |= UNP_HAVEPC;
3321 
3322 	memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
3323 	    sizeof(server_unp->unp_peercred));
3324 	server_unp->unp_flags |= UNP_HAVEPC;
3325 	client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
3326 }
3327 
3328 /*
3329  * unix/stream & unix/seqpacket version of soisconnected().
3330  *
3331  * The crucial thing we are doing here is setting up the uxst_peer linkage,
3332  * holding unp and receive buffer locks of the both sockets.  The disconnect
3333  * procedure does the same.  This gives as a safe way to access the peer in the
3334  * send(2) and recv(2) during the socket lifetime.
3335  *
3336  * The less important thing is event notification of the fact that a socket is
3337  * now connected.  It is unusual for a software to put a socket into event
3338  * mechanism before connect(2), but is supposed to be supported.  Note that
3339  * there can not be any sleeping I/O on the socket, yet, only presence in the
3340  * select/poll/kevent.
3341  *
3342  * This function can be called via two call paths:
3343  * 1) socketpair(2) - in this case socket has not been yet reported to userland
3344  *    and just can't have any event notifications mechanisms set up.  The
3345  *    'wakeup' boolean is always false.
3346  * 2) connect(2) of existing socket to a recent clone of a listener:
3347  *   2.1) Socket that connect(2)s will have 'wakeup' true.  An application
3348  *        could have already put it into event mechanism, is it shall be
3349  *        reported as readable and as writable.
3350  *   2.2) Socket that was just cloned with solisten_clone().  Same as 1).
3351  */
3352 static void
unp_soisconnected(struct socket * so,bool wakeup)3353 unp_soisconnected(struct socket *so, bool wakeup)
3354 {
3355 	struct socket *so2 = sotounpcb(so)->unp_conn->unp_socket;
3356 	struct sockbuf *sb;
3357 
3358 	SOCK_LOCK_ASSERT(so);
3359 	UNP_PCB_LOCK_ASSERT(sotounpcb(so));
3360 	UNP_PCB_LOCK_ASSERT(sotounpcb(so2));
3361 	SOCK_RECVBUF_LOCK_ASSERT(so);
3362 	SOCK_RECVBUF_LOCK_ASSERT(so2);
3363 
3364 	MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3365 	MPASS((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
3366 	    SS_ISDISCONNECTING)) == 0);
3367 	MPASS(so->so_qstate == SQ_NONE);
3368 
3369 	so->so_state &= ~SS_ISDISCONNECTED;
3370 	so->so_state |= SS_ISCONNECTED;
3371 
3372 	sb = &so2->so_rcv;
3373 	sb->uxst_peer = so;
3374 
3375 	if (wakeup) {
3376 		KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
3377 		sb = &so->so_rcv;
3378 		selwakeuppri(sb->sb_sel, PSOCK);
3379 		SOCK_SENDBUF_LOCK_ASSERT(so);
3380 		sb = &so->so_snd;
3381 		selwakeuppri(sb->sb_sel, PSOCK);
3382 		SOCK_SENDBUF_UNLOCK(so);
3383 	}
3384 }
3385 
3386 static void
unp_connect2(struct socket * so,struct socket * so2,bool wakeup)3387 unp_connect2(struct socket *so, struct socket *so2, bool wakeup)
3388 {
3389 	struct unpcb *unp;
3390 	struct unpcb *unp2;
3391 
3392 	MPASS(so2->so_type == so->so_type);
3393 	unp = sotounpcb(so);
3394 	KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
3395 	unp2 = sotounpcb(so2);
3396 	KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
3397 
3398 	UNP_PCB_LOCK_ASSERT(unp);
3399 	UNP_PCB_LOCK_ASSERT(unp2);
3400 	KASSERT(unp->unp_conn == NULL,
3401 	    ("%s: socket %p is already connected", __func__, unp));
3402 
3403 	unp->unp_conn = unp2;
3404 	unp_pcb_hold(unp2);
3405 	unp_pcb_hold(unp);
3406 	switch (so->so_type) {
3407 	case SOCK_DGRAM:
3408 		UNP_REF_LIST_LOCK();
3409 		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
3410 		UNP_REF_LIST_UNLOCK();
3411 		soisconnected(so);
3412 		break;
3413 
3414 	case SOCK_STREAM:
3415 	case SOCK_SEQPACKET:
3416 		KASSERT(unp2->unp_conn == NULL,
3417 		    ("%s: socket %p is already connected", __func__, unp2));
3418 		unp2->unp_conn = unp;
3419 		SOCK_LOCK(so);
3420 		SOCK_LOCK(so2);
3421 		if (wakeup)	/* Avoid LOR with receive buffer lock. */
3422 			SOCK_SENDBUF_LOCK(so);
3423 		SOCK_RECVBUF_LOCK(so);
3424 		SOCK_RECVBUF_LOCK(so2);
3425 		unp_soisconnected(so, wakeup);	/* Will unlock send buffer. */
3426 		unp_soisconnected(so2, false);
3427 		SOCK_RECVBUF_UNLOCK(so);
3428 		SOCK_RECVBUF_UNLOCK(so2);
3429 		SOCK_UNLOCK(so);
3430 		SOCK_UNLOCK(so2);
3431 		break;
3432 
3433 	default:
3434 		panic("unp_connect2");
3435 	}
3436 }
3437 
3438 static void
unp_soisdisconnected(struct socket * so)3439 unp_soisdisconnected(struct socket *so)
3440 {
3441 	SOCK_LOCK_ASSERT(so);
3442 	SOCK_RECVBUF_LOCK_ASSERT(so);
3443 	MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3444 	MPASS(!SOLISTENING(so));
3445 	MPASS((so->so_state & (SS_ISCONNECTING | SS_ISDISCONNECTING |
3446 	    SS_ISDISCONNECTED)) == 0);
3447 	MPASS(so->so_state & SS_ISCONNECTED);
3448 
3449 	so->so_state |= SS_ISDISCONNECTED;
3450 	so->so_state &= ~SS_ISCONNECTED;
3451 	so->so_rcv.uxst_peer = NULL;
3452 	selwakeuppri(&so->so_wrsel, PSOCK);
3453 	KNOTE_LOCKED(&so->so_snd.sb_sel->si_note, 0);
3454 	socantrcvmore_locked(so);
3455 }
3456 
3457 static void
unp_disconnect(struct unpcb * unp,struct unpcb * unp2)3458 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
3459 {
3460 	struct socket *so, *so2;
3461 	struct mbuf *m = NULL;
3462 #ifdef INVARIANTS
3463 	struct unpcb *unptmp;
3464 #endif
3465 
3466 	UNP_PCB_LOCK_ASSERT(unp);
3467 	UNP_PCB_LOCK_ASSERT(unp2);
3468 	KASSERT(unp->unp_conn == unp2,
3469 	    ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
3470 
3471 	unp->unp_conn = NULL;
3472 	so = unp->unp_socket;
3473 	so2 = unp2->unp_socket;
3474 	switch (unp->unp_socket->so_type) {
3475 	case SOCK_DGRAM:
3476 		/*
3477 		 * Remove our send socket buffer from the peer's receive buffer.
3478 		 * Move the data to the receive buffer only if it is empty.
3479 		 * This is a protection against a scenario where a peer
3480 		 * connects, floods and disconnects, effectively blocking
3481 		 * sendto() from unconnected sockets.
3482 		 */
3483 		SOCK_RECVBUF_LOCK(so2);
3484 		if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
3485 			TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
3486 			    uxdg_clist);
3487 			if (__predict_true((so2->so_rcv.sb_state &
3488 			    SBS_CANTRCVMORE) == 0) &&
3489 			    STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
3490 				STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
3491 				    &so->so_snd.uxdg_mb);
3492 				so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
3493 				so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
3494 				so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
3495 			} else {
3496 				m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
3497 				STAILQ_INIT(&so->so_snd.uxdg_mb);
3498 				so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
3499 				so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
3500 				so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
3501 				so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
3502 			}
3503 			/* Note: so may reconnect. */
3504 			so->so_snd.uxdg_cc = 0;
3505 			so->so_snd.uxdg_ctl = 0;
3506 			so->so_snd.uxdg_mbcnt = 0;
3507 		}
3508 		SOCK_RECVBUF_UNLOCK(so2);
3509 		UNP_REF_LIST_LOCK();
3510 #ifdef INVARIANTS
3511 		LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
3512 			if (unptmp == unp)
3513 				break;
3514 		}
3515 		KASSERT(unptmp != NULL,
3516 		    ("%s: %p not found in reflist of %p", __func__, unp, unp2));
3517 #endif
3518 		LIST_REMOVE(unp, unp_reflink);
3519 		UNP_REF_LIST_UNLOCK();
3520 		SOCK_LOCK(so);
3521 		so->so_state &= ~SS_ISCONNECTED;
3522 		SOCK_UNLOCK(so);
3523 		break;
3524 
3525 	case SOCK_STREAM:
3526 	case SOCK_SEQPACKET:
3527 		SOCK_LOCK(so);
3528 		SOCK_LOCK(so2);
3529 		SOCK_RECVBUF_LOCK(so);
3530 		SOCK_RECVBUF_LOCK(so2);
3531 		unp_soisdisconnected(so);
3532 		MPASS(unp2->unp_conn == unp);
3533 		unp2->unp_conn = NULL;
3534 		unp_soisdisconnected(so2);
3535 		SOCK_UNLOCK(so);
3536 		SOCK_UNLOCK(so2);
3537 		break;
3538 	}
3539 
3540 	if (unp == unp2) {
3541 		unp_pcb_rele_notlast(unp);
3542 		if (!unp_pcb_rele(unp))
3543 			UNP_PCB_UNLOCK(unp);
3544 	} else {
3545 		if (!unp_pcb_rele(unp))
3546 			UNP_PCB_UNLOCK(unp);
3547 		if (!unp_pcb_rele(unp2))
3548 			UNP_PCB_UNLOCK(unp2);
3549 	}
3550 
3551 	if (m != NULL) {
3552 		unp_scan(m, unp_freerights);
3553 		m_freemp(m);
3554 	}
3555 }
3556 
3557 /*
3558  * unp_pcblist() walks the global list of struct unpcb's to generate a
3559  * pointer list, bumping the refcount on each unpcb.  It then copies them out
3560  * sequentially, validating the generation number on each to see if it has
3561  * been detached.  All of this is necessary because copyout() may sleep on
3562  * disk I/O.
3563  */
3564 static int
unp_pcblist(SYSCTL_HANDLER_ARGS)3565 unp_pcblist(SYSCTL_HANDLER_ARGS)
3566 {
3567 	struct unpcb *unp, **unp_list;
3568 	unp_gen_t gencnt;
3569 	struct xunpgen *xug;
3570 	struct unp_head *head;
3571 	struct xunpcb *xu;
3572 	u_int i;
3573 	int error, n;
3574 
3575 	switch ((intptr_t)arg1) {
3576 	case SOCK_STREAM:
3577 		head = &unp_shead;
3578 		break;
3579 
3580 	case SOCK_DGRAM:
3581 		head = &unp_dhead;
3582 		break;
3583 
3584 	case SOCK_SEQPACKET:
3585 		head = &unp_sphead;
3586 		break;
3587 
3588 	default:
3589 		panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
3590 	}
3591 
3592 	/*
3593 	 * The process of preparing the PCB list is too time-consuming and
3594 	 * resource-intensive to repeat twice on every request.
3595 	 */
3596 	if (req->oldptr == NULL) {
3597 		n = unp_count;
3598 		req->oldidx = 2 * (sizeof *xug)
3599 			+ (n + n/8) * sizeof(struct xunpcb);
3600 		return (0);
3601 	}
3602 
3603 	if (req->newptr != NULL)
3604 		return (EPERM);
3605 
3606 	/*
3607 	 * OK, now we're committed to doing something.
3608 	 */
3609 	xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
3610 	UNP_LINK_RLOCK();
3611 	gencnt = unp_gencnt;
3612 	n = unp_count;
3613 	UNP_LINK_RUNLOCK();
3614 
3615 	xug->xug_len = sizeof *xug;
3616 	xug->xug_count = n;
3617 	xug->xug_gen = gencnt;
3618 	xug->xug_sogen = so_gencnt;
3619 	error = SYSCTL_OUT(req, xug, sizeof *xug);
3620 	if (error) {
3621 		free(xug, M_TEMP);
3622 		return (error);
3623 	}
3624 
3625 	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
3626 
3627 	UNP_LINK_RLOCK();
3628 	for (unp = LIST_FIRST(head), i = 0; unp && i < n;
3629 	     unp = LIST_NEXT(unp, unp_link)) {
3630 		UNP_PCB_LOCK(unp);
3631 		if (unp->unp_gencnt <= gencnt) {
3632 			if (cr_cansee(req->td->td_ucred,
3633 			    unp->unp_socket->so_cred)) {
3634 				UNP_PCB_UNLOCK(unp);
3635 				continue;
3636 			}
3637 			unp_list[i++] = unp;
3638 			unp_pcb_hold(unp);
3639 		}
3640 		UNP_PCB_UNLOCK(unp);
3641 	}
3642 	UNP_LINK_RUNLOCK();
3643 	n = i;			/* In case we lost some during malloc. */
3644 
3645 	error = 0;
3646 	xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
3647 	for (i = 0; i < n; i++) {
3648 		unp = unp_list[i];
3649 		UNP_PCB_LOCK(unp);
3650 		if (unp_pcb_rele(unp))
3651 			continue;
3652 
3653 		if (unp->unp_gencnt <= gencnt) {
3654 			xu->xu_len = sizeof *xu;
3655 			xu->xu_unpp = (uintptr_t)unp;
3656 			/*
3657 			 * XXX - need more locking here to protect against
3658 			 * connect/disconnect races for SMP.
3659 			 */
3660 			if (unp->unp_addr != NULL)
3661 				bcopy(unp->unp_addr, &xu->xu_addr,
3662 				      unp->unp_addr->sun_len);
3663 			else
3664 				bzero(&xu->xu_addr, sizeof(xu->xu_addr));
3665 			if (unp->unp_conn != NULL &&
3666 			    unp->unp_conn->unp_addr != NULL)
3667 				bcopy(unp->unp_conn->unp_addr,
3668 				      &xu->xu_caddr,
3669 				      unp->unp_conn->unp_addr->sun_len);
3670 			else
3671 				bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
3672 			xu->unp_vnode = (uintptr_t)unp->unp_vnode;
3673 			xu->unp_conn = (uintptr_t)unp->unp_conn;
3674 			xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
3675 			xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
3676 			xu->unp_gencnt = unp->unp_gencnt;
3677 			sotoxsocket(unp->unp_socket, &xu->xu_socket);
3678 			UNP_PCB_UNLOCK(unp);
3679 			error = SYSCTL_OUT(req, xu, sizeof *xu);
3680 		} else {
3681 			UNP_PCB_UNLOCK(unp);
3682 		}
3683 	}
3684 	free(xu, M_TEMP);
3685 	if (!error) {
3686 		/*
3687 		 * Give the user an updated idea of our state.  If the
3688 		 * generation differs from what we told her before, she knows
3689 		 * that something happened while we were processing this
3690 		 * request, and it might be necessary to retry.
3691 		 */
3692 		xug->xug_gen = unp_gencnt;
3693 		xug->xug_sogen = so_gencnt;
3694 		xug->xug_count = unp_count;
3695 		error = SYSCTL_OUT(req, xug, sizeof *xug);
3696 	}
3697 	free(unp_list, M_TEMP);
3698 	free(xug, M_TEMP);
3699 	return (error);
3700 }
3701 
3702 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
3703     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3704     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
3705     "List of active local datagram sockets");
3706 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
3707     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3708     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
3709     "List of active local stream sockets");
3710 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
3711     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3712     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
3713     "List of active local seqpacket sockets");
3714 
3715 static void
unp_drop(struct unpcb * unp)3716 unp_drop(struct unpcb *unp)
3717 {
3718 	struct socket *so;
3719 	struct unpcb *unp2;
3720 
3721 	/*
3722 	 * Regardless of whether the socket's peer dropped the connection
3723 	 * with this socket by aborting or disconnecting, POSIX requires
3724 	 * that ECONNRESET is returned on next connected send(2) in case of
3725 	 * a SOCK_DGRAM socket and EPIPE for SOCK_STREAM.
3726 	 */
3727 	UNP_PCB_LOCK(unp);
3728 	if ((so = unp->unp_socket) != NULL)
3729 		so->so_error =
3730 		    so->so_proto->pr_type == SOCK_DGRAM ? ECONNRESET : EPIPE;
3731 	if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
3732 		/* Last reference dropped in unp_disconnect(). */
3733 		unp_pcb_rele_notlast(unp);
3734 		unp_disconnect(unp, unp2);
3735 	} else if (!unp_pcb_rele(unp)) {
3736 		UNP_PCB_UNLOCK(unp);
3737 	}
3738 }
3739 
3740 static void
unp_freerights(struct filedescent ** fdep,int fdcount)3741 unp_freerights(struct filedescent **fdep, int fdcount)
3742 {
3743 	struct file *fp;
3744 	int i;
3745 
3746 	KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
3747 
3748 	for (i = 0; i < fdcount; i++) {
3749 		fp = fdep[i]->fde_file;
3750 		filecaps_free(&fdep[i]->fde_caps);
3751 		unp_discard(fp);
3752 	}
3753 	free(fdep[0], M_FILECAPS);
3754 }
3755 
3756 /*
3757  * Flags to set on the receiving side when externalizing a file descriptor.
3758  * When transferring fds between jails, ensure that the receiver cannot use
3759  * a dirfd to escape the jail chroot.
3760  */
3761 static int
externalize_fdflags(struct filedescent * fde,struct thread * td)3762 externalize_fdflags(struct filedescent *fde, struct thread *td)
3763 {
3764 	struct prison *prison1, *prison2;
3765 
3766 	if ((fde->fde_flags & UF_RESOLVE_BENEATH) != 0)
3767 		return (O_RESOLVE_BENEATH);
3768 	prison1 = fde->fde_file->f_cred->cr_prison;
3769 	prison2 = td->td_ucred->cr_prison;
3770 	if (prison1 != prison2 && prison1->pr_root != prison2->pr_root &&
3771 	    prison2 != &prison0)
3772 		return (O_RESOLVE_BENEATH);
3773 	else
3774 		return (0);
3775 }
3776 
3777 static int
unp_externalize(const struct socket * so,struct mbuf * control,struct mbuf ** controlp,int flags)3778 unp_externalize(const struct socket *so, struct mbuf *control,
3779     struct mbuf **controlp, int flags)
3780 {
3781 	struct thread *td = curthread;		/* XXX */
3782 	struct cmsghdr *cm = mtod(control, struct cmsghdr *);
3783 	int *fdp;
3784 	struct filedesc *fdesc = td->td_proc->p_fd;
3785 	struct filedescent **fdep;
3786 	void *data;
3787 	socklen_t clen = control->m_len, datalen;
3788 	int error, fdflags, newfds;
3789 	u_int newlen;
3790 
3791 	UNP_LINK_UNLOCK_ASSERT();
3792 
3793 	fdflags = ((flags & MSG_CMSG_CLOEXEC) ? O_CLOEXEC : 0) |
3794 	    ((flags & MSG_CMSG_CLOFORK) ? O_CLOFORK : 0);
3795 
3796 	error = 0;
3797 	if (controlp != NULL) /* controlp == NULL => free control messages */
3798 		*controlp = NULL;
3799 	while (cm != NULL) {
3800 		MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
3801 
3802 		data = CMSG_DATA(cm);
3803 		datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
3804 		if (cm->cmsg_level == SOL_SOCKET
3805 		    && cm->cmsg_type == SCM_RIGHTS) {
3806 			newfds = datalen / sizeof(*fdep);
3807 			if (newfds == 0)
3808 				goto next;
3809 			fdep = data;
3810 
3811 			/*
3812 			 * If we're not outputting the descriptors, free them.
3813 			 *
3814 			 * In the case of having revoked SCM_PASSRIGHTS, the
3815 			 * receiver must have toggled it before trying to
3816 			 * receive control messages- we'll take that as a signal
3817 			 * that they didn't want these, but they raced against
3818 			 * the sender trying to pass files anyways.
3819 			 */
3820 			if (error || controlp == NULL ||
3821 			    (atomic_load_int(&so->so_options) &
3822 			    SO_PASSRIGHTS) == 0) {
3823 				unp_freerights(fdep, newfds);
3824 				goto next;
3825 			}
3826 			FILEDESC_XLOCK(fdesc);
3827 
3828 			/*
3829 			 * Now change each pointer to an fd in the global
3830 			 * table to an integer that is the index to the local
3831 			 * fd table entry that we set up to point to the
3832 			 * global one we are transferring.
3833 			 */
3834 			newlen = newfds * sizeof(int);
3835 			*controlp = sbcreatecontrol(NULL, newlen,
3836 			    SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
3837 
3838 			fdp = (int *)
3839 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *));
3840 			if ((error = fdallocn(td, 0, fdp, newfds))) {
3841 				FILEDESC_XUNLOCK(fdesc);
3842 				unp_freerights(fdep, newfds);
3843 				m_freem(*controlp);
3844 				*controlp = NULL;
3845 				goto next;
3846 			}
3847 			for (int i = 0; i < newfds; i++, fdp++) {
3848 				struct file *fp;
3849 
3850 				fp = fdep[i]->fde_file;
3851 				_finstall(fdesc, fp, *fdp,
3852 				    fdflags | externalize_fdflags(fdep[i], td),
3853 				    &fdep[i]->fde_caps);
3854 				unp_externalize_fp(fp);
3855 			}
3856 
3857 			/*
3858 			 * The new type indicates that the mbuf data refers to
3859 			 * kernel resources that may need to be released before
3860 			 * the mbuf is freed.
3861 			 */
3862 			m_chtype(*controlp, MT_EXTCONTROL);
3863 			FILEDESC_XUNLOCK(fdesc);
3864 			free(fdep[0], M_FILECAPS);
3865 		} else {
3866 			/* We can just copy anything else across. */
3867 			if (error || controlp == NULL)
3868 				goto next;
3869 			*controlp = sbcreatecontrol(NULL, datalen,
3870 			    cm->cmsg_type, cm->cmsg_level, M_WAITOK);
3871 			bcopy(data,
3872 			    CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
3873 			    datalen);
3874 		}
3875 		controlp = &(*controlp)->m_next;
3876 
3877 next:
3878 		if (CMSG_SPACE(datalen) < clen) {
3879 			clen -= CMSG_SPACE(datalen);
3880 			cm = (struct cmsghdr *)
3881 			    ((caddr_t)cm + CMSG_SPACE(datalen));
3882 		} else {
3883 			clen = 0;
3884 			cm = NULL;
3885 		}
3886 	}
3887 
3888 	return (error);
3889 }
3890 
3891 static void
unp_zone_change(void * tag)3892 unp_zone_change(void *tag)
3893 {
3894 
3895 	uma_zone_set_max(unp_zone, maxsockets);
3896 }
3897 
3898 #ifdef INVARIANTS
3899 static void
unp_zdtor(void * mem,int size __unused,void * arg __unused)3900 unp_zdtor(void *mem, int size __unused, void *arg __unused)
3901 {
3902 	struct unpcb *unp;
3903 
3904 	unp = mem;
3905 
3906 	KASSERT(LIST_EMPTY(&unp->unp_refs),
3907 	    ("%s: unpcb %p has lingering refs", __func__, unp));
3908 	KASSERT(unp->unp_socket == NULL,
3909 	    ("%s: unpcb %p has socket backpointer", __func__, unp));
3910 	KASSERT(unp->unp_vnode == NULL,
3911 	    ("%s: unpcb %p has vnode references", __func__, unp));
3912 	KASSERT(unp->unp_conn == NULL,
3913 	    ("%s: unpcb %p is still connected", __func__, unp));
3914 	KASSERT(unp->unp_addr == NULL,
3915 	    ("%s: unpcb %p has leaked addr", __func__, unp));
3916 }
3917 #endif
3918 
3919 static void
unp_init(void * arg __unused)3920 unp_init(void *arg __unused)
3921 {
3922 	uma_dtor dtor;
3923 
3924 #ifdef INVARIANTS
3925 	dtor = unp_zdtor;
3926 #else
3927 	dtor = NULL;
3928 #endif
3929 	unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
3930 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
3931 	uma_zone_set_max(unp_zone, maxsockets);
3932 	uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
3933 	EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
3934 	    NULL, EVENTHANDLER_PRI_ANY);
3935 	LIST_INIT(&unp_dhead);
3936 	LIST_INIT(&unp_shead);
3937 	LIST_INIT(&unp_sphead);
3938 	SLIST_INIT(&unp_defers);
3939 	TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
3940 	TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
3941 	UNP_LINK_LOCK_INIT();
3942 	UNP_DEFERRED_LOCK_INIT();
3943 	unp_vp_mtxpool = mtx_pool_create("unp vp mtxpool", 32, MTX_DEF);
3944 }
3945 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
3946 
3947 static void
unp_internalize_cleanup_rights(struct mbuf * control)3948 unp_internalize_cleanup_rights(struct mbuf *control)
3949 {
3950 	struct cmsghdr *cp;
3951 	struct mbuf *m;
3952 	void *data;
3953 	socklen_t datalen;
3954 
3955 	for (m = control; m != NULL; m = m->m_next) {
3956 		cp = mtod(m, struct cmsghdr *);
3957 		if (cp->cmsg_level != SOL_SOCKET ||
3958 		    cp->cmsg_type != SCM_RIGHTS)
3959 			continue;
3960 		data = CMSG_DATA(cp);
3961 		datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
3962 		unp_freerights(data, datalen / sizeof(struct filedesc *));
3963 	}
3964 }
3965 
3966 static int
unp_internalize(struct mbuf * control,struct mchain * mc,struct thread * td,int * needsopts)3967 unp_internalize(struct mbuf *control, struct mchain *mc, struct thread *td,
3968     int *needsopts)
3969 {
3970 	struct proc *p;
3971 	struct filedesc *fdesc;
3972 	struct bintime *bt;
3973 	struct cmsghdr *cm;
3974 	struct cmsgcred *cmcred;
3975 	struct mbuf *m;
3976 	struct filedescent *fde, **fdep, *fdev;
3977 	struct file *fp;
3978 	struct timeval *tv;
3979 	struct timespec *ts;
3980 	void *data;
3981 	socklen_t clen, datalen;
3982 	int i, j, error, *fdp, oldfds;
3983 	u_int newlen;
3984 
3985 	MPASS(control->m_next == NULL); /* COMPAT_OLDSOCK may violate */
3986 	UNP_LINK_UNLOCK_ASSERT();
3987 
3988 	p = td->td_proc;
3989 	fdesc = p->p_fd;
3990 	error = 0;
3991 	*mc = MCHAIN_INITIALIZER(mc);
3992 	for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
3993 	    data = CMSG_DATA(cm);
3994 
3995 	    clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
3996 	    clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
3997 	    (char *)cm + cm->cmsg_len >= (char *)data;
3998 
3999 	    clen -= min(CMSG_SPACE(datalen), clen),
4000 	    cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
4001 	    data = CMSG_DATA(cm)) {
4002 		datalen = (char *)cm + cm->cmsg_len - (char *)data;
4003 		switch (cm->cmsg_type) {
4004 		case SCM_CREDS:
4005 			m = sbcreatecontrol(NULL, sizeof(*cmcred), SCM_CREDS,
4006 			    SOL_SOCKET, M_WAITOK);
4007 			cmcred = (struct cmsgcred *)
4008 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4009 			cmcred->cmcred_pid = p->p_pid;
4010 			cmcred->cmcred_uid = td->td_ucred->cr_ruid;
4011 			cmcred->cmcred_gid = td->td_ucred->cr_rgid;
4012 			cmcred->cmcred_euid = td->td_ucred->cr_uid;
4013 			_Static_assert(CMGROUP_MAX >= 1,
4014 			    "Room needed for the effective GID.");
4015 			cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups + 1,
4016 			    CMGROUP_MAX);
4017 			cmcred->cmcred_groups[0] = td->td_ucred->cr_gid;
4018 			for (i = 1; i < cmcred->cmcred_ngroups; i++)
4019 				cmcred->cmcred_groups[i] =
4020 				    td->td_ucred->cr_groups[i - 1];
4021 			break;
4022 
4023 		case SCM_RIGHTS:
4024 			*needsopts |= SO_PASSRIGHTS;
4025 			oldfds = datalen / sizeof (int);
4026 			if (oldfds == 0)
4027 				continue;
4028 			/* On some machines sizeof pointer is bigger than
4029 			 * sizeof int, so we need to check if data fits into
4030 			 * single mbuf.  We could allocate several mbufs, and
4031 			 * unp_externalize() should even properly handle that.
4032 			 * But it is not worth to complicate the code for an
4033 			 * insane scenario of passing over 200 file descriptors
4034 			 * at once.
4035 			 */
4036 			newlen = oldfds * sizeof(fdep[0]);
4037 			if (CMSG_SPACE(newlen) > MCLBYTES) {
4038 				error = EMSGSIZE;
4039 				goto out;
4040 			}
4041 			/*
4042 			 * Check that all the FDs passed in refer to legal
4043 			 * files.  If not, reject the entire operation.
4044 			 */
4045 			fdp = data;
4046 			FILEDESC_SLOCK(fdesc);
4047 			for (i = 0; i < oldfds; i++, fdp++) {
4048 				fp = fget_noref(fdesc, *fdp);
4049 				if (fp == NULL) {
4050 					FILEDESC_SUNLOCK(fdesc);
4051 					error = EBADF;
4052 					goto out;
4053 				}
4054 				if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
4055 					FILEDESC_SUNLOCK(fdesc);
4056 					error = EOPNOTSUPP;
4057 					goto out;
4058 				}
4059 			}
4060 
4061 			/*
4062 			 * Now replace the integer FDs with pointers to the
4063 			 * file structure and capability rights.
4064 			 */
4065 			m = sbcreatecontrol(NULL, newlen, SCM_RIGHTS,
4066 			    SOL_SOCKET, M_WAITOK);
4067 			fdp = data;
4068 			for (i = 0; i < oldfds; i++, fdp++) {
4069 				if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
4070 					fdp = data;
4071 					for (j = 0; j < i; j++, fdp++) {
4072 						fdrop(fdesc->fd_ofiles[*fdp].
4073 						    fde_file, td);
4074 					}
4075 					FILEDESC_SUNLOCK(fdesc);
4076 					error = EBADF;
4077 					goto out;
4078 				}
4079 			}
4080 			fdp = data;
4081 			fdep = (struct filedescent **)
4082 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4083 			fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
4084 			    M_WAITOK);
4085 			for (i = 0; i < oldfds; i++, fdev++, fdp++) {
4086 				fde = &fdesc->fd_ofiles[*fdp];
4087 				fdep[i] = fdev;
4088 				fdep[i]->fde_file = fde->fde_file;
4089 				filecaps_copy(&fde->fde_caps,
4090 				    &fdep[i]->fde_caps, true);
4091 				fdep[i]->fde_flags = fde->fde_flags;
4092 				unp_internalize_fp(fdep[i]->fde_file);
4093 			}
4094 			FILEDESC_SUNLOCK(fdesc);
4095 			break;
4096 
4097 		case SCM_TIMESTAMP:
4098 			m = sbcreatecontrol(NULL, sizeof(*tv), SCM_TIMESTAMP,
4099 			    SOL_SOCKET, M_WAITOK);
4100 			tv = (struct timeval *)
4101 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4102 			microtime(tv);
4103 			break;
4104 
4105 		case SCM_BINTIME:
4106 			m = sbcreatecontrol(NULL, sizeof(*bt), SCM_BINTIME,
4107 			    SOL_SOCKET, M_WAITOK);
4108 			bt = (struct bintime *)
4109 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4110 			bintime(bt);
4111 			break;
4112 
4113 		case SCM_REALTIME:
4114 			m = sbcreatecontrol(NULL, sizeof(*ts), SCM_REALTIME,
4115 			    SOL_SOCKET, M_WAITOK);
4116 			ts = (struct timespec *)
4117 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4118 			nanotime(ts);
4119 			break;
4120 
4121 		case SCM_MONOTONIC:
4122 			m = sbcreatecontrol(NULL, sizeof(*ts), SCM_MONOTONIC,
4123 			    SOL_SOCKET, M_WAITOK);
4124 			ts = (struct timespec *)
4125 			    CMSG_DATA(mtod(m, struct cmsghdr *));
4126 			nanouptime(ts);
4127 			break;
4128 
4129 		default:
4130 			error = EINVAL;
4131 			goto out;
4132 		}
4133 
4134 		mc_append(mc, m);
4135 	}
4136 	if (clen > 0)
4137 		error = EINVAL;
4138 
4139 out:
4140 	if (error != 0)
4141 		unp_internalize_cleanup_rights(mc_first(mc));
4142 	m_freem(control);
4143 	return (error);
4144 }
4145 
4146 static void
unp_addsockcred(struct thread * td,struct mchain * mc,int mode)4147 unp_addsockcred(struct thread *td, struct mchain *mc, int mode)
4148 {
4149 	struct mbuf *m, *n, *n_prev;
4150 	const struct cmsghdr *cm;
4151 	int ngroups, i, cmsgtype;
4152 	size_t ctrlsz;
4153 
4154 	ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
4155 	if (mode & UNP_WANTCRED_ALWAYS) {
4156 		ctrlsz = SOCKCRED2SIZE(ngroups);
4157 		cmsgtype = SCM_CREDS2;
4158 	} else {
4159 		ctrlsz = SOCKCREDSIZE(ngroups);
4160 		cmsgtype = SCM_CREDS;
4161 	}
4162 
4163 	/* XXXGL: uipc_sosend_*() need to be improved so that we can M_WAITOK */
4164 	m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
4165 	if (m == NULL)
4166 		return;
4167 	MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
4168 
4169 	if (mode & UNP_WANTCRED_ALWAYS) {
4170 		struct sockcred2 *sc;
4171 
4172 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
4173 		sc->sc_version = 0;
4174 		sc->sc_pid = td->td_proc->p_pid;
4175 		sc->sc_uid = td->td_ucred->cr_ruid;
4176 		sc->sc_euid = td->td_ucred->cr_uid;
4177 		sc->sc_gid = td->td_ucred->cr_rgid;
4178 		sc->sc_egid = td->td_ucred->cr_gid;
4179 		sc->sc_ngroups = ngroups;
4180 		for (i = 0; i < sc->sc_ngroups; i++)
4181 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
4182 	} else {
4183 		struct sockcred *sc;
4184 
4185 		sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
4186 		sc->sc_uid = td->td_ucred->cr_ruid;
4187 		sc->sc_euid = td->td_ucred->cr_uid;
4188 		sc->sc_gid = td->td_ucred->cr_rgid;
4189 		sc->sc_egid = td->td_ucred->cr_gid;
4190 		sc->sc_ngroups = ngroups;
4191 		for (i = 0; i < sc->sc_ngroups; i++)
4192 			sc->sc_groups[i] = td->td_ucred->cr_groups[i];
4193 	}
4194 
4195 	/*
4196 	 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
4197 	 * created SCM_CREDS control message (struct sockcred) has another
4198 	 * format.
4199 	 */
4200 	if (!STAILQ_EMPTY(&mc->mc_q) && cmsgtype == SCM_CREDS)
4201 		STAILQ_FOREACH_SAFE(n, &mc->mc_q, m_stailq, n_prev) {
4202 			cm = mtod(n, struct cmsghdr *);
4203     			if (cm->cmsg_level == SOL_SOCKET &&
4204 			    cm->cmsg_type == SCM_CREDS) {
4205 				mc_remove(mc, n);
4206 				m_free(n);
4207 			}
4208 		}
4209 
4210 	/* Prepend it to the head. */
4211 	mc_prepend(mc, m);
4212 }
4213 
4214 static struct unpcb *
fptounp(struct file * fp)4215 fptounp(struct file *fp)
4216 {
4217 	struct socket *so;
4218 
4219 	if (fp->f_type != DTYPE_SOCKET)
4220 		return (NULL);
4221 	if ((so = fp->f_data) == NULL)
4222 		return (NULL);
4223 	if (so->so_proto->pr_domain != &localdomain)
4224 		return (NULL);
4225 	return sotounpcb(so);
4226 }
4227 
4228 static void
unp_discard(struct file * fp)4229 unp_discard(struct file *fp)
4230 {
4231 	struct unp_defer *dr;
4232 
4233 	if (unp_externalize_fp(fp)) {
4234 		dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
4235 		dr->ud_fp = fp;
4236 		UNP_DEFERRED_LOCK();
4237 		SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
4238 		UNP_DEFERRED_UNLOCK();
4239 		atomic_add_int(&unp_defers_count, 1);
4240 		taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
4241 	} else
4242 		closef_nothread(fp);
4243 }
4244 
4245 static void
unp_process_defers(void * arg __unused,int pending)4246 unp_process_defers(void *arg __unused, int pending)
4247 {
4248 	struct unp_defer *dr;
4249 	SLIST_HEAD(, unp_defer) drl;
4250 	int count;
4251 
4252 	SLIST_INIT(&drl);
4253 	for (;;) {
4254 		UNP_DEFERRED_LOCK();
4255 		if (SLIST_FIRST(&unp_defers) == NULL) {
4256 			UNP_DEFERRED_UNLOCK();
4257 			break;
4258 		}
4259 		SLIST_SWAP(&unp_defers, &drl, unp_defer);
4260 		UNP_DEFERRED_UNLOCK();
4261 		count = 0;
4262 		while ((dr = SLIST_FIRST(&drl)) != NULL) {
4263 			SLIST_REMOVE_HEAD(&drl, ud_link);
4264 			closef_nothread(dr->ud_fp);
4265 			free(dr, M_TEMP);
4266 			count++;
4267 		}
4268 		atomic_add_int(&unp_defers_count, -count);
4269 	}
4270 }
4271 
4272 static void
unp_internalize_fp(struct file * fp)4273 unp_internalize_fp(struct file *fp)
4274 {
4275 	struct unpcb *unp;
4276 
4277 	UNP_LINK_WLOCK();
4278 	if ((unp = fptounp(fp)) != NULL) {
4279 		unp->unp_file = fp;
4280 		unp->unp_msgcount++;
4281 	}
4282 	unp_rights++;
4283 	UNP_LINK_WUNLOCK();
4284 }
4285 
4286 static int
unp_externalize_fp(struct file * fp)4287 unp_externalize_fp(struct file *fp)
4288 {
4289 	struct unpcb *unp;
4290 	int ret;
4291 
4292 	UNP_LINK_WLOCK();
4293 	if ((unp = fptounp(fp)) != NULL) {
4294 		unp->unp_msgcount--;
4295 		ret = 1;
4296 	} else
4297 		ret = 0;
4298 	unp_rights--;
4299 	UNP_LINK_WUNLOCK();
4300 	return (ret);
4301 }
4302 
4303 /*
4304  * unp_defer indicates whether additional work has been defered for a future
4305  * pass through unp_gc().  It is thread local and does not require explicit
4306  * synchronization.
4307  */
4308 static int	unp_marked;
4309 
4310 static void
unp_remove_dead_ref(struct filedescent ** fdep,int fdcount)4311 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
4312 {
4313 	struct unpcb *unp;
4314 	struct file *fp;
4315 	int i;
4316 
4317 	/*
4318 	 * This function can only be called from the gc task.
4319 	 */
4320 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
4321 	    ("%s: not on gc callout", __func__));
4322 	UNP_LINK_LOCK_ASSERT();
4323 
4324 	for (i = 0; i < fdcount; i++) {
4325 		fp = fdep[i]->fde_file;
4326 		if ((unp = fptounp(fp)) == NULL)
4327 			continue;
4328 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
4329 			continue;
4330 		unp->unp_gcrefs--;
4331 	}
4332 }
4333 
4334 static void
unp_restore_undead_ref(struct filedescent ** fdep,int fdcount)4335 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
4336 {
4337 	struct unpcb *unp;
4338 	struct file *fp;
4339 	int i;
4340 
4341 	/*
4342 	 * This function can only be called from the gc task.
4343 	 */
4344 	KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
4345 	    ("%s: not on gc callout", __func__));
4346 	UNP_LINK_LOCK_ASSERT();
4347 
4348 	for (i = 0; i < fdcount; i++) {
4349 		fp = fdep[i]->fde_file;
4350 		if ((unp = fptounp(fp)) == NULL)
4351 			continue;
4352 		if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
4353 			continue;
4354 		unp->unp_gcrefs++;
4355 		unp_marked++;
4356 	}
4357 }
4358 
4359 static void
unp_scan_socket(struct socket * so,void (* op)(struct filedescent **,int))4360 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
4361 {
4362 	struct sockbuf *sb;
4363 
4364 	SOCK_LOCK_ASSERT(so);
4365 
4366 	if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
4367 		return;
4368 
4369 	SOCK_RECVBUF_LOCK(so);
4370 	switch (so->so_type) {
4371 	case SOCK_DGRAM:
4372 		unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
4373 		unp_scan(so->so_rcv.uxdg_peeked, op);
4374 		TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
4375 			unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
4376 		break;
4377 	case SOCK_STREAM:
4378 	case SOCK_SEQPACKET:
4379 		unp_scan(STAILQ_FIRST(&so->so_rcv.uxst_mbq), op);
4380 		break;
4381 	}
4382 	SOCK_RECVBUF_UNLOCK(so);
4383 }
4384 
4385 static void
unp_gc_scan(struct unpcb * unp,void (* op)(struct filedescent **,int))4386 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
4387 {
4388 	struct socket *so, *soa;
4389 
4390 	so = unp->unp_socket;
4391 	SOCK_LOCK(so);
4392 	if (SOLISTENING(so)) {
4393 		/*
4394 		 * Mark all sockets in our accept queue.
4395 		 */
4396 		TAILQ_FOREACH(soa, &so->sol_comp, so_list)
4397 			unp_scan_socket(soa, op);
4398 	} else {
4399 		/*
4400 		 * Mark all sockets we reference with RIGHTS.
4401 		 */
4402 		unp_scan_socket(so, op);
4403 	}
4404 	SOCK_UNLOCK(so);
4405 }
4406 
4407 static int unp_recycled;
4408 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
4409     "Number of unreachable sockets claimed by the garbage collector.");
4410 
4411 static int unp_taskcount;
4412 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
4413     "Number of times the garbage collector has run.");
4414 
4415 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
4416     "Number of active local sockets.");
4417 
4418 static void
unp_gc(__unused void * arg,int pending)4419 unp_gc(__unused void *arg, int pending)
4420 {
4421 	struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
4422 				    NULL };
4423 	struct unp_head **head;
4424 	struct unp_head unp_deadhead;	/* List of potentially-dead sockets. */
4425 	struct file *f, **unref;
4426 	struct unpcb *unp, *unptmp;
4427 	int i, total, unp_unreachable;
4428 
4429 	LIST_INIT(&unp_deadhead);
4430 	unp_taskcount++;
4431 	UNP_LINK_RLOCK();
4432 	/*
4433 	 * First determine which sockets may be in cycles.
4434 	 */
4435 	unp_unreachable = 0;
4436 
4437 	for (head = heads; *head != NULL; head++)
4438 		LIST_FOREACH(unp, *head, unp_link) {
4439 			KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
4440 			    ("%s: unp %p has unexpected gc flags 0x%x",
4441 			    __func__, unp, (unsigned int)unp->unp_gcflag));
4442 
4443 			f = unp->unp_file;
4444 
4445 			/*
4446 			 * Check for an unreachable socket potentially in a
4447 			 * cycle.  It must be in a queue as indicated by
4448 			 * msgcount, and this must equal the file reference
4449 			 * count.  Note that when msgcount is 0 the file is
4450 			 * NULL.
4451 			 */
4452 			if (f != NULL && unp->unp_msgcount != 0 &&
4453 			    refcount_load(&f->f_count) == unp->unp_msgcount) {
4454 				LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
4455 				unp->unp_gcflag |= UNPGC_DEAD;
4456 				unp->unp_gcrefs = unp->unp_msgcount;
4457 				unp_unreachable++;
4458 			}
4459 		}
4460 
4461 	/*
4462 	 * Scan all sockets previously marked as potentially being in a cycle
4463 	 * and remove the references each socket holds on any UNPGC_DEAD
4464 	 * sockets in its queue.  After this step, all remaining references on
4465 	 * sockets marked UNPGC_DEAD should not be part of any cycle.
4466 	 */
4467 	LIST_FOREACH(unp, &unp_deadhead, unp_dead)
4468 		unp_gc_scan(unp, unp_remove_dead_ref);
4469 
4470 	/*
4471 	 * If a socket still has a non-negative refcount, it cannot be in a
4472 	 * cycle.  In this case increment refcount of all children iteratively.
4473 	 * Stop the scan once we do a complete loop without discovering
4474 	 * a new reachable socket.
4475 	 */
4476 	do {
4477 		unp_marked = 0;
4478 		LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
4479 			if (unp->unp_gcrefs > 0) {
4480 				unp->unp_gcflag &= ~UNPGC_DEAD;
4481 				LIST_REMOVE(unp, unp_dead);
4482 				KASSERT(unp_unreachable > 0,
4483 				    ("%s: unp_unreachable underflow.",
4484 				    __func__));
4485 				unp_unreachable--;
4486 				unp_gc_scan(unp, unp_restore_undead_ref);
4487 			}
4488 	} while (unp_marked);
4489 
4490 	UNP_LINK_RUNLOCK();
4491 
4492 	if (unp_unreachable == 0)
4493 		return;
4494 
4495 	/*
4496 	 * Allocate space for a local array of dead unpcbs.
4497 	 * TODO: can this path be simplified by instead using the local
4498 	 * dead list at unp_deadhead, after taking out references
4499 	 * on the file object and/or unpcb and dropping the link lock?
4500 	 */
4501 	unref = malloc(unp_unreachable * sizeof(struct file *),
4502 	    M_TEMP, M_WAITOK);
4503 
4504 	/*
4505 	 * Iterate looking for sockets which have been specifically marked
4506 	 * as unreachable and store them locally.
4507 	 */
4508 	UNP_LINK_RLOCK();
4509 	total = 0;
4510 	LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
4511 		KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
4512 		    ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
4513 		unp->unp_gcflag &= ~UNPGC_DEAD;
4514 		f = unp->unp_file;
4515 		if (unp->unp_msgcount == 0 || f == NULL ||
4516 		    refcount_load(&f->f_count) != unp->unp_msgcount ||
4517 		    !fhold(f))
4518 			continue;
4519 		unref[total++] = f;
4520 		KASSERT(total <= unp_unreachable,
4521 		    ("%s: incorrect unreachable count.", __func__));
4522 	}
4523 	UNP_LINK_RUNLOCK();
4524 
4525 	/*
4526 	 * Now flush all sockets, free'ing rights.  This will free the
4527 	 * struct files associated with these sockets but leave each socket
4528 	 * with one remaining ref.
4529 	 */
4530 	for (i = 0; i < total; i++) {
4531 		struct socket *so;
4532 
4533 		so = unref[i]->f_data;
4534 		if (!SOLISTENING(so)) {
4535 			CURVNET_SET(so->so_vnet);
4536 			socantrcvmore(so);
4537 			unp_dispose(so);
4538 			CURVNET_RESTORE();
4539 		}
4540 	}
4541 
4542 	/*
4543 	 * And finally release the sockets so they can be reclaimed.
4544 	 */
4545 	for (i = 0; i < total; i++)
4546 		fdrop(unref[i], NULL);
4547 	unp_recycled += total;
4548 	free(unref, M_TEMP);
4549 }
4550 
4551 /*
4552  * Synchronize against unp_gc, which can trip over data as we are freeing it.
4553  */
4554 static void
unp_dispose(struct socket * so)4555 unp_dispose(struct socket *so)
4556 {
4557 	struct sockbuf *sb;
4558 	struct unpcb *unp;
4559 	struct mbuf *m;
4560 	int error __diagused;
4561 
4562 	MPASS(!SOLISTENING(so));
4563 
4564 	unp = sotounpcb(so);
4565 	UNP_LINK_WLOCK();
4566 	unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
4567 	UNP_LINK_WUNLOCK();
4568 
4569 	/*
4570 	 * Grab our special mbufs before calling sbrelease().
4571 	 */
4572 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
4573 	MPASS(!error);
4574 	SOCK_RECVBUF_LOCK(so);
4575 	switch (so->so_type) {
4576 	case SOCK_DGRAM:
4577 		while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
4578 			STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
4579 			TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
4580 			/* Note: socket of sb may reconnect. */
4581 			sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
4582 		}
4583 		sb = &so->so_rcv;
4584 		if (sb->uxdg_peeked != NULL) {
4585 			STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
4586 			    m_stailqpkt);
4587 			sb->uxdg_peeked = NULL;
4588 		}
4589 		m = STAILQ_FIRST(&sb->uxdg_mb);
4590 		STAILQ_INIT(&sb->uxdg_mb);
4591 		break;
4592 	case SOCK_STREAM:
4593 	case SOCK_SEQPACKET:
4594 		sb = &so->so_rcv;
4595 		m = STAILQ_FIRST(&sb->uxst_mbq);
4596 		STAILQ_INIT(&sb->uxst_mbq);
4597 		sb->sb_acc = sb->sb_ccc = sb->sb_ctl = sb->sb_mbcnt = 0;
4598 		/*
4599 		 * Trim M_NOTREADY buffers from the free list.  They are
4600 		 * referenced by the I/O thread.
4601 		 */
4602 		if (sb->uxst_fnrdy != NULL) {
4603 			struct mbuf *n, *prev;
4604 
4605 			while (m != NULL && m->m_flags & M_NOTREADY)
4606 				m = m->m_next;
4607 			for (prev = n = m; n != NULL; n = n->m_next) {
4608 				if (n->m_flags & M_NOTREADY)
4609 					prev->m_next = n->m_next;
4610 				else
4611 					prev = n;
4612 			}
4613 			sb->uxst_fnrdy = NULL;
4614 		}
4615 		break;
4616 	}
4617 	/*
4618 	 * Mark sb with SBS_CANTRCVMORE.  This is needed to prevent
4619 	 * uipc_sosend_*() or unp_disconnect() adding more data to the socket.
4620 	 * We came here either through shutdown(2) or from the final sofree().
4621 	 * The sofree() case is simple as it guarantees that no more sends will
4622 	 * happen, however we can race with unp_disconnect() from our peer.
4623 	 * The shutdown(2) case is more exotic.  It would call into
4624 	 * unp_dispose() only if socket is SS_ISCONNECTED.  This is possible if
4625 	 * we did connect(2) on this socket and we also had it bound with
4626 	 * bind(2) and receive connections from other sockets.  Because
4627 	 * uipc_shutdown() violates POSIX (see comment there) this applies to
4628 	 * SOCK_DGRAM as well.  For SOCK_DGRAM this SBS_CANTRCVMORE will have
4629 	 * affect not only on the peer we connect(2)ed to, but also on all of
4630 	 * the peers who had connect(2)ed to us.  Their sends would end up
4631 	 * with ENOBUFS.
4632 	 */
4633 	sb->sb_state |= SBS_CANTRCVMORE;
4634 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
4635 	    RLIM_INFINITY);
4636 	SOCK_RECVBUF_UNLOCK(so);
4637 	SOCK_IO_RECV_UNLOCK(so);
4638 
4639 	if (m != NULL) {
4640 		unp_scan(m, unp_freerights);
4641 		m_freemp(m);
4642 	}
4643 }
4644 
4645 static void
unp_scan(struct mbuf * m0,void (* op)(struct filedescent **,int))4646 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
4647 {
4648 	struct mbuf *m;
4649 	struct cmsghdr *cm;
4650 	void *data;
4651 	socklen_t clen, datalen;
4652 
4653 	while (m0 != NULL) {
4654 		for (m = m0; m; m = m->m_next) {
4655 			if (m->m_type != MT_CONTROL)
4656 				continue;
4657 
4658 			cm = mtod(m, struct cmsghdr *);
4659 			clen = m->m_len;
4660 
4661 			while (cm != NULL) {
4662 				if (sizeof(*cm) > clen || cm->cmsg_len > clen)
4663 					break;
4664 
4665 				data = CMSG_DATA(cm);
4666 				datalen = (caddr_t)cm + cm->cmsg_len
4667 				    - (caddr_t)data;
4668 
4669 				if (cm->cmsg_level == SOL_SOCKET &&
4670 				    cm->cmsg_type == SCM_RIGHTS) {
4671 					(*op)(data, datalen /
4672 					    sizeof(struct filedescent *));
4673 				}
4674 
4675 				if (CMSG_SPACE(datalen) < clen) {
4676 					clen -= CMSG_SPACE(datalen);
4677 					cm = (struct cmsghdr *)
4678 					    ((caddr_t)cm + CMSG_SPACE(datalen));
4679 				} else {
4680 					clen = 0;
4681 					cm = NULL;
4682 				}
4683 			}
4684 		}
4685 		m0 = m0->m_nextpkt;
4686 	}
4687 }
4688 
4689 /*
4690  * Definitions of protocols supported in the LOCAL domain.
4691  */
4692 static struct protosw streamproto = {
4693 	.pr_type =		SOCK_STREAM,
4694 	.pr_flags =		PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4695 	.pr_ctloutput =		&uipc_ctloutput,
4696 	.pr_abort = 		uipc_abort,
4697 	.pr_accept =		uipc_peeraddr,
4698 	.pr_attach =		uipc_attach,
4699 	.pr_bind =		uipc_bind,
4700 	.pr_bindat =		uipc_bindat,
4701 	.pr_connect =		uipc_connect,
4702 	.pr_connectat =		uipc_connectat,
4703 	.pr_connect2 =		uipc_connect2,
4704 	.pr_detach =		uipc_detach,
4705 	.pr_disconnect =	uipc_disconnect,
4706 	.pr_fdclose =		uipc_fdclose,
4707 	.pr_listen =		uipc_listen,
4708 	.pr_peeraddr =		uipc_peeraddr,
4709 	.pr_send =		uipc_sendfile,
4710 	.pr_sendfile_wait =	uipc_sendfile_wait,
4711 	.pr_ready =		uipc_ready,
4712 	.pr_sense =		uipc_sense,
4713 	.pr_shutdown =		uipc_shutdown,
4714 	.pr_sockaddr =		uipc_sockaddr,
4715 	.pr_sosend = 		uipc_sosend_stream_or_seqpacket,
4716 	.pr_soreceive =		uipc_soreceive_stream_or_seqpacket,
4717 	.pr_sopoll =		uipc_sopoll_stream_or_seqpacket,
4718 	.pr_kqfilter =		uipc_kqfilter_stream_or_seqpacket,
4719 	.pr_close =		uipc_close,
4720 	.pr_chmod =		uipc_chmod,
4721 };
4722 
4723 static struct protosw dgramproto = {
4724 	.pr_type =		SOCK_DGRAM,
4725 	.pr_flags =		PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF,
4726 	.pr_ctloutput =		&uipc_ctloutput,
4727 	.pr_abort = 		uipc_abort,
4728 	.pr_accept =		uipc_peeraddr,
4729 	.pr_attach =		uipc_attach,
4730 	.pr_bind =		uipc_bind,
4731 	.pr_bindat =		uipc_bindat,
4732 	.pr_connect =		uipc_connect,
4733 	.pr_connectat =		uipc_connectat,
4734 	.pr_connect2 =		uipc_connect2,
4735 	.pr_detach =		uipc_detach,
4736 	.pr_disconnect =	uipc_disconnect,
4737 	.pr_fdclose =		uipc_fdclose,
4738 	.pr_peeraddr =		uipc_peeraddr,
4739 	.pr_sosend =		uipc_sosend_dgram,
4740 	.pr_sense =		uipc_sense,
4741 	.pr_shutdown =		uipc_shutdown,
4742 	.pr_sockaddr =		uipc_sockaddr,
4743 	.pr_soreceive =		uipc_soreceive_dgram,
4744 	.pr_close =		uipc_close,
4745 	.pr_chmod =		uipc_chmod,
4746 };
4747 
4748 static struct protosw seqpacketproto = {
4749 	.pr_type =		SOCK_SEQPACKET,
4750 	.pr_flags =		PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4751 	.pr_ctloutput =		&uipc_ctloutput,
4752 	.pr_abort =		uipc_abort,
4753 	.pr_accept =		uipc_peeraddr,
4754 	.pr_attach =		uipc_attach,
4755 	.pr_bind =		uipc_bind,
4756 	.pr_bindat =		uipc_bindat,
4757 	.pr_connect =		uipc_connect,
4758 	.pr_connectat =		uipc_connectat,
4759 	.pr_connect2 =		uipc_connect2,
4760 	.pr_detach =		uipc_detach,
4761 	.pr_disconnect =	uipc_disconnect,
4762 	.pr_fdclose =		uipc_fdclose,
4763 	.pr_listen =		uipc_listen,
4764 	.pr_peeraddr =		uipc_peeraddr,
4765 	.pr_sense =		uipc_sense,
4766 	.pr_shutdown =		uipc_shutdown,
4767 	.pr_sockaddr =		uipc_sockaddr,
4768 	.pr_sosend = 		uipc_sosend_stream_or_seqpacket,
4769 	.pr_soreceive =		uipc_soreceive_stream_or_seqpacket,
4770 	.pr_sopoll =		uipc_sopoll_stream_or_seqpacket,
4771 	.pr_kqfilter =		uipc_kqfilter_stream_or_seqpacket,
4772 	.pr_close =		uipc_close,
4773 	.pr_chmod =		uipc_chmod,
4774 };
4775 
4776 static struct domain localdomain = {
4777 	.dom_family =		AF_LOCAL,
4778 	.dom_name =		"local",
4779 	.dom_nprotosw =		3,
4780 	.dom_protosw =		{
4781 		&streamproto,
4782 		&dgramproto,
4783 		&seqpacketproto,
4784 	}
4785 };
4786 DOMAIN_SET(local);
4787 
4788 /*
4789  * A helper function called by VFS before socket-type vnode reclamation.
4790  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
4791  * use count.
4792  */
4793 void
vfs_unp_reclaim(struct vnode * vp)4794 vfs_unp_reclaim(struct vnode *vp)
4795 {
4796 	struct unpcb *unp;
4797 	int active;
4798 	struct mtx *vplock;
4799 
4800 	ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
4801 	KASSERT(vp->v_type == VSOCK,
4802 	    ("vfs_unp_reclaim: vp->v_type != VSOCK"));
4803 
4804 	active = 0;
4805 	vplock = mtx_pool_find(unp_vp_mtxpool, vp);
4806 	mtx_lock(vplock);
4807 	VOP_UNP_CONNECT(vp, &unp);
4808 	if (unp == NULL)
4809 		goto done;
4810 	UNP_PCB_LOCK(unp);
4811 	if (unp->unp_vnode == vp) {
4812 		VOP_UNP_DETACH(vp);
4813 		unp->unp_vnode = NULL;
4814 		active = 1;
4815 	}
4816 	UNP_PCB_UNLOCK(unp);
4817  done:
4818 	mtx_unlock(vplock);
4819 	if (active)
4820 		vunref(vp);
4821 }
4822 
4823 #ifdef DDB
4824 static void
db_print_indent(int indent)4825 db_print_indent(int indent)
4826 {
4827 	int i;
4828 
4829 	for (i = 0; i < indent; i++)
4830 		db_printf(" ");
4831 }
4832 
4833 static void
db_print_unpflags(int unp_flags)4834 db_print_unpflags(int unp_flags)
4835 {
4836 	int comma;
4837 
4838 	comma = 0;
4839 	if (unp_flags & UNP_HAVEPC) {
4840 		db_printf("%sUNP_HAVEPC", comma ? ", " : "");
4841 		comma = 1;
4842 	}
4843 	if (unp_flags & UNP_WANTCRED_ALWAYS) {
4844 		db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
4845 		comma = 1;
4846 	}
4847 	if (unp_flags & UNP_WANTCRED_ONESHOT) {
4848 		db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
4849 		comma = 1;
4850 	}
4851 	if (unp_flags & UNP_CONNECTING) {
4852 		db_printf("%sUNP_CONNECTING", comma ? ", " : "");
4853 		comma = 1;
4854 	}
4855 	if (unp_flags & UNP_BINDING) {
4856 		db_printf("%sUNP_BINDING", comma ? ", " : "");
4857 		comma = 1;
4858 	}
4859 }
4860 
4861 static void
db_print_xucred(int indent,struct xucred * xu)4862 db_print_xucred(int indent, struct xucred *xu)
4863 {
4864 	int comma, i;
4865 
4866 	db_print_indent(indent);
4867 	db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
4868 	    xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
4869 	db_print_indent(indent);
4870 	db_printf("cr_groups: ");
4871 	comma = 0;
4872 	for (i = 0; i < xu->cr_ngroups; i++) {
4873 		db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
4874 		comma = 1;
4875 	}
4876 	db_printf("\n");
4877 }
4878 
4879 static void
db_print_unprefs(int indent,struct unp_head * uh)4880 db_print_unprefs(int indent, struct unp_head *uh)
4881 {
4882 	struct unpcb *unp;
4883 	int counter;
4884 
4885 	counter = 0;
4886 	LIST_FOREACH(unp, uh, unp_reflink) {
4887 		if (counter % 4 == 0)
4888 			db_print_indent(indent);
4889 		db_printf("%p  ", unp);
4890 		if (counter % 4 == 3)
4891 			db_printf("\n");
4892 		counter++;
4893 	}
4894 	if (counter != 0 && counter % 4 != 0)
4895 		db_printf("\n");
4896 }
4897 
DB_SHOW_COMMAND(unpcb,db_show_unpcb)4898 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
4899 {
4900 	struct unpcb *unp;
4901 
4902         if (!have_addr) {
4903                 db_printf("usage: show unpcb <addr>\n");
4904                 return;
4905         }
4906         unp = (struct unpcb *)addr;
4907 
4908 	db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
4909 	    unp->unp_vnode);
4910 
4911 	db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
4912 	    unp->unp_conn);
4913 
4914 	db_printf("unp_refs:\n");
4915 	db_print_unprefs(2, &unp->unp_refs);
4916 
4917 	/* XXXRW: Would be nice to print the full address, if any. */
4918 	db_printf("unp_addr: %p\n", unp->unp_addr);
4919 
4920 	db_printf("unp_gencnt: %llu\n",
4921 	    (unsigned long long)unp->unp_gencnt);
4922 
4923 	db_printf("unp_flags: %x (", unp->unp_flags);
4924 	db_print_unpflags(unp->unp_flags);
4925 	db_printf(")\n");
4926 
4927 	db_printf("unp_peercred:\n");
4928 	db_print_xucred(2, &unp->unp_peercred);
4929 
4930 	db_printf("unp_refcount: %u\n", unp->unp_refcount);
4931 }
4932 #endif
4933