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