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