xref: /freebsd/sys/netgraph/ng_ksocket.c (revision 9336e0699bda8a301cd2bfa37106b6ec5e32012e)
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 <netatalk/at.h>
70 
71 #ifdef NG_SEPARATE_MALLOC
72 MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock", "netgraph ksock node ");
73 #else
74 #define M_NETGRAPH_KSOCKET M_NETGRAPH
75 #endif
76 
77 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
78 #define SADATA_OFFSET	(OFFSETOF(struct sockaddr, sa_data))
79 
80 /* Node private data */
81 struct ng_ksocket_private {
82 	node_p		node;
83 	hook_p		hook;
84 	struct socket	*so;
85 	LIST_HEAD(, ng_ksocket_private)	embryos;
86 	LIST_ENTRY(ng_ksocket_private)	siblings;
87 	u_int32_t	flags;
88 	u_int32_t	response_token;
89 	ng_ID_t		response_addr;
90 };
91 typedef struct ng_ksocket_private *priv_p;
92 
93 /* Flags for priv_p */
94 #define	KSF_CONNECTING	0x00000001	/* Waiting for connection complete */
95 #define	KSF_ACCEPTING	0x00000002	/* Waiting for accept complete */
96 #define	KSF_EOFSEEN	0x00000004	/* Have sent 0-length EOF mbuf */
97 #define	KSF_CLONED	0x00000008	/* Cloned from an accepting socket */
98 #define	KSF_EMBRYONIC	0x00000010	/* Cloned node with no hooks yet */
99 
100 /* Netgraph node methods */
101 static ng_constructor_t	ng_ksocket_constructor;
102 static ng_rcvmsg_t	ng_ksocket_rcvmsg;
103 static ng_shutdown_t	ng_ksocket_shutdown;
104 static ng_newhook_t	ng_ksocket_newhook;
105 static ng_rcvdata_t	ng_ksocket_rcvdata;
106 static ng_connect_t	ng_ksocket_connect;
107 static ng_disconnect_t	ng_ksocket_disconnect;
108 
109 /* Alias structure */
110 struct ng_ksocket_alias {
111 	const char	*name;
112 	const int	value;
113 	const int	family;
114 };
115 
116 /* Protocol family aliases */
117 static const struct ng_ksocket_alias ng_ksocket_families[] = {
118 	{ "local",	PF_LOCAL	},
119 	{ "inet",	PF_INET		},
120 	{ "inet6",	PF_INET6	},
121 	{ "atalk",	PF_APPLETALK	},
122 	{ "ipx",	PF_IPX		},
123 	{ "atm",	PF_ATM		},
124 	{ NULL,		-1		},
125 };
126 
127 /* Socket type aliases */
128 static const struct ng_ksocket_alias ng_ksocket_types[] = {
129 	{ "stream",	SOCK_STREAM	},
130 	{ "dgram",	SOCK_DGRAM	},
131 	{ "raw",	SOCK_RAW	},
132 	{ "rdm",	SOCK_RDM	},
133 	{ "seqpacket",	SOCK_SEQPACKET	},
134 	{ NULL,		-1		},
135 };
136 
137 /* Protocol aliases */
138 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
139 	{ "ip",		IPPROTO_IP,		PF_INET		},
140 	{ "raw",	IPPROTO_RAW,		PF_INET		},
141 	{ "icmp",	IPPROTO_ICMP,		PF_INET		},
142 	{ "igmp",	IPPROTO_IGMP,		PF_INET		},
143 	{ "tcp",	IPPROTO_TCP,		PF_INET		},
144 	{ "udp",	IPPROTO_UDP,		PF_INET		},
145 	{ "gre",	IPPROTO_GRE,		PF_INET		},
146 	{ "esp",	IPPROTO_ESP,		PF_INET		},
147 	{ "ah",		IPPROTO_AH,		PF_INET		},
148 	{ "swipe",	IPPROTO_SWIPE,		PF_INET		},
149 	{ "encap",	IPPROTO_ENCAP,		PF_INET		},
150 	{ "divert",	IPPROTO_DIVERT,		PF_INET		},
151 	{ "pim",	IPPROTO_PIM,		PF_INET		},
152 	{ "ddp",	ATPROTO_DDP,		PF_APPLETALK	},
153 	{ "aarp",	ATPROTO_AARP,		PF_APPLETALK	},
154 	{ NULL,		-1					},
155 };
156 
157 /* Helper functions */
158 static int	ng_ksocket_check_accept(priv_p);
159 static void	ng_ksocket_finish_accept(priv_p);
160 static void	ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
161 static int	ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
162 			const char *s, int family);
163 static void	ng_ksocket_incoming2(node_p node, hook_p hook,
164 			void *arg1, int waitflag);
165 
166 /************************************************************************
167 			STRUCT SOCKADDR PARSE TYPE
168  ************************************************************************/
169 
170 /* Get the length of the data portion of a generic struct sockaddr */
171 static int
172 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
173 	const u_char *start, const u_char *buf)
174 {
175 	const struct sockaddr *sa;
176 
177 	sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
178 	return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
179 }
180 
181 /* Type for the variable length data portion of a generic struct sockaddr */
182 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
183 	&ng_parse_bytearray_type,
184 	&ng_parse_generic_sockdata_getLength
185 };
186 
187 /* Type for a generic struct sockaddr */
188 static const struct ng_parse_struct_field
189     ng_parse_generic_sockaddr_type_fields[] = {
190 	  { "len",	&ng_parse_uint8_type			},
191 	  { "family",	&ng_parse_uint8_type			},
192 	  { "data",	&ng_ksocket_generic_sockdata_type	},
193 	  { NULL }
194 };
195 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
196 	&ng_parse_struct_type,
197 	&ng_parse_generic_sockaddr_type_fields
198 };
199 
200 /* Convert a struct sockaddr from ASCII to binary.  If its a protocol
201    family that we specially handle, do that, otherwise defer to the
202    generic parse type ng_ksocket_generic_sockaddr_type. */
203 static int
204 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
205 	const char *s, int *off, const u_char *const start,
206 	u_char *const buf, int *buflen)
207 {
208 	struct sockaddr *const sa = (struct sockaddr *)buf;
209 	enum ng_parse_token tok;
210 	char fambuf[32];
211 	int family, len;
212 	char *t;
213 
214 	/* If next token is a left curly brace, use generic parse type */
215 	if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
216 		return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
217 		    (&ng_ksocket_generic_sockaddr_type,
218 		    s, off, start, buf, buflen);
219 	}
220 
221 	/* Get socket address family followed by a slash */
222 	while (isspace(s[*off]))
223 		(*off)++;
224 	if ((t = index(s + *off, '/')) == NULL)
225 		return (EINVAL);
226 	if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
227 		return (EINVAL);
228 	strncpy(fambuf, s + *off, len);
229 	fambuf[len] = '\0';
230 	*off += len + 1;
231 	if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
232 		return (EINVAL);
233 
234 	/* Set family */
235 	if (*buflen < SADATA_OFFSET)
236 		return (ERANGE);
237 	sa->sa_family = family;
238 
239 	/* Set family-specific data and length */
240 	switch (sa->sa_family) {
241 	case PF_LOCAL:		/* Get pathname */
242 	    {
243 		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
244 		struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
245 		int toklen, pathlen;
246 		char *path;
247 
248 		if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
249 			return (EINVAL);
250 		pathlen = strlen(path);
251 		if (pathlen > SOCK_MAXADDRLEN) {
252 			FREE(path, M_NETGRAPH_KSOCKET);
253 			return (E2BIG);
254 		}
255 		if (*buflen < pathoff + pathlen) {
256 			FREE(path, M_NETGRAPH_KSOCKET);
257 			return (ERANGE);
258 		}
259 		*off += toklen;
260 		bcopy(path, sun->sun_path, pathlen);
261 		sun->sun_len = pathoff + pathlen;
262 		FREE(path, M_NETGRAPH_KSOCKET);
263 		break;
264 	    }
265 
266 	case PF_INET:		/* Get an IP address with optional port */
267 	    {
268 		struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
269 		int i;
270 
271 		/* Parse this: <ipaddress>[:port] */
272 		for (i = 0; i < 4; i++) {
273 			u_long val;
274 			char *eptr;
275 
276 			val = strtoul(s + *off, &eptr, 10);
277 			if (val > 0xff || eptr == s + *off)
278 				return (EINVAL);
279 			*off += (eptr - (s + *off));
280 			((u_char *)&sin->sin_addr)[i] = (u_char)val;
281 			if (i < 3) {
282 				if (s[*off] != '.')
283 					return (EINVAL);
284 				(*off)++;
285 			} else if (s[*off] == ':') {
286 				(*off)++;
287 				val = strtoul(s + *off, &eptr, 10);
288 				if (val > 0xffff || eptr == s + *off)
289 					return (EINVAL);
290 				*off += (eptr - (s + *off));
291 				sin->sin_port = htons(val);
292 			} else
293 				sin->sin_port = 0;
294 		}
295 		bzero(&sin->sin_zero, sizeof(sin->sin_zero));
296 		sin->sin_len = sizeof(*sin);
297 		break;
298 	    }
299 
300 #if 0
301 	case PF_APPLETALK:	/* XXX implement these someday */
302 	case PF_INET6:
303 	case PF_IPX:
304 #endif
305 
306 	default:
307 		return (EINVAL);
308 	}
309 
310 	/* Done */
311 	*buflen = sa->sa_len;
312 	return (0);
313 }
314 
315 /* Convert a struct sockaddr from binary to ASCII */
316 static int
317 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
318 	const u_char *data, int *off, char *cbuf, int cbuflen)
319 {
320 	const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
321 	int slen = 0;
322 
323 	/* Output socket address, either in special or generic format */
324 	switch (sa->sa_family) {
325 	case PF_LOCAL:
326 	    {
327 		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
328 		const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
329 		const int pathlen = sun->sun_len - pathoff;
330 		char pathbuf[SOCK_MAXADDRLEN + 1];
331 		char *pathtoken;
332 
333 		bcopy(sun->sun_path, pathbuf, pathlen);
334 		if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
335 			return (ENOMEM);
336 		slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
337 		FREE(pathtoken, M_NETGRAPH_KSOCKET);
338 		if (slen >= cbuflen)
339 			return (ERANGE);
340 		*off += sun->sun_len;
341 		return (0);
342 	    }
343 
344 	case PF_INET:
345 	    {
346 		const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
347 
348 		slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
349 		  ((const u_char *)&sin->sin_addr)[0],
350 		  ((const u_char *)&sin->sin_addr)[1],
351 		  ((const u_char *)&sin->sin_addr)[2],
352 		  ((const u_char *)&sin->sin_addr)[3]);
353 		if (sin->sin_port != 0) {
354 			slen += snprintf(cbuf + strlen(cbuf),
355 			    cbuflen - strlen(cbuf), ":%d",
356 			    (u_int)ntohs(sin->sin_port));
357 		}
358 		if (slen >= cbuflen)
359 			return (ERANGE);
360 		*off += sizeof(*sin);
361 		return(0);
362 	    }
363 
364 #if 0
365 	case PF_APPLETALK:	/* XXX implement these someday */
366 	case PF_INET6:
367 	case PF_IPX:
368 #endif
369 
370 	default:
371 		return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
372 		    (&ng_ksocket_generic_sockaddr_type,
373 		    data, off, cbuf, cbuflen);
374 	}
375 }
376 
377 /* Parse type for struct sockaddr */
378 static const struct ng_parse_type ng_ksocket_sockaddr_type = {
379 	NULL,
380 	NULL,
381 	NULL,
382 	&ng_ksocket_sockaddr_parse,
383 	&ng_ksocket_sockaddr_unparse,
384 	NULL		/* no such thing as a default struct sockaddr */
385 };
386 
387 /************************************************************************
388 		STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
389  ************************************************************************/
390 
391 /* Get length of the struct ng_ksocket_sockopt value field, which is the
392    just the excess of the message argument portion over the length of
393    the struct ng_ksocket_sockopt. */
394 static int
395 ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
396 	const u_char *start, const u_char *buf)
397 {
398 	static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
399 	const struct ng_ksocket_sockopt *sopt;
400 	const struct ng_mesg *msg;
401 
402 	sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
403 	msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
404 	return msg->header.arglen - sizeof(*sopt);
405 }
406 
407 /* Parse type for the option value part of a struct ng_ksocket_sockopt
408    XXX Eventually, we should handle the different socket options specially.
409    XXX This would avoid byte order problems, eg an integer value of 1 is
410    XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
411 static const struct ng_parse_type ng_ksocket_sockoptval_type = {
412 	&ng_parse_bytearray_type,
413 	&ng_parse_sockoptval_getLength
414 };
415 
416 /* Parse type for struct ng_ksocket_sockopt */
417 static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
418 	= NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
419 static const struct ng_parse_type ng_ksocket_sockopt_type = {
420 	&ng_parse_struct_type,
421 	&ng_ksocket_sockopt_type_fields
422 };
423 
424 /* Parse type for struct ng_ksocket_accept */
425 static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
426 	= NGM_KSOCKET_ACCEPT_INFO;
427 static const struct ng_parse_type ng_ksocket_accept_type = {
428 	&ng_parse_struct_type,
429 	&ng_ksocket_accept_type_fields
430 };
431 
432 /* List of commands and how to convert arguments to/from ASCII */
433 static const struct ng_cmdlist ng_ksocket_cmds[] = {
434 	{
435 	  NGM_KSOCKET_COOKIE,
436 	  NGM_KSOCKET_BIND,
437 	  "bind",
438 	  &ng_ksocket_sockaddr_type,
439 	  NULL
440 	},
441 	{
442 	  NGM_KSOCKET_COOKIE,
443 	  NGM_KSOCKET_LISTEN,
444 	  "listen",
445 	  &ng_parse_int32_type,
446 	  NULL
447 	},
448 	{
449 	  NGM_KSOCKET_COOKIE,
450 	  NGM_KSOCKET_ACCEPT,
451 	  "accept",
452 	  NULL,
453 	  &ng_ksocket_accept_type
454 	},
455 	{
456 	  NGM_KSOCKET_COOKIE,
457 	  NGM_KSOCKET_CONNECT,
458 	  "connect",
459 	  &ng_ksocket_sockaddr_type,
460 	  &ng_parse_int32_type
461 	},
462 	{
463 	  NGM_KSOCKET_COOKIE,
464 	  NGM_KSOCKET_GETNAME,
465 	  "getname",
466 	  NULL,
467 	  &ng_ksocket_sockaddr_type
468 	},
469 	{
470 	  NGM_KSOCKET_COOKIE,
471 	  NGM_KSOCKET_GETPEERNAME,
472 	  "getpeername",
473 	  NULL,
474 	  &ng_ksocket_sockaddr_type
475 	},
476 	{
477 	  NGM_KSOCKET_COOKIE,
478 	  NGM_KSOCKET_SETOPT,
479 	  "setopt",
480 	  &ng_ksocket_sockopt_type,
481 	  NULL
482 	},
483 	{
484 	  NGM_KSOCKET_COOKIE,
485 	  NGM_KSOCKET_GETOPT,
486 	  "getopt",
487 	  &ng_ksocket_sockopt_type,
488 	  &ng_ksocket_sockopt_type
489 	},
490 	{ 0 }
491 };
492 
493 /* Node type descriptor */
494 static struct ng_type ng_ksocket_typestruct = {
495 	.version =	NG_ABI_VERSION,
496 	.name =		NG_KSOCKET_NODE_TYPE,
497 	.constructor =	ng_ksocket_constructor,
498 	.rcvmsg =	ng_ksocket_rcvmsg,
499 	.shutdown =	ng_ksocket_shutdown,
500 	.newhook =	ng_ksocket_newhook,
501 	.connect =	ng_ksocket_connect,
502 	.rcvdata =	ng_ksocket_rcvdata,
503 	.disconnect =	ng_ksocket_disconnect,
504 	.cmdlist =	ng_ksocket_cmds,
505 };
506 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
507 
508 #define ERROUT(x)	do { error = (x); goto done; } while (0)
509 
510 /************************************************************************
511 			NETGRAPH NODE STUFF
512  ************************************************************************/
513 
514 /*
515  * Node type constructor
516  * The NODE part is assumed to be all set up.
517  * There is already a reference to the node for us.
518  */
519 static int
520 ng_ksocket_constructor(node_p node)
521 {
522 	priv_p priv;
523 
524 	/* Allocate private structure */
525 	MALLOC(priv, priv_p, sizeof(*priv),
526 	    M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
527 	if (priv == NULL)
528 		return (ENOMEM);
529 
530 	LIST_INIT(&priv->embryos);
531 	/* cross link them */
532 	priv->node = node;
533 	NG_NODE_SET_PRIVATE(node, priv);
534 
535 	/* Done */
536 	return (0);
537 }
538 
539 /*
540  * Give our OK for a hook to be added. The hook name is of the
541  * form "<family>/<type>/<proto>" where the three components may
542  * be decimal numbers or else aliases from the above lists.
543  *
544  * Connecting a hook amounts to opening the socket.  Disconnecting
545  * the hook closes the socket and destroys the node as well.
546  */
547 static int
548 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
549 {
550 	struct thread *td = curthread;	/* XXX broken */
551 	const priv_p priv = NG_NODE_PRIVATE(node);
552 	char *s1, *s2, name[NG_HOOKSIZ];
553 	int family, type, protocol, error;
554 
555 	/* Check if we're already connected */
556 	if (priv->hook != NULL)
557 		return (EISCONN);
558 
559 	if (priv->flags & KSF_CLONED) {
560 		if (priv->flags & KSF_EMBRYONIC) {
561 			/* Remove ourselves from our parent's embryo list */
562 			LIST_REMOVE(priv, siblings);
563 			priv->flags &= ~KSF_EMBRYONIC;
564 		}
565 	} else {
566 		/* Extract family, type, and protocol from hook name */
567 		snprintf(name, sizeof(name), "%s", name0);
568 		s1 = name;
569 		if ((s2 = index(s1, '/')) == NULL)
570 			return (EINVAL);
571 		*s2++ = '\0';
572 		family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
573 		if (family == -1)
574 			return (EINVAL);
575 		s1 = s2;
576 		if ((s2 = index(s1, '/')) == NULL)
577 			return (EINVAL);
578 		*s2++ = '\0';
579 		type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
580 		if (type == -1)
581 			return (EINVAL);
582 		s1 = s2;
583 		protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
584 		if (protocol == -1)
585 			return (EINVAL);
586 
587 		/* Create the socket */
588 		error = socreate(family, &priv->so, type, protocol,
589 		   td->td_ucred, td);
590 		if (error != 0)
591 			return (error);
592 
593 		/* XXX call soreserve() ? */
594 
595 	}
596 
597 	/* OK */
598 	priv->hook = hook;
599 
600 	/*
601 	 * In case of misconfigured routing a packet may reenter
602 	 * ksocket node recursively. Decouple stack to avoid possible
603 	 * panics about sleeping with locks held.
604 	 */
605 	NG_HOOK_FORCE_QUEUE(hook);
606 
607 	return(0);
608 }
609 
610 static int
611 ng_ksocket_connect(hook_p hook)
612 {
613 	node_p node = NG_HOOK_NODE(hook);
614 	const priv_p priv = NG_NODE_PRIVATE(node);
615 	struct socket *const so = priv->so;
616 
617 	/* Add our hook for incoming data and other events */
618 	priv->so->so_upcallarg = (caddr_t)node;
619 	priv->so->so_upcall = ng_ksocket_incoming;
620 	SOCKBUF_LOCK(&priv->so->so_rcv);
621 	priv->so->so_rcv.sb_flags |= SB_UPCALL;
622 	SOCKBUF_UNLOCK(&priv->so->so_rcv);
623 	SOCKBUF_LOCK(&priv->so->so_snd);
624 	priv->so->so_snd.sb_flags |= SB_UPCALL;
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 	struct sa_tag *stag;
907 
908 	/* Extract data */
909 	NGI_GET_M(item, m);
910 	NG_FREE_ITEM(item);
911 
912 	/*
913 	 * Look if socket address is stored in packet tags.
914 	 * If sockaddr is ours, or provided by a third party (zero id),
915 	 * then we accept it.
916 	 */
917 	if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
918 	    NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
919 	    (stag->id == NG_NODE_ID(node) || stag->id == 0))
920 		sa = &stag->sa;
921 
922 	/* Reset specific mbuf flags to prevent addressing problems. */
923 	m->m_flags &= ~(M_BCAST|M_MCAST);
924 
925 	/* Send packet */
926 	error = sosend(so, sa, 0, m, 0, 0, td);
927 
928 	return (error);
929 }
930 
931 /*
932  * Destroy node
933  */
934 static int
935 ng_ksocket_shutdown(node_p node)
936 {
937 	const priv_p priv = NG_NODE_PRIVATE(node);
938 	priv_p embryo;
939 
940 	/* Close our socket (if any) */
941 	if (priv->so != NULL) {
942 		priv->so->so_upcall = NULL;
943 		SOCKBUF_LOCK(&priv->so->so_rcv);
944 		priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
945 		SOCKBUF_UNLOCK(&priv->so->so_rcv);
946 		SOCKBUF_LOCK(&priv->so->so_snd);
947 		priv->so->so_snd.sb_flags &= ~SB_UPCALL;
948 		SOCKBUF_UNLOCK(&priv->so->so_snd);
949 		soclose(priv->so);
950 		priv->so = NULL;
951 	}
952 
953 	/* If we are an embryo, take ourselves out of the parent's list */
954 	if (priv->flags & KSF_EMBRYONIC) {
955 		LIST_REMOVE(priv, siblings);
956 		priv->flags &= ~KSF_EMBRYONIC;
957 	}
958 
959 	/* Remove any embryonic children we have */
960 	while (!LIST_EMPTY(&priv->embryos)) {
961 		embryo = LIST_FIRST(&priv->embryos);
962 		ng_rmnode_self(embryo->node);
963 	}
964 
965 	/* Take down netgraph node */
966 	bzero(priv, sizeof(*priv));
967 	FREE(priv, M_NETGRAPH_KSOCKET);
968 	NG_NODE_SET_PRIVATE(node, NULL);
969 	NG_NODE_UNREF(node);		/* let the node escape */
970 	return (0);
971 }
972 
973 /*
974  * Hook disconnection
975  */
976 static int
977 ng_ksocket_disconnect(hook_p hook)
978 {
979 	KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
980 	    ("%s: numhooks=%d?", __func__,
981 	    NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
982 	if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
983 		ng_rmnode_self(NG_HOOK_NODE(hook));
984 	return (0);
985 }
986 
987 /************************************************************************
988 			HELPER STUFF
989  ************************************************************************/
990 /*
991  * You should no-longer "just call" a netgraph node function
992  * from an external asynchronous event.
993  * This is because in doing so you are ignoring the locking on the netgraph
994  * nodes. Instead call your function via
995  * "int ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn,
996  *	 void *arg1, int arg2);"
997  * this will call the function you chose, but will first do all the
998  * locking rigmarole. Your function MAY only be called at some distant future
999  * time (several millisecs away) so don't give it any arguments
1000  * that may be revoked soon (e.g. on your stack).
1001  * In this case even the 'so' argument is doubtful.
1002  * While the function request is being processed the node
1003  * has an extra reference and as such will not disappear until
1004  * the request has at least been done, but the 'so' may not be so lucky.
1005  * handle this by checking the validity of the node in the target function
1006  * before dereferencing the socket pointer.
1007  *
1008  * To decouple stack, we use queue version of ng_send_fn().
1009  */
1010 
1011 static void
1012 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
1013 {
1014 	const node_p node = arg;
1015 	int wait;
1016 
1017 	wait = (waitflag & M_WAITOK) ? NG_WAITOK : 0;
1018 	ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, waitflag,
1019 	    wait | NG_QUEUE);
1020 }
1021 
1022 
1023 /*
1024  * When incoming data is appended to the socket, we get notified here.
1025  * This is also called whenever a significant event occurs for the socket.
1026  * We know that HOOK is NULL. Because of how we were called we know we have a
1027  * lock on this node an are participating inthe netgraph locking.
1028  * Our original caller may have queued this even some time ago and
1029  * we cannot trust that he even still exists. The node however is being
1030  * held with a reference by the queueing code, at least until we finish,
1031  * even if it has been zapped, so first check it's validiy
1032  * before we trust the socket (which was derived from it).
1033  */
1034 static void
1035 ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int waitflag)
1036 {
1037 	struct socket *so = arg1;
1038 	const priv_p priv = NG_NODE_PRIVATE(node);
1039 	struct mbuf *m;
1040 	struct ng_mesg *response;
1041 	struct uio auio;
1042 	int s, flags, error;
1043 
1044 	s = splnet();
1045 
1046 	/* Sanity check */
1047 	if (NG_NODE_NOT_VALID(node)) {
1048 		splx(s);
1049 		return;
1050 	}
1051 	/* so = priv->so; *//* XXX could have derived this like so */
1052 	KASSERT(so == priv->so, ("%s: wrong socket", __func__));
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), waitflag);
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 		splx(s);
1095 		return;
1096 	}
1097 
1098 	/* Read and forward available mbuf's */
1099 	auio.uio_td = NULL;
1100 	auio.uio_resid = 1000000000;
1101 	flags = MSG_DONTWAIT;
1102 	while (1) {
1103 		struct sockaddr *sa = NULL;
1104 		struct mbuf *n;
1105 
1106 		/* Try to get next packet from socket */
1107 		if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1108 		    NULL : &sa, &auio, &m, (struct mbuf **)0, &flags)) != 0)
1109 			break;
1110 
1111 		/* See if we got anything */
1112 		if (m == NULL) {
1113 			if (sa != NULL)
1114 				FREE(sa, M_SONAME);
1115 			break;
1116 		}
1117 
1118 		/*
1119 		 * Don't trust the various socket layers to get the
1120 		 * packet header and length correct (e.g. kern/15175).
1121 		 *
1122 		 * Also, do not trust that soreceive() will clear m_nextpkt
1123 		 * for us (e.g. kern/84952, kern/82413).
1124 		 */
1125 		m->m_pkthdr.csum_flags = 0;
1126 		for (n = m, m->m_pkthdr.len = 0; n != NULL; n = n->m_next) {
1127 			m->m_pkthdr.len += n->m_len;
1128 			n->m_nextpkt = NULL;
1129 		}
1130 
1131 		/* Put peer's socket address (if any) into a tag */
1132 		if (sa != NULL) {
1133 			struct sa_tag	*stag;
1134 
1135 			stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1136 			    NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1137 			    sa->sa_len, M_NOWAIT);
1138 			if (stag == NULL) {
1139 				FREE(sa, M_SONAME);
1140 				goto sendit;
1141 			}
1142 			bcopy(sa, &stag->sa, sa->sa_len);
1143 			FREE(sa, M_SONAME);
1144 			stag->id = NG_NODE_ID(node);
1145 			m_tag_prepend(m, &stag->tag);
1146 		}
1147 
1148 sendit:		/* Forward data with optional peer sockaddr as packet tag */
1149 		NG_SEND_DATA_ONLY(error, priv->hook, m);
1150 	}
1151 
1152 	/*
1153 	 * If the peer has closed the connection, forward a 0-length mbuf
1154 	 * to indicate end-of-file.
1155 	 */
1156 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1157 		MGETHDR(m, waitflag, MT_DATA);
1158 		if (m != NULL) {
1159 			m->m_len = m->m_pkthdr.len = 0;
1160 			NG_SEND_DATA_ONLY(error, priv->hook, m);
1161 		}
1162 		priv->flags |= KSF_EOFSEEN;
1163 	}
1164 	splx(s);
1165 }
1166 
1167 /*
1168  * Check for a completed incoming connection and return 0 if one is found.
1169  * Otherwise return the appropriate error code.
1170  */
1171 static int
1172 ng_ksocket_check_accept(priv_p priv)
1173 {
1174 	struct socket *const head = priv->so;
1175 	int error;
1176 
1177 	if ((error = head->so_error) != 0) {
1178 		head->so_error = 0;
1179 		return error;
1180 	}
1181 	/* Unlocked read. */
1182 	if (TAILQ_EMPTY(&head->so_comp)) {
1183 		if (head->so_rcv.sb_state & SBS_CANTRCVMORE)
1184 			return ECONNABORTED;
1185 		return EWOULDBLOCK;
1186 	}
1187 	return 0;
1188 }
1189 
1190 /*
1191  * Handle the first completed incoming connection, assumed to be already
1192  * on the socket's so_comp queue.
1193  */
1194 static void
1195 ng_ksocket_finish_accept(priv_p priv)
1196 {
1197 	struct socket *const head = priv->so;
1198 	struct socket *so;
1199 	struct sockaddr *sa = NULL;
1200 	struct ng_mesg *resp;
1201 	struct ng_ksocket_accept *resp_data;
1202 	node_p node;
1203 	priv_p priv2;
1204 	int len;
1205 	int error;
1206 
1207 	ACCEPT_LOCK();
1208 	so = TAILQ_FIRST(&head->so_comp);
1209 	if (so == NULL) {	/* Should never happen */
1210 		ACCEPT_UNLOCK();
1211 		return;
1212 	}
1213 	TAILQ_REMOVE(&head->so_comp, so, so_list);
1214 	head->so_qlen--;
1215 	so->so_qstate &= ~SQ_COMP;
1216 	so->so_head = NULL;
1217 	SOCK_LOCK(so);
1218 	soref(so);
1219 	so->so_state |= SS_NBIO;
1220 	SOCK_UNLOCK(so);
1221 	ACCEPT_UNLOCK();
1222 
1223 	/* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
1224 
1225 	soaccept(so, &sa);
1226 
1227 	len = OFFSETOF(struct ng_ksocket_accept, addr);
1228 	if (sa != NULL)
1229 		len += sa->sa_len;
1230 
1231 	NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1232 	    M_NOWAIT);
1233 	if (resp == NULL) {
1234 		soclose(so);
1235 		goto out;
1236 	}
1237 	resp->header.flags |= NGF_RESP;
1238 	resp->header.token = priv->response_token;
1239 
1240 	/* Clone a ksocket node to wrap the new socket */
1241         error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1242         if (error) {
1243 		FREE(resp, M_NETGRAPH);
1244 		soclose(so);
1245 		goto out;
1246 	}
1247 
1248 	if (ng_ksocket_constructor(node) != 0) {
1249 		NG_NODE_UNREF(node);
1250 		FREE(resp, M_NETGRAPH);
1251 		soclose(so);
1252 		goto out;
1253 	}
1254 
1255 	priv2 = NG_NODE_PRIVATE(node);
1256 	priv2->so = so;
1257 	priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1258 
1259 	/*
1260 	 * Insert the cloned node into a list of embryonic children
1261 	 * on the parent node.  When a hook is created on the cloned
1262 	 * node it will be removed from this list.  When the parent
1263 	 * is destroyed it will destroy any embryonic children it has.
1264 	 */
1265 	LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1266 
1267 	so->so_upcallarg = (caddr_t)node;
1268 	so->so_upcall = ng_ksocket_incoming;
1269 	SOCKBUF_LOCK(&so->so_rcv);
1270 	so->so_rcv.sb_flags |= SB_UPCALL;
1271 	SOCKBUF_UNLOCK(&so->so_rcv);
1272 	SOCKBUF_LOCK(&so->so_snd);
1273 	so->so_snd.sb_flags |= SB_UPCALL;
1274 	SOCKBUF_UNLOCK(&so->so_snd);
1275 
1276 	/* Fill in the response data and send it or return it to the caller */
1277 	resp_data = (struct ng_ksocket_accept *)resp->data;
1278 	resp_data->nodeid = NG_NODE_ID(node);
1279 	if (sa != NULL)
1280 		bcopy(sa, &resp_data->addr, sa->sa_len);
1281 	NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1282 
1283 out:
1284 	if (sa != NULL)
1285 		FREE(sa, M_SONAME);
1286 }
1287 
1288 /*
1289  * Parse out either an integer value or an alias.
1290  */
1291 static int
1292 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1293 	const char *s, int family)
1294 {
1295 	int k, val;
1296 	char *eptr;
1297 
1298 	/* Try aliases */
1299 	for (k = 0; aliases[k].name != NULL; k++) {
1300 		if (strcmp(s, aliases[k].name) == 0
1301 		    && aliases[k].family == family)
1302 			return aliases[k].value;
1303 	}
1304 
1305 	/* Try parsing as a number */
1306 	val = (int)strtoul(s, &eptr, 10);
1307 	if (val < 0 || *eptr != '\0')
1308 		return (-1);
1309 	return (val);
1310 }
1311 
1312