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