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