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