Merge branch 'vendor/GCC44' into gcc441
[dragonfly.git] / sys / netgraph7 / 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: src/sys/netgraph/ng_ksocket.c,v 1.61 2008/03/07 21:12:56 mav Exp $
41  * $DragonFly: src/sys/netgraph7/ng_ksocket.c,v 1.2 2008/06/26 23:05:35 dillon Exp $
42  * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
43  */
44
45 /*
46  * Kernel socket node type.  This node type is basically a kernel-mode
47  * version of a socket... kindof like the reverse of the socket node type.
48  */
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/mbuf.h>
54 #include <sys/proc.h>
55 #include <sys/malloc.h>
56 #include <sys/ctype.h>
57 #include <sys/protosw.h>
58 #include <sys/errno.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/uio.h>
62 #include <sys/un.h>
63
64 #include "ng_message.h"
65 #include "netgraph.h"
66 #include "ng_parse.h"
67 #include "ng_ksocket.h"
68
69 #include <netinet/in.h>
70 #include <netatalk/at.h>
71
72 #ifdef NG_SEPARATE_MALLOC
73 MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock", "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 void     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 = index(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         MALLOC(priv, priv_p, sizeof(*priv),
528             M_NETGRAPH_KSOCKET, M_WAITOK | M_NULLOK | 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 = index(s1, '/')) == NULL)
572                         return (EINVAL);
573                 *s2++ = '\0';
574                 family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
575                 if (family == -1)
576                         return (EINVAL);
577                 s1 = s2;
578                 if ((s2 = index(s1, '/')) == NULL)
579                         return (EINVAL);
580                 *s2++ = '\0';
581                 type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
582                 if (type == -1)
583                         return (EINVAL);
584                 s1 = s2;
585                 protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
586                 if (protocol == -1)
587                         return (EINVAL);
588
589                 /* Create the socket */
590                 error = socreate(family, &priv->so, type, protocol,
591                    td->td_ucred, td);
592                 if (error != 0)
593                         return (error);
594
595                 /* XXX call soreserve() ? */
596
597         }
598
599         /* OK */
600         priv->hook = hook;
601
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         priv->so->so_upcallarg = (caddr_t)node;
621         priv->so->so_upcall = ng_ksocket_incoming;
622         SOCKBUF_LOCK(&priv->so->so_rcv);
623         priv->so->so_rcv.sb_flags |= SB_UPCALL;
624         SOCKBUF_UNLOCK(&priv->so->so_rcv);
625         SOCKBUF_LOCK(&priv->so->so_snd);
626         priv->so->so_snd.sb_flags |= SB_UPCALL;
627         SOCKBUF_UNLOCK(&priv->so->so_snd);
628         SOCK_LOCK(priv->so);
629         priv->so->so_state |= SS_NBIO;
630         SOCK_UNLOCK(priv->so);
631         /*
632          * --Original comment--
633          * On a cloned socket we may have already received one or more
634          * upcalls which we couldn't handle without a hook.  Handle
635          * those now.
636          * We cannot call the upcall function directly
637          * from here, because until this function has returned our
638          * hook isn't connected.
639          *
640          * ---meta comment for -current ---
641          * XXX This is dubius.
642          * Upcalls between the time that the hook was
643          * first created and now (on another processesor) will
644          * be earlier on the queue than the request to finalise the hook.
645          * By the time the hook is finalised,
646          * The queued upcalls will have happenned and the code
647          * will have discarded them because of a lack of a hook.
648          * (socket not open).
649          *
650          * This is a bad byproduct of the complicated way in which hooks
651          * are now created (3 daisy chained async events).
652          *
653          * Since we are a netgraph operation 
654          * We know that we hold a lock on this node. This forces the
655          * request we make below to be queued rather than implemented
656          * immediatly which will cause the upcall function to be called a bit
657          * later.
658          * However, as we will run any waiting queued operations immediatly
659          * after doing this one, if we have not finalised the other end
660          * of the hook, those queued operations will fail.
661          */
662         if (priv->flags & KSF_CLONED) {
663                 ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_WAITOK | M_NULLOK);
664         }
665
666         return (0);
667 }
668
669 /*
670  * Receive a control message
671  */
672 static int
673 ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
674 {
675         struct thread *td = curthread;  /* XXX broken */
676         const priv_p priv = NG_NODE_PRIVATE(node);
677         struct socket *const so = priv->so;
678         struct ng_mesg *resp = NULL;
679         int error = 0;
680         struct ng_mesg *msg;
681         ng_ID_t raddr;
682
683         NGI_GET_MSG(item, msg);
684         switch (msg->header.typecookie) {
685         case NGM_KSOCKET_COOKIE:
686                 switch (msg->header.cmd) {
687                 case NGM_KSOCKET_BIND:
688                     {
689                         struct sockaddr *const sa
690                             = (struct sockaddr *)msg->data;
691
692                         /* Sanity check */
693                         if (msg->header.arglen < SADATA_OFFSET
694                             || msg->header.arglen < sa->sa_len)
695                                 ERROUT(EINVAL);
696                         if (so == NULL)
697                                 ERROUT(ENXIO);
698
699                         /* Bind */
700                         error = sobind(so, sa, td);
701                         break;
702                     }
703                 case NGM_KSOCKET_LISTEN:
704                     {
705                         /* Sanity check */
706                         if (msg->header.arglen != sizeof(int32_t))
707                                 ERROUT(EINVAL);
708                         if (so == NULL)
709                                 ERROUT(ENXIO);
710
711                         /* Listen */
712                         error = solisten(so, *((int32_t *)msg->data), td);
713                         break;
714                     }
715
716                 case NGM_KSOCKET_ACCEPT:
717                     {
718                         /* Sanity check */
719                         if (msg->header.arglen != 0)
720                                 ERROUT(EINVAL);
721                         if (so == NULL)
722                                 ERROUT(ENXIO);
723
724                         /* Make sure the socket is capable of accepting */
725                         if (!(so->so_options & SO_ACCEPTCONN))
726                                 ERROUT(EINVAL);
727                         if (priv->flags & KSF_ACCEPTING)
728                                 ERROUT(EALREADY);
729
730                         error = ng_ksocket_check_accept(priv);
731                         if (error != 0 && error != EWOULDBLOCK)
732                                 ERROUT(error);
733
734                         /*
735                          * If a connection is already complete, take it.
736                          * Otherwise let the upcall function deal with
737                          * the connection when it comes in.
738                          */
739                         priv->response_token = msg->header.token;
740                         raddr = priv->response_addr = NGI_RETADDR(item);
741                         if (error == 0) {
742                                 ng_ksocket_finish_accept(priv);
743                         } else
744                                 priv->flags |= KSF_ACCEPTING;
745                         break;
746                     }
747
748                 case NGM_KSOCKET_CONNECT:
749                     {
750                         struct sockaddr *const sa
751                             = (struct sockaddr *)msg->data;
752
753                         /* Sanity check */
754                         if (msg->header.arglen < SADATA_OFFSET
755                             || msg->header.arglen < sa->sa_len)
756                                 ERROUT(EINVAL);
757                         if (so == NULL)
758                                 ERROUT(ENXIO);
759
760                         /* Do connect */
761                         if ((so->so_state & SS_ISCONNECTING) != 0)
762                                 ERROUT(EALREADY);
763                         if ((error = soconnect(so, sa, td)) != 0) {
764                                 so->so_state &= ~SS_ISCONNECTING;
765                                 ERROUT(error);
766                         }
767                         if ((so->so_state & SS_ISCONNECTING) != 0) {
768                                 /* We will notify the sender when we connect */
769                                 priv->response_token = msg->header.token;
770                                 raddr = priv->response_addr = NGI_RETADDR(item);
771                                 priv->flags |= KSF_CONNECTING;
772                                 ERROUT(EINPROGRESS);
773                         }
774                         break;
775                     }
776
777                 case NGM_KSOCKET_GETNAME:
778                 case NGM_KSOCKET_GETPEERNAME:
779                     {
780                         int (*func)(struct socket *so, struct sockaddr **nam);
781                         struct sockaddr *sa = NULL;
782                         int len;
783
784                         /* Sanity check */
785                         if (msg->header.arglen != 0)
786                                 ERROUT(EINVAL);
787                         if (so == NULL)
788                                 ERROUT(ENXIO);
789
790                         /* Get function */
791                         if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
792                                 if ((so->so_state
793                                     & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) 
794                                         ERROUT(ENOTCONN);
795                                 func = so->so_proto->pr_usrreqs->pru_peeraddr;
796                         } else
797                                 func = so->so_proto->pr_usrreqs->pru_sockaddr;
798
799                         /* Get local or peer address */
800                         if ((error = (*func)(so, &sa)) != 0)
801                                 goto bail;
802                         len = (sa == NULL) ? 0 : sa->sa_len;
803
804                         /* Send it back in a response */
805                         NG_MKRESPONSE(resp, msg, len, M_WAITOK | M_NULLOK);
806                         if (resp == NULL) {
807                                 error = ENOMEM;
808                                 goto bail;
809                         }
810                         bcopy(sa, resp->data, len);
811
812                 bail:
813                         /* Cleanup */
814                         if (sa != NULL)
815                                 FREE(sa, M_SONAME);
816                         break;
817                     }
818
819                 case NGM_KSOCKET_GETOPT:
820                     {
821                         struct ng_ksocket_sockopt *ksopt = 
822                             (struct ng_ksocket_sockopt *)msg->data;
823                         struct sockopt sopt;
824
825                         /* Sanity check */
826                         if (msg->header.arglen != sizeof(*ksopt))
827                                 ERROUT(EINVAL);
828                         if (so == NULL)
829                                 ERROUT(ENXIO);
830
831                         /* Get response with room for option value */
832                         NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
833                             + NG_KSOCKET_MAX_OPTLEN, M_WAITOK | M_NULLOK);
834                         if (resp == NULL)
835                                 ERROUT(ENOMEM);
836
837                         /* Get socket option, and put value in the response */
838                         sopt.sopt_dir = SOPT_GET;
839                         sopt.sopt_level = ksopt->level;
840                         sopt.sopt_name = ksopt->name;
841                         sopt.sopt_td = NULL;
842                         sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
843                         ksopt = (struct ng_ksocket_sockopt *)resp->data;
844                         sopt.sopt_val = ksopt->value;
845                         if ((error = sogetopt(so, &sopt)) != 0) {
846                                 NG_FREE_MSG(resp);
847                                 break;
848                         }
849
850                         /* Set actual value length */
851                         resp->header.arglen = sizeof(*ksopt)
852                             + sopt.sopt_valsize;
853                         break;
854                     }
855
856                 case NGM_KSOCKET_SETOPT:
857                     {
858                         struct ng_ksocket_sockopt *const ksopt = 
859                             (struct ng_ksocket_sockopt *)msg->data;
860                         const int valsize = msg->header.arglen - sizeof(*ksopt);
861                         struct sockopt sopt;
862
863                         /* Sanity check */
864                         if (valsize < 0)
865                                 ERROUT(EINVAL);
866                         if (so == NULL)
867                                 ERROUT(ENXIO);
868
869                         /* Set socket option */
870                         sopt.sopt_dir = SOPT_SET;
871                         sopt.sopt_level = ksopt->level;
872                         sopt.sopt_name = ksopt->name;
873                         sopt.sopt_val = ksopt->value;
874                         sopt.sopt_valsize = valsize;
875                         sopt.sopt_td = NULL;
876                         error = sosetopt(so, &sopt);
877                         break;
878                     }
879
880                 default:
881                         error = EINVAL;
882                         break;
883                 }
884                 break;
885         default:
886                 error = EINVAL;
887                 break;
888         }
889 done:
890         NG_RESPOND_MSG(error, node, item, resp);
891         NG_FREE_MSG(msg);
892         return (error);
893 }
894
895 /*
896  * Receive incoming data on our hook.  Send it out the socket.
897  */
898 static int
899 ng_ksocket_rcvdata(hook_p hook, item_p item)
900 {
901         struct thread *td = curthread;  /* XXX broken */
902         const node_p node = NG_HOOK_NODE(hook);
903         const priv_p priv = NG_NODE_PRIVATE(node);
904         struct socket *const so = priv->so;
905         struct sockaddr *sa = NULL;
906         int error;
907         struct mbuf *m;
908         struct sa_tag *stag;
909
910         /* Extract data */
911         NGI_GET_M(item, m);
912         NG_FREE_ITEM(item);
913
914         /*
915          * Look if socket address is stored in packet tags.
916          * If sockaddr is ours, or provided by a third party (zero id),
917          * then we accept it.
918          */
919         if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
920             NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
921             (stag->id == NG_NODE_ID(node) || stag->id == 0))
922                 sa = &stag->sa;
923
924         /* Reset specific mbuf flags to prevent addressing problems. */
925         m->m_flags &= ~(M_BCAST|M_MCAST);
926
927         /* Send packet */
928         error = sosend(so, sa, 0, m, 0, 0, td);
929
930         return (error);
931 }
932
933 /*
934  * Destroy node
935  */
936 static int
937 ng_ksocket_shutdown(node_p node)
938 {
939         const priv_p priv = NG_NODE_PRIVATE(node);
940         priv_p embryo;
941
942         /* Close our socket (if any) */
943         if (priv->so != NULL) {
944                 SOCKBUF_LOCK(&priv->so->so_rcv);
945                 priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
946                 SOCKBUF_UNLOCK(&priv->so->so_rcv);
947                 SOCKBUF_LOCK(&priv->so->so_snd);
948                 priv->so->so_snd.sb_flags &= ~SB_UPCALL;
949                 SOCKBUF_UNLOCK(&priv->so->so_snd);
950                 priv->so->so_upcall = NULL;
951                 soclose(priv->so);
952                 priv->so = NULL;
953         }
954
955         /* If we are an embryo, take ourselves out of the parent's list */
956         if (priv->flags & KSF_EMBRYONIC) {
957                 LIST_REMOVE(priv, siblings);
958                 priv->flags &= ~KSF_EMBRYONIC;
959         }
960
961         /* Remove any embryonic children we have */
962         while (!LIST_EMPTY(&priv->embryos)) {
963                 embryo = LIST_FIRST(&priv->embryos);
964                 ng_rmnode_self(embryo->node);
965         }
966
967         /* Take down netgraph node */
968         bzero(priv, sizeof(*priv));
969         FREE(priv, M_NETGRAPH_KSOCKET);
970         NG_NODE_SET_PRIVATE(node, NULL);
971         NG_NODE_UNREF(node);            /* let the node escape */
972         return (0);
973 }
974
975 /*
976  * Hook disconnection
977  */
978 static int
979 ng_ksocket_disconnect(hook_p hook)
980 {
981         KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
982             ("%s: numhooks=%d?", __func__,
983             NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
984         if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
985                 ng_rmnode_self(NG_HOOK_NODE(hook));
986         return (0);
987 }
988
989 /************************************************************************
990                         HELPER STUFF
991  ************************************************************************/
992 /* 
993  * You should not "just call" a netgraph node function from an external
994  * asynchronous event. This is because in doing so you are ignoring the
995  * locking on the netgraph nodes. Instead call your function via ng_send_fn().
996  * This will call the function you chose, but will first do all the 
997  * locking rigmarole. Your function MAY only be called at some distant future
998  * time (several millisecs away) so don't give it any arguments
999  * that may be revoked soon (e.g. on your stack).
1000  *
1001  * To decouple stack, we use queue version of ng_send_fn().
1002  */
1003
1004 static void
1005 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
1006 {
1007         const node_p node = arg;
1008         const priv_p priv = NG_NODE_PRIVATE(node);
1009         int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1010
1011         /*
1012          * Even if node is not locked, as soon as we are called, we assume
1013          * it exist and it's private area is valid. With some care we can
1014          * access it. Mark node that incoming event for it was sent to
1015          * avoid unneded queue trashing.
1016          */
1017         if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1018             ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1019                 atomic_store_rel_int(&priv->fn_sent, 0);
1020         }
1021 }
1022
1023
1024 /*
1025  * When incoming data is appended to the socket, we get notified here.
1026  * This is also called whenever a significant event occurs for the socket.
1027  * Our original caller may have queued this even some time ago and 
1028  * we cannot trust that he even still exists. The node however is being
1029  * held with a reference by the queueing code and guarantied to be valid.
1030  */
1031 static void
1032 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1033 {
1034         struct socket *so = arg1;
1035         const priv_p priv = NG_NODE_PRIVATE(node);
1036         struct mbuf *m;
1037         struct ng_mesg *response;
1038         struct uio auio;
1039         int s, flags, error;
1040
1041         s = splnet();
1042
1043         /* so = priv->so; *//* XXX could have derived this like so */
1044         KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1045         
1046         /* Allow next incoming event to be queued. */
1047         atomic_store_rel_int(&priv->fn_sent, 0);
1048
1049         /* Check whether a pending connect operation has completed */
1050         if (priv->flags & KSF_CONNECTING) {
1051                 if ((error = so->so_error) != 0) {
1052                         so->so_error = 0;
1053                         so->so_state &= ~SS_ISCONNECTING;
1054                 }
1055                 if (!(so->so_state & SS_ISCONNECTING)) {
1056                         NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1057                             NGM_KSOCKET_CONNECT, sizeof(int32_t), M_WAITOK | M_NULLOK);
1058                         if (response != NULL) {
1059                                 response->header.flags |= NGF_RESP;
1060                                 response->header.token = priv->response_token;
1061                                 *(int32_t *)response->data = error;
1062                                 /* 
1063                                  * send an async "response" message
1064                                  * to the node that set us up
1065                                  * (if it still exists)
1066                                  */
1067                                 NG_SEND_MSG_ID(error, node,
1068                                     response, priv->response_addr, 0);
1069                         }
1070                         priv->flags &= ~KSF_CONNECTING;
1071                 }
1072         }
1073
1074         /* Check whether a pending accept operation has completed */
1075         if (priv->flags & KSF_ACCEPTING) {
1076                 error = ng_ksocket_check_accept(priv);
1077                 if (error != EWOULDBLOCK)
1078                         priv->flags &= ~KSF_ACCEPTING;
1079                 if (error == 0)
1080                         ng_ksocket_finish_accept(priv);
1081         }
1082
1083         /*
1084          * If we don't have a hook, we must handle data events later.  When
1085          * the hook gets created and is connected, this upcall function
1086          * will be called again.
1087          */
1088         if (priv->hook == NULL) {
1089                 splx(s);
1090                 return;
1091         }
1092
1093         /* Read and forward available mbuf's */
1094         auio.uio_td = NULL;
1095         auio.uio_resid = 1000000000;
1096         flags = MSG_DONTWAIT;
1097         while (1) {
1098                 struct sockaddr *sa = NULL;
1099                 struct mbuf *n;
1100
1101                 /* Try to get next packet from socket */
1102                 if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1103                     NULL : &sa, &auio, &m, NULL, &flags)) != 0)
1104                         break;
1105
1106                 /* See if we got anything */
1107                 if (m == NULL) {
1108                         if (sa != NULL)
1109                                 FREE(sa, M_SONAME);
1110                         break;
1111                 }
1112
1113                 /*
1114                  * Don't trust the various socket layers to get the
1115                  * packet header and length correct (e.g. kern/15175).
1116                  *
1117                  * Also, do not trust that soreceive() will clear m_nextpkt
1118                  * for us (e.g. kern/84952, kern/82413).
1119                  */
1120                 m->m_pkthdr.csum_flags = 0;
1121                 for (n = m, m->m_pkthdr.len = 0; n != NULL; n = n->m_next) {
1122                         m->m_pkthdr.len += n->m_len;
1123                         n->m_nextpkt = NULL;
1124                 }
1125
1126                 /* Put peer's socket address (if any) into a tag */
1127                 if (sa != NULL) {
1128                         struct sa_tag   *stag;
1129
1130                         stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1131                             NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1132                             sa->sa_len, MB_DONTWAIT);
1133                         if (stag == NULL) {
1134                                 FREE(sa, M_SONAME);
1135                                 goto sendit;
1136                         }
1137                         bcopy(sa, &stag->sa, sa->sa_len);
1138                         FREE(sa, M_SONAME);
1139                         stag->id = NG_NODE_ID(node);
1140                         m_tag_prepend(m, &stag->tag);
1141                 }
1142
1143 sendit:         /* Forward data with optional peer sockaddr as packet tag */
1144                 NG_SEND_DATA_ONLY(error, priv->hook, m);
1145         }
1146
1147         /*
1148          * If the peer has closed the connection, forward a 0-length mbuf
1149          * to indicate end-of-file.
1150          */
1151         if (so->so_rcv.sb_state & SBS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1152                 MGETHDR(m, MB_DONTWAIT, MT_DATA);
1153                 if (m != NULL) {
1154                         m->m_len = m->m_pkthdr.len = 0;
1155                         NG_SEND_DATA_ONLY(error, priv->hook, m);
1156                 }
1157                 priv->flags |= KSF_EOFSEEN;
1158         }
1159         splx(s);
1160 }
1161
1162 /*
1163  * Check for a completed incoming connection and return 0 if one is found.
1164  * Otherwise return the appropriate error code.
1165  */
1166 static int
1167 ng_ksocket_check_accept(priv_p priv)
1168 {
1169         struct socket *const head = priv->so;
1170         int error;
1171
1172         if ((error = head->so_error) != 0) {
1173                 head->so_error = 0;
1174                 return error;
1175         }
1176         /* Unlocked read. */
1177         if (TAILQ_EMPTY(&head->so_comp)) {
1178                 if (head->so_rcv.sb_state & SBS_CANTRCVMORE)
1179                         return ECONNABORTED;
1180                 return EWOULDBLOCK;
1181         }
1182         return 0;
1183 }
1184
1185 /*
1186  * Handle the first completed incoming connection, assumed to be already
1187  * on the socket's so_comp queue.
1188  */
1189 static void
1190 ng_ksocket_finish_accept(priv_p priv)
1191 {
1192         struct socket *const head = priv->so;
1193         struct socket *so;
1194         struct sockaddr *sa = NULL;
1195         struct ng_mesg *resp;
1196         struct ng_ksocket_accept *resp_data;
1197         node_p node;
1198         priv_p priv2;
1199         int len;
1200         int error;
1201
1202         ACCEPT_LOCK();
1203         so = TAILQ_FIRST(&head->so_comp);
1204         if (so == NULL) {       /* Should never happen */
1205                 ACCEPT_UNLOCK();
1206                 return;
1207         }
1208         TAILQ_REMOVE(&head->so_comp, so, so_list);
1209         head->so_qlen--;
1210         so->so_qstate &= ~SQ_COMP;
1211         so->so_head = NULL;
1212         SOCK_LOCK(so);
1213         soref(so);
1214         so->so_state |= SS_NBIO;
1215         SOCK_UNLOCK(so);
1216         ACCEPT_UNLOCK();
1217
1218         /* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
1219
1220         soaccept(so, &sa);
1221
1222         len = OFFSETOF(struct ng_ksocket_accept, addr);
1223         if (sa != NULL)
1224                 len += sa->sa_len;
1225
1226         NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1227             M_WAITOK | M_NULLOK);
1228         if (resp == NULL) {
1229                 soclose(so);
1230                 goto out;
1231         }
1232         resp->header.flags |= NGF_RESP;
1233         resp->header.token = priv->response_token;
1234
1235         /* Clone a ksocket node to wrap the new socket */
1236         error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1237         if (error) {
1238                 FREE(resp, M_NETGRAPH);
1239                 soclose(so);
1240                 goto out;
1241         }
1242
1243         if (ng_ksocket_constructor(node) != 0) {
1244                 NG_NODE_UNREF(node);
1245                 FREE(resp, M_NETGRAPH);
1246                 soclose(so);
1247                 goto out;
1248         }
1249
1250         priv2 = NG_NODE_PRIVATE(node);
1251         priv2->so = so;
1252         priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1253
1254         /*
1255          * Insert the cloned node into a list of embryonic children
1256          * on the parent node.  When a hook is created on the cloned
1257          * node it will be removed from this list.  When the parent
1258          * is destroyed it will destroy any embryonic children it has.
1259          */
1260         LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1261
1262         so->so_upcallarg = (caddr_t)node;
1263         so->so_upcall = ng_ksocket_incoming;
1264         SOCKBUF_LOCK(&so->so_rcv);
1265         so->so_rcv.sb_flags |= SB_UPCALL;
1266         SOCKBUF_UNLOCK(&so->so_rcv);
1267         SOCKBUF_LOCK(&so->so_snd);
1268         so->so_snd.sb_flags |= SB_UPCALL;
1269         SOCKBUF_UNLOCK(&so->so_snd);
1270
1271         /* Fill in the response data and send it or return it to the caller */
1272         resp_data = (struct ng_ksocket_accept *)resp->data;
1273         resp_data->nodeid = NG_NODE_ID(node);
1274         if (sa != NULL)
1275                 bcopy(sa, &resp_data->addr, sa->sa_len);
1276         NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1277
1278 out:
1279         if (sa != NULL)
1280                 FREE(sa, M_SONAME);
1281 }
1282
1283 /*
1284  * Parse out either an integer value or an alias.
1285  */
1286 static int
1287 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1288         const char *s, int family)
1289 {
1290         int k, val;
1291         char *eptr;
1292
1293         /* Try aliases */
1294         for (k = 0; aliases[k].name != NULL; k++) {
1295                 if (strcmp(s, aliases[k].name) == 0
1296                     && aliases[k].family == family)
1297                         return aliases[k].value;
1298         }
1299
1300         /* Try parsing as a number */
1301         val = (int)strtoul(s, &eptr, 10);
1302         if (val < 0 || *eptr != '\0')
1303                 return (-1);
1304         return (val);
1305 }
1306