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