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/netgraph/ng_ksocket.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 
    2 /*
    3  * ng_ksocket.c
    4  *
    5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
    6  * All rights reserved.
    7  * 
    8  * Subject to the following obligations and disclaimer of warranty, use and
    9  * redistribution of this software, in source or object code forms, with or
   10  * without modifications are expressly permitted by Whistle Communications;
   11  * provided, however, that:
   12  * 1. Any and all reproductions of the source or object code must include the
   13  *    copyright notice above and the following disclaimer of warranties; and
   14  * 2. No rights are granted, in any manner or form, to use Whistle
   15  *    Communications, Inc. trademarks, including the mark "WHISTLE
   16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
   17  *    such appears in the above copyright notice or in the software.
   18  * 
   19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
   20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
   21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
   22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
   23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
   24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
   25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
   26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
   27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
   28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
   29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
   30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
   31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
   32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
   35  * OF SUCH DAMAGE.
   36  *
   37  * Author: Archie Cobbs <archie@freebsd.org>
   38  *
   39  * $FreeBSD: releng/5.2/sys/netgraph/ng_ksocket.c 119187 2003-08-20 22:11:58Z hsu $
   40  * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
   41  */
   42 
   43 /*
   44  * Kernel socket node type.  This node type is basically a kernel-mode
   45  * version of a socket... kindof like the reverse of the socket node type.
   46  */
   47 
   48 #include <sys/param.h>
   49 #include <sys/systm.h>
   50 #include <sys/kernel.h>
   51 #include <sys/mbuf.h>
   52 #include <sys/proc.h>
   53 #include <sys/malloc.h>
   54 #include <sys/ctype.h>
   55 #include <sys/protosw.h>
   56 #include <sys/errno.h>
   57 #include <sys/socket.h>
   58 #include <sys/socketvar.h>
   59 #include <sys/uio.h>
   60 #include <sys/un.h>
   61 
   62 #include <netgraph/ng_message.h>
   63 #include <netgraph/netgraph.h>
   64 #include <netgraph/ng_parse.h>
   65 #include <netgraph/ng_ksocket.h>
   66 
   67 #include <netinet/in.h>
   68 #include <netatalk/at.h>
   69 
   70 #ifdef NG_SEPARATE_MALLOC
   71 MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock", "netgraph ksock node ");
   72 #else
   73 #define M_NETGRAPH_KSOCKET M_NETGRAPH
   74 #endif
   75 
   76 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
   77 #define SADATA_OFFSET   (OFFSETOF(struct sockaddr, sa_data))
   78 
   79 /* Node private data */
   80 struct ng_ksocket_private {
   81         node_p          node;
   82         hook_p          hook;
   83         struct socket   *so;
   84         LIST_HEAD(, ng_ksocket_private) embryos;
   85         LIST_ENTRY(ng_ksocket_private)  siblings;
   86         u_int32_t       flags;
   87         u_int32_t       response_token;
   88         ng_ID_t         response_addr;
   89 };
   90 typedef struct ng_ksocket_private *priv_p;
   91 
   92 /* Flags for priv_p */
   93 #define KSF_CONNECTING  0x00000001      /* Waiting for connection complete */
   94 #define KSF_ACCEPTING   0x00000002      /* Waiting for accept complete */
   95 #define KSF_EOFSEEN     0x00000004      /* Have sent 0-length EOF mbuf */
   96 #define KSF_CLONED      0x00000008      /* Cloned from an accepting socket */
   97 #define KSF_EMBRYONIC   0x00000010      /* Cloned node with no hooks yet */
   98 #define KSF_SENDING     0x00000020      /* Sending on socket */
   99 
  100 /* Netgraph node methods */
  101 static ng_constructor_t ng_ksocket_constructor;
  102 static ng_rcvmsg_t      ng_ksocket_rcvmsg;
  103 static ng_shutdown_t    ng_ksocket_shutdown;
  104 static ng_newhook_t     ng_ksocket_newhook;
  105 static ng_rcvdata_t     ng_ksocket_rcvdata;
  106 static ng_connect_t     ng_ksocket_connect;
  107 static ng_disconnect_t  ng_ksocket_disconnect;
  108 
  109 /* Alias structure */
  110 struct ng_ksocket_alias {
  111         const char      *name;
  112         const int       value;
  113         const int       family;
  114 };
  115 
  116 /* Protocol family aliases */
  117 static const struct ng_ksocket_alias ng_ksocket_families[] = {
  118         { "local",      PF_LOCAL        },
  119         { "inet",       PF_INET         },
  120         { "inet6",      PF_INET6        },
  121         { "atalk",      PF_APPLETALK    },
  122         { "ipx",        PF_IPX          },
  123         { "atm",        PF_ATM          },
  124         { NULL,         -1              },
  125 };
  126 
  127 /* Socket type aliases */
  128 static const struct ng_ksocket_alias ng_ksocket_types[] = {
  129         { "stream",     SOCK_STREAM     },
  130         { "dgram",      SOCK_DGRAM      },
  131         { "raw",        SOCK_RAW        },
  132         { "rdm",        SOCK_RDM        },
  133         { "seqpacket",  SOCK_SEQPACKET  },
  134         { NULL,         -1              },
  135 };
  136 
  137 /* Protocol aliases */
  138 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
  139         { "ip",         IPPROTO_IP,             PF_INET         },
  140         { "raw",        IPPROTO_RAW,            PF_INET         },
  141         { "icmp",       IPPROTO_ICMP,           PF_INET         },
  142         { "igmp",       IPPROTO_IGMP,           PF_INET         },
  143         { "tcp",        IPPROTO_TCP,            PF_INET         },
  144         { "udp",        IPPROTO_UDP,            PF_INET         },
  145         { "gre",        IPPROTO_GRE,            PF_INET         },
  146         { "esp",        IPPROTO_ESP,            PF_INET         },
  147         { "ah",         IPPROTO_AH,             PF_INET         },
  148         { "swipe",      IPPROTO_SWIPE,          PF_INET         },
  149         { "encap",      IPPROTO_ENCAP,          PF_INET         },
  150         { "divert",     IPPROTO_DIVERT,         PF_INET         },
  151         { "pim",        IPPROTO_PIM,            PF_INET         },
  152         { "ddp",        ATPROTO_DDP,            PF_APPLETALK    },
  153         { "aarp",       ATPROTO_AARP,           PF_APPLETALK    },
  154         { NULL,         -1                                      },
  155 };
  156 
  157 /* Helper functions */
  158 static int      ng_ksocket_check_accept(priv_p);
  159 static void     ng_ksocket_finish_accept(priv_p);
  160 static void     ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
  161 static int      ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
  162                         const char *s, int family);
  163 static void     ng_ksocket_incoming2(node_p node, hook_p hook,
  164                         void *arg1, int waitflag);
  165 
  166 /************************************************************************
  167                         STRUCT SOCKADDR PARSE TYPE
  168  ************************************************************************/
  169 
  170 /* Get the length of the data portion of a generic struct sockaddr */
  171 static int
  172 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
  173         const u_char *start, const u_char *buf)
  174 {
  175         const struct sockaddr *sa;
  176 
  177         sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
  178         return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
  179 }
  180 
  181 /* Type for the variable length data portion of a generic struct sockaddr */
  182 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
  183         &ng_parse_bytearray_type,
  184         &ng_parse_generic_sockdata_getLength
  185 };
  186 
  187 /* Type for a generic struct sockaddr */
  188 static const struct ng_parse_struct_field
  189     ng_parse_generic_sockaddr_type_fields[] = {
  190           { "len",      &ng_parse_uint8_type                    },
  191           { "family",   &ng_parse_uint8_type                    },
  192           { "data",     &ng_ksocket_generic_sockdata_type       },
  193           { NULL }
  194 };
  195 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
  196         &ng_parse_struct_type,
  197         &ng_parse_generic_sockaddr_type_fields
  198 };
  199 
  200 /* Convert a struct sockaddr from ASCII to binary.  If its a protocol
  201    family that we specially handle, do that, otherwise defer to the
  202    generic parse type ng_ksocket_generic_sockaddr_type. */
  203 static int
  204 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
  205         const char *s, int *off, const u_char *const start,
  206         u_char *const buf, int *buflen)
  207 {
  208         struct sockaddr *const sa = (struct sockaddr *)buf;
  209         enum ng_parse_token tok;
  210         char fambuf[32];
  211         int family, len;
  212         char *t;
  213 
  214         /* If next token is a left curly brace, use generic parse type */
  215         if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
  216                 return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
  217                     (&ng_ksocket_generic_sockaddr_type,
  218                     s, off, start, buf, buflen);
  219         }
  220 
  221         /* Get socket address family followed by a slash */
  222         while (isspace(s[*off]))
  223                 (*off)++;
  224         if ((t = index(s + *off, '/')) == NULL)
  225                 return (EINVAL);
  226         if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
  227                 return (EINVAL);
  228         strncpy(fambuf, s + *off, len);
  229         fambuf[len] = '\0';
  230         *off += len + 1;
  231         if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
  232                 return (EINVAL);
  233 
  234         /* Set family */
  235         if (*buflen < SADATA_OFFSET)
  236                 return (ERANGE);
  237         sa->sa_family = family;
  238 
  239         /* Set family-specific data and length */
  240         switch (sa->sa_family) {
  241         case PF_LOCAL:          /* Get pathname */
  242             {
  243                 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
  244                 struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
  245                 int toklen, pathlen;
  246                 char *path;
  247 
  248                 if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
  249                         return (EINVAL);
  250                 pathlen = strlen(path);
  251                 if (pathlen > SOCK_MAXADDRLEN) {
  252                         FREE(path, M_NETGRAPH_KSOCKET);
  253                         return (E2BIG);
  254                 }
  255                 if (*buflen < pathoff + pathlen) {
  256                         FREE(path, M_NETGRAPH_KSOCKET);
  257                         return (ERANGE);
  258                 }
  259                 *off += toklen;
  260                 bcopy(path, sun->sun_path, pathlen);
  261                 sun->sun_len = pathoff + pathlen;
  262                 FREE(path, M_NETGRAPH_KSOCKET);
  263                 break;
  264             }
  265 
  266         case PF_INET:           /* Get an IP address with optional port */
  267             {
  268                 struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
  269                 int i;
  270 
  271                 /* Parse this: <ipaddress>[:port] */
  272                 for (i = 0; i < 4; i++) {
  273                         u_long val;
  274                         char *eptr;
  275 
  276                         val = strtoul(s + *off, &eptr, 10);
  277                         if (val > 0xff || eptr == s + *off)
  278                                 return (EINVAL);
  279                         *off += (eptr - (s + *off));
  280                         ((u_char *)&sin->sin_addr)[i] = (u_char)val;
  281                         if (i < 3) {
  282                                 if (s[*off] != '.')
  283                                         return (EINVAL);
  284                                 (*off)++;
  285                         } else if (s[*off] == ':') {
  286                                 (*off)++;
  287                                 val = strtoul(s + *off, &eptr, 10);
  288                                 if (val > 0xffff || eptr == s + *off)
  289                                         return (EINVAL);
  290                                 *off += (eptr - (s + *off));
  291                                 sin->sin_port = htons(val);
  292                         } else
  293                                 sin->sin_port = 0;
  294                 }
  295                 bzero(&sin->sin_zero, sizeof(sin->sin_zero));
  296                 sin->sin_len = sizeof(*sin);
  297                 break;
  298             }
  299 
  300 #if 0
  301         case PF_APPLETALK:      /* XXX implement these someday */
  302         case PF_INET6:
  303         case PF_IPX:
  304 #endif
  305 
  306         default:
  307                 return (EINVAL);
  308         }
  309 
  310         /* Done */
  311         *buflen = sa->sa_len;
  312         return (0);
  313 }
  314 
  315 /* Convert a struct sockaddr from binary to ASCII */
  316 static int
  317 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
  318         const u_char *data, int *off, char *cbuf, int cbuflen)
  319 {
  320         const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
  321         int slen = 0;
  322 
  323         /* Output socket address, either in special or generic format */
  324         switch (sa->sa_family) {
  325         case PF_LOCAL:
  326             {
  327                 const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
  328                 const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
  329                 const int pathlen = sun->sun_len - pathoff;
  330                 char pathbuf[SOCK_MAXADDRLEN + 1];
  331                 char *pathtoken;
  332 
  333                 bcopy(sun->sun_path, pathbuf, pathlen);
  334                 if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
  335                         return (ENOMEM);
  336                 slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
  337                 FREE(pathtoken, M_NETGRAPH_KSOCKET);
  338                 if (slen >= cbuflen)
  339                         return (ERANGE);
  340                 *off += sun->sun_len;
  341                 return (0);
  342             }
  343 
  344         case PF_INET:
  345             {
  346                 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
  347 
  348                 slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
  349                   ((const u_char *)&sin->sin_addr)[0],
  350                   ((const u_char *)&sin->sin_addr)[1],
  351                   ((const u_char *)&sin->sin_addr)[2],
  352                   ((const u_char *)&sin->sin_addr)[3]);
  353                 if (sin->sin_port != 0) {
  354                         slen += snprintf(cbuf + strlen(cbuf),
  355                             cbuflen - strlen(cbuf), ":%d",
  356                             (u_int)ntohs(sin->sin_port));
  357                 }
  358                 if (slen >= cbuflen)
  359                         return (ERANGE);
  360                 *off += sizeof(*sin);
  361                 return(0);
  362             }
  363 
  364 #if 0
  365         case PF_APPLETALK:      /* XXX implement these someday */
  366         case PF_INET6:
  367         case PF_IPX:
  368 #endif
  369 
  370         default:
  371                 return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
  372                     (&ng_ksocket_generic_sockaddr_type,
  373                     data, off, cbuf, cbuflen);
  374         }
  375 }
  376 
  377 /* Parse type for struct sockaddr */
  378 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
  379         NULL,
  380         NULL,
  381         NULL,
  382         &ng_ksocket_sockaddr_parse,
  383         &ng_ksocket_sockaddr_unparse,
  384         NULL            /* no such thing as a default struct sockaddr */
  385 };
  386 
  387 /************************************************************************
  388                 STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
  389  ************************************************************************/
  390 
  391 /* Get length of the struct ng_ksocket_sockopt value field, which is the
  392    just the excess of the message argument portion over the length of
  393    the struct ng_ksocket_sockopt. */
  394 static int
  395 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
  396         const u_char *start, const u_char *buf)
  397 {
  398         static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
  399         const struct ng_ksocket_sockopt *sopt;
  400         const struct ng_mesg *msg;
  401 
  402         sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
  403         msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
  404         return msg->header.arglen - sizeof(*sopt);
  405 }
  406 
  407 /* Parse type for the option value part of a struct ng_ksocket_sockopt
  408    XXX Eventually, we should handle the different socket options specially.
  409    XXX This would avoid byte order problems, eg an integer value of 1 is
  410    XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
  411 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
  412         &ng_parse_bytearray_type,
  413         &ng_parse_sockoptval_getLength
  414 };
  415 
  416 /* Parse type for struct ng_ksocket_sockopt */
  417 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
  418         = NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
  419 static const struct ng_parse_type ng_ksocket_sockopt_type = {
  420         &ng_parse_struct_type,
  421         &ng_ksocket_sockopt_type_fields
  422 };
  423 
  424 /* Parse type for struct ng_ksocket_accept */
  425 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
  426         = NGM_KSOCKET_ACCEPT_INFO;
  427 static const struct ng_parse_type ng_ksocket_accept_type = {
  428         &ng_parse_struct_type,
  429         &ng_ksocket_accept_type_fields
  430 };
  431 
  432 /* List of commands and how to convert arguments to/from ASCII */
  433 static const struct ng_cmdlist ng_ksocket_cmds[] = {
  434         {
  435           NGM_KSOCKET_COOKIE,
  436           NGM_KSOCKET_BIND,
  437           "bind",
  438           &ng_ksocket_sockaddr_type,
  439           NULL
  440         },
  441         {
  442           NGM_KSOCKET_COOKIE,
  443           NGM_KSOCKET_LISTEN,
  444           "listen",
  445           &ng_parse_int32_type,
  446           NULL
  447         },
  448         {
  449           NGM_KSOCKET_COOKIE,
  450           NGM_KSOCKET_ACCEPT,
  451           "accept",
  452           NULL,
  453           &ng_ksocket_accept_type
  454         },
  455         {
  456           NGM_KSOCKET_COOKIE,
  457           NGM_KSOCKET_CONNECT,
  458           "connect",
  459           &ng_ksocket_sockaddr_type,
  460           &ng_parse_int32_type
  461         },
  462         {
  463           NGM_KSOCKET_COOKIE,
  464           NGM_KSOCKET_GETNAME,
  465           "getname",
  466           NULL,
  467           &ng_ksocket_sockaddr_type
  468         },
  469         {
  470           NGM_KSOCKET_COOKIE,
  471           NGM_KSOCKET_GETPEERNAME,
  472           "getpeername",
  473           NULL,
  474           &ng_ksocket_sockaddr_type
  475         },
  476         {
  477           NGM_KSOCKET_COOKIE,
  478           NGM_KSOCKET_SETOPT,
  479           "setopt",
  480           &ng_ksocket_sockopt_type,
  481           NULL
  482         },
  483         {
  484           NGM_KSOCKET_COOKIE,
  485           NGM_KSOCKET_GETOPT,
  486           "getopt",
  487           &ng_ksocket_sockopt_type,
  488           &ng_ksocket_sockopt_type
  489         },
  490         { 0 }
  491 };
  492 
  493 /* Node type descriptor */
  494 static struct ng_type ng_ksocket_typestruct = {
  495         NG_ABI_VERSION,
  496         NG_KSOCKET_NODE_TYPE,
  497         NULL,
  498         ng_ksocket_constructor,
  499         ng_ksocket_rcvmsg,
  500         ng_ksocket_shutdown,
  501         ng_ksocket_newhook,
  502         NULL,
  503         ng_ksocket_connect,
  504         ng_ksocket_rcvdata,
  505         ng_ksocket_disconnect,
  506         ng_ksocket_cmds
  507 };
  508 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
  509 
  510 #define ERROUT(x)       do { error = (x); goto done; } while (0)
  511 
  512 /************************************************************************
  513                         NETGRAPH NODE STUFF
  514  ************************************************************************/
  515 
  516 /*
  517  * Node type constructor
  518  * The NODE part is assumed to be all set up.
  519  * There is already a reference to the node for us.
  520  */
  521 static int
  522 ng_ksocket_constructor(node_p node)
  523 {
  524         priv_p priv;
  525 
  526         /* Allocate private structure */
  527         MALLOC(priv, priv_p, sizeof(*priv),
  528             M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
  529         if (priv == NULL)
  530                 return (ENOMEM);
  531 
  532         LIST_INIT(&priv->embryos);
  533         /* cross link them */
  534         priv->node = node;
  535         NG_NODE_SET_PRIVATE(node, priv);
  536 
  537         /* Done */
  538         return (0);
  539 }
  540 
  541 /*
  542  * Give our OK for a hook to be added. The hook name is of the
  543  * form "<family>/<type>/<proto>" where the three components may
  544  * be decimal numbers or else aliases from the above lists.
  545  *
  546  * Connecting a hook amounts to opening the socket.  Disconnecting
  547  * the hook closes the socket and destroys the node as well.
  548  */
  549 static int
  550 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
  551 {
  552         struct thread *td = curthread ? curthread : &thread0;   /* XXX broken */
  553         const priv_p priv = NG_NODE_PRIVATE(node);
  554         char *s1, *s2, name[NG_HOOKLEN+1];
  555         int family, type, protocol, error;
  556 
  557         /* Check if we're already connected */
  558         if (priv->hook != NULL)
  559                 return (EISCONN);
  560 
  561         if (priv->flags & KSF_CLONED) {
  562                 if (priv->flags & KSF_EMBRYONIC) {
  563                         /* Remove ourselves from our parent's embryo list */
  564                         LIST_REMOVE(priv, siblings);
  565                         priv->flags &= ~KSF_EMBRYONIC;
  566                 }
  567         } else {
  568                 /* Extract family, type, and protocol from hook name */
  569                 snprintf(name, sizeof(name), "%s", name0);
  570                 s1 = name;
  571                 if ((s2 = index(s1, '/')) == NULL)
  572                         return (EINVAL);
  573                 *s2++ = '\0';
  574                 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
  575                 if (family == -1)
  576                         return (EINVAL);
  577                 s1 = s2;
  578                 if ((s2 = index(s1, '/')) == NULL)
  579                         return (EINVAL);
  580                 *s2++ = '\0';
  581                 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
  582                 if (type == -1)
  583                         return (EINVAL);
  584                 s1 = s2;
  585                 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
  586                 if (protocol == -1)
  587                         return (EINVAL);
  588 
  589                 /* Create the socket */
  590                 error = socreate(family, &priv->so, type, protocol,
  591                    td->td_ucred, td);
  592                 if (error != 0)
  593                         return (error);
  594 
  595                 /* XXX call soreserve() ? */
  596 
  597         }
  598 
  599         /* OK */
  600         priv->hook = hook;
  601         return(0);
  602 }
  603 
  604 static int
  605 ng_ksocket_connect(hook_p hook)
  606 {
  607         node_p node = NG_HOOK_NODE(hook);
  608         const priv_p priv = NG_NODE_PRIVATE(node);
  609         struct socket *const so = priv->so;
  610 
  611         /* Add our hook for incoming data and other events */
  612         priv->so->so_upcallarg = (caddr_t)node;
  613         priv->so->so_upcall = ng_ksocket_incoming;
  614         priv->so->so_rcv.sb_flags |= SB_UPCALL;
  615         priv->so->so_snd.sb_flags |= SB_UPCALL;
  616         priv->so->so_state |= SS_NBIO;
  617         /*
  618          * --Original comment--
  619          * On a cloned socket we may have already received one or more
  620          * upcalls which we couldn't handle without a hook.  Handle
  621          * those now.
  622          * We cannot call the upcall function directly
  623          * from here, because until this function has returned our
  624          * hook isn't connected.
  625          *
  626          * ---meta comment for -current ---
  627          * XXX This is dubius.
  628          * Upcalls between the time that the hook was
  629          * first created and now (on another processesor) will
  630          * be earlier on the queue than the request to finalise the hook.
  631          * By the time the hook is finalised,
  632          * The queued upcalls will have happenned and the code
  633          * will have discarded them because of a lack of a hook.
  634          * (socket not open).
  635          *
  636          * This is a bad byproduct of the complicated way in which hooks
  637          * are now created (3 daisy chained async events).
  638          *
  639          * Since we are a netgraph operation 
  640          * We know that we hold a lock on this node. This forces the
  641          * request we make below to be queued rather than implemented
  642          * immediatly which will cause the upcall function to be called a bit
  643          * later.
  644          * However, as we will run any waiting queued operations immediatly
  645          * after doing this one, if we have not finalised the other end
  646          * of the hook, those queued operations will fail.
  647          */
  648         if (priv->flags & KSF_CLONED) {
  649                 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_NOWAIT);
  650         }
  651 
  652         return (0);
  653 }
  654 
  655 /*
  656  * Receive a control message
  657  */
  658 static int
  659 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
  660 {
  661         struct thread *td = curthread ? curthread : &thread0;   /* XXX broken */
  662         const priv_p priv = NG_NODE_PRIVATE(node);
  663         struct socket *const so = priv->so;
  664         struct ng_mesg *resp = NULL;
  665         int error = 0;
  666         struct ng_mesg *msg;
  667         ng_ID_t raddr;
  668 
  669         NGI_GET_MSG(item, msg);
  670         switch (msg->header.typecookie) {
  671         case NGM_KSOCKET_COOKIE:
  672                 switch (msg->header.cmd) {
  673                 case NGM_KSOCKET_BIND:
  674                     {
  675                         struct sockaddr *const sa
  676                             = (struct sockaddr *)msg->data;
  677 
  678                         /* Sanity check */
  679                         if (msg->header.arglen < SADATA_OFFSET
  680                             || msg->header.arglen < sa->sa_len)
  681                                 ERROUT(EINVAL);
  682                         if (so == NULL)
  683                                 ERROUT(ENXIO);
  684 
  685                         /* Bind */
  686                         error = sobind(so, sa, td);
  687                         break;
  688                     }
  689                 case NGM_KSOCKET_LISTEN:
  690                     {
  691                         /* Sanity check */
  692                         if (msg->header.arglen != sizeof(int32_t))
  693                                 ERROUT(EINVAL);
  694                         if (so == NULL)
  695                                 ERROUT(ENXIO);
  696 
  697                         /* Listen */
  698                         error = solisten(so, *((int32_t *)msg->data), td);
  699                         break;
  700                     }
  701 
  702                 case NGM_KSOCKET_ACCEPT:
  703                     {
  704                         /* Sanity check */
  705                         if (msg->header.arglen != 0)
  706                                 ERROUT(EINVAL);
  707                         if (so == NULL)
  708                                 ERROUT(ENXIO);
  709 
  710                         /* Make sure the socket is capable of accepting */
  711                         if (!(so->so_options & SO_ACCEPTCONN))
  712                                 ERROUT(EINVAL);
  713                         if (priv->flags & KSF_ACCEPTING)
  714                                 ERROUT(EALREADY);
  715 
  716                         error = ng_ksocket_check_accept(priv);
  717                         if (error != 0 && error != EWOULDBLOCK)
  718                                 ERROUT(error);
  719 
  720                         /*
  721                          * If a connection is already complete, take it.
  722                          * Otherwise let the upcall function deal with
  723                          * the connection when it comes in.
  724                          */
  725                         priv->response_token = msg->header.token;
  726                         raddr = priv->response_addr = NGI_RETADDR(item);
  727                         if (error == 0) {
  728                                 ng_ksocket_finish_accept(priv);
  729                         } else
  730                                 priv->flags |= KSF_ACCEPTING;
  731                         break;
  732                     }
  733 
  734                 case NGM_KSOCKET_CONNECT:
  735                     {
  736                         struct sockaddr *const sa
  737                             = (struct sockaddr *)msg->data;
  738 
  739                         /* Sanity check */
  740                         if (msg->header.arglen < SADATA_OFFSET
  741                             || msg->header.arglen < sa->sa_len)
  742                                 ERROUT(EINVAL);
  743                         if (so == NULL)
  744                                 ERROUT(ENXIO);
  745 
  746                         /* Do connect */
  747                         if ((so->so_state & SS_ISCONNECTING) != 0)
  748                                 ERROUT(EALREADY);
  749                         if ((error = soconnect(so, sa, td)) != 0) {
  750                                 so->so_state &= ~SS_ISCONNECTING;
  751                                 ERROUT(error);
  752                         }
  753                         if ((so->so_state & SS_ISCONNECTING) != 0) {
  754                                 /* We will notify the sender when we connect */
  755                                 priv->response_token = msg->header.token;
  756                                 raddr = priv->response_addr = NGI_RETADDR(item);
  757                                 priv->flags |= KSF_CONNECTING;
  758                                 ERROUT(EINPROGRESS);
  759                         }
  760                         break;
  761                     }
  762 
  763                 case NGM_KSOCKET_GETNAME:
  764                 case NGM_KSOCKET_GETPEERNAME:
  765                     {
  766                         int (*func)(struct socket *so, struct sockaddr **nam);
  767                         struct sockaddr *sa = NULL;
  768                         int len;
  769 
  770                         /* Sanity check */
  771                         if (msg->header.arglen != 0)
  772                                 ERROUT(EINVAL);
  773                         if (so == NULL)
  774                                 ERROUT(ENXIO);
  775 
  776                         /* Get function */
  777                         if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
  778                                 if ((so->so_state
  779                                     & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) 
  780                                         ERROUT(ENOTCONN);
  781                                 func = so->so_proto->pr_usrreqs->pru_peeraddr;
  782                         } else
  783                                 func = so->so_proto->pr_usrreqs->pru_sockaddr;
  784 
  785                         /* Get local or peer address */
  786                         if ((error = (*func)(so, &sa)) != 0)
  787                                 goto bail;
  788                         len = (sa == NULL) ? 0 : sa->sa_len;
  789 
  790                         /* Send it back in a response */
  791                         NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
  792                         if (resp == NULL) {
  793                                 error = ENOMEM;
  794                                 goto bail;
  795                         }
  796                         bcopy(sa, resp->data, len);
  797 
  798                 bail:
  799                         /* Cleanup */
  800                         if (sa != NULL)
  801                                 FREE(sa, M_SONAME);
  802                         break;
  803                     }
  804 
  805                 case NGM_KSOCKET_GETOPT:
  806                     {
  807                         struct ng_ksocket_sockopt *ksopt = 
  808                             (struct ng_ksocket_sockopt *)msg->data;
  809                         struct sockopt sopt;
  810 
  811                         /* Sanity check */
  812                         if (msg->header.arglen != sizeof(*ksopt))
  813                                 ERROUT(EINVAL);
  814                         if (so == NULL)
  815                                 ERROUT(ENXIO);
  816 
  817                         /* Get response with room for option value */
  818                         NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
  819                             + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
  820                         if (resp == NULL)
  821                                 ERROUT(ENOMEM);
  822 
  823                         /* Get socket option, and put value in the response */
  824                         sopt.sopt_dir = SOPT_GET;
  825                         sopt.sopt_level = ksopt->level;
  826                         sopt.sopt_name = ksopt->name;
  827                         sopt.sopt_td = NULL;
  828                         sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
  829                         ksopt = (struct ng_ksocket_sockopt *)resp->data;
  830                         sopt.sopt_val = ksopt->value;
  831                         if ((error = sogetopt(so, &sopt)) != 0) {
  832                                 NG_FREE_MSG(resp);
  833                                 break;
  834                         }
  835 
  836                         /* Set actual value length */
  837                         resp->header.arglen = sizeof(*ksopt)
  838                             + sopt.sopt_valsize;
  839                         break;
  840                     }
  841 
  842                 case NGM_KSOCKET_SETOPT:
  843                     {
  844                         struct ng_ksocket_sockopt *const ksopt = 
  845                             (struct ng_ksocket_sockopt *)msg->data;
  846                         const int valsize = msg->header.arglen - sizeof(*ksopt);
  847                         struct sockopt sopt;
  848 
  849                         /* Sanity check */
  850                         if (valsize < 0)
  851                                 ERROUT(EINVAL);
  852                         if (so == NULL)
  853                                 ERROUT(ENXIO);
  854 
  855                         /* Set socket option */
  856                         sopt.sopt_dir = SOPT_SET;
  857                         sopt.sopt_level = ksopt->level;
  858                         sopt.sopt_name = ksopt->name;
  859                         sopt.sopt_val = ksopt->value;
  860                         sopt.sopt_valsize = valsize;
  861                         sopt.sopt_td = NULL;
  862                         error = sosetopt(so, &sopt);
  863                         break;
  864                     }
  865 
  866                 default:
  867                         error = EINVAL;
  868                         break;
  869                 }
  870                 break;
  871         default:
  872                 error = EINVAL;
  873                 break;
  874         }
  875 done:
  876         NG_RESPOND_MSG(error, node, item, resp);
  877         NG_FREE_MSG(msg);
  878         return (error);
  879 }
  880 
  881 /*
  882  * Receive incoming data on our hook.  Send it out the socket.
  883  */
  884 static int
  885 ng_ksocket_rcvdata(hook_p hook, item_p item)
  886 {
  887         struct thread *td = curthread ? curthread : &thread0;   /* XXX broken */
  888         const node_p node = NG_HOOK_NODE(hook);
  889         const priv_p priv = NG_NODE_PRIVATE(node);
  890         struct socket *const so = priv->so;
  891         struct sockaddr *sa = NULL;
  892         meta_p meta;
  893         int error;
  894         struct mbuf *m;
  895 
  896         /* Avoid reentrantly sending on the socket */
  897         if ((priv->flags & KSF_SENDING) != 0) {
  898                 NG_FREE_ITEM(item);
  899                 return (EDEADLK);
  900         }
  901 
  902         /* Extract data and meta information */
  903         NGI_GET_M(item, m);
  904         NGI_GET_META(item, meta);
  905         NG_FREE_ITEM(item);
  906 
  907         /* If any meta info, look for peer socket address */
  908         if (meta != NULL) {
  909                 struct meta_field_header *field;
  910 
  911                 /* Look for peer socket address */
  912                 for (field = &meta->options[0];
  913                     (caddr_t)field < (caddr_t)meta + meta->used_len;
  914                     field = (struct meta_field_header *)
  915                       ((caddr_t)field + field->len)) {
  916                         if (field->cookie != NGM_KSOCKET_COOKIE
  917                             || field->type != NG_KSOCKET_META_SOCKADDR)
  918                                 continue;
  919                         sa = (struct sockaddr *)field->data;
  920                         break;
  921                 }
  922         }
  923 
  924         /* Send packet */
  925         priv->flags |= KSF_SENDING;
  926         error = (*so->so_proto->pr_usrreqs->pru_sosend)(so, sa, 0, m, 0, 0, td);
  927         priv->flags &= ~KSF_SENDING;
  928 
  929         /* Clean up and exit */
  930         NG_FREE_META(meta);
  931         return (error);
  932 }
  933 
  934 /*
  935  * Destroy node
  936  */
  937 static int
  938 ng_ksocket_shutdown(node_p node)
  939 {
  940         const priv_p priv = NG_NODE_PRIVATE(node);
  941         priv_p embryo;
  942 
  943         /* Close our socket (if any) */
  944         if (priv->so != NULL) {
  945                 priv->so->so_upcall = NULL;
  946                 priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
  947                 priv->so->so_snd.sb_flags &= ~SB_UPCALL;
  948                 soclose(priv->so);
  949                 priv->so = NULL;
  950         }
  951 
  952         /* If we are an embryo, take ourselves out of the parent's list */
  953         if (priv->flags & KSF_EMBRYONIC) {
  954                 LIST_REMOVE(priv, siblings);
  955                 priv->flags &= ~KSF_EMBRYONIC;
  956         }
  957 
  958         /* Remove any embryonic children we have */
  959         while (!LIST_EMPTY(&priv->embryos)) {
  960                 embryo = LIST_FIRST(&priv->embryos);
  961                 ng_rmnode_self(embryo->node);
  962         }
  963 
  964         /* Take down netgraph node */
  965         bzero(priv, sizeof(*priv));
  966         FREE(priv, M_NETGRAPH_KSOCKET);
  967         NG_NODE_SET_PRIVATE(node, NULL);
  968         NG_NODE_UNREF(node);            /* let the node escape */
  969         return (0);
  970 }
  971 
  972 /*
  973  * Hook disconnection
  974  */
  975 static int
  976 ng_ksocket_disconnect(hook_p hook)
  977 {
  978         KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
  979             ("%s: numhooks=%d?", __func__,
  980             NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
  981         if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
  982                 ng_rmnode_self(NG_HOOK_NODE(hook));
  983         return (0);
  984 }
  985 
  986 /************************************************************************
  987                         HELPER STUFF
  988  ************************************************************************/
  989 /* 
  990  * You should no-longer "just call" a netgraph node function
  991  * from an external asynchronous event.
  992  * This is because in doing so you are ignoring the locking on the netgraph
  993  * nodes. Instead call your function via 
  994  * "int ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn,
  995  *       void *arg1, int arg2);"
  996  * this will call the function you chose, but will first do all the 
  997  * locking rigmarole. Your function MAY only be called at some distant future
  998  * time (several millisecs away) so don't give it any arguments
  999  * that may be revoked soon (e.g. on your stack).
 1000  * In this case even the 'so' argument is doubtful. 
 1001  * While the function request is being processed the node
 1002  * has an extra reference and as such will not disappear until
 1003  * the request has at least been done, but the 'so' may not be so lucky.
 1004  * handle this by checking the validity of the node in the target function
 1005  * before dereferencing the socket pointer.
 1006  */
 1007 
 1008 static void
 1009 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
 1010 {
 1011         const node_p node = arg;
 1012 
 1013         ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, waitflag);
 1014 }
 1015 
 1016 
 1017 /*
 1018  * When incoming data is appended to the socket, we get notified here.
 1019  * This is also called whenever a significant event occurs for the socket.
 1020  * We know that HOOK is NULL. Because of how we were called we know we have a 
 1021  * lock on this node an are participating inthe netgraph locking.
 1022  * Our original caller may have queued this even some time ago and 
 1023  * we cannot trust that he even still exists. The node however is being
 1024  * held with a reference by the queueing code, at least until we finish,
 1025  * even if it has been zapped, so first check it's validiy 
 1026  * before we trust the socket (which was derived from it).
 1027  */
 1028 static void
 1029 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int waitflag)
 1030 {
 1031         struct socket *so = arg1;
 1032         const priv_p priv = NG_NODE_PRIVATE(node);
 1033         struct mbuf *m;
 1034         struct ng_mesg *response;
 1035         struct uio auio;
 1036         int s, flags, error;
 1037 
 1038         s = splnet();
 1039 
 1040         /* Sanity check */
 1041         if (NG_NODE_NOT_VALID(node)) {
 1042                 splx(s);
 1043                 return;
 1044         }
 1045         /* so = priv->so; *//* XXX could have derived this like so */
 1046         KASSERT(so == priv->so, ("%s: wrong socket", __func__));
 1047 
 1048         /* Check whether a pending connect operation has completed */
 1049         if (priv->flags & KSF_CONNECTING) {
 1050                 if ((error = so->so_error) != 0) {
 1051                         so->so_error = 0;
 1052                         so->so_state &= ~SS_ISCONNECTING;
 1053                 }
 1054                 if (!(so->so_state & SS_ISCONNECTING)) {
 1055                         NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
 1056                             NGM_KSOCKET_CONNECT, sizeof(int32_t), waitflag);
 1057                         if (response != NULL) {
 1058                                 response->header.flags |= NGF_RESP;
 1059                                 response->header.token = priv->response_token;
 1060                                 *(int32_t *)response->data = error;
 1061                                 /* 
 1062                                  * send an async "response" message
 1063                                  * to the node that set us up
 1064                                  * (if it still exists)
 1065                                  */
 1066                                 NG_SEND_MSG_ID(error, node,
 1067                                     response, priv->response_addr, 0);
 1068                         }
 1069                         priv->flags &= ~KSF_CONNECTING;
 1070                 }
 1071         }
 1072 
 1073         /* Check whether a pending accept operation has completed */
 1074         if (priv->flags & KSF_ACCEPTING) {
 1075                 error = ng_ksocket_check_accept(priv);
 1076                 if (error != EWOULDBLOCK)
 1077                         priv->flags &= ~KSF_ACCEPTING;
 1078                 if (error == 0)
 1079                         ng_ksocket_finish_accept(priv);
 1080         }
 1081 
 1082         /*
 1083          * If we don't have a hook, we must handle data events later.  When
 1084          * the hook gets created and is connected, this upcall function
 1085          * will be called again.
 1086          */
 1087         if (priv->hook == NULL) {
 1088                 splx(s);
 1089                 return;
 1090         }
 1091 
 1092         /* Read and forward available mbuf's */
 1093         auio.uio_td = NULL;
 1094         auio.uio_resid = 1000000000;
 1095         flags = MSG_DONTWAIT;
 1096         while (1) {
 1097                 struct sockaddr *sa = NULL;
 1098                 meta_p meta = NULL;
 1099                 struct mbuf *n;
 1100 
 1101                 /* Try to get next packet from socket */
 1102                 if ((error = (*so->so_proto->pr_usrreqs->pru_soreceive)
 1103                     (so, (so->so_state & SS_ISCONNECTED) ? NULL : &sa,
 1104                     &auio, &m, (struct mbuf **)0, &flags)) != 0)
 1105                         break;
 1106 
 1107                 /* See if we got anything */
 1108                 if (m == NULL) {
 1109                         if (sa != NULL)
 1110                                 FREE(sa, M_SONAME);
 1111                         break;
 1112                 }
 1113 
 1114                 /* Don't trust the various socket layers to get the
 1115                    packet header and length correct (eg. kern/15175) */
 1116                 for (n = m, m->m_pkthdr.len = 0; n != NULL; n = n->m_next)
 1117                         m->m_pkthdr.len += n->m_len;
 1118 
 1119                 /* Put peer's socket address (if any) into a meta info blob */
 1120                 if (sa != NULL) {
 1121                         struct meta_field_header *mhead;
 1122                         u_int len;
 1123 
 1124                         len = sizeof(*meta) + sizeof(*mhead) + sa->sa_len;
 1125                         MALLOC(meta, meta_p, len, M_NETGRAPH_META, M_NOWAIT);
 1126                         if (meta == NULL) {
 1127                                 FREE(sa, M_SONAME);
 1128                                 goto sendit;
 1129                         }
 1130                         mhead = &meta->options[0];
 1131                         bzero(meta, sizeof(*meta));
 1132                         bzero(mhead, sizeof(*mhead));
 1133                         meta->allocated_len = len;
 1134                         meta->used_len = len;
 1135                         mhead->cookie = NGM_KSOCKET_COOKIE;
 1136                         mhead->type = NG_KSOCKET_META_SOCKADDR;
 1137                         mhead->len = sizeof(*mhead) + sa->sa_len;
 1138                         bcopy(sa, mhead->data, sa->sa_len);
 1139                         FREE(sa, M_SONAME);
 1140                 }
 1141 
 1142 sendit:         /* Forward data with optional peer sockaddr as meta info */
 1143                 NG_SEND_DATA(error, priv->hook, m, meta);
 1144         }
 1145 
 1146         /*
 1147          * If the peer has closed the connection, forward a 0-length mbuf
 1148          * to indicate end-of-file.
 1149          */
 1150         if (so->so_state & SS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
 1151                 MGETHDR(m, waitflag, MT_DATA);
 1152                 if (m != NULL) {
 1153                         m->m_len = m->m_pkthdr.len = 0;
 1154                         NG_SEND_DATA_ONLY(error, priv->hook, m);
 1155                 }
 1156                 priv->flags |= KSF_EOFSEEN;
 1157         }
 1158         splx(s);
 1159 }
 1160 
 1161 /*
 1162  * Check for a completed incoming connection and return 0 if one is found.
 1163  * Otherwise return the appropriate error code.
 1164  */
 1165 static int
 1166 ng_ksocket_check_accept(priv_p priv)
 1167 {
 1168         struct socket *const head = priv->so;
 1169         int error;
 1170 
 1171         if ((error = head->so_error) != 0) {
 1172                 head->so_error = 0;
 1173                 return error;
 1174         }
 1175         if (TAILQ_EMPTY(&head->so_comp)) {
 1176                 if (head->so_state & SS_CANTRCVMORE)
 1177                         return ECONNABORTED;
 1178                 return EWOULDBLOCK;
 1179         }
 1180         return 0;
 1181 }
 1182 
 1183 /*
 1184  * Handle the first completed incoming connection, assumed to be already
 1185  * on the socket's so_comp queue.
 1186  */
 1187 static void
 1188 ng_ksocket_finish_accept(priv_p priv)
 1189 {
 1190         struct socket *const head = priv->so;
 1191         struct socket *so;
 1192         struct sockaddr *sa = NULL;
 1193         struct ng_mesg *resp;
 1194         struct ng_ksocket_accept *resp_data;
 1195         node_p node;
 1196         priv_p priv2;
 1197         int len;
 1198         int error;
 1199 
 1200         so = TAILQ_FIRST(&head->so_comp);
 1201         if (so == NULL)         /* Should never happen */
 1202                 return;
 1203         TAILQ_REMOVE(&head->so_comp, so, so_list);
 1204         head->so_qlen--;
 1205 
 1206         /* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
 1207 
 1208         soref(so);
 1209 
 1210         so->so_state &= ~SS_COMP;
 1211         so->so_state |= SS_NBIO;
 1212         so->so_head = NULL;
 1213 
 1214         soaccept(so, &sa);
 1215 
 1216         len = OFFSETOF(struct ng_ksocket_accept, addr);
 1217         if (sa != NULL)
 1218                 len += sa->sa_len;
 1219 
 1220         NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
 1221             M_NOWAIT);
 1222         if (resp == NULL) {
 1223                 soclose(so);
 1224                 goto out;
 1225         }
 1226         resp->header.flags |= NGF_RESP;
 1227         resp->header.token = priv->response_token;
 1228 
 1229         /* Clone a ksocket node to wrap the new socket */
 1230         error = ng_make_node_common(&ng_ksocket_typestruct, &node);
 1231         if (error) {
 1232                 FREE(resp, M_NETGRAPH);
 1233                 soclose(so);
 1234                 goto out;
 1235         }
 1236 
 1237         if (ng_ksocket_constructor(node) != 0) {
 1238                 NG_NODE_UNREF(node);
 1239                 FREE(resp, M_NETGRAPH);
 1240                 soclose(so);
 1241                 goto out;
 1242         }
 1243 
 1244         priv2 = NG_NODE_PRIVATE(node);
 1245         priv2->so = so;
 1246         priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
 1247 
 1248         /*
 1249          * Insert the cloned node into a list of embryonic children
 1250          * on the parent node.  When a hook is created on the cloned
 1251          * node it will be removed from this list.  When the parent
 1252          * is destroyed it will destroy any embryonic children it has.
 1253          */
 1254         LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
 1255 
 1256         so->so_upcallarg = (caddr_t)node;
 1257         so->so_upcall = ng_ksocket_incoming;
 1258         so->so_rcv.sb_flags |= SB_UPCALL;
 1259         so->so_snd.sb_flags |= SB_UPCALL;
 1260 
 1261         /* Fill in the response data and send it or return it to the caller */
 1262         resp_data = (struct ng_ksocket_accept *)resp->data;
 1263         resp_data->nodeid = NG_NODE_ID(node);
 1264         if (sa != NULL)
 1265                 bcopy(sa, &resp_data->addr, sa->sa_len);
 1266         NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
 1267 
 1268 out:
 1269         if (sa != NULL)
 1270                 FREE(sa, M_SONAME);
 1271 }
 1272 
 1273 /*
 1274  * Parse out either an integer value or an alias.
 1275  */
 1276 static int
 1277 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
 1278         const char *s, int family)
 1279 {
 1280         int k, val;
 1281         char *eptr;
 1282 
 1283         /* Try aliases */
 1284         for (k = 0; aliases[k].name != NULL; k++) {
 1285                 if (strcmp(s, aliases[k].name) == 0
 1286                     && aliases[k].family == family)
 1287                         return aliases[k].value;
 1288         }
 1289 
 1290         /* Try parsing as a number */
 1291         val = (int)strtoul(s, &eptr, 10);
 1292         if (val < 0 || *eptr != '\0')
 1293                 return (-1);
 1294         return (val);
 1295 }
 1296 

Cache object: 5c818f1102392063e6eebf11b45e86e1


[ 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.