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