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