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