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