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

Cache object: a296f5c3947b7569884b528753cfc81f


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