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