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