The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/uipc_usrreq.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*      $NetBSD: uipc_usrreq.c,v 1.94.2.3 2009/04/10 20:32:04 snj Exp $ */
    2 
    3 /*-
    4  * Copyright (c) 1998, 2000, 2004 The NetBSD Foundation, Inc.
    5  * All rights reserved.
    6  *
    7  * This code is derived from software contributed to The NetBSD Foundation
    8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
    9  * NASA Ames Research Center.
   10  *
   11  * Redistribution and use in source and binary forms, with or without
   12  * modification, are permitted provided that the following conditions
   13  * are met:
   14  * 1. Redistributions of source code must retain the above copyright
   15  *    notice, this list of conditions and the following disclaimer.
   16  * 2. Redistributions in binary form must reproduce the above copyright
   17  *    notice, this list of conditions and the following disclaimer in the
   18  *    documentation and/or other materials provided with the distribution.
   19  * 3. All advertising materials mentioning features or use of this software
   20  *    must display the following acknowledgement:
   21  *      This product includes software developed by the NetBSD
   22  *      Foundation, Inc. and its contributors.
   23  * 4. Neither the name of The NetBSD Foundation nor the names of its
   24  *    contributors may be used to endorse or promote products derived
   25  *    from this software without specific prior written permission.
   26  *
   27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
   28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
   31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   37  * POSSIBILITY OF SUCH DAMAGE.
   38  */
   39 
   40 /*
   41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
   42  *      The Regents of the University of California.  All rights reserved.
   43  *
   44  * Redistribution and use in source and binary forms, with or without
   45  * modification, are permitted provided that the following conditions
   46  * are met:
   47  * 1. Redistributions of source code must retain the above copyright
   48  *    notice, this list of conditions and the following disclaimer.
   49  * 2. Redistributions in binary form must reproduce the above copyright
   50  *    notice, this list of conditions and the following disclaimer in the
   51  *    documentation and/or other materials provided with the distribution.
   52  * 3. Neither the name of the University nor the names of its contributors
   53  *    may be used to endorse or promote products derived from this software
   54  *    without specific prior written permission.
   55  *
   56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   66  * SUCH DAMAGE.
   67  *
   68  *      @(#)uipc_usrreq.c       8.9 (Berkeley) 5/14/95
   69  */
   70 
   71 /*
   72  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
   73  *
   74  * Redistribution and use in source and binary forms, with or without
   75  * modification, are permitted provided that the following conditions
   76  * are met:
   77  * 1. Redistributions of source code must retain the above copyright
   78  *    notice, this list of conditions and the following disclaimer.
   79  * 2. Redistributions in binary form must reproduce the above copyright
   80  *    notice, this list of conditions and the following disclaimer in the
   81  *    documentation and/or other materials provided with the distribution.
   82  * 3. All advertising materials mentioning features or use of this software
   83  *    must display the following acknowledgement:
   84  *      This product includes software developed by the University of
   85  *      California, Berkeley and its contributors.
   86  * 4. Neither the name of the University nor the names of its contributors
   87  *    may be used to endorse or promote products derived from this software
   88  *    without specific prior written permission.
   89  *
   90  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   91  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   92  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   93  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   94  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   95  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   96  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   97  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   98  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   99  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  100  * SUCH DAMAGE.
  101  *
  102  *      @(#)uipc_usrreq.c       8.9 (Berkeley) 5/14/95
  103  */
  104 
  105 #include <sys/cdefs.h>
  106 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.94.2.3 2009/04/10 20:32:04 snj Exp $");
  107 
  108 #include <sys/param.h>
  109 #include <sys/systm.h>
  110 #include <sys/proc.h>
  111 #include <sys/filedesc.h>
  112 #include <sys/domain.h>
  113 #include <sys/protosw.h>
  114 #include <sys/socket.h>
  115 #include <sys/socketvar.h>
  116 #include <sys/unpcb.h>
  117 #include <sys/un.h>
  118 #include <sys/namei.h>
  119 #include <sys/vnode.h>
  120 #include <sys/file.h>
  121 #include <sys/stat.h>
  122 #include <sys/mbuf.h>
  123 #include <sys/kauth.h>
  124 
  125 /*
  126  * Unix communications domain.
  127  *
  128  * TODO:
  129  *      SEQPACKET, RDM
  130  *      rethink name space problems
  131  *      need a proper out-of-band
  132  */
  133 const struct sockaddr_un sun_noname = {
  134         .sun_len = sizeof(sun_noname),
  135         .sun_family = AF_LOCAL,
  136 };
  137 ino_t   unp_ino;                        /* prototype for fake inode numbers */
  138 
  139 struct mbuf *unp_addsockcred(struct lwp *, struct mbuf *);
  140 
  141 int
  142 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp,
  143         struct lwp *l)
  144 {
  145         struct socket *so2;
  146         const struct sockaddr_un *sun;
  147 
  148         so2 = unp->unp_conn->unp_socket;
  149         if (unp->unp_addr)
  150                 sun = unp->unp_addr;
  151         else
  152                 sun = &sun_noname;
  153         if (unp->unp_conn->unp_flags & UNP_WANTCRED)
  154                 control = unp_addsockcred(l, control);
  155         if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m,
  156             control) == 0) {
  157                 unp_dispose(control);
  158                 m_freem(control);
  159                 m_freem(m);
  160                 so2->so_rcv.sb_overflowed++;
  161                 return (ENOBUFS);
  162         } else {
  163                 sorwakeup(so2);
  164                 return (0);
  165         }
  166 }
  167 
  168 void
  169 unp_setsockaddr(struct unpcb *unp, struct mbuf *nam)
  170 {
  171         const struct sockaddr_un *sun;
  172 
  173         if (unp->unp_addr)
  174                 sun = unp->unp_addr;
  175         else
  176                 sun = &sun_noname;
  177         nam->m_len = sun->sun_len;
  178         if (nam->m_len > MLEN)
  179                 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
  180         memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
  181 }
  182 
  183 void
  184 unp_setpeeraddr(struct unpcb *unp, struct mbuf *nam)
  185 {
  186         const struct sockaddr_un *sun;
  187 
  188         if (unp->unp_conn && unp->unp_conn->unp_addr)
  189                 sun = unp->unp_conn->unp_addr;
  190         else
  191                 sun = &sun_noname;
  192         nam->m_len = sun->sun_len;
  193         if (nam->m_len > MLEN)
  194                 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
  195         memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
  196 }
  197 
  198 /*ARGSUSED*/
  199 int
  200 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
  201         struct mbuf *control, struct lwp *l)
  202 {
  203         struct unpcb *unp = sotounpcb(so);
  204         struct socket *so2;
  205         struct proc *p;
  206         u_int newhiwat;
  207         int error = 0;
  208 
  209         if (req == PRU_CONTROL)
  210                 return (EOPNOTSUPP);
  211 
  212 #ifdef DIAGNOSTIC
  213         if (req != PRU_SEND && req != PRU_SENDOOB && control)
  214                 panic("uipc_usrreq: unexpected control mbuf");
  215 #endif
  216         p = l ? l->l_proc : NULL;
  217         if (unp == 0 && req != PRU_ATTACH) {
  218                 error = EINVAL;
  219                 goto release;
  220         }
  221 
  222         switch (req) {
  223 
  224         case PRU_ATTACH:
  225                 if (unp != 0) {
  226                         error = EISCONN;
  227                         break;
  228                 }
  229                 error = unp_attach(so);
  230                 break;
  231 
  232         case PRU_DETACH:
  233                 unp_detach(unp);
  234                 break;
  235 
  236         case PRU_BIND:
  237                 KASSERT(l != NULL);
  238                 error = unp_bind(unp, nam, l);
  239                 break;
  240 
  241         case PRU_LISTEN:
  242                 if (unp->unp_vnode == 0)
  243                         error = EINVAL;
  244                 break;
  245 
  246         case PRU_CONNECT:
  247                 KASSERT(l != NULL);
  248                 error = unp_connect(so, nam, l);
  249                 break;
  250 
  251         case PRU_CONNECT2:
  252                 error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
  253                 break;
  254 
  255         case PRU_DISCONNECT:
  256                 unp_disconnect(unp);
  257                 break;
  258 
  259         case PRU_ACCEPT:
  260                 unp_setpeeraddr(unp, nam);
  261                 /*
  262                  * Mark the initiating STREAM socket as connected *ONLY*
  263                  * after it's been accepted.  This prevents a client from
  264                  * overrunning a server and receiving ECONNREFUSED.
  265                  */
  266                 if (unp->unp_conn != NULL &&
  267                     (unp->unp_conn->unp_socket->so_state & SS_ISCONNECTING))
  268                         soisconnected(unp->unp_conn->unp_socket);
  269                 break;
  270 
  271         case PRU_SHUTDOWN:
  272                 socantsendmore(so);
  273                 unp_shutdown(unp);
  274                 break;
  275 
  276         case PRU_RCVD:
  277                 switch (so->so_type) {
  278 
  279                 case SOCK_DGRAM:
  280                         panic("uipc 1");
  281                         /*NOTREACHED*/
  282 
  283                 case SOCK_STREAM:
  284 #define rcv (&so->so_rcv)
  285 #define snd (&so2->so_snd)
  286                         if (unp->unp_conn == 0)
  287                                 break;
  288                         so2 = unp->unp_conn->unp_socket;
  289                         /*
  290                          * Adjust backpressure on sender
  291                          * and wakeup any waiting to write.
  292                          */
  293                         snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
  294                         unp->unp_mbcnt = rcv->sb_mbcnt;
  295                         newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
  296                         (void)chgsbsize(so2->so_uidinfo,
  297                             &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
  298                         unp->unp_cc = rcv->sb_cc;
  299                         sowwakeup(so2);
  300 #undef snd
  301 #undef rcv
  302                         break;
  303 
  304                 default:
  305                         panic("uipc 2");
  306                 }
  307                 break;
  308 
  309         case PRU_SEND:
  310                 /*
  311                  * Note: unp_internalize() rejects any control message
  312                  * other than SCM_RIGHTS, and only allows one.  This
  313                  * has the side-effect of preventing a caller from
  314                  * forging SCM_CREDS.
  315                  */
  316                 if (control) {
  317                         KASSERT(l != NULL);
  318                         if ((error = unp_internalize(control, l)) != 0) {
  319                                 m_freem(control);
  320                                 m_freem(m);
  321                                 break;
  322                         }
  323                 }
  324                 switch (so->so_type) {
  325 
  326                 case SOCK_DGRAM: {
  327                         if (nam) {
  328                                 if ((so->so_state & SS_ISCONNECTED) != 0)
  329                                         error = EISCONN;
  330                                 else {
  331                                         KASSERT(l != NULL);
  332                                         error = unp_connect(so, nam, l);
  333                                 }
  334                         } else {
  335                                 if ((so->so_state & SS_ISCONNECTED) == 0)
  336                                         error = ENOTCONN;
  337                         }
  338                         if (error) {
  339                                 unp_dispose(control);
  340                                 m_freem(control);
  341                                 m_freem(m);
  342                                 break;
  343                         }
  344                         KASSERT(p != NULL);
  345                         error = unp_output(m, control, unp, l);
  346                         if (nam)
  347                                 unp_disconnect(unp);
  348                         break;
  349                 }
  350 
  351                 case SOCK_STREAM:
  352 #define rcv (&so2->so_rcv)
  353 #define snd (&so->so_snd)
  354                         if (unp->unp_conn == NULL) {
  355                                 error = ENOTCONN;
  356                                 break;
  357                         }
  358                         so2 = unp->unp_conn->unp_socket;
  359                         if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
  360                                 /*
  361                                  * Credentials are passed only once on
  362                                  * SOCK_STREAM.
  363                                  */
  364                                 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
  365                                 control = unp_addsockcred(l, control);
  366                         }
  367                         /*
  368                          * Send to paired receive port, and then reduce
  369                          * send buffer hiwater marks to maintain backpressure.
  370                          * Wake up readers.
  371                          */
  372                         if (control) {
  373                                 if (sbappendcontrol(rcv, m, control) == 0) {
  374                                         unp_dispose(control);
  375                                         m_freem(control);
  376                                 }
  377                         } else
  378                                 sbappend(rcv, m);
  379                         snd->sb_mbmax -=
  380                             rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
  381                         unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
  382                         newhiwat = snd->sb_hiwat -
  383                             (rcv->sb_cc - unp->unp_conn->unp_cc);
  384                         (void)chgsbsize(so->so_uidinfo,
  385                             &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
  386                         unp->unp_conn->unp_cc = rcv->sb_cc;
  387                         sorwakeup(so2);
  388 #undef snd
  389 #undef rcv
  390                         break;
  391 
  392                 default:
  393                         panic("uipc 4");
  394                 }
  395                 break;
  396 
  397         case PRU_ABORT:
  398                 unp_drop(unp, ECONNABORTED);
  399 
  400                 KASSERT(so->so_head == NULL);
  401 #ifdef DIAGNOSTIC
  402                 if (so->so_pcb == 0)
  403                         panic("uipc 5: drop killed pcb");
  404 #endif
  405                 unp_detach(unp);
  406                 break;
  407 
  408         case PRU_SENSE:
  409                 ((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
  410                 if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
  411                         so2 = unp->unp_conn->unp_socket;
  412                         ((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
  413                 }
  414                 ((struct stat *) m)->st_dev = NODEV;
  415                 if (unp->unp_ino == 0)
  416                         unp->unp_ino = unp_ino++;
  417                 ((struct stat *) m)->st_atimespec =
  418                     ((struct stat *) m)->st_mtimespec =
  419                     ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
  420                 ((struct stat *) m)->st_ino = unp->unp_ino;
  421                 return (0);
  422 
  423         case PRU_RCVOOB:
  424                 error = EOPNOTSUPP;
  425                 break;
  426 
  427         case PRU_SENDOOB:
  428                 m_freem(control);
  429                 m_freem(m);
  430                 error = EOPNOTSUPP;
  431                 break;
  432 
  433         case PRU_SOCKADDR:
  434                 unp_setsockaddr(unp, nam);
  435                 break;
  436 
  437         case PRU_PEERADDR:
  438                 unp_setpeeraddr(unp, nam);
  439                 break;
  440 
  441         default:
  442                 panic("piusrreq");
  443         }
  444 
  445 release:
  446         return (error);
  447 }
  448 
  449 /*
  450  * Unix domain socket option processing.
  451  */
  452 int
  453 uipc_ctloutput(int op, struct socket *so, int level, int optname,
  454         struct mbuf **mp)
  455 {
  456         struct unpcb *unp = sotounpcb(so);
  457         struct mbuf *m = *mp;
  458         int optval = 0, error = 0;
  459 
  460         if (level != 0) {
  461                 error = EINVAL;
  462                 if (op == PRCO_SETOPT && m)
  463                         (void) m_free(m);
  464         } else switch (op) {
  465 
  466         case PRCO_SETOPT:
  467                 switch (optname) {
  468                 case LOCAL_CREDS:
  469                 case LOCAL_CONNWAIT:
  470                         if (m == NULL || m->m_len != sizeof(int))
  471                                 error = EINVAL;
  472                         else {
  473                                 optval = *mtod(m, int *);
  474                                 switch (optname) {
  475 #define OPTSET(bit) \
  476         if (optval) \
  477                 unp->unp_flags |= (bit); \
  478         else \
  479                 unp->unp_flags &= ~(bit);
  480 
  481                                 case LOCAL_CREDS:
  482                                         OPTSET(UNP_WANTCRED);
  483                                         break;
  484                                 case LOCAL_CONNWAIT:
  485                                         OPTSET(UNP_CONNWAIT);
  486                                         break;
  487                                 }
  488                         }
  489                         break;
  490 #undef OPTSET
  491 
  492                 default:
  493                         error = ENOPROTOOPT;
  494                         break;
  495                 }
  496                 if (m)
  497                         (void) m_free(m);
  498                 break;
  499 
  500         case PRCO_GETOPT:
  501                 switch (optname) {
  502                 case LOCAL_CREDS:
  503                         *mp = m = m_get(M_WAIT, MT_SOOPTS);
  504                         m->m_len = sizeof(int);
  505                         switch (optname) {
  506 
  507 #define OPTBIT(bit)     (unp->unp_flags & (bit) ? 1 : 0)
  508 
  509                         case LOCAL_CREDS:
  510                                 optval = OPTBIT(UNP_WANTCRED);
  511                                 break;
  512                         }
  513                         *mtod(m, int *) = optval;
  514                         break;
  515 #undef OPTBIT
  516 
  517                 default:
  518                         error = ENOPROTOOPT;
  519                         break;
  520                 }
  521                 break;
  522         }
  523         return (error);
  524 }
  525 
  526 /*
  527  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
  528  * for stream sockets, although the total for sender and receiver is
  529  * actually only PIPSIZ.
  530  * Datagram sockets really use the sendspace as the maximum datagram size,
  531  * and don't really want to reserve the sendspace.  Their recvspace should
  532  * be large enough for at least one max-size datagram plus address.
  533  */
  534 #define PIPSIZ  4096
  535 u_long  unpst_sendspace = PIPSIZ;
  536 u_long  unpst_recvspace = PIPSIZ;
  537 u_long  unpdg_sendspace = 2*1024;       /* really max datagram size */
  538 u_long  unpdg_recvspace = 4*1024;
  539 
  540 int     unp_rights;                     /* file descriptors in flight */
  541 int     unp_rights_ratio = 2;           /* limit, fraction of maxfiles */
  542 
  543 int
  544 unp_attach(struct socket *so)
  545 {
  546         struct unpcb *unp;
  547         int error;
  548 
  549         if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
  550                 switch (so->so_type) {
  551 
  552                 case SOCK_STREAM:
  553                         error = soreserve(so, unpst_sendspace, unpst_recvspace);
  554                         break;
  555 
  556                 case SOCK_DGRAM:
  557                         error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
  558                         break;
  559 
  560                 default:
  561                         panic("unp_attach");
  562                 }
  563                 if (error)
  564                         return (error);
  565         }
  566         unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
  567         if (unp == NULL)
  568                 return (ENOBUFS);
  569         memset((caddr_t)unp, 0, sizeof(*unp));
  570         unp->unp_socket = so;
  571         so->so_pcb = unp;
  572         nanotime(&unp->unp_ctime);
  573         return (0);
  574 }
  575 
  576 void
  577 unp_detach(struct unpcb *unp)
  578 {
  579 
  580         if (unp->unp_vnode) {
  581                 unp->unp_vnode->v_socket = 0;
  582                 vrele(unp->unp_vnode);
  583                 unp->unp_vnode = 0;
  584         }
  585         if (unp->unp_conn)
  586                 unp_disconnect(unp);
  587         while (unp->unp_refs)
  588                 unp_drop(unp->unp_refs, ECONNRESET);
  589         soisdisconnected(unp->unp_socket);
  590         unp->unp_socket->so_pcb = 0;
  591         if (unp->unp_addr)
  592                 free(unp->unp_addr, M_SONAME);
  593         if (unp_rights) {
  594                 /*
  595                  * Normally the receive buffer is flushed later,
  596                  * in sofree, but if our receive buffer holds references
  597                  * to descriptors that are now garbage, we will dispose
  598                  * of those descriptor references after the garbage collector
  599                  * gets them (resulting in a "panic: closef: count < 0").
  600                  */
  601                 sorflush(unp->unp_socket);
  602                 free(unp, M_PCB);
  603                 unp_gc();
  604         } else
  605                 free(unp, M_PCB);
  606 }
  607 
  608 int
  609 unp_bind(struct unpcb *unp, struct mbuf *nam, struct lwp *l)
  610 {
  611         struct sockaddr_un *sun;
  612         struct vnode *vp;
  613         struct mount *mp;
  614         struct vattr vattr;
  615         size_t addrlen;
  616         struct proc *p;
  617         int error;
  618         struct nameidata nd;
  619 
  620         if (unp->unp_vnode != 0)
  621                 return (EINVAL);
  622 
  623         p = l->l_proc;
  624         /*
  625          * Allocate the new sockaddr.  We have to allocate one
  626          * extra byte so that we can ensure that the pathname
  627          * is nul-terminated.
  628          */
  629         addrlen = nam->m_len + 1;
  630         sun = malloc(addrlen, M_SONAME, M_WAITOK);
  631         m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
  632         *(((char *)sun) + nam->m_len) = '\0';
  633 
  634 restart:
  635         NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
  636             sun->sun_path, l);
  637 
  638 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
  639         if ((error = namei(&nd)) != 0)
  640                 goto bad;
  641         vp = nd.ni_vp;
  642         if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
  643                 VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
  644                 if (nd.ni_dvp == vp)
  645                         vrele(nd.ni_dvp);
  646                 else
  647                         vput(nd.ni_dvp);
  648                 vrele(vp);
  649                 if (vp != NULL) {
  650                         error = EADDRINUSE;
  651                         goto bad;
  652                 }
  653                 error = vn_start_write(NULL, &mp,
  654                     V_WAIT | V_SLEEPONLY | V_PCATCH);
  655                 if (error)
  656                         goto bad;
  657                 goto restart;
  658         }
  659         VATTR_NULL(&vattr);
  660         vattr.va_type = VSOCK;
  661         vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
  662         VOP_LEASE(nd.ni_dvp, l, l->l_cred, LEASE_WRITE);
  663         error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
  664         vn_finished_write(mp, 0);
  665         if (error)
  666                 goto bad;
  667         vp = nd.ni_vp;
  668         vp->v_socket = unp->unp_socket;
  669         unp->unp_vnode = vp;
  670         unp->unp_addrlen = addrlen;
  671         unp->unp_addr = sun;
  672         VOP_UNLOCK(vp, 0);
  673         return (0);
  674 
  675  bad:
  676         free(sun, M_SONAME);
  677         return (error);
  678 }
  679 
  680 int
  681 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
  682 {
  683         struct sockaddr_un *sun;
  684         struct vnode *vp;
  685         struct socket *so2, *so3;
  686         struct unpcb *unp2, *unp3;
  687         size_t addrlen;
  688         int error;
  689         struct nameidata nd;
  690 
  691         /*
  692          * Allocate a temporary sockaddr.  We have to allocate one extra
  693          * byte so that we can ensure that the pathname is nul-terminated.
  694          * When we establish the connection, we copy the other PCB's
  695          * sockaddr to our own.
  696          */
  697         addrlen = nam->m_len + 1;
  698         sun = malloc(addrlen, M_SONAME, M_WAITOK);
  699         m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
  700         *(((char *)sun) + nam->m_len) = '\0';
  701 
  702         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, sun->sun_path, l);
  703 
  704         if ((error = namei(&nd)) != 0)
  705                 goto bad2;
  706         vp = nd.ni_vp;
  707         if (vp->v_type != VSOCK) {
  708                 error = ENOTSOCK;
  709                 goto bad;
  710         }
  711         if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred, l)) != 0)
  712                 goto bad;
  713         so2 = vp->v_socket;
  714         if (so2 == 0) {
  715                 error = ECONNREFUSED;
  716                 goto bad;
  717         }
  718         if (so->so_type != so2->so_type) {
  719                 error = EPROTOTYPE;
  720                 goto bad;
  721         }
  722         if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
  723                 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
  724                     (so3 = sonewconn(so2, 0)) == 0) {
  725                         error = ECONNREFUSED;
  726                         goto bad;
  727                 }
  728                 unp2 = sotounpcb(so2);
  729                 unp3 = sotounpcb(so3);
  730                 if (unp2->unp_addr) {
  731                         unp3->unp_addr = malloc(unp2->unp_addrlen,
  732                             M_SONAME, M_WAITOK);
  733                         memcpy(unp3->unp_addr, unp2->unp_addr,
  734                             unp2->unp_addrlen);
  735                         unp3->unp_addrlen = unp2->unp_addrlen;
  736                 }
  737                 unp3->unp_flags = unp2->unp_flags;
  738                 so2 = so3;
  739         }
  740         error = unp_connect2(so, so2, PRU_CONNECT);
  741  bad:
  742         vput(vp);
  743  bad2:
  744         free(sun, M_SONAME);
  745         return (error);
  746 }
  747 
  748 int
  749 unp_connect2(struct socket *so, struct socket *so2, int req)
  750 {
  751         struct unpcb *unp = sotounpcb(so);
  752         struct unpcb *unp2;
  753 
  754         if (so2->so_type != so->so_type)
  755                 return (EPROTOTYPE);
  756         unp2 = sotounpcb(so2);
  757         unp->unp_conn = unp2;
  758         switch (so->so_type) {
  759 
  760         case SOCK_DGRAM:
  761                 unp->unp_nextref = unp2->unp_refs;
  762                 unp2->unp_refs = unp;
  763                 soisconnected(so);
  764                 break;
  765 
  766         case SOCK_STREAM:
  767                 unp2->unp_conn = unp;
  768                 if (req == PRU_CONNECT &&
  769                     ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
  770                         soisconnecting(so);
  771                 else
  772                         soisconnected(so);
  773                 soisconnected(so2);
  774                 break;
  775 
  776         default:
  777                 panic("unp_connect2");
  778         }
  779         return (0);
  780 }
  781 
  782 void
  783 unp_disconnect(struct unpcb *unp)
  784 {
  785         struct unpcb *unp2 = unp->unp_conn;
  786 
  787         if (unp2 == 0)
  788                 return;
  789         unp->unp_conn = 0;
  790         switch (unp->unp_socket->so_type) {
  791 
  792         case SOCK_DGRAM:
  793                 if (unp2->unp_refs == unp)
  794                         unp2->unp_refs = unp->unp_nextref;
  795                 else {
  796                         unp2 = unp2->unp_refs;
  797                         for (;;) {
  798                                 if (unp2 == 0)
  799                                         panic("unp_disconnect");
  800                                 if (unp2->unp_nextref == unp)
  801                                         break;
  802                                 unp2 = unp2->unp_nextref;
  803                         }
  804                         unp2->unp_nextref = unp->unp_nextref;
  805                 }
  806                 unp->unp_nextref = 0;
  807                 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
  808                 break;
  809 
  810         case SOCK_STREAM:
  811                 soisdisconnected(unp->unp_socket);
  812                 unp2->unp_conn = 0;
  813                 soisdisconnected(unp2->unp_socket);
  814                 break;
  815         }
  816 }
  817 
  818 #ifdef notdef
  819 unp_abort(struct unpcb *unp)
  820 {
  821         unp_detach(unp);
  822 }
  823 #endif
  824 
  825 void
  826 unp_shutdown(struct unpcb *unp)
  827 {
  828         struct socket *so;
  829 
  830         if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
  831             (so = unp->unp_conn->unp_socket))
  832                 socantrcvmore(so);
  833 }
  834 
  835 void
  836 unp_drop(struct unpcb *unp, int errno)
  837 {
  838         struct socket *so = unp->unp_socket;
  839 
  840         so->so_error = errno;
  841         unp_disconnect(unp);
  842         if (so->so_head) {
  843                 so->so_pcb = 0;
  844                 sofree(so);
  845                 if (unp->unp_addr)
  846                         free(unp->unp_addr, M_SONAME);
  847                 free(unp, M_PCB);
  848         }
  849 }
  850 
  851 #ifdef notdef
  852 unp_drain(void)
  853 {
  854 
  855 }
  856 #endif
  857 
  858 int
  859 unp_externalize(struct mbuf *rights, struct lwp *l)
  860 {
  861         struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
  862         struct proc *p = l->l_proc;
  863         int i, *fdp;
  864         struct file **rp;
  865         struct file *fp;
  866         int nfds, error = 0;
  867 
  868         nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
  869             sizeof(struct file *);
  870         rp = (struct file **)CMSG_DATA(cm);
  871 
  872         fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
  873 
  874         /* Make sure the recipient should be able to see the descriptors.. */
  875         if (p->p_cwdi->cwdi_rdir != NULL) {
  876                 rp = (struct file **)CMSG_DATA(cm);
  877                 for (i = 0; i < nfds; i++) {
  878                         fp = *rp++;
  879                         /*
  880                          * If we are in a chroot'ed directory, and
  881                          * someone wants to pass us a directory, make
  882                          * sure it's inside the subtree we're allowed
  883                          * to access.
  884                          */
  885                         if (fp->f_type == DTYPE_VNODE) {
  886                                 struct vnode *vp = (struct vnode *)fp->f_data;
  887                                 if ((vp->v_type == VDIR) &&
  888                                     !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
  889                                         error = EPERM;
  890                                         break;
  891                                 }
  892                         }
  893                 }
  894         }
  895 
  896  restart:
  897         rp = (struct file **)CMSG_DATA(cm);
  898         if (error != 0) {
  899                 for (i = 0; i < nfds; i++) {
  900                         fp = *rp;
  901                         /*
  902                          * zero the pointer before calling unp_discard,
  903                          * since it may end up in unp_gc()..
  904                          */
  905                         *rp++ = 0;
  906                         unp_discard(fp);
  907                 }
  908                 goto out;
  909         }
  910 
  911         /*
  912          * First loop -- allocate file descriptor table slots for the
  913          * new descriptors.
  914          */
  915         for (i = 0; i < nfds; i++) {
  916                 fp = *rp++;
  917                 if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
  918                         /*
  919                          * Back out what we've done so far.
  920                          */
  921                         for (--i; i >= 0; i--)
  922                                 fdremove(p->p_fd, fdp[i]);
  923 
  924                         if (error == ENOSPC) {
  925                                 fdexpand(p);
  926                                 error = 0;
  927                         } else {
  928                                 /*
  929                                  * This is the error that has historically
  930                                  * been returned, and some callers may
  931                                  * expect it.
  932                                  */
  933                                 error = EMSGSIZE;
  934                         }
  935                         goto restart;
  936                 }
  937 
  938                 /*
  939                  * Make the slot reference the descriptor so that
  940                  * fdalloc() works properly.. We finalize it all
  941                  * in the loop below.
  942                  */
  943                 p->p_fd->fd_ofiles[fdp[i]] = fp;
  944         }
  945 
  946         /*
  947          * Now that adding them has succeeded, update all of the
  948          * descriptor passing state.
  949          */
  950         rp = (struct file **)CMSG_DATA(cm);
  951         for (i = 0; i < nfds; i++) {
  952                 fp = *rp++;
  953                 fp->f_msgcount--;
  954                 unp_rights--;
  955         }
  956 
  957         /*
  958          * Copy temporary array to message and adjust length, in case of
  959          * transition from large struct file pointers to ints.
  960          */
  961         memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
  962         cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
  963         rights->m_len = CMSG_SPACE(nfds * sizeof(int));
  964  out:
  965         free(fdp, M_TEMP);
  966         return (error);
  967 }
  968 
  969 int
  970 unp_internalize(struct mbuf *control, struct lwp *l)
  971 {
  972         struct proc *p = l->l_proc;
  973         struct filedesc *fdescp = p->p_fd;
  974         struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
  975         struct file **rp, **files;
  976         struct file *fp;
  977         int i, fd, *fdp;
  978         int nfds;
  979         u_int neededspace;
  980         u_int maxmsg;
  981 
  982         /* Sanity check the control message header */
  983         if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
  984             cm->cmsg_len != control->m_len)
  985                 return (EINVAL);
  986 
  987         /* Verify that the file descriptors are valid */
  988         nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
  989 
  990         maxmsg = maxfiles / unp_rights_ratio;
  991         if (unp_rights + nfds > maxmsg)
  992                 return (EAGAIN);
  993 
  994         fdp = (int *)CMSG_DATA(cm);
  995         for (i = 0; i < nfds; i++) {
  996                 fd = *fdp++;
  997                 if ((fp = fd_getfile(fdescp, fd)) == NULL)
  998                         return (EBADF);
  999                 simple_unlock(&fp->f_slock);
 1000         }
 1001 
 1002         /* Make sure we have room for the struct file pointers */
 1003         neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
 1004             control->m_len;
 1005         if (neededspace > M_TRAILINGSPACE(control)) {
 1006 
 1007                 /* allocate new space and copy header into it */
 1008                 newcm = malloc(
 1009                     CMSG_SPACE(nfds * sizeof(struct file *)),
 1010                     M_MBUF, M_WAITOK);
 1011                 if (newcm == NULL)
 1012                         return (E2BIG);
 1013                 memcpy(newcm, cm, sizeof(struct cmsghdr));
 1014                 files = (struct file **)CMSG_DATA(newcm);
 1015         } else {
 1016                 /* we can convert in-place */
 1017                 newcm = NULL;
 1018                 files = (struct file **)CMSG_DATA(cm);
 1019         }
 1020 
 1021         /*
 1022          * Transform the file descriptors into struct file pointers, in
 1023          * reverse order so that if pointers are bigger than ints, the
 1024          * int won't get until we're done.
 1025          */
 1026         fdp = (int *)CMSG_DATA(cm) + nfds;
 1027         rp = files + nfds;
 1028         for (i = 0; i < nfds; i++) {
 1029                 fp = fdescp->fd_ofiles[*--fdp];
 1030                 simple_lock(&fp->f_slock);
 1031 #ifdef DIAGNOSTIC
 1032                 if (fp->f_iflags & FIF_WANTCLOSE)
 1033                         panic("unp_internalize: file already closed");
 1034 #endif
 1035                 *--rp = fp;
 1036                 fp->f_count++;
 1037                 fp->f_msgcount++;
 1038                 simple_unlock(&fp->f_slock);
 1039                 unp_rights++;
 1040         }
 1041 
 1042         if (newcm) {
 1043                 if (control->m_flags & M_EXT)
 1044                         MEXTREMOVE(control);
 1045                 MEXTADD(control, newcm,
 1046                     CMSG_SPACE(nfds * sizeof(struct file *)),
 1047                     M_MBUF, NULL, NULL);
 1048                 cm = newcm;
 1049         }
 1050 
 1051         /* adjust message & mbuf to note amount of space actually used. */
 1052         cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
 1053         control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
 1054 
 1055         return (0);
 1056 }
 1057 
 1058 struct mbuf *
 1059 unp_addsockcred(struct lwp *l, struct mbuf *control)
 1060 {
 1061         struct cmsghdr *cmp;
 1062         struct sockcred *sc;
 1063         struct mbuf *m, *n;
 1064         int len, space, i;
 1065 
 1066         len = CMSG_LEN(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)));
 1067         space = CMSG_SPACE(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)));
 1068 
 1069         m = m_get(M_WAIT, MT_CONTROL);
 1070         if (space > MLEN) {
 1071                 if (space > MCLBYTES)
 1072                         MEXTMALLOC(m, space, M_WAITOK);
 1073                 else
 1074                         m_clget(m, M_WAIT);
 1075                 if ((m->m_flags & M_EXT) == 0) {
 1076                         m_free(m);
 1077                         return (control);
 1078                 }
 1079         }
 1080 
 1081         m->m_len = space;
 1082         m->m_next = NULL;
 1083         cmp = mtod(m, struct cmsghdr *);
 1084         sc = (struct sockcred *)CMSG_DATA(cmp);
 1085         cmp->cmsg_len = len;
 1086         cmp->cmsg_level = SOL_SOCKET;
 1087         cmp->cmsg_type = SCM_CREDS;
 1088         sc->sc_uid = kauth_cred_getuid(l->l_cred);
 1089         sc->sc_euid = kauth_cred_geteuid(l->l_cred);
 1090         sc->sc_gid = kauth_cred_getgid(l->l_cred);
 1091         sc->sc_egid = kauth_cred_getegid(l->l_cred);
 1092         sc->sc_ngroups = kauth_cred_ngroups(l->l_cred);
 1093         for (i = 0; i < sc->sc_ngroups; i++)
 1094                 sc->sc_groups[i] = kauth_cred_group(l->l_cred, i);
 1095 
 1096         /*
 1097          * If a control message already exists, append us to the end.
 1098          */
 1099         if (control != NULL) {
 1100                 for (n = control; n->m_next != NULL; n = n->m_next)
 1101                         ;
 1102                 n->m_next = m;
 1103         } else
 1104                 control = m;
 1105 
 1106         return (control);
 1107 }
 1108 
 1109 int     unp_defer, unp_gcing;
 1110 extern  struct domain unixdomain;
 1111 
 1112 /*
 1113  * Comment added long after the fact explaining what's going on here.
 1114  * Do a mark-sweep GC of file descriptors on the system, to free up
 1115  * any which are caught in flight to an about-to-be-closed socket.
 1116  *
 1117  * Traditional mark-sweep gc's start at the "root", and mark
 1118  * everything reachable from the root (which, in our case would be the
 1119  * process table).  The mark bits are cleared during the sweep.
 1120  *
 1121  * XXX For some inexplicable reason (perhaps because the file
 1122  * descriptor tables used to live in the u area which could be swapped
 1123  * out and thus hard to reach), we do multiple scans over the set of
 1124  * descriptors, using use *two* mark bits per object (DEFER and MARK).
 1125  * Whenever we find a descriptor which references other descriptors,
 1126  * the ones it references are marked with both bits, and we iterate
 1127  * over the whole file table until there are no more DEFER bits set.
 1128  * We also make an extra pass *before* the GC to clear the mark bits,
 1129  * which could have been cleared at almost no cost during the previous
 1130  * sweep.
 1131  *
 1132  * XXX MP: this needs to run with locks such that no other thread of
 1133  * control can create or destroy references to file descriptors. it
 1134  * may be necessary to defer the GC until later (when the locking
 1135  * situation is more hospitable); it may be necessary to push this
 1136  * into a separate thread.
 1137  */
 1138 void
 1139 unp_gc(void)
 1140 {
 1141         struct file *fp, *nextfp;
 1142         struct socket *so, *so1;
 1143         struct file **extra_ref, **fpp;
 1144         int nunref, i;
 1145 
 1146         if (unp_gcing)
 1147                 return;
 1148         unp_gcing = 1;
 1149         unp_defer = 0;
 1150 
 1151         /* Clear mark bits */
 1152         LIST_FOREACH(fp, &filehead, f_list)
 1153                 fp->f_flag &= ~(FMARK|FDEFER);
 1154 
 1155         /*
 1156          * Iterate over the set of descriptors, marking ones believed
 1157          * (based on refcount) to be referenced from a process, and
 1158          * marking for rescan descriptors which are queued on a socket.
 1159          */
 1160         do {
 1161                 LIST_FOREACH(fp, &filehead, f_list) {
 1162                         if (fp->f_flag & FDEFER) {
 1163                                 fp->f_flag &= ~FDEFER;
 1164                                 unp_defer--;
 1165 #ifdef DIAGNOSTIC
 1166                                 if (fp->f_count == 0)
 1167                                         panic("unp_gc: deferred unreferenced socket");
 1168 #endif
 1169                         } else {
 1170                                 if (fp->f_count == 0)
 1171                                         continue;
 1172                                 if (fp->f_flag & FMARK)
 1173                                         continue;
 1174                                 if (fp->f_count == fp->f_msgcount)
 1175                                         continue;
 1176                         }
 1177                         if (fp->f_iflags & FIF_DISCARDED)
 1178                                 continue;
 1179                         fp->f_flag |= FMARK;
 1180 
 1181                         if (fp->f_type != DTYPE_SOCKET ||
 1182                             (so = (struct socket *)fp->f_data) == 0)
 1183                                 continue;
 1184                         if (so->so_proto->pr_domain != &unixdomain ||
 1185                             (so->so_proto->pr_flags&PR_RIGHTS) == 0)
 1186                                 continue;
 1187 #ifdef notdef
 1188                         if (so->so_rcv.sb_flags & SB_LOCK) {
 1189                                 /*
 1190                                  * This is problematical; it's not clear
 1191                                  * we need to wait for the sockbuf to be
 1192                                  * unlocked (on a uniprocessor, at least),
 1193                                  * and it's also not clear what to do
 1194                                  * if sbwait returns an error due to receipt
 1195                                  * of a signal.  If sbwait does return
 1196                                  * an error, we'll go into an infinite
 1197                                  * loop.  Delete all of this for now.
 1198                                  */
 1199                                 (void) sbwait(&so->so_rcv);
 1200                                 goto restart;
 1201                         }
 1202 #endif
 1203                         unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
 1204                         /*
 1205                          * mark descriptors referenced from sockets queued on the accept queue as well.
 1206                          */
 1207                         if (so->so_options & SO_ACCEPTCONN) {
 1208                                 TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
 1209                                         unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
 1210                                 }
 1211                                 TAILQ_FOREACH(so1, &so->so_q, so_qe) {
 1212                                         unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
 1213                                 }
 1214                         }
 1215 
 1216                 }
 1217         } while (unp_defer);
 1218         /*
 1219          * Sweep pass.  Find unmarked descriptors, and free them.
 1220          *
 1221          * We grab an extra reference to each of the file table entries
 1222          * that are not otherwise accessible and then free the rights
 1223          * that are stored in messages on them.
 1224          *
 1225          * The bug in the original code is a little tricky, so I'll describe
 1226          * what's wrong with it here.
 1227          *
 1228          * It is incorrect to simply unp_discard each entry for f_msgcount
 1229          * times -- consider the case of sockets A and B that contain
 1230          * references to each other.  On a last close of some other socket,
 1231          * we trigger a gc since the number of outstanding rights (unp_rights)
 1232          * is non-zero.  If during the sweep phase the gc code un_discards,
 1233          * we end up doing a (full) closef on the descriptor.  A closef on A
 1234          * results in the following chain.  Closef calls soo_close, which
 1235          * calls soclose.   Soclose calls first (through the switch
 1236          * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
 1237          * returns because the previous instance had set unp_gcing, and
 1238          * we return all the way back to soclose, which marks the socket
 1239          * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
 1240          * to free up the rights that are queued in messages on the socket A,
 1241          * i.e., the reference on B.  The sorflush calls via the dom_dispose
 1242          * switch unp_dispose, which unp_scans with unp_discard.  This second
 1243          * instance of unp_discard just calls closef on B.
 1244          *
 1245          * Well, a similar chain occurs on B, resulting in a sorflush on B,
 1246          * which results in another closef on A.  Unfortunately, A is already
 1247          * being closed, and the descriptor has already been marked with
 1248          * SS_NOFDREF, and soclose panics at this point.
 1249          *
 1250          * Here, we first take an extra reference to each inaccessible
 1251          * descriptor.  Then, if the inaccessible descriptor is a
 1252          * socket, we call sorflush in case it is a Unix domain
 1253          * socket.  After we destroy all the rights carried in
 1254          * messages, we do a last closef to get rid of our extra
 1255          * reference.  This is the last close, and the unp_detach etc
 1256          * will shut down the socket.
 1257          *
 1258          * 91/09/19, bsy@cs.cmu.edu
 1259          */
 1260         extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
 1261         for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
 1262             fp = nextfp) {
 1263                 nextfp = LIST_NEXT(fp, f_list);
 1264                 simple_lock(&fp->f_slock);
 1265                 if (fp->f_count != 0 &&
 1266                     fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
 1267                         *fpp++ = fp;
 1268                         nunref++;
 1269                         fp->f_count++;
 1270                 }
 1271                 simple_unlock(&fp->f_slock);
 1272         }
 1273         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
 1274                 fp = *fpp;
 1275                 simple_lock(&fp->f_slock);
 1276                 FILE_USE(fp);
 1277                 if (fp->f_type == DTYPE_SOCKET)
 1278                         sorflush((struct socket *)fp->f_data);
 1279                 FILE_UNUSE(fp, NULL);
 1280         }
 1281         for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
 1282                 fp = *fpp;
 1283                 simple_lock(&fp->f_slock);
 1284                 if (fp->f_iflags & FIF_DISCARDED) {
 1285                         fp->f_usecount++;
 1286                         fp->f_msgcount--;
 1287                         simple_unlock(&fp->f_slock);
 1288                         unp_rights--;
 1289                         (void) closef(fp, (struct lwp *)0);
 1290                         simple_lock(&fp->f_slock);
 1291                 }
 1292                 FILE_USE(fp);
 1293                 (void) closef(fp, (struct lwp *)0);
 1294         }
 1295         free((caddr_t)extra_ref, M_FILE);
 1296         unp_gcing = 0;
 1297 }
 1298 
 1299 void
 1300 unp_dispose(struct mbuf *m)
 1301 {
 1302 
 1303         if (m)
 1304                 unp_scan(m, unp_discard, 1);
 1305 }
 1306 
 1307 void
 1308 unp_scan(struct mbuf *m0, void (*op)(struct file *), int discard)
 1309 {
 1310         struct mbuf *m;
 1311         struct file **rp;
 1312         struct cmsghdr *cm;
 1313         int i;
 1314         int qfds;
 1315 
 1316         while (m0) {
 1317                 for (m = m0; m; m = m->m_next) {
 1318                         if (m->m_type == MT_CONTROL &&
 1319                             m->m_len >= sizeof(*cm)) {
 1320                                 cm = mtod(m, struct cmsghdr *);
 1321                                 if (cm->cmsg_level != SOL_SOCKET ||
 1322                                     cm->cmsg_type != SCM_RIGHTS)
 1323                                         continue;
 1324                                 qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
 1325                                     / sizeof(struct file *);
 1326                                 rp = (struct file **)CMSG_DATA(cm);
 1327                                 for (i = 0; i < qfds; i++) {
 1328                                         struct file *fp = *rp;
 1329                                         if (discard)
 1330                                                 *rp = 0;
 1331                                         (*op)(fp);
 1332                                         rp++;
 1333                                 }
 1334                                 break;          /* XXX, but saves time */
 1335                         }
 1336                 }
 1337                 m0 = m0->m_nextpkt;
 1338         }
 1339 }
 1340 
 1341 void
 1342 unp_mark(struct file *fp)
 1343 {
 1344         if (fp == NULL)
 1345                 return;
 1346 
 1347         if (fp->f_flag & FMARK)
 1348                 return;
 1349 
 1350         /* If we're already deferred, don't screw up the defer count */
 1351         if (fp->f_flag & FDEFER)
 1352                 return;
 1353 
 1354         /*
 1355          * Minimize the number of deferrals...  Sockets are the only
 1356          * type of descriptor which can hold references to another
 1357          * descriptor, so just mark other descriptors, and defer
 1358          * unmarked sockets for the next pass.
 1359          */
 1360         if (fp->f_type == DTYPE_SOCKET) {
 1361                 unp_defer++;
 1362                 if (fp->f_count == 0)
 1363                         panic("unp_mark: queued unref");
 1364                 fp->f_flag |= FDEFER;
 1365         } else {
 1366                 fp->f_flag |= FMARK;
 1367         }
 1368         return;
 1369 }
 1370 
 1371 void
 1372 unp_discard(struct file *fp)
 1373 {
 1374         if (fp == NULL)
 1375                 return;
 1376 
 1377         simple_lock(&fp->f_slock);
 1378         /*
 1379          * closing unix domain sockets may cause a deep
 1380          * recursion, so leave them open and mark them
 1381          * for the garbage collector to discard them safely.
 1382          */
 1383         if (fp->f_type == DTYPE_SOCKET && fp->f_count == 1) {
 1384                 struct socket *so;
 1385 
 1386                 so = (struct socket *)fp->f_data;
 1387                 if (so && so->so_proto->pr_domain == &unixdomain &&
 1388                     (so->so_proto->pr_flags&PR_RIGHTS) != 0) {
 1389                         fp->f_iflags |= FIF_DISCARDED;
 1390                         simple_unlock(&fp->f_slock);
 1391                         return;
 1392                 }
 1393         }
 1394         fp->f_usecount++;       /* i.e. FILE_USE(fp) sans locking */
 1395         fp->f_msgcount--;
 1396         simple_unlock(&fp->f_slock);
 1397         unp_rights--;
 1398         (void) closef(fp, (struct lwp *)0);
 1399 }

Cache object: 141b9eca25fc3da277a5245da5307513


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.