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