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 /*
1811 * XXXGL: maybe kn->kn_flags |= EV_EOF ?
1812 */
1813 return (1);
1814 } else if (kn->kn_sfflags & NOTE_LOWAT)
1815 return (kn->kn_data >= kn->kn_sdata);
1816 else
1817 return (kn->kn_data >= so2->so_rcv.sb_lowat);
1818 }
1819
1820 static int
uipc_filt_soempty(struct knote * kn,long hint)1821 uipc_filt_soempty(struct knote *kn, long hint)
1822 {
1823 struct socket *so = kn->kn_fp->f_data, *so2;
1824 struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn;
1825
1826 if (SOLISTENING(so) || unp2 == NULL)
1827 return (1);
1828
1829 so2 = unp2->unp_socket;
1830 SOCK_RECVBUF_LOCK_ASSERT(so2);
1831 kn->kn_data = uipc_stream_sbspace(&so2->so_rcv);
1832
1833 return (kn->kn_data == 0 ? 1 : 0);
1834 }
1835
1836 static const struct filterops uipc_write_filtops = {
1837 .f_isfd = 1,
1838 .f_detach = uipc_filt_sowdetach,
1839 .f_event = uipc_filt_sowrite,
1840 };
1841 static const struct filterops uipc_empty_filtops = {
1842 .f_isfd = 1,
1843 .f_detach = uipc_filt_sowdetach,
1844 .f_event = uipc_filt_soempty,
1845 };
1846
1847 static int
uipc_kqfilter_stream_or_seqpacket(struct socket * so,struct knote * kn)1848 uipc_kqfilter_stream_or_seqpacket(struct socket *so, struct knote *kn)
1849 {
1850 struct unpcb *unp = sotounpcb(so);
1851 struct knlist *knl;
1852
1853 switch (kn->kn_filter) {
1854 case EVFILT_READ:
1855 return (sokqfilter_generic(so, kn));
1856 case EVFILT_WRITE:
1857 kn->kn_fop = &uipc_write_filtops;
1858 break;
1859 case EVFILT_EMPTY:
1860 kn->kn_fop = &uipc_empty_filtops;
1861 break;
1862 default:
1863 return (EINVAL);
1864 }
1865
1866 knl = &so->so_wrsel.si_note;
1867 UNP_PCB_LOCK(unp);
1868 if (SOLISTENING(so)) {
1869 SOLISTEN_LOCK(so);
1870 knlist_add(knl, kn, 1);
1871 SOLISTEN_UNLOCK(so);
1872 } else {
1873 struct socket *so2 = so->so_rcv.uxst_peer;
1874
1875 if (so2 != NULL)
1876 SOCK_RECVBUF_LOCK(so2);
1877 knlist_add(knl, kn, 1);
1878 if (so2 != NULL)
1879 SOCK_RECVBUF_UNLOCK(so2);
1880 }
1881 UNP_PCB_UNLOCK(unp);
1882 return (0);
1883 }
1884
1885 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1886 static inline bool
uipc_dgram_sbspace(struct sockbuf * sb,u_int cc,u_int mbcnt)1887 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1888 {
1889 u_int bleft, mleft;
1890
1891 /*
1892 * Negative space may happen if send(2) is followed by
1893 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1894 */
1895 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1896 sb->sb_mbmax < sb->uxdg_mbcnt))
1897 return (false);
1898
1899 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1900 return (false);
1901
1902 bleft = sb->sb_hiwat - sb->uxdg_cc;
1903 mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1904
1905 return (bleft >= cc && mleft >= mbcnt);
1906 }
1907
1908 /*
1909 * PF_UNIX/SOCK_DGRAM send
1910 *
1911 * Allocate a record consisting of 3 mbufs in the sequence of
1912 * from -> control -> data and append it to the socket buffer.
1913 *
1914 * The first mbuf carries sender's name and is a pkthdr that stores
1915 * overall length of datagram, its memory consumption and control length.
1916 */
1917 #define ctllen PH_loc.thirtytwo[1]
1918 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1919 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1920 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)1921 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1922 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1923 {
1924 struct unpcb *unp, *unp2;
1925 const struct sockaddr *from;
1926 struct socket *so2;
1927 struct sockbuf *sb;
1928 struct mchain cmc = MCHAIN_INITIALIZER(&cmc);
1929 struct mbuf *f;
1930 u_int cc, ctl, mbcnt;
1931 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1932 int error;
1933
1934 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1935
1936 error = 0;
1937 f = NULL;
1938
1939 if (__predict_false(flags & MSG_OOB)) {
1940 error = EOPNOTSUPP;
1941 goto out;
1942 }
1943 if (m == NULL) {
1944 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1945 error = EMSGSIZE;
1946 goto out;
1947 }
1948 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1949 if (__predict_false(m == NULL)) {
1950 error = EFAULT;
1951 goto out;
1952 }
1953 f = m_gethdr(M_WAITOK, MT_SONAME);
1954 cc = m->m_pkthdr.len;
1955 mbcnt = MSIZE + m->m_pkthdr.memlen;
1956 if (c != NULL && (error = unp_internalize(c, &cmc, td)))
1957 goto out;
1958 } else {
1959 struct mchain mc;
1960
1961 uipc_reset_kernel_mbuf(m, &mc);
1962 cc = mc.mc_len;
1963 mbcnt = mc.mc_mlen;
1964 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1965 error = EMSGSIZE;
1966 goto out;
1967 }
1968 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1969 error = ENOBUFS;
1970 goto out;
1971 }
1972 }
1973
1974 unp = sotounpcb(so);
1975 MPASS(unp);
1976
1977 /*
1978 * XXXGL: would be cool to fully remove so_snd out of the equation
1979 * and avoid this lock, which is not only extraneous, but also being
1980 * released, thus still leaving possibility for a race. We can easily
1981 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1982 * is more difficult to invent something to handle so_error.
1983 */
1984 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1985 if (error)
1986 goto out2;
1987 SOCK_SENDBUF_LOCK(so);
1988 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1989 SOCK_SENDBUF_UNLOCK(so);
1990 error = EPIPE;
1991 goto out3;
1992 }
1993 if (so->so_error != 0) {
1994 error = so->so_error;
1995 so->so_error = 0;
1996 SOCK_SENDBUF_UNLOCK(so);
1997 goto out3;
1998 }
1999 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
2000 SOCK_SENDBUF_UNLOCK(so);
2001 error = EDESTADDRREQ;
2002 goto out3;
2003 }
2004 SOCK_SENDBUF_UNLOCK(so);
2005
2006 if (addr != NULL) {
2007 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
2008 goto out3;
2009 UNP_PCB_LOCK_ASSERT(unp);
2010 unp2 = unp->unp_conn;
2011 UNP_PCB_LOCK_ASSERT(unp2);
2012 } else {
2013 UNP_PCB_LOCK(unp);
2014 unp2 = unp_pcb_lock_peer(unp);
2015 if (unp2 == NULL) {
2016 UNP_PCB_UNLOCK(unp);
2017 error = ENOTCONN;
2018 goto out3;
2019 }
2020 }
2021
2022 if (unp2->unp_flags & UNP_WANTCRED_MASK)
2023 unp_addsockcred(td, &cmc, unp2->unp_flags);
2024 if (unp->unp_addr != NULL)
2025 from = (struct sockaddr *)unp->unp_addr;
2026 else
2027 from = &sun_noname;
2028 f->m_len = from->sa_len;
2029 MPASS(from->sa_len <= MLEN);
2030 bcopy(from, mtod(f, void *), from->sa_len);
2031
2032 /*
2033 * Concatenate mbufs: from -> control -> data.
2034 * Save overall cc and mbcnt in "from" mbuf.
2035 */
2036 if (!STAILQ_EMPTY(&cmc.mc_q)) {
2037 f->m_next = mc_first(&cmc);
2038 mc_last(&cmc)->m_next = m;
2039 /* XXXGL: This is dirty as well as rollback after ENOBUFS. */
2040 STAILQ_INIT(&cmc.mc_q);
2041 } else
2042 f->m_next = m;
2043 m = NULL;
2044 ctl = f->m_len + cmc.mc_len;
2045 mbcnt += cmc.mc_mlen;
2046 #ifdef INVARIANTS
2047 dcc = dctl = dmbcnt = 0;
2048 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
2049 if (mb->m_type == MT_DATA)
2050 dcc += mb->m_len;
2051 else
2052 dctl += mb->m_len;
2053 dmbcnt += MSIZE;
2054 if (mb->m_flags & M_EXT)
2055 dmbcnt += mb->m_ext.ext_size;
2056 }
2057 MPASS(dcc == cc);
2058 MPASS(dctl == ctl);
2059 MPASS(dmbcnt == mbcnt);
2060 #endif
2061 f->m_pkthdr.len = cc + ctl;
2062 f->m_pkthdr.memlen = mbcnt;
2063 f->m_pkthdr.ctllen = ctl;
2064
2065 /*
2066 * Destination socket buffer selection.
2067 *
2068 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
2069 * destination address is supplied, create a temporary connection for
2070 * the run time of the function (see call to unp_connectat() above and
2071 * to unp_disconnect() below). We distinguish them by condition of
2072 * (addr != NULL). We intentionally avoid adding 'bool connected' for
2073 * that condition, since, again, through the run time of this code we
2074 * are always connected. For such "unconnected" sends, the destination
2075 * buffer would be the receive buffer of destination socket so2.
2076 *
2077 * For connected sends, data lands on the send buffer of the sender's
2078 * socket "so". Then, if we just added the very first datagram
2079 * on this send buffer, we need to add the send buffer on to the
2080 * receiving socket's buffer list. We put ourselves on top of the
2081 * list. Such logic gives infrequent senders priority over frequent
2082 * senders.
2083 *
2084 * Note on byte count management. As long as event methods kevent(2),
2085 * select(2) are not protocol specific (yet), we need to maintain
2086 * meaningful values on the receive buffer. So, the receive buffer
2087 * would accumulate counters from all connected buffers potentially
2088 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
2089 */
2090 so2 = unp2->unp_socket;
2091 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
2092 SOCK_RECVBUF_LOCK(so2);
2093 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
2094 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
2095 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
2096 uxdg_clist);
2097 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
2098 sb->uxdg_cc += cc + ctl;
2099 sb->uxdg_ctl += ctl;
2100 sb->uxdg_mbcnt += mbcnt;
2101 so2->so_rcv.sb_acc += cc + ctl;
2102 so2->so_rcv.sb_ccc += cc + ctl;
2103 so2->so_rcv.sb_ctl += ctl;
2104 so2->so_rcv.sb_mbcnt += mbcnt;
2105 sorwakeup_locked(so2);
2106 f = NULL;
2107 } else {
2108 soroverflow_locked(so2);
2109 error = ENOBUFS;
2110 if (f->m_next->m_type == MT_CONTROL) {
2111 STAILQ_FIRST(&cmc.mc_q) = f->m_next;
2112 f->m_next = NULL;
2113 }
2114 }
2115
2116 if (addr != NULL)
2117 unp_disconnect(unp, unp2);
2118 else
2119 unp_pcb_unlock_pair(unp, unp2);
2120
2121 td->td_ru.ru_msgsnd++;
2122
2123 out3:
2124 SOCK_IO_SEND_UNLOCK(so);
2125 out2:
2126 if (!mc_empty(&cmc))
2127 unp_scan(mc_first(&cmc), unp_freerights);
2128 out:
2129 if (f)
2130 m_freem(f);
2131 mc_freem(&cmc);
2132 if (m)
2133 m_freem(m);
2134
2135 return (error);
2136 }
2137
2138 /*
2139 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
2140 * The mbuf has already been unlinked from the uxdg_mb of socket buffer
2141 * and needs to be linked onto uxdg_peeked of receive socket buffer.
2142 */
2143 static int
uipc_peek_dgram(struct socket * so,struct mbuf * m,struct sockaddr ** psa,struct uio * uio,struct mbuf ** controlp,int * flagsp)2144 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
2145 struct uio *uio, struct mbuf **controlp, int *flagsp)
2146 {
2147 ssize_t len = 0;
2148 int error;
2149
2150 so->so_rcv.uxdg_peeked = m;
2151 so->so_rcv.uxdg_cc += m->m_pkthdr.len;
2152 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
2153 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
2154 SOCK_RECVBUF_UNLOCK(so);
2155
2156 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2157 if (psa != NULL)
2158 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2159
2160 m = m->m_next;
2161 KASSERT(m, ("%s: no data or control after soname", __func__));
2162
2163 /*
2164 * With MSG_PEEK the control isn't executed, just copied.
2165 */
2166 while (m != NULL && m->m_type == MT_CONTROL) {
2167 if (controlp != NULL) {
2168 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
2169 controlp = &(*controlp)->m_next;
2170 }
2171 m = m->m_next;
2172 }
2173 KASSERT(m == NULL || m->m_type == MT_DATA,
2174 ("%s: not MT_DATA mbuf %p", __func__, m));
2175 while (m != NULL && uio->uio_resid > 0) {
2176 len = uio->uio_resid;
2177 if (len > m->m_len)
2178 len = m->m_len;
2179 error = uiomove(mtod(m, char *), (int)len, uio);
2180 if (error) {
2181 SOCK_IO_RECV_UNLOCK(so);
2182 return (error);
2183 }
2184 if (len == m->m_len)
2185 m = m->m_next;
2186 }
2187 SOCK_IO_RECV_UNLOCK(so);
2188
2189 if (flagsp != NULL) {
2190 if (m != NULL) {
2191 if (*flagsp & MSG_TRUNC) {
2192 /* Report real length of the packet */
2193 uio->uio_resid -= m_length(m, NULL) - len;
2194 }
2195 *flagsp |= MSG_TRUNC;
2196 } else
2197 *flagsp &= ~MSG_TRUNC;
2198 }
2199
2200 return (0);
2201 }
2202
2203 /*
2204 * PF_UNIX/SOCK_DGRAM receive
2205 */
2206 static int
uipc_soreceive_dgram(struct socket * so,struct sockaddr ** psa,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)2207 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2208 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2209 {
2210 struct sockbuf *sb = NULL;
2211 struct mbuf *m;
2212 int flags, error;
2213 ssize_t len = 0;
2214 bool nonblock;
2215
2216 MPASS(mp0 == NULL);
2217
2218 if (psa != NULL)
2219 *psa = NULL;
2220 if (controlp != NULL)
2221 *controlp = NULL;
2222
2223 flags = flagsp != NULL ? *flagsp : 0;
2224 nonblock = (so->so_state & SS_NBIO) ||
2225 (flags & (MSG_DONTWAIT | MSG_NBIO));
2226
2227 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2228 if (__predict_false(error))
2229 return (error);
2230
2231 /*
2232 * Loop blocking while waiting for a datagram. Prioritize connected
2233 * peers over unconnected sends. Set sb to selected socket buffer
2234 * containing an mbuf on exit from the wait loop. A datagram that
2235 * had already been peeked at has top priority.
2236 */
2237 SOCK_RECVBUF_LOCK(so);
2238 while ((m = so->so_rcv.uxdg_peeked) == NULL &&
2239 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
2240 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
2241 if (so->so_error) {
2242 error = so->so_error;
2243 if (!(flags & MSG_PEEK))
2244 so->so_error = 0;
2245 SOCK_RECVBUF_UNLOCK(so);
2246 SOCK_IO_RECV_UNLOCK(so);
2247 return (error);
2248 }
2249 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2250 uio->uio_resid == 0) {
2251 SOCK_RECVBUF_UNLOCK(so);
2252 SOCK_IO_RECV_UNLOCK(so);
2253 return (0);
2254 }
2255 if (nonblock) {
2256 SOCK_RECVBUF_UNLOCK(so);
2257 SOCK_IO_RECV_UNLOCK(so);
2258 return (EWOULDBLOCK);
2259 }
2260 error = sbwait(so, SO_RCV);
2261 if (error) {
2262 SOCK_RECVBUF_UNLOCK(so);
2263 SOCK_IO_RECV_UNLOCK(so);
2264 return (error);
2265 }
2266 }
2267
2268 if (sb == NULL)
2269 sb = &so->so_rcv;
2270 else if (m == NULL)
2271 m = STAILQ_FIRST(&sb->uxdg_mb);
2272 else
2273 MPASS(m == so->so_rcv.uxdg_peeked);
2274
2275 MPASS(sb->uxdg_cc > 0);
2276 M_ASSERTPKTHDR(m);
2277 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
2278
2279 if (uio->uio_td)
2280 uio->uio_td->td_ru.ru_msgrcv++;
2281
2282 if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
2283 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
2284 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
2285 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
2286 } else
2287 so->so_rcv.uxdg_peeked = NULL;
2288
2289 sb->uxdg_cc -= m->m_pkthdr.len;
2290 sb->uxdg_ctl -= m->m_pkthdr.ctllen;
2291 sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
2292
2293 if (__predict_false(flags & MSG_PEEK))
2294 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
2295
2296 so->so_rcv.sb_acc -= m->m_pkthdr.len;
2297 so->so_rcv.sb_ccc -= m->m_pkthdr.len;
2298 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
2299 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
2300 SOCK_RECVBUF_UNLOCK(so);
2301
2302 if (psa != NULL)
2303 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
2304 m = m_free(m);
2305 KASSERT(m, ("%s: no data or control after soname", __func__));
2306
2307 /*
2308 * Packet to copyout() is now in 'm' and it is disconnected from the
2309 * queue.
2310 *
2311 * Process one or more MT_CONTROL mbufs present before any data mbufs
2312 * in the first mbuf chain on the socket buffer. We call into the
2313 * unp_externalize() to perform externalization (or freeing if
2314 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
2315 * without MT_DATA mbufs.
2316 */
2317 while (m != NULL && m->m_type == MT_CONTROL) {
2318 error = unp_externalize(m, controlp, flags);
2319 m = m_free(m);
2320 if (error != 0) {
2321 SOCK_IO_RECV_UNLOCK(so);
2322 unp_scan(m, unp_freerights);
2323 m_freem(m);
2324 return (error);
2325 }
2326 if (controlp != NULL) {
2327 while (*controlp != NULL)
2328 controlp = &(*controlp)->m_next;
2329 }
2330 }
2331 KASSERT(m == NULL || m->m_type == MT_DATA,
2332 ("%s: not MT_DATA mbuf %p", __func__, m));
2333 while (m != NULL && uio->uio_resid > 0) {
2334 len = uio->uio_resid;
2335 if (len > m->m_len)
2336 len = m->m_len;
2337 error = uiomove(mtod(m, char *), (int)len, uio);
2338 if (error) {
2339 SOCK_IO_RECV_UNLOCK(so);
2340 m_freem(m);
2341 return (error);
2342 }
2343 if (len == m->m_len)
2344 m = m_free(m);
2345 else {
2346 m->m_data += len;
2347 m->m_len -= len;
2348 }
2349 }
2350 SOCK_IO_RECV_UNLOCK(so);
2351
2352 if (m != NULL) {
2353 if (flagsp != NULL) {
2354 if (flags & MSG_TRUNC) {
2355 /* Report real length of the packet */
2356 uio->uio_resid -= m_length(m, NULL);
2357 }
2358 *flagsp |= MSG_TRUNC;
2359 }
2360 m_freem(m);
2361 } else if (flagsp != NULL)
2362 *flagsp &= ~MSG_TRUNC;
2363
2364 return (0);
2365 }
2366
2367 static int
uipc_sendfile_wait(struct socket * so,off_t need,int * space)2368 uipc_sendfile_wait(struct socket *so, off_t need, int *space)
2369 {
2370 struct unpcb *unp2;
2371 struct socket *so2;
2372 struct sockbuf *sb;
2373 bool nonblock, sockref;
2374 int error;
2375
2376 MPASS(so->so_type == SOCK_STREAM);
2377 MPASS(need > 0);
2378 MPASS(space != NULL);
2379
2380 nonblock = so->so_state & SS_NBIO;
2381 sockref = false;
2382
2383 if (__predict_false((so->so_state & SS_ISCONNECTED) == 0))
2384 return (ENOTCONN);
2385
2386 if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2387 return (error);
2388
2389 so2 = unp2->unp_socket;
2390 sb = &so2->so_rcv;
2391 SOCK_RECVBUF_LOCK(so2);
2392 UNP_PCB_UNLOCK(unp2);
2393 while ((*space = uipc_stream_sbspace(sb)) < need &&
2394 (*space < so->so_snd.sb_hiwat / 2)) {
2395 UIPC_STREAM_SBCHECK(sb);
2396 if (nonblock) {
2397 SOCK_RECVBUF_UNLOCK(so2);
2398 return (EAGAIN);
2399 }
2400 if (!sockref)
2401 soref(so2);
2402 error = sbwait(so2, SO_RCV);
2403 if (error == 0 &&
2404 __predict_false(sb->sb_state & SBS_CANTRCVMORE))
2405 error = EPIPE;
2406 if (error) {
2407 SOCK_RECVBUF_UNLOCK(so2);
2408 sorele(so2);
2409 return (error);
2410 }
2411 }
2412 UIPC_STREAM_SBCHECK(sb);
2413 SOCK_RECVBUF_UNLOCK(so2);
2414 if (sockref)
2415 sorele(so2);
2416
2417 return (0);
2418 }
2419
2420 /*
2421 * Although this is a pr_send method, for unix(4) it is called only via
2422 * sendfile(2) path. This means we can be sure that mbufs are clear of
2423 * any extra flags and don't require any conditioning.
2424 */
2425 static int
uipc_sendfile(struct socket * so,int flags,struct mbuf * m,struct sockaddr * from,struct mbuf * control,struct thread * td)2426 uipc_sendfile(struct socket *so, int flags, struct mbuf *m,
2427 struct sockaddr *from, struct mbuf *control, struct thread *td)
2428 {
2429 struct mchain mc;
2430 struct unpcb *unp2;
2431 struct socket *so2;
2432 struct sockbuf *sb;
2433 bool notready, wakeup;
2434 int error;
2435
2436 MPASS(so->so_type == SOCK_STREAM);
2437 MPASS(from == NULL && control == NULL);
2438 KASSERT(!(m->m_flags & M_EXTPG),
2439 ("unix(4): TLS sendfile(2) not supported"));
2440
2441 notready = flags & PRUS_NOTREADY;
2442
2443 if (__predict_false((so->so_state & SS_ISCONNECTED) == 0)) {
2444 error = ENOTCONN;
2445 goto out;
2446 }
2447
2448 if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0))
2449 goto out;
2450
2451 mc_init_m(&mc, m);
2452
2453 so2 = unp2->unp_socket;
2454 sb = &so2->so_rcv;
2455 SOCK_RECVBUF_LOCK(so2);
2456 UNP_PCB_UNLOCK(unp2);
2457 UIPC_STREAM_SBCHECK(sb);
2458 sb->sb_ccc += mc.mc_len;
2459 sb->sb_mbcnt += mc.mc_mlen;
2460 if (sb->uxst_fnrdy == NULL) {
2461 if (notready) {
2462 wakeup = false;
2463 STAILQ_FOREACH(m, &mc.mc_q, m_stailq) {
2464 if (m->m_flags & M_NOTREADY) {
2465 sb->uxst_fnrdy = m;
2466 break;
2467 } else {
2468 sb->sb_acc += m->m_len;
2469 wakeup = true;
2470 }
2471 }
2472 } else {
2473 wakeup = true;
2474 sb->sb_acc += mc.mc_len;
2475 }
2476 } else {
2477 wakeup = false;
2478 }
2479 STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q);
2480 UIPC_STREAM_SBCHECK(sb);
2481 if (wakeup)
2482 sorwakeup_locked(so2);
2483 else
2484 SOCK_RECVBUF_UNLOCK(so2);
2485
2486 return (0);
2487 out:
2488 /*
2489 * In case of not ready data, uipc_ready() is responsible
2490 * for freeing memory.
2491 */
2492 if (m != NULL && !notready)
2493 m_freem(m);
2494
2495 return (error);
2496 }
2497
2498 static int
uipc_sbready(struct sockbuf * sb,struct mbuf * m,int count)2499 uipc_sbready(struct sockbuf *sb, struct mbuf *m, int count)
2500 {
2501 bool blocker;
2502
2503 /* assert locked */
2504
2505 blocker = (sb->uxst_fnrdy == m);
2506 STAILQ_FOREACH_FROM(m, &sb->uxst_mbq, m_stailq) {
2507 if (count > 0) {
2508 MPASS(m->m_flags & M_NOTREADY);
2509 m->m_flags &= ~M_NOTREADY;
2510 if (blocker)
2511 sb->sb_acc += m->m_len;
2512 count--;
2513 } else if (m->m_flags & M_NOTREADY)
2514 break;
2515 else if (blocker)
2516 sb->sb_acc += m->m_len;
2517 }
2518 if (blocker) {
2519 sb->uxst_fnrdy = m;
2520 return (0);
2521 } else
2522 return (EINPROGRESS);
2523 }
2524
2525 static bool
uipc_ready_scan(struct socket * so,struct mbuf * m,int count,int * errorp)2526 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
2527 {
2528 struct mbuf *mb;
2529 struct sockbuf *sb;
2530
2531 SOCK_LOCK(so);
2532 if (SOLISTENING(so)) {
2533 SOCK_UNLOCK(so);
2534 return (false);
2535 }
2536 mb = NULL;
2537 sb = &so->so_rcv;
2538 SOCK_RECVBUF_LOCK(so);
2539 if (sb->uxst_fnrdy != NULL) {
2540 STAILQ_FOREACH(mb, &sb->uxst_mbq, m_stailq) {
2541 if (mb == m) {
2542 *errorp = uipc_sbready(sb, m, count);
2543 break;
2544 }
2545 }
2546 }
2547 SOCK_RECVBUF_UNLOCK(so);
2548 SOCK_UNLOCK(so);
2549 return (mb != NULL);
2550 }
2551
2552 static int
uipc_ready(struct socket * so,struct mbuf * m,int count)2553 uipc_ready(struct socket *so, struct mbuf *m, int count)
2554 {
2555 struct unpcb *unp, *unp2;
2556 int error;
2557
2558 MPASS(so->so_type == SOCK_STREAM);
2559
2560 if (__predict_true(uipc_lock_peer(so, &unp2) == 0)) {
2561 struct socket *so2;
2562 struct sockbuf *sb;
2563
2564 so2 = unp2->unp_socket;
2565 sb = &so2->so_rcv;
2566 SOCK_RECVBUF_LOCK(so2);
2567 UNP_PCB_UNLOCK(unp2);
2568 UIPC_STREAM_SBCHECK(sb);
2569 error = uipc_sbready(sb, m, count);
2570 UIPC_STREAM_SBCHECK(sb);
2571 if (error == 0)
2572 sorwakeup_locked(so2);
2573 else
2574 SOCK_RECVBUF_UNLOCK(so2);
2575 } else {
2576 /*
2577 * The receiving socket has been disconnected, but may still
2578 * be valid. In this case, the not-ready mbufs are still
2579 * present in its socket buffer, so perform an exhaustive
2580 * search before giving up and freeing the mbufs.
2581 */
2582 UNP_LINK_RLOCK();
2583 LIST_FOREACH(unp, &unp_shead, unp_link) {
2584 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
2585 break;
2586 }
2587 UNP_LINK_RUNLOCK();
2588
2589 if (unp == NULL) {
2590 for (int i = 0; i < count; i++)
2591 m = m_free(m);
2592 return (ECONNRESET);
2593 }
2594 }
2595 return (error);
2596 }
2597
2598 static int
uipc_sense(struct socket * so,struct stat * sb)2599 uipc_sense(struct socket *so, struct stat *sb)
2600 {
2601 struct unpcb *unp;
2602
2603 unp = sotounpcb(so);
2604 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
2605
2606 sb->st_blksize = so->so_snd.sb_hiwat;
2607 sb->st_dev = NODEV;
2608 sb->st_ino = unp->unp_ino;
2609 return (0);
2610 }
2611
2612 static int
uipc_shutdown(struct socket * so,enum shutdown_how how)2613 uipc_shutdown(struct socket *so, enum shutdown_how how)
2614 {
2615 struct unpcb *unp = sotounpcb(so);
2616 int error;
2617
2618 SOCK_LOCK(so);
2619 if (SOLISTENING(so)) {
2620 if (how != SHUT_WR) {
2621 so->so_error = ECONNABORTED;
2622 solisten_wakeup(so); /* unlocks so */
2623 } else
2624 SOCK_UNLOCK(so);
2625 return (ENOTCONN);
2626 } else if ((so->so_state &
2627 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2628 /*
2629 * POSIX mandates us to just return ENOTCONN when shutdown(2) is
2630 * invoked on a datagram sockets, however historically we would
2631 * actually tear socket down. This is known to be leveraged by
2632 * some applications to unblock process waiting in recv(2) by
2633 * other process that it shares that socket with. Try to meet
2634 * both backward-compatibility and POSIX requirements by forcing
2635 * ENOTCONN but still flushing buffers and performing wakeup(9).
2636 *
2637 * XXXGL: it remains unknown what applications expect this
2638 * behavior and is this isolated to unix/dgram or inet/dgram or
2639 * both. See: D10351, D3039.
2640 */
2641 error = ENOTCONN;
2642 if (so->so_type != SOCK_DGRAM) {
2643 SOCK_UNLOCK(so);
2644 return (error);
2645 }
2646 } else
2647 error = 0;
2648 SOCK_UNLOCK(so);
2649
2650 switch (how) {
2651 case SHUT_RD:
2652 if (so->so_type == SOCK_DGRAM)
2653 socantrcvmore(so);
2654 else
2655 uipc_cantrcvmore(so);
2656 unp_dispose(so);
2657 break;
2658 case SHUT_RDWR:
2659 if (so->so_type == SOCK_DGRAM)
2660 socantrcvmore(so);
2661 else
2662 uipc_cantrcvmore(so);
2663 unp_dispose(so);
2664 /* FALLTHROUGH */
2665 case SHUT_WR:
2666 if (so->so_type == SOCK_DGRAM) {
2667 socantsendmore(so);
2668 } else {
2669 UNP_PCB_LOCK(unp);
2670 if (unp->unp_conn != NULL)
2671 uipc_cantrcvmore(unp->unp_conn->unp_socket);
2672 UNP_PCB_UNLOCK(unp);
2673 }
2674 }
2675 wakeup(&so->so_timeo);
2676
2677 return (error);
2678 }
2679
2680 static int
uipc_sockaddr(struct socket * so,struct sockaddr * ret)2681 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
2682 {
2683 struct unpcb *unp;
2684 const struct sockaddr *sa;
2685
2686 unp = sotounpcb(so);
2687 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
2688
2689 UNP_PCB_LOCK(unp);
2690 if (unp->unp_addr != NULL)
2691 sa = (struct sockaddr *) unp->unp_addr;
2692 else
2693 sa = &sun_noname;
2694 bcopy(sa, ret, sa->sa_len);
2695 UNP_PCB_UNLOCK(unp);
2696 return (0);
2697 }
2698
2699 static int
uipc_ctloutput(struct socket * so,struct sockopt * sopt)2700 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
2701 {
2702 struct unpcb *unp;
2703 struct xucred xu;
2704 int error, optval;
2705
2706 if (sopt->sopt_level != SOL_LOCAL)
2707 return (EINVAL);
2708
2709 unp = sotounpcb(so);
2710 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
2711 error = 0;
2712 switch (sopt->sopt_dir) {
2713 case SOPT_GET:
2714 switch (sopt->sopt_name) {
2715 case LOCAL_PEERCRED:
2716 UNP_PCB_LOCK(unp);
2717 if (unp->unp_flags & UNP_HAVEPC)
2718 xu = unp->unp_peercred;
2719 else {
2720 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2721 error = ENOTCONN;
2722 else
2723 error = EINVAL;
2724 }
2725 UNP_PCB_UNLOCK(unp);
2726 if (error == 0)
2727 error = sooptcopyout(sopt, &xu, sizeof(xu));
2728 break;
2729
2730 case LOCAL_CREDS:
2731 /* Unlocked read. */
2732 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
2733 error = sooptcopyout(sopt, &optval, sizeof(optval));
2734 break;
2735
2736 case LOCAL_CREDS_PERSISTENT:
2737 /* Unlocked read. */
2738 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
2739 error = sooptcopyout(sopt, &optval, sizeof(optval));
2740 break;
2741
2742 default:
2743 error = EOPNOTSUPP;
2744 break;
2745 }
2746 break;
2747
2748 case SOPT_SET:
2749 switch (sopt->sopt_name) {
2750 case LOCAL_CREDS:
2751 case LOCAL_CREDS_PERSISTENT:
2752 error = sooptcopyin(sopt, &optval, sizeof(optval),
2753 sizeof(optval));
2754 if (error)
2755 break;
2756
2757 #define OPTSET(bit, exclusive) do { \
2758 UNP_PCB_LOCK(unp); \
2759 if (optval) { \
2760 if ((unp->unp_flags & (exclusive)) != 0) { \
2761 UNP_PCB_UNLOCK(unp); \
2762 error = EINVAL; \
2763 break; \
2764 } \
2765 unp->unp_flags |= (bit); \
2766 } else \
2767 unp->unp_flags &= ~(bit); \
2768 UNP_PCB_UNLOCK(unp); \
2769 } while (0)
2770
2771 switch (sopt->sopt_name) {
2772 case LOCAL_CREDS:
2773 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
2774 break;
2775
2776 case LOCAL_CREDS_PERSISTENT:
2777 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
2778 break;
2779
2780 default:
2781 break;
2782 }
2783 break;
2784 #undef OPTSET
2785 default:
2786 error = ENOPROTOOPT;
2787 break;
2788 }
2789 break;
2790
2791 default:
2792 error = EOPNOTSUPP;
2793 break;
2794 }
2795 return (error);
2796 }
2797
2798 static int
unp_connect(struct socket * so,struct sockaddr * nam,struct thread * td)2799 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
2800 {
2801
2802 return (unp_connectat(AT_FDCWD, so, nam, td, false));
2803 }
2804
2805 static int
unp_connectat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td,bool return_locked)2806 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
2807 struct thread *td, bool return_locked)
2808 {
2809 struct mtx *vplock;
2810 struct sockaddr_un *soun;
2811 struct vnode *vp;
2812 struct socket *so2;
2813 struct unpcb *unp, *unp2, *unp3;
2814 struct nameidata nd;
2815 char buf[SOCK_MAXADDRLEN];
2816 struct sockaddr *sa;
2817 cap_rights_t rights;
2818 int error, len;
2819 bool connreq;
2820
2821 CURVNET_ASSERT_SET();
2822
2823 if (nam->sa_family != AF_UNIX)
2824 return (EAFNOSUPPORT);
2825 if (nam->sa_len > sizeof(struct sockaddr_un))
2826 return (EINVAL);
2827 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
2828 if (len <= 0)
2829 return (EINVAL);
2830 soun = (struct sockaddr_un *)nam;
2831 bcopy(soun->sun_path, buf, len);
2832 buf[len] = 0;
2833
2834 error = 0;
2835 unp = sotounpcb(so);
2836 UNP_PCB_LOCK(unp);
2837 for (;;) {
2838 /*
2839 * Wait for connection state to stabilize. If a connection
2840 * already exists, give up. For datagram sockets, which permit
2841 * multiple consecutive connect(2) calls, upper layers are
2842 * responsible for disconnecting in advance of a subsequent
2843 * connect(2), but this is not synchronized with PCB connection
2844 * state.
2845 *
2846 * Also make sure that no threads are currently attempting to
2847 * lock the peer socket, to ensure that unp_conn cannot
2848 * transition between two valid sockets while locks are dropped.
2849 */
2850 if (SOLISTENING(so))
2851 error = EOPNOTSUPP;
2852 else if (unp->unp_conn != NULL)
2853 error = EISCONN;
2854 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
2855 error = EALREADY;
2856 }
2857 if (error != 0) {
2858 UNP_PCB_UNLOCK(unp);
2859 return (error);
2860 }
2861 if (unp->unp_pairbusy > 0) {
2862 unp->unp_flags |= UNP_WAITING;
2863 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
2864 continue;
2865 }
2866 break;
2867 }
2868 unp->unp_flags |= UNP_CONNECTING;
2869 UNP_PCB_UNLOCK(unp);
2870
2871 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
2872 if (connreq)
2873 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
2874 else
2875 sa = NULL;
2876 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
2877 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
2878 error = namei(&nd);
2879 if (error)
2880 vp = NULL;
2881 else
2882 vp = nd.ni_vp;
2883 ASSERT_VOP_LOCKED(vp, "unp_connect");
2884 if (error)
2885 goto bad;
2886 NDFREE_PNBUF(&nd);
2887
2888 if (vp->v_type != VSOCK) {
2889 error = ENOTSOCK;
2890 goto bad;
2891 }
2892 #ifdef MAC
2893 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
2894 if (error)
2895 goto bad;
2896 #endif
2897 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
2898 if (error)
2899 goto bad;
2900
2901 unp = sotounpcb(so);
2902 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
2903
2904 vplock = mtx_pool_find(unp_vp_mtxpool, vp);
2905 mtx_lock(vplock);
2906 VOP_UNP_CONNECT(vp, &unp2);
2907 if (unp2 == NULL) {
2908 error = ECONNREFUSED;
2909 goto bad2;
2910 }
2911 so2 = unp2->unp_socket;
2912 if (so->so_type != so2->so_type) {
2913 error = EPROTOTYPE;
2914 goto bad2;
2915 }
2916 if (connreq) {
2917 if (SOLISTENING(so2))
2918 so2 = solisten_clone(so2);
2919 else
2920 so2 = NULL;
2921 if (so2 == NULL) {
2922 error = ECONNREFUSED;
2923 goto bad2;
2924 }
2925 if ((error = uipc_attach(so2, 0, NULL)) != 0) {
2926 sodealloc(so2);
2927 goto bad2;
2928 }
2929 unp3 = sotounpcb(so2);
2930 unp_pcb_lock_pair(unp2, unp3);
2931 if (unp2->unp_addr != NULL) {
2932 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
2933 unp3->unp_addr = (struct sockaddr_un *) sa;
2934 sa = NULL;
2935 }
2936
2937 unp_copy_peercred(td, unp3, unp, unp2);
2938
2939 UNP_PCB_UNLOCK(unp2);
2940 unp2 = unp3;
2941
2942 /*
2943 * It is safe to block on the PCB lock here since unp2 is
2944 * nascent and cannot be connected to any other sockets.
2945 */
2946 UNP_PCB_LOCK(unp);
2947 #ifdef MAC
2948 mac_socketpeer_set_from_socket(so, so2);
2949 mac_socketpeer_set_from_socket(so2, so);
2950 #endif
2951 } else {
2952 unp_pcb_lock_pair(unp, unp2);
2953 }
2954 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
2955 sotounpcb(so2) == unp2,
2956 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
2957 unp_connect2(so, so2, connreq);
2958 if (connreq)
2959 (void)solisten_enqueue(so2, SS_ISCONNECTED);
2960 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2961 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2962 unp->unp_flags &= ~UNP_CONNECTING;
2963 if (!return_locked)
2964 unp_pcb_unlock_pair(unp, unp2);
2965 bad2:
2966 mtx_unlock(vplock);
2967 bad:
2968 if (vp != NULL) {
2969 /*
2970 * If we are returning locked (called via uipc_sosend_dgram()),
2971 * we need to be sure that vput() won't sleep. This is
2972 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2973 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2974 */
2975 MPASS(!(return_locked && connreq));
2976 vput(vp);
2977 }
2978 free(sa, M_SONAME);
2979 if (__predict_false(error)) {
2980 UNP_PCB_LOCK(unp);
2981 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2982 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2983 unp->unp_flags &= ~UNP_CONNECTING;
2984 UNP_PCB_UNLOCK(unp);
2985 }
2986 return (error);
2987 }
2988
2989 /*
2990 * Set socket peer credentials at connection time.
2991 *
2992 * The client's PCB credentials are copied from its process structure. The
2993 * server's PCB credentials are copied from the socket on which it called
2994 * listen(2). uipc_listen cached that process's credentials at the time.
2995 */
2996 void
unp_copy_peercred(struct thread * td,struct unpcb * client_unp,struct unpcb * server_unp,struct unpcb * listen_unp)2997 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2998 struct unpcb *server_unp, struct unpcb *listen_unp)
2999 {
3000 cru2xt(td, &client_unp->unp_peercred);
3001 client_unp->unp_flags |= UNP_HAVEPC;
3002
3003 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
3004 sizeof(server_unp->unp_peercred));
3005 server_unp->unp_flags |= UNP_HAVEPC;
3006 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
3007 }
3008
3009 /*
3010 * unix/stream & unix/seqpacket version of soisconnected().
3011 *
3012 * The crucial thing we are doing here is setting up the uxst_peer linkage,
3013 * holding unp and receive buffer locks of the both sockets. The disconnect
3014 * procedure does the same. This gives as a safe way to access the peer in the
3015 * send(2) and recv(2) during the socket lifetime.
3016 *
3017 * The less important thing is event notification of the fact that a socket is
3018 * now connected. It is unusual for a software to put a socket into event
3019 * mechanism before connect(2), but is supposed to be supported. Note that
3020 * there can not be any sleeping I/O on the socket, yet, only presence in the
3021 * select/poll/kevent.
3022 *
3023 * This function can be called via two call paths:
3024 * 1) socketpair(2) - in this case socket has not been yet reported to userland
3025 * and just can't have any event notifications mechanisms set up. The
3026 * 'wakeup' boolean is always false.
3027 * 2) connect(2) of existing socket to a recent clone of a listener:
3028 * 2.1) Socket that connect(2)s will have 'wakeup' true. An application
3029 * could have already put it into event mechanism, is it shall be
3030 * reported as readable and as writable.
3031 * 2.2) Socket that was just cloned with solisten_clone(). Same as 1).
3032 */
3033 static void
unp_soisconnected(struct socket * so,bool wakeup)3034 unp_soisconnected(struct socket *so, bool wakeup)
3035 {
3036 struct socket *so2 = sotounpcb(so)->unp_conn->unp_socket;
3037 struct sockbuf *sb;
3038
3039 SOCK_LOCK_ASSERT(so);
3040 UNP_PCB_LOCK_ASSERT(sotounpcb(so));
3041 UNP_PCB_LOCK_ASSERT(sotounpcb(so2));
3042 SOCK_RECVBUF_LOCK_ASSERT(so);
3043 SOCK_RECVBUF_LOCK_ASSERT(so2);
3044
3045 MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3046 MPASS((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
3047 SS_ISDISCONNECTING)) == 0);
3048 MPASS(so->so_qstate == SQ_NONE);
3049
3050 so->so_state &= ~SS_ISDISCONNECTED;
3051 so->so_state |= SS_ISCONNECTED;
3052
3053 sb = &so2->so_rcv;
3054 sb->uxst_peer = so;
3055
3056 if (wakeup) {
3057 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
3058 sb = &so->so_rcv;
3059 selwakeuppri(sb->sb_sel, PSOCK);
3060 SOCK_SENDBUF_LOCK_ASSERT(so);
3061 sb = &so->so_snd;
3062 selwakeuppri(sb->sb_sel, PSOCK);
3063 SOCK_SENDBUF_UNLOCK(so);
3064 }
3065 }
3066
3067 static void
unp_connect2(struct socket * so,struct socket * so2,bool wakeup)3068 unp_connect2(struct socket *so, struct socket *so2, bool wakeup)
3069 {
3070 struct unpcb *unp;
3071 struct unpcb *unp2;
3072
3073 MPASS(so2->so_type == so->so_type);
3074 unp = sotounpcb(so);
3075 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
3076 unp2 = sotounpcb(so2);
3077 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
3078
3079 UNP_PCB_LOCK_ASSERT(unp);
3080 UNP_PCB_LOCK_ASSERT(unp2);
3081 KASSERT(unp->unp_conn == NULL,
3082 ("%s: socket %p is already connected", __func__, unp));
3083
3084 unp->unp_conn = unp2;
3085 unp_pcb_hold(unp2);
3086 unp_pcb_hold(unp);
3087 switch (so->so_type) {
3088 case SOCK_DGRAM:
3089 UNP_REF_LIST_LOCK();
3090 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
3091 UNP_REF_LIST_UNLOCK();
3092 soisconnected(so);
3093 break;
3094
3095 case SOCK_STREAM:
3096 case SOCK_SEQPACKET:
3097 KASSERT(unp2->unp_conn == NULL,
3098 ("%s: socket %p is already connected", __func__, unp2));
3099 unp2->unp_conn = unp;
3100 SOCK_LOCK(so);
3101 SOCK_LOCK(so2);
3102 if (wakeup) /* Avoid LOR with receive buffer lock. */
3103 SOCK_SENDBUF_LOCK(so);
3104 SOCK_RECVBUF_LOCK(so);
3105 SOCK_RECVBUF_LOCK(so2);
3106 unp_soisconnected(so, wakeup); /* Will unlock send buffer. */
3107 unp_soisconnected(so2, false);
3108 SOCK_RECVBUF_UNLOCK(so);
3109 SOCK_RECVBUF_UNLOCK(so2);
3110 SOCK_UNLOCK(so);
3111 SOCK_UNLOCK(so2);
3112 break;
3113
3114 default:
3115 panic("unp_connect2");
3116 }
3117 }
3118
3119 static void
unp_soisdisconnected(struct socket * so)3120 unp_soisdisconnected(struct socket *so)
3121 {
3122 SOCK_LOCK_ASSERT(so);
3123 SOCK_RECVBUF_LOCK_ASSERT(so);
3124 MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET);
3125 MPASS(!SOLISTENING(so));
3126 MPASS((so->so_state & (SS_ISCONNECTING | SS_ISDISCONNECTING |
3127 SS_ISDISCONNECTED)) == 0);
3128 MPASS(so->so_state & SS_ISCONNECTED);
3129
3130 so->so_state |= SS_ISDISCONNECTED;
3131 so->so_state &= ~SS_ISCONNECTED;
3132 so->so_rcv.uxst_peer = NULL;
3133 socantrcvmore_locked(so);
3134 }
3135
3136 static void
unp_disconnect(struct unpcb * unp,struct unpcb * unp2)3137 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
3138 {
3139 struct socket *so, *so2;
3140 struct mbuf *m = NULL;
3141 #ifdef INVARIANTS
3142 struct unpcb *unptmp;
3143 #endif
3144
3145 UNP_PCB_LOCK_ASSERT(unp);
3146 UNP_PCB_LOCK_ASSERT(unp2);
3147 KASSERT(unp->unp_conn == unp2,
3148 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
3149
3150 unp->unp_conn = NULL;
3151 so = unp->unp_socket;
3152 so2 = unp2->unp_socket;
3153 switch (unp->unp_socket->so_type) {
3154 case SOCK_DGRAM:
3155 /*
3156 * Remove our send socket buffer from the peer's receive buffer.
3157 * Move the data to the receive buffer only if it is empty.
3158 * This is a protection against a scenario where a peer
3159 * connects, floods and disconnects, effectively blocking
3160 * sendto() from unconnected sockets.
3161 */
3162 SOCK_RECVBUF_LOCK(so2);
3163 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
3164 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
3165 uxdg_clist);
3166 if (__predict_true((so2->so_rcv.sb_state &
3167 SBS_CANTRCVMORE) == 0) &&
3168 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
3169 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
3170 &so->so_snd.uxdg_mb);
3171 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
3172 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
3173 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
3174 } else {
3175 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
3176 STAILQ_INIT(&so->so_snd.uxdg_mb);
3177 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
3178 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
3179 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
3180 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
3181 }
3182 /* Note: so may reconnect. */
3183 so->so_snd.uxdg_cc = 0;
3184 so->so_snd.uxdg_ctl = 0;
3185 so->so_snd.uxdg_mbcnt = 0;
3186 }
3187 SOCK_RECVBUF_UNLOCK(so2);
3188 UNP_REF_LIST_LOCK();
3189 #ifdef INVARIANTS
3190 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
3191 if (unptmp == unp)
3192 break;
3193 }
3194 KASSERT(unptmp != NULL,
3195 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
3196 #endif
3197 LIST_REMOVE(unp, unp_reflink);
3198 UNP_REF_LIST_UNLOCK();
3199 if (so) {
3200 SOCK_LOCK(so);
3201 so->so_state &= ~SS_ISCONNECTED;
3202 SOCK_UNLOCK(so);
3203 }
3204 break;
3205
3206 case SOCK_STREAM:
3207 case SOCK_SEQPACKET:
3208 SOCK_LOCK(so);
3209 SOCK_LOCK(so2);
3210 SOCK_RECVBUF_LOCK(so);
3211 SOCK_RECVBUF_LOCK(so2);
3212 unp_soisdisconnected(so);
3213 MPASS(unp2->unp_conn == unp);
3214 unp2->unp_conn = NULL;
3215 unp_soisdisconnected(so2);
3216 SOCK_UNLOCK(so);
3217 SOCK_UNLOCK(so2);
3218 break;
3219 }
3220
3221 if (unp == unp2) {
3222 unp_pcb_rele_notlast(unp);
3223 if (!unp_pcb_rele(unp))
3224 UNP_PCB_UNLOCK(unp);
3225 } else {
3226 if (!unp_pcb_rele(unp))
3227 UNP_PCB_UNLOCK(unp);
3228 if (!unp_pcb_rele(unp2))
3229 UNP_PCB_UNLOCK(unp2);
3230 }
3231
3232 if (m != NULL) {
3233 unp_scan(m, unp_freerights);
3234 m_freemp(m);
3235 }
3236 }
3237
3238 /*
3239 * unp_pcblist() walks the global list of struct unpcb's to generate a
3240 * pointer list, bumping the refcount on each unpcb. It then copies them out
3241 * sequentially, validating the generation number on each to see if it has
3242 * been detached. All of this is necessary because copyout() may sleep on
3243 * disk I/O.
3244 */
3245 static int
unp_pcblist(SYSCTL_HANDLER_ARGS)3246 unp_pcblist(SYSCTL_HANDLER_ARGS)
3247 {
3248 struct unpcb *unp, **unp_list;
3249 unp_gen_t gencnt;
3250 struct xunpgen *xug;
3251 struct unp_head *head;
3252 struct xunpcb *xu;
3253 u_int i;
3254 int error, n;
3255
3256 switch ((intptr_t)arg1) {
3257 case SOCK_STREAM:
3258 head = &unp_shead;
3259 break;
3260
3261 case SOCK_DGRAM:
3262 head = &unp_dhead;
3263 break;
3264
3265 case SOCK_SEQPACKET:
3266 head = &unp_sphead;
3267 break;
3268
3269 default:
3270 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
3271 }
3272
3273 /*
3274 * The process of preparing the PCB list is too time-consuming and
3275 * resource-intensive to repeat twice on every request.
3276 */
3277 if (req->oldptr == NULL) {
3278 n = unp_count;
3279 req->oldidx = 2 * (sizeof *xug)
3280 + (n + n/8) * sizeof(struct xunpcb);
3281 return (0);
3282 }
3283
3284 if (req->newptr != NULL)
3285 return (EPERM);
3286
3287 /*
3288 * OK, now we're committed to doing something.
3289 */
3290 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
3291 UNP_LINK_RLOCK();
3292 gencnt = unp_gencnt;
3293 n = unp_count;
3294 UNP_LINK_RUNLOCK();
3295
3296 xug->xug_len = sizeof *xug;
3297 xug->xug_count = n;
3298 xug->xug_gen = gencnt;
3299 xug->xug_sogen = so_gencnt;
3300 error = SYSCTL_OUT(req, xug, sizeof *xug);
3301 if (error) {
3302 free(xug, M_TEMP);
3303 return (error);
3304 }
3305
3306 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
3307
3308 UNP_LINK_RLOCK();
3309 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
3310 unp = LIST_NEXT(unp, unp_link)) {
3311 UNP_PCB_LOCK(unp);
3312 if (unp->unp_gencnt <= gencnt) {
3313 if (cr_cansee(req->td->td_ucred,
3314 unp->unp_socket->so_cred)) {
3315 UNP_PCB_UNLOCK(unp);
3316 continue;
3317 }
3318 unp_list[i++] = unp;
3319 unp_pcb_hold(unp);
3320 }
3321 UNP_PCB_UNLOCK(unp);
3322 }
3323 UNP_LINK_RUNLOCK();
3324 n = i; /* In case we lost some during malloc. */
3325
3326 error = 0;
3327 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
3328 for (i = 0; i < n; i++) {
3329 unp = unp_list[i];
3330 UNP_PCB_LOCK(unp);
3331 if (unp_pcb_rele(unp))
3332 continue;
3333
3334 if (unp->unp_gencnt <= gencnt) {
3335 xu->xu_len = sizeof *xu;
3336 xu->xu_unpp = (uintptr_t)unp;
3337 /*
3338 * XXX - need more locking here to protect against
3339 * connect/disconnect races for SMP.
3340 */
3341 if (unp->unp_addr != NULL)
3342 bcopy(unp->unp_addr, &xu->xu_addr,
3343 unp->unp_addr->sun_len);
3344 else
3345 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
3346 if (unp->unp_conn != NULL &&
3347 unp->unp_conn->unp_addr != NULL)
3348 bcopy(unp->unp_conn->unp_addr,
3349 &xu->xu_caddr,
3350 unp->unp_conn->unp_addr->sun_len);
3351 else
3352 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
3353 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
3354 xu->unp_conn = (uintptr_t)unp->unp_conn;
3355 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
3356 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
3357 xu->unp_gencnt = unp->unp_gencnt;
3358 sotoxsocket(unp->unp_socket, &xu->xu_socket);
3359 UNP_PCB_UNLOCK(unp);
3360 error = SYSCTL_OUT(req, xu, sizeof *xu);
3361 } else {
3362 UNP_PCB_UNLOCK(unp);
3363 }
3364 }
3365 free(xu, M_TEMP);
3366 if (!error) {
3367 /*
3368 * Give the user an updated idea of our state. If the
3369 * generation differs from what we told her before, she knows
3370 * that something happened while we were processing this
3371 * request, and it might be necessary to retry.
3372 */
3373 xug->xug_gen = unp_gencnt;
3374 xug->xug_sogen = so_gencnt;
3375 xug->xug_count = unp_count;
3376 error = SYSCTL_OUT(req, xug, sizeof *xug);
3377 }
3378 free(unp_list, M_TEMP);
3379 free(xug, M_TEMP);
3380 return (error);
3381 }
3382
3383 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
3384 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3385 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
3386 "List of active local datagram sockets");
3387 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
3388 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3389 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
3390 "List of active local stream sockets");
3391 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
3392 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
3393 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
3394 "List of active local seqpacket sockets");
3395
3396 static void
unp_drop(struct unpcb * unp)3397 unp_drop(struct unpcb *unp)
3398 {
3399 struct socket *so;
3400 struct unpcb *unp2;
3401
3402 /*
3403 * Regardless of whether the socket's peer dropped the connection
3404 * with this socket by aborting or disconnecting, POSIX requires
3405 * that ECONNRESET is returned on next connected send(2) in case of
3406 * a SOCK_DGRAM socket and EPIPE for SOCK_STREAM.
3407 */
3408 UNP_PCB_LOCK(unp);
3409 if ((so = unp->unp_socket) != NULL)
3410 so->so_error =
3411 so->so_proto->pr_type == SOCK_DGRAM ? ECONNRESET : EPIPE;
3412 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
3413 /* Last reference dropped in unp_disconnect(). */
3414 unp_pcb_rele_notlast(unp);
3415 unp_disconnect(unp, unp2);
3416 } else if (!unp_pcb_rele(unp)) {
3417 UNP_PCB_UNLOCK(unp);
3418 }
3419 }
3420
3421 static void
unp_freerights(struct filedescent ** fdep,int fdcount)3422 unp_freerights(struct filedescent **fdep, int fdcount)
3423 {
3424 struct file *fp;
3425 int i;
3426
3427 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
3428
3429 for (i = 0; i < fdcount; i++) {
3430 fp = fdep[i]->fde_file;
3431 filecaps_free(&fdep[i]->fde_caps);
3432 unp_discard(fp);
3433 }
3434 free(fdep[0], M_FILECAPS);
3435 }
3436
3437 static bool
restrict_rights(struct file * fp,struct thread * td)3438 restrict_rights(struct file *fp, struct thread *td)
3439 {
3440 struct prison *prison1, *prison2;
3441
3442 prison1 = fp->f_cred->cr_prison;
3443 prison2 = td->td_ucred->cr_prison;
3444 return (prison1 != prison2 && prison1->pr_root != prison2->pr_root &&
3445 prison2 != &prison0);
3446 }
3447
3448 static int
unp_externalize(struct mbuf * control,struct mbuf ** controlp,int flags)3449 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
3450 {
3451 struct thread *td = curthread; /* XXX */
3452 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
3453 int *fdp;
3454 struct filedesc *fdesc = td->td_proc->p_fd;
3455 struct filedescent **fdep;
3456 void *data;
3457 socklen_t clen = control->m_len, datalen;
3458 int error, fdflags, newfds;
3459 u_int newlen;
3460
3461 UNP_LINK_UNLOCK_ASSERT();
3462
3463 fdflags = ((flags & MSG_CMSG_CLOEXEC) ? O_CLOEXEC : 0) |
3464 ((flags & MSG_CMSG_CLOFORK) ? O_CLOFORK : 0);
3465
3466 error = 0;
3467 if (controlp != NULL) /* controlp == NULL => free control messages */
3468 *controlp = NULL;
3469 while (cm != NULL) {
3470 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
3471
3472 data = CMSG_DATA(cm);
3473 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
3474 if (cm->cmsg_level == SOL_SOCKET
3475 && cm->cmsg_type == SCM_RIGHTS) {
3476 newfds = datalen / sizeof(*fdep);
3477 if (newfds == 0)
3478 goto next;
3479 fdep = data;
3480
3481 /* If we're not outputting the descriptors free them. */
3482 if (error || controlp == NULL) {
3483 unp_freerights(fdep, newfds);
3484 goto next;
3485 }
3486 FILEDESC_XLOCK(fdesc);
3487
3488 /*
3489 * Now change each pointer to an fd in the global
3490 * table to an integer that is the index to the local
3491 * fd table entry that we set up to point to the
3492 * global one we are transferring.
3493 */
3494 newlen = newfds * sizeof(int);
3495 *controlp = sbcreatecontrol(NULL, newlen,
3496 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
3497
3498 fdp = (int *)
3499 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
3500 if ((error = fdallocn(td, 0, fdp, newfds))) {
3501 FILEDESC_XUNLOCK(fdesc);
3502 unp_freerights(fdep, newfds);
3503 m_freem(*controlp);
3504 *controlp = NULL;
3505 goto next;
3506 }
3507 for (int i = 0; i < newfds; i++, fdp++) {
3508 struct file *fp;
3509
3510 fp = fdep[i]->fde_file;
3511 _finstall(fdesc, fp, *fdp, fdflags |
3512 (restrict_rights(fp, td) ?
3513 O_RESOLVE_BENEATH : 0), &fdep[i]->fde_caps);
3514 unp_externalize_fp(fp);
3515 }
3516
3517 /*
3518 * The new type indicates that the mbuf data refers to
3519 * kernel resources that may need to be released before
3520 * the mbuf is freed.
3521 */
3522 m_chtype(*controlp, MT_EXTCONTROL);
3523 FILEDESC_XUNLOCK(fdesc);
3524 free(fdep[0], M_FILECAPS);
3525 } else {
3526 /* We can just copy anything else across. */
3527 if (error || controlp == NULL)
3528 goto next;
3529 *controlp = sbcreatecontrol(NULL, datalen,
3530 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
3531 bcopy(data,
3532 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
3533 datalen);
3534 }
3535 controlp = &(*controlp)->m_next;
3536
3537 next:
3538 if (CMSG_SPACE(datalen) < clen) {
3539 clen -= CMSG_SPACE(datalen);
3540 cm = (struct cmsghdr *)
3541 ((caddr_t)cm + CMSG_SPACE(datalen));
3542 } else {
3543 clen = 0;
3544 cm = NULL;
3545 }
3546 }
3547
3548 return (error);
3549 }
3550
3551 static void
unp_zone_change(void * tag)3552 unp_zone_change(void *tag)
3553 {
3554
3555 uma_zone_set_max(unp_zone, maxsockets);
3556 }
3557
3558 #ifdef INVARIANTS
3559 static void
unp_zdtor(void * mem,int size __unused,void * arg __unused)3560 unp_zdtor(void *mem, int size __unused, void *arg __unused)
3561 {
3562 struct unpcb *unp;
3563
3564 unp = mem;
3565
3566 KASSERT(LIST_EMPTY(&unp->unp_refs),
3567 ("%s: unpcb %p has lingering refs", __func__, unp));
3568 KASSERT(unp->unp_socket == NULL,
3569 ("%s: unpcb %p has socket backpointer", __func__, unp));
3570 KASSERT(unp->unp_vnode == NULL,
3571 ("%s: unpcb %p has vnode references", __func__, unp));
3572 KASSERT(unp->unp_conn == NULL,
3573 ("%s: unpcb %p is still connected", __func__, unp));
3574 KASSERT(unp->unp_addr == NULL,
3575 ("%s: unpcb %p has leaked addr", __func__, unp));
3576 }
3577 #endif
3578
3579 static void
unp_init(void * arg __unused)3580 unp_init(void *arg __unused)
3581 {
3582 uma_dtor dtor;
3583
3584 #ifdef INVARIANTS
3585 dtor = unp_zdtor;
3586 #else
3587 dtor = NULL;
3588 #endif
3589 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
3590 NULL, NULL, UMA_ALIGN_CACHE, 0);
3591 uma_zone_set_max(unp_zone, maxsockets);
3592 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
3593 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
3594 NULL, EVENTHANDLER_PRI_ANY);
3595 LIST_INIT(&unp_dhead);
3596 LIST_INIT(&unp_shead);
3597 LIST_INIT(&unp_sphead);
3598 SLIST_INIT(&unp_defers);
3599 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
3600 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
3601 UNP_LINK_LOCK_INIT();
3602 UNP_DEFERRED_LOCK_INIT();
3603 unp_vp_mtxpool = mtx_pool_create("unp vp mtxpool", 32, MTX_DEF);
3604 }
3605 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
3606
3607 static void
unp_internalize_cleanup_rights(struct mbuf * control)3608 unp_internalize_cleanup_rights(struct mbuf *control)
3609 {
3610 struct cmsghdr *cp;
3611 struct mbuf *m;
3612 void *data;
3613 socklen_t datalen;
3614
3615 for (m = control; m != NULL; m = m->m_next) {
3616 cp = mtod(m, struct cmsghdr *);
3617 if (cp->cmsg_level != SOL_SOCKET ||
3618 cp->cmsg_type != SCM_RIGHTS)
3619 continue;
3620 data = CMSG_DATA(cp);
3621 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
3622 unp_freerights(data, datalen / sizeof(struct filedesc *));
3623 }
3624 }
3625
3626 static int
unp_internalize(struct mbuf * control,struct mchain * mc,struct thread * td)3627 unp_internalize(struct mbuf *control, struct mchain *mc, struct thread *td)
3628 {
3629 struct proc *p;
3630 struct filedesc *fdesc;
3631 struct bintime *bt;
3632 struct cmsghdr *cm;
3633 struct cmsgcred *cmcred;
3634 struct mbuf *m;
3635 struct filedescent *fde, **fdep, *fdev;
3636 struct file *fp;
3637 struct timeval *tv;
3638 struct timespec *ts;
3639 void *data;
3640 socklen_t clen, datalen;
3641 int i, j, error, *fdp, oldfds;
3642 u_int newlen;
3643
3644 MPASS(control->m_next == NULL); /* COMPAT_OLDSOCK may violate */
3645 UNP_LINK_UNLOCK_ASSERT();
3646
3647 p = td->td_proc;
3648 fdesc = p->p_fd;
3649 error = 0;
3650 *mc = MCHAIN_INITIALIZER(mc);
3651 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
3652 data = CMSG_DATA(cm);
3653
3654 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
3655 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
3656 (char *)cm + cm->cmsg_len >= (char *)data;
3657
3658 clen -= min(CMSG_SPACE(datalen), clen),
3659 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
3660 data = CMSG_DATA(cm)) {
3661 datalen = (char *)cm + cm->cmsg_len - (char *)data;
3662 switch (cm->cmsg_type) {
3663 case SCM_CREDS:
3664 m = sbcreatecontrol(NULL, sizeof(*cmcred), SCM_CREDS,
3665 SOL_SOCKET, M_WAITOK);
3666 cmcred = (struct cmsgcred *)
3667 CMSG_DATA(mtod(m, struct cmsghdr *));
3668 cmcred->cmcred_pid = p->p_pid;
3669 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
3670 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
3671 cmcred->cmcred_euid = td->td_ucred->cr_uid;
3672 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
3673 CMGROUP_MAX);
3674 for (i = 0; i < cmcred->cmcred_ngroups; i++)
3675 cmcred->cmcred_groups[i] =
3676 td->td_ucred->cr_groups[i];
3677 break;
3678
3679 case SCM_RIGHTS:
3680 oldfds = datalen / sizeof (int);
3681 if (oldfds == 0)
3682 continue;
3683 /* On some machines sizeof pointer is bigger than
3684 * sizeof int, so we need to check if data fits into
3685 * single mbuf. We could allocate several mbufs, and
3686 * unp_externalize() should even properly handle that.
3687 * But it is not worth to complicate the code for an
3688 * insane scenario of passing over 200 file descriptors
3689 * at once.
3690 */
3691 newlen = oldfds * sizeof(fdep[0]);
3692 if (CMSG_SPACE(newlen) > MCLBYTES) {
3693 error = EMSGSIZE;
3694 goto out;
3695 }
3696 /*
3697 * Check that all the FDs passed in refer to legal
3698 * files. If not, reject the entire operation.
3699 */
3700 fdp = data;
3701 FILEDESC_SLOCK(fdesc);
3702 for (i = 0; i < oldfds; i++, fdp++) {
3703 fp = fget_noref(fdesc, *fdp);
3704 if (fp == NULL) {
3705 FILEDESC_SUNLOCK(fdesc);
3706 error = EBADF;
3707 goto out;
3708 }
3709 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
3710 FILEDESC_SUNLOCK(fdesc);
3711 error = EOPNOTSUPP;
3712 goto out;
3713 }
3714 }
3715
3716 /*
3717 * Now replace the integer FDs with pointers to the
3718 * file structure and capability rights.
3719 */
3720 m = sbcreatecontrol(NULL, newlen, SCM_RIGHTS,
3721 SOL_SOCKET, M_WAITOK);
3722 fdp = data;
3723 for (i = 0; i < oldfds; i++, fdp++) {
3724 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
3725 fdp = data;
3726 for (j = 0; j < i; j++, fdp++) {
3727 fdrop(fdesc->fd_ofiles[*fdp].
3728 fde_file, td);
3729 }
3730 FILEDESC_SUNLOCK(fdesc);
3731 error = EBADF;
3732 goto out;
3733 }
3734 }
3735 fdp = data;
3736 fdep = (struct filedescent **)
3737 CMSG_DATA(mtod(m, struct cmsghdr *));
3738 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
3739 M_WAITOK);
3740 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
3741 fde = &fdesc->fd_ofiles[*fdp];
3742 fdep[i] = fdev;
3743 fdep[i]->fde_file = fde->fde_file;
3744 filecaps_copy(&fde->fde_caps,
3745 &fdep[i]->fde_caps, true);
3746 unp_internalize_fp(fdep[i]->fde_file);
3747 }
3748 FILEDESC_SUNLOCK(fdesc);
3749 break;
3750
3751 case SCM_TIMESTAMP:
3752 m = sbcreatecontrol(NULL, sizeof(*tv), SCM_TIMESTAMP,
3753 SOL_SOCKET, M_WAITOK);
3754 tv = (struct timeval *)
3755 CMSG_DATA(mtod(m, struct cmsghdr *));
3756 microtime(tv);
3757 break;
3758
3759 case SCM_BINTIME:
3760 m = sbcreatecontrol(NULL, sizeof(*bt), SCM_BINTIME,
3761 SOL_SOCKET, M_WAITOK);
3762 bt = (struct bintime *)
3763 CMSG_DATA(mtod(m, struct cmsghdr *));
3764 bintime(bt);
3765 break;
3766
3767 case SCM_REALTIME:
3768 m = sbcreatecontrol(NULL, sizeof(*ts), SCM_REALTIME,
3769 SOL_SOCKET, M_WAITOK);
3770 ts = (struct timespec *)
3771 CMSG_DATA(mtod(m, struct cmsghdr *));
3772 nanotime(ts);
3773 break;
3774
3775 case SCM_MONOTONIC:
3776 m = sbcreatecontrol(NULL, sizeof(*ts), SCM_MONOTONIC,
3777 SOL_SOCKET, M_WAITOK);
3778 ts = (struct timespec *)
3779 CMSG_DATA(mtod(m, struct cmsghdr *));
3780 nanouptime(ts);
3781 break;
3782
3783 default:
3784 error = EINVAL;
3785 goto out;
3786 }
3787
3788 mc_append(mc, m);
3789 }
3790 if (clen > 0)
3791 error = EINVAL;
3792
3793 out:
3794 if (error != 0)
3795 unp_internalize_cleanup_rights(mc_first(mc));
3796 m_freem(control);
3797 return (error);
3798 }
3799
3800 static void
unp_addsockcred(struct thread * td,struct mchain * mc,int mode)3801 unp_addsockcred(struct thread *td, struct mchain *mc, int mode)
3802 {
3803 struct mbuf *m, *n, *n_prev;
3804 const struct cmsghdr *cm;
3805 int ngroups, i, cmsgtype;
3806 size_t ctrlsz;
3807
3808 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
3809 if (mode & UNP_WANTCRED_ALWAYS) {
3810 ctrlsz = SOCKCRED2SIZE(ngroups);
3811 cmsgtype = SCM_CREDS2;
3812 } else {
3813 ctrlsz = SOCKCREDSIZE(ngroups);
3814 cmsgtype = SCM_CREDS;
3815 }
3816
3817 /* XXXGL: uipc_sosend_*() need to be improved so that we can M_WAITOK */
3818 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
3819 if (m == NULL)
3820 return;
3821 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
3822
3823 if (mode & UNP_WANTCRED_ALWAYS) {
3824 struct sockcred2 *sc;
3825
3826 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
3827 sc->sc_version = 0;
3828 sc->sc_pid = td->td_proc->p_pid;
3829 sc->sc_uid = td->td_ucred->cr_ruid;
3830 sc->sc_euid = td->td_ucred->cr_uid;
3831 sc->sc_gid = td->td_ucred->cr_rgid;
3832 sc->sc_egid = td->td_ucred->cr_gid;
3833 sc->sc_ngroups = ngroups;
3834 for (i = 0; i < sc->sc_ngroups; i++)
3835 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
3836 } else {
3837 struct sockcred *sc;
3838
3839 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
3840 sc->sc_uid = td->td_ucred->cr_ruid;
3841 sc->sc_euid = td->td_ucred->cr_uid;
3842 sc->sc_gid = td->td_ucred->cr_rgid;
3843 sc->sc_egid = td->td_ucred->cr_gid;
3844 sc->sc_ngroups = ngroups;
3845 for (i = 0; i < sc->sc_ngroups; i++)
3846 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
3847 }
3848
3849 /*
3850 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
3851 * created SCM_CREDS control message (struct sockcred) has another
3852 * format.
3853 */
3854 if (!STAILQ_EMPTY(&mc->mc_q) && cmsgtype == SCM_CREDS)
3855 STAILQ_FOREACH_SAFE(n, &mc->mc_q, m_stailq, n_prev) {
3856 cm = mtod(n, struct cmsghdr *);
3857 if (cm->cmsg_level == SOL_SOCKET &&
3858 cm->cmsg_type == SCM_CREDS) {
3859 mc_remove(mc, n);
3860 m_free(n);
3861 }
3862 }
3863
3864 /* Prepend it to the head. */
3865 mc_prepend(mc, m);
3866 }
3867
3868 static struct unpcb *
fptounp(struct file * fp)3869 fptounp(struct file *fp)
3870 {
3871 struct socket *so;
3872
3873 if (fp->f_type != DTYPE_SOCKET)
3874 return (NULL);
3875 if ((so = fp->f_data) == NULL)
3876 return (NULL);
3877 if (so->so_proto->pr_domain != &localdomain)
3878 return (NULL);
3879 return sotounpcb(so);
3880 }
3881
3882 static void
unp_discard(struct file * fp)3883 unp_discard(struct file *fp)
3884 {
3885 struct unp_defer *dr;
3886
3887 if (unp_externalize_fp(fp)) {
3888 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
3889 dr->ud_fp = fp;
3890 UNP_DEFERRED_LOCK();
3891 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
3892 UNP_DEFERRED_UNLOCK();
3893 atomic_add_int(&unp_defers_count, 1);
3894 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
3895 } else
3896 closef_nothread(fp);
3897 }
3898
3899 static void
unp_process_defers(void * arg __unused,int pending)3900 unp_process_defers(void *arg __unused, int pending)
3901 {
3902 struct unp_defer *dr;
3903 SLIST_HEAD(, unp_defer) drl;
3904 int count;
3905
3906 SLIST_INIT(&drl);
3907 for (;;) {
3908 UNP_DEFERRED_LOCK();
3909 if (SLIST_FIRST(&unp_defers) == NULL) {
3910 UNP_DEFERRED_UNLOCK();
3911 break;
3912 }
3913 SLIST_SWAP(&unp_defers, &drl, unp_defer);
3914 UNP_DEFERRED_UNLOCK();
3915 count = 0;
3916 while ((dr = SLIST_FIRST(&drl)) != NULL) {
3917 SLIST_REMOVE_HEAD(&drl, ud_link);
3918 closef_nothread(dr->ud_fp);
3919 free(dr, M_TEMP);
3920 count++;
3921 }
3922 atomic_add_int(&unp_defers_count, -count);
3923 }
3924 }
3925
3926 static void
unp_internalize_fp(struct file * fp)3927 unp_internalize_fp(struct file *fp)
3928 {
3929 struct unpcb *unp;
3930
3931 UNP_LINK_WLOCK();
3932 if ((unp = fptounp(fp)) != NULL) {
3933 unp->unp_file = fp;
3934 unp->unp_msgcount++;
3935 }
3936 unp_rights++;
3937 UNP_LINK_WUNLOCK();
3938 }
3939
3940 static int
unp_externalize_fp(struct file * fp)3941 unp_externalize_fp(struct file *fp)
3942 {
3943 struct unpcb *unp;
3944 int ret;
3945
3946 UNP_LINK_WLOCK();
3947 if ((unp = fptounp(fp)) != NULL) {
3948 unp->unp_msgcount--;
3949 ret = 1;
3950 } else
3951 ret = 0;
3952 unp_rights--;
3953 UNP_LINK_WUNLOCK();
3954 return (ret);
3955 }
3956
3957 /*
3958 * unp_defer indicates whether additional work has been defered for a future
3959 * pass through unp_gc(). It is thread local and does not require explicit
3960 * synchronization.
3961 */
3962 static int unp_marked;
3963
3964 static void
unp_remove_dead_ref(struct filedescent ** fdep,int fdcount)3965 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
3966 {
3967 struct unpcb *unp;
3968 struct file *fp;
3969 int i;
3970
3971 /*
3972 * This function can only be called from the gc task.
3973 */
3974 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
3975 ("%s: not on gc callout", __func__));
3976 UNP_LINK_LOCK_ASSERT();
3977
3978 for (i = 0; i < fdcount; i++) {
3979 fp = fdep[i]->fde_file;
3980 if ((unp = fptounp(fp)) == NULL)
3981 continue;
3982 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3983 continue;
3984 unp->unp_gcrefs--;
3985 }
3986 }
3987
3988 static void
unp_restore_undead_ref(struct filedescent ** fdep,int fdcount)3989 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
3990 {
3991 struct unpcb *unp;
3992 struct file *fp;
3993 int i;
3994
3995 /*
3996 * This function can only be called from the gc task.
3997 */
3998 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
3999 ("%s: not on gc callout", __func__));
4000 UNP_LINK_LOCK_ASSERT();
4001
4002 for (i = 0; i < fdcount; i++) {
4003 fp = fdep[i]->fde_file;
4004 if ((unp = fptounp(fp)) == NULL)
4005 continue;
4006 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
4007 continue;
4008 unp->unp_gcrefs++;
4009 unp_marked++;
4010 }
4011 }
4012
4013 static void
unp_scan_socket(struct socket * so,void (* op)(struct filedescent **,int))4014 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
4015 {
4016 struct sockbuf *sb;
4017
4018 SOCK_LOCK_ASSERT(so);
4019
4020 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
4021 return;
4022
4023 SOCK_RECVBUF_LOCK(so);
4024 switch (so->so_type) {
4025 case SOCK_DGRAM:
4026 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
4027 unp_scan(so->so_rcv.uxdg_peeked, op);
4028 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
4029 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
4030 break;
4031 case SOCK_STREAM:
4032 case SOCK_SEQPACKET:
4033 unp_scan(STAILQ_FIRST(&so->so_rcv.uxst_mbq), op);
4034 break;
4035 }
4036 SOCK_RECVBUF_UNLOCK(so);
4037 }
4038
4039 static void
unp_gc_scan(struct unpcb * unp,void (* op)(struct filedescent **,int))4040 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
4041 {
4042 struct socket *so, *soa;
4043
4044 so = unp->unp_socket;
4045 SOCK_LOCK(so);
4046 if (SOLISTENING(so)) {
4047 /*
4048 * Mark all sockets in our accept queue.
4049 */
4050 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
4051 unp_scan_socket(soa, op);
4052 } else {
4053 /*
4054 * Mark all sockets we reference with RIGHTS.
4055 */
4056 unp_scan_socket(so, op);
4057 }
4058 SOCK_UNLOCK(so);
4059 }
4060
4061 static int unp_recycled;
4062 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
4063 "Number of unreachable sockets claimed by the garbage collector.");
4064
4065 static int unp_taskcount;
4066 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
4067 "Number of times the garbage collector has run.");
4068
4069 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
4070 "Number of active local sockets.");
4071
4072 static void
unp_gc(__unused void * arg,int pending)4073 unp_gc(__unused void *arg, int pending)
4074 {
4075 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
4076 NULL };
4077 struct unp_head **head;
4078 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
4079 struct file *f, **unref;
4080 struct unpcb *unp, *unptmp;
4081 int i, total, unp_unreachable;
4082
4083 LIST_INIT(&unp_deadhead);
4084 unp_taskcount++;
4085 UNP_LINK_RLOCK();
4086 /*
4087 * First determine which sockets may be in cycles.
4088 */
4089 unp_unreachable = 0;
4090
4091 for (head = heads; *head != NULL; head++)
4092 LIST_FOREACH(unp, *head, unp_link) {
4093 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
4094 ("%s: unp %p has unexpected gc flags 0x%x",
4095 __func__, unp, (unsigned int)unp->unp_gcflag));
4096
4097 f = unp->unp_file;
4098
4099 /*
4100 * Check for an unreachable socket potentially in a
4101 * cycle. It must be in a queue as indicated by
4102 * msgcount, and this must equal the file reference
4103 * count. Note that when msgcount is 0 the file is
4104 * NULL.
4105 */
4106 if (f != NULL && unp->unp_msgcount != 0 &&
4107 refcount_load(&f->f_count) == unp->unp_msgcount) {
4108 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
4109 unp->unp_gcflag |= UNPGC_DEAD;
4110 unp->unp_gcrefs = unp->unp_msgcount;
4111 unp_unreachable++;
4112 }
4113 }
4114
4115 /*
4116 * Scan all sockets previously marked as potentially being in a cycle
4117 * and remove the references each socket holds on any UNPGC_DEAD
4118 * sockets in its queue. After this step, all remaining references on
4119 * sockets marked UNPGC_DEAD should not be part of any cycle.
4120 */
4121 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
4122 unp_gc_scan(unp, unp_remove_dead_ref);
4123
4124 /*
4125 * If a socket still has a non-negative refcount, it cannot be in a
4126 * cycle. In this case increment refcount of all children iteratively.
4127 * Stop the scan once we do a complete loop without discovering
4128 * a new reachable socket.
4129 */
4130 do {
4131 unp_marked = 0;
4132 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
4133 if (unp->unp_gcrefs > 0) {
4134 unp->unp_gcflag &= ~UNPGC_DEAD;
4135 LIST_REMOVE(unp, unp_dead);
4136 KASSERT(unp_unreachable > 0,
4137 ("%s: unp_unreachable underflow.",
4138 __func__));
4139 unp_unreachable--;
4140 unp_gc_scan(unp, unp_restore_undead_ref);
4141 }
4142 } while (unp_marked);
4143
4144 UNP_LINK_RUNLOCK();
4145
4146 if (unp_unreachable == 0)
4147 return;
4148
4149 /*
4150 * Allocate space for a local array of dead unpcbs.
4151 * TODO: can this path be simplified by instead using the local
4152 * dead list at unp_deadhead, after taking out references
4153 * on the file object and/or unpcb and dropping the link lock?
4154 */
4155 unref = malloc(unp_unreachable * sizeof(struct file *),
4156 M_TEMP, M_WAITOK);
4157
4158 /*
4159 * Iterate looking for sockets which have been specifically marked
4160 * as unreachable and store them locally.
4161 */
4162 UNP_LINK_RLOCK();
4163 total = 0;
4164 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
4165 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
4166 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
4167 unp->unp_gcflag &= ~UNPGC_DEAD;
4168 f = unp->unp_file;
4169 if (unp->unp_msgcount == 0 || f == NULL ||
4170 refcount_load(&f->f_count) != unp->unp_msgcount ||
4171 !fhold(f))
4172 continue;
4173 unref[total++] = f;
4174 KASSERT(total <= unp_unreachable,
4175 ("%s: incorrect unreachable count.", __func__));
4176 }
4177 UNP_LINK_RUNLOCK();
4178
4179 /*
4180 * Now flush all sockets, free'ing rights. This will free the
4181 * struct files associated with these sockets but leave each socket
4182 * with one remaining ref.
4183 */
4184 for (i = 0; i < total; i++) {
4185 struct socket *so;
4186
4187 so = unref[i]->f_data;
4188 CURVNET_SET(so->so_vnet);
4189 socantrcvmore(so);
4190 unp_dispose(so);
4191 CURVNET_RESTORE();
4192 }
4193
4194 /*
4195 * And finally release the sockets so they can be reclaimed.
4196 */
4197 for (i = 0; i < total; i++)
4198 fdrop(unref[i], NULL);
4199 unp_recycled += total;
4200 free(unref, M_TEMP);
4201 }
4202
4203 /*
4204 * Synchronize against unp_gc, which can trip over data as we are freeing it.
4205 */
4206 static void
unp_dispose(struct socket * so)4207 unp_dispose(struct socket *so)
4208 {
4209 struct sockbuf *sb;
4210 struct unpcb *unp;
4211 struct mbuf *m;
4212 int error __diagused;
4213
4214 MPASS(!SOLISTENING(so));
4215
4216 unp = sotounpcb(so);
4217 UNP_LINK_WLOCK();
4218 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
4219 UNP_LINK_WUNLOCK();
4220
4221 /*
4222 * Grab our special mbufs before calling sbrelease().
4223 */
4224 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
4225 MPASS(!error);
4226 SOCK_RECVBUF_LOCK(so);
4227 switch (so->so_type) {
4228 case SOCK_DGRAM:
4229 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
4230 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
4231 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
4232 /* Note: socket of sb may reconnect. */
4233 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
4234 }
4235 sb = &so->so_rcv;
4236 if (sb->uxdg_peeked != NULL) {
4237 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
4238 m_stailqpkt);
4239 sb->uxdg_peeked = NULL;
4240 }
4241 m = STAILQ_FIRST(&sb->uxdg_mb);
4242 STAILQ_INIT(&sb->uxdg_mb);
4243 break;
4244 case SOCK_STREAM:
4245 case SOCK_SEQPACKET:
4246 sb = &so->so_rcv;
4247 m = STAILQ_FIRST(&sb->uxst_mbq);
4248 STAILQ_INIT(&sb->uxst_mbq);
4249 sb->sb_acc = sb->sb_ccc = sb->sb_ctl = sb->sb_mbcnt = 0;
4250 /*
4251 * Trim M_NOTREADY buffers from the free list. They are
4252 * referenced by the I/O thread.
4253 */
4254 if (sb->uxst_fnrdy != NULL) {
4255 struct mbuf *n, *prev;
4256
4257 while (m != NULL && m->m_flags & M_NOTREADY)
4258 m = m->m_next;
4259 for (prev = n = m; n != NULL; n = n->m_next) {
4260 if (n->m_flags & M_NOTREADY)
4261 prev->m_next = n->m_next;
4262 else
4263 prev = n;
4264 }
4265 sb->uxst_fnrdy = NULL;
4266 }
4267 break;
4268 }
4269 /*
4270 * Mark sb with SBS_CANTRCVMORE. This is needed to prevent
4271 * uipc_sosend_*() or unp_disconnect() adding more data to the socket.
4272 * We came here either through shutdown(2) or from the final sofree().
4273 * The sofree() case is simple as it guarantees that no more sends will
4274 * happen, however we can race with unp_disconnect() from our peer.
4275 * The shutdown(2) case is more exotic. It would call into
4276 * unp_dispose() only if socket is SS_ISCONNECTED. This is possible if
4277 * we did connect(2) on this socket and we also had it bound with
4278 * bind(2) and receive connections from other sockets. Because
4279 * uipc_shutdown() violates POSIX (see comment there) this applies to
4280 * SOCK_DGRAM as well. For SOCK_DGRAM this SBS_CANTRCVMORE will have
4281 * affect not only on the peer we connect(2)ed to, but also on all of
4282 * the peers who had connect(2)ed to us. Their sends would end up
4283 * with ENOBUFS.
4284 */
4285 sb->sb_state |= SBS_CANTRCVMORE;
4286 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
4287 RLIM_INFINITY);
4288 SOCK_RECVBUF_UNLOCK(so);
4289 SOCK_IO_RECV_UNLOCK(so);
4290
4291 if (m != NULL) {
4292 unp_scan(m, unp_freerights);
4293 m_freemp(m);
4294 }
4295 }
4296
4297 static void
unp_scan(struct mbuf * m0,void (* op)(struct filedescent **,int))4298 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
4299 {
4300 struct mbuf *m;
4301 struct cmsghdr *cm;
4302 void *data;
4303 socklen_t clen, datalen;
4304
4305 while (m0 != NULL) {
4306 for (m = m0; m; m = m->m_next) {
4307 if (m->m_type != MT_CONTROL)
4308 continue;
4309
4310 cm = mtod(m, struct cmsghdr *);
4311 clen = m->m_len;
4312
4313 while (cm != NULL) {
4314 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
4315 break;
4316
4317 data = CMSG_DATA(cm);
4318 datalen = (caddr_t)cm + cm->cmsg_len
4319 - (caddr_t)data;
4320
4321 if (cm->cmsg_level == SOL_SOCKET &&
4322 cm->cmsg_type == SCM_RIGHTS) {
4323 (*op)(data, datalen /
4324 sizeof(struct filedescent *));
4325 }
4326
4327 if (CMSG_SPACE(datalen) < clen) {
4328 clen -= CMSG_SPACE(datalen);
4329 cm = (struct cmsghdr *)
4330 ((caddr_t)cm + CMSG_SPACE(datalen));
4331 } else {
4332 clen = 0;
4333 cm = NULL;
4334 }
4335 }
4336 }
4337 m0 = m0->m_nextpkt;
4338 }
4339 }
4340
4341 /*
4342 * Definitions of protocols supported in the LOCAL domain.
4343 */
4344 static struct protosw streamproto = {
4345 .pr_type = SOCK_STREAM,
4346 .pr_flags = PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4347 .pr_ctloutput = &uipc_ctloutput,
4348 .pr_abort = uipc_abort,
4349 .pr_accept = uipc_peeraddr,
4350 .pr_attach = uipc_attach,
4351 .pr_bind = uipc_bind,
4352 .pr_bindat = uipc_bindat,
4353 .pr_connect = uipc_connect,
4354 .pr_connectat = uipc_connectat,
4355 .pr_connect2 = uipc_connect2,
4356 .pr_detach = uipc_detach,
4357 .pr_disconnect = uipc_disconnect,
4358 .pr_listen = uipc_listen,
4359 .pr_peeraddr = uipc_peeraddr,
4360 .pr_send = uipc_sendfile,
4361 .pr_sendfile_wait = uipc_sendfile_wait,
4362 .pr_ready = uipc_ready,
4363 .pr_sense = uipc_sense,
4364 .pr_shutdown = uipc_shutdown,
4365 .pr_sockaddr = uipc_sockaddr,
4366 .pr_sosend = uipc_sosend_stream_or_seqpacket,
4367 .pr_soreceive = uipc_soreceive_stream_or_seqpacket,
4368 .pr_sopoll = uipc_sopoll_stream_or_seqpacket,
4369 .pr_kqfilter = uipc_kqfilter_stream_or_seqpacket,
4370 .pr_close = uipc_close,
4371 .pr_chmod = uipc_chmod,
4372 };
4373
4374 static struct protosw dgramproto = {
4375 .pr_type = SOCK_DGRAM,
4376 .pr_flags = PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF,
4377 .pr_ctloutput = &uipc_ctloutput,
4378 .pr_abort = uipc_abort,
4379 .pr_accept = uipc_peeraddr,
4380 .pr_attach = uipc_attach,
4381 .pr_bind = uipc_bind,
4382 .pr_bindat = uipc_bindat,
4383 .pr_connect = uipc_connect,
4384 .pr_connectat = uipc_connectat,
4385 .pr_connect2 = uipc_connect2,
4386 .pr_detach = uipc_detach,
4387 .pr_disconnect = uipc_disconnect,
4388 .pr_peeraddr = uipc_peeraddr,
4389 .pr_sosend = uipc_sosend_dgram,
4390 .pr_sense = uipc_sense,
4391 .pr_shutdown = uipc_shutdown,
4392 .pr_sockaddr = uipc_sockaddr,
4393 .pr_soreceive = uipc_soreceive_dgram,
4394 .pr_close = uipc_close,
4395 .pr_chmod = uipc_chmod,
4396 };
4397
4398 static struct protosw seqpacketproto = {
4399 .pr_type = SOCK_SEQPACKET,
4400 .pr_flags = PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF,
4401 .pr_ctloutput = &uipc_ctloutput,
4402 .pr_abort = uipc_abort,
4403 .pr_accept = uipc_peeraddr,
4404 .pr_attach = uipc_attach,
4405 .pr_bind = uipc_bind,
4406 .pr_bindat = uipc_bindat,
4407 .pr_connect = uipc_connect,
4408 .pr_connectat = uipc_connectat,
4409 .pr_connect2 = uipc_connect2,
4410 .pr_detach = uipc_detach,
4411 .pr_disconnect = uipc_disconnect,
4412 .pr_listen = uipc_listen,
4413 .pr_peeraddr = uipc_peeraddr,
4414 .pr_sense = uipc_sense,
4415 .pr_shutdown = uipc_shutdown,
4416 .pr_sockaddr = uipc_sockaddr,
4417 .pr_sosend = uipc_sosend_stream_or_seqpacket,
4418 .pr_soreceive = uipc_soreceive_stream_or_seqpacket,
4419 .pr_sopoll = uipc_sopoll_stream_or_seqpacket,
4420 .pr_kqfilter = uipc_kqfilter_stream_or_seqpacket,
4421 .pr_close = uipc_close,
4422 .pr_chmod = uipc_chmod,
4423 };
4424
4425 static struct domain localdomain = {
4426 .dom_family = AF_LOCAL,
4427 .dom_name = "local",
4428 .dom_nprotosw = 3,
4429 .dom_protosw = {
4430 &streamproto,
4431 &dgramproto,
4432 &seqpacketproto,
4433 }
4434 };
4435 DOMAIN_SET(local);
4436
4437 /*
4438 * A helper function called by VFS before socket-type vnode reclamation.
4439 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
4440 * use count.
4441 */
4442 void
vfs_unp_reclaim(struct vnode * vp)4443 vfs_unp_reclaim(struct vnode *vp)
4444 {
4445 struct unpcb *unp;
4446 int active;
4447 struct mtx *vplock;
4448
4449 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
4450 KASSERT(vp->v_type == VSOCK,
4451 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
4452
4453 active = 0;
4454 vplock = mtx_pool_find(unp_vp_mtxpool, vp);
4455 mtx_lock(vplock);
4456 VOP_UNP_CONNECT(vp, &unp);
4457 if (unp == NULL)
4458 goto done;
4459 UNP_PCB_LOCK(unp);
4460 if (unp->unp_vnode == vp) {
4461 VOP_UNP_DETACH(vp);
4462 unp->unp_vnode = NULL;
4463 active = 1;
4464 }
4465 UNP_PCB_UNLOCK(unp);
4466 done:
4467 mtx_unlock(vplock);
4468 if (active)
4469 vunref(vp);
4470 }
4471
4472 #ifdef DDB
4473 static void
db_print_indent(int indent)4474 db_print_indent(int indent)
4475 {
4476 int i;
4477
4478 for (i = 0; i < indent; i++)
4479 db_printf(" ");
4480 }
4481
4482 static void
db_print_unpflags(int unp_flags)4483 db_print_unpflags(int unp_flags)
4484 {
4485 int comma;
4486
4487 comma = 0;
4488 if (unp_flags & UNP_HAVEPC) {
4489 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
4490 comma = 1;
4491 }
4492 if (unp_flags & UNP_WANTCRED_ALWAYS) {
4493 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
4494 comma = 1;
4495 }
4496 if (unp_flags & UNP_WANTCRED_ONESHOT) {
4497 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
4498 comma = 1;
4499 }
4500 if (unp_flags & UNP_CONNECTING) {
4501 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
4502 comma = 1;
4503 }
4504 if (unp_flags & UNP_BINDING) {
4505 db_printf("%sUNP_BINDING", comma ? ", " : "");
4506 comma = 1;
4507 }
4508 }
4509
4510 static void
db_print_xucred(int indent,struct xucred * xu)4511 db_print_xucred(int indent, struct xucred *xu)
4512 {
4513 int comma, i;
4514
4515 db_print_indent(indent);
4516 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
4517 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
4518 db_print_indent(indent);
4519 db_printf("cr_groups: ");
4520 comma = 0;
4521 for (i = 0; i < xu->cr_ngroups; i++) {
4522 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
4523 comma = 1;
4524 }
4525 db_printf("\n");
4526 }
4527
4528 static void
db_print_unprefs(int indent,struct unp_head * uh)4529 db_print_unprefs(int indent, struct unp_head *uh)
4530 {
4531 struct unpcb *unp;
4532 int counter;
4533
4534 counter = 0;
4535 LIST_FOREACH(unp, uh, unp_reflink) {
4536 if (counter % 4 == 0)
4537 db_print_indent(indent);
4538 db_printf("%p ", unp);
4539 if (counter % 4 == 3)
4540 db_printf("\n");
4541 counter++;
4542 }
4543 if (counter != 0 && counter % 4 != 0)
4544 db_printf("\n");
4545 }
4546
DB_SHOW_COMMAND(unpcb,db_show_unpcb)4547 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
4548 {
4549 struct unpcb *unp;
4550
4551 if (!have_addr) {
4552 db_printf("usage: show unpcb <addr>\n");
4553 return;
4554 }
4555 unp = (struct unpcb *)addr;
4556
4557 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
4558 unp->unp_vnode);
4559
4560 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
4561 unp->unp_conn);
4562
4563 db_printf("unp_refs:\n");
4564 db_print_unprefs(2, &unp->unp_refs);
4565
4566 /* XXXRW: Would be nice to print the full address, if any. */
4567 db_printf("unp_addr: %p\n", unp->unp_addr);
4568
4569 db_printf("unp_gencnt: %llu\n",
4570 (unsigned long long)unp->unp_gencnt);
4571
4572 db_printf("unp_flags: %x (", unp->unp_flags);
4573 db_print_unpflags(unp->unp_flags);
4574 db_printf(")\n");
4575
4576 db_printf("unp_peercred:\n");
4577 db_print_xucred(2, &unp->unp_peercred);
4578
4579 db_printf("unp_refcount: %u\n", unp->unp_refcount);
4580 }
4581 #endif
4582