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