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