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