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