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 Gleb Smirnoff <[email protected]>
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 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
35 */
36
37 /*
38 * UNIX Domain (Local) Sockets
39 *
40 * This is an implementation of UNIX (local) domain sockets. Each socket has
41 * an associated struct unpcb (UNIX protocol control block). Stream sockets
42 * may be connected to 0 or 1 other socket. Datagram sockets may be
43 * connected to 0, 1, or many other sockets. Sockets may be created and
44 * connected in pairs (socketpair(2)), or bound/connected to using the file
45 * system name space. For most purposes, only the receive socket buffer is
46 * used, as sending on one socket delivers directly to the receive socket
47 * buffer of a second socket.
48 *
49 * The implementation is substantially complicated by the fact that
50 * "ancillary data", such as file descriptors or credentials, may be passed
51 * across UNIX domain sockets. The potential for passing UNIX domain sockets
52 * over other UNIX domain sockets requires the implementation of a simple
53 * garbage collector to find and tear down cycles of disconnected sockets.
54 *
55 * TODO:
56 * RDM
57 * rethink name space problems
58 * need a proper out-of-band
59 */
60
61 #include <sys/cdefs.h>
62 #include "opt_ddb.h"
63
64 #include <sys/param.h>
65 #include <sys/capsicum.h>
66 #include <sys/domain.h>
67 #include <sys/eventhandler.h>
68 #include <sys/fcntl.h>
69 #include <sys/file.h>
70 #include <sys/filedesc.h>
71 #include <sys/kernel.h>
72 #include <sys/lock.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
77 #include <sys/namei.h>
78 #include <sys/proc.h>
79 #include <sys/protosw.h>
80 #include <sys/queue.h>
81 #include <sys/resourcevar.h>
82 #include <sys/rwlock.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/signalvar.h>
86 #include <sys/stat.h>
87 #include <sys/sx.h>
88 #include <sys/sysctl.h>
89 #include <sys/systm.h>
90 #include <sys/taskqueue.h>
91 #include <sys/un.h>
92 #include <sys/unpcb.h>
93 #include <sys/vnode.h>
94
95 #include <net/vnet.h>
96
97 #ifdef DDB
98 #include <ddb/ddb.h>
99 #endif
100
101 #include <security/mac/mac_framework.h>
102
103 #include <vm/uma.h>
104
105 MALLOC_DECLARE(M_FILECAPS);
106
107 static struct domain localdomain;
108
109 static uma_zone_t unp_zone;
110 static unp_gen_t unp_gencnt; /* (l) */
111 static u_int unp_count; /* (l) Count of local sockets. */
112 static ino_t unp_ino; /* Prototype for fake inode numbers. */
113 static int unp_rights; /* (g) File descriptors in flight. */
114 static struct unp_head unp_shead; /* (l) List of stream sockets. */
115 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
116 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
117
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 = { sizeof(sun_noname), AF_LOCAL };
126
127 /*
128 * Garbage collection of cyclic file descriptor/socket references occurs
129 * asynchronously in a taskqueue context in order to avoid recursion and
130 * reentrance in the UNIX domain socket, file descriptor, and socket layer
131 * code. See unp_gc() for a full description.
132 */
133 static struct timeout_task unp_gc_task;
134
135 /*
136 * The close of unix domain sockets attached as SCM_RIGHTS is
137 * postponed to the taskqueue, to avoid arbitrary recursion depth.
138 * The attached sockets might have another sockets attached.
139 */
140 static struct task unp_defer_task;
141
142 /*
143 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
144 * stream sockets, although the total for sender and receiver is actually
145 * only PIPSIZ.
146 *
147 * Datagram sockets really use the sendspace as the maximum datagram size,
148 * and don't really want to reserve the sendspace. Their recvspace should be
149 * large enough for at least one max-size datagram plus address.
150 */
151 #ifndef PIPSIZ
152 #define PIPSIZ 8192
153 #endif
154 static u_long unpst_sendspace = PIPSIZ;
155 static u_long unpst_recvspace = PIPSIZ;
156 static u_long unpdg_maxdgram = 8*1024; /* support 8KB syslog msgs */
157 static u_long unpdg_recvspace = 16*1024;
158 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
159 static u_long unpsp_recvspace = PIPSIZ;
160
161 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
162 "Local domain");
163 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
164 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
165 "SOCK_STREAM");
166 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
167 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
168 "SOCK_DGRAM");
169 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
170 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171 "SOCK_SEQPACKET");
172
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
174 &unpst_sendspace, 0, "Default stream send space.");
175 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
176 &unpst_recvspace, 0, "Default stream receive space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
178 &unpdg_maxdgram, 0, "Maximum datagram size.");
179 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
180 &unpdg_recvspace, 0, "Default datagram receive space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
182 &unpsp_sendspace, 0, "Default seqpacket send space.");
183 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
184 &unpsp_recvspace, 0, "Default seqpacket receive space.");
185 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
186 "File descriptors in flight.");
187 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
188 &unp_defers_count, 0,
189 "File descriptors deferred to taskqueue for close.");
190
191 /*
192 * Locking and synchronization:
193 *
194 * Several types of locks exist in the local domain socket implementation:
195 * - a global linkage lock
196 * - a global connection list lock
197 * - the mtxpool lock
198 * - per-unpcb mutexes
199 *
200 * The linkage lock protects the global socket lists, the generation number
201 * counter and garbage collector state.
202 *
203 * The connection list lock protects the list of referring sockets in a datagram
204 * socket PCB. This lock is also overloaded to protect a global list of
205 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
206 * messages. To avoid recursion, such references are released by a dedicated
207 * thread.
208 *
209 * The mtxpool lock protects the vnode from being modified while referenced.
210 * Lock ordering rules require that it be acquired before any PCB locks.
211 *
212 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
213 * unpcb. This includes the unp_conn field, which either links two connected
214 * PCBs together (for connected socket types) or points at the destination
215 * socket (for connectionless socket types). The operations of creating or
216 * destroying a connection therefore involve locking multiple PCBs. To avoid
217 * lock order reversals, in some cases this involves dropping a PCB lock and
218 * using a reference counter to maintain liveness.
219 *
220 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
221 * allocated in pr_attach() and freed in pr_detach(). The validity of that
222 * pointer is an invariant, so no lock is required to dereference the so_pcb
223 * pointer if a valid socket reference is held by the caller. In practice,
224 * this is always true during operations performed on a socket. Each unpcb
225 * has a back-pointer to its socket, unp_socket, which will be stable under
226 * the same circumstances.
227 *
228 * This pointer may only be safely dereferenced as long as a valid reference
229 * to the unpcb is held. Typically, this reference will be from the socket,
230 * or from another unpcb when the referring unpcb's lock is held (in order
231 * that the reference not be invalidated during use). For example, to follow
232 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
233 * that detach is not run clearing unp_socket.
234 *
235 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
236 * protocols, bind() is a non-atomic operation, and connect() requires
237 * potential sleeping in the protocol, due to potentially waiting on local or
238 * distributed file systems. We try to separate "lookup" operations, which
239 * may sleep, and the IPC operations themselves, which typically can occur
240 * with relative atomicity as locks can be held over the entire operation.
241 *
242 * Another tricky issue is simultaneous multi-threaded or multi-process
243 * access to a single UNIX domain socket. These are handled by the flags
244 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
245 * binding, both of which involve dropping UNIX domain socket locks in order
246 * to perform namei() and other file system operations.
247 */
248 static struct rwlock unp_link_rwlock;
249 static struct mtx unp_defers_lock;
250
251 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
252 "unp_link_rwlock")
253
254 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
255 RA_LOCKED)
256 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
257 RA_UNLOCKED)
258
259 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
260 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
261 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
262 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
263 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
264 RA_WLOCKED)
265 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
266
267 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
268 "unp_defer", NULL, MTX_DEF)
269 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
270 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
271
272 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
273 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
274
275 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
276 "unp", "unp", \
277 MTX_DUPOK|MTX_DEF)
278 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
279 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
280 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
281 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
282 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
283 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
284 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
285 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
286
287 static int uipc_connect2(struct socket *, struct socket *);
288 static int uipc_ctloutput(struct socket *, struct sockopt *);
289 static int unp_connect(struct socket *, struct sockaddr *,
290 struct thread *);
291 static int unp_connectat(int, struct socket *, struct sockaddr *,
292 struct thread *, bool);
293 typedef enum { PRU_CONNECT, PRU_CONNECT2 } conn2_how;
294 static void unp_connect2(struct socket *so, struct socket *so2, conn2_how);
295 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
296 static void unp_dispose(struct socket *so);
297 static void unp_shutdown(struct unpcb *);
298 static void unp_drop(struct unpcb *);
299 static void unp_gc(__unused void *, int);
300 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
301 static void unp_discard(struct file *);
302 static void unp_freerights(struct filedescent **, int);
303 static int unp_internalize(struct mbuf **, struct thread *,
304 struct mbuf **, u_int *, u_int *);
305 static void unp_internalize_fp(struct file *);
306 static int unp_externalize(struct mbuf *, struct mbuf **, int);
307 static int unp_externalize_fp(struct file *);
308 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *,
309 int, struct mbuf **, u_int *, u_int *);
310 static void unp_process_defers(void * __unused, int);
311
312 static void
unp_pcb_hold(struct unpcb * unp)313 unp_pcb_hold(struct unpcb *unp)
314 {
315 u_int old __unused;
316
317 old = refcount_acquire(&unp->unp_refcount);
318 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
319 }
320
321 static __result_use_check bool
unp_pcb_rele(struct unpcb * unp)322 unp_pcb_rele(struct unpcb *unp)
323 {
324 bool ret;
325
326 UNP_PCB_LOCK_ASSERT(unp);
327
328 if ((ret = refcount_release(&unp->unp_refcount))) {
329 UNP_PCB_UNLOCK(unp);
330 UNP_PCB_LOCK_DESTROY(unp);
331 uma_zfree(unp_zone, unp);
332 }
333 return (ret);
334 }
335
336 static void
unp_pcb_rele_notlast(struct unpcb * unp)337 unp_pcb_rele_notlast(struct unpcb *unp)
338 {
339 bool ret __unused;
340
341 ret = refcount_release(&unp->unp_refcount);
342 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
343 }
344
345 static void
unp_pcb_lock_pair(struct unpcb * unp,struct unpcb * unp2)346 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
347 {
348 UNP_PCB_UNLOCK_ASSERT(unp);
349 UNP_PCB_UNLOCK_ASSERT(unp2);
350
351 if (unp == unp2) {
352 UNP_PCB_LOCK(unp);
353 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
354 UNP_PCB_LOCK(unp);
355 UNP_PCB_LOCK(unp2);
356 } else {
357 UNP_PCB_LOCK(unp2);
358 UNP_PCB_LOCK(unp);
359 }
360 }
361
362 static void
unp_pcb_unlock_pair(struct unpcb * unp,struct unpcb * unp2)363 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
364 {
365 UNP_PCB_UNLOCK(unp);
366 if (unp != unp2)
367 UNP_PCB_UNLOCK(unp2);
368 }
369
370 /*
371 * Try to lock the connected peer of an already locked socket. In some cases
372 * this requires that we unlock the current socket. The pairbusy counter is
373 * used to block concurrent connection attempts while the lock is dropped. The
374 * caller must be careful to revalidate PCB state.
375 */
376 static struct unpcb *
unp_pcb_lock_peer(struct unpcb * unp)377 unp_pcb_lock_peer(struct unpcb *unp)
378 {
379 struct unpcb *unp2;
380
381 UNP_PCB_LOCK_ASSERT(unp);
382 unp2 = unp->unp_conn;
383 if (unp2 == NULL)
384 return (NULL);
385 if (__predict_false(unp == unp2))
386 return (unp);
387
388 UNP_PCB_UNLOCK_ASSERT(unp2);
389
390 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
391 return (unp2);
392 if ((uintptr_t)unp2 > (uintptr_t)unp) {
393 UNP_PCB_LOCK(unp2);
394 return (unp2);
395 }
396 unp->unp_pairbusy++;
397 unp_pcb_hold(unp2);
398 UNP_PCB_UNLOCK(unp);
399
400 UNP_PCB_LOCK(unp2);
401 UNP_PCB_LOCK(unp);
402 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
403 ("%s: socket %p was reconnected", __func__, unp));
404 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
405 unp->unp_flags &= ~UNP_WAITING;
406 wakeup(unp);
407 }
408 if (unp_pcb_rele(unp2)) {
409 /* unp2 is unlocked. */
410 return (NULL);
411 }
412 if (unp->unp_conn == NULL) {
413 UNP_PCB_UNLOCK(unp2);
414 return (NULL);
415 }
416 return (unp2);
417 }
418
419 static void
uipc_abort(struct socket * so)420 uipc_abort(struct socket *so)
421 {
422 struct unpcb *unp, *unp2;
423
424 unp = sotounpcb(so);
425 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
426 UNP_PCB_UNLOCK_ASSERT(unp);
427
428 UNP_PCB_LOCK(unp);
429 unp2 = unp->unp_conn;
430 if (unp2 != NULL) {
431 unp_pcb_hold(unp2);
432 UNP_PCB_UNLOCK(unp);
433 unp_drop(unp2);
434 } else
435 UNP_PCB_UNLOCK(unp);
436 }
437
438 static int
uipc_accept(struct socket * so,struct sockaddr ** nam)439 uipc_accept(struct socket *so, struct sockaddr **nam)
440 {
441 struct unpcb *unp, *unp2;
442 const struct sockaddr *sa;
443
444 /*
445 * Pass back name of connected socket, if it was bound and we are
446 * still connected (our peer may have closed already!).
447 */
448 unp = sotounpcb(so);
449 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
450
451 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
452 UNP_PCB_LOCK(unp);
453 unp2 = unp_pcb_lock_peer(unp);
454 if (unp2 != NULL && unp2->unp_addr != NULL)
455 sa = (struct sockaddr *)unp2->unp_addr;
456 else
457 sa = &sun_noname;
458 bcopy(sa, *nam, sa->sa_len);
459 if (unp2 != NULL)
460 unp_pcb_unlock_pair(unp, unp2);
461 else
462 UNP_PCB_UNLOCK(unp);
463 return (0);
464 }
465
466 static int
uipc_attach(struct socket * so,int proto,struct thread * td)467 uipc_attach(struct socket *so, int proto, struct thread *td)
468 {
469 u_long sendspace, recvspace;
470 struct unpcb *unp;
471 int error;
472 bool locked;
473
474 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
475 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
476 switch (so->so_type) {
477 case SOCK_STREAM:
478 sendspace = unpst_sendspace;
479 recvspace = unpst_recvspace;
480 break;
481
482 case SOCK_DGRAM:
483 STAILQ_INIT(&so->so_rcv.uxdg_mb);
484 STAILQ_INIT(&so->so_snd.uxdg_mb);
485 TAILQ_INIT(&so->so_rcv.uxdg_conns);
486 /*
487 * Since send buffer is either bypassed or is a part
488 * of one-to-many receive buffer, we assign both space
489 * limits to unpdg_recvspace.
490 */
491 sendspace = recvspace = unpdg_recvspace;
492 break;
493
494 case SOCK_SEQPACKET:
495 sendspace = unpsp_sendspace;
496 recvspace = unpsp_recvspace;
497 break;
498
499 default:
500 panic("uipc_attach");
501 }
502 error = soreserve(so, sendspace, recvspace);
503 if (error)
504 return (error);
505 }
506 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
507 if (unp == NULL)
508 return (ENOBUFS);
509 LIST_INIT(&unp->unp_refs);
510 UNP_PCB_LOCK_INIT(unp);
511 unp->unp_socket = so;
512 so->so_pcb = unp;
513 refcount_init(&unp->unp_refcount, 1);
514
515 if ((locked = UNP_LINK_WOWNED()) == false)
516 UNP_LINK_WLOCK();
517
518 unp->unp_gencnt = ++unp_gencnt;
519 unp->unp_ino = ++unp_ino;
520 unp_count++;
521 switch (so->so_type) {
522 case SOCK_STREAM:
523 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
524 break;
525
526 case SOCK_DGRAM:
527 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
528 break;
529
530 case SOCK_SEQPACKET:
531 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
532 break;
533
534 default:
535 panic("uipc_attach");
536 }
537
538 if (locked == false)
539 UNP_LINK_WUNLOCK();
540
541 return (0);
542 }
543
544 static int
uipc_bindat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td)545 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
546 {
547 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
548 struct vattr vattr;
549 int error, namelen;
550 struct nameidata nd;
551 struct unpcb *unp;
552 struct vnode *vp;
553 struct mount *mp;
554 cap_rights_t rights;
555 char *buf;
556
557 if (nam->sa_family != AF_UNIX)
558 return (EAFNOSUPPORT);
559
560 unp = sotounpcb(so);
561 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
562
563 if (soun->sun_len > sizeof(struct sockaddr_un))
564 return (EINVAL);
565 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
566 if (namelen <= 0)
567 return (EINVAL);
568
569 /*
570 * We don't allow simultaneous bind() calls on a single UNIX domain
571 * socket, so flag in-progress operations, and return an error if an
572 * operation is already in progress.
573 *
574 * Historically, we have not allowed a socket to be rebound, so this
575 * also returns an error. Not allowing re-binding simplifies the
576 * implementation and avoids a great many possible failure modes.
577 */
578 UNP_PCB_LOCK(unp);
579 if (unp->unp_vnode != NULL) {
580 UNP_PCB_UNLOCK(unp);
581 return (EINVAL);
582 }
583 if (unp->unp_flags & UNP_BINDING) {
584 UNP_PCB_UNLOCK(unp);
585 return (EALREADY);
586 }
587 unp->unp_flags |= UNP_BINDING;
588 UNP_PCB_UNLOCK(unp);
589
590 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
591 bcopy(soun->sun_path, buf, namelen);
592 buf[namelen] = 0;
593
594 restart:
595 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
596 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
597 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
598 error = namei(&nd);
599 if (error)
600 goto error;
601 vp = nd.ni_vp;
602 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
603 NDFREE_PNBUF(&nd);
604 if (nd.ni_dvp == vp)
605 vrele(nd.ni_dvp);
606 else
607 vput(nd.ni_dvp);
608 if (vp != NULL) {
609 vrele(vp);
610 error = EADDRINUSE;
611 goto error;
612 }
613 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
614 if (error)
615 goto error;
616 goto restart;
617 }
618 VATTR_NULL(&vattr);
619 vattr.va_type = VSOCK;
620 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
621 #ifdef MAC
622 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
623 &vattr);
624 #endif
625 if (error == 0) {
626 /*
627 * The prior lookup may have left LK_SHARED in cn_lkflags,
628 * and VOP_CREATE technically only requires the new vnode to
629 * be locked shared. Most filesystems will return the new vnode
630 * locked exclusive regardless, but we should explicitly
631 * specify that here since we require it and assert to that
632 * effect below.
633 */
634 nd.ni_cnd.cn_lkflags = (nd.ni_cnd.cn_lkflags & ~LK_SHARED) |
635 LK_EXCLUSIVE;
636 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
637 }
638 NDFREE_PNBUF(&nd);
639 if (error) {
640 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
641 vn_finished_write(mp);
642 if (error == ERELOOKUP)
643 goto restart;
644 goto error;
645 }
646 vp = nd.ni_vp;
647 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
648 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
649
650 UNP_PCB_LOCK(unp);
651 VOP_UNP_BIND(vp, unp);
652 unp->unp_vnode = vp;
653 unp->unp_addr = soun;
654 unp->unp_flags &= ~UNP_BINDING;
655 UNP_PCB_UNLOCK(unp);
656 vref(vp);
657 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
658 vn_finished_write(mp);
659 free(buf, M_TEMP);
660 return (0);
661
662 error:
663 UNP_PCB_LOCK(unp);
664 unp->unp_flags &= ~UNP_BINDING;
665 UNP_PCB_UNLOCK(unp);
666 free(buf, M_TEMP);
667 return (error);
668 }
669
670 static int
uipc_bind(struct socket * so,struct sockaddr * nam,struct thread * td)671 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
672 {
673
674 return (uipc_bindat(AT_FDCWD, so, nam, td));
675 }
676
677 static int
uipc_connect(struct socket * so,struct sockaddr * nam,struct thread * td)678 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
679 {
680 int error;
681
682 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
683 error = unp_connect(so, nam, td);
684 return (error);
685 }
686
687 static int
uipc_connectat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td)688 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
689 struct thread *td)
690 {
691 int error;
692
693 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
694 error = unp_connectat(fd, so, nam, td, false);
695 return (error);
696 }
697
698 static void
uipc_close(struct socket * so)699 uipc_close(struct socket *so)
700 {
701 struct unpcb *unp, *unp2;
702 struct vnode *vp = NULL;
703 struct mtx *vplock;
704
705 unp = sotounpcb(so);
706 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
707
708 vplock = NULL;
709 if ((vp = unp->unp_vnode) != NULL) {
710 vplock = mtx_pool_find(mtxpool_sleep, vp);
711 mtx_lock(vplock);
712 }
713 UNP_PCB_LOCK(unp);
714 if (vp && unp->unp_vnode == NULL) {
715 mtx_unlock(vplock);
716 vp = NULL;
717 }
718 if (vp != NULL) {
719 VOP_UNP_DETACH(vp);
720 unp->unp_vnode = NULL;
721 }
722 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
723 unp_disconnect(unp, unp2);
724 else
725 UNP_PCB_UNLOCK(unp);
726 if (vp) {
727 mtx_unlock(vplock);
728 vrele(vp);
729 }
730 }
731
732 static int
uipc_connect2(struct socket * so1,struct socket * so2)733 uipc_connect2(struct socket *so1, struct socket *so2)
734 {
735 struct unpcb *unp, *unp2;
736
737 if (so1->so_type != so2->so_type)
738 return (EPROTOTYPE);
739
740 unp = so1->so_pcb;
741 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
742 unp2 = so2->so_pcb;
743 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
744 unp_pcb_lock_pair(unp, unp2);
745 unp_connect2(so1, so2, PRU_CONNECT2);
746 unp_pcb_unlock_pair(unp, unp2);
747
748 return (0);
749 }
750
751 static void
uipc_detach(struct socket * so)752 uipc_detach(struct socket *so)
753 {
754 struct unpcb *unp, *unp2;
755 struct mtx *vplock;
756 struct vnode *vp;
757 int local_unp_rights;
758
759 unp = sotounpcb(so);
760 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
761
762 vp = NULL;
763 vplock = NULL;
764
765 UNP_LINK_WLOCK();
766 LIST_REMOVE(unp, unp_link);
767 if (unp->unp_gcflag & UNPGC_DEAD)
768 LIST_REMOVE(unp, unp_dead);
769 unp->unp_gencnt = ++unp_gencnt;
770 --unp_count;
771 UNP_LINK_WUNLOCK();
772
773 UNP_PCB_UNLOCK_ASSERT(unp);
774 restart:
775 if ((vp = unp->unp_vnode) != NULL) {
776 vplock = mtx_pool_find(mtxpool_sleep, vp);
777 mtx_lock(vplock);
778 }
779 UNP_PCB_LOCK(unp);
780 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
781 if (vplock)
782 mtx_unlock(vplock);
783 UNP_PCB_UNLOCK(unp);
784 goto restart;
785 }
786 if ((vp = unp->unp_vnode) != NULL) {
787 VOP_UNP_DETACH(vp);
788 unp->unp_vnode = NULL;
789 }
790 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
791 unp_disconnect(unp, unp2);
792 else
793 UNP_PCB_UNLOCK(unp);
794
795 UNP_REF_LIST_LOCK();
796 while (!LIST_EMPTY(&unp->unp_refs)) {
797 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
798
799 unp_pcb_hold(ref);
800 UNP_REF_LIST_UNLOCK();
801
802 MPASS(ref != unp);
803 UNP_PCB_UNLOCK_ASSERT(ref);
804 unp_drop(ref);
805 UNP_REF_LIST_LOCK();
806 }
807 UNP_REF_LIST_UNLOCK();
808
809 UNP_PCB_LOCK(unp);
810 local_unp_rights = unp_rights;
811 unp->unp_socket->so_pcb = NULL;
812 unp->unp_socket = NULL;
813 free(unp->unp_addr, M_SONAME);
814 unp->unp_addr = NULL;
815 if (!unp_pcb_rele(unp))
816 UNP_PCB_UNLOCK(unp);
817 if (vp) {
818 mtx_unlock(vplock);
819 vrele(vp);
820 }
821 if (local_unp_rights)
822 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
823
824 switch (so->so_type) {
825 case SOCK_DGRAM:
826 /*
827 * Everything should have been unlinked/freed by unp_dispose()
828 * and/or unp_disconnect().
829 */
830 MPASS(so->so_rcv.uxdg_peeked == NULL);
831 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
832 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
833 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
834 }
835 }
836
837 static int
uipc_disconnect(struct socket * so)838 uipc_disconnect(struct socket *so)
839 {
840 struct unpcb *unp, *unp2;
841
842 unp = sotounpcb(so);
843 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
844
845 UNP_PCB_LOCK(unp);
846 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
847 unp_disconnect(unp, unp2);
848 else
849 UNP_PCB_UNLOCK(unp);
850 return (0);
851 }
852
853 static int
uipc_listen(struct socket * so,int backlog,struct thread * td)854 uipc_listen(struct socket *so, int backlog, struct thread *td)
855 {
856 struct unpcb *unp;
857 int error;
858
859 MPASS(so->so_type != SOCK_DGRAM);
860
861 /*
862 * Synchronize with concurrent connection attempts.
863 */
864 error = 0;
865 unp = sotounpcb(so);
866 UNP_PCB_LOCK(unp);
867 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
868 error = EINVAL;
869 else if (unp->unp_vnode == NULL)
870 error = EDESTADDRREQ;
871 if (error != 0) {
872 UNP_PCB_UNLOCK(unp);
873 return (error);
874 }
875
876 SOCK_LOCK(so);
877 error = solisten_proto_check(so);
878 if (error == 0) {
879 cru2xt(td, &unp->unp_peercred);
880 solisten_proto(so, backlog);
881 }
882 SOCK_UNLOCK(so);
883 UNP_PCB_UNLOCK(unp);
884 return (error);
885 }
886
887 static int
uipc_peeraddr(struct socket * so,struct sockaddr ** nam)888 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
889 {
890 struct unpcb *unp, *unp2;
891 const struct sockaddr *sa;
892
893 unp = sotounpcb(so);
894 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
895
896 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
897
898 UNP_PCB_LOCK(unp);
899 unp2 = unp_pcb_lock_peer(unp);
900 if (unp2 != NULL) {
901 if (unp2->unp_addr != NULL)
902 sa = (struct sockaddr *)unp2->unp_addr;
903 else
904 sa = &sun_noname;
905 bcopy(sa, *nam, sa->sa_len);
906 unp_pcb_unlock_pair(unp, unp2);
907 } else {
908 sa = &sun_noname;
909 bcopy(sa, *nam, sa->sa_len);
910 UNP_PCB_UNLOCK(unp);
911 }
912 return (0);
913 }
914
915 static int
uipc_rcvd(struct socket * so,int flags)916 uipc_rcvd(struct socket *so, int flags)
917 {
918 struct unpcb *unp, *unp2;
919 struct socket *so2;
920 u_int mbcnt, sbcc;
921
922 unp = sotounpcb(so);
923 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
924 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
925 ("%s: socktype %d", __func__, so->so_type));
926
927 /*
928 * Adjust backpressure on sender and wakeup any waiting to write.
929 *
930 * The unp lock is acquired to maintain the validity of the unp_conn
931 * pointer; no lock on unp2 is required as unp2->unp_socket will be
932 * static as long as we don't permit unp2 to disconnect from unp,
933 * which is prevented by the lock on unp. We cache values from
934 * so_rcv to avoid holding the so_rcv lock over the entire
935 * transaction on the remote so_snd.
936 */
937 SOCKBUF_LOCK(&so->so_rcv);
938 mbcnt = so->so_rcv.sb_mbcnt;
939 sbcc = sbavail(&so->so_rcv);
940 SOCKBUF_UNLOCK(&so->so_rcv);
941 /*
942 * There is a benign race condition at this point. If we're planning to
943 * clear SB_STOP, but uipc_send is called on the connected socket at
944 * this instant, it might add data to the sockbuf and set SB_STOP. Then
945 * we would erroneously clear SB_STOP below, even though the sockbuf is
946 * full. The race is benign because the only ill effect is to allow the
947 * sockbuf to exceed its size limit, and the size limits are not
948 * strictly guaranteed anyway.
949 */
950 UNP_PCB_LOCK(unp);
951 unp2 = unp->unp_conn;
952 if (unp2 == NULL) {
953 UNP_PCB_UNLOCK(unp);
954 return (0);
955 }
956 so2 = unp2->unp_socket;
957 SOCKBUF_LOCK(&so2->so_snd);
958 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
959 so2->so_snd.sb_flags &= ~SB_STOP;
960 sowwakeup_locked(so2);
961 UNP_PCB_UNLOCK(unp);
962 return (0);
963 }
964
965 static int
uipc_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct thread * td)966 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
967 struct mbuf *control, struct thread *td)
968 {
969 struct unpcb *unp, *unp2;
970 struct socket *so2;
971 u_int mbcnt, sbcc;
972 int error;
973
974 unp = sotounpcb(so);
975 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
976 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
977 ("%s: socktype %d", __func__, so->so_type));
978
979 error = 0;
980 if (flags & PRUS_OOB) {
981 error = EOPNOTSUPP;
982 goto release;
983 }
984 if (control != NULL &&
985 (error = unp_internalize(&control, td, NULL, NULL, NULL)))
986 goto release;
987
988 unp2 = NULL;
989 if ((so->so_state & SS_ISCONNECTED) == 0) {
990 if (nam != NULL) {
991 if ((error = unp_connect(so, nam, td)) != 0)
992 goto out;
993 } else {
994 error = ENOTCONN;
995 goto out;
996 }
997 }
998
999 UNP_PCB_LOCK(unp);
1000 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1001 UNP_PCB_UNLOCK(unp);
1002 error = ENOTCONN;
1003 goto out;
1004 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1005 unp_pcb_unlock_pair(unp, unp2);
1006 error = EPIPE;
1007 goto out;
1008 }
1009 UNP_PCB_UNLOCK(unp);
1010 if ((so2 = unp2->unp_socket) == NULL) {
1011 UNP_PCB_UNLOCK(unp2);
1012 error = ENOTCONN;
1013 goto out;
1014 }
1015 SOCKBUF_LOCK(&so2->so_rcv);
1016 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1017 /*
1018 * Credentials are passed only once on SOCK_STREAM and
1019 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1020 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1021 */
1022 control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
1023 NULL, NULL);
1024 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1025 }
1026
1027 /*
1028 * Send to paired receive port and wake up readers. Don't
1029 * check for space available in the receive buffer if we're
1030 * attaching ancillary data; Unix domain sockets only check
1031 * for space in the sending sockbuf, and that check is
1032 * performed one level up the stack. At that level we cannot
1033 * precisely account for the amount of buffer space used
1034 * (e.g., because control messages are not yet internalized).
1035 */
1036 switch (so->so_type) {
1037 case SOCK_STREAM:
1038 if (control != NULL) {
1039 sbappendcontrol_locked(&so2->so_rcv, m,
1040 control, flags);
1041 control = NULL;
1042 } else
1043 sbappend_locked(&so2->so_rcv, m, flags);
1044 break;
1045
1046 case SOCK_SEQPACKET:
1047 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1048 &sun_noname, m, control))
1049 control = NULL;
1050 break;
1051 }
1052
1053 mbcnt = so2->so_rcv.sb_mbcnt;
1054 sbcc = sbavail(&so2->so_rcv);
1055 if (sbcc)
1056 sorwakeup_locked(so2);
1057 else
1058 SOCKBUF_UNLOCK(&so2->so_rcv);
1059
1060 /*
1061 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1062 * it would be possible for uipc_rcvd to be called at this
1063 * point, drain the receiving sockbuf, clear SB_STOP, and then
1064 * we would set SB_STOP below. That could lead to an empty
1065 * sockbuf having SB_STOP set
1066 */
1067 SOCKBUF_LOCK(&so->so_snd);
1068 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1069 so->so_snd.sb_flags |= SB_STOP;
1070 SOCKBUF_UNLOCK(&so->so_snd);
1071 UNP_PCB_UNLOCK(unp2);
1072 m = NULL;
1073 out:
1074 /*
1075 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1076 */
1077 if (flags & PRUS_EOF) {
1078 UNP_PCB_LOCK(unp);
1079 socantsendmore(so);
1080 unp_shutdown(unp);
1081 UNP_PCB_UNLOCK(unp);
1082 }
1083 if (control != NULL && error != 0)
1084 unp_scan(control, unp_freerights);
1085
1086 release:
1087 if (control != NULL)
1088 m_freem(control);
1089 /*
1090 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1091 * for freeing memory.
1092 */
1093 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1094 m_freem(m);
1095 return (error);
1096 }
1097
1098 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1099 static inline bool
uipc_dgram_sbspace(struct sockbuf * sb,u_int cc,u_int mbcnt)1100 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1101 {
1102 u_int bleft, mleft;
1103
1104 /*
1105 * Negative space may happen if send(2) is followed by
1106 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1107 */
1108 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1109 sb->sb_mbmax < sb->uxdg_mbcnt))
1110 return (false);
1111
1112 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1113 return (false);
1114
1115 bleft = sb->sb_hiwat - sb->uxdg_cc;
1116 mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1117
1118 return (bleft >= cc && mleft >= mbcnt);
1119 }
1120
1121 /*
1122 * PF_UNIX/SOCK_DGRAM send
1123 *
1124 * Allocate a record consisting of 3 mbufs in the sequence of
1125 * from -> control -> data and append it to the socket buffer.
1126 *
1127 * The first mbuf carries sender's name and is a pkthdr that stores
1128 * overall length of datagram, its memory consumption and control length.
1129 */
1130 #define ctllen PH_loc.thirtytwo[1]
1131 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1132 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1133 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)1134 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1135 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1136 {
1137 struct unpcb *unp, *unp2;
1138 const struct sockaddr *from;
1139 struct socket *so2;
1140 struct sockbuf *sb;
1141 struct mbuf *f, *clast;
1142 u_int cc, ctl, mbcnt;
1143 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1144 int error;
1145
1146 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1147
1148 error = 0;
1149 f = NULL;
1150 ctl = 0;
1151
1152 if (__predict_false(flags & MSG_OOB)) {
1153 error = EOPNOTSUPP;
1154 goto out;
1155 }
1156 if (m == NULL) {
1157 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1158 error = EMSGSIZE;
1159 goto out;
1160 }
1161 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1162 if (__predict_false(m == NULL)) {
1163 error = EFAULT;
1164 goto out;
1165 }
1166 f = m_gethdr(M_WAITOK, MT_SONAME);
1167 cc = m->m_pkthdr.len;
1168 mbcnt = MSIZE + m->m_pkthdr.memlen;
1169 if (c != NULL &&
1170 (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1171 goto out;
1172 } else {
1173 /* pr_sosend() with mbuf usually is a kernel thread. */
1174
1175 M_ASSERTPKTHDR(m);
1176 if (__predict_false(c != NULL))
1177 panic("%s: control from a kernel thread", __func__);
1178
1179 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1180 error = EMSGSIZE;
1181 goto out;
1182 }
1183 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1184 error = ENOBUFS;
1185 goto out;
1186 }
1187 /* Condition the foreign mbuf to our standards. */
1188 m_clrprotoflags(m);
1189 m_tag_delete_chain(m, NULL);
1190 m->m_pkthdr.rcvif = NULL;
1191 m->m_pkthdr.flowid = 0;
1192 m->m_pkthdr.csum_flags = 0;
1193 m->m_pkthdr.fibnum = 0;
1194 m->m_pkthdr.rsstype = 0;
1195
1196 cc = m->m_pkthdr.len;
1197 mbcnt = MSIZE;
1198 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1199 mbcnt += MSIZE;
1200 if (mb->m_flags & M_EXT)
1201 mbcnt += mb->m_ext.ext_size;
1202 }
1203 }
1204
1205 unp = sotounpcb(so);
1206 MPASS(unp);
1207
1208 /*
1209 * XXXGL: would be cool to fully remove so_snd out of the equation
1210 * and avoid this lock, which is not only extraneous, but also being
1211 * released, thus still leaving possibility for a race. We can easily
1212 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1213 * is more difficult to invent something to handle so_error.
1214 */
1215 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1216 if (error)
1217 goto out2;
1218 SOCK_SENDBUF_LOCK(so);
1219 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1220 SOCK_SENDBUF_UNLOCK(so);
1221 error = EPIPE;
1222 goto out3;
1223 }
1224 if (so->so_error != 0) {
1225 error = so->so_error;
1226 so->so_error = 0;
1227 SOCK_SENDBUF_UNLOCK(so);
1228 goto out3;
1229 }
1230 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1231 SOCK_SENDBUF_UNLOCK(so);
1232 error = EDESTADDRREQ;
1233 goto out3;
1234 }
1235 SOCK_SENDBUF_UNLOCK(so);
1236
1237 if (addr != NULL) {
1238 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1239 goto out3;
1240 UNP_PCB_LOCK_ASSERT(unp);
1241 unp2 = unp->unp_conn;
1242 UNP_PCB_LOCK_ASSERT(unp2);
1243 } else {
1244 UNP_PCB_LOCK(unp);
1245 unp2 = unp_pcb_lock_peer(unp);
1246 if (unp2 == NULL) {
1247 UNP_PCB_UNLOCK(unp);
1248 error = ENOTCONN;
1249 goto out3;
1250 }
1251 }
1252
1253 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1254 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1255 &mbcnt);
1256 if (unp->unp_addr != NULL)
1257 from = (struct sockaddr *)unp->unp_addr;
1258 else
1259 from = &sun_noname;
1260 f->m_len = from->sa_len;
1261 MPASS(from->sa_len <= MLEN);
1262 bcopy(from, mtod(f, void *), from->sa_len);
1263 ctl += f->m_len;
1264
1265 /*
1266 * Concatenate mbufs: from -> control -> data.
1267 * Save overall cc and mbcnt in "from" mbuf.
1268 */
1269 if (c != NULL) {
1270 #ifdef INVARIANTS
1271 struct mbuf *mc;
1272
1273 for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1274 MPASS(mc == clast);
1275 #endif
1276 f->m_next = c;
1277 clast->m_next = m;
1278 c = NULL;
1279 } else
1280 f->m_next = m;
1281 m = NULL;
1282 #ifdef INVARIANTS
1283 dcc = dctl = dmbcnt = 0;
1284 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1285 if (mb->m_type == MT_DATA)
1286 dcc += mb->m_len;
1287 else
1288 dctl += mb->m_len;
1289 dmbcnt += MSIZE;
1290 if (mb->m_flags & M_EXT)
1291 dmbcnt += mb->m_ext.ext_size;
1292 }
1293 MPASS(dcc == cc);
1294 MPASS(dctl == ctl);
1295 MPASS(dmbcnt == mbcnt);
1296 #endif
1297 f->m_pkthdr.len = cc + ctl;
1298 f->m_pkthdr.memlen = mbcnt;
1299 f->m_pkthdr.ctllen = ctl;
1300
1301 /*
1302 * Destination socket buffer selection.
1303 *
1304 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1305 * destination address is supplied, create a temporary connection for
1306 * the run time of the function (see call to unp_connectat() above and
1307 * to unp_disconnect() below). We distinguish them by condition of
1308 * (addr != NULL). We intentionally avoid adding 'bool connected' for
1309 * that condition, since, again, through the run time of this code we
1310 * are always connected. For such "unconnected" sends, the destination
1311 * buffer would be the receive buffer of destination socket so2.
1312 *
1313 * For connected sends, data lands on the send buffer of the sender's
1314 * socket "so". Then, if we just added the very first datagram
1315 * on this send buffer, we need to add the send buffer on to the
1316 * receiving socket's buffer list. We put ourselves on top of the
1317 * list. Such logic gives infrequent senders priority over frequent
1318 * senders.
1319 *
1320 * Note on byte count management. As long as event methods kevent(2),
1321 * select(2) are not protocol specific (yet), we need to maintain
1322 * meaningful values on the receive buffer. So, the receive buffer
1323 * would accumulate counters from all connected buffers potentially
1324 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1325 */
1326 so2 = unp2->unp_socket;
1327 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1328 SOCK_RECVBUF_LOCK(so2);
1329 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1330 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1331 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1332 uxdg_clist);
1333 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1334 sb->uxdg_cc += cc + ctl;
1335 sb->uxdg_ctl += ctl;
1336 sb->uxdg_mbcnt += mbcnt;
1337 so2->so_rcv.sb_acc += cc + ctl;
1338 so2->so_rcv.sb_ccc += cc + ctl;
1339 so2->so_rcv.sb_ctl += ctl;
1340 so2->so_rcv.sb_mbcnt += mbcnt;
1341 sorwakeup_locked(so2);
1342 f = NULL;
1343 } else {
1344 soroverflow_locked(so2);
1345 error = ENOBUFS;
1346 if (f->m_next->m_type == MT_CONTROL) {
1347 c = f->m_next;
1348 f->m_next = NULL;
1349 }
1350 }
1351
1352 if (addr != NULL)
1353 unp_disconnect(unp, unp2);
1354 else
1355 unp_pcb_unlock_pair(unp, unp2);
1356
1357 td->td_ru.ru_msgsnd++;
1358
1359 out3:
1360 SOCK_IO_SEND_UNLOCK(so);
1361 out2:
1362 if (c)
1363 unp_scan(c, unp_freerights);
1364 out:
1365 if (f)
1366 m_freem(f);
1367 if (c)
1368 m_freem(c);
1369 if (m)
1370 m_freem(m);
1371
1372 return (error);
1373 }
1374
1375 /*
1376 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1377 * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1378 * and needs to be linked onto uxdg_peeked of receive socket buffer.
1379 */
1380 static int
uipc_peek_dgram(struct socket * so,struct mbuf * m,struct sockaddr ** psa,struct uio * uio,struct mbuf ** controlp,int * flagsp)1381 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1382 struct uio *uio, struct mbuf **controlp, int *flagsp)
1383 {
1384 ssize_t len = 0;
1385 int error;
1386
1387 so->so_rcv.uxdg_peeked = m;
1388 so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1389 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1390 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1391 SOCK_RECVBUF_UNLOCK(so);
1392
1393 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1394 if (psa != NULL)
1395 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1396
1397 m = m->m_next;
1398 KASSERT(m, ("%s: no data or control after soname", __func__));
1399
1400 /*
1401 * With MSG_PEEK the control isn't executed, just copied.
1402 */
1403 while (m != NULL && m->m_type == MT_CONTROL) {
1404 if (controlp != NULL) {
1405 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1406 controlp = &(*controlp)->m_next;
1407 }
1408 m = m->m_next;
1409 }
1410 KASSERT(m == NULL || m->m_type == MT_DATA,
1411 ("%s: not MT_DATA mbuf %p", __func__, m));
1412 while (m != NULL && uio->uio_resid > 0) {
1413 len = uio->uio_resid;
1414 if (len > m->m_len)
1415 len = m->m_len;
1416 error = uiomove(mtod(m, char *), (int)len, uio);
1417 if (error) {
1418 SOCK_IO_RECV_UNLOCK(so);
1419 return (error);
1420 }
1421 if (len == m->m_len)
1422 m = m->m_next;
1423 }
1424 SOCK_IO_RECV_UNLOCK(so);
1425
1426 if (flagsp != NULL) {
1427 if (m != NULL) {
1428 if (*flagsp & MSG_TRUNC) {
1429 /* Report real length of the packet */
1430 uio->uio_resid -= m_length(m, NULL) - len;
1431 }
1432 *flagsp |= MSG_TRUNC;
1433 } else
1434 *flagsp &= ~MSG_TRUNC;
1435 }
1436
1437 return (0);
1438 }
1439
1440 /*
1441 * PF_UNIX/SOCK_DGRAM receive
1442 */
1443 static int
uipc_soreceive_dgram(struct socket * so,struct sockaddr ** psa,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)1444 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1445 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1446 {
1447 struct sockbuf *sb = NULL;
1448 struct mbuf *m;
1449 int flags, error;
1450 ssize_t len = 0;
1451 bool nonblock;
1452
1453 MPASS(mp0 == NULL);
1454
1455 if (psa != NULL)
1456 *psa = NULL;
1457 if (controlp != NULL)
1458 *controlp = NULL;
1459
1460 flags = flagsp != NULL ? *flagsp : 0;
1461 nonblock = (so->so_state & SS_NBIO) ||
1462 (flags & (MSG_DONTWAIT | MSG_NBIO));
1463
1464 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1465 if (__predict_false(error))
1466 return (error);
1467
1468 /*
1469 * Loop blocking while waiting for a datagram. Prioritize connected
1470 * peers over unconnected sends. Set sb to selected socket buffer
1471 * containing an mbuf on exit from the wait loop. A datagram that
1472 * had already been peeked at has top priority.
1473 */
1474 SOCK_RECVBUF_LOCK(so);
1475 while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1476 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1477 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1478 if (so->so_error) {
1479 error = so->so_error;
1480 so->so_error = 0;
1481 SOCK_RECVBUF_UNLOCK(so);
1482 SOCK_IO_RECV_UNLOCK(so);
1483 return (error);
1484 }
1485 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1486 uio->uio_resid == 0) {
1487 SOCK_RECVBUF_UNLOCK(so);
1488 SOCK_IO_RECV_UNLOCK(so);
1489 return (0);
1490 }
1491 if (nonblock) {
1492 SOCK_RECVBUF_UNLOCK(so);
1493 SOCK_IO_RECV_UNLOCK(so);
1494 return (EWOULDBLOCK);
1495 }
1496 error = sbwait(so, SO_RCV);
1497 if (error) {
1498 SOCK_RECVBUF_UNLOCK(so);
1499 SOCK_IO_RECV_UNLOCK(so);
1500 return (error);
1501 }
1502 }
1503
1504 if (sb == NULL)
1505 sb = &so->so_rcv;
1506 else if (m == NULL)
1507 m = STAILQ_FIRST(&sb->uxdg_mb);
1508 else
1509 MPASS(m == so->so_rcv.uxdg_peeked);
1510
1511 MPASS(sb->uxdg_cc > 0);
1512 M_ASSERTPKTHDR(m);
1513 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1514
1515 if (uio->uio_td)
1516 uio->uio_td->td_ru.ru_msgrcv++;
1517
1518 if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1519 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1520 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1521 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1522 } else
1523 so->so_rcv.uxdg_peeked = NULL;
1524
1525 sb->uxdg_cc -= m->m_pkthdr.len;
1526 sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1527 sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1528
1529 if (__predict_false(flags & MSG_PEEK))
1530 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1531
1532 so->so_rcv.sb_acc -= m->m_pkthdr.len;
1533 so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1534 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1535 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1536 SOCK_RECVBUF_UNLOCK(so);
1537
1538 if (psa != NULL)
1539 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1540 m = m_free(m);
1541 KASSERT(m, ("%s: no data or control after soname", __func__));
1542
1543 /*
1544 * Packet to copyout() is now in 'm' and it is disconnected from the
1545 * queue.
1546 *
1547 * Process one or more MT_CONTROL mbufs present before any data mbufs
1548 * in the first mbuf chain on the socket buffer. We call into the
1549 * unp_externalize() to perform externalization (or freeing if
1550 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1551 * without MT_DATA mbufs.
1552 */
1553 while (m != NULL && m->m_type == MT_CONTROL) {
1554 struct mbuf *cm;
1555
1556 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1557 * it frees whole chain, so we must disconnect the mbuf.
1558 */
1559 cm = m; m = m->m_next; cm->m_next = NULL;
1560 error = unp_externalize(cm, controlp, flags);
1561 if (error != 0) {
1562 SOCK_IO_RECV_UNLOCK(so);
1563 unp_scan(m, unp_freerights);
1564 m_freem(m);
1565 return (error);
1566 }
1567 if (controlp != NULL) {
1568 while (*controlp != NULL)
1569 controlp = &(*controlp)->m_next;
1570 }
1571 }
1572 KASSERT(m == NULL || m->m_type == MT_DATA,
1573 ("%s: not MT_DATA mbuf %p", __func__, m));
1574 while (m != NULL && uio->uio_resid > 0) {
1575 len = uio->uio_resid;
1576 if (len > m->m_len)
1577 len = m->m_len;
1578 error = uiomove(mtod(m, char *), (int)len, uio);
1579 if (error) {
1580 SOCK_IO_RECV_UNLOCK(so);
1581 m_freem(m);
1582 return (error);
1583 }
1584 if (len == m->m_len)
1585 m = m_free(m);
1586 else {
1587 m->m_data += len;
1588 m->m_len -= len;
1589 }
1590 }
1591 SOCK_IO_RECV_UNLOCK(so);
1592
1593 if (m != NULL) {
1594 if (flagsp != NULL) {
1595 if (flags & MSG_TRUNC) {
1596 /* Report real length of the packet */
1597 uio->uio_resid -= m_length(m, NULL);
1598 }
1599 *flagsp |= MSG_TRUNC;
1600 }
1601 m_freem(m);
1602 } else if (flagsp != NULL)
1603 *flagsp &= ~MSG_TRUNC;
1604
1605 return (0);
1606 }
1607
1608 static bool
uipc_ready_scan(struct socket * so,struct mbuf * m,int count,int * errorp)1609 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1610 {
1611 struct mbuf *mb, *n;
1612 struct sockbuf *sb;
1613
1614 SOCK_LOCK(so);
1615 if (SOLISTENING(so)) {
1616 SOCK_UNLOCK(so);
1617 return (false);
1618 }
1619 mb = NULL;
1620 sb = &so->so_rcv;
1621 SOCKBUF_LOCK(sb);
1622 if (sb->sb_fnrdy != NULL) {
1623 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1624 if (mb == m) {
1625 *errorp = sbready(sb, m, count);
1626 break;
1627 }
1628 mb = mb->m_next;
1629 if (mb == NULL) {
1630 mb = n;
1631 if (mb != NULL)
1632 n = mb->m_nextpkt;
1633 }
1634 }
1635 }
1636 SOCKBUF_UNLOCK(sb);
1637 SOCK_UNLOCK(so);
1638 return (mb != NULL);
1639 }
1640
1641 static int
uipc_ready(struct socket * so,struct mbuf * m,int count)1642 uipc_ready(struct socket *so, struct mbuf *m, int count)
1643 {
1644 struct unpcb *unp, *unp2;
1645 struct socket *so2;
1646 int error, i;
1647
1648 unp = sotounpcb(so);
1649
1650 KASSERT(so->so_type == SOCK_STREAM,
1651 ("%s: unexpected socket type for %p", __func__, so));
1652
1653 UNP_PCB_LOCK(unp);
1654 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1655 UNP_PCB_UNLOCK(unp);
1656 so2 = unp2->unp_socket;
1657 SOCKBUF_LOCK(&so2->so_rcv);
1658 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1659 sorwakeup_locked(so2);
1660 else
1661 SOCKBUF_UNLOCK(&so2->so_rcv);
1662 UNP_PCB_UNLOCK(unp2);
1663 return (error);
1664 }
1665 UNP_PCB_UNLOCK(unp);
1666
1667 /*
1668 * The receiving socket has been disconnected, but may still be valid.
1669 * In this case, the now-ready mbufs are still present in its socket
1670 * buffer, so perform an exhaustive search before giving up and freeing
1671 * the mbufs.
1672 */
1673 UNP_LINK_RLOCK();
1674 LIST_FOREACH(unp, &unp_shead, unp_link) {
1675 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1676 break;
1677 }
1678 UNP_LINK_RUNLOCK();
1679
1680 if (unp == NULL) {
1681 for (i = 0; i < count; i++)
1682 m = m_free(m);
1683 error = ECONNRESET;
1684 }
1685 return (error);
1686 }
1687
1688 static int
uipc_sense(struct socket * so,struct stat * sb)1689 uipc_sense(struct socket *so, struct stat *sb)
1690 {
1691 struct unpcb *unp;
1692
1693 unp = sotounpcb(so);
1694 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1695
1696 sb->st_blksize = so->so_snd.sb_hiwat;
1697 sb->st_dev = NODEV;
1698 sb->st_ino = unp->unp_ino;
1699 return (0);
1700 }
1701
1702 static int
uipc_shutdown(struct socket * so)1703 uipc_shutdown(struct socket *so)
1704 {
1705 struct unpcb *unp;
1706
1707 unp = sotounpcb(so);
1708 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1709
1710 UNP_PCB_LOCK(unp);
1711 socantsendmore(so);
1712 unp_shutdown(unp);
1713 UNP_PCB_UNLOCK(unp);
1714 return (0);
1715 }
1716
1717 static int
uipc_sockaddr(struct socket * so,struct sockaddr ** nam)1718 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1719 {
1720 struct unpcb *unp;
1721 const struct sockaddr *sa;
1722
1723 unp = sotounpcb(so);
1724 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1725
1726 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1727 UNP_PCB_LOCK(unp);
1728 if (unp->unp_addr != NULL)
1729 sa = (struct sockaddr *) unp->unp_addr;
1730 else
1731 sa = &sun_noname;
1732 bcopy(sa, *nam, sa->sa_len);
1733 UNP_PCB_UNLOCK(unp);
1734 return (0);
1735 }
1736
1737 static int
uipc_ctloutput(struct socket * so,struct sockopt * sopt)1738 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1739 {
1740 struct unpcb *unp;
1741 struct xucred xu;
1742 int error, optval;
1743
1744 if (sopt->sopt_level != SOL_LOCAL)
1745 return (EINVAL);
1746
1747 unp = sotounpcb(so);
1748 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1749 error = 0;
1750 switch (sopt->sopt_dir) {
1751 case SOPT_GET:
1752 switch (sopt->sopt_name) {
1753 case LOCAL_PEERCRED:
1754 UNP_PCB_LOCK(unp);
1755 if (unp->unp_flags & UNP_HAVEPC)
1756 xu = unp->unp_peercred;
1757 else {
1758 if (so->so_type == SOCK_STREAM)
1759 error = ENOTCONN;
1760 else
1761 error = EINVAL;
1762 }
1763 UNP_PCB_UNLOCK(unp);
1764 if (error == 0)
1765 error = sooptcopyout(sopt, &xu, sizeof(xu));
1766 break;
1767
1768 case LOCAL_CREDS:
1769 /* Unlocked read. */
1770 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1771 error = sooptcopyout(sopt, &optval, sizeof(optval));
1772 break;
1773
1774 case LOCAL_CREDS_PERSISTENT:
1775 /* Unlocked read. */
1776 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1777 error = sooptcopyout(sopt, &optval, sizeof(optval));
1778 break;
1779
1780 case LOCAL_CONNWAIT:
1781 /* Unlocked read. */
1782 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1783 error = sooptcopyout(sopt, &optval, sizeof(optval));
1784 break;
1785
1786 default:
1787 error = EOPNOTSUPP;
1788 break;
1789 }
1790 break;
1791
1792 case SOPT_SET:
1793 switch (sopt->sopt_name) {
1794 case LOCAL_CREDS:
1795 case LOCAL_CREDS_PERSISTENT:
1796 case LOCAL_CONNWAIT:
1797 error = sooptcopyin(sopt, &optval, sizeof(optval),
1798 sizeof(optval));
1799 if (error)
1800 break;
1801
1802 #define OPTSET(bit, exclusive) do { \
1803 UNP_PCB_LOCK(unp); \
1804 if (optval) { \
1805 if ((unp->unp_flags & (exclusive)) != 0) { \
1806 UNP_PCB_UNLOCK(unp); \
1807 error = EINVAL; \
1808 break; \
1809 } \
1810 unp->unp_flags |= (bit); \
1811 } else \
1812 unp->unp_flags &= ~(bit); \
1813 UNP_PCB_UNLOCK(unp); \
1814 } while (0)
1815
1816 switch (sopt->sopt_name) {
1817 case LOCAL_CREDS:
1818 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1819 break;
1820
1821 case LOCAL_CREDS_PERSISTENT:
1822 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1823 break;
1824
1825 case LOCAL_CONNWAIT:
1826 OPTSET(UNP_CONNWAIT, 0);
1827 break;
1828
1829 default:
1830 break;
1831 }
1832 break;
1833 #undef OPTSET
1834 default:
1835 error = ENOPROTOOPT;
1836 break;
1837 }
1838 break;
1839
1840 default:
1841 error = EOPNOTSUPP;
1842 break;
1843 }
1844 return (error);
1845 }
1846
1847 static int
unp_connect(struct socket * so,struct sockaddr * nam,struct thread * td)1848 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1849 {
1850
1851 return (unp_connectat(AT_FDCWD, so, nam, td, false));
1852 }
1853
1854 static int
unp_connectat(int fd,struct socket * so,struct sockaddr * nam,struct thread * td,bool return_locked)1855 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1856 struct thread *td, bool return_locked)
1857 {
1858 struct mtx *vplock;
1859 struct sockaddr_un *soun;
1860 struct vnode *vp;
1861 struct socket *so2;
1862 struct unpcb *unp, *unp2, *unp3;
1863 struct nameidata nd;
1864 char buf[SOCK_MAXADDRLEN];
1865 struct sockaddr *sa;
1866 cap_rights_t rights;
1867 int error, len;
1868 bool connreq;
1869
1870 if (nam->sa_family != AF_UNIX)
1871 return (EAFNOSUPPORT);
1872 if (nam->sa_len > sizeof(struct sockaddr_un))
1873 return (EINVAL);
1874 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1875 if (len <= 0)
1876 return (EINVAL);
1877 soun = (struct sockaddr_un *)nam;
1878 bcopy(soun->sun_path, buf, len);
1879 buf[len] = 0;
1880
1881 error = 0;
1882 unp = sotounpcb(so);
1883 UNP_PCB_LOCK(unp);
1884 for (;;) {
1885 /*
1886 * Wait for connection state to stabilize. If a connection
1887 * already exists, give up. For datagram sockets, which permit
1888 * multiple consecutive connect(2) calls, upper layers are
1889 * responsible for disconnecting in advance of a subsequent
1890 * connect(2), but this is not synchronized with PCB connection
1891 * state.
1892 *
1893 * Also make sure that no threads are currently attempting to
1894 * lock the peer socket, to ensure that unp_conn cannot
1895 * transition between two valid sockets while locks are dropped.
1896 */
1897 if (SOLISTENING(so))
1898 error = EOPNOTSUPP;
1899 else if (unp->unp_conn != NULL)
1900 error = EISCONN;
1901 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1902 error = EALREADY;
1903 }
1904 if (error != 0) {
1905 UNP_PCB_UNLOCK(unp);
1906 return (error);
1907 }
1908 if (unp->unp_pairbusy > 0) {
1909 unp->unp_flags |= UNP_WAITING;
1910 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1911 continue;
1912 }
1913 break;
1914 }
1915 unp->unp_flags |= UNP_CONNECTING;
1916 UNP_PCB_UNLOCK(unp);
1917
1918 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1919 if (connreq)
1920 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1921 else
1922 sa = NULL;
1923 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1924 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1925 error = namei(&nd);
1926 if (error)
1927 vp = NULL;
1928 else
1929 vp = nd.ni_vp;
1930 ASSERT_VOP_LOCKED(vp, "unp_connect");
1931 if (error)
1932 goto bad;
1933 NDFREE_PNBUF(&nd);
1934
1935 if (vp->v_type != VSOCK) {
1936 error = ENOTSOCK;
1937 goto bad;
1938 }
1939 #ifdef MAC
1940 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1941 if (error)
1942 goto bad;
1943 #endif
1944 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1945 if (error)
1946 goto bad;
1947
1948 unp = sotounpcb(so);
1949 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1950
1951 vplock = mtx_pool_find(mtxpool_sleep, vp);
1952 mtx_lock(vplock);
1953 VOP_UNP_CONNECT(vp, &unp2);
1954 if (unp2 == NULL) {
1955 error = ECONNREFUSED;
1956 goto bad2;
1957 }
1958 so2 = unp2->unp_socket;
1959 if (so->so_type != so2->so_type) {
1960 error = EPROTOTYPE;
1961 goto bad2;
1962 }
1963 if (connreq) {
1964 if (SOLISTENING(so2)) {
1965 CURVNET_SET(so2->so_vnet);
1966 so2 = sonewconn(so2, 0);
1967 CURVNET_RESTORE();
1968 } else
1969 so2 = NULL;
1970 if (so2 == NULL) {
1971 error = ECONNREFUSED;
1972 goto bad2;
1973 }
1974 unp3 = sotounpcb(so2);
1975 unp_pcb_lock_pair(unp2, unp3);
1976 if (unp2->unp_addr != NULL) {
1977 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1978 unp3->unp_addr = (struct sockaddr_un *) sa;
1979 sa = NULL;
1980 }
1981
1982 unp_copy_peercred(td, unp3, unp, unp2);
1983
1984 UNP_PCB_UNLOCK(unp2);
1985 unp2 = unp3;
1986
1987 /*
1988 * It is safe to block on the PCB lock here since unp2 is
1989 * nascent and cannot be connected to any other sockets.
1990 */
1991 UNP_PCB_LOCK(unp);
1992 #ifdef MAC
1993 mac_socketpeer_set_from_socket(so, so2);
1994 mac_socketpeer_set_from_socket(so2, so);
1995 #endif
1996 } else {
1997 unp_pcb_lock_pair(unp, unp2);
1998 }
1999 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
2000 sotounpcb(so2) == unp2,
2001 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
2002 unp_connect2(so, so2, PRU_CONNECT);
2003 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2004 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2005 unp->unp_flags &= ~UNP_CONNECTING;
2006 if (!return_locked)
2007 unp_pcb_unlock_pair(unp, unp2);
2008 bad2:
2009 mtx_unlock(vplock);
2010 bad:
2011 if (vp != NULL) {
2012 /*
2013 * If we are returning locked (called via uipc_sosend_dgram()),
2014 * we need to be sure that vput() won't sleep. This is
2015 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2016 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2017 */
2018 MPASS(!(return_locked && connreq));
2019 vput(vp);
2020 }
2021 free(sa, M_SONAME);
2022 if (__predict_false(error)) {
2023 UNP_PCB_LOCK(unp);
2024 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2025 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2026 unp->unp_flags &= ~UNP_CONNECTING;
2027 UNP_PCB_UNLOCK(unp);
2028 }
2029 return (error);
2030 }
2031
2032 /*
2033 * Set socket peer credentials at connection time.
2034 *
2035 * The client's PCB credentials are copied from its process structure. The
2036 * server's PCB credentials are copied from the socket on which it called
2037 * listen(2). uipc_listen cached that process's credentials at the time.
2038 */
2039 void
unp_copy_peercred(struct thread * td,struct unpcb * client_unp,struct unpcb * server_unp,struct unpcb * listen_unp)2040 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2041 struct unpcb *server_unp, struct unpcb *listen_unp)
2042 {
2043 cru2xt(td, &client_unp->unp_peercred);
2044 client_unp->unp_flags |= UNP_HAVEPC;
2045
2046 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2047 sizeof(server_unp->unp_peercred));
2048 server_unp->unp_flags |= UNP_HAVEPC;
2049 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2050 }
2051
2052 static void
unp_connect2(struct socket * so,struct socket * so2,conn2_how req)2053 unp_connect2(struct socket *so, struct socket *so2, conn2_how req)
2054 {
2055 struct unpcb *unp;
2056 struct unpcb *unp2;
2057
2058 MPASS(so2->so_type == so->so_type);
2059 unp = sotounpcb(so);
2060 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2061 unp2 = sotounpcb(so2);
2062 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2063
2064 UNP_PCB_LOCK_ASSERT(unp);
2065 UNP_PCB_LOCK_ASSERT(unp2);
2066 KASSERT(unp->unp_conn == NULL,
2067 ("%s: socket %p is already connected", __func__, unp));
2068
2069 unp->unp_conn = unp2;
2070 unp_pcb_hold(unp2);
2071 unp_pcb_hold(unp);
2072 switch (so->so_type) {
2073 case SOCK_DGRAM:
2074 UNP_REF_LIST_LOCK();
2075 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2076 UNP_REF_LIST_UNLOCK();
2077 soisconnected(so);
2078 break;
2079
2080 case SOCK_STREAM:
2081 case SOCK_SEQPACKET:
2082 KASSERT(unp2->unp_conn == NULL,
2083 ("%s: socket %p is already connected", __func__, unp2));
2084 unp2->unp_conn = unp;
2085 if (req == PRU_CONNECT &&
2086 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2087 soisconnecting(so);
2088 else
2089 soisconnected(so);
2090 soisconnected(so2);
2091 break;
2092
2093 default:
2094 panic("unp_connect2");
2095 }
2096 }
2097
2098 static void
unp_disconnect(struct unpcb * unp,struct unpcb * unp2)2099 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2100 {
2101 struct socket *so, *so2;
2102 struct mbuf *m = NULL;
2103 #ifdef INVARIANTS
2104 struct unpcb *unptmp;
2105 #endif
2106
2107 UNP_PCB_LOCK_ASSERT(unp);
2108 UNP_PCB_LOCK_ASSERT(unp2);
2109 KASSERT(unp->unp_conn == unp2,
2110 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2111
2112 unp->unp_conn = NULL;
2113 so = unp->unp_socket;
2114 so2 = unp2->unp_socket;
2115 switch (unp->unp_socket->so_type) {
2116 case SOCK_DGRAM:
2117 /*
2118 * Remove our send socket buffer from the peer's receive buffer.
2119 * Move the data to the receive buffer only if it is empty.
2120 * This is a protection against a scenario where a peer
2121 * connects, floods and disconnects, effectively blocking
2122 * sendto() from unconnected sockets.
2123 */
2124 SOCK_RECVBUF_LOCK(so2);
2125 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2126 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2127 uxdg_clist);
2128 if (__predict_true((so2->so_rcv.sb_state &
2129 SBS_CANTRCVMORE) == 0) &&
2130 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2131 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2132 &so->so_snd.uxdg_mb);
2133 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2134 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2135 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2136 } else {
2137 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2138 STAILQ_INIT(&so->so_snd.uxdg_mb);
2139 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2140 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2141 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2142 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2143 }
2144 /* Note: so may reconnect. */
2145 so->so_snd.uxdg_cc = 0;
2146 so->so_snd.uxdg_ctl = 0;
2147 so->so_snd.uxdg_mbcnt = 0;
2148 }
2149 SOCK_RECVBUF_UNLOCK(so2);
2150 UNP_REF_LIST_LOCK();
2151 #ifdef INVARIANTS
2152 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2153 if (unptmp == unp)
2154 break;
2155 }
2156 KASSERT(unptmp != NULL,
2157 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2158 #endif
2159 LIST_REMOVE(unp, unp_reflink);
2160 UNP_REF_LIST_UNLOCK();
2161 if (so) {
2162 SOCK_LOCK(so);
2163 so->so_state &= ~SS_ISCONNECTED;
2164 SOCK_UNLOCK(so);
2165 }
2166 break;
2167
2168 case SOCK_STREAM:
2169 case SOCK_SEQPACKET:
2170 if (so)
2171 soisdisconnected(so);
2172 MPASS(unp2->unp_conn == unp);
2173 unp2->unp_conn = NULL;
2174 if (so2)
2175 soisdisconnected(so2);
2176 break;
2177 }
2178
2179 if (unp == unp2) {
2180 unp_pcb_rele_notlast(unp);
2181 if (!unp_pcb_rele(unp))
2182 UNP_PCB_UNLOCK(unp);
2183 } else {
2184 if (!unp_pcb_rele(unp))
2185 UNP_PCB_UNLOCK(unp);
2186 if (!unp_pcb_rele(unp2))
2187 UNP_PCB_UNLOCK(unp2);
2188 }
2189
2190 if (m != NULL) {
2191 unp_scan(m, unp_freerights);
2192 m_freemp(m);
2193 }
2194 }
2195
2196 /*
2197 * unp_pcblist() walks the global list of struct unpcb's to generate a
2198 * pointer list, bumping the refcount on each unpcb. It then copies them out
2199 * sequentially, validating the generation number on each to see if it has
2200 * been detached. All of this is necessary because copyout() may sleep on
2201 * disk I/O.
2202 */
2203 static int
unp_pcblist(SYSCTL_HANDLER_ARGS)2204 unp_pcblist(SYSCTL_HANDLER_ARGS)
2205 {
2206 struct unpcb *unp, **unp_list;
2207 unp_gen_t gencnt;
2208 struct xunpgen *xug;
2209 struct unp_head *head;
2210 struct xunpcb *xu;
2211 u_int i;
2212 int error, n;
2213
2214 switch ((intptr_t)arg1) {
2215 case SOCK_STREAM:
2216 head = &unp_shead;
2217 break;
2218
2219 case SOCK_DGRAM:
2220 head = &unp_dhead;
2221 break;
2222
2223 case SOCK_SEQPACKET:
2224 head = &unp_sphead;
2225 break;
2226
2227 default:
2228 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2229 }
2230
2231 /*
2232 * The process of preparing the PCB list is too time-consuming and
2233 * resource-intensive to repeat twice on every request.
2234 */
2235 if (req->oldptr == NULL) {
2236 n = unp_count;
2237 req->oldidx = 2 * (sizeof *xug)
2238 + (n + n/8) * sizeof(struct xunpcb);
2239 return (0);
2240 }
2241
2242 if (req->newptr != NULL)
2243 return (EPERM);
2244
2245 /*
2246 * OK, now we're committed to doing something.
2247 */
2248 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2249 UNP_LINK_RLOCK();
2250 gencnt = unp_gencnt;
2251 n = unp_count;
2252 UNP_LINK_RUNLOCK();
2253
2254 xug->xug_len = sizeof *xug;
2255 xug->xug_count = n;
2256 xug->xug_gen = gencnt;
2257 xug->xug_sogen = so_gencnt;
2258 error = SYSCTL_OUT(req, xug, sizeof *xug);
2259 if (error) {
2260 free(xug, M_TEMP);
2261 return (error);
2262 }
2263
2264 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2265
2266 UNP_LINK_RLOCK();
2267 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2268 unp = LIST_NEXT(unp, unp_link)) {
2269 UNP_PCB_LOCK(unp);
2270 if (unp->unp_gencnt <= gencnt) {
2271 if (cr_cansee(req->td->td_ucred,
2272 unp->unp_socket->so_cred)) {
2273 UNP_PCB_UNLOCK(unp);
2274 continue;
2275 }
2276 unp_list[i++] = unp;
2277 unp_pcb_hold(unp);
2278 }
2279 UNP_PCB_UNLOCK(unp);
2280 }
2281 UNP_LINK_RUNLOCK();
2282 n = i; /* In case we lost some during malloc. */
2283
2284 error = 0;
2285 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2286 for (i = 0; i < n; i++) {
2287 unp = unp_list[i];
2288 UNP_PCB_LOCK(unp);
2289 if (unp_pcb_rele(unp))
2290 continue;
2291
2292 if (unp->unp_gencnt <= gencnt) {
2293 xu->xu_len = sizeof *xu;
2294 xu->xu_unpp = (uintptr_t)unp;
2295 /*
2296 * XXX - need more locking here to protect against
2297 * connect/disconnect races for SMP.
2298 */
2299 if (unp->unp_addr != NULL)
2300 bcopy(unp->unp_addr, &xu->xu_addr,
2301 unp->unp_addr->sun_len);
2302 else
2303 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2304 if (unp->unp_conn != NULL &&
2305 unp->unp_conn->unp_addr != NULL)
2306 bcopy(unp->unp_conn->unp_addr,
2307 &xu->xu_caddr,
2308 unp->unp_conn->unp_addr->sun_len);
2309 else
2310 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2311 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2312 xu->unp_conn = (uintptr_t)unp->unp_conn;
2313 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2314 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2315 xu->unp_gencnt = unp->unp_gencnt;
2316 sotoxsocket(unp->unp_socket, &xu->xu_socket);
2317 UNP_PCB_UNLOCK(unp);
2318 error = SYSCTL_OUT(req, xu, sizeof *xu);
2319 } else {
2320 UNP_PCB_UNLOCK(unp);
2321 }
2322 }
2323 free(xu, M_TEMP);
2324 if (!error) {
2325 /*
2326 * Give the user an updated idea of our state. If the
2327 * generation differs from what we told her before, she knows
2328 * that something happened while we were processing this
2329 * request, and it might be necessary to retry.
2330 */
2331 xug->xug_gen = unp_gencnt;
2332 xug->xug_sogen = so_gencnt;
2333 xug->xug_count = unp_count;
2334 error = SYSCTL_OUT(req, xug, sizeof *xug);
2335 }
2336 free(unp_list, M_TEMP);
2337 free(xug, M_TEMP);
2338 return (error);
2339 }
2340
2341 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2342 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2343 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2344 "List of active local datagram sockets");
2345 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2346 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2347 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2348 "List of active local stream sockets");
2349 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2350 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2351 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2352 "List of active local seqpacket sockets");
2353
2354 static void
unp_shutdown(struct unpcb * unp)2355 unp_shutdown(struct unpcb *unp)
2356 {
2357 struct unpcb *unp2;
2358 struct socket *so;
2359
2360 UNP_PCB_LOCK_ASSERT(unp);
2361
2362 unp2 = unp->unp_conn;
2363 if ((unp->unp_socket->so_type == SOCK_STREAM ||
2364 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2365 so = unp2->unp_socket;
2366 if (so != NULL)
2367 socantrcvmore(so);
2368 }
2369 }
2370
2371 static void
unp_drop(struct unpcb * unp)2372 unp_drop(struct unpcb *unp)
2373 {
2374 struct socket *so;
2375 struct unpcb *unp2;
2376
2377 /*
2378 * Regardless of whether the socket's peer dropped the connection
2379 * with this socket by aborting or disconnecting, POSIX requires
2380 * that ECONNRESET is returned.
2381 */
2382
2383 UNP_PCB_LOCK(unp);
2384 so = unp->unp_socket;
2385 if (so)
2386 so->so_error = ECONNRESET;
2387 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2388 /* Last reference dropped in unp_disconnect(). */
2389 unp_pcb_rele_notlast(unp);
2390 unp_disconnect(unp, unp2);
2391 } else if (!unp_pcb_rele(unp)) {
2392 UNP_PCB_UNLOCK(unp);
2393 }
2394 }
2395
2396 static void
unp_freerights(struct filedescent ** fdep,int fdcount)2397 unp_freerights(struct filedescent **fdep, int fdcount)
2398 {
2399 struct file *fp;
2400 int i;
2401
2402 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2403
2404 for (i = 0; i < fdcount; i++) {
2405 fp = fdep[i]->fde_file;
2406 filecaps_free(&fdep[i]->fde_caps);
2407 unp_discard(fp);
2408 }
2409 free(fdep[0], M_FILECAPS);
2410 }
2411
2412 static int
unp_externalize(struct mbuf * control,struct mbuf ** controlp,int flags)2413 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2414 {
2415 struct thread *td = curthread; /* XXX */
2416 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2417 int i;
2418 int *fdp;
2419 struct filedesc *fdesc = td->td_proc->p_fd;
2420 struct filedescent **fdep;
2421 void *data;
2422 socklen_t clen = control->m_len, datalen;
2423 int error, newfds;
2424 u_int newlen;
2425
2426 UNP_LINK_UNLOCK_ASSERT();
2427
2428 error = 0;
2429 if (controlp != NULL) /* controlp == NULL => free control messages */
2430 *controlp = NULL;
2431 while (cm != NULL) {
2432 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2433
2434 data = CMSG_DATA(cm);
2435 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2436 if (cm->cmsg_level == SOL_SOCKET
2437 && cm->cmsg_type == SCM_RIGHTS) {
2438 newfds = datalen / sizeof(*fdep);
2439 if (newfds == 0)
2440 goto next;
2441 fdep = data;
2442
2443 /* If we're not outputting the descriptors free them. */
2444 if (error || controlp == NULL) {
2445 unp_freerights(fdep, newfds);
2446 goto next;
2447 }
2448 FILEDESC_XLOCK(fdesc);
2449
2450 /*
2451 * Now change each pointer to an fd in the global
2452 * table to an integer that is the index to the local
2453 * fd table entry that we set up to point to the
2454 * global one we are transferring.
2455 */
2456 newlen = newfds * sizeof(int);
2457 *controlp = sbcreatecontrol(NULL, newlen,
2458 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2459
2460 fdp = (int *)
2461 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2462 if ((error = fdallocn(td, 0, fdp, newfds))) {
2463 FILEDESC_XUNLOCK(fdesc);
2464 unp_freerights(fdep, newfds);
2465 m_freem(*controlp);
2466 *controlp = NULL;
2467 goto next;
2468 }
2469 for (i = 0; i < newfds; i++, fdp++) {
2470 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2471 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2472 &fdep[i]->fde_caps);
2473 unp_externalize_fp(fdep[i]->fde_file);
2474 }
2475
2476 /*
2477 * The new type indicates that the mbuf data refers to
2478 * kernel resources that may need to be released before
2479 * the mbuf is freed.
2480 */
2481 m_chtype(*controlp, MT_EXTCONTROL);
2482 FILEDESC_XUNLOCK(fdesc);
2483 free(fdep[0], M_FILECAPS);
2484 } else {
2485 /* We can just copy anything else across. */
2486 if (error || controlp == NULL)
2487 goto next;
2488 *controlp = sbcreatecontrol(NULL, datalen,
2489 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2490 bcopy(data,
2491 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2492 datalen);
2493 }
2494 controlp = &(*controlp)->m_next;
2495
2496 next:
2497 if (CMSG_SPACE(datalen) < clen) {
2498 clen -= CMSG_SPACE(datalen);
2499 cm = (struct cmsghdr *)
2500 ((caddr_t)cm + CMSG_SPACE(datalen));
2501 } else {
2502 clen = 0;
2503 cm = NULL;
2504 }
2505 }
2506
2507 m_freem(control);
2508 return (error);
2509 }
2510
2511 static void
unp_zone_change(void * tag)2512 unp_zone_change(void *tag)
2513 {
2514
2515 uma_zone_set_max(unp_zone, maxsockets);
2516 }
2517
2518 #ifdef INVARIANTS
2519 static void
unp_zdtor(void * mem,int size __unused,void * arg __unused)2520 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2521 {
2522 struct unpcb *unp;
2523
2524 unp = mem;
2525
2526 KASSERT(LIST_EMPTY(&unp->unp_refs),
2527 ("%s: unpcb %p has lingering refs", __func__, unp));
2528 KASSERT(unp->unp_socket == NULL,
2529 ("%s: unpcb %p has socket backpointer", __func__, unp));
2530 KASSERT(unp->unp_vnode == NULL,
2531 ("%s: unpcb %p has vnode references", __func__, unp));
2532 KASSERT(unp->unp_conn == NULL,
2533 ("%s: unpcb %p is still connected", __func__, unp));
2534 KASSERT(unp->unp_addr == NULL,
2535 ("%s: unpcb %p has leaked addr", __func__, unp));
2536 }
2537 #endif
2538
2539 static void
unp_init(void * arg __unused)2540 unp_init(void *arg __unused)
2541 {
2542 uma_dtor dtor;
2543
2544 #ifdef INVARIANTS
2545 dtor = unp_zdtor;
2546 #else
2547 dtor = NULL;
2548 #endif
2549 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2550 NULL, NULL, UMA_ALIGN_CACHE, 0);
2551 uma_zone_set_max(unp_zone, maxsockets);
2552 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2553 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2554 NULL, EVENTHANDLER_PRI_ANY);
2555 LIST_INIT(&unp_dhead);
2556 LIST_INIT(&unp_shead);
2557 LIST_INIT(&unp_sphead);
2558 SLIST_INIT(&unp_defers);
2559 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2560 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2561 UNP_LINK_LOCK_INIT();
2562 UNP_DEFERRED_LOCK_INIT();
2563 }
2564 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2565
2566 static void
unp_internalize_cleanup_rights(struct mbuf * control)2567 unp_internalize_cleanup_rights(struct mbuf *control)
2568 {
2569 struct cmsghdr *cp;
2570 struct mbuf *m;
2571 void *data;
2572 socklen_t datalen;
2573
2574 for (m = control; m != NULL; m = m->m_next) {
2575 cp = mtod(m, struct cmsghdr *);
2576 if (cp->cmsg_level != SOL_SOCKET ||
2577 cp->cmsg_type != SCM_RIGHTS)
2578 continue;
2579 data = CMSG_DATA(cp);
2580 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2581 unp_freerights(data, datalen / sizeof(struct filedesc *));
2582 }
2583 }
2584
2585 static int
unp_internalize(struct mbuf ** controlp,struct thread * td,struct mbuf ** clast,u_int * space,u_int * mbcnt)2586 unp_internalize(struct mbuf **controlp, struct thread *td,
2587 struct mbuf **clast, u_int *space, u_int *mbcnt)
2588 {
2589 struct mbuf *control, **initial_controlp;
2590 struct proc *p;
2591 struct filedesc *fdesc;
2592 struct bintime *bt;
2593 struct cmsghdr *cm;
2594 struct cmsgcred *cmcred;
2595 struct filedescent *fde, **fdep, *fdev;
2596 struct file *fp;
2597 struct timeval *tv;
2598 struct timespec *ts;
2599 void *data;
2600 socklen_t clen, datalen;
2601 int i, j, error, *fdp, oldfds;
2602 u_int newlen;
2603
2604 MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2605 UNP_LINK_UNLOCK_ASSERT();
2606
2607 p = td->td_proc;
2608 fdesc = p->p_fd;
2609 error = 0;
2610 control = *controlp;
2611 *controlp = NULL;
2612 initial_controlp = controlp;
2613 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2614 data = CMSG_DATA(cm);
2615
2616 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2617 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2618 (char *)cm + cm->cmsg_len >= (char *)data;
2619
2620 clen -= min(CMSG_SPACE(datalen), clen),
2621 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2622 data = CMSG_DATA(cm)) {
2623 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2624 switch (cm->cmsg_type) {
2625 case SCM_CREDS:
2626 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2627 SCM_CREDS, SOL_SOCKET, M_WAITOK);
2628 cmcred = (struct cmsgcred *)
2629 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2630 cmcred->cmcred_pid = p->p_pid;
2631 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2632 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2633 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2634 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2635 CMGROUP_MAX);
2636 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2637 cmcred->cmcred_groups[i] =
2638 td->td_ucred->cr_groups[i];
2639 break;
2640
2641 case SCM_RIGHTS:
2642 oldfds = datalen / sizeof (int);
2643 if (oldfds == 0)
2644 continue;
2645 /* On some machines sizeof pointer is bigger than
2646 * sizeof int, so we need to check if data fits into
2647 * single mbuf. We could allocate several mbufs, and
2648 * unp_externalize() should even properly handle that.
2649 * But it is not worth to complicate the code for an
2650 * insane scenario of passing over 200 file descriptors
2651 * at once.
2652 */
2653 newlen = oldfds * sizeof(fdep[0]);
2654 if (CMSG_SPACE(newlen) > MCLBYTES) {
2655 error = EMSGSIZE;
2656 goto out;
2657 }
2658 /*
2659 * Check that all the FDs passed in refer to legal
2660 * files. If not, reject the entire operation.
2661 */
2662 fdp = data;
2663 FILEDESC_SLOCK(fdesc);
2664 for (i = 0; i < oldfds; i++, fdp++) {
2665 fp = fget_noref(fdesc, *fdp);
2666 if (fp == NULL) {
2667 FILEDESC_SUNLOCK(fdesc);
2668 error = EBADF;
2669 goto out;
2670 }
2671 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2672 FILEDESC_SUNLOCK(fdesc);
2673 error = EOPNOTSUPP;
2674 goto out;
2675 }
2676 }
2677
2678 /*
2679 * Now replace the integer FDs with pointers to the
2680 * file structure and capability rights.
2681 */
2682 *controlp = sbcreatecontrol(NULL, newlen,
2683 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2684 fdp = data;
2685 for (i = 0; i < oldfds; i++, fdp++) {
2686 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2687 fdp = data;
2688 for (j = 0; j < i; j++, fdp++) {
2689 fdrop(fdesc->fd_ofiles[*fdp].
2690 fde_file, td);
2691 }
2692 FILEDESC_SUNLOCK(fdesc);
2693 error = EBADF;
2694 goto out;
2695 }
2696 }
2697 fdp = data;
2698 fdep = (struct filedescent **)
2699 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2700 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2701 M_WAITOK);
2702 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2703 fde = &fdesc->fd_ofiles[*fdp];
2704 fdep[i] = fdev;
2705 fdep[i]->fde_file = fde->fde_file;
2706 filecaps_copy(&fde->fde_caps,
2707 &fdep[i]->fde_caps, true);
2708 unp_internalize_fp(fdep[i]->fde_file);
2709 }
2710 FILEDESC_SUNLOCK(fdesc);
2711 break;
2712
2713 case SCM_TIMESTAMP:
2714 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2715 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2716 tv = (struct timeval *)
2717 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2718 microtime(tv);
2719 break;
2720
2721 case SCM_BINTIME:
2722 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2723 SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2724 bt = (struct bintime *)
2725 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2726 bintime(bt);
2727 break;
2728
2729 case SCM_REALTIME:
2730 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2731 SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2732 ts = (struct timespec *)
2733 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2734 nanotime(ts);
2735 break;
2736
2737 case SCM_MONOTONIC:
2738 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2739 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2740 ts = (struct timespec *)
2741 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2742 nanouptime(ts);
2743 break;
2744
2745 default:
2746 error = EINVAL;
2747 goto out;
2748 }
2749
2750 if (space != NULL) {
2751 *space += (*controlp)->m_len;
2752 *mbcnt += MSIZE;
2753 if ((*controlp)->m_flags & M_EXT)
2754 *mbcnt += (*controlp)->m_ext.ext_size;
2755 *clast = *controlp;
2756 }
2757 controlp = &(*controlp)->m_next;
2758 }
2759 if (clen > 0)
2760 error = EINVAL;
2761
2762 out:
2763 if (error != 0 && initial_controlp != NULL)
2764 unp_internalize_cleanup_rights(*initial_controlp);
2765 m_freem(control);
2766 return (error);
2767 }
2768
2769 static struct mbuf *
unp_addsockcred(struct thread * td,struct mbuf * control,int mode,struct mbuf ** clast,u_int * space,u_int * mbcnt)2770 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2771 struct mbuf **clast, u_int *space, u_int *mbcnt)
2772 {
2773 struct mbuf *m, *n, *n_prev;
2774 const struct cmsghdr *cm;
2775 int ngroups, i, cmsgtype;
2776 size_t ctrlsz;
2777
2778 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2779 if (mode & UNP_WANTCRED_ALWAYS) {
2780 ctrlsz = SOCKCRED2SIZE(ngroups);
2781 cmsgtype = SCM_CREDS2;
2782 } else {
2783 ctrlsz = SOCKCREDSIZE(ngroups);
2784 cmsgtype = SCM_CREDS;
2785 }
2786
2787 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2788 if (m == NULL)
2789 return (control);
2790 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2791
2792 if (mode & UNP_WANTCRED_ALWAYS) {
2793 struct sockcred2 *sc;
2794
2795 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2796 sc->sc_version = 0;
2797 sc->sc_pid = td->td_proc->p_pid;
2798 sc->sc_uid = td->td_ucred->cr_ruid;
2799 sc->sc_euid = td->td_ucred->cr_uid;
2800 sc->sc_gid = td->td_ucred->cr_rgid;
2801 sc->sc_egid = td->td_ucred->cr_gid;
2802 sc->sc_ngroups = ngroups;
2803 for (i = 0; i < sc->sc_ngroups; i++)
2804 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2805 } else {
2806 struct sockcred *sc;
2807
2808 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2809 sc->sc_uid = td->td_ucred->cr_ruid;
2810 sc->sc_euid = td->td_ucred->cr_uid;
2811 sc->sc_gid = td->td_ucred->cr_rgid;
2812 sc->sc_egid = td->td_ucred->cr_gid;
2813 sc->sc_ngroups = ngroups;
2814 for (i = 0; i < sc->sc_ngroups; i++)
2815 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2816 }
2817
2818 /*
2819 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2820 * created SCM_CREDS control message (struct sockcred) has another
2821 * format.
2822 */
2823 if (control != NULL && cmsgtype == SCM_CREDS)
2824 for (n = control, n_prev = NULL; n != NULL;) {
2825 cm = mtod(n, struct cmsghdr *);
2826 if (cm->cmsg_level == SOL_SOCKET &&
2827 cm->cmsg_type == SCM_CREDS) {
2828 if (n_prev == NULL)
2829 control = n->m_next;
2830 else
2831 n_prev->m_next = n->m_next;
2832 if (space != NULL) {
2833 MPASS(*space >= n->m_len);
2834 *space -= n->m_len;
2835 MPASS(*mbcnt >= MSIZE);
2836 *mbcnt -= MSIZE;
2837 if (n->m_flags & M_EXT) {
2838 MPASS(*mbcnt >=
2839 n->m_ext.ext_size);
2840 *mbcnt -= n->m_ext.ext_size;
2841 }
2842 MPASS(clast);
2843 if (*clast == n) {
2844 MPASS(n->m_next == NULL);
2845 if (n_prev == NULL)
2846 *clast = m;
2847 else
2848 *clast = n_prev;
2849 }
2850 }
2851 n = m_free(n);
2852 } else {
2853 n_prev = n;
2854 n = n->m_next;
2855 }
2856 }
2857
2858 /* Prepend it to the head. */
2859 m->m_next = control;
2860 if (space != NULL) {
2861 *space += m->m_len;
2862 *mbcnt += MSIZE;
2863 if (control == NULL)
2864 *clast = m;
2865 }
2866 return (m);
2867 }
2868
2869 static struct unpcb *
fptounp(struct file * fp)2870 fptounp(struct file *fp)
2871 {
2872 struct socket *so;
2873
2874 if (fp->f_type != DTYPE_SOCKET)
2875 return (NULL);
2876 if ((so = fp->f_data) == NULL)
2877 return (NULL);
2878 if (so->so_proto->pr_domain != &localdomain)
2879 return (NULL);
2880 return sotounpcb(so);
2881 }
2882
2883 static void
unp_discard(struct file * fp)2884 unp_discard(struct file *fp)
2885 {
2886 struct unp_defer *dr;
2887
2888 if (unp_externalize_fp(fp)) {
2889 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2890 dr->ud_fp = fp;
2891 UNP_DEFERRED_LOCK();
2892 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2893 UNP_DEFERRED_UNLOCK();
2894 atomic_add_int(&unp_defers_count, 1);
2895 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2896 } else
2897 closef_nothread(fp);
2898 }
2899
2900 static void
unp_process_defers(void * arg __unused,int pending)2901 unp_process_defers(void *arg __unused, int pending)
2902 {
2903 struct unp_defer *dr;
2904 SLIST_HEAD(, unp_defer) drl;
2905 int count;
2906
2907 SLIST_INIT(&drl);
2908 for (;;) {
2909 UNP_DEFERRED_LOCK();
2910 if (SLIST_FIRST(&unp_defers) == NULL) {
2911 UNP_DEFERRED_UNLOCK();
2912 break;
2913 }
2914 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2915 UNP_DEFERRED_UNLOCK();
2916 count = 0;
2917 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2918 SLIST_REMOVE_HEAD(&drl, ud_link);
2919 closef_nothread(dr->ud_fp);
2920 free(dr, M_TEMP);
2921 count++;
2922 }
2923 atomic_add_int(&unp_defers_count, -count);
2924 }
2925 }
2926
2927 static void
unp_internalize_fp(struct file * fp)2928 unp_internalize_fp(struct file *fp)
2929 {
2930 struct unpcb *unp;
2931
2932 UNP_LINK_WLOCK();
2933 if ((unp = fptounp(fp)) != NULL) {
2934 unp->unp_file = fp;
2935 unp->unp_msgcount++;
2936 }
2937 unp_rights++;
2938 UNP_LINK_WUNLOCK();
2939 }
2940
2941 static int
unp_externalize_fp(struct file * fp)2942 unp_externalize_fp(struct file *fp)
2943 {
2944 struct unpcb *unp;
2945 int ret;
2946
2947 UNP_LINK_WLOCK();
2948 if ((unp = fptounp(fp)) != NULL) {
2949 unp->unp_msgcount--;
2950 ret = 1;
2951 } else
2952 ret = 0;
2953 unp_rights--;
2954 UNP_LINK_WUNLOCK();
2955 return (ret);
2956 }
2957
2958 /*
2959 * unp_defer indicates whether additional work has been defered for a future
2960 * pass through unp_gc(). It is thread local and does not require explicit
2961 * synchronization.
2962 */
2963 static int unp_marked;
2964
2965 static void
unp_remove_dead_ref(struct filedescent ** fdep,int fdcount)2966 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2967 {
2968 struct unpcb *unp;
2969 struct file *fp;
2970 int i;
2971
2972 /*
2973 * This function can only be called from the gc task.
2974 */
2975 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2976 ("%s: not on gc callout", __func__));
2977 UNP_LINK_LOCK_ASSERT();
2978
2979 for (i = 0; i < fdcount; i++) {
2980 fp = fdep[i]->fde_file;
2981 if ((unp = fptounp(fp)) == NULL)
2982 continue;
2983 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2984 continue;
2985 unp->unp_gcrefs--;
2986 }
2987 }
2988
2989 static void
unp_restore_undead_ref(struct filedescent ** fdep,int fdcount)2990 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2991 {
2992 struct unpcb *unp;
2993 struct file *fp;
2994 int i;
2995
2996 /*
2997 * This function can only be called from the gc task.
2998 */
2999 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
3000 ("%s: not on gc callout", __func__));
3001 UNP_LINK_LOCK_ASSERT();
3002
3003 for (i = 0; i < fdcount; i++) {
3004 fp = fdep[i]->fde_file;
3005 if ((unp = fptounp(fp)) == NULL)
3006 continue;
3007 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3008 continue;
3009 unp->unp_gcrefs++;
3010 unp_marked++;
3011 }
3012 }
3013
3014 static void
unp_scan_socket(struct socket * so,void (* op)(struct filedescent **,int))3015 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
3016 {
3017 struct sockbuf *sb;
3018
3019 SOCK_LOCK_ASSERT(so);
3020
3021 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
3022 return;
3023
3024 SOCK_RECVBUF_LOCK(so);
3025 switch (so->so_type) {
3026 case SOCK_DGRAM:
3027 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
3028 unp_scan(so->so_rcv.uxdg_peeked, op);
3029 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
3030 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
3031 break;
3032 case SOCK_STREAM:
3033 case SOCK_SEQPACKET:
3034 unp_scan(so->so_rcv.sb_mb, op);
3035 break;
3036 }
3037 SOCK_RECVBUF_UNLOCK(so);
3038 }
3039
3040 static void
unp_gc_scan(struct unpcb * unp,void (* op)(struct filedescent **,int))3041 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3042 {
3043 struct socket *so, *soa;
3044
3045 so = unp->unp_socket;
3046 SOCK_LOCK(so);
3047 if (SOLISTENING(so)) {
3048 /*
3049 * Mark all sockets in our accept queue.
3050 */
3051 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3052 unp_scan_socket(soa, op);
3053 } else {
3054 /*
3055 * Mark all sockets we reference with RIGHTS.
3056 */
3057 unp_scan_socket(so, op);
3058 }
3059 SOCK_UNLOCK(so);
3060 }
3061
3062 static int unp_recycled;
3063 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
3064 "Number of unreachable sockets claimed by the garbage collector.");
3065
3066 static int unp_taskcount;
3067 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
3068 "Number of times the garbage collector has run.");
3069
3070 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
3071 "Number of active local sockets.");
3072
3073 static void
unp_gc(__unused void * arg,int pending)3074 unp_gc(__unused void *arg, int pending)
3075 {
3076 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3077 NULL };
3078 struct unp_head **head;
3079 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
3080 struct file *f, **unref;
3081 struct unpcb *unp, *unptmp;
3082 int i, total, unp_unreachable;
3083
3084 LIST_INIT(&unp_deadhead);
3085 unp_taskcount++;
3086 UNP_LINK_RLOCK();
3087 /*
3088 * First determine which sockets may be in cycles.
3089 */
3090 unp_unreachable = 0;
3091
3092 for (head = heads; *head != NULL; head++)
3093 LIST_FOREACH(unp, *head, unp_link) {
3094 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3095 ("%s: unp %p has unexpected gc flags 0x%x",
3096 __func__, unp, (unsigned int)unp->unp_gcflag));
3097
3098 f = unp->unp_file;
3099
3100 /*
3101 * Check for an unreachable socket potentially in a
3102 * cycle. It must be in a queue as indicated by
3103 * msgcount, and this must equal the file reference
3104 * count. Note that when msgcount is 0 the file is
3105 * NULL.
3106 */
3107 if (f != NULL && unp->unp_msgcount != 0 &&
3108 refcount_load(&f->f_count) == unp->unp_msgcount) {
3109 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3110 unp->unp_gcflag |= UNPGC_DEAD;
3111 unp->unp_gcrefs = unp->unp_msgcount;
3112 unp_unreachable++;
3113 }
3114 }
3115
3116 /*
3117 * Scan all sockets previously marked as potentially being in a cycle
3118 * and remove the references each socket holds on any UNPGC_DEAD
3119 * sockets in its queue. After this step, all remaining references on
3120 * sockets marked UNPGC_DEAD should not be part of any cycle.
3121 */
3122 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3123 unp_gc_scan(unp, unp_remove_dead_ref);
3124
3125 /*
3126 * If a socket still has a non-negative refcount, it cannot be in a
3127 * cycle. In this case increment refcount of all children iteratively.
3128 * Stop the scan once we do a complete loop without discovering
3129 * a new reachable socket.
3130 */
3131 do {
3132 unp_marked = 0;
3133 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3134 if (unp->unp_gcrefs > 0) {
3135 unp->unp_gcflag &= ~UNPGC_DEAD;
3136 LIST_REMOVE(unp, unp_dead);
3137 KASSERT(unp_unreachable > 0,
3138 ("%s: unp_unreachable underflow.",
3139 __func__));
3140 unp_unreachable--;
3141 unp_gc_scan(unp, unp_restore_undead_ref);
3142 }
3143 } while (unp_marked);
3144
3145 UNP_LINK_RUNLOCK();
3146
3147 if (unp_unreachable == 0)
3148 return;
3149
3150 /*
3151 * Allocate space for a local array of dead unpcbs.
3152 * TODO: can this path be simplified by instead using the local
3153 * dead list at unp_deadhead, after taking out references
3154 * on the file object and/or unpcb and dropping the link lock?
3155 */
3156 unref = malloc(unp_unreachable * sizeof(struct file *),
3157 M_TEMP, M_WAITOK);
3158
3159 /*
3160 * Iterate looking for sockets which have been specifically marked
3161 * as unreachable and store them locally.
3162 */
3163 UNP_LINK_RLOCK();
3164 total = 0;
3165 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3166 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3167 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3168 unp->unp_gcflag &= ~UNPGC_DEAD;
3169 f = unp->unp_file;
3170 if (unp->unp_msgcount == 0 || f == NULL ||
3171 refcount_load(&f->f_count) != unp->unp_msgcount ||
3172 !fhold(f))
3173 continue;
3174 unref[total++] = f;
3175 KASSERT(total <= unp_unreachable,
3176 ("%s: incorrect unreachable count.", __func__));
3177 }
3178 UNP_LINK_RUNLOCK();
3179
3180 /*
3181 * Now flush all sockets, free'ing rights. This will free the
3182 * struct files associated with these sockets but leave each socket
3183 * with one remaining ref.
3184 */
3185 for (i = 0; i < total; i++) {
3186 struct socket *so;
3187
3188 so = unref[i]->f_data;
3189 CURVNET_SET(so->so_vnet);
3190 sorflush(so);
3191 CURVNET_RESTORE();
3192 }
3193
3194 /*
3195 * And finally release the sockets so they can be reclaimed.
3196 */
3197 for (i = 0; i < total; i++)
3198 fdrop(unref[i], NULL);
3199 unp_recycled += total;
3200 free(unref, M_TEMP);
3201 }
3202
3203 /*
3204 * Synchronize against unp_gc, which can trip over data as we are freeing it.
3205 */
3206 static void
unp_dispose(struct socket * so)3207 unp_dispose(struct socket *so)
3208 {
3209 struct sockbuf *sb;
3210 struct unpcb *unp;
3211 struct mbuf *m;
3212
3213 MPASS(!SOLISTENING(so));
3214
3215 unp = sotounpcb(so);
3216 UNP_LINK_WLOCK();
3217 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3218 UNP_LINK_WUNLOCK();
3219
3220 /*
3221 * Grab our special mbufs before calling sbrelease().
3222 */
3223 SOCK_RECVBUF_LOCK(so);
3224 switch (so->so_type) {
3225 case SOCK_DGRAM:
3226 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3227 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3228 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3229 /* Note: socket of sb may reconnect. */
3230 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3231 }
3232 sb = &so->so_rcv;
3233 if (sb->uxdg_peeked != NULL) {
3234 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3235 m_stailqpkt);
3236 sb->uxdg_peeked = NULL;
3237 }
3238 m = STAILQ_FIRST(&sb->uxdg_mb);
3239 STAILQ_INIT(&sb->uxdg_mb);
3240 /* XXX: our shortened sbrelease() */
3241 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3242 RLIM_INFINITY);
3243 /*
3244 * XXXGL Mark sb with SBS_CANTRCVMORE. This is needed to
3245 * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3246 * data to the socket.
3247 * We are now in dom_dispose and it could be a call from
3248 * soshutdown() or from the final sofree(). The sofree() case
3249 * is simple as it guarantees that no more sends will happen,
3250 * however we can race with unp_disconnect() from our peer.
3251 * The shutdown(2) case is more exotic. It would call into
3252 * dom_dispose() only if socket is SS_ISCONNECTED. This is
3253 * possible if we did connect(2) on this socket and we also
3254 * had it bound with bind(2) and receive connections from other
3255 * sockets. Because soshutdown() violates POSIX (see comment
3256 * there) we will end up here shutting down our receive side.
3257 * Of course this will have affect not only on the peer we
3258 * connect(2)ed to, but also on all of the peers who had
3259 * connect(2)ed to us. Their sends would end up with ENOBUFS.
3260 */
3261 sb->sb_state |= SBS_CANTRCVMORE;
3262 break;
3263 case SOCK_STREAM:
3264 case SOCK_SEQPACKET:
3265 sb = &so->so_rcv;
3266 m = sbcut_locked(sb, sb->sb_ccc);
3267 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3268 ("%s: ccc %u mb %p mbcnt %u", __func__,
3269 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3270 sbrelease_locked(so, SO_RCV);
3271 break;
3272 }
3273 SOCK_RECVBUF_UNLOCK(so);
3274 if (SOCK_IO_RECV_OWNED(so))
3275 SOCK_IO_RECV_UNLOCK(so);
3276
3277 if (m != NULL) {
3278 unp_scan(m, unp_freerights);
3279 m_freemp(m);
3280 }
3281 }
3282
3283 static void
unp_scan(struct mbuf * m0,void (* op)(struct filedescent **,int))3284 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3285 {
3286 struct mbuf *m;
3287 struct cmsghdr *cm;
3288 void *data;
3289 socklen_t clen, datalen;
3290
3291 while (m0 != NULL) {
3292 for (m = m0; m; m = m->m_next) {
3293 if (m->m_type != MT_CONTROL)
3294 continue;
3295
3296 cm = mtod(m, struct cmsghdr *);
3297 clen = m->m_len;
3298
3299 while (cm != NULL) {
3300 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3301 break;
3302
3303 data = CMSG_DATA(cm);
3304 datalen = (caddr_t)cm + cm->cmsg_len
3305 - (caddr_t)data;
3306
3307 if (cm->cmsg_level == SOL_SOCKET &&
3308 cm->cmsg_type == SCM_RIGHTS) {
3309 (*op)(data, datalen /
3310 sizeof(struct filedescent *));
3311 }
3312
3313 if (CMSG_SPACE(datalen) < clen) {
3314 clen -= CMSG_SPACE(datalen);
3315 cm = (struct cmsghdr *)
3316 ((caddr_t)cm + CMSG_SPACE(datalen));
3317 } else {
3318 clen = 0;
3319 cm = NULL;
3320 }
3321 }
3322 }
3323 m0 = m0->m_nextpkt;
3324 }
3325 }
3326
3327 /*
3328 * Definitions of protocols supported in the LOCAL domain.
3329 */
3330 static struct protosw streamproto = {
3331 .pr_type = SOCK_STREAM,
3332 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
3333 PR_CAPATTACH,
3334 .pr_ctloutput = &uipc_ctloutput,
3335 .pr_abort = uipc_abort,
3336 .pr_accept = uipc_accept,
3337 .pr_attach = uipc_attach,
3338 .pr_bind = uipc_bind,
3339 .pr_bindat = uipc_bindat,
3340 .pr_connect = uipc_connect,
3341 .pr_connectat = uipc_connectat,
3342 .pr_connect2 = uipc_connect2,
3343 .pr_detach = uipc_detach,
3344 .pr_disconnect = uipc_disconnect,
3345 .pr_listen = uipc_listen,
3346 .pr_peeraddr = uipc_peeraddr,
3347 .pr_rcvd = uipc_rcvd,
3348 .pr_send = uipc_send,
3349 .pr_ready = uipc_ready,
3350 .pr_sense = uipc_sense,
3351 .pr_shutdown = uipc_shutdown,
3352 .pr_sockaddr = uipc_sockaddr,
3353 .pr_soreceive = soreceive_generic,
3354 .pr_close = uipc_close,
3355 };
3356
3357 static struct protosw dgramproto = {
3358 .pr_type = SOCK_DGRAM,
3359 .pr_flags = PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
3360 PR_SOCKBUF,
3361 .pr_ctloutput = &uipc_ctloutput,
3362 .pr_abort = uipc_abort,
3363 .pr_accept = uipc_accept,
3364 .pr_attach = uipc_attach,
3365 .pr_bind = uipc_bind,
3366 .pr_bindat = uipc_bindat,
3367 .pr_connect = uipc_connect,
3368 .pr_connectat = uipc_connectat,
3369 .pr_connect2 = uipc_connect2,
3370 .pr_detach = uipc_detach,
3371 .pr_disconnect = uipc_disconnect,
3372 .pr_peeraddr = uipc_peeraddr,
3373 .pr_sosend = uipc_sosend_dgram,
3374 .pr_sense = uipc_sense,
3375 .pr_shutdown = uipc_shutdown,
3376 .pr_sockaddr = uipc_sockaddr,
3377 .pr_soreceive = uipc_soreceive_dgram,
3378 .pr_close = uipc_close,
3379 };
3380
3381 static struct protosw seqpacketproto = {
3382 .pr_type = SOCK_SEQPACKET,
3383 /*
3384 * XXXRW: For now, PR_ADDR because soreceive will bump into them
3385 * due to our use of sbappendaddr. A new sbappend variants is needed
3386 * that supports both atomic record writes and control data.
3387 */
3388 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
3389 PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
3390 .pr_ctloutput = &uipc_ctloutput,
3391 .pr_abort = uipc_abort,
3392 .pr_accept = uipc_accept,
3393 .pr_attach = uipc_attach,
3394 .pr_bind = uipc_bind,
3395 .pr_bindat = uipc_bindat,
3396 .pr_connect = uipc_connect,
3397 .pr_connectat = uipc_connectat,
3398 .pr_connect2 = uipc_connect2,
3399 .pr_detach = uipc_detach,
3400 .pr_disconnect = uipc_disconnect,
3401 .pr_listen = uipc_listen,
3402 .pr_peeraddr = uipc_peeraddr,
3403 .pr_rcvd = uipc_rcvd,
3404 .pr_send = uipc_send,
3405 .pr_sense = uipc_sense,
3406 .pr_shutdown = uipc_shutdown,
3407 .pr_sockaddr = uipc_sockaddr,
3408 .pr_soreceive = soreceive_generic, /* XXX: or...? */
3409 .pr_close = uipc_close,
3410 };
3411
3412 static struct domain localdomain = {
3413 .dom_family = AF_LOCAL,
3414 .dom_name = "local",
3415 .dom_externalize = unp_externalize,
3416 .dom_dispose = unp_dispose,
3417 .dom_nprotosw = 3,
3418 .dom_protosw = {
3419 &streamproto,
3420 &dgramproto,
3421 &seqpacketproto,
3422 }
3423 };
3424 DOMAIN_SET(local);
3425
3426 /*
3427 * A helper function called by VFS before socket-type vnode reclamation.
3428 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3429 * use count.
3430 */
3431 void
vfs_unp_reclaim(struct vnode * vp)3432 vfs_unp_reclaim(struct vnode *vp)
3433 {
3434 struct unpcb *unp;
3435 int active;
3436 struct mtx *vplock;
3437
3438 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3439 KASSERT(vp->v_type == VSOCK,
3440 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3441
3442 active = 0;
3443 vplock = mtx_pool_find(mtxpool_sleep, vp);
3444 mtx_lock(vplock);
3445 VOP_UNP_CONNECT(vp, &unp);
3446 if (unp == NULL)
3447 goto done;
3448 UNP_PCB_LOCK(unp);
3449 if (unp->unp_vnode == vp) {
3450 VOP_UNP_DETACH(vp);
3451 unp->unp_vnode = NULL;
3452 active = 1;
3453 }
3454 UNP_PCB_UNLOCK(unp);
3455 done:
3456 mtx_unlock(vplock);
3457 if (active)
3458 vunref(vp);
3459 }
3460
3461 #ifdef DDB
3462 static void
db_print_indent(int indent)3463 db_print_indent(int indent)
3464 {
3465 int i;
3466
3467 for (i = 0; i < indent; i++)
3468 db_printf(" ");
3469 }
3470
3471 static void
db_print_unpflags(int unp_flags)3472 db_print_unpflags(int unp_flags)
3473 {
3474 int comma;
3475
3476 comma = 0;
3477 if (unp_flags & UNP_HAVEPC) {
3478 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3479 comma = 1;
3480 }
3481 if (unp_flags & UNP_WANTCRED_ALWAYS) {
3482 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3483 comma = 1;
3484 }
3485 if (unp_flags & UNP_WANTCRED_ONESHOT) {
3486 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3487 comma = 1;
3488 }
3489 if (unp_flags & UNP_CONNWAIT) {
3490 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3491 comma = 1;
3492 }
3493 if (unp_flags & UNP_CONNECTING) {
3494 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3495 comma = 1;
3496 }
3497 if (unp_flags & UNP_BINDING) {
3498 db_printf("%sUNP_BINDING", comma ? ", " : "");
3499 comma = 1;
3500 }
3501 }
3502
3503 static void
db_print_xucred(int indent,struct xucred * xu)3504 db_print_xucred(int indent, struct xucred *xu)
3505 {
3506 int comma, i;
3507
3508 db_print_indent(indent);
3509 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
3510 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3511 db_print_indent(indent);
3512 db_printf("cr_groups: ");
3513 comma = 0;
3514 for (i = 0; i < xu->cr_ngroups; i++) {
3515 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3516 comma = 1;
3517 }
3518 db_printf("\n");
3519 }
3520
3521 static void
db_print_unprefs(int indent,struct unp_head * uh)3522 db_print_unprefs(int indent, struct unp_head *uh)
3523 {
3524 struct unpcb *unp;
3525 int counter;
3526
3527 counter = 0;
3528 LIST_FOREACH(unp, uh, unp_reflink) {
3529 if (counter % 4 == 0)
3530 db_print_indent(indent);
3531 db_printf("%p ", unp);
3532 if (counter % 4 == 3)
3533 db_printf("\n");
3534 counter++;
3535 }
3536 if (counter != 0 && counter % 4 != 0)
3537 db_printf("\n");
3538 }
3539
DB_SHOW_COMMAND(unpcb,db_show_unpcb)3540 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3541 {
3542 struct unpcb *unp;
3543
3544 if (!have_addr) {
3545 db_printf("usage: show unpcb <addr>\n");
3546 return;
3547 }
3548 unp = (struct unpcb *)addr;
3549
3550 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
3551 unp->unp_vnode);
3552
3553 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3554 unp->unp_conn);
3555
3556 db_printf("unp_refs:\n");
3557 db_print_unprefs(2, &unp->unp_refs);
3558
3559 /* XXXRW: Would be nice to print the full address, if any. */
3560 db_printf("unp_addr: %p\n", unp->unp_addr);
3561
3562 db_printf("unp_gencnt: %llu\n",
3563 (unsigned long long)unp->unp_gencnt);
3564
3565 db_printf("unp_flags: %x (", unp->unp_flags);
3566 db_print_unpflags(unp->unp_flags);
3567 db_printf(")\n");
3568
3569 db_printf("unp_peercred:\n");
3570 db_print_xucred(2, &unp->unp_peercred);
3571
3572 db_printf("unp_refcount: %u\n", unp->unp_refcount);
3573 }
3574 #endif
3575