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