]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_usrreq.c
smp_topo: dynamically allocate group array
[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 = 16*1024;      /* support 8KB syslog msgs */
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_one(&rights, CAP_BINDAT),
640             td);
641 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
642         error = namei(&nd);
643         if (error)
644                 goto error;
645         vp = nd.ni_vp;
646         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
647                 NDFREE(&nd, NDF_ONLY_PNBUF);
648                 if (nd.ni_dvp == vp)
649                         vrele(nd.ni_dvp);
650                 else
651                         vput(nd.ni_dvp);
652                 if (vp != NULL) {
653                         vrele(vp);
654                         error = EADDRINUSE;
655                         goto error;
656                 }
657                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
658                 if (error)
659                         goto error;
660                 goto restart;
661         }
662         VATTR_NULL(&vattr);
663         vattr.va_type = VSOCK;
664         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
665 #ifdef MAC
666         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
667             &vattr);
668 #endif
669         if (error == 0)
670                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
671         NDFREE(&nd, NDF_ONLY_PNBUF);
672         if (error) {
673                 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
674                 vn_finished_write(mp);
675                 if (error == ERELOOKUP)
676                         goto restart;
677                 goto error;
678         }
679         vp = nd.ni_vp;
680         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
681         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
682
683         UNP_PCB_LOCK(unp);
684         VOP_UNP_BIND(vp, unp);
685         unp->unp_vnode = vp;
686         unp->unp_addr = soun;
687         unp->unp_flags &= ~UNP_BINDING;
688         UNP_PCB_UNLOCK(unp);
689         vref(vp);
690         VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
691         vn_finished_write(mp);
692         free(buf, M_TEMP);
693         return (0);
694
695 error:
696         UNP_PCB_LOCK(unp);
697         unp->unp_flags &= ~UNP_BINDING;
698         UNP_PCB_UNLOCK(unp);
699         free(buf, M_TEMP);
700         return (error);
701 }
702
703 static int
704 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
705 {
706
707         return (uipc_bindat(AT_FDCWD, so, nam, td));
708 }
709
710 static int
711 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
712 {
713         int error;
714
715         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
716         error = unp_connect(so, nam, td);
717         return (error);
718 }
719
720 static int
721 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
722     struct thread *td)
723 {
724         int error;
725
726         KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
727         error = unp_connectat(fd, so, nam, td);
728         return (error);
729 }
730
731 static void
732 uipc_close(struct socket *so)
733 {
734         struct unpcb *unp, *unp2;
735         struct vnode *vp = NULL;
736         struct mtx *vplock;
737
738         unp = sotounpcb(so);
739         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
740
741         vplock = NULL;
742         if ((vp = unp->unp_vnode) != NULL) {
743                 vplock = mtx_pool_find(mtxpool_sleep, vp);
744                 mtx_lock(vplock);
745         }
746         UNP_PCB_LOCK(unp);
747         if (vp && unp->unp_vnode == NULL) {
748                 mtx_unlock(vplock);
749                 vp = NULL;
750         }
751         if (vp != NULL) {
752                 VOP_UNP_DETACH(vp);
753                 unp->unp_vnode = NULL;
754         }
755         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
756                 unp_disconnect(unp, unp2);
757         else
758                 UNP_PCB_UNLOCK(unp);
759         if (vp) {
760                 mtx_unlock(vplock);
761                 vrele(vp);
762         }
763 }
764
765 static int
766 uipc_connect2(struct socket *so1, struct socket *so2)
767 {
768         struct unpcb *unp, *unp2;
769         int error;
770
771         unp = so1->so_pcb;
772         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
773         unp2 = so2->so_pcb;
774         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
775         unp_pcb_lock_pair(unp, unp2);
776         error = unp_connect2(so1, so2, PRU_CONNECT2);
777         unp_pcb_unlock_pair(unp, unp2);
778         return (error);
779 }
780
781 static void
782 uipc_detach(struct socket *so)
783 {
784         struct unpcb *unp, *unp2;
785         struct mtx *vplock;
786         struct vnode *vp;
787         int local_unp_rights;
788
789         unp = sotounpcb(so);
790         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
791
792         vp = NULL;
793         vplock = NULL;
794
795         SOCK_LOCK(so);
796         if (!SOLISTENING(so)) {
797                 /*
798                  * Once the socket is removed from the global lists,
799                  * uipc_ready() will not be able to locate its socket buffer, so
800                  * clear the buffer now.  At this point internalized rights have
801                  * already been disposed of.
802                  */
803                 sbrelease(&so->so_rcv, so);
804         }
805         SOCK_UNLOCK(so);
806
807         UNP_LINK_WLOCK();
808         LIST_REMOVE(unp, unp_link);
809         if (unp->unp_gcflag & UNPGC_DEAD)
810                 LIST_REMOVE(unp, unp_dead);
811         unp->unp_gencnt = ++unp_gencnt;
812         --unp_count;
813         UNP_LINK_WUNLOCK();
814
815         UNP_PCB_UNLOCK_ASSERT(unp);
816  restart:
817         if ((vp = unp->unp_vnode) != NULL) {
818                 vplock = mtx_pool_find(mtxpool_sleep, vp);
819                 mtx_lock(vplock);
820         }
821         UNP_PCB_LOCK(unp);
822         if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
823                 if (vplock)
824                         mtx_unlock(vplock);
825                 UNP_PCB_UNLOCK(unp);
826                 goto restart;
827         }
828         if ((vp = unp->unp_vnode) != NULL) {
829                 VOP_UNP_DETACH(vp);
830                 unp->unp_vnode = NULL;
831         }
832         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
833                 unp_disconnect(unp, unp2);
834         else
835                 UNP_PCB_UNLOCK(unp);
836
837         UNP_REF_LIST_LOCK();
838         while (!LIST_EMPTY(&unp->unp_refs)) {
839                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
840
841                 unp_pcb_hold(ref);
842                 UNP_REF_LIST_UNLOCK();
843
844                 MPASS(ref != unp);
845                 UNP_PCB_UNLOCK_ASSERT(ref);
846                 unp_drop(ref);
847                 UNP_REF_LIST_LOCK();
848         }
849         UNP_REF_LIST_UNLOCK();
850
851         UNP_PCB_LOCK(unp);
852         local_unp_rights = unp_rights;
853         unp->unp_socket->so_pcb = NULL;
854         unp->unp_socket = NULL;
855         free(unp->unp_addr, M_SONAME);
856         unp->unp_addr = NULL;
857         if (!unp_pcb_rele(unp))
858                 UNP_PCB_UNLOCK(unp);
859         if (vp) {
860                 mtx_unlock(vplock);
861                 vrele(vp);
862         }
863         if (local_unp_rights)
864                 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
865 }
866
867 static int
868 uipc_disconnect(struct socket *so)
869 {
870         struct unpcb *unp, *unp2;
871
872         unp = sotounpcb(so);
873         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
874
875         UNP_PCB_LOCK(unp);
876         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
877                 unp_disconnect(unp, unp2);
878         else
879                 UNP_PCB_UNLOCK(unp);
880         return (0);
881 }
882
883 static int
884 uipc_listen(struct socket *so, int backlog, struct thread *td)
885 {
886         struct unpcb *unp;
887         int error;
888
889         if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
890                 return (EOPNOTSUPP);
891
892         unp = sotounpcb(so);
893         KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
894
895         UNP_PCB_LOCK(unp);
896         if (unp->unp_vnode == NULL) {
897                 /* Already connected or not bound to an address. */
898                 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
899                 UNP_PCB_UNLOCK(unp);
900                 return (error);
901         }
902
903         SOCK_LOCK(so);
904         error = solisten_proto_check(so);
905         if (error == 0) {
906                 cru2xt(td, &unp->unp_peercred);
907                 solisten_proto(so, backlog);
908         }
909         SOCK_UNLOCK(so);
910         UNP_PCB_UNLOCK(unp);
911         return (error);
912 }
913
914 static int
915 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
916 {
917         struct unpcb *unp, *unp2;
918         const struct sockaddr *sa;
919
920         unp = sotounpcb(so);
921         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
922
923         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
924
925         UNP_PCB_LOCK(unp);
926         unp2 = unp_pcb_lock_peer(unp);
927         if (unp2 != NULL) {
928                 if (unp2->unp_addr != NULL)
929                         sa = (struct sockaddr *) unp2->unp_addr;
930                 else
931                         sa = &sun_noname;
932                 bcopy(sa, *nam, sa->sa_len);
933                 UNP_PCB_UNLOCK(unp2);
934         } else {
935                 sa = &sun_noname;
936                 bcopy(sa, *nam, sa->sa_len);
937         }
938         UNP_PCB_UNLOCK(unp);
939         return (0);
940 }
941
942 static int
943 uipc_rcvd(struct socket *so, int flags)
944 {
945         struct unpcb *unp, *unp2;
946         struct socket *so2;
947         u_int mbcnt, sbcc;
948
949         unp = sotounpcb(so);
950         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
951         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
952             ("%s: socktype %d", __func__, so->so_type));
953
954         /*
955          * Adjust backpressure on sender and wakeup any waiting to write.
956          *
957          * The unp lock is acquired to maintain the validity of the unp_conn
958          * pointer; no lock on unp2 is required as unp2->unp_socket will be
959          * static as long as we don't permit unp2 to disconnect from unp,
960          * which is prevented by the lock on unp.  We cache values from
961          * so_rcv to avoid holding the so_rcv lock over the entire
962          * transaction on the remote so_snd.
963          */
964         SOCKBUF_LOCK(&so->so_rcv);
965         mbcnt = so->so_rcv.sb_mbcnt;
966         sbcc = sbavail(&so->so_rcv);
967         SOCKBUF_UNLOCK(&so->so_rcv);
968         /*
969          * There is a benign race condition at this point.  If we're planning to
970          * clear SB_STOP, but uipc_send is called on the connected socket at
971          * this instant, it might add data to the sockbuf and set SB_STOP.  Then
972          * we would erroneously clear SB_STOP below, even though the sockbuf is
973          * full.  The race is benign because the only ill effect is to allow the
974          * sockbuf to exceed its size limit, and the size limits are not
975          * strictly guaranteed anyway.
976          */
977         UNP_PCB_LOCK(unp);
978         unp2 = unp->unp_conn;
979         if (unp2 == NULL) {
980                 UNP_PCB_UNLOCK(unp);
981                 return (0);
982         }
983         so2 = unp2->unp_socket;
984         SOCKBUF_LOCK(&so2->so_snd);
985         if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
986                 so2->so_snd.sb_flags &= ~SB_STOP;
987         sowwakeup_locked(so2);
988         UNP_PCB_UNLOCK(unp);
989         return (0);
990 }
991
992 static int
993 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
994     struct mbuf *control, struct thread *td)
995 {
996         struct unpcb *unp, *unp2;
997         struct socket *so2;
998         u_int mbcnt, sbcc;
999         int error;
1000
1001         unp = sotounpcb(so);
1002         KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1003         KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1004             so->so_type == SOCK_SEQPACKET,
1005             ("%s: socktype %d", __func__, so->so_type));
1006
1007         error = 0;
1008         if (flags & PRUS_OOB) {
1009                 error = EOPNOTSUPP;
1010                 goto release;
1011         }
1012         if (control != NULL && (error = unp_internalize(&control, td)))
1013                 goto release;
1014
1015         unp2 = NULL;
1016         switch (so->so_type) {
1017         case SOCK_DGRAM:
1018         {
1019                 const struct sockaddr *from;
1020
1021                 if (nam != NULL) {
1022                         error = unp_connect(so, nam, td);
1023                         if (error != 0)
1024                                 break;
1025                 }
1026                 UNP_PCB_LOCK(unp);
1027
1028                 /*
1029                  * Because connect() and send() are non-atomic in a sendto()
1030                  * with a target address, it's possible that the socket will
1031                  * have disconnected before the send() can run.  In that case
1032                  * return the slightly counter-intuitive but otherwise
1033                  * correct error that the socket is not connected.
1034                  */
1035                 unp2 = unp_pcb_lock_peer(unp);
1036                 if (unp2 == NULL) {
1037                         UNP_PCB_UNLOCK(unp);
1038                         error = ENOTCONN;
1039                         break;
1040                 }
1041
1042                 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1043                         control = unp_addsockcred(td, control,
1044                             unp2->unp_flags);
1045                 if (unp->unp_addr != NULL)
1046                         from = (struct sockaddr *)unp->unp_addr;
1047                 else
1048                         from = &sun_noname;
1049                 so2 = unp2->unp_socket;
1050                 SOCKBUF_LOCK(&so2->so_rcv);
1051                 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1052                     control)) {
1053                         sorwakeup_locked(so2);
1054                         m = NULL;
1055                         control = NULL;
1056                 } else {
1057                         soroverflow_locked(so2);
1058                         error = ENOBUFS;
1059                 }
1060                 if (nam != NULL)
1061                         unp_disconnect(unp, unp2);
1062                 else
1063                         unp_pcb_unlock_pair(unp, unp2);
1064                 break;
1065         }
1066
1067         case SOCK_SEQPACKET:
1068         case SOCK_STREAM:
1069                 if ((so->so_state & SS_ISCONNECTED) == 0) {
1070                         if (nam != NULL) {
1071                                 error = unp_connect(so, nam, td);
1072                                 if (error != 0)
1073                                         break;
1074                         } else {
1075                                 error = ENOTCONN;
1076                                 break;
1077                         }
1078                 }
1079
1080                 UNP_PCB_LOCK(unp);
1081                 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1082                         UNP_PCB_UNLOCK(unp);
1083                         error = ENOTCONN;
1084                         break;
1085                 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1086                         unp_pcb_unlock_pair(unp, unp2);
1087                         error = EPIPE;
1088                         break;
1089                 }
1090                 UNP_PCB_UNLOCK(unp);
1091                 if ((so2 = unp2->unp_socket) == NULL) {
1092                         UNP_PCB_UNLOCK(unp2);
1093                         error = ENOTCONN;
1094                         break;
1095                 }
1096                 SOCKBUF_LOCK(&so2->so_rcv);
1097                 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1098                         /*
1099                          * Credentials are passed only once on SOCK_STREAM and
1100                          * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1101                          * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1102                          */
1103                         control = unp_addsockcred(td, control, unp2->unp_flags);
1104                         unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1105                 }
1106
1107                 /*
1108                  * Send to paired receive port and wake up readers.  Don't
1109                  * check for space available in the receive buffer if we're
1110                  * attaching ancillary data; Unix domain sockets only check
1111                  * for space in the sending sockbuf, and that check is
1112                  * performed one level up the stack.  At that level we cannot
1113                  * precisely account for the amount of buffer space used
1114                  * (e.g., because control messages are not yet internalized).
1115                  */
1116                 switch (so->so_type) {
1117                 case SOCK_STREAM:
1118                         if (control != NULL) {
1119                                 sbappendcontrol_locked(&so2->so_rcv, m,
1120                                     control, flags);
1121                                 control = NULL;
1122                         } else
1123                                 sbappend_locked(&so2->so_rcv, m, flags);
1124                         break;
1125
1126                 case SOCK_SEQPACKET:
1127                         if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1128                             &sun_noname, m, control))
1129                                 control = NULL;
1130                         break;
1131                 }
1132
1133                 mbcnt = so2->so_rcv.sb_mbcnt;
1134                 sbcc = sbavail(&so2->so_rcv);
1135                 if (sbcc)
1136                         sorwakeup_locked(so2);
1137                 else
1138                         SOCKBUF_UNLOCK(&so2->so_rcv);
1139
1140                 /*
1141                  * The PCB lock on unp2 protects the SB_STOP flag.  Without it,
1142                  * it would be possible for uipc_rcvd to be called at this
1143                  * point, drain the receiving sockbuf, clear SB_STOP, and then
1144                  * we would set SB_STOP below.  That could lead to an empty
1145                  * sockbuf having SB_STOP set
1146                  */
1147                 SOCKBUF_LOCK(&so->so_snd);
1148                 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1149                         so->so_snd.sb_flags |= SB_STOP;
1150                 SOCKBUF_UNLOCK(&so->so_snd);
1151                 UNP_PCB_UNLOCK(unp2);
1152                 m = NULL;
1153                 break;
1154         }
1155
1156         /*
1157          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1158          */
1159         if (flags & PRUS_EOF) {
1160                 UNP_PCB_LOCK(unp);
1161                 socantsendmore(so);
1162                 unp_shutdown(unp);
1163                 UNP_PCB_UNLOCK(unp);
1164         }
1165         if (control != NULL && error != 0)
1166                 unp_dispose_mbuf(control);
1167
1168 release:
1169         if (control != NULL)
1170                 m_freem(control);
1171         /*
1172          * In case of PRUS_NOTREADY, uipc_ready() is responsible
1173          * for freeing memory.
1174          */   
1175         if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1176                 m_freem(m);
1177         return (error);
1178 }
1179
1180 static bool
1181 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1182 {
1183         struct mbuf *mb, *n;
1184         struct sockbuf *sb;
1185
1186         SOCK_LOCK(so);
1187         if (SOLISTENING(so)) {
1188                 SOCK_UNLOCK(so);
1189                 return (false);
1190         }
1191         mb = NULL;
1192         sb = &so->so_rcv;
1193         SOCKBUF_LOCK(sb);
1194         if (sb->sb_fnrdy != NULL) {
1195                 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1196                         if (mb == m) {
1197                                 *errorp = sbready(sb, m, count);
1198                                 break;
1199                         }
1200                         mb = mb->m_next;
1201                         if (mb == NULL) {
1202                                 mb = n;
1203                                 if (mb != NULL)
1204                                         n = mb->m_nextpkt;
1205                         }
1206                 }
1207         }
1208         SOCKBUF_UNLOCK(sb);
1209         SOCK_UNLOCK(so);
1210         return (mb != NULL);
1211 }
1212
1213 static int
1214 uipc_ready(struct socket *so, struct mbuf *m, int count)
1215 {
1216         struct unpcb *unp, *unp2;
1217         struct socket *so2;
1218         int error, i;
1219
1220         unp = sotounpcb(so);
1221
1222         KASSERT(so->so_type == SOCK_STREAM,
1223             ("%s: unexpected socket type for %p", __func__, so));
1224
1225         UNP_PCB_LOCK(unp);
1226         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1227                 UNP_PCB_UNLOCK(unp);
1228                 so2 = unp2->unp_socket;
1229                 SOCKBUF_LOCK(&so2->so_rcv);
1230                 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1231                         sorwakeup_locked(so2);
1232                 else
1233                         SOCKBUF_UNLOCK(&so2->so_rcv);
1234                 UNP_PCB_UNLOCK(unp2);
1235                 return (error);
1236         }
1237         UNP_PCB_UNLOCK(unp);
1238
1239         /*
1240          * The receiving socket has been disconnected, but may still be valid.
1241          * In this case, the now-ready mbufs are still present in its socket
1242          * buffer, so perform an exhaustive search before giving up and freeing
1243          * the mbufs.
1244          */
1245         UNP_LINK_RLOCK();
1246         LIST_FOREACH(unp, &unp_shead, unp_link) {
1247                 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1248                         break;
1249         }
1250         UNP_LINK_RUNLOCK();
1251
1252         if (unp == NULL) {
1253                 for (i = 0; i < count; i++)
1254                         m = m_free(m);
1255                 error = ECONNRESET;
1256         }
1257         return (error);
1258 }
1259
1260 static int
1261 uipc_sense(struct socket *so, struct stat *sb)
1262 {
1263         struct unpcb *unp;
1264
1265         unp = sotounpcb(so);
1266         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1267
1268         sb->st_blksize = so->so_snd.sb_hiwat;
1269         sb->st_dev = NODEV;
1270         sb->st_ino = unp->unp_ino;
1271         return (0);
1272 }
1273
1274 static int
1275 uipc_shutdown(struct socket *so)
1276 {
1277         struct unpcb *unp;
1278
1279         unp = sotounpcb(so);
1280         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1281
1282         UNP_PCB_LOCK(unp);
1283         socantsendmore(so);
1284         unp_shutdown(unp);
1285         UNP_PCB_UNLOCK(unp);
1286         return (0);
1287 }
1288
1289 static int
1290 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1291 {
1292         struct unpcb *unp;
1293         const struct sockaddr *sa;
1294
1295         unp = sotounpcb(so);
1296         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1297
1298         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1299         UNP_PCB_LOCK(unp);
1300         if (unp->unp_addr != NULL)
1301                 sa = (struct sockaddr *) unp->unp_addr;
1302         else
1303                 sa = &sun_noname;
1304         bcopy(sa, *nam, sa->sa_len);
1305         UNP_PCB_UNLOCK(unp);
1306         return (0);
1307 }
1308
1309 static struct pr_usrreqs uipc_usrreqs_dgram = {
1310         .pru_abort =            uipc_abort,
1311         .pru_accept =           uipc_accept,
1312         .pru_attach =           uipc_attach,
1313         .pru_bind =             uipc_bind,
1314         .pru_bindat =           uipc_bindat,
1315         .pru_connect =          uipc_connect,
1316         .pru_connectat =        uipc_connectat,
1317         .pru_connect2 =         uipc_connect2,
1318         .pru_detach =           uipc_detach,
1319         .pru_disconnect =       uipc_disconnect,
1320         .pru_listen =           uipc_listen,
1321         .pru_peeraddr =         uipc_peeraddr,
1322         .pru_rcvd =             uipc_rcvd,
1323         .pru_send =             uipc_send,
1324         .pru_sense =            uipc_sense,
1325         .pru_shutdown =         uipc_shutdown,
1326         .pru_sockaddr =         uipc_sockaddr,
1327         .pru_soreceive =        soreceive_dgram,
1328         .pru_close =            uipc_close,
1329 };
1330
1331 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1332         .pru_abort =            uipc_abort,
1333         .pru_accept =           uipc_accept,
1334         .pru_attach =           uipc_attach,
1335         .pru_bind =             uipc_bind,
1336         .pru_bindat =           uipc_bindat,
1337         .pru_connect =          uipc_connect,
1338         .pru_connectat =        uipc_connectat,
1339         .pru_connect2 =         uipc_connect2,
1340         .pru_detach =           uipc_detach,
1341         .pru_disconnect =       uipc_disconnect,
1342         .pru_listen =           uipc_listen,
1343         .pru_peeraddr =         uipc_peeraddr,
1344         .pru_rcvd =             uipc_rcvd,
1345         .pru_send =             uipc_send,
1346         .pru_sense =            uipc_sense,
1347         .pru_shutdown =         uipc_shutdown,
1348         .pru_sockaddr =         uipc_sockaddr,
1349         .pru_soreceive =        soreceive_generic,      /* XXX: or...? */
1350         .pru_close =            uipc_close,
1351 };
1352
1353 static struct pr_usrreqs uipc_usrreqs_stream = {
1354         .pru_abort =            uipc_abort,
1355         .pru_accept =           uipc_accept,
1356         .pru_attach =           uipc_attach,
1357         .pru_bind =             uipc_bind,
1358         .pru_bindat =           uipc_bindat,
1359         .pru_connect =          uipc_connect,
1360         .pru_connectat =        uipc_connectat,
1361         .pru_connect2 =         uipc_connect2,
1362         .pru_detach =           uipc_detach,
1363         .pru_disconnect =       uipc_disconnect,
1364         .pru_listen =           uipc_listen,
1365         .pru_peeraddr =         uipc_peeraddr,
1366         .pru_rcvd =             uipc_rcvd,
1367         .pru_send =             uipc_send,
1368         .pru_ready =            uipc_ready,
1369         .pru_sense =            uipc_sense,
1370         .pru_shutdown =         uipc_shutdown,
1371         .pru_sockaddr =         uipc_sockaddr,
1372         .pru_soreceive =        soreceive_generic,
1373         .pru_close =            uipc_close,
1374 };
1375
1376 static int
1377 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1378 {
1379         struct unpcb *unp;
1380         struct xucred xu;
1381         int error, optval;
1382
1383         if (sopt->sopt_level != SOL_LOCAL)
1384                 return (EINVAL);
1385
1386         unp = sotounpcb(so);
1387         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1388         error = 0;
1389         switch (sopt->sopt_dir) {
1390         case SOPT_GET:
1391                 switch (sopt->sopt_name) {
1392                 case LOCAL_PEERCRED:
1393                         UNP_PCB_LOCK(unp);
1394                         if (unp->unp_flags & UNP_HAVEPC)
1395                                 xu = unp->unp_peercred;
1396                         else {
1397                                 if (so->so_type == SOCK_STREAM)
1398                                         error = ENOTCONN;
1399                                 else
1400                                         error = EINVAL;
1401                         }
1402                         UNP_PCB_UNLOCK(unp);
1403                         if (error == 0)
1404                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1405                         break;
1406
1407                 case LOCAL_CREDS:
1408                         /* Unlocked read. */
1409                         optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1410                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1411                         break;
1412
1413                 case LOCAL_CREDS_PERSISTENT:
1414                         /* Unlocked read. */
1415                         optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1416                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1417                         break;
1418
1419                 case LOCAL_CONNWAIT:
1420                         /* Unlocked read. */
1421                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1422                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1423                         break;
1424
1425                 default:
1426                         error = EOPNOTSUPP;
1427                         break;
1428                 }
1429                 break;
1430
1431         case SOPT_SET:
1432                 switch (sopt->sopt_name) {
1433                 case LOCAL_CREDS:
1434                 case LOCAL_CREDS_PERSISTENT:
1435                 case LOCAL_CONNWAIT:
1436                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1437                                             sizeof(optval));
1438                         if (error)
1439                                 break;
1440
1441 #define OPTSET(bit, exclusive) do {                                     \
1442         UNP_PCB_LOCK(unp);                                              \
1443         if (optval) {                                                   \
1444                 if ((unp->unp_flags & (exclusive)) != 0) {              \
1445                         UNP_PCB_UNLOCK(unp);                            \
1446                         error = EINVAL;                                 \
1447                         break;                                          \
1448                 }                                                       \
1449                 unp->unp_flags |= (bit);                                \
1450         } else                                                          \
1451                 unp->unp_flags &= ~(bit);                               \
1452         UNP_PCB_UNLOCK(unp);                                            \
1453 } while (0)
1454
1455                         switch (sopt->sopt_name) {
1456                         case LOCAL_CREDS:
1457                                 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1458                                 break;
1459
1460                         case LOCAL_CREDS_PERSISTENT:
1461                                 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1462                                 break;
1463
1464                         case LOCAL_CONNWAIT:
1465                                 OPTSET(UNP_CONNWAIT, 0);
1466                                 break;
1467
1468                         default:
1469                                 break;
1470                         }
1471                         break;
1472 #undef  OPTSET
1473                 default:
1474                         error = ENOPROTOOPT;
1475                         break;
1476                 }
1477                 break;
1478
1479         default:
1480                 error = EOPNOTSUPP;
1481                 break;
1482         }
1483         return (error);
1484 }
1485
1486 static int
1487 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1488 {
1489
1490         return (unp_connectat(AT_FDCWD, so, nam, td));
1491 }
1492
1493 static int
1494 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1495     struct thread *td)
1496 {
1497         struct mtx *vplock;
1498         struct sockaddr_un *soun;
1499         struct vnode *vp;
1500         struct socket *so2;
1501         struct unpcb *unp, *unp2, *unp3;
1502         struct nameidata nd;
1503         char buf[SOCK_MAXADDRLEN];
1504         struct sockaddr *sa;
1505         cap_rights_t rights;
1506         int error, len;
1507         bool connreq;
1508
1509         if (nam->sa_family != AF_UNIX)
1510                 return (EAFNOSUPPORT);
1511         if (nam->sa_len > sizeof(struct sockaddr_un))
1512                 return (EINVAL);
1513         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1514         if (len <= 0)
1515                 return (EINVAL);
1516         soun = (struct sockaddr_un *)nam;
1517         bcopy(soun->sun_path, buf, len);
1518         buf[len] = 0;
1519
1520         unp = sotounpcb(so);
1521         UNP_PCB_LOCK(unp);
1522         for (;;) {
1523                 /*
1524                  * Wait for connection state to stabilize.  If a connection
1525                  * already exists, give up.  For datagram sockets, which permit
1526                  * multiple consecutive connect(2) calls, upper layers are
1527                  * responsible for disconnecting in advance of a subsequent
1528                  * connect(2), but this is not synchronized with PCB connection
1529                  * state.
1530                  *
1531                  * Also make sure that no threads are currently attempting to
1532                  * lock the peer socket, to ensure that unp_conn cannot
1533                  * transition between two valid sockets while locks are dropped.
1534                  */
1535                 if (unp->unp_conn != NULL) {
1536                         UNP_PCB_UNLOCK(unp);
1537                         return (EISCONN);
1538                 }
1539                 if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1540                         UNP_PCB_UNLOCK(unp);
1541                         return (EALREADY);
1542                 }
1543                 if (unp->unp_pairbusy > 0) {
1544                         unp->unp_flags |= UNP_WAITING;
1545                         mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1546                         continue;
1547                 }
1548                 break;
1549         }
1550         unp->unp_flags |= UNP_CONNECTING;
1551         UNP_PCB_UNLOCK(unp);
1552
1553         connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1554         if (connreq)
1555                 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1556         else
1557                 sa = NULL;
1558         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1559             UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT),
1560             td);
1561         error = namei(&nd);
1562         if (error)
1563                 vp = NULL;
1564         else
1565                 vp = nd.ni_vp;
1566         ASSERT_VOP_LOCKED(vp, "unp_connect");
1567         NDFREE_NOTHING(&nd);
1568         if (error)
1569                 goto bad;
1570
1571         if (vp->v_type != VSOCK) {
1572                 error = ENOTSOCK;
1573                 goto bad;
1574         }
1575 #ifdef MAC
1576         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1577         if (error)
1578                 goto bad;
1579 #endif
1580         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1581         if (error)
1582                 goto bad;
1583
1584         unp = sotounpcb(so);
1585         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1586
1587         vplock = mtx_pool_find(mtxpool_sleep, vp);
1588         mtx_lock(vplock);
1589         VOP_UNP_CONNECT(vp, &unp2);
1590         if (unp2 == NULL) {
1591                 error = ECONNREFUSED;
1592                 goto bad2;
1593         }
1594         so2 = unp2->unp_socket;
1595         if (so->so_type != so2->so_type) {
1596                 error = EPROTOTYPE;
1597                 goto bad2;
1598         }
1599         if (connreq) {
1600                 if (SOLISTENING(so2)) {
1601                         CURVNET_SET(so2->so_vnet);
1602                         so2 = sonewconn(so2, 0);
1603                         CURVNET_RESTORE();
1604                 } else
1605                         so2 = NULL;
1606                 if (so2 == NULL) {
1607                         error = ECONNREFUSED;
1608                         goto bad2;
1609                 }
1610                 unp3 = sotounpcb(so2);
1611                 unp_pcb_lock_pair(unp2, unp3);
1612                 if (unp2->unp_addr != NULL) {
1613                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1614                         unp3->unp_addr = (struct sockaddr_un *) sa;
1615                         sa = NULL;
1616                 }
1617
1618                 unp_copy_peercred(td, unp3, unp, unp2);
1619
1620                 UNP_PCB_UNLOCK(unp2);
1621                 unp2 = unp3;
1622
1623                 /*
1624                  * It is safe to block on the PCB lock here since unp2 is
1625                  * nascent and cannot be connected to any other sockets.
1626                  */
1627                 UNP_PCB_LOCK(unp);
1628 #ifdef MAC
1629                 mac_socketpeer_set_from_socket(so, so2);
1630                 mac_socketpeer_set_from_socket(so2, so);
1631 #endif
1632         } else {
1633                 unp_pcb_lock_pair(unp, unp2);
1634         }
1635         KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1636             sotounpcb(so2) == unp2,
1637             ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1638         error = unp_connect2(so, so2, PRU_CONNECT);
1639         unp_pcb_unlock_pair(unp, unp2);
1640 bad2:
1641         mtx_unlock(vplock);
1642 bad:
1643         if (vp != NULL) {
1644                 vput(vp);
1645         }
1646         free(sa, M_SONAME);
1647         UNP_PCB_LOCK(unp);
1648         KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1649             ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1650         unp->unp_flags &= ~UNP_CONNECTING;
1651         UNP_PCB_UNLOCK(unp);
1652         return (error);
1653 }
1654
1655 /*
1656  * Set socket peer credentials at connection time.
1657  *
1658  * The client's PCB credentials are copied from its process structure.  The
1659  * server's PCB credentials are copied from the socket on which it called
1660  * listen(2).  uipc_listen cached that process's credentials at the time.
1661  */
1662 void
1663 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1664     struct unpcb *server_unp, struct unpcb *listen_unp)
1665 {
1666         cru2xt(td, &client_unp->unp_peercred);
1667         client_unp->unp_flags |= UNP_HAVEPC;
1668
1669         memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1670             sizeof(server_unp->unp_peercred));
1671         server_unp->unp_flags |= UNP_HAVEPC;
1672         client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
1673 }
1674
1675 static int
1676 unp_connect2(struct socket *so, struct socket *so2, int req)
1677 {
1678         struct unpcb *unp;
1679         struct unpcb *unp2;
1680
1681         unp = sotounpcb(so);
1682         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1683         unp2 = sotounpcb(so2);
1684         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1685
1686         UNP_PCB_LOCK_ASSERT(unp);
1687         UNP_PCB_LOCK_ASSERT(unp2);
1688         KASSERT(unp->unp_conn == NULL,
1689             ("%s: socket %p is already connected", __func__, unp));
1690
1691         if (so2->so_type != so->so_type)
1692                 return (EPROTOTYPE);
1693         unp->unp_conn = unp2;
1694         unp_pcb_hold(unp2);
1695         unp_pcb_hold(unp);
1696         switch (so->so_type) {
1697         case SOCK_DGRAM:
1698                 UNP_REF_LIST_LOCK();
1699                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1700                 UNP_REF_LIST_UNLOCK();
1701                 soisconnected(so);
1702                 break;
1703
1704         case SOCK_STREAM:
1705         case SOCK_SEQPACKET:
1706                 KASSERT(unp2->unp_conn == NULL,
1707                     ("%s: socket %p is already connected", __func__, unp2));
1708                 unp2->unp_conn = unp;
1709                 if (req == PRU_CONNECT &&
1710                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1711                         soisconnecting(so);
1712                 else
1713                         soisconnected(so);
1714                 soisconnected(so2);
1715                 break;
1716
1717         default:
1718                 panic("unp_connect2");
1719         }
1720         return (0);
1721 }
1722
1723 static void
1724 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1725 {
1726         struct socket *so, *so2;
1727 #ifdef INVARIANTS
1728         struct unpcb *unptmp;
1729 #endif
1730
1731         UNP_PCB_LOCK_ASSERT(unp);
1732         UNP_PCB_LOCK_ASSERT(unp2);
1733         KASSERT(unp->unp_conn == unp2,
1734             ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1735
1736         unp->unp_conn = NULL;
1737         so = unp->unp_socket;
1738         so2 = unp2->unp_socket;
1739         switch (unp->unp_socket->so_type) {
1740         case SOCK_DGRAM:
1741                 UNP_REF_LIST_LOCK();
1742 #ifdef INVARIANTS
1743                 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1744                         if (unptmp == unp)
1745                                 break;
1746                 }
1747                 KASSERT(unptmp != NULL,
1748                     ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1749 #endif
1750                 LIST_REMOVE(unp, unp_reflink);
1751                 UNP_REF_LIST_UNLOCK();
1752                 if (so) {
1753                         SOCK_LOCK(so);
1754                         so->so_state &= ~SS_ISCONNECTED;
1755                         SOCK_UNLOCK(so);
1756                 }
1757                 break;
1758
1759         case SOCK_STREAM:
1760         case SOCK_SEQPACKET:
1761                 if (so)
1762                         soisdisconnected(so);
1763                 MPASS(unp2->unp_conn == unp);
1764                 unp2->unp_conn = NULL;
1765                 if (so2)
1766                         soisdisconnected(so2);
1767                 break;
1768         }
1769
1770         if (unp == unp2) {
1771                 unp_pcb_rele_notlast(unp);
1772                 if (!unp_pcb_rele(unp))
1773                         UNP_PCB_UNLOCK(unp);
1774         } else {
1775                 if (!unp_pcb_rele(unp))
1776                         UNP_PCB_UNLOCK(unp);
1777                 if (!unp_pcb_rele(unp2))
1778                         UNP_PCB_UNLOCK(unp2);
1779         }
1780 }
1781
1782 /*
1783  * unp_pcblist() walks the global list of struct unpcb's to generate a
1784  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1785  * sequentially, validating the generation number on each to see if it has
1786  * been detached.  All of this is necessary because copyout() may sleep on
1787  * disk I/O.
1788  */
1789 static int
1790 unp_pcblist(SYSCTL_HANDLER_ARGS)
1791 {
1792         struct unpcb *unp, **unp_list;
1793         unp_gen_t gencnt;
1794         struct xunpgen *xug;
1795         struct unp_head *head;
1796         struct xunpcb *xu;
1797         u_int i;
1798         int error, n;
1799
1800         switch ((intptr_t)arg1) {
1801         case SOCK_STREAM:
1802                 head = &unp_shead;
1803                 break;
1804
1805         case SOCK_DGRAM:
1806                 head = &unp_dhead;
1807                 break;
1808
1809         case SOCK_SEQPACKET:
1810                 head = &unp_sphead;
1811                 break;
1812
1813         default:
1814                 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1815         }
1816
1817         /*
1818          * The process of preparing the PCB list is too time-consuming and
1819          * resource-intensive to repeat twice on every request.
1820          */
1821         if (req->oldptr == NULL) {
1822                 n = unp_count;
1823                 req->oldidx = 2 * (sizeof *xug)
1824                         + (n + n/8) * sizeof(struct xunpcb);
1825                 return (0);
1826         }
1827
1828         if (req->newptr != NULL)
1829                 return (EPERM);
1830
1831         /*
1832          * OK, now we're committed to doing something.
1833          */
1834         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1835         UNP_LINK_RLOCK();
1836         gencnt = unp_gencnt;
1837         n = unp_count;
1838         UNP_LINK_RUNLOCK();
1839
1840         xug->xug_len = sizeof *xug;
1841         xug->xug_count = n;
1842         xug->xug_gen = gencnt;
1843         xug->xug_sogen = so_gencnt;
1844         error = SYSCTL_OUT(req, xug, sizeof *xug);
1845         if (error) {
1846                 free(xug, M_TEMP);
1847                 return (error);
1848         }
1849
1850         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1851
1852         UNP_LINK_RLOCK();
1853         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1854              unp = LIST_NEXT(unp, unp_link)) {
1855                 UNP_PCB_LOCK(unp);
1856                 if (unp->unp_gencnt <= gencnt) {
1857                         if (cr_cansee(req->td->td_ucred,
1858                             unp->unp_socket->so_cred)) {
1859                                 UNP_PCB_UNLOCK(unp);
1860                                 continue;
1861                         }
1862                         unp_list[i++] = unp;
1863                         unp_pcb_hold(unp);
1864                 }
1865                 UNP_PCB_UNLOCK(unp);
1866         }
1867         UNP_LINK_RUNLOCK();
1868         n = i;                  /* In case we lost some during malloc. */
1869
1870         error = 0;
1871         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1872         for (i = 0; i < n; i++) {
1873                 unp = unp_list[i];
1874                 UNP_PCB_LOCK(unp);
1875                 if (unp_pcb_rele(unp))
1876                         continue;
1877
1878                 if (unp->unp_gencnt <= gencnt) {
1879                         xu->xu_len = sizeof *xu;
1880                         xu->xu_unpp = (uintptr_t)unp;
1881                         /*
1882                          * XXX - need more locking here to protect against
1883                          * connect/disconnect races for SMP.
1884                          */
1885                         if (unp->unp_addr != NULL)
1886                                 bcopy(unp->unp_addr, &xu->xu_addr,
1887                                       unp->unp_addr->sun_len);
1888                         else
1889                                 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1890                         if (unp->unp_conn != NULL &&
1891                             unp->unp_conn->unp_addr != NULL)
1892                                 bcopy(unp->unp_conn->unp_addr,
1893                                       &xu->xu_caddr,
1894                                       unp->unp_conn->unp_addr->sun_len);
1895                         else
1896                                 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1897                         xu->unp_vnode = (uintptr_t)unp->unp_vnode;
1898                         xu->unp_conn = (uintptr_t)unp->unp_conn;
1899                         xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
1900                         xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
1901                         xu->unp_gencnt = unp->unp_gencnt;
1902                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
1903                         UNP_PCB_UNLOCK(unp);
1904                         error = SYSCTL_OUT(req, xu, sizeof *xu);
1905                 } else {
1906                         UNP_PCB_UNLOCK(unp);
1907                 }
1908         }
1909         free(xu, M_TEMP);
1910         if (!error) {
1911                 /*
1912                  * Give the user an updated idea of our state.  If the
1913                  * generation differs from what we told her before, she knows
1914                  * that something happened while we were processing this
1915                  * request, and it might be necessary to retry.
1916                  */
1917                 xug->xug_gen = unp_gencnt;
1918                 xug->xug_sogen = so_gencnt;
1919                 xug->xug_count = unp_count;
1920                 error = SYSCTL_OUT(req, xug, sizeof *xug);
1921         }
1922         free(unp_list, M_TEMP);
1923         free(xug, M_TEMP);
1924         return (error);
1925 }
1926
1927 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
1928     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1929     (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1930     "List of active local datagram sockets");
1931 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
1932     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1933     (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1934     "List of active local stream sockets");
1935 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1936     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1937     (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1938     "List of active local seqpacket sockets");
1939
1940 static void
1941 unp_shutdown(struct unpcb *unp)
1942 {
1943         struct unpcb *unp2;
1944         struct socket *so;
1945
1946         UNP_PCB_LOCK_ASSERT(unp);
1947
1948         unp2 = unp->unp_conn;
1949         if ((unp->unp_socket->so_type == SOCK_STREAM ||
1950             (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1951                 so = unp2->unp_socket;
1952                 if (so != NULL)
1953                         socantrcvmore(so);
1954         }
1955 }
1956
1957 static void
1958 unp_drop(struct unpcb *unp)
1959 {
1960         struct socket *so;
1961         struct unpcb *unp2;
1962
1963         /*
1964          * Regardless of whether the socket's peer dropped the connection
1965          * with this socket by aborting or disconnecting, POSIX requires
1966          * that ECONNRESET is returned.
1967          */
1968
1969         UNP_PCB_LOCK(unp);
1970         so = unp->unp_socket;
1971         if (so)
1972                 so->so_error = ECONNRESET;
1973         if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1974                 /* Last reference dropped in unp_disconnect(). */
1975                 unp_pcb_rele_notlast(unp);
1976                 unp_disconnect(unp, unp2);
1977         } else if (!unp_pcb_rele(unp)) {
1978                 UNP_PCB_UNLOCK(unp);
1979         }
1980 }
1981
1982 static void
1983 unp_freerights(struct filedescent **fdep, int fdcount)
1984 {
1985         struct file *fp;
1986         int i;
1987
1988         KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1989
1990         for (i = 0; i < fdcount; i++) {
1991                 fp = fdep[i]->fde_file;
1992                 filecaps_free(&fdep[i]->fde_caps);
1993                 unp_discard(fp);
1994         }
1995         free(fdep[0], M_FILECAPS);
1996 }
1997
1998 static int
1999 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2000 {
2001         struct thread *td = curthread;          /* XXX */
2002         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2003         int i;
2004         int *fdp;
2005         struct filedesc *fdesc = td->td_proc->p_fd;
2006         struct filedescent **fdep;
2007         void *data;
2008         socklen_t clen = control->m_len, datalen;
2009         int error, newfds;
2010         u_int newlen;
2011
2012         UNP_LINK_UNLOCK_ASSERT();
2013
2014         error = 0;
2015         if (controlp != NULL) /* controlp == NULL => free control messages */
2016                 *controlp = NULL;
2017         while (cm != NULL) {
2018                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
2019                         error = EINVAL;
2020                         break;
2021                 }
2022                 data = CMSG_DATA(cm);
2023                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2024                 if (cm->cmsg_level == SOL_SOCKET
2025                     && cm->cmsg_type == SCM_RIGHTS) {
2026                         newfds = datalen / sizeof(*fdep);
2027                         if (newfds == 0)
2028                                 goto next;
2029                         fdep = data;
2030
2031                         /* If we're not outputting the descriptors free them. */
2032                         if (error || controlp == NULL) {
2033                                 unp_freerights(fdep, newfds);
2034                                 goto next;
2035                         }
2036                         FILEDESC_XLOCK(fdesc);
2037
2038                         /*
2039                          * Now change each pointer to an fd in the global
2040                          * table to an integer that is the index to the local
2041                          * fd table entry that we set up to point to the
2042                          * global one we are transferring.
2043                          */
2044                         newlen = newfds * sizeof(int);
2045                         *controlp = sbcreatecontrol(NULL, newlen,
2046                             SCM_RIGHTS, SOL_SOCKET);
2047                         if (*controlp == NULL) {
2048                                 FILEDESC_XUNLOCK(fdesc);
2049                                 error = E2BIG;
2050                                 unp_freerights(fdep, newfds);
2051                                 goto next;
2052                         }
2053
2054                         fdp = (int *)
2055                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2056                         if (fdallocn(td, 0, fdp, newfds) != 0) {
2057                                 FILEDESC_XUNLOCK(fdesc);
2058                                 error = EMSGSIZE;
2059                                 unp_freerights(fdep, newfds);
2060                                 m_freem(*controlp);
2061                                 *controlp = NULL;
2062                                 goto next;
2063                         }
2064                         for (i = 0; i < newfds; i++, fdp++) {
2065                                 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2066                                     (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2067                                     &fdep[i]->fde_caps);
2068                                 unp_externalize_fp(fdep[i]->fde_file);
2069                         }
2070
2071                         /*
2072                          * The new type indicates that the mbuf data refers to
2073                          * kernel resources that may need to be released before
2074                          * the mbuf is freed.
2075                          */
2076                         m_chtype(*controlp, MT_EXTCONTROL);
2077                         FILEDESC_XUNLOCK(fdesc);
2078                         free(fdep[0], M_FILECAPS);
2079                 } else {
2080                         /* We can just copy anything else across. */
2081                         if (error || controlp == NULL)
2082                                 goto next;
2083                         *controlp = sbcreatecontrol(NULL, datalen,
2084                             cm->cmsg_type, cm->cmsg_level);
2085                         if (*controlp == NULL) {
2086                                 error = ENOBUFS;
2087                                 goto next;
2088                         }
2089                         bcopy(data,
2090                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2091                             datalen);
2092                 }
2093                 controlp = &(*controlp)->m_next;
2094
2095 next:
2096                 if (CMSG_SPACE(datalen) < clen) {
2097                         clen -= CMSG_SPACE(datalen);
2098                         cm = (struct cmsghdr *)
2099                             ((caddr_t)cm + CMSG_SPACE(datalen));
2100                 } else {
2101                         clen = 0;
2102                         cm = NULL;
2103                 }
2104         }
2105
2106         m_freem(control);
2107         return (error);
2108 }
2109
2110 static void
2111 unp_zone_change(void *tag)
2112 {
2113
2114         uma_zone_set_max(unp_zone, maxsockets);
2115 }
2116
2117 #ifdef INVARIANTS
2118 static void
2119 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2120 {
2121         struct unpcb *unp;
2122
2123         unp = mem;
2124
2125         KASSERT(LIST_EMPTY(&unp->unp_refs),
2126             ("%s: unpcb %p has lingering refs", __func__, unp));
2127         KASSERT(unp->unp_socket == NULL,
2128             ("%s: unpcb %p has socket backpointer", __func__, unp));
2129         KASSERT(unp->unp_vnode == NULL,
2130             ("%s: unpcb %p has vnode references", __func__, unp));
2131         KASSERT(unp->unp_conn == NULL,
2132             ("%s: unpcb %p is still connected", __func__, unp));
2133         KASSERT(unp->unp_addr == NULL,
2134             ("%s: unpcb %p has leaked addr", __func__, unp));
2135 }
2136 #endif
2137
2138 static void
2139 unp_init(void)
2140 {
2141         uma_dtor dtor;
2142
2143 #ifdef VIMAGE
2144         if (!IS_DEFAULT_VNET(curvnet))
2145                 return;
2146 #endif
2147
2148 #ifdef INVARIANTS
2149         dtor = unp_zdtor;
2150 #else
2151         dtor = NULL;
2152 #endif
2153         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2154             NULL, NULL, UMA_ALIGN_CACHE, 0);
2155         uma_zone_set_max(unp_zone, maxsockets);
2156         uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2157         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2158             NULL, EVENTHANDLER_PRI_ANY);
2159         LIST_INIT(&unp_dhead);
2160         LIST_INIT(&unp_shead);
2161         LIST_INIT(&unp_sphead);
2162         SLIST_INIT(&unp_defers);
2163         TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2164         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2165         UNP_LINK_LOCK_INIT();
2166         UNP_DEFERRED_LOCK_INIT();
2167 }
2168
2169 static void
2170 unp_internalize_cleanup_rights(struct mbuf *control)
2171 {
2172         struct cmsghdr *cp;
2173         struct mbuf *m;
2174         void *data;
2175         socklen_t datalen;
2176
2177         for (m = control; m != NULL; m = m->m_next) {
2178                 cp = mtod(m, struct cmsghdr *);
2179                 if (cp->cmsg_level != SOL_SOCKET ||
2180                     cp->cmsg_type != SCM_RIGHTS)
2181                         continue;
2182                 data = CMSG_DATA(cp);
2183                 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2184                 unp_freerights(data, datalen / sizeof(struct filedesc *));
2185         }
2186 }
2187
2188 static int
2189 unp_internalize(struct mbuf **controlp, struct thread *td)
2190 {
2191         struct mbuf *control, **initial_controlp;
2192         struct proc *p;
2193         struct filedesc *fdesc;
2194         struct bintime *bt;
2195         struct cmsghdr *cm;
2196         struct cmsgcred *cmcred;
2197         struct filedescent *fde, **fdep, *fdev;
2198         struct file *fp;
2199         struct timeval *tv;
2200         struct timespec *ts;
2201         void *data;
2202         socklen_t clen, datalen;
2203         int i, j, error, *fdp, oldfds;
2204         u_int newlen;
2205
2206         UNP_LINK_UNLOCK_ASSERT();
2207
2208         p = td->td_proc;
2209         fdesc = p->p_fd;
2210         error = 0;
2211         control = *controlp;
2212         clen = control->m_len;
2213         *controlp = NULL;
2214         initial_controlp = controlp;
2215         for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
2216                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2217                     || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2218                         error = EINVAL;
2219                         goto out;
2220                 }
2221                 data = CMSG_DATA(cm);
2222                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2223
2224                 switch (cm->cmsg_type) {
2225                 /*
2226                  * Fill in credential information.
2227                  */
2228                 case SCM_CREDS:
2229                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2230                             SCM_CREDS, SOL_SOCKET);
2231                         if (*controlp == NULL) {
2232                                 error = ENOBUFS;
2233                                 goto out;
2234                         }
2235                         cmcred = (struct cmsgcred *)
2236                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2237                         cmcred->cmcred_pid = p->p_pid;
2238                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2239                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2240                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
2241                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2242                             CMGROUP_MAX);
2243                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
2244                                 cmcred->cmcred_groups[i] =
2245                                     td->td_ucred->cr_groups[i];
2246                         break;
2247
2248                 case SCM_RIGHTS:
2249                         oldfds = datalen / sizeof (int);
2250                         if (oldfds == 0)
2251                                 break;
2252                         /*
2253                          * Check that all the FDs passed in refer to legal
2254                          * files.  If not, reject the entire operation.
2255                          */
2256                         fdp = data;
2257                         FILEDESC_SLOCK(fdesc);
2258                         for (i = 0; i < oldfds; i++, fdp++) {
2259                                 fp = fget_locked(fdesc, *fdp);
2260                                 if (fp == NULL) {
2261                                         FILEDESC_SUNLOCK(fdesc);
2262                                         error = EBADF;
2263                                         goto out;
2264                                 }
2265                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2266                                         FILEDESC_SUNLOCK(fdesc);
2267                                         error = EOPNOTSUPP;
2268                                         goto out;
2269                                 }
2270                         }
2271
2272                         /*
2273                          * Now replace the integer FDs with pointers to the
2274                          * file structure and capability rights.
2275                          */
2276                         newlen = oldfds * sizeof(fdep[0]);
2277                         *controlp = sbcreatecontrol(NULL, newlen,
2278                             SCM_RIGHTS, SOL_SOCKET);
2279                         if (*controlp == NULL) {
2280                                 FILEDESC_SUNLOCK(fdesc);
2281                                 error = E2BIG;
2282                                 goto out;
2283                         }
2284                         fdp = data;
2285                         for (i = 0; i < oldfds; i++, fdp++) {
2286                                 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2287                                         fdp = data;
2288                                         for (j = 0; j < i; j++, fdp++) {
2289                                                 fdrop(fdesc->fd_ofiles[*fdp].
2290                                                     fde_file, td);
2291                                         }
2292                                         FILEDESC_SUNLOCK(fdesc);
2293                                         error = EBADF;
2294                                         goto out;
2295                                 }
2296                         }
2297                         fdp = data;
2298                         fdep = (struct filedescent **)
2299                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2300                         fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2301                             M_WAITOK);
2302                         for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2303                                 fde = &fdesc->fd_ofiles[*fdp];
2304                                 fdep[i] = fdev;
2305                                 fdep[i]->fde_file = fde->fde_file;
2306                                 filecaps_copy(&fde->fde_caps,
2307                                     &fdep[i]->fde_caps, true);
2308                                 unp_internalize_fp(fdep[i]->fde_file);
2309                         }
2310                         FILEDESC_SUNLOCK(fdesc);
2311                         break;
2312
2313                 case SCM_TIMESTAMP:
2314                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2315                             SCM_TIMESTAMP, SOL_SOCKET);
2316                         if (*controlp == NULL) {
2317                                 error = ENOBUFS;
2318                                 goto out;
2319                         }
2320                         tv = (struct timeval *)
2321                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2322                         microtime(tv);
2323                         break;
2324
2325                 case SCM_BINTIME:
2326                         *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2327                             SCM_BINTIME, SOL_SOCKET);
2328                         if (*controlp == NULL) {
2329                                 error = ENOBUFS;
2330                                 goto out;
2331                         }
2332                         bt = (struct bintime *)
2333                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2334                         bintime(bt);
2335                         break;
2336
2337                 case SCM_REALTIME:
2338                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2339                             SCM_REALTIME, SOL_SOCKET);
2340                         if (*controlp == NULL) {
2341                                 error = ENOBUFS;
2342                                 goto out;
2343                         }
2344                         ts = (struct timespec *)
2345                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2346                         nanotime(ts);
2347                         break;
2348
2349                 case SCM_MONOTONIC:
2350                         *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2351                             SCM_MONOTONIC, SOL_SOCKET);
2352                         if (*controlp == NULL) {
2353                                 error = ENOBUFS;
2354                                 goto out;
2355                         }
2356                         ts = (struct timespec *)
2357                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2358                         nanouptime(ts);
2359                         break;
2360
2361                 default:
2362                         error = EINVAL;
2363                         goto out;
2364                 }
2365
2366                 if (*controlp != NULL)
2367                         controlp = &(*controlp)->m_next;
2368                 if (CMSG_SPACE(datalen) < clen) {
2369                         clen -= CMSG_SPACE(datalen);
2370                         cm = (struct cmsghdr *)
2371                             ((caddr_t)cm + CMSG_SPACE(datalen));
2372                 } else {
2373                         clen = 0;
2374                         cm = NULL;
2375                 }
2376         }
2377
2378 out:
2379         if (error != 0 && initial_controlp != NULL)
2380                 unp_internalize_cleanup_rights(*initial_controlp);
2381         m_freem(control);
2382         return (error);
2383 }
2384
2385 static struct mbuf *
2386 unp_addsockcred(struct thread *td, struct mbuf *control, int mode)
2387 {
2388         struct mbuf *m, *n, *n_prev;
2389         const struct cmsghdr *cm;
2390         int ngroups, i, cmsgtype;
2391         size_t ctrlsz;
2392
2393         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2394         if (mode & UNP_WANTCRED_ALWAYS) {
2395                 ctrlsz = SOCKCRED2SIZE(ngroups);
2396                 cmsgtype = SCM_CREDS2;
2397         } else {
2398                 ctrlsz = SOCKCREDSIZE(ngroups);
2399                 cmsgtype = SCM_CREDS;
2400         }
2401
2402         m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET);
2403         if (m == NULL)
2404                 return (control);
2405
2406         if (mode & UNP_WANTCRED_ALWAYS) {
2407                 struct sockcred2 *sc;
2408
2409                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2410                 sc->sc_version = 0;
2411                 sc->sc_pid = td->td_proc->p_pid;
2412                 sc->sc_uid = td->td_ucred->cr_ruid;
2413                 sc->sc_euid = td->td_ucred->cr_uid;
2414                 sc->sc_gid = td->td_ucred->cr_rgid;
2415                 sc->sc_egid = td->td_ucred->cr_gid;
2416                 sc->sc_ngroups = ngroups;
2417                 for (i = 0; i < sc->sc_ngroups; i++)
2418                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2419         } else {
2420                 struct sockcred *sc;
2421
2422                 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2423                 sc->sc_uid = td->td_ucred->cr_ruid;
2424                 sc->sc_euid = td->td_ucred->cr_uid;
2425                 sc->sc_gid = td->td_ucred->cr_rgid;
2426                 sc->sc_egid = td->td_ucred->cr_gid;
2427                 sc->sc_ngroups = ngroups;
2428                 for (i = 0; i < sc->sc_ngroups; i++)
2429                         sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2430         }
2431
2432         /*
2433          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2434          * created SCM_CREDS control message (struct sockcred) has another
2435          * format.
2436          */
2437         if (control != NULL && cmsgtype == SCM_CREDS)
2438                 for (n = control, n_prev = NULL; n != NULL;) {
2439                         cm = mtod(n, struct cmsghdr *);
2440                         if (cm->cmsg_level == SOL_SOCKET &&
2441                             cm->cmsg_type == SCM_CREDS) {
2442                                 if (n_prev == NULL)
2443                                         control = n->m_next;
2444                                 else
2445                                         n_prev->m_next = n->m_next;
2446                                 n = m_free(n);
2447                         } else {
2448                                 n_prev = n;
2449                                 n = n->m_next;
2450                         }
2451                 }
2452
2453         /* Prepend it to the head. */
2454         m->m_next = control;
2455         return (m);
2456 }
2457
2458 static struct unpcb *
2459 fptounp(struct file *fp)
2460 {
2461         struct socket *so;
2462
2463         if (fp->f_type != DTYPE_SOCKET)
2464                 return (NULL);
2465         if ((so = fp->f_data) == NULL)
2466                 return (NULL);
2467         if (so->so_proto->pr_domain != &localdomain)
2468                 return (NULL);
2469         return sotounpcb(so);
2470 }
2471
2472 static void
2473 unp_discard(struct file *fp)
2474 {
2475         struct unp_defer *dr;
2476
2477         if (unp_externalize_fp(fp)) {
2478                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2479                 dr->ud_fp = fp;
2480                 UNP_DEFERRED_LOCK();
2481                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2482                 UNP_DEFERRED_UNLOCK();
2483                 atomic_add_int(&unp_defers_count, 1);
2484                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2485         } else
2486                 closef_nothread(fp);
2487 }
2488
2489 static void
2490 unp_process_defers(void *arg __unused, int pending)
2491 {
2492         struct unp_defer *dr;
2493         SLIST_HEAD(, unp_defer) drl;
2494         int count;
2495
2496         SLIST_INIT(&drl);
2497         for (;;) {
2498                 UNP_DEFERRED_LOCK();
2499                 if (SLIST_FIRST(&unp_defers) == NULL) {
2500                         UNP_DEFERRED_UNLOCK();
2501                         break;
2502                 }
2503                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2504                 UNP_DEFERRED_UNLOCK();
2505                 count = 0;
2506                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2507                         SLIST_REMOVE_HEAD(&drl, ud_link);
2508                         closef_nothread(dr->ud_fp);
2509                         free(dr, M_TEMP);
2510                         count++;
2511                 }
2512                 atomic_add_int(&unp_defers_count, -count);
2513         }
2514 }
2515
2516 static void
2517 unp_internalize_fp(struct file *fp)
2518 {
2519         struct unpcb *unp;
2520
2521         UNP_LINK_WLOCK();
2522         if ((unp = fptounp(fp)) != NULL) {
2523                 unp->unp_file = fp;
2524                 unp->unp_msgcount++;
2525         }
2526         unp_rights++;
2527         UNP_LINK_WUNLOCK();
2528 }
2529
2530 static int
2531 unp_externalize_fp(struct file *fp)
2532 {
2533         struct unpcb *unp;
2534         int ret;
2535
2536         UNP_LINK_WLOCK();
2537         if ((unp = fptounp(fp)) != NULL) {
2538                 unp->unp_msgcount--;
2539                 ret = 1;
2540         } else
2541                 ret = 0;
2542         unp_rights--;
2543         UNP_LINK_WUNLOCK();
2544         return (ret);
2545 }
2546
2547 /*
2548  * unp_defer indicates whether additional work has been defered for a future
2549  * pass through unp_gc().  It is thread local and does not require explicit
2550  * synchronization.
2551  */
2552 static int      unp_marked;
2553
2554 static void
2555 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2556 {
2557         struct unpcb *unp;
2558         struct file *fp;
2559         int i;
2560
2561         /*
2562          * This function can only be called from the gc task.
2563          */
2564         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2565             ("%s: not on gc callout", __func__));
2566         UNP_LINK_LOCK_ASSERT();
2567
2568         for (i = 0; i < fdcount; i++) {
2569                 fp = fdep[i]->fde_file;
2570                 if ((unp = fptounp(fp)) == NULL)
2571                         continue;
2572                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2573                         continue;
2574                 unp->unp_gcrefs--;
2575         }
2576 }
2577
2578 static void
2579 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2580 {
2581         struct unpcb *unp;
2582         struct file *fp;
2583         int i;
2584
2585         /*
2586          * This function can only be called from the gc task.
2587          */
2588         KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2589             ("%s: not on gc callout", __func__));
2590         UNP_LINK_LOCK_ASSERT();
2591
2592         for (i = 0; i < fdcount; i++) {
2593                 fp = fdep[i]->fde_file;
2594                 if ((unp = fptounp(fp)) == NULL)
2595                         continue;
2596                 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2597                         continue;
2598                 unp->unp_gcrefs++;
2599                 unp_marked++;
2600         }
2601 }
2602
2603 static void
2604 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2605 {
2606         struct socket *so, *soa;
2607
2608         so = unp->unp_socket;
2609         SOCK_LOCK(so);
2610         if (SOLISTENING(so)) {
2611                 /*
2612                  * Mark all sockets in our accept queue.
2613                  */
2614                 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2615                         if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2616                                 continue;
2617                         SOCKBUF_LOCK(&soa->so_rcv);
2618                         unp_scan(soa->so_rcv.sb_mb, op);
2619                         SOCKBUF_UNLOCK(&soa->so_rcv);
2620                 }
2621         } else {
2622                 /*
2623                  * Mark all sockets we reference with RIGHTS.
2624                  */
2625                 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2626                         SOCKBUF_LOCK(&so->so_rcv);
2627                         unp_scan(so->so_rcv.sb_mb, op);
2628                         SOCKBUF_UNLOCK(&so->so_rcv);
2629                 }
2630         }
2631         SOCK_UNLOCK(so);
2632 }
2633
2634 static int unp_recycled;
2635 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2636     "Number of unreachable sockets claimed by the garbage collector.");
2637
2638 static int unp_taskcount;
2639 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2640     "Number of times the garbage collector has run.");
2641
2642 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 
2643     "Number of active local sockets.");
2644
2645 static void
2646 unp_gc(__unused void *arg, int pending)
2647 {
2648         struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2649                                     NULL };
2650         struct unp_head **head;
2651         struct unp_head unp_deadhead;   /* List of potentially-dead sockets. */
2652         struct file *f, **unref;
2653         struct unpcb *unp, *unptmp;
2654         int i, total, unp_unreachable;
2655
2656         LIST_INIT(&unp_deadhead);
2657         unp_taskcount++;
2658         UNP_LINK_RLOCK();
2659         /*
2660          * First determine which sockets may be in cycles.
2661          */
2662         unp_unreachable = 0;
2663
2664         for (head = heads; *head != NULL; head++)
2665                 LIST_FOREACH(unp, *head, unp_link) {
2666                         KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2667                             ("%s: unp %p has unexpected gc flags 0x%x",
2668                             __func__, unp, (unsigned int)unp->unp_gcflag));
2669
2670                         f = unp->unp_file;
2671
2672                         /*
2673                          * Check for an unreachable socket potentially in a
2674                          * cycle.  It must be in a queue as indicated by
2675                          * msgcount, and this must equal the file reference
2676                          * count.  Note that when msgcount is 0 the file is
2677                          * NULL.
2678                          */
2679                         if (f != NULL && unp->unp_msgcount != 0 &&
2680                             refcount_load(&f->f_count) == unp->unp_msgcount) {
2681                                 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2682                                 unp->unp_gcflag |= UNPGC_DEAD;
2683                                 unp->unp_gcrefs = unp->unp_msgcount;
2684                                 unp_unreachable++;
2685                         }
2686                 }
2687
2688         /*
2689          * Scan all sockets previously marked as potentially being in a cycle
2690          * and remove the references each socket holds on any UNPGC_DEAD
2691          * sockets in its queue.  After this step, all remaining references on
2692          * sockets marked UNPGC_DEAD should not be part of any cycle.
2693          */
2694         LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2695                 unp_gc_scan(unp, unp_remove_dead_ref);
2696
2697         /*
2698          * If a socket still has a non-negative refcount, it cannot be in a
2699          * cycle.  In this case increment refcount of all children iteratively.
2700          * Stop the scan once we do a complete loop without discovering
2701          * a new reachable socket.
2702          */
2703         do {
2704                 unp_marked = 0;
2705                 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2706                         if (unp->unp_gcrefs > 0) {
2707                                 unp->unp_gcflag &= ~UNPGC_DEAD;
2708                                 LIST_REMOVE(unp, unp_dead);
2709                                 KASSERT(unp_unreachable > 0,
2710                                     ("%s: unp_unreachable underflow.",
2711                                     __func__));
2712                                 unp_unreachable--;
2713                                 unp_gc_scan(unp, unp_restore_undead_ref);
2714                         }
2715         } while (unp_marked);
2716
2717         UNP_LINK_RUNLOCK();
2718
2719         if (unp_unreachable == 0)
2720                 return;
2721
2722         /*
2723          * Allocate space for a local array of dead unpcbs.
2724          * TODO: can this path be simplified by instead using the local
2725          * dead list at unp_deadhead, after taking out references
2726          * on the file object and/or unpcb and dropping the link lock?
2727          */
2728         unref = malloc(unp_unreachable * sizeof(struct file *),
2729             M_TEMP, M_WAITOK);
2730
2731         /*
2732          * Iterate looking for sockets which have been specifically marked
2733          * as unreachable and store them locally.
2734          */
2735         UNP_LINK_RLOCK();
2736         total = 0;
2737         LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2738                 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2739                     ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2740                 unp->unp_gcflag &= ~UNPGC_DEAD;
2741                 f = unp->unp_file;
2742                 if (unp->unp_msgcount == 0 || f == NULL ||
2743                     refcount_load(&f->f_count) != unp->unp_msgcount ||
2744                     !fhold(f))
2745                         continue;
2746                 unref[total++] = f;
2747                 KASSERT(total <= unp_unreachable,
2748                     ("%s: incorrect unreachable count.", __func__));
2749         }
2750         UNP_LINK_RUNLOCK();
2751
2752         /*
2753          * Now flush all sockets, free'ing rights.  This will free the
2754          * struct files associated with these sockets but leave each socket
2755          * with one remaining ref.
2756          */
2757         for (i = 0; i < total; i++) {
2758                 struct socket *so;
2759
2760                 so = unref[i]->f_data;
2761                 CURVNET_SET(so->so_vnet);
2762                 sorflush(so);
2763                 CURVNET_RESTORE();
2764         }
2765
2766         /*
2767          * And finally release the sockets so they can be reclaimed.
2768          */
2769         for (i = 0; i < total; i++)
2770                 fdrop(unref[i], NULL);
2771         unp_recycled += total;
2772         free(unref, M_TEMP);
2773 }
2774
2775 static void
2776 unp_dispose_mbuf(struct mbuf *m)
2777 {
2778
2779         if (m)
2780                 unp_scan(m, unp_freerights);
2781 }
2782
2783 /*
2784  * Synchronize against unp_gc, which can trip over data as we are freeing it.
2785  */
2786 static void
2787 unp_dispose(struct socket *so)
2788 {
2789         struct unpcb *unp;
2790
2791         unp = sotounpcb(so);
2792         UNP_LINK_WLOCK();
2793         unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2794         UNP_LINK_WUNLOCK();
2795         if (!SOLISTENING(so))
2796                 unp_dispose_mbuf(so->so_rcv.sb_mb);
2797 }
2798
2799 static void
2800 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2801 {
2802         struct mbuf *m;
2803         struct cmsghdr *cm;
2804         void *data;
2805         socklen_t clen, datalen;
2806
2807         while (m0 != NULL) {
2808                 for (m = m0; m; m = m->m_next) {
2809                         if (m->m_type != MT_CONTROL)
2810                                 continue;
2811
2812                         cm = mtod(m, struct cmsghdr *);
2813                         clen = m->m_len;
2814
2815                         while (cm != NULL) {
2816                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2817                                         break;
2818
2819                                 data = CMSG_DATA(cm);
2820                                 datalen = (caddr_t)cm + cm->cmsg_len
2821                                     - (caddr_t)data;
2822
2823                                 if (cm->cmsg_level == SOL_SOCKET &&
2824                                     cm->cmsg_type == SCM_RIGHTS) {
2825                                         (*op)(data, datalen /
2826                                             sizeof(struct filedescent *));
2827                                 }
2828
2829                                 if (CMSG_SPACE(datalen) < clen) {
2830                                         clen -= CMSG_SPACE(datalen);
2831                                         cm = (struct cmsghdr *)
2832                                             ((caddr_t)cm + CMSG_SPACE(datalen));
2833                                 } else {
2834                                         clen = 0;
2835                                         cm = NULL;
2836                                 }
2837                         }
2838                 }
2839                 m0 = m0->m_nextpkt;
2840         }
2841 }
2842
2843 /*
2844  * A helper function called by VFS before socket-type vnode reclamation.
2845  * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2846  * use count.
2847  */
2848 void
2849 vfs_unp_reclaim(struct vnode *vp)
2850 {
2851         struct unpcb *unp;
2852         int active;
2853         struct mtx *vplock;
2854
2855         ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2856         KASSERT(vp->v_type == VSOCK,
2857             ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2858
2859         active = 0;
2860         vplock = mtx_pool_find(mtxpool_sleep, vp);
2861         mtx_lock(vplock);
2862         VOP_UNP_CONNECT(vp, &unp);
2863         if (unp == NULL)
2864                 goto done;
2865         UNP_PCB_LOCK(unp);
2866         if (unp->unp_vnode == vp) {
2867                 VOP_UNP_DETACH(vp);
2868                 unp->unp_vnode = NULL;
2869                 active = 1;
2870         }
2871         UNP_PCB_UNLOCK(unp);
2872  done:
2873         mtx_unlock(vplock);
2874         if (active)
2875                 vunref(vp);
2876 }
2877
2878 #ifdef DDB
2879 static void
2880 db_print_indent(int indent)
2881 {
2882         int i;
2883
2884         for (i = 0; i < indent; i++)
2885                 db_printf(" ");
2886 }
2887
2888 static void
2889 db_print_unpflags(int unp_flags)
2890 {
2891         int comma;
2892
2893         comma = 0;
2894         if (unp_flags & UNP_HAVEPC) {
2895                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2896                 comma = 1;
2897         }
2898         if (unp_flags & UNP_WANTCRED_ALWAYS) {
2899                 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
2900                 comma = 1;
2901         }
2902         if (unp_flags & UNP_WANTCRED_ONESHOT) {
2903                 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
2904                 comma = 1;
2905         }
2906         if (unp_flags & UNP_CONNWAIT) {
2907                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2908                 comma = 1;
2909         }
2910         if (unp_flags & UNP_CONNECTING) {
2911                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2912                 comma = 1;
2913         }
2914         if (unp_flags & UNP_BINDING) {
2915                 db_printf("%sUNP_BINDING", comma ? ", " : "");
2916                 comma = 1;
2917         }
2918 }
2919
2920 static void
2921 db_print_xucred(int indent, struct xucred *xu)
2922 {
2923         int comma, i;
2924
2925         db_print_indent(indent);
2926         db_printf("cr_version: %u   cr_uid: %u   cr_pid: %d   cr_ngroups: %d\n",
2927             xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
2928         db_print_indent(indent);
2929         db_printf("cr_groups: ");
2930         comma = 0;
2931         for (i = 0; i < xu->cr_ngroups; i++) {
2932                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2933                 comma = 1;
2934         }
2935         db_printf("\n");
2936 }
2937
2938 static void
2939 db_print_unprefs(int indent, struct unp_head *uh)
2940 {
2941         struct unpcb *unp;
2942         int counter;
2943
2944         counter = 0;
2945         LIST_FOREACH(unp, uh, unp_reflink) {
2946                 if (counter % 4 == 0)
2947                         db_print_indent(indent);
2948                 db_printf("%p  ", unp);
2949                 if (counter % 4 == 3)
2950                         db_printf("\n");
2951                 counter++;
2952         }
2953         if (counter != 0 && counter % 4 != 0)
2954                 db_printf("\n");
2955 }
2956
2957 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2958 {
2959         struct unpcb *unp;
2960
2961         if (!have_addr) {
2962                 db_printf("usage: show unpcb <addr>\n");
2963                 return;
2964         }
2965         unp = (struct unpcb *)addr;
2966
2967         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2968             unp->unp_vnode);
2969
2970         db_printf("unp_ino: %ju   unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2971             unp->unp_conn);
2972
2973         db_printf("unp_refs:\n");
2974         db_print_unprefs(2, &unp->unp_refs);
2975
2976         /* XXXRW: Would be nice to print the full address, if any. */
2977         db_printf("unp_addr: %p\n", unp->unp_addr);
2978
2979         db_printf("unp_gencnt: %llu\n",
2980             (unsigned long long)unp->unp_gencnt);
2981
2982         db_printf("unp_flags: %x (", unp->unp_flags);
2983         db_print_unpflags(unp->unp_flags);
2984         db_printf(")\n");
2985
2986         db_printf("unp_peercred:\n");
2987         db_print_xucred(2, &unp->unp_peercred);
2988
2989         db_printf("unp_refcount: %u\n", unp->unp_refcount);
2990 }
2991 #endif