]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/uipc_usrreq.c
MFC r231976:
[FreeBSD/stable/8.git] / sys / kern / uipc_usrreq.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.
4  * Copyright (c) 2004-2009 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
32  */
33
34 /*
35  * UNIX Domain (Local) Sockets
36  *
37  * This is an implementation of UNIX (local) domain sockets.  Each socket has
38  * an associated struct unpcb (UNIX protocol control block).  Stream sockets
39  * may be connected to 0 or 1 other socket.  Datagram sockets may be
40  * connected to 0, 1, or many other sockets.  Sockets may be created and
41  * connected in pairs (socketpair(2)), or bound/connected to using the file
42  * system name space.  For most purposes, only the receive socket buffer is
43  * used, as sending on one socket delivers directly to the receive socket
44  * buffer of a second socket.
45  *
46  * The implementation is substantially complicated by the fact that
47  * "ancillary data", such as file descriptors or credentials, may be passed
48  * across UNIX domain sockets.  The potential for passing UNIX domain sockets
49  * over other UNIX domain sockets requires the implementation of a simple
50  * garbage collector to find and tear down cycles of disconnected sockets.
51  *
52  * TODO:
53  *      SEQPACKET, RDM
54  *      rethink name space problems
55  *      need a proper out-of-band
56  */
57
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
60
61 #include "opt_ddb.h"
62
63 #include <sys/param.h>
64 #include <sys/domain.h>
65 #include <sys/fcntl.h>
66 #include <sys/malloc.h>         /* XXX must be before <sys/file.h> */
67 #include <sys/eventhandler.h>
68 #include <sys/file.h>
69 #include <sys/filedesc.h>
70 #include <sys/kernel.h>
71 #include <sys/lock.h>
72 #include <sys/mbuf.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
76 #include <sys/proc.h>
77 #include <sys/protosw.h>
78 #include <sys/queue.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
84 #include <sys/stat.h>
85 #include <sys/sx.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/taskqueue.h>
89 #include <sys/un.h>
90 #include <sys/unpcb.h>
91 #include <sys/vnode.h>
92
93 #include <net/vnet.h>
94
95 #ifdef DDB
96 #include <ddb/ddb.h>
97 #endif
98
99 #include <security/mac/mac_framework.h>
100
101 #include <vm/uma.h>
102
103 /*
104  * Locking key:
105  * (l)  Locked using list lock
106  * (g)  Locked using linkage lock
107  */
108
109 static uma_zone_t       unp_zone;
110 static unp_gen_t        unp_gencnt;     /* (l) */
111 static u_int            unp_count;      /* (l) Count of local sockets. */
112 static ino_t            unp_ino;        /* Prototype for fake inode numbers. */
113 static int              unp_rights;     /* (g) File descriptors in flight. */
114 static struct unp_head  unp_shead;      /* (l) List of stream sockets. */
115 static struct unp_head  unp_dhead;      /* (l) List of datagram sockets. */
116
117 struct unp_defer {
118         SLIST_ENTRY(unp_defer) ud_link;
119         struct file *ud_fp;
120 };
121 static SLIST_HEAD(, unp_defer) unp_defers;
122 static int unp_defers_count;
123
124 static const struct sockaddr    sun_noname = { sizeof(sun_noname), AF_LOCAL };
125
126 /*
127  * Garbage collection of cyclic file descriptor/socket references occurs
128  * asynchronously in a taskqueue context in order to avoid recursion and
129  * reentrance in the UNIX domain socket, file descriptor, and socket layer
130  * code.  See unp_gc() for a full description.
131  */
132 static struct task      unp_gc_task;
133
134 /*
135  * The close of unix domain sockets attached as SCM_RIGHTS is
136  * postponed to the taskqueue, to avoid arbitrary recursion depth.
137  * The attached sockets might have another sockets attached.
138  */
139 static struct task      unp_defer_task;
140
141 /*
142  * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
143  * stream sockets, although the total for sender and receiver is actually
144  * only PIPSIZ.
145  *
146  * Datagram sockets really use the sendspace as the maximum datagram size,
147  * and don't really want to reserve the sendspace.  Their recvspace should be
148  * large enough for at least one max-size datagram plus address.
149  */
150 #ifndef PIPSIZ
151 #define PIPSIZ  8192
152 #endif
153 static u_long   unpst_sendspace = PIPSIZ;
154 static u_long   unpst_recvspace = PIPSIZ;
155 static u_long   unpdg_sendspace = 2*1024;       /* really max datagram size */
156 static u_long   unpdg_recvspace = 4*1024;
157
158 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
159 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
160 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
161
162 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
163            &unpst_sendspace, 0, "Default stream send space.");
164 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
165            &unpst_recvspace, 0, "Default stream receive space.");
166 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
167            &unpdg_sendspace, 0, "Default datagram send space.");
168 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
169            &unpdg_recvspace, 0, "Default datagram receive space.");
170 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
171     "File descriptors in flight.");
172 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
173     &unp_defers_count, 0,
174     "File descriptors deferred to taskqueue for close.");
175
176 /*-
177  * Locking and synchronization:
178  *
179  * Three types of locks exit in the local domain socket implementation: a
180  * global list mutex, a global linkage rwlock, and per-unpcb mutexes.  Of the
181  * global locks, the list lock protects the socket count, global generation
182  * number, and stream/datagram global lists.  The linkage lock protects the
183  * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
184  * held exclusively over the acquisition of multiple unpcb locks to prevent
185  * deadlock.
186  *
187  * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
188  * allocated in pru_attach() and freed in pru_detach().  The validity of that
189  * pointer is an invariant, so no lock is required to dereference the so_pcb
190  * pointer if a valid socket reference is held by the caller.  In practice,
191  * this is always true during operations performed on a socket.  Each unpcb
192  * has a back-pointer to its socket, unp_socket, which will be stable under
193  * the same circumstances.
194  *
195  * This pointer may only be safely dereferenced as long as a valid reference
196  * to the unpcb is held.  Typically, this reference will be from the socket,
197  * or from another unpcb when the referring unpcb's lock is held (in order
198  * that the reference not be invalidated during use).  For example, to follow
199  * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
200  * as unp_socket remains valid as long as the reference to unp_conn is valid.
201  *
202  * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx.  Individual
203  * atomic reads without the lock may be performed "lockless", but more
204  * complex reads and read-modify-writes require the mutex to be held.  No
205  * lock order is defined between unpcb locks -- multiple unpcb locks may be
206  * acquired at the same time only when holding the linkage rwlock
207  * exclusively, which prevents deadlocks.
208  *
209  * Blocking with UNIX domain sockets is a tricky issue: unlike most network
210  * protocols, bind() is a non-atomic operation, and connect() requires
211  * potential sleeping in the protocol, due to potentially waiting on local or
212  * distributed file systems.  We try to separate "lookup" operations, which
213  * may sleep, and the IPC operations themselves, which typically can occur
214  * with relative atomicity as locks can be held over the entire operation.
215  *
216  * Another tricky issue is simultaneous multi-threaded or multi-process
217  * access to a single UNIX domain socket.  These are handled by the flags
218  * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
219  * binding, both of which involve dropping UNIX domain socket locks in order
220  * to perform namei() and other file system operations.
221  */
222 static struct rwlock    unp_link_rwlock;
223 static struct mtx       unp_list_lock;
224 static struct mtx       unp_defers_lock;
225
226 #define UNP_LINK_LOCK_INIT()            rw_init(&unp_link_rwlock,       \
227                                             "unp_link_rwlock")
228
229 #define UNP_LINK_LOCK_ASSERT()  rw_assert(&unp_link_rwlock,     \
230                                             RA_LOCKED)
231 #define UNP_LINK_UNLOCK_ASSERT()        rw_assert(&unp_link_rwlock,     \
232                                             RA_UNLOCKED)
233
234 #define UNP_LINK_RLOCK()                rw_rlock(&unp_link_rwlock)
235 #define UNP_LINK_RUNLOCK()              rw_runlock(&unp_link_rwlock)
236 #define UNP_LINK_WLOCK()                rw_wlock(&unp_link_rwlock)
237 #define UNP_LINK_WUNLOCK()              rw_wunlock(&unp_link_rwlock)
238 #define UNP_LINK_WLOCK_ASSERT()         rw_assert(&unp_link_rwlock,     \
239                                             RA_WLOCKED)
240
241 #define UNP_LIST_LOCK_INIT()            mtx_init(&unp_list_lock,        \
242                                             "unp_list_lock", NULL, MTX_DEF)
243 #define UNP_LIST_LOCK()                 mtx_lock(&unp_list_lock)
244 #define UNP_LIST_UNLOCK()               mtx_unlock(&unp_list_lock)
245
246 #define UNP_DEFERRED_LOCK_INIT()        mtx_init(&unp_defers_lock, \
247                                             "unp_defer", NULL, MTX_DEF)
248 #define UNP_DEFERRED_LOCK()             mtx_lock(&unp_defers_lock)
249 #define UNP_DEFERRED_UNLOCK()           mtx_unlock(&unp_defers_lock)
250
251 #define UNP_PCB_LOCK_INIT(unp)          mtx_init(&(unp)->unp_mtx,       \
252                                             "unp_mtx", "unp_mtx",       \
253                                             MTX_DUPOK|MTX_DEF|MTX_RECURSE)
254 #define UNP_PCB_LOCK_DESTROY(unp)       mtx_destroy(&(unp)->unp_mtx)
255 #define UNP_PCB_LOCK(unp)               mtx_lock(&(unp)->unp_mtx)
256 #define UNP_PCB_UNLOCK(unp)             mtx_unlock(&(unp)->unp_mtx)
257 #define UNP_PCB_LOCK_ASSERT(unp)        mtx_assert(&(unp)->unp_mtx, MA_OWNED)
258
259 static int      uipc_connect2(struct socket *, struct socket *);
260 static int      uipc_ctloutput(struct socket *, struct sockopt *);
261 static int      unp_connect(struct socket *, struct sockaddr *,
262                     struct thread *);
263 static int      unp_connect2(struct socket *so, struct socket *so2, int);
264 static void     unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
265 static void     unp_dispose(struct mbuf *);
266 static void     unp_shutdown(struct unpcb *);
267 static void     unp_drop(struct unpcb *, int);
268 static void     unp_gc(__unused void *, int);
269 static void     unp_scan(struct mbuf *, void (*)(struct file *));
270 static void     unp_discard(struct file *);
271 static void     unp_freerights(struct file **, int);
272 static void     unp_init(void);
273 static int      unp_internalize(struct mbuf **, struct thread *);
274 static void     unp_internalize_fp(struct file *);
275 static int      unp_externalize(struct mbuf *, struct mbuf **);
276 static int      unp_externalize_fp(struct file *);
277 static struct mbuf      *unp_addsockcred(struct thread *, struct mbuf *);
278 static void     unp_process_defers(void * __unused, int);
279
280 /*
281  * Definitions of protocols supported in the LOCAL domain.
282  */
283 static struct domain localdomain;
284 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
285 static struct protosw localsw[] = {
286 {
287         .pr_type =              SOCK_STREAM,
288         .pr_domain =            &localdomain,
289         .pr_flags =             PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
290         .pr_ctloutput =         &uipc_ctloutput,
291         .pr_usrreqs =           &uipc_usrreqs_stream
292 },
293 {
294         .pr_type =              SOCK_DGRAM,
295         .pr_domain =            &localdomain,
296         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_RIGHTS,
297         .pr_usrreqs =           &uipc_usrreqs_dgram
298 },
299 };
300
301 static struct domain localdomain = {
302         .dom_family =           AF_LOCAL,
303         .dom_name =             "local",
304         .dom_init =             unp_init,
305         .dom_externalize =      unp_externalize,
306         .dom_dispose =          unp_dispose,
307         .dom_protosw =          localsw,
308         .dom_protoswNPROTOSW =  &localsw[sizeof(localsw)/sizeof(localsw[0])]
309 };
310 DOMAIN_SET(local);
311
312 static void
313 uipc_abort(struct socket *so)
314 {
315         struct unpcb *unp, *unp2;
316
317         unp = sotounpcb(so);
318         KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
319
320         UNP_LINK_WLOCK();
321         UNP_PCB_LOCK(unp);
322         unp2 = unp->unp_conn;
323         if (unp2 != NULL) {
324                 UNP_PCB_LOCK(unp2);
325                 unp_drop(unp2, ECONNABORTED);
326                 UNP_PCB_UNLOCK(unp2);
327         }
328         UNP_PCB_UNLOCK(unp);
329         UNP_LINK_WUNLOCK();
330 }
331
332 static int
333 uipc_accept(struct socket *so, struct sockaddr **nam)
334 {
335         struct unpcb *unp, *unp2;
336         const struct sockaddr *sa;
337
338         /*
339          * Pass back name of connected socket, if it was bound and we are
340          * still connected (our peer may have closed already!).
341          */
342         unp = sotounpcb(so);
343         KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
344
345         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
346         UNP_LINK_RLOCK();
347         unp2 = unp->unp_conn;
348         if (unp2 != NULL && unp2->unp_addr != NULL) {
349                 UNP_PCB_LOCK(unp2);
350                 sa = (struct sockaddr *) unp2->unp_addr;
351                 bcopy(sa, *nam, sa->sa_len);
352                 UNP_PCB_UNLOCK(unp2);
353         } else {
354                 sa = &sun_noname;
355                 bcopy(sa, *nam, sa->sa_len);
356         }
357         UNP_LINK_RUNLOCK();
358         return (0);
359 }
360
361 static int
362 uipc_attach(struct socket *so, int proto, struct thread *td)
363 {
364         u_long sendspace, recvspace;
365         struct unpcb *unp;
366         int error;
367
368         KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
369         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
370                 switch (so->so_type) {
371                 case SOCK_STREAM:
372                         sendspace = unpst_sendspace;
373                         recvspace = unpst_recvspace;
374                         break;
375
376                 case SOCK_DGRAM:
377                         sendspace = unpdg_sendspace;
378                         recvspace = unpdg_recvspace;
379                         break;
380
381                 default:
382                         panic("uipc_attach");
383                 }
384                 error = soreserve(so, sendspace, recvspace);
385                 if (error)
386                         return (error);
387         }
388         unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
389         if (unp == NULL)
390                 return (ENOBUFS);
391         LIST_INIT(&unp->unp_refs);
392         UNP_PCB_LOCK_INIT(unp);
393         unp->unp_socket = so;
394         so->so_pcb = unp;
395         unp->unp_refcount = 1;
396
397         UNP_LIST_LOCK();
398         unp->unp_gencnt = ++unp_gencnt;
399         unp_count++;
400         LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
401             unp, unp_link);
402         UNP_LIST_UNLOCK();
403
404         return (0);
405 }
406
407 static int
408 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
409 {
410         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
411         struct vattr vattr;
412         int error, namelen, vfslocked;
413         struct nameidata nd;
414         struct unpcb *unp;
415         struct vnode *vp;
416         struct mount *mp;
417         char *buf;
418
419         unp = sotounpcb(so);
420         KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
421
422         if (soun->sun_len > sizeof(struct sockaddr_un))
423                 return (EINVAL);
424         namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
425         if (namelen <= 0)
426                 return (EINVAL);
427
428         /*
429          * We don't allow simultaneous bind() calls on a single UNIX domain
430          * socket, so flag in-progress operations, and return an error if an
431          * operation is already in progress.
432          *
433          * Historically, we have not allowed a socket to be rebound, so this
434          * also returns an error.  Not allowing re-binding simplifies the
435          * implementation and avoids a great many possible failure modes.
436          */
437         UNP_PCB_LOCK(unp);
438         if (unp->unp_vnode != NULL) {
439                 UNP_PCB_UNLOCK(unp);
440                 return (EINVAL);
441         }
442         if (unp->unp_flags & UNP_BINDING) {
443                 UNP_PCB_UNLOCK(unp);
444                 return (EALREADY);
445         }
446         unp->unp_flags |= UNP_BINDING;
447         UNP_PCB_UNLOCK(unp);
448
449         buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
450         bcopy(soun->sun_path, buf, namelen);
451         buf[namelen] = 0;
452
453 restart:
454         vfslocked = 0;
455         NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
456             UIO_SYSSPACE, buf, td);
457 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
458         error = namei(&nd);
459         if (error)
460                 goto error;
461         vp = nd.ni_vp;
462         vfslocked = NDHASGIANT(&nd);
463         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
464                 NDFREE(&nd, NDF_ONLY_PNBUF);
465                 if (nd.ni_dvp == vp)
466                         vrele(nd.ni_dvp);
467                 else
468                         vput(nd.ni_dvp);
469                 if (vp != NULL) {
470                         vrele(vp);
471                         error = EADDRINUSE;
472                         goto error;
473                 }
474                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
475                 if (error)
476                         goto error;
477                 VFS_UNLOCK_GIANT(vfslocked);
478                 goto restart;
479         }
480         VATTR_NULL(&vattr);
481         vattr.va_type = VSOCK;
482         vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
483 #ifdef MAC
484         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
485             &vattr);
486 #endif
487         if (error == 0)
488                 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
489         NDFREE(&nd, NDF_ONLY_PNBUF);
490         vput(nd.ni_dvp);
491         if (error) {
492                 vn_finished_write(mp);
493                 goto error;
494         }
495         vp = nd.ni_vp;
496         ASSERT_VOP_ELOCKED(vp, "uipc_bind");
497         soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
498
499         UNP_LINK_WLOCK();
500         UNP_PCB_LOCK(unp);
501         vp->v_socket = unp->unp_socket;
502         unp->unp_vnode = vp;
503         unp->unp_addr = soun;
504         unp->unp_flags &= ~UNP_BINDING;
505         UNP_PCB_UNLOCK(unp);
506         UNP_LINK_WUNLOCK();
507         VOP_UNLOCK(vp, 0);
508         vn_finished_write(mp);
509         VFS_UNLOCK_GIANT(vfslocked);
510         free(buf, M_TEMP);
511         return (0);
512
513 error:
514         VFS_UNLOCK_GIANT(vfslocked);
515         UNP_PCB_LOCK(unp);
516         unp->unp_flags &= ~UNP_BINDING;
517         UNP_PCB_UNLOCK(unp);
518         free(buf, M_TEMP);
519         return (error);
520 }
521
522 static int
523 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
524 {
525         int error;
526
527         KASSERT(td == curthread, ("uipc_connect: td != curthread"));
528         UNP_LINK_WLOCK();
529         error = unp_connect(so, nam, td);
530         UNP_LINK_WUNLOCK();
531         return (error);
532 }
533
534 static void
535 uipc_close(struct socket *so)
536 {
537         struct unpcb *unp, *unp2;
538
539         unp = sotounpcb(so);
540         KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
541
542         UNP_LINK_WLOCK();
543         UNP_PCB_LOCK(unp);
544         unp2 = unp->unp_conn;
545         if (unp2 != NULL) {
546                 UNP_PCB_LOCK(unp2);
547                 unp_disconnect(unp, unp2);
548                 UNP_PCB_UNLOCK(unp2);
549         }
550         UNP_PCB_UNLOCK(unp);
551         UNP_LINK_WUNLOCK();
552 }
553
554 static int
555 uipc_connect2(struct socket *so1, struct socket *so2)
556 {
557         struct unpcb *unp, *unp2;
558         int error;
559
560         UNP_LINK_WLOCK();
561         unp = so1->so_pcb;
562         KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
563         UNP_PCB_LOCK(unp);
564         unp2 = so2->so_pcb;
565         KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
566         UNP_PCB_LOCK(unp2);
567         error = unp_connect2(so1, so2, PRU_CONNECT2);
568         UNP_PCB_UNLOCK(unp2);
569         UNP_PCB_UNLOCK(unp);
570         UNP_LINK_WUNLOCK();
571         return (error);
572 }
573
574 static void
575 uipc_detach(struct socket *so)
576 {
577         struct unpcb *unp, *unp2;
578         struct sockaddr_un *saved_unp_addr;
579         struct vnode *vp;
580         int freeunp, local_unp_rights;
581
582         unp = sotounpcb(so);
583         KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
584
585         UNP_LINK_WLOCK();
586         UNP_LIST_LOCK();
587         UNP_PCB_LOCK(unp);
588         LIST_REMOVE(unp, unp_link);
589         unp->unp_gencnt = ++unp_gencnt;
590         --unp_count;
591         UNP_LIST_UNLOCK();
592
593         /*
594          * XXXRW: Should assert vp->v_socket == so.
595          */
596         if ((vp = unp->unp_vnode) != NULL) {
597                 unp->unp_vnode->v_socket = NULL;
598                 unp->unp_vnode = NULL;
599         }
600         unp2 = unp->unp_conn;
601         if (unp2 != NULL) {
602                 UNP_PCB_LOCK(unp2);
603                 unp_disconnect(unp, unp2);
604                 UNP_PCB_UNLOCK(unp2);
605         }
606
607         /*
608          * We hold the linkage lock exclusively, so it's OK to acquire
609          * multiple pcb locks at a time.
610          */
611         while (!LIST_EMPTY(&unp->unp_refs)) {
612                 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
613
614                 UNP_PCB_LOCK(ref);
615                 unp_drop(ref, ECONNRESET);
616                 UNP_PCB_UNLOCK(ref);
617         }
618         local_unp_rights = unp_rights;
619         UNP_LINK_WUNLOCK();
620         unp->unp_socket->so_pcb = NULL;
621         saved_unp_addr = unp->unp_addr;
622         unp->unp_addr = NULL;
623         unp->unp_refcount--;
624         freeunp = (unp->unp_refcount == 0);
625         if (saved_unp_addr != NULL)
626                 free(saved_unp_addr, M_SONAME);
627         if (freeunp) {
628                 UNP_PCB_LOCK_DESTROY(unp);
629                 uma_zfree(unp_zone, unp);
630         } else
631                 UNP_PCB_UNLOCK(unp);
632         if (vp) {
633                 int vfslocked;
634
635                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
636                 vrele(vp);
637                 VFS_UNLOCK_GIANT(vfslocked);
638         }
639         if (local_unp_rights)
640                 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
641 }
642
643 static int
644 uipc_disconnect(struct socket *so)
645 {
646         struct unpcb *unp, *unp2;
647
648         unp = sotounpcb(so);
649         KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
650
651         UNP_LINK_WLOCK();
652         UNP_PCB_LOCK(unp);
653         unp2 = unp->unp_conn;
654         if (unp2 != NULL) {
655                 UNP_PCB_LOCK(unp2);
656                 unp_disconnect(unp, unp2);
657                 UNP_PCB_UNLOCK(unp2);
658         }
659         UNP_PCB_UNLOCK(unp);
660         UNP_LINK_WUNLOCK();
661         return (0);
662 }
663
664 static int
665 uipc_listen(struct socket *so, int backlog, struct thread *td)
666 {
667         struct unpcb *unp;
668         int error;
669
670         unp = sotounpcb(so);
671         KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
672
673         UNP_PCB_LOCK(unp);
674         if (unp->unp_vnode == NULL) {
675                 UNP_PCB_UNLOCK(unp);
676                 return (EINVAL);
677         }
678
679         SOCK_LOCK(so);
680         error = solisten_proto_check(so);
681         if (error == 0) {
682                 cru2x(td->td_ucred, &unp->unp_peercred);
683                 unp->unp_flags |= UNP_HAVEPCCACHED;
684                 solisten_proto(so, backlog);
685         }
686         SOCK_UNLOCK(so);
687         UNP_PCB_UNLOCK(unp);
688         return (error);
689 }
690
691 static int
692 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
693 {
694         struct unpcb *unp, *unp2;
695         const struct sockaddr *sa;
696
697         unp = sotounpcb(so);
698         KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
699
700         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
701         UNP_LINK_RLOCK();
702         /*
703          * XXX: It seems that this test always fails even when connection is
704          * established.  So, this else clause is added as workaround to
705          * return PF_LOCAL sockaddr.
706          */
707         unp2 = unp->unp_conn;
708         if (unp2 != NULL) {
709                 UNP_PCB_LOCK(unp2);
710                 if (unp2->unp_addr != NULL)
711                         sa = (struct sockaddr *) unp2->unp_addr;
712                 else
713                         sa = &sun_noname;
714                 bcopy(sa, *nam, sa->sa_len);
715                 UNP_PCB_UNLOCK(unp2);
716         } else {
717                 sa = &sun_noname;
718                 bcopy(sa, *nam, sa->sa_len);
719         }
720         UNP_LINK_RUNLOCK();
721         return (0);
722 }
723
724 static int
725 uipc_rcvd(struct socket *so, int flags)
726 {
727         struct unpcb *unp, *unp2;
728         struct socket *so2;
729         u_int mbcnt, sbcc;
730         u_long newhiwat;
731
732         unp = sotounpcb(so);
733         KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
734
735         if (so->so_type == SOCK_DGRAM)
736                 panic("uipc_rcvd DGRAM?");
737
738         if (so->so_type != SOCK_STREAM)
739                 panic("uipc_rcvd unknown socktype");
740
741         /*
742          * Adjust backpressure on sender and wakeup any waiting to write.
743          *
744          * The unp lock is acquired to maintain the validity of the unp_conn
745          * pointer; no lock on unp2 is required as unp2->unp_socket will be
746          * static as long as we don't permit unp2 to disconnect from unp,
747          * which is prevented by the lock on unp.  We cache values from
748          * so_rcv to avoid holding the so_rcv lock over the entire
749          * transaction on the remote so_snd.
750          */
751         SOCKBUF_LOCK(&so->so_rcv);
752         mbcnt = so->so_rcv.sb_mbcnt;
753         sbcc = so->so_rcv.sb_cc;
754         SOCKBUF_UNLOCK(&so->so_rcv);
755         UNP_PCB_LOCK(unp);
756         unp2 = unp->unp_conn;
757         if (unp2 == NULL) {
758                 UNP_PCB_UNLOCK(unp);
759                 return (0);
760         }
761         so2 = unp2->unp_socket;
762         SOCKBUF_LOCK(&so2->so_snd);
763         so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
764         newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
765         (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
766             newhiwat, RLIM_INFINITY);
767         sowwakeup_locked(so2);
768         unp->unp_mbcnt = mbcnt;
769         unp->unp_cc = sbcc;
770         UNP_PCB_UNLOCK(unp);
771         return (0);
772 }
773
774 static int
775 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
776     struct mbuf *control, struct thread *td)
777 {
778         struct unpcb *unp, *unp2;
779         struct socket *so2;
780         u_int mbcnt_delta, sbcc;
781         u_int newhiwat;
782         int error = 0;
783
784         unp = sotounpcb(so);
785         KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
786
787         if (flags & PRUS_OOB) {
788                 error = EOPNOTSUPP;
789                 goto release;
790         }
791         if (control != NULL && (error = unp_internalize(&control, td)))
792                 goto release;
793         if ((nam != NULL) || (flags & PRUS_EOF))
794                 UNP_LINK_WLOCK();
795         else
796                 UNP_LINK_RLOCK();
797         switch (so->so_type) {
798         case SOCK_DGRAM:
799         {
800                 const struct sockaddr *from;
801
802                 unp2 = unp->unp_conn;
803                 if (nam != NULL) {
804                         UNP_LINK_WLOCK_ASSERT();
805                         if (unp2 != NULL) {
806                                 error = EISCONN;
807                                 break;
808                         }
809                         error = unp_connect(so, nam, td);
810                         if (error)
811                                 break;
812                         unp2 = unp->unp_conn;
813                 }
814
815                 /*
816                  * Because connect() and send() are non-atomic in a sendto()
817                  * with a target address, it's possible that the socket will
818                  * have disconnected before the send() can run.  In that case
819                  * return the slightly counter-intuitive but otherwise
820                  * correct error that the socket is not connected.
821                  */
822                 if (unp2 == NULL) {
823                         error = ENOTCONN;
824                         break;
825                 }
826                 /* Lockless read. */
827                 if (unp2->unp_flags & UNP_WANTCRED)
828                         control = unp_addsockcred(td, control);
829                 UNP_PCB_LOCK(unp);
830                 if (unp->unp_addr != NULL)
831                         from = (struct sockaddr *)unp->unp_addr;
832                 else
833                         from = &sun_noname;
834                 so2 = unp2->unp_socket;
835                 SOCKBUF_LOCK(&so2->so_rcv);
836                 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
837                         sorwakeup_locked(so2);
838                         m = NULL;
839                         control = NULL;
840                 } else {
841                         SOCKBUF_UNLOCK(&so2->so_rcv);
842                         error = ENOBUFS;
843                 }
844                 if (nam != NULL) {
845                         UNP_LINK_WLOCK_ASSERT();
846                         UNP_PCB_LOCK(unp2);
847                         unp_disconnect(unp, unp2);
848                         UNP_PCB_UNLOCK(unp2);
849                 }
850                 UNP_PCB_UNLOCK(unp);
851                 break;
852         }
853
854         case SOCK_STREAM:
855                 if ((so->so_state & SS_ISCONNECTED) == 0) {
856                         if (nam != NULL) {
857                                 UNP_LINK_WLOCK_ASSERT();
858                                 error = unp_connect(so, nam, td);
859                                 if (error)
860                                         break;  /* XXX */
861                         } else {
862                                 error = ENOTCONN;
863                                 break;
864                         }
865                 }
866
867                 /* Lockless read. */
868                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
869                         error = EPIPE;
870                         break;
871                 }
872
873                 /*
874                  * Because connect() and send() are non-atomic in a sendto()
875                  * with a target address, it's possible that the socket will
876                  * have disconnected before the send() can run.  In that case
877                  * return the slightly counter-intuitive but otherwise
878                  * correct error that the socket is not connected.
879                  *
880                  * Locking here must be done carefully: the linkage lock
881                  * prevents interconnections between unpcbs from changing, so
882                  * we can traverse from unp to unp2 without acquiring unp's
883                  * lock.  Socket buffer locks follow unpcb locks, so we can
884                  * acquire both remote and lock socket buffer locks.
885                  */
886                 unp2 = unp->unp_conn;
887                 if (unp2 == NULL) {
888                         error = ENOTCONN;
889                         break;
890                 }
891                 so2 = unp2->unp_socket;
892                 UNP_PCB_LOCK(unp2);
893                 SOCKBUF_LOCK(&so2->so_rcv);
894                 if (unp2->unp_flags & UNP_WANTCRED) {
895                         /*
896                          * Credentials are passed only once on SOCK_STREAM.
897                          */
898                         unp2->unp_flags &= ~UNP_WANTCRED;
899                         control = unp_addsockcred(td, control);
900                 }
901                 /*
902                  * Send to paired receive port, and then reduce send buffer
903                  * hiwater marks to maintain backpressure.  Wake up readers.
904                  */
905                 if (control != NULL) {
906                         if (sbappendcontrol_locked(&so2->so_rcv, m, control))
907                                 control = NULL;
908                 } else
909                         sbappend_locked(&so2->so_rcv, m);
910                 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
911                 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
912                 sbcc = so2->so_rcv.sb_cc;
913                 sorwakeup_locked(so2);
914
915                 SOCKBUF_LOCK(&so->so_snd);
916                 if ((int)so->so_snd.sb_hiwat >= (int)(sbcc - unp2->unp_cc))
917                         newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
918                 else
919                         newhiwat = 0;
920                 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
921                     newhiwat, RLIM_INFINITY);
922                 so->so_snd.sb_mbmax -= mbcnt_delta;
923                 SOCKBUF_UNLOCK(&so->so_snd);
924                 unp2->unp_cc = sbcc;
925                 UNP_PCB_UNLOCK(unp2);
926                 m = NULL;
927                 break;
928
929         default:
930                 panic("uipc_send unknown socktype");
931         }
932
933         /*
934          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
935          */
936         if (flags & PRUS_EOF) {
937                 UNP_PCB_LOCK(unp);
938                 socantsendmore(so);
939                 unp_shutdown(unp);
940                 UNP_PCB_UNLOCK(unp);
941         }
942
943         if ((nam != NULL) || (flags & PRUS_EOF))
944                 UNP_LINK_WUNLOCK();
945         else
946                 UNP_LINK_RUNLOCK();
947
948         if (control != NULL && error != 0)
949                 unp_dispose(control);
950
951 release:
952         if (control != NULL)
953                 m_freem(control);
954         if (m != NULL)
955                 m_freem(m);
956         return (error);
957 }
958
959 static int
960 uipc_sense(struct socket *so, struct stat *sb)
961 {
962         struct unpcb *unp, *unp2;
963         struct socket *so2;
964
965         unp = sotounpcb(so);
966         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
967
968         sb->st_blksize = so->so_snd.sb_hiwat;
969         UNP_LINK_RLOCK();
970         UNP_PCB_LOCK(unp);
971         unp2 = unp->unp_conn;
972         if (so->so_type == SOCK_STREAM && unp2 != NULL) {
973                 so2 = unp2->unp_socket;
974                 sb->st_blksize += so2->so_rcv.sb_cc;
975         }
976         sb->st_dev = NODEV;
977         if (unp->unp_ino == 0)
978                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
979         sb->st_ino = unp->unp_ino;
980         UNP_PCB_UNLOCK(unp);
981         UNP_LINK_RUNLOCK();
982         return (0);
983 }
984
985 static int
986 uipc_shutdown(struct socket *so)
987 {
988         struct unpcb *unp;
989
990         unp = sotounpcb(so);
991         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
992
993         UNP_LINK_WLOCK();
994         UNP_PCB_LOCK(unp);
995         socantsendmore(so);
996         unp_shutdown(unp);
997         UNP_PCB_UNLOCK(unp);
998         UNP_LINK_WUNLOCK();
999         return (0);
1000 }
1001
1002 static int
1003 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1004 {
1005         struct unpcb *unp;
1006         const struct sockaddr *sa;
1007
1008         unp = sotounpcb(so);
1009         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1010
1011         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1012         UNP_PCB_LOCK(unp);
1013         if (unp->unp_addr != NULL)
1014                 sa = (struct sockaddr *) unp->unp_addr;
1015         else
1016                 sa = &sun_noname;
1017         bcopy(sa, *nam, sa->sa_len);
1018         UNP_PCB_UNLOCK(unp);
1019         return (0);
1020 }
1021
1022 static struct pr_usrreqs uipc_usrreqs_dgram = {
1023         .pru_abort =            uipc_abort,
1024         .pru_accept =           uipc_accept,
1025         .pru_attach =           uipc_attach,
1026         .pru_bind =             uipc_bind,
1027         .pru_connect =          uipc_connect,
1028         .pru_connect2 =         uipc_connect2,
1029         .pru_detach =           uipc_detach,
1030         .pru_disconnect =       uipc_disconnect,
1031         .pru_listen =           uipc_listen,
1032         .pru_peeraddr =         uipc_peeraddr,
1033         .pru_rcvd =             uipc_rcvd,
1034         .pru_send =             uipc_send,
1035         .pru_sense =            uipc_sense,
1036         .pru_shutdown =         uipc_shutdown,
1037         .pru_sockaddr =         uipc_sockaddr,
1038         .pru_soreceive =        soreceive_dgram,
1039         .pru_close =            uipc_close,
1040 };
1041
1042 static struct pr_usrreqs uipc_usrreqs_stream = {
1043         .pru_abort =            uipc_abort,
1044         .pru_accept =           uipc_accept,
1045         .pru_attach =           uipc_attach,
1046         .pru_bind =             uipc_bind,
1047         .pru_connect =          uipc_connect,
1048         .pru_connect2 =         uipc_connect2,
1049         .pru_detach =           uipc_detach,
1050         .pru_disconnect =       uipc_disconnect,
1051         .pru_listen =           uipc_listen,
1052         .pru_peeraddr =         uipc_peeraddr,
1053         .pru_rcvd =             uipc_rcvd,
1054         .pru_send =             uipc_send,
1055         .pru_sense =            uipc_sense,
1056         .pru_shutdown =         uipc_shutdown,
1057         .pru_sockaddr =         uipc_sockaddr,
1058         .pru_soreceive =        soreceive_generic,
1059         .pru_close =            uipc_close,
1060 };
1061
1062 static int
1063 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1064 {
1065         struct unpcb *unp;
1066         struct xucred xu;
1067         int error, optval;
1068
1069         if (sopt->sopt_level != 0)
1070                 return (EINVAL);
1071
1072         unp = sotounpcb(so);
1073         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1074         error = 0;
1075         switch (sopt->sopt_dir) {
1076         case SOPT_GET:
1077                 switch (sopt->sopt_name) {
1078                 case LOCAL_PEERCRED:
1079                         UNP_PCB_LOCK(unp);
1080                         if (unp->unp_flags & UNP_HAVEPC)
1081                                 xu = unp->unp_peercred;
1082                         else {
1083                                 if (so->so_type == SOCK_STREAM)
1084                                         error = ENOTCONN;
1085                                 else
1086                                         error = EINVAL;
1087                         }
1088                         UNP_PCB_UNLOCK(unp);
1089                         if (error == 0)
1090                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1091                         break;
1092
1093                 case LOCAL_CREDS:
1094                         /* Unlocked read. */
1095                         optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1096                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1097                         break;
1098
1099                 case LOCAL_CONNWAIT:
1100                         /* Unlocked read. */
1101                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1102                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1103                         break;
1104
1105                 default:
1106                         error = EOPNOTSUPP;
1107                         break;
1108                 }
1109                 break;
1110
1111         case SOPT_SET:
1112                 switch (sopt->sopt_name) {
1113                 case LOCAL_CREDS:
1114                 case LOCAL_CONNWAIT:
1115                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1116                                             sizeof(optval));
1117                         if (error)
1118                                 break;
1119
1120 #define OPTSET(bit) do {                                                \
1121         UNP_PCB_LOCK(unp);                                              \
1122         if (optval)                                                     \
1123                 unp->unp_flags |= bit;                                  \
1124         else                                                            \
1125                 unp->unp_flags &= ~bit;                                 \
1126         UNP_PCB_UNLOCK(unp);                                            \
1127 } while (0)
1128
1129                         switch (sopt->sopt_name) {
1130                         case LOCAL_CREDS:
1131                                 OPTSET(UNP_WANTCRED);
1132                                 break;
1133
1134                         case LOCAL_CONNWAIT:
1135                                 OPTSET(UNP_CONNWAIT);
1136                                 break;
1137
1138                         default:
1139                                 break;
1140                         }
1141                         break;
1142 #undef  OPTSET
1143                 default:
1144                         error = ENOPROTOOPT;
1145                         break;
1146                 }
1147                 break;
1148
1149         default:
1150                 error = EOPNOTSUPP;
1151                 break;
1152         }
1153         return (error);
1154 }
1155
1156 static int
1157 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1158 {
1159         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1160         struct vnode *vp;
1161         struct socket *so2, *so3;
1162         struct unpcb *unp, *unp2, *unp3;
1163         int error, len, vfslocked;
1164         struct nameidata nd;
1165         char buf[SOCK_MAXADDRLEN];
1166         struct sockaddr *sa;
1167
1168         UNP_LINK_WLOCK_ASSERT();
1169
1170         unp = sotounpcb(so);
1171         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1172
1173         if (nam->sa_len > sizeof(struct sockaddr_un))
1174                 return (EINVAL);
1175         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1176         if (len <= 0)
1177                 return (EINVAL);
1178         bcopy(soun->sun_path, buf, len);
1179         buf[len] = 0;
1180
1181         UNP_PCB_LOCK(unp);
1182         if (unp->unp_flags & UNP_CONNECTING) {
1183                 UNP_PCB_UNLOCK(unp);
1184                 return (EALREADY);
1185         }
1186         UNP_LINK_WUNLOCK();
1187         unp->unp_flags |= UNP_CONNECTING;
1188         UNP_PCB_UNLOCK(unp);
1189
1190         sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1191         NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKSHARED | LOCKLEAF,
1192             UIO_SYSSPACE, buf, td);
1193         error = namei(&nd);
1194         if (error)
1195                 vp = NULL;
1196         else
1197                 vp = nd.ni_vp;
1198         ASSERT_VOP_LOCKED(vp, "unp_connect");
1199         vfslocked = NDHASGIANT(&nd);
1200         NDFREE(&nd, NDF_ONLY_PNBUF);
1201         if (error)
1202                 goto bad;
1203
1204         if (vp->v_type != VSOCK) {
1205                 error = ENOTSOCK;
1206                 goto bad;
1207         }
1208 #ifdef MAC
1209         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1210         if (error)
1211                 goto bad;
1212 #endif
1213         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1214         if (error)
1215                 goto bad;
1216         VFS_UNLOCK_GIANT(vfslocked);
1217
1218         unp = sotounpcb(so);
1219         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1220
1221         /*
1222          * Lock linkage lock for two reasons: make sure v_socket is stable,
1223          * and to protect simultaneous locking of multiple pcbs.
1224          */
1225         UNP_LINK_WLOCK();
1226         so2 = vp->v_socket;
1227         if (so2 == NULL) {
1228                 error = ECONNREFUSED;
1229                 goto bad2;
1230         }
1231         if (so->so_type != so2->so_type) {
1232                 error = EPROTOTYPE;
1233                 goto bad2;
1234         }
1235         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1236                 if (so2->so_options & SO_ACCEPTCONN) {
1237                         CURVNET_SET(so2->so_vnet);
1238                         so3 = sonewconn(so2, 0);
1239                         CURVNET_RESTORE();
1240                 } else
1241                         so3 = NULL;
1242                 if (so3 == NULL) {
1243                         error = ECONNREFUSED;
1244                         goto bad2;
1245                 }
1246                 unp = sotounpcb(so);
1247                 unp2 = sotounpcb(so2);
1248                 unp3 = sotounpcb(so3);
1249                 UNP_PCB_LOCK(unp);
1250                 UNP_PCB_LOCK(unp2);
1251                 UNP_PCB_LOCK(unp3);
1252                 if (unp2->unp_addr != NULL) {
1253                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1254                         unp3->unp_addr = (struct sockaddr_un *) sa;
1255                         sa = NULL;
1256                 }
1257
1258                 /*
1259                  * The connecter's (client's) credentials are copied from its
1260                  * process structure at the time of connect() (which is now).
1261                  */
1262                 cru2x(td->td_ucred, &unp3->unp_peercred);
1263                 unp3->unp_flags |= UNP_HAVEPC;
1264
1265                 /*
1266                  * The receiver's (server's) credentials are copied from the
1267                  * unp_peercred member of socket on which the former called
1268                  * listen(); uipc_listen() cached that process's credentials
1269                  * at that time so we can use them now.
1270                  */
1271                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1272                     ("unp_connect: listener without cached peercred"));
1273                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1274                     sizeof(unp->unp_peercred));
1275                 unp->unp_flags |= UNP_HAVEPC;
1276                 if (unp2->unp_flags & UNP_WANTCRED)
1277                         unp3->unp_flags |= UNP_WANTCRED;
1278                 UNP_PCB_UNLOCK(unp3);
1279                 UNP_PCB_UNLOCK(unp2);
1280                 UNP_PCB_UNLOCK(unp);
1281 #ifdef MAC
1282                 mac_socketpeer_set_from_socket(so, so3);
1283                 mac_socketpeer_set_from_socket(so3, so);
1284 #endif
1285
1286                 so2 = so3;
1287         }
1288         unp = sotounpcb(so);
1289         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1290         unp2 = sotounpcb(so2);
1291         KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1292         UNP_PCB_LOCK(unp);
1293         UNP_PCB_LOCK(unp2);
1294         error = unp_connect2(so, so2, PRU_CONNECT);
1295         UNP_PCB_UNLOCK(unp2);
1296         UNP_PCB_UNLOCK(unp);
1297 bad2:
1298         UNP_LINK_WUNLOCK();
1299         if (vfslocked)
1300                 /* 
1301                  * Giant has been previously acquired. This means filesystem
1302                  * isn't MPSAFE.  Do it once again.
1303                  */
1304                 mtx_lock(&Giant);
1305 bad:
1306         if (vp != NULL)
1307                 vput(vp);
1308         VFS_UNLOCK_GIANT(vfslocked);
1309         free(sa, M_SONAME);
1310         UNP_LINK_WLOCK();
1311         UNP_PCB_LOCK(unp);
1312         unp->unp_flags &= ~UNP_CONNECTING;
1313         UNP_PCB_UNLOCK(unp);
1314         return (error);
1315 }
1316
1317 static int
1318 unp_connect2(struct socket *so, struct socket *so2, int req)
1319 {
1320         struct unpcb *unp;
1321         struct unpcb *unp2;
1322
1323         unp = sotounpcb(so);
1324         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1325         unp2 = sotounpcb(so2);
1326         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1327
1328         UNP_LINK_WLOCK_ASSERT();
1329         UNP_PCB_LOCK_ASSERT(unp);
1330         UNP_PCB_LOCK_ASSERT(unp2);
1331
1332         if (so2->so_type != so->so_type)
1333                 return (EPROTOTYPE);
1334         unp->unp_conn = unp2;
1335
1336         switch (so->so_type) {
1337         case SOCK_DGRAM:
1338                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1339                 soisconnected(so);
1340                 break;
1341
1342         case SOCK_STREAM:
1343                 unp2->unp_conn = unp;
1344                 if (req == PRU_CONNECT &&
1345                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1346                         soisconnecting(so);
1347                 else
1348                         soisconnected(so);
1349                 soisconnected(so2);
1350                 break;
1351
1352         default:
1353                 panic("unp_connect2");
1354         }
1355         return (0);
1356 }
1357
1358 static void
1359 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1360 {
1361         struct socket *so;
1362
1363         KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1364
1365         UNP_LINK_WLOCK_ASSERT();
1366         UNP_PCB_LOCK_ASSERT(unp);
1367         UNP_PCB_LOCK_ASSERT(unp2);
1368
1369         unp->unp_conn = NULL;
1370         switch (unp->unp_socket->so_type) {
1371         case SOCK_DGRAM:
1372                 LIST_REMOVE(unp, unp_reflink);
1373                 so = unp->unp_socket;
1374                 SOCK_LOCK(so);
1375                 so->so_state &= ~SS_ISCONNECTED;
1376                 SOCK_UNLOCK(so);
1377                 break;
1378
1379         case SOCK_STREAM:
1380                 soisdisconnected(unp->unp_socket);
1381                 unp2->unp_conn = NULL;
1382                 soisdisconnected(unp2->unp_socket);
1383                 break;
1384         }
1385 }
1386
1387 /*
1388  * unp_pcblist() walks the global list of struct unpcb's to generate a
1389  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1390  * sequentially, validating the generation number on each to see if it has
1391  * been detached.  All of this is necessary because copyout() may sleep on
1392  * disk I/O.
1393  */
1394 static int
1395 unp_pcblist(SYSCTL_HANDLER_ARGS)
1396 {
1397         int error, i, n;
1398         int freeunp;
1399         struct unpcb *unp, **unp_list;
1400         unp_gen_t gencnt;
1401         struct xunpgen *xug;
1402         struct unp_head *head;
1403         struct xunpcb *xu;
1404
1405         head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1406
1407         /*
1408          * The process of preparing the PCB list is too time-consuming and
1409          * resource-intensive to repeat twice on every request.
1410          */
1411         if (req->oldptr == NULL) {
1412                 n = unp_count;
1413                 req->oldidx = 2 * (sizeof *xug)
1414                         + (n + n/8) * sizeof(struct xunpcb);
1415                 return (0);
1416         }
1417
1418         if (req->newptr != NULL)
1419                 return (EPERM);
1420
1421         /*
1422          * OK, now we're committed to doing something.
1423          */
1424         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1425         UNP_LIST_LOCK();
1426         gencnt = unp_gencnt;
1427         n = unp_count;
1428         UNP_LIST_UNLOCK();
1429
1430         xug->xug_len = sizeof *xug;
1431         xug->xug_count = n;
1432         xug->xug_gen = gencnt;
1433         xug->xug_sogen = so_gencnt;
1434         error = SYSCTL_OUT(req, xug, sizeof *xug);
1435         if (error) {
1436                 free(xug, M_TEMP);
1437                 return (error);
1438         }
1439
1440         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1441
1442         UNP_LIST_LOCK();
1443         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1444              unp = LIST_NEXT(unp, unp_link)) {
1445                 UNP_PCB_LOCK(unp);
1446                 if (unp->unp_gencnt <= gencnt) {
1447                         if (cr_cansee(req->td->td_ucred,
1448                             unp->unp_socket->so_cred)) {
1449                                 UNP_PCB_UNLOCK(unp);
1450                                 continue;
1451                         }
1452                         unp_list[i++] = unp;
1453                         unp->unp_refcount++;
1454                 }
1455                 UNP_PCB_UNLOCK(unp);
1456         }
1457         UNP_LIST_UNLOCK();
1458         n = i;                  /* In case we lost some during malloc. */
1459
1460         error = 0;
1461         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1462         for (i = 0; i < n; i++) {
1463                 unp = unp_list[i];
1464                 UNP_PCB_LOCK(unp);
1465                 unp->unp_refcount--;
1466                 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1467                         xu->xu_len = sizeof *xu;
1468                         xu->xu_unpp = unp;
1469                         /*
1470                          * XXX - need more locking here to protect against
1471                          * connect/disconnect races for SMP.
1472                          */
1473                         if (unp->unp_addr != NULL)
1474                                 bcopy(unp->unp_addr, &xu->xu_addr,
1475                                       unp->unp_addr->sun_len);
1476                         if (unp->unp_conn != NULL &&
1477                             unp->unp_conn->unp_addr != NULL)
1478                                 bcopy(unp->unp_conn->unp_addr,
1479                                       &xu->xu_caddr,
1480                                       unp->unp_conn->unp_addr->sun_len);
1481                         bcopy(unp, &xu->xu_unp, sizeof *unp);
1482                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
1483                         UNP_PCB_UNLOCK(unp);
1484                         error = SYSCTL_OUT(req, xu, sizeof *xu);
1485                 } else {
1486                         freeunp = (unp->unp_refcount == 0);
1487                         UNP_PCB_UNLOCK(unp);
1488                         if (freeunp) {
1489                                 UNP_PCB_LOCK_DESTROY(unp);
1490                                 uma_zfree(unp_zone, unp);
1491                         }
1492                 }
1493         }
1494         free(xu, M_TEMP);
1495         if (!error) {
1496                 /*
1497                  * Give the user an updated idea of our state.  If the
1498                  * generation differs from what we told her before, she knows
1499                  * that something happened while we were processing this
1500                  * request, and it might be necessary to retry.
1501                  */
1502                 xug->xug_gen = unp_gencnt;
1503                 xug->xug_sogen = so_gencnt;
1504                 xug->xug_count = unp_count;
1505                 error = SYSCTL_OUT(req, xug, sizeof *xug);
1506         }
1507         free(unp_list, M_TEMP);
1508         free(xug, M_TEMP);
1509         return (error);
1510 }
1511
1512 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1513             (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1514             "List of active local datagram sockets");
1515 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1516             (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1517             "List of active local stream sockets");
1518
1519 static void
1520 unp_shutdown(struct unpcb *unp)
1521 {
1522         struct unpcb *unp2;
1523         struct socket *so;
1524
1525         UNP_LINK_WLOCK_ASSERT();
1526         UNP_PCB_LOCK_ASSERT(unp);
1527
1528         unp2 = unp->unp_conn;
1529         if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1530                 so = unp2->unp_socket;
1531                 if (so != NULL)
1532                         socantrcvmore(so);
1533         }
1534 }
1535
1536 static void
1537 unp_drop(struct unpcb *unp, int errno)
1538 {
1539         struct socket *so = unp->unp_socket;
1540         struct unpcb *unp2;
1541
1542         UNP_LINK_WLOCK_ASSERT();
1543         UNP_PCB_LOCK_ASSERT(unp);
1544
1545         so->so_error = errno;
1546         unp2 = unp->unp_conn;
1547         if (unp2 == NULL)
1548                 return;
1549         UNP_PCB_LOCK(unp2);
1550         unp_disconnect(unp, unp2);
1551         UNP_PCB_UNLOCK(unp2);
1552 }
1553
1554 static void
1555 unp_freerights(struct file **rp, int fdcount)
1556 {
1557         int i;
1558         struct file *fp;
1559
1560         for (i = 0; i < fdcount; i++) {
1561                 fp = *rp;
1562                 *rp++ = NULL;
1563                 unp_discard(fp);
1564         }
1565 }
1566
1567 static int
1568 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1569 {
1570         struct thread *td = curthread;          /* XXX */
1571         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1572         int i;
1573         int *fdp;
1574         struct file **rp;
1575         struct file *fp;
1576         void *data;
1577         socklen_t clen = control->m_len, datalen;
1578         int error, newfds;
1579         int f;
1580         u_int newlen;
1581
1582         UNP_LINK_UNLOCK_ASSERT();
1583
1584         error = 0;
1585         if (controlp != NULL) /* controlp == NULL => free control messages */
1586                 *controlp = NULL;
1587         while (cm != NULL) {
1588                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1589                         error = EINVAL;
1590                         break;
1591                 }
1592                 data = CMSG_DATA(cm);
1593                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1594                 if (cm->cmsg_level == SOL_SOCKET
1595                     && cm->cmsg_type == SCM_RIGHTS) {
1596                         newfds = datalen / sizeof(struct file *);
1597                         rp = data;
1598
1599                         /* If we're not outputting the descriptors free them. */
1600                         if (error || controlp == NULL) {
1601                                 unp_freerights(rp, newfds);
1602                                 goto next;
1603                         }
1604                         FILEDESC_XLOCK(td->td_proc->p_fd);
1605                         /* if the new FD's will not fit free them.  */
1606                         if (!fdavail(td, newfds)) {
1607                                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1608                                 error = EMSGSIZE;
1609                                 unp_freerights(rp, newfds);
1610                                 goto next;
1611                         }
1612
1613                         /*
1614                          * Now change each pointer to an fd in the global
1615                          * table to an integer that is the index to the local
1616                          * fd table entry that we set up to point to the
1617                          * global one we are transferring.
1618                          */
1619                         newlen = newfds * sizeof(int);
1620                         *controlp = sbcreatecontrol(NULL, newlen,
1621                             SCM_RIGHTS, SOL_SOCKET);
1622                         if (*controlp == NULL) {
1623                                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1624                                 error = E2BIG;
1625                                 unp_freerights(rp, newfds);
1626                                 goto next;
1627                         }
1628
1629                         fdp = (int *)
1630                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1631                         for (i = 0; i < newfds; i++) {
1632                                 if (fdalloc(td, 0, &f))
1633                                         panic("unp_externalize fdalloc failed");
1634                                 fp = *rp++;
1635                                 td->td_proc->p_fd->fd_ofiles[f] = fp;
1636                                 unp_externalize_fp(fp);
1637                                 *fdp++ = f;
1638                         }
1639                         FILEDESC_XUNLOCK(td->td_proc->p_fd);
1640                 } else {
1641                         /* We can just copy anything else across. */
1642                         if (error || controlp == NULL)
1643                                 goto next;
1644                         *controlp = sbcreatecontrol(NULL, datalen,
1645                             cm->cmsg_type, cm->cmsg_level);
1646                         if (*controlp == NULL) {
1647                                 error = ENOBUFS;
1648                                 goto next;
1649                         }
1650                         bcopy(data,
1651                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1652                             datalen);
1653                 }
1654                 controlp = &(*controlp)->m_next;
1655
1656 next:
1657                 if (CMSG_SPACE(datalen) < clen) {
1658                         clen -= CMSG_SPACE(datalen);
1659                         cm = (struct cmsghdr *)
1660                             ((caddr_t)cm + CMSG_SPACE(datalen));
1661                 } else {
1662                         clen = 0;
1663                         cm = NULL;
1664                 }
1665         }
1666
1667         m_freem(control);
1668         return (error);
1669 }
1670
1671 static void
1672 unp_zone_change(void *tag)
1673 {
1674
1675         uma_zone_set_max(unp_zone, maxsockets);
1676 }
1677
1678 static void
1679 unp_init(void)
1680 {
1681
1682 #ifdef VIMAGE
1683         if (!IS_DEFAULT_VNET(curvnet))
1684                 return;
1685 #endif
1686         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1687             NULL, NULL, UMA_ALIGN_PTR, 0);
1688         if (unp_zone == NULL)
1689                 panic("unp_init");
1690         uma_zone_set_max(unp_zone, maxsockets);
1691         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1692             NULL, EVENTHANDLER_PRI_ANY);
1693         LIST_INIT(&unp_dhead);
1694         LIST_INIT(&unp_shead);
1695         SLIST_INIT(&unp_defers);
1696         TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1697         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1698         UNP_LINK_LOCK_INIT();
1699         UNP_LIST_LOCK_INIT();
1700         UNP_DEFERRED_LOCK_INIT();
1701 }
1702
1703 static int
1704 unp_internalize(struct mbuf **controlp, struct thread *td)
1705 {
1706         struct mbuf *control = *controlp;
1707         struct proc *p = td->td_proc;
1708         struct filedesc *fdescp = p->p_fd;
1709         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1710         struct cmsgcred *cmcred;
1711         struct file **rp;
1712         struct file *fp;
1713         struct timeval *tv;
1714         int i, fd, *fdp;
1715         void *data;
1716         socklen_t clen = control->m_len, datalen;
1717         int error, oldfds;
1718         u_int newlen;
1719
1720         UNP_LINK_UNLOCK_ASSERT();
1721
1722         error = 0;
1723         *controlp = NULL;
1724         while (cm != NULL) {
1725                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1726                     || cm->cmsg_len > clen) {
1727                         error = EINVAL;
1728                         goto out;
1729                 }
1730                 data = CMSG_DATA(cm);
1731                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1732
1733                 switch (cm->cmsg_type) {
1734                 /*
1735                  * Fill in credential information.
1736                  */
1737                 case SCM_CREDS:
1738                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1739                             SCM_CREDS, SOL_SOCKET);
1740                         if (*controlp == NULL) {
1741                                 error = ENOBUFS;
1742                                 goto out;
1743                         }
1744                         cmcred = (struct cmsgcred *)
1745                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1746                         cmcred->cmcred_pid = p->p_pid;
1747                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1748                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1749                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
1750                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1751                             CMGROUP_MAX);
1752                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
1753                                 cmcred->cmcred_groups[i] =
1754                                     td->td_ucred->cr_groups[i];
1755                         break;
1756
1757                 case SCM_RIGHTS:
1758                         oldfds = datalen / sizeof (int);
1759                         /*
1760                          * Check that all the FDs passed in refer to legal
1761                          * files.  If not, reject the entire operation.
1762                          */
1763                         fdp = data;
1764                         FILEDESC_SLOCK(fdescp);
1765                         for (i = 0; i < oldfds; i++) {
1766                                 fd = *fdp++;
1767                                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1768                                     fdescp->fd_ofiles[fd] == NULL) {
1769                                         FILEDESC_SUNLOCK(fdescp);
1770                                         error = EBADF;
1771                                         goto out;
1772                                 }
1773                                 fp = fdescp->fd_ofiles[fd];
1774                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1775                                         FILEDESC_SUNLOCK(fdescp);
1776                                         error = EOPNOTSUPP;
1777                                         goto out;
1778                                 }
1779
1780                         }
1781
1782                         /*
1783                          * Now replace the integer FDs with pointers to the
1784                          * associated global file table entry..
1785                          */
1786                         newlen = oldfds * sizeof(struct file *);
1787                         *controlp = sbcreatecontrol(NULL, newlen,
1788                             SCM_RIGHTS, SOL_SOCKET);
1789                         if (*controlp == NULL) {
1790                                 FILEDESC_SUNLOCK(fdescp);
1791                                 error = E2BIG;
1792                                 goto out;
1793                         }
1794                         fdp = data;
1795                         rp = (struct file **)
1796                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1797                         for (i = 0; i < oldfds; i++) {
1798                                 fp = fdescp->fd_ofiles[*fdp++];
1799                                 *rp++ = fp;
1800                                 unp_internalize_fp(fp);
1801                         }
1802                         FILEDESC_SUNLOCK(fdescp);
1803                         break;
1804
1805                 case SCM_TIMESTAMP:
1806                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1807                             SCM_TIMESTAMP, SOL_SOCKET);
1808                         if (*controlp == NULL) {
1809                                 error = ENOBUFS;
1810                                 goto out;
1811                         }
1812                         tv = (struct timeval *)
1813                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1814                         microtime(tv);
1815                         break;
1816
1817                 default:
1818                         error = EINVAL;
1819                         goto out;
1820                 }
1821
1822                 controlp = &(*controlp)->m_next;
1823                 if (CMSG_SPACE(datalen) < clen) {
1824                         clen -= CMSG_SPACE(datalen);
1825                         cm = (struct cmsghdr *)
1826                             ((caddr_t)cm + CMSG_SPACE(datalen));
1827                 } else {
1828                         clen = 0;
1829                         cm = NULL;
1830                 }
1831         }
1832
1833 out:
1834         m_freem(control);
1835         return (error);
1836 }
1837
1838 static struct mbuf *
1839 unp_addsockcred(struct thread *td, struct mbuf *control)
1840 {
1841         struct mbuf *m, *n, *n_prev;
1842         struct sockcred *sc;
1843         const struct cmsghdr *cm;
1844         int ngroups;
1845         int i;
1846
1847         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1848         m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1849         if (m == NULL)
1850                 return (control);
1851
1852         sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1853         sc->sc_uid = td->td_ucred->cr_ruid;
1854         sc->sc_euid = td->td_ucred->cr_uid;
1855         sc->sc_gid = td->td_ucred->cr_rgid;
1856         sc->sc_egid = td->td_ucred->cr_gid;
1857         sc->sc_ngroups = ngroups;
1858         for (i = 0; i < sc->sc_ngroups; i++)
1859                 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1860
1861         /*
1862          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1863          * created SCM_CREDS control message (struct sockcred) has another
1864          * format.
1865          */
1866         if (control != NULL)
1867                 for (n = control, n_prev = NULL; n != NULL;) {
1868                         cm = mtod(n, struct cmsghdr *);
1869                         if (cm->cmsg_level == SOL_SOCKET &&
1870                             cm->cmsg_type == SCM_CREDS) {
1871                                 if (n_prev == NULL)
1872                                         control = n->m_next;
1873                                 else
1874                                         n_prev->m_next = n->m_next;
1875                                 n = m_free(n);
1876                         } else {
1877                                 n_prev = n;
1878                                 n = n->m_next;
1879                         }
1880                 }
1881
1882         /* Prepend it to the head. */
1883         m->m_next = control;
1884         return (m);
1885 }
1886
1887 static struct unpcb *
1888 fptounp(struct file *fp)
1889 {
1890         struct socket *so;
1891
1892         if (fp->f_type != DTYPE_SOCKET)
1893                 return (NULL);
1894         if ((so = fp->f_data) == NULL)
1895                 return (NULL);
1896         if (so->so_proto->pr_domain != &localdomain)
1897                 return (NULL);
1898         return sotounpcb(so);
1899 }
1900
1901 static void
1902 unp_discard(struct file *fp)
1903 {
1904         struct unp_defer *dr;
1905
1906         if (unp_externalize_fp(fp)) {
1907                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
1908                 dr->ud_fp = fp;
1909                 UNP_DEFERRED_LOCK();
1910                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
1911                 UNP_DEFERRED_UNLOCK();
1912                 atomic_add_int(&unp_defers_count, 1);
1913                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
1914         } else
1915                 (void) closef(fp, (struct thread *)NULL);
1916 }
1917
1918 static void
1919 unp_process_defers(void *arg __unused, int pending)
1920 {
1921         struct unp_defer *dr;
1922         SLIST_HEAD(, unp_defer) drl;
1923         int count;
1924
1925         SLIST_INIT(&drl);
1926         for (;;) {
1927                 UNP_DEFERRED_LOCK();
1928                 if (SLIST_FIRST(&unp_defers) == NULL) {
1929                         UNP_DEFERRED_UNLOCK();
1930                         break;
1931                 }
1932                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
1933                 UNP_DEFERRED_UNLOCK();
1934                 count = 0;
1935                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
1936                         SLIST_REMOVE_HEAD(&drl, ud_link);
1937                         closef(dr->ud_fp, NULL);
1938                         free(dr, M_TEMP);
1939                         count++;
1940                 }
1941                 atomic_add_int(&unp_defers_count, -count);
1942         }
1943 }
1944
1945 static void
1946 unp_internalize_fp(struct file *fp)
1947 {
1948         struct unpcb *unp;
1949
1950         UNP_LINK_WLOCK();
1951         if ((unp = fptounp(fp)) != NULL) {
1952                 unp->unp_file = fp;
1953                 unp->unp_msgcount++;
1954         }
1955         fhold(fp);
1956         unp_rights++;
1957         UNP_LINK_WUNLOCK();
1958 }
1959
1960 static int
1961 unp_externalize_fp(struct file *fp)
1962 {
1963         struct unpcb *unp;
1964         int ret;
1965
1966         UNP_LINK_WLOCK();
1967         if ((unp = fptounp(fp)) != NULL) {
1968                 unp->unp_msgcount--;
1969                 ret = 1;
1970         } else
1971                 ret = 0;
1972         unp_rights--;
1973         UNP_LINK_WUNLOCK();
1974         return (ret);
1975 }
1976
1977 /*
1978  * unp_defer indicates whether additional work has been defered for a future
1979  * pass through unp_gc().  It is thread local and does not require explicit
1980  * synchronization.
1981  */
1982 static int      unp_marked;
1983 static int      unp_unreachable;
1984
1985 static void
1986 unp_accessable(struct file *fp)
1987 {
1988         struct unpcb *unp;
1989
1990         if ((unp = fptounp(fp)) == NULL)
1991                 return;
1992         if (unp->unp_gcflag & UNPGC_REF)
1993                 return;
1994         unp->unp_gcflag &= ~UNPGC_DEAD;
1995         unp->unp_gcflag |= UNPGC_REF;
1996         unp_marked++;
1997 }
1998
1999 static void
2000 unp_gc_process(struct unpcb *unp)
2001 {
2002         struct socket *soa;
2003         struct socket *so;
2004         struct file *fp;
2005
2006         /* Already processed. */
2007         if (unp->unp_gcflag & UNPGC_SCANNED)
2008                 return;
2009         fp = unp->unp_file;
2010
2011         /*
2012          * Check for a socket potentially in a cycle.  It must be in a
2013          * queue as indicated by msgcount, and this must equal the file
2014          * reference count.  Note that when msgcount is 0 the file is NULL.
2015          */
2016         if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2017             unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2018                 unp->unp_gcflag |= UNPGC_DEAD;
2019                 unp_unreachable++;
2020                 return;
2021         }
2022
2023         /*
2024          * Mark all sockets we reference with RIGHTS.
2025          */
2026         so = unp->unp_socket;
2027         SOCKBUF_LOCK(&so->so_rcv);
2028         unp_scan(so->so_rcv.sb_mb, unp_accessable);
2029         SOCKBUF_UNLOCK(&so->so_rcv);
2030
2031         /*
2032          * Mark all sockets in our accept queue.
2033          */
2034         ACCEPT_LOCK();
2035         TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2036                 SOCKBUF_LOCK(&soa->so_rcv);
2037                 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2038                 SOCKBUF_UNLOCK(&soa->so_rcv);
2039         }
2040         ACCEPT_UNLOCK();
2041         unp->unp_gcflag |= UNPGC_SCANNED;
2042 }
2043
2044 static int unp_recycled;
2045 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2046     "Number of unreachable sockets claimed by the garbage collector.");
2047
2048 static int unp_taskcount;
2049 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2050     "Number of times the garbage collector has run.");
2051
2052 static void
2053 unp_gc(__unused void *arg, int pending)
2054 {
2055         struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
2056         struct unp_head **head;
2057         struct file *f, **unref;
2058         struct unpcb *unp;
2059         int i, total;
2060
2061         unp_taskcount++;
2062         UNP_LIST_LOCK();
2063         /*
2064          * First clear all gc flags from previous runs.
2065          */
2066         for (head = heads; *head != NULL; head++)
2067                 LIST_FOREACH(unp, *head, unp_link)
2068                         unp->unp_gcflag = 0;
2069
2070         /*
2071          * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2072          * is reachable all of the sockets it references are reachable.
2073          * Stop the scan once we do a complete loop without discovering
2074          * a new reachable socket.
2075          */
2076         do {
2077                 unp_unreachable = 0;
2078                 unp_marked = 0;
2079                 for (head = heads; *head != NULL; head++)
2080                         LIST_FOREACH(unp, *head, unp_link)
2081                                 unp_gc_process(unp);
2082         } while (unp_marked);
2083         UNP_LIST_UNLOCK();
2084         if (unp_unreachable == 0)
2085                 return;
2086
2087         /*
2088          * Allocate space for a local list of dead unpcbs.
2089          */
2090         unref = malloc(unp_unreachable * sizeof(struct file *),
2091             M_TEMP, M_WAITOK);
2092
2093         /*
2094          * Iterate looking for sockets which have been specifically marked
2095          * as as unreachable and store them locally.
2096          */
2097         UNP_LINK_RLOCK();
2098         UNP_LIST_LOCK();
2099         for (total = 0, head = heads; *head != NULL; head++)
2100                 LIST_FOREACH(unp, *head, unp_link)
2101                         if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2102                                 f = unp->unp_file;
2103                                 if (unp->unp_msgcount == 0 || f == NULL ||
2104                                     f->f_count != unp->unp_msgcount)
2105                                         continue;
2106                                 unref[total++] = f;
2107                                 fhold(f);
2108                                 KASSERT(total <= unp_unreachable,
2109                                     ("unp_gc: incorrect unreachable count."));
2110                         }
2111         UNP_LIST_UNLOCK();
2112         UNP_LINK_RUNLOCK();
2113
2114         /*
2115          * Now flush all sockets, free'ing rights.  This will free the
2116          * struct files associated with these sockets but leave each socket
2117          * with one remaining ref.
2118          */
2119         for (i = 0; i < total; i++) {
2120                 struct socket *so;
2121
2122                 so = unref[i]->f_data;
2123                 CURVNET_SET(so->so_vnet);
2124                 sorflush(so);
2125                 CURVNET_RESTORE();
2126         }
2127
2128         /*
2129          * And finally release the sockets so they can be reclaimed.
2130          */
2131         for (i = 0; i < total; i++)
2132                 fdrop(unref[i], NULL);
2133         unp_recycled += total;
2134         free(unref, M_TEMP);
2135 }
2136
2137 static void
2138 unp_dispose(struct mbuf *m)
2139 {
2140
2141         if (m)
2142                 unp_scan(m, unp_discard);
2143 }
2144
2145 static void
2146 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2147 {
2148         struct mbuf *m;
2149         struct file **rp;
2150         struct cmsghdr *cm;
2151         void *data;
2152         int i;
2153         socklen_t clen, datalen;
2154         int qfds;
2155
2156         while (m0 != NULL) {
2157                 for (m = m0; m; m = m->m_next) {
2158                         if (m->m_type != MT_CONTROL)
2159                                 continue;
2160
2161                         cm = mtod(m, struct cmsghdr *);
2162                         clen = m->m_len;
2163
2164                         while (cm != NULL) {
2165                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2166                                         break;
2167
2168                                 data = CMSG_DATA(cm);
2169                                 datalen = (caddr_t)cm + cm->cmsg_len
2170                                     - (caddr_t)data;
2171
2172                                 if (cm->cmsg_level == SOL_SOCKET &&
2173                                     cm->cmsg_type == SCM_RIGHTS) {
2174                                         qfds = datalen / sizeof (struct file *);
2175                                         rp = data;
2176                                         for (i = 0; i < qfds; i++)
2177                                                 (*op)(*rp++);
2178                                 }
2179
2180                                 if (CMSG_SPACE(datalen) < clen) {
2181                                         clen -= CMSG_SPACE(datalen);
2182                                         cm = (struct cmsghdr *)
2183                                             ((caddr_t)cm + CMSG_SPACE(datalen));
2184                                 } else {
2185                                         clen = 0;
2186                                         cm = NULL;
2187                                 }
2188                         }
2189                 }
2190                 m0 = m0->m_act;
2191         }
2192 }
2193
2194 #ifdef DDB
2195 static void
2196 db_print_indent(int indent)
2197 {
2198         int i;
2199
2200         for (i = 0; i < indent; i++)
2201                 db_printf(" ");
2202 }
2203
2204 static void
2205 db_print_unpflags(int unp_flags)
2206 {
2207         int comma;
2208
2209         comma = 0;
2210         if (unp_flags & UNP_HAVEPC) {
2211                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2212                 comma = 1;
2213         }
2214         if (unp_flags & UNP_HAVEPCCACHED) {
2215                 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2216                 comma = 1;
2217         }
2218         if (unp_flags & UNP_WANTCRED) {
2219                 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2220                 comma = 1;
2221         }
2222         if (unp_flags & UNP_CONNWAIT) {
2223                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2224                 comma = 1;
2225         }
2226         if (unp_flags & UNP_CONNECTING) {
2227                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2228                 comma = 1;
2229         }
2230         if (unp_flags & UNP_BINDING) {
2231                 db_printf("%sUNP_BINDING", comma ? ", " : "");
2232                 comma = 1;
2233         }
2234 }
2235
2236 static void
2237 db_print_xucred(int indent, struct xucred *xu)
2238 {
2239         int comma, i;
2240
2241         db_print_indent(indent);
2242         db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2243             xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2244         db_print_indent(indent);
2245         db_printf("cr_groups: ");
2246         comma = 0;
2247         for (i = 0; i < xu->cr_ngroups; i++) {
2248                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2249                 comma = 1;
2250         }
2251         db_printf("\n");
2252 }
2253
2254 static void
2255 db_print_unprefs(int indent, struct unp_head *uh)
2256 {
2257         struct unpcb *unp;
2258         int counter;
2259
2260         counter = 0;
2261         LIST_FOREACH(unp, uh, unp_reflink) {
2262                 if (counter % 4 == 0)
2263                         db_print_indent(indent);
2264                 db_printf("%p  ", unp);
2265                 if (counter % 4 == 3)
2266                         db_printf("\n");
2267                 counter++;
2268         }
2269         if (counter != 0 && counter % 4 != 0)
2270                 db_printf("\n");
2271 }
2272
2273 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2274 {
2275         struct unpcb *unp;
2276
2277         if (!have_addr) {
2278                 db_printf("usage: show unpcb <addr>\n");
2279                 return;
2280         }
2281         unp = (struct unpcb *)addr;
2282
2283         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2284             unp->unp_vnode);
2285
2286         db_printf("unp_ino: %d   unp_conn: %p\n", unp->unp_ino,
2287             unp->unp_conn);
2288
2289         db_printf("unp_refs:\n");
2290         db_print_unprefs(2, &unp->unp_refs);
2291
2292         /* XXXRW: Would be nice to print the full address, if any. */
2293         db_printf("unp_addr: %p\n", unp->unp_addr);
2294
2295         db_printf("unp_cc: %d   unp_mbcnt: %d   unp_gencnt: %llu\n",
2296             unp->unp_cc, unp->unp_mbcnt,
2297             (unsigned long long)unp->unp_gencnt);
2298
2299         db_printf("unp_flags: %x (", unp->unp_flags);
2300         db_print_unpflags(unp->unp_flags);
2301         db_printf(")\n");
2302
2303         db_printf("unp_peercred:\n");
2304         db_print_xucred(2, &unp->unp_peercred);
2305
2306         db_printf("unp_refcount: %u\n", unp->unp_refcount);
2307 }
2308 #endif