]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/kern/uipc_usrreq.c
Fix handling of corrupt compress(1)ed data. [11:04]
[FreeBSD/releng/8.2.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_long 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                 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
917                 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
918                     newhiwat, RLIM_INFINITY);
919                 so->so_snd.sb_mbmax -= mbcnt_delta;
920                 SOCKBUF_UNLOCK(&so->so_snd);
921                 unp2->unp_cc = sbcc;
922                 UNP_PCB_UNLOCK(unp2);
923                 m = NULL;
924                 break;
925
926         default:
927                 panic("uipc_send unknown socktype");
928         }
929
930         /*
931          * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
932          */
933         if (flags & PRUS_EOF) {
934                 UNP_PCB_LOCK(unp);
935                 socantsendmore(so);
936                 unp_shutdown(unp);
937                 UNP_PCB_UNLOCK(unp);
938         }
939
940         if ((nam != NULL) || (flags & PRUS_EOF))
941                 UNP_LINK_WUNLOCK();
942         else
943                 UNP_LINK_RUNLOCK();
944
945         if (control != NULL && error != 0)
946                 unp_dispose(control);
947
948 release:
949         if (control != NULL)
950                 m_freem(control);
951         if (m != NULL)
952                 m_freem(m);
953         return (error);
954 }
955
956 static int
957 uipc_sense(struct socket *so, struct stat *sb)
958 {
959         struct unpcb *unp, *unp2;
960         struct socket *so2;
961
962         unp = sotounpcb(so);
963         KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
964
965         sb->st_blksize = so->so_snd.sb_hiwat;
966         UNP_LINK_RLOCK();
967         UNP_PCB_LOCK(unp);
968         unp2 = unp->unp_conn;
969         if (so->so_type == SOCK_STREAM && unp2 != NULL) {
970                 so2 = unp2->unp_socket;
971                 sb->st_blksize += so2->so_rcv.sb_cc;
972         }
973         sb->st_dev = NODEV;
974         if (unp->unp_ino == 0)
975                 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
976         sb->st_ino = unp->unp_ino;
977         UNP_PCB_UNLOCK(unp);
978         UNP_LINK_RUNLOCK();
979         return (0);
980 }
981
982 static int
983 uipc_shutdown(struct socket *so)
984 {
985         struct unpcb *unp;
986
987         unp = sotounpcb(so);
988         KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
989
990         UNP_LINK_WLOCK();
991         UNP_PCB_LOCK(unp);
992         socantsendmore(so);
993         unp_shutdown(unp);
994         UNP_PCB_UNLOCK(unp);
995         UNP_LINK_WUNLOCK();
996         return (0);
997 }
998
999 static int
1000 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1001 {
1002         struct unpcb *unp;
1003         const struct sockaddr *sa;
1004
1005         unp = sotounpcb(so);
1006         KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1007
1008         *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1009         UNP_PCB_LOCK(unp);
1010         if (unp->unp_addr != NULL)
1011                 sa = (struct sockaddr *) unp->unp_addr;
1012         else
1013                 sa = &sun_noname;
1014         bcopy(sa, *nam, sa->sa_len);
1015         UNP_PCB_UNLOCK(unp);
1016         return (0);
1017 }
1018
1019 static struct pr_usrreqs uipc_usrreqs_dgram = {
1020         .pru_abort =            uipc_abort,
1021         .pru_accept =           uipc_accept,
1022         .pru_attach =           uipc_attach,
1023         .pru_bind =             uipc_bind,
1024         .pru_connect =          uipc_connect,
1025         .pru_connect2 =         uipc_connect2,
1026         .pru_detach =           uipc_detach,
1027         .pru_disconnect =       uipc_disconnect,
1028         .pru_listen =           uipc_listen,
1029         .pru_peeraddr =         uipc_peeraddr,
1030         .pru_rcvd =             uipc_rcvd,
1031         .pru_send =             uipc_send,
1032         .pru_sense =            uipc_sense,
1033         .pru_shutdown =         uipc_shutdown,
1034         .pru_sockaddr =         uipc_sockaddr,
1035         .pru_soreceive =        soreceive_dgram,
1036         .pru_close =            uipc_close,
1037 };
1038
1039 static struct pr_usrreqs uipc_usrreqs_stream = {
1040         .pru_abort =            uipc_abort,
1041         .pru_accept =           uipc_accept,
1042         .pru_attach =           uipc_attach,
1043         .pru_bind =             uipc_bind,
1044         .pru_connect =          uipc_connect,
1045         .pru_connect2 =         uipc_connect2,
1046         .pru_detach =           uipc_detach,
1047         .pru_disconnect =       uipc_disconnect,
1048         .pru_listen =           uipc_listen,
1049         .pru_peeraddr =         uipc_peeraddr,
1050         .pru_rcvd =             uipc_rcvd,
1051         .pru_send =             uipc_send,
1052         .pru_sense =            uipc_sense,
1053         .pru_shutdown =         uipc_shutdown,
1054         .pru_sockaddr =         uipc_sockaddr,
1055         .pru_soreceive =        soreceive_generic,
1056         .pru_close =            uipc_close,
1057 };
1058
1059 static int
1060 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1061 {
1062         struct unpcb *unp;
1063         struct xucred xu;
1064         int error, optval;
1065
1066         if (sopt->sopt_level != 0)
1067                 return (EINVAL);
1068
1069         unp = sotounpcb(so);
1070         KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1071         error = 0;
1072         switch (sopt->sopt_dir) {
1073         case SOPT_GET:
1074                 switch (sopt->sopt_name) {
1075                 case LOCAL_PEERCRED:
1076                         UNP_PCB_LOCK(unp);
1077                         if (unp->unp_flags & UNP_HAVEPC)
1078                                 xu = unp->unp_peercred;
1079                         else {
1080                                 if (so->so_type == SOCK_STREAM)
1081                                         error = ENOTCONN;
1082                                 else
1083                                         error = EINVAL;
1084                         }
1085                         UNP_PCB_UNLOCK(unp);
1086                         if (error == 0)
1087                                 error = sooptcopyout(sopt, &xu, sizeof(xu));
1088                         break;
1089
1090                 case LOCAL_CREDS:
1091                         /* Unlocked read. */
1092                         optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1093                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1094                         break;
1095
1096                 case LOCAL_CONNWAIT:
1097                         /* Unlocked read. */
1098                         optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1099                         error = sooptcopyout(sopt, &optval, sizeof(optval));
1100                         break;
1101
1102                 default:
1103                         error = EOPNOTSUPP;
1104                         break;
1105                 }
1106                 break;
1107
1108         case SOPT_SET:
1109                 switch (sopt->sopt_name) {
1110                 case LOCAL_CREDS:
1111                 case LOCAL_CONNWAIT:
1112                         error = sooptcopyin(sopt, &optval, sizeof(optval),
1113                                             sizeof(optval));
1114                         if (error)
1115                                 break;
1116
1117 #define OPTSET(bit) do {                                                \
1118         UNP_PCB_LOCK(unp);                                              \
1119         if (optval)                                                     \
1120                 unp->unp_flags |= bit;                                  \
1121         else                                                            \
1122                 unp->unp_flags &= ~bit;                                 \
1123         UNP_PCB_UNLOCK(unp);                                            \
1124 } while (0)
1125
1126                         switch (sopt->sopt_name) {
1127                         case LOCAL_CREDS:
1128                                 OPTSET(UNP_WANTCRED);
1129                                 break;
1130
1131                         case LOCAL_CONNWAIT:
1132                                 OPTSET(UNP_CONNWAIT);
1133                                 break;
1134
1135                         default:
1136                                 break;
1137                         }
1138                         break;
1139 #undef  OPTSET
1140                 default:
1141                         error = ENOPROTOOPT;
1142                         break;
1143                 }
1144                 break;
1145
1146         default:
1147                 error = EOPNOTSUPP;
1148                 break;
1149         }
1150         return (error);
1151 }
1152
1153 static int
1154 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1155 {
1156         struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1157         struct vnode *vp;
1158         struct socket *so2, *so3;
1159         struct unpcb *unp, *unp2, *unp3;
1160         int error, len, vfslocked;
1161         struct nameidata nd;
1162         char buf[SOCK_MAXADDRLEN];
1163         struct sockaddr *sa;
1164
1165         UNP_LINK_WLOCK_ASSERT();
1166
1167         unp = sotounpcb(so);
1168         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1169
1170         if (nam->sa_len > sizeof(struct sockaddr_un))
1171                 return (EINVAL);
1172         len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1173         if (len <= 0)
1174                 return (EINVAL);
1175         bcopy(soun->sun_path, buf, len);
1176         buf[len] = 0;
1177
1178         UNP_PCB_LOCK(unp);
1179         if (unp->unp_flags & UNP_CONNECTING) {
1180                 UNP_PCB_UNLOCK(unp);
1181                 return (EALREADY);
1182         }
1183         UNP_LINK_WUNLOCK();
1184         unp->unp_flags |= UNP_CONNECTING;
1185         UNP_PCB_UNLOCK(unp);
1186
1187         sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1188         NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1189             td);
1190         error = namei(&nd);
1191         if (error)
1192                 vp = NULL;
1193         else
1194                 vp = nd.ni_vp;
1195         ASSERT_VOP_LOCKED(vp, "unp_connect");
1196         vfslocked = NDHASGIANT(&nd);
1197         NDFREE(&nd, NDF_ONLY_PNBUF);
1198         if (error)
1199                 goto bad;
1200
1201         if (vp->v_type != VSOCK) {
1202                 error = ENOTSOCK;
1203                 goto bad;
1204         }
1205 #ifdef MAC
1206         error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1207         if (error)
1208                 goto bad;
1209 #endif
1210         error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1211         if (error)
1212                 goto bad;
1213         VFS_UNLOCK_GIANT(vfslocked);
1214
1215         unp = sotounpcb(so);
1216         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1217
1218         /*
1219          * Lock linkage lock for two reasons: make sure v_socket is stable,
1220          * and to protect simultaneous locking of multiple pcbs.
1221          */
1222         UNP_LINK_WLOCK();
1223         so2 = vp->v_socket;
1224         if (so2 == NULL) {
1225                 error = ECONNREFUSED;
1226                 goto bad2;
1227         }
1228         if (so->so_type != so2->so_type) {
1229                 error = EPROTOTYPE;
1230                 goto bad2;
1231         }
1232         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1233                 if (so2->so_options & SO_ACCEPTCONN) {
1234                         so3 = sonewconn(so2, 0);
1235                 } else
1236                         so3 = NULL;
1237                 if (so3 == NULL) {
1238                         error = ECONNREFUSED;
1239                         goto bad2;
1240                 }
1241                 unp = sotounpcb(so);
1242                 unp2 = sotounpcb(so2);
1243                 unp3 = sotounpcb(so3);
1244                 UNP_PCB_LOCK(unp);
1245                 UNP_PCB_LOCK(unp2);
1246                 UNP_PCB_LOCK(unp3);
1247                 if (unp2->unp_addr != NULL) {
1248                         bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1249                         unp3->unp_addr = (struct sockaddr_un *) sa;
1250                         sa = NULL;
1251                 }
1252
1253                 /*
1254                  * The connecter's (client's) credentials are copied from its
1255                  * process structure at the time of connect() (which is now).
1256                  */
1257                 cru2x(td->td_ucred, &unp3->unp_peercred);
1258                 unp3->unp_flags |= UNP_HAVEPC;
1259
1260                 /*
1261                  * The receiver's (server's) credentials are copied from the
1262                  * unp_peercred member of socket on which the former called
1263                  * listen(); uipc_listen() cached that process's credentials
1264                  * at that time so we can use them now.
1265                  */
1266                 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1267                     ("unp_connect: listener without cached peercred"));
1268                 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1269                     sizeof(unp->unp_peercred));
1270                 unp->unp_flags |= UNP_HAVEPC;
1271                 if (unp2->unp_flags & UNP_WANTCRED)
1272                         unp3->unp_flags |= UNP_WANTCRED;
1273                 UNP_PCB_UNLOCK(unp3);
1274                 UNP_PCB_UNLOCK(unp2);
1275                 UNP_PCB_UNLOCK(unp);
1276 #ifdef MAC
1277                 mac_socketpeer_set_from_socket(so, so3);
1278                 mac_socketpeer_set_from_socket(so3, so);
1279 #endif
1280
1281                 so2 = so3;
1282         }
1283         unp = sotounpcb(so);
1284         KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1285         unp2 = sotounpcb(so2);
1286         KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1287         UNP_PCB_LOCK(unp);
1288         UNP_PCB_LOCK(unp2);
1289         error = unp_connect2(so, so2, PRU_CONNECT);
1290         UNP_PCB_UNLOCK(unp2);
1291         UNP_PCB_UNLOCK(unp);
1292 bad2:
1293         UNP_LINK_WUNLOCK();
1294         if (vfslocked)
1295                 /* 
1296                  * Giant has been previously acquired. This means filesystem
1297                  * isn't MPSAFE.  Do it once again.
1298                  */
1299                 mtx_lock(&Giant);
1300 bad:
1301         if (vp != NULL)
1302                 vput(vp);
1303         VFS_UNLOCK_GIANT(vfslocked);
1304         free(sa, M_SONAME);
1305         UNP_LINK_WLOCK();
1306         UNP_PCB_LOCK(unp);
1307         unp->unp_flags &= ~UNP_CONNECTING;
1308         UNP_PCB_UNLOCK(unp);
1309         return (error);
1310 }
1311
1312 static int
1313 unp_connect2(struct socket *so, struct socket *so2, int req)
1314 {
1315         struct unpcb *unp;
1316         struct unpcb *unp2;
1317
1318         unp = sotounpcb(so);
1319         KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1320         unp2 = sotounpcb(so2);
1321         KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1322
1323         UNP_LINK_WLOCK_ASSERT();
1324         UNP_PCB_LOCK_ASSERT(unp);
1325         UNP_PCB_LOCK_ASSERT(unp2);
1326
1327         if (so2->so_type != so->so_type)
1328                 return (EPROTOTYPE);
1329         unp->unp_conn = unp2;
1330
1331         switch (so->so_type) {
1332         case SOCK_DGRAM:
1333                 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1334                 soisconnected(so);
1335                 break;
1336
1337         case SOCK_STREAM:
1338                 unp2->unp_conn = unp;
1339                 if (req == PRU_CONNECT &&
1340                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1341                         soisconnecting(so);
1342                 else
1343                         soisconnected(so);
1344                 soisconnected(so2);
1345                 break;
1346
1347         default:
1348                 panic("unp_connect2");
1349         }
1350         return (0);
1351 }
1352
1353 static void
1354 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1355 {
1356         struct socket *so;
1357
1358         KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1359
1360         UNP_LINK_WLOCK_ASSERT();
1361         UNP_PCB_LOCK_ASSERT(unp);
1362         UNP_PCB_LOCK_ASSERT(unp2);
1363
1364         unp->unp_conn = NULL;
1365         switch (unp->unp_socket->so_type) {
1366         case SOCK_DGRAM:
1367                 LIST_REMOVE(unp, unp_reflink);
1368                 so = unp->unp_socket;
1369                 SOCK_LOCK(so);
1370                 so->so_state &= ~SS_ISCONNECTED;
1371                 SOCK_UNLOCK(so);
1372                 break;
1373
1374         case SOCK_STREAM:
1375                 soisdisconnected(unp->unp_socket);
1376                 unp2->unp_conn = NULL;
1377                 soisdisconnected(unp2->unp_socket);
1378                 break;
1379         }
1380 }
1381
1382 /*
1383  * unp_pcblist() walks the global list of struct unpcb's to generate a
1384  * pointer list, bumping the refcount on each unpcb.  It then copies them out
1385  * sequentially, validating the generation number on each to see if it has
1386  * been detached.  All of this is necessary because copyout() may sleep on
1387  * disk I/O.
1388  */
1389 static int
1390 unp_pcblist(SYSCTL_HANDLER_ARGS)
1391 {
1392         int error, i, n;
1393         int freeunp;
1394         struct unpcb *unp, **unp_list;
1395         unp_gen_t gencnt;
1396         struct xunpgen *xug;
1397         struct unp_head *head;
1398         struct xunpcb *xu;
1399
1400         head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1401
1402         /*
1403          * The process of preparing the PCB list is too time-consuming and
1404          * resource-intensive to repeat twice on every request.
1405          */
1406         if (req->oldptr == NULL) {
1407                 n = unp_count;
1408                 req->oldidx = 2 * (sizeof *xug)
1409                         + (n + n/8) * sizeof(struct xunpcb);
1410                 return (0);
1411         }
1412
1413         if (req->newptr != NULL)
1414                 return (EPERM);
1415
1416         /*
1417          * OK, now we're committed to doing something.
1418          */
1419         xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1420         UNP_LIST_LOCK();
1421         gencnt = unp_gencnt;
1422         n = unp_count;
1423         UNP_LIST_UNLOCK();
1424
1425         xug->xug_len = sizeof *xug;
1426         xug->xug_count = n;
1427         xug->xug_gen = gencnt;
1428         xug->xug_sogen = so_gencnt;
1429         error = SYSCTL_OUT(req, xug, sizeof *xug);
1430         if (error) {
1431                 free(xug, M_TEMP);
1432                 return (error);
1433         }
1434
1435         unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1436
1437         UNP_LIST_LOCK();
1438         for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1439              unp = LIST_NEXT(unp, unp_link)) {
1440                 UNP_PCB_LOCK(unp);
1441                 if (unp->unp_gencnt <= gencnt) {
1442                         if (cr_cansee(req->td->td_ucred,
1443                             unp->unp_socket->so_cred)) {
1444                                 UNP_PCB_UNLOCK(unp);
1445                                 continue;
1446                         }
1447                         unp_list[i++] = unp;
1448                         unp->unp_refcount++;
1449                 }
1450                 UNP_PCB_UNLOCK(unp);
1451         }
1452         UNP_LIST_UNLOCK();
1453         n = i;                  /* In case we lost some during malloc. */
1454
1455         error = 0;
1456         xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1457         for (i = 0; i < n; i++) {
1458                 unp = unp_list[i];
1459                 UNP_PCB_LOCK(unp);
1460                 unp->unp_refcount--;
1461                 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1462                         xu->xu_len = sizeof *xu;
1463                         xu->xu_unpp = unp;
1464                         /*
1465                          * XXX - need more locking here to protect against
1466                          * connect/disconnect races for SMP.
1467                          */
1468                         if (unp->unp_addr != NULL)
1469                                 bcopy(unp->unp_addr, &xu->xu_addr,
1470                                       unp->unp_addr->sun_len);
1471                         if (unp->unp_conn != NULL &&
1472                             unp->unp_conn->unp_addr != NULL)
1473                                 bcopy(unp->unp_conn->unp_addr,
1474                                       &xu->xu_caddr,
1475                                       unp->unp_conn->unp_addr->sun_len);
1476                         bcopy(unp, &xu->xu_unp, sizeof *unp);
1477                         sotoxsocket(unp->unp_socket, &xu->xu_socket);
1478                         UNP_PCB_UNLOCK(unp);
1479                         error = SYSCTL_OUT(req, xu, sizeof *xu);
1480                 } else {
1481                         freeunp = (unp->unp_refcount == 0);
1482                         UNP_PCB_UNLOCK(unp);
1483                         if (freeunp) {
1484                                 UNP_PCB_LOCK_DESTROY(unp);
1485                                 uma_zfree(unp_zone, unp);
1486                         }
1487                 }
1488         }
1489         free(xu, M_TEMP);
1490         if (!error) {
1491                 /*
1492                  * Give the user an updated idea of our state.  If the
1493                  * generation differs from what we told her before, she knows
1494                  * that something happened while we were processing this
1495                  * request, and it might be necessary to retry.
1496                  */
1497                 xug->xug_gen = unp_gencnt;
1498                 xug->xug_sogen = so_gencnt;
1499                 xug->xug_count = unp_count;
1500                 error = SYSCTL_OUT(req, xug, sizeof *xug);
1501         }
1502         free(unp_list, M_TEMP);
1503         free(xug, M_TEMP);
1504         return (error);
1505 }
1506
1507 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1508             (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1509             "List of active local datagram sockets");
1510 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1511             (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1512             "List of active local stream sockets");
1513
1514 static void
1515 unp_shutdown(struct unpcb *unp)
1516 {
1517         struct unpcb *unp2;
1518         struct socket *so;
1519
1520         UNP_LINK_WLOCK_ASSERT();
1521         UNP_PCB_LOCK_ASSERT(unp);
1522
1523         unp2 = unp->unp_conn;
1524         if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1525                 so = unp2->unp_socket;
1526                 if (so != NULL)
1527                         socantrcvmore(so);
1528         }
1529 }
1530
1531 static void
1532 unp_drop(struct unpcb *unp, int errno)
1533 {
1534         struct socket *so = unp->unp_socket;
1535         struct unpcb *unp2;
1536
1537         UNP_LINK_WLOCK_ASSERT();
1538         UNP_PCB_LOCK_ASSERT(unp);
1539
1540         so->so_error = errno;
1541         unp2 = unp->unp_conn;
1542         if (unp2 == NULL)
1543                 return;
1544         UNP_PCB_LOCK(unp2);
1545         unp_disconnect(unp, unp2);
1546         UNP_PCB_UNLOCK(unp2);
1547 }
1548
1549 static void
1550 unp_freerights(struct file **rp, int fdcount)
1551 {
1552         int i;
1553         struct file *fp;
1554
1555         for (i = 0; i < fdcount; i++) {
1556                 fp = *rp;
1557                 *rp++ = NULL;
1558                 unp_discard(fp);
1559         }
1560 }
1561
1562 static int
1563 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1564 {
1565         struct thread *td = curthread;          /* XXX */
1566         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1567         int i;
1568         int *fdp;
1569         struct file **rp;
1570         struct file *fp;
1571         void *data;
1572         socklen_t clen = control->m_len, datalen;
1573         int error, newfds;
1574         int f;
1575         u_int newlen;
1576
1577         UNP_LINK_UNLOCK_ASSERT();
1578
1579         error = 0;
1580         if (controlp != NULL) /* controlp == NULL => free control messages */
1581                 *controlp = NULL;
1582         while (cm != NULL) {
1583                 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1584                         error = EINVAL;
1585                         break;
1586                 }
1587                 data = CMSG_DATA(cm);
1588                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1589                 if (cm->cmsg_level == SOL_SOCKET
1590                     && cm->cmsg_type == SCM_RIGHTS) {
1591                         newfds = datalen / sizeof(struct file *);
1592                         rp = data;
1593
1594                         /* If we're not outputting the descriptors free them. */
1595                         if (error || controlp == NULL) {
1596                                 unp_freerights(rp, newfds);
1597                                 goto next;
1598                         }
1599                         FILEDESC_XLOCK(td->td_proc->p_fd);
1600                         /* if the new FD's will not fit free them.  */
1601                         if (!fdavail(td, newfds)) {
1602                                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1603                                 error = EMSGSIZE;
1604                                 unp_freerights(rp, newfds);
1605                                 goto next;
1606                         }
1607
1608                         /*
1609                          * Now change each pointer to an fd in the global
1610                          * table to an integer that is the index to the local
1611                          * fd table entry that we set up to point to the
1612                          * global one we are transferring.
1613                          */
1614                         newlen = newfds * sizeof(int);
1615                         *controlp = sbcreatecontrol(NULL, newlen,
1616                             SCM_RIGHTS, SOL_SOCKET);
1617                         if (*controlp == NULL) {
1618                                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1619                                 error = E2BIG;
1620                                 unp_freerights(rp, newfds);
1621                                 goto next;
1622                         }
1623
1624                         fdp = (int *)
1625                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1626                         for (i = 0; i < newfds; i++) {
1627                                 if (fdalloc(td, 0, &f))
1628                                         panic("unp_externalize fdalloc failed");
1629                                 fp = *rp++;
1630                                 td->td_proc->p_fd->fd_ofiles[f] = fp;
1631                                 unp_externalize_fp(fp);
1632                                 *fdp++ = f;
1633                         }
1634                         FILEDESC_XUNLOCK(td->td_proc->p_fd);
1635                 } else {
1636                         /* We can just copy anything else across. */
1637                         if (error || controlp == NULL)
1638                                 goto next;
1639                         *controlp = sbcreatecontrol(NULL, datalen,
1640                             cm->cmsg_type, cm->cmsg_level);
1641                         if (*controlp == NULL) {
1642                                 error = ENOBUFS;
1643                                 goto next;
1644                         }
1645                         bcopy(data,
1646                             CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1647                             datalen);
1648                 }
1649                 controlp = &(*controlp)->m_next;
1650
1651 next:
1652                 if (CMSG_SPACE(datalen) < clen) {
1653                         clen -= CMSG_SPACE(datalen);
1654                         cm = (struct cmsghdr *)
1655                             ((caddr_t)cm + CMSG_SPACE(datalen));
1656                 } else {
1657                         clen = 0;
1658                         cm = NULL;
1659                 }
1660         }
1661
1662         m_freem(control);
1663         return (error);
1664 }
1665
1666 static void
1667 unp_zone_change(void *tag)
1668 {
1669
1670         uma_zone_set_max(unp_zone, maxsockets);
1671 }
1672
1673 static void
1674 unp_init(void)
1675 {
1676
1677 #ifdef VIMAGE
1678         if (!IS_DEFAULT_VNET(curvnet))
1679                 return;
1680 #endif
1681         unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1682             NULL, NULL, UMA_ALIGN_PTR, 0);
1683         if (unp_zone == NULL)
1684                 panic("unp_init");
1685         uma_zone_set_max(unp_zone, maxsockets);
1686         EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1687             NULL, EVENTHANDLER_PRI_ANY);
1688         LIST_INIT(&unp_dhead);
1689         LIST_INIT(&unp_shead);
1690         SLIST_INIT(&unp_defers);
1691         TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1692         TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1693         UNP_LINK_LOCK_INIT();
1694         UNP_LIST_LOCK_INIT();
1695         UNP_DEFERRED_LOCK_INIT();
1696 }
1697
1698 static int
1699 unp_internalize(struct mbuf **controlp, struct thread *td)
1700 {
1701         struct mbuf *control = *controlp;
1702         struct proc *p = td->td_proc;
1703         struct filedesc *fdescp = p->p_fd;
1704         struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1705         struct cmsgcred *cmcred;
1706         struct file **rp;
1707         struct file *fp;
1708         struct timeval *tv;
1709         int i, fd, *fdp;
1710         void *data;
1711         socklen_t clen = control->m_len, datalen;
1712         int error, oldfds;
1713         u_int newlen;
1714
1715         UNP_LINK_UNLOCK_ASSERT();
1716
1717         error = 0;
1718         *controlp = NULL;
1719         while (cm != NULL) {
1720                 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1721                     || cm->cmsg_len > clen) {
1722                         error = EINVAL;
1723                         goto out;
1724                 }
1725                 data = CMSG_DATA(cm);
1726                 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1727
1728                 switch (cm->cmsg_type) {
1729                 /*
1730                  * Fill in credential information.
1731                  */
1732                 case SCM_CREDS:
1733                         *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1734                             SCM_CREDS, SOL_SOCKET);
1735                         if (*controlp == NULL) {
1736                                 error = ENOBUFS;
1737                                 goto out;
1738                         }
1739                         cmcred = (struct cmsgcred *)
1740                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1741                         cmcred->cmcred_pid = p->p_pid;
1742                         cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1743                         cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1744                         cmcred->cmcred_euid = td->td_ucred->cr_uid;
1745                         cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1746                             CMGROUP_MAX);
1747                         for (i = 0; i < cmcred->cmcred_ngroups; i++)
1748                                 cmcred->cmcred_groups[i] =
1749                                     td->td_ucred->cr_groups[i];
1750                         break;
1751
1752                 case SCM_RIGHTS:
1753                         oldfds = datalen / sizeof (int);
1754                         /*
1755                          * Check that all the FDs passed in refer to legal
1756                          * files.  If not, reject the entire operation.
1757                          */
1758                         fdp = data;
1759                         FILEDESC_SLOCK(fdescp);
1760                         for (i = 0; i < oldfds; i++) {
1761                                 fd = *fdp++;
1762                                 if ((unsigned)fd >= fdescp->fd_nfiles ||
1763                                     fdescp->fd_ofiles[fd] == NULL) {
1764                                         FILEDESC_SUNLOCK(fdescp);
1765                                         error = EBADF;
1766                                         goto out;
1767                                 }
1768                                 fp = fdescp->fd_ofiles[fd];
1769                                 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1770                                         FILEDESC_SUNLOCK(fdescp);
1771                                         error = EOPNOTSUPP;
1772                                         goto out;
1773                                 }
1774
1775                         }
1776
1777                         /*
1778                          * Now replace the integer FDs with pointers to the
1779                          * associated global file table entry..
1780                          */
1781                         newlen = oldfds * sizeof(struct file *);
1782                         *controlp = sbcreatecontrol(NULL, newlen,
1783                             SCM_RIGHTS, SOL_SOCKET);
1784                         if (*controlp == NULL) {
1785                                 FILEDESC_SUNLOCK(fdescp);
1786                                 error = E2BIG;
1787                                 goto out;
1788                         }
1789                         fdp = data;
1790                         rp = (struct file **)
1791                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1792                         for (i = 0; i < oldfds; i++) {
1793                                 fp = fdescp->fd_ofiles[*fdp++];
1794                                 *rp++ = fp;
1795                                 unp_internalize_fp(fp);
1796                         }
1797                         FILEDESC_SUNLOCK(fdescp);
1798                         break;
1799
1800                 case SCM_TIMESTAMP:
1801                         *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1802                             SCM_TIMESTAMP, SOL_SOCKET);
1803                         if (*controlp == NULL) {
1804                                 error = ENOBUFS;
1805                                 goto out;
1806                         }
1807                         tv = (struct timeval *)
1808                             CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1809                         microtime(tv);
1810                         break;
1811
1812                 default:
1813                         error = EINVAL;
1814                         goto out;
1815                 }
1816
1817                 controlp = &(*controlp)->m_next;
1818                 if (CMSG_SPACE(datalen) < clen) {
1819                         clen -= CMSG_SPACE(datalen);
1820                         cm = (struct cmsghdr *)
1821                             ((caddr_t)cm + CMSG_SPACE(datalen));
1822                 } else {
1823                         clen = 0;
1824                         cm = NULL;
1825                 }
1826         }
1827
1828 out:
1829         m_freem(control);
1830         return (error);
1831 }
1832
1833 static struct mbuf *
1834 unp_addsockcred(struct thread *td, struct mbuf *control)
1835 {
1836         struct mbuf *m, *n, *n_prev;
1837         struct sockcred *sc;
1838         const struct cmsghdr *cm;
1839         int ngroups;
1840         int i;
1841
1842         ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1843         m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1844         if (m == NULL)
1845                 return (control);
1846
1847         sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1848         sc->sc_uid = td->td_ucred->cr_ruid;
1849         sc->sc_euid = td->td_ucred->cr_uid;
1850         sc->sc_gid = td->td_ucred->cr_rgid;
1851         sc->sc_egid = td->td_ucred->cr_gid;
1852         sc->sc_ngroups = ngroups;
1853         for (i = 0; i < sc->sc_ngroups; i++)
1854                 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1855
1856         /*
1857          * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1858          * created SCM_CREDS control message (struct sockcred) has another
1859          * format.
1860          */
1861         if (control != NULL)
1862                 for (n = control, n_prev = NULL; n != NULL;) {
1863                         cm = mtod(n, struct cmsghdr *);
1864                         if (cm->cmsg_level == SOL_SOCKET &&
1865                             cm->cmsg_type == SCM_CREDS) {
1866                                 if (n_prev == NULL)
1867                                         control = n->m_next;
1868                                 else
1869                                         n_prev->m_next = n->m_next;
1870                                 n = m_free(n);
1871                         } else {
1872                                 n_prev = n;
1873                                 n = n->m_next;
1874                         }
1875                 }
1876
1877         /* Prepend it to the head. */
1878         m->m_next = control;
1879         return (m);
1880 }
1881
1882 static struct unpcb *
1883 fptounp(struct file *fp)
1884 {
1885         struct socket *so;
1886
1887         if (fp->f_type != DTYPE_SOCKET)
1888                 return (NULL);
1889         if ((so = fp->f_data) == NULL)
1890                 return (NULL);
1891         if (so->so_proto->pr_domain != &localdomain)
1892                 return (NULL);
1893         return sotounpcb(so);
1894 }
1895
1896 static void
1897 unp_discard(struct file *fp)
1898 {
1899         struct unp_defer *dr;
1900
1901         if (unp_externalize_fp(fp)) {
1902                 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
1903                 dr->ud_fp = fp;
1904                 UNP_DEFERRED_LOCK();
1905                 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
1906                 UNP_DEFERRED_UNLOCK();
1907                 atomic_add_int(&unp_defers_count, 1);
1908                 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
1909         } else
1910                 (void) closef(fp, (struct thread *)NULL);
1911 }
1912
1913 static void
1914 unp_process_defers(void *arg __unused, int pending)
1915 {
1916         struct unp_defer *dr;
1917         SLIST_HEAD(, unp_defer) drl;
1918         int count;
1919
1920         SLIST_INIT(&drl);
1921         for (;;) {
1922                 UNP_DEFERRED_LOCK();
1923                 if (SLIST_FIRST(&unp_defers) == NULL) {
1924                         UNP_DEFERRED_UNLOCK();
1925                         break;
1926                 }
1927                 SLIST_SWAP(&unp_defers, &drl, unp_defer);
1928                 UNP_DEFERRED_UNLOCK();
1929                 count = 0;
1930                 while ((dr = SLIST_FIRST(&drl)) != NULL) {
1931                         SLIST_REMOVE_HEAD(&drl, ud_link);
1932                         closef(dr->ud_fp, NULL);
1933                         free(dr, M_TEMP);
1934                         count++;
1935                 }
1936                 atomic_add_int(&unp_defers_count, -count);
1937         }
1938 }
1939
1940 static void
1941 unp_internalize_fp(struct file *fp)
1942 {
1943         struct unpcb *unp;
1944
1945         UNP_LINK_WLOCK();
1946         if ((unp = fptounp(fp)) != NULL) {
1947                 unp->unp_file = fp;
1948                 unp->unp_msgcount++;
1949         }
1950         fhold(fp);
1951         unp_rights++;
1952         UNP_LINK_WUNLOCK();
1953 }
1954
1955 static int
1956 unp_externalize_fp(struct file *fp)
1957 {
1958         struct unpcb *unp;
1959         int ret;
1960
1961         UNP_LINK_WLOCK();
1962         if ((unp = fptounp(fp)) != NULL) {
1963                 unp->unp_msgcount--;
1964                 ret = 1;
1965         } else
1966                 ret = 0;
1967         unp_rights--;
1968         UNP_LINK_WUNLOCK();
1969         return (ret);
1970 }
1971
1972 /*
1973  * unp_defer indicates whether additional work has been defered for a future
1974  * pass through unp_gc().  It is thread local and does not require explicit
1975  * synchronization.
1976  */
1977 static int      unp_marked;
1978 static int      unp_unreachable;
1979
1980 static void
1981 unp_accessable(struct file *fp)
1982 {
1983         struct unpcb *unp;
1984
1985         if ((unp = fptounp(fp)) == NULL)
1986                 return;
1987         if (unp->unp_gcflag & UNPGC_REF)
1988                 return;
1989         unp->unp_gcflag &= ~UNPGC_DEAD;
1990         unp->unp_gcflag |= UNPGC_REF;
1991         unp_marked++;
1992 }
1993
1994 static void
1995 unp_gc_process(struct unpcb *unp)
1996 {
1997         struct socket *soa;
1998         struct socket *so;
1999         struct file *fp;
2000
2001         /* Already processed. */
2002         if (unp->unp_gcflag & UNPGC_SCANNED)
2003                 return;
2004         fp = unp->unp_file;
2005
2006         /*
2007          * Check for a socket potentially in a cycle.  It must be in a
2008          * queue as indicated by msgcount, and this must equal the file
2009          * reference count.  Note that when msgcount is 0 the file is NULL.
2010          */
2011         if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2012             unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2013                 unp->unp_gcflag |= UNPGC_DEAD;
2014                 unp_unreachable++;
2015                 return;
2016         }
2017
2018         /*
2019          * Mark all sockets we reference with RIGHTS.
2020          */
2021         so = unp->unp_socket;
2022         SOCKBUF_LOCK(&so->so_rcv);
2023         unp_scan(so->so_rcv.sb_mb, unp_accessable);
2024         SOCKBUF_UNLOCK(&so->so_rcv);
2025
2026         /*
2027          * Mark all sockets in our accept queue.
2028          */
2029         ACCEPT_LOCK();
2030         TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2031                 SOCKBUF_LOCK(&soa->so_rcv);
2032                 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2033                 SOCKBUF_UNLOCK(&soa->so_rcv);
2034         }
2035         ACCEPT_UNLOCK();
2036         unp->unp_gcflag |= UNPGC_SCANNED;
2037 }
2038
2039 static int unp_recycled;
2040 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 
2041     "Number of unreachable sockets claimed by the garbage collector.");
2042
2043 static int unp_taskcount;
2044 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 
2045     "Number of times the garbage collector has run.");
2046
2047 static void
2048 unp_gc(__unused void *arg, int pending)
2049 {
2050         struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
2051         struct unp_head **head;
2052         struct file **unref;
2053         struct unpcb *unp;
2054         int i;
2055
2056         unp_taskcount++;
2057         UNP_LIST_LOCK();
2058         /*
2059          * First clear all gc flags from previous runs.
2060          */
2061         for (head = heads; *head != NULL; head++)
2062                 LIST_FOREACH(unp, *head, unp_link)
2063                         unp->unp_gcflag = 0;
2064
2065         /*
2066          * Scan marking all reachable sockets with UNPGC_REF.  Once a socket
2067          * is reachable all of the sockets it references are reachable.
2068          * Stop the scan once we do a complete loop without discovering
2069          * a new reachable socket.
2070          */
2071         do {
2072                 unp_unreachable = 0;
2073                 unp_marked = 0;
2074                 for (head = heads; *head != NULL; head++)
2075                         LIST_FOREACH(unp, *head, unp_link)
2076                                 unp_gc_process(unp);
2077         } while (unp_marked);
2078         UNP_LIST_UNLOCK();
2079         if (unp_unreachable == 0)
2080                 return;
2081
2082         /*
2083          * Allocate space for a local list of dead unpcbs.
2084          */
2085         unref = malloc(unp_unreachable * sizeof(struct file *),
2086             M_TEMP, M_WAITOK);
2087
2088         /*
2089          * Iterate looking for sockets which have been specifically marked
2090          * as as unreachable and store them locally.
2091          */
2092         UNP_LIST_LOCK();
2093         for (i = 0, head = heads; *head != NULL; head++)
2094                 LIST_FOREACH(unp, *head, unp_link)
2095                         if (unp->unp_gcflag & UNPGC_DEAD) {
2096                                 unref[i++] = unp->unp_file;
2097                                 fhold(unp->unp_file);
2098                                 KASSERT(unp->unp_file != NULL,
2099                                     ("unp_gc: Invalid unpcb."));
2100                                 KASSERT(i <= unp_unreachable,
2101                                     ("unp_gc: incorrect unreachable count."));
2102                         }
2103         UNP_LIST_UNLOCK();
2104
2105         /*
2106          * Now flush all sockets, free'ing rights.  This will free the
2107          * struct files associated with these sockets but leave each socket
2108          * with one remaining ref.
2109          */
2110         for (i = 0; i < unp_unreachable; i++)
2111                 sorflush(unref[i]->f_data);
2112
2113         /*
2114          * And finally release the sockets so they can be reclaimed.
2115          */
2116         for (i = 0; i < unp_unreachable; i++)
2117                 fdrop(unref[i], NULL);
2118         unp_recycled += unp_unreachable;
2119         free(unref, M_TEMP);
2120 }
2121
2122 static void
2123 unp_dispose(struct mbuf *m)
2124 {
2125
2126         if (m)
2127                 unp_scan(m, unp_discard);
2128 }
2129
2130 static void
2131 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2132 {
2133         struct mbuf *m;
2134         struct file **rp;
2135         struct cmsghdr *cm;
2136         void *data;
2137         int i;
2138         socklen_t clen, datalen;
2139         int qfds;
2140
2141         while (m0 != NULL) {
2142                 for (m = m0; m; m = m->m_next) {
2143                         if (m->m_type != MT_CONTROL)
2144                                 continue;
2145
2146                         cm = mtod(m, struct cmsghdr *);
2147                         clen = m->m_len;
2148
2149                         while (cm != NULL) {
2150                                 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2151                                         break;
2152
2153                                 data = CMSG_DATA(cm);
2154                                 datalen = (caddr_t)cm + cm->cmsg_len
2155                                     - (caddr_t)data;
2156
2157                                 if (cm->cmsg_level == SOL_SOCKET &&
2158                                     cm->cmsg_type == SCM_RIGHTS) {
2159                                         qfds = datalen / sizeof (struct file *);
2160                                         rp = data;
2161                                         for (i = 0; i < qfds; i++)
2162                                                 (*op)(*rp++);
2163                                 }
2164
2165                                 if (CMSG_SPACE(datalen) < clen) {
2166                                         clen -= CMSG_SPACE(datalen);
2167                                         cm = (struct cmsghdr *)
2168                                             ((caddr_t)cm + CMSG_SPACE(datalen));
2169                                 } else {
2170                                         clen = 0;
2171                                         cm = NULL;
2172                                 }
2173                         }
2174                 }
2175                 m0 = m0->m_act;
2176         }
2177 }
2178
2179 #ifdef DDB
2180 static void
2181 db_print_indent(int indent)
2182 {
2183         int i;
2184
2185         for (i = 0; i < indent; i++)
2186                 db_printf(" ");
2187 }
2188
2189 static void
2190 db_print_unpflags(int unp_flags)
2191 {
2192         int comma;
2193
2194         comma = 0;
2195         if (unp_flags & UNP_HAVEPC) {
2196                 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2197                 comma = 1;
2198         }
2199         if (unp_flags & UNP_HAVEPCCACHED) {
2200                 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2201                 comma = 1;
2202         }
2203         if (unp_flags & UNP_WANTCRED) {
2204                 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2205                 comma = 1;
2206         }
2207         if (unp_flags & UNP_CONNWAIT) {
2208                 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2209                 comma = 1;
2210         }
2211         if (unp_flags & UNP_CONNECTING) {
2212                 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2213                 comma = 1;
2214         }
2215         if (unp_flags & UNP_BINDING) {
2216                 db_printf("%sUNP_BINDING", comma ? ", " : "");
2217                 comma = 1;
2218         }
2219 }
2220
2221 static void
2222 db_print_xucred(int indent, struct xucred *xu)
2223 {
2224         int comma, i;
2225
2226         db_print_indent(indent);
2227         db_printf("cr_version: %u   cr_uid: %u   cr_ngroups: %d\n",
2228             xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2229         db_print_indent(indent);
2230         db_printf("cr_groups: ");
2231         comma = 0;
2232         for (i = 0; i < xu->cr_ngroups; i++) {
2233                 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2234                 comma = 1;
2235         }
2236         db_printf("\n");
2237 }
2238
2239 static void
2240 db_print_unprefs(int indent, struct unp_head *uh)
2241 {
2242         struct unpcb *unp;
2243         int counter;
2244
2245         counter = 0;
2246         LIST_FOREACH(unp, uh, unp_reflink) {
2247                 if (counter % 4 == 0)
2248                         db_print_indent(indent);
2249                 db_printf("%p  ", unp);
2250                 if (counter % 4 == 3)
2251                         db_printf("\n");
2252                 counter++;
2253         }
2254         if (counter != 0 && counter % 4 != 0)
2255                 db_printf("\n");
2256 }
2257
2258 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2259 {
2260         struct unpcb *unp;
2261
2262         if (!have_addr) {
2263                 db_printf("usage: show unpcb <addr>\n");
2264                 return;
2265         }
2266         unp = (struct unpcb *)addr;
2267
2268         db_printf("unp_socket: %p   unp_vnode: %p\n", unp->unp_socket,
2269             unp->unp_vnode);
2270
2271         db_printf("unp_ino: %d   unp_conn: %p\n", unp->unp_ino,
2272             unp->unp_conn);
2273
2274         db_printf("unp_refs:\n");
2275         db_print_unprefs(2, &unp->unp_refs);
2276
2277         /* XXXRW: Would be nice to print the full address, if any. */
2278         db_printf("unp_addr: %p\n", unp->unp_addr);
2279
2280         db_printf("unp_cc: %d   unp_mbcnt: %d   unp_gencnt: %llu\n",
2281             unp->unp_cc, unp->unp_mbcnt,
2282             (unsigned long long)unp->unp_gencnt);
2283
2284         db_printf("unp_flags: %x (", unp->unp_flags);
2285         db_print_unpflags(unp->unp_flags);
2286         db_printf(")\n");
2287
2288         db_printf("unp_peercred:\n");
2289         db_print_xucred(2, &unp->unp_peercred);
2290
2291         db_printf("unp_refcount: %u\n", unp->unp_refcount);
2292 }
2293 #endif