xref: /dragonfly/sys/netgraph/ksocket/ng_ksocket.c (revision 9dbf638f)
1 
2 /*
3  * ng_ksocket.c
4  *
5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
6  * All rights reserved.
7  *
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  *
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Author: Archie Cobbs <archie@freebsd.org>
38  *
39  * $FreeBSD: src/sys/netgraph/ng_ksocket.c,v 1.5.2.14 2003/08/24 08:24:38 hsu Exp $
40  * $DragonFly: src/sys/netgraph/ksocket/ng_ksocket.c,v 1.6 2003/08/24 23:07:07 hsu Exp $
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 "ng_ksocket.h"
67 
68 #include <netinet/in.h>
69 #include <netproto/atalk/at.h>
70 
71 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
72 #define SADATA_OFFSET	(OFFSETOF(struct sockaddr, sa_data))
73 
74 /* Node private data */
75 struct ng_ksocket_private {
76 	node_p		node;
77 	hook_p		hook;
78 	struct socket	*so;
79 	LIST_HEAD(, ng_ksocket_private)	embryos;
80 	LIST_ENTRY(ng_ksocket_private)	siblings;
81 	u_int32_t	flags;
82 	u_int32_t	response_token;
83 	char		response_addr[NG_PATHLEN+1];
84 };
85 typedef struct ng_ksocket_private *priv_p;
86 
87 /* Flags for priv_p */
88 #define	KSF_CONNECTING	0x00000001	/* Waiting for connection complete */
89 #define	KSF_ACCEPTING	0x00000002	/* Waiting for accept complete */
90 #define	KSF_EOFSEEN	0x00000004	/* Have sent 0-length EOF mbuf */
91 #define	KSF_CLONED	0x00000008	/* Cloned from an accepting socket */
92 #define	KSF_EMBRYONIC	0x00000010	/* Cloned node with no hooks yet */
93 #define	KSF_SENDING	0x00000020	/* Sending on socket */
94 
95 /* Internal commands which we send to ourselves */
96 #define	NGM_KSOCKET_INTERNAL_COOKIE	(NGM_KSOCKET_COOKIE + 1)
97 
98 enum {
99 	NGM_KSOCKET_INTERNAL_UPCALL = 1
100 };
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_rmnode;
106 static ng_newhook_t	ng_ksocket_newhook;
107 static ng_rcvdata_t	ng_ksocket_rcvdata;
108 static ng_disconnect_t	ng_ksocket_disconnect;
109 
110 /* Alias structure */
111 struct ng_ksocket_alias {
112 	const char	*name;
113 	const int	value;
114 	const int	family;
115 };
116 
117 /* Protocol family aliases */
118 static const struct ng_ksocket_alias ng_ksocket_families[] = {
119 	{ "local",	PF_LOCAL	},
120 	{ "inet",	PF_INET		},
121 	{ "inet6",	PF_INET6	},
122 	{ "atalk",	PF_APPLETALK	},
123 	{ "ipx",	PF_IPX		},
124 	{ "atm",	PF_ATM		},
125 	{ NULL,		-1		},
126 };
127 
128 /* Socket type aliases */
129 static const struct ng_ksocket_alias ng_ksocket_types[] = {
130 	{ "stream",	SOCK_STREAM	},
131 	{ "dgram",	SOCK_DGRAM	},
132 	{ "raw",	SOCK_RAW	},
133 	{ "rdm",	SOCK_RDM	},
134 	{ "seqpacket",	SOCK_SEQPACKET	},
135 	{ NULL,		-1		},
136 };
137 
138 /* Protocol aliases */
139 static const struct ng_ksocket_alias ng_ksocket_protos[] = {
140 	{ "ip",		IPPROTO_IP,		PF_INET		},
141 	{ "raw",	IPPROTO_RAW,		PF_INET		},
142 	{ "icmp",	IPPROTO_ICMP,		PF_INET		},
143 	{ "igmp",	IPPROTO_IGMP,		PF_INET		},
144 	{ "tcp",	IPPROTO_TCP,		PF_INET		},
145 	{ "udp",	IPPROTO_UDP,		PF_INET		},
146 	{ "gre",	IPPROTO_GRE,		PF_INET		},
147 	{ "esp",	IPPROTO_ESP,		PF_INET		},
148 	{ "ah",		IPPROTO_AH,		PF_INET		},
149 	{ "swipe",	IPPROTO_SWIPE,		PF_INET		},
150 	{ "encap",	IPPROTO_ENCAP,		PF_INET		},
151 	{ "divert",	IPPROTO_DIVERT,		PF_INET		},
152 	{ "pim",	IPPROTO_PIM,		PF_INET		},
153 	{ "ddp",	ATPROTO_DDP,		PF_APPLETALK	},
154 	{ "aarp",	ATPROTO_AARP,		PF_APPLETALK	},
155 	{ NULL,		-1					},
156 };
157 
158 /* Helper functions */
159 static int	ng_ksocket_check_accept(priv_p);
160 static void	ng_ksocket_finish_accept(priv_p, struct ng_mesg **);
161 static void	ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
162 static int	ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
163 			const char *s, int family);
164 
165 /************************************************************************
166 			STRUCT SOCKADDR PARSE TYPE
167  ************************************************************************/
168 
169 /* Get the length of the data portion of a generic struct sockaddr */
170 static int
171 ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
172 	const u_char *start, const u_char *buf)
173 {
174 	const struct sockaddr *sa;
175 
176 	sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
177 	return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
178 }
179 
180 /* Type for the variable length data portion of a generic struct sockaddr */
181 static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
182 	&ng_parse_bytearray_type,
183 	&ng_parse_generic_sockdata_getLength
184 };
185 
186 /* Type for a generic struct sockaddr */
187 static const struct ng_parse_struct_field
188     ng_parse_generic_sockaddr_type_fields[] = {
189 	  { "len",	&ng_parse_uint8_type			},
190 	  { "family",	&ng_parse_uint8_type			},
191 	  { "data",	&ng_ksocket_generic_sockdata_type	},
192 	  { NULL }
193 };
194 static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
195 	&ng_parse_struct_type,
196 	&ng_parse_generic_sockaddr_type_fields
197 };
198 
199 /* Convert a struct sockaddr from ASCII to binary.  If its a protocol
200    family that we specially handle, do that, otherwise defer to the
201    generic parse type ng_ksocket_generic_sockaddr_type. */
202 static int
203 ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
204 	const char *s, int *off, const u_char *const start,
205 	u_char *const buf, int *buflen)
206 {
207 	struct sockaddr *const sa = (struct sockaddr *)buf;
208 	enum ng_parse_token tok;
209 	char fambuf[32];
210 	int family, len;
211 	char *t;
212 
213 	/* If next token is a left curly brace, use generic parse type */
214 	if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
215 		return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
216 		    (&ng_ksocket_generic_sockaddr_type,
217 		    s, off, start, buf, buflen);
218 	}
219 
220 	/* Get socket address family followed by a slash */
221 	while (isspace(s[*off]))
222 		(*off)++;
223 	if ((t = index(s + *off, '/')) == NULL)
224 		return (EINVAL);
225 	if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
226 		return (EINVAL);
227 	strncpy(fambuf, s + *off, len);
228 	fambuf[len] = '\0';
229 	*off += len + 1;
230 	if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
231 		return (EINVAL);
232 
233 	/* Set family */
234 	if (*buflen < SADATA_OFFSET)
235 		return (ERANGE);
236 	sa->sa_family = family;
237 
238 	/* Set family-specific data and length */
239 	switch (sa->sa_family) {
240 	case PF_LOCAL:		/* Get pathname */
241 	    {
242 		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
243 		struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
244 		int toklen, pathlen;
245 		char *path;
246 
247 		if ((path = ng_get_string_token(s, off, &toklen)) == NULL)
248 			return (EINVAL);
249 		pathlen = strlen(path);
250 		if (pathlen > SOCK_MAXADDRLEN) {
251 			FREE(path, M_NETGRAPH);
252 			return (E2BIG);
253 		}
254 		if (*buflen < pathoff + pathlen) {
255 			FREE(path, M_NETGRAPH);
256 			return (ERANGE);
257 		}
258 		*off += toklen;
259 		bcopy(path, sun->sun_path, pathlen);
260 		sun->sun_len = pathoff + pathlen;
261 		FREE(path, M_NETGRAPH);
262 		break;
263 	    }
264 
265 	case PF_INET:		/* Get an IP address with optional port */
266 	    {
267 		struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
268 		int i;
269 
270 		/* Parse this: <ipaddress>[:port] */
271 		for (i = 0; i < 4; i++) {
272 			u_long val;
273 			char *eptr;
274 
275 			val = strtoul(s + *off, &eptr, 10);
276 			if (val > 0xff || eptr == s + *off)
277 				return (EINVAL);
278 			*off += (eptr - (s + *off));
279 			((u_char *)&sin->sin_addr)[i] = (u_char)val;
280 			if (i < 3) {
281 				if (s[*off] != '.')
282 					return (EINVAL);
283 				(*off)++;
284 			} else if (s[*off] == ':') {
285 				(*off)++;
286 				val = strtoul(s + *off, &eptr, 10);
287 				if (val > 0xffff || eptr == s + *off)
288 					return (EINVAL);
289 				*off += (eptr - (s + *off));
290 				sin->sin_port = htons(val);
291 			} else
292 				sin->sin_port = 0;
293 		}
294 		bzero(&sin->sin_zero, sizeof(sin->sin_zero));
295 		sin->sin_len = sizeof(*sin);
296 		break;
297 	    }
298 
299 #if 0
300 	case PF_APPLETALK:	/* XXX implement these someday */
301 	case PF_INET6:
302 	case PF_IPX:
303 #endif
304 
305 	default:
306 		return (EINVAL);
307 	}
308 
309 	/* Done */
310 	*buflen = sa->sa_len;
311 	return (0);
312 }
313 
314 /* Convert a struct sockaddr from binary to ASCII */
315 static int
316 ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
317 	const u_char *data, int *off, char *cbuf, int cbuflen)
318 {
319 	const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
320 	int slen = 0;
321 
322 	/* Output socket address, either in special or generic format */
323 	switch (sa->sa_family) {
324 	case PF_LOCAL:
325 	    {
326 		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
327 		const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
328 		const int pathlen = sun->sun_len - pathoff;
329 		char pathbuf[SOCK_MAXADDRLEN + 1];
330 		char *pathtoken;
331 
332 		bcopy(sun->sun_path, pathbuf, pathlen);
333 		pathbuf[pathlen] = '\0';
334 		if ((pathtoken = ng_encode_string(pathbuf)) == NULL)
335 			return (ENOMEM);
336 		slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
337 		FREE(pathtoken, M_NETGRAPH);
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 
491 	/* Internal commands */
492 	{
493 	  NGM_KSOCKET_INTERNAL_COOKIE,
494 	  NGM_KSOCKET_INTERNAL_UPCALL,
495 	  "upcall",
496 	  NULL,
497 	  NULL
498 	},
499 	{ 0 }
500 };
501 
502 /* Node type descriptor */
503 static struct ng_type ng_ksocket_typestruct = {
504 	NG_VERSION,
505 	NG_KSOCKET_NODE_TYPE,
506 	NULL,
507 	ng_ksocket_constructor,
508 	ng_ksocket_rcvmsg,
509 	ng_ksocket_rmnode,
510 	ng_ksocket_newhook,
511 	NULL,
512 	NULL,
513 	ng_ksocket_rcvdata,
514 	ng_ksocket_rcvdata,
515 	ng_ksocket_disconnect,
516 	ng_ksocket_cmds
517 };
518 NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
519 
520 #define ERROUT(x)	do { error = (x); goto done; } while (0)
521 
522 /************************************************************************
523 			NETGRAPH NODE STUFF
524  ************************************************************************/
525 
526 /*
527  * Node type constructor
528  */
529 static int
530 ng_ksocket_constructor(node_p *nodep)
531 {
532 	priv_p priv;
533 	int error;
534 
535 	/* Allocate private structure */
536 	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT);
537 	if (priv == NULL)
538 		return (ENOMEM);
539 	bzero(priv, sizeof(*priv));
540 
541 	/* Call generic node constructor */
542 	if ((error = ng_make_node_common(&ng_ksocket_typestruct, nodep))) {
543 		FREE(priv, M_NETGRAPH);
544 		return (error);
545 	}
546 	(*nodep)->private = priv;
547 	priv->node = *nodep;
548 	LIST_INIT(&priv->embryos);
549 
550 	/* Done */
551 	return (0);
552 }
553 
554 /*
555  * Give our OK for a hook to be added. The hook name is of the
556  * form "<family>/<type>/<proto>" where the three components may
557  * be decimal numbers or else aliases from the above lists.
558  *
559  * Connecting a hook amounts to opening the socket.  Disconnecting
560  * the hook closes the socket and destroys the node as well.
561  */
562 static int
563 ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
564 {
565 	struct thread *td = curthread;	/* XXX broken */
566 	const priv_p priv = node->private;
567 	struct ng_mesg *msg;
568 	char *s1, *s2, name[NG_HOOKLEN+1];
569 	int family, type, protocol, error;
570 
571 	/* Check if we're already connected */
572 	if (priv->hook != NULL)
573 		return (EISCONN);
574 
575 	if (priv->flags & KSF_CLONED) {
576 		if (priv->flags & KSF_EMBRYONIC) {
577 			/* Remove ourselves from our parent's embryo list */
578 			LIST_REMOVE(priv, siblings);
579 			priv->flags &= ~KSF_EMBRYONIC;
580 		}
581 	} else {
582 		/* Extract family, type, and protocol from hook name */
583 		snprintf(name, sizeof(name), "%s", name0);
584 		s1 = name;
585 		if ((s2 = index(s1, '/')) == NULL)
586 			return (EINVAL);
587 		*s2++ = '\0';
588 		family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
589 		if (family == -1)
590 			return (EINVAL);
591 		s1 = s2;
592 		if ((s2 = index(s1, '/')) == NULL)
593 			return (EINVAL);
594 		*s2++ = '\0';
595 		type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
596 		if (type == -1)
597 			return (EINVAL);
598 		s1 = s2;
599 		protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
600 		if (protocol == -1)
601 			return (EINVAL);
602 
603 		/* Create the socket */
604 		error = socreate(family, &priv->so, type, protocol, td);
605 		if (error != 0)
606 			return (error);
607 
608 		/* XXX call soreserve() ? */
609 
610 		/* Add our hook for incoming data and other events */
611 		priv->so->so_upcallarg = (caddr_t)node;
612 		priv->so->so_upcall = ng_ksocket_incoming;
613 		priv->so->so_rcv.sb_flags |= SB_UPCALL;
614 		priv->so->so_snd.sb_flags |= SB_UPCALL;
615 		priv->so->so_state |= SS_NBIO;
616 	}
617 
618 	/* OK */
619 	priv->hook = hook;
620 
621 	/*
622 	 * On a cloned socket we may have already received one or more
623 	 * upcalls which we couldn't handle without a hook.  Handle
624 	 * those now.  We cannot call the upcall function directly
625 	 * from here, because until this function has returned our
626 	 * hook isn't connected.  So we queue a message to ourselves
627 	 * which will cause the upcall function to be called a bit
628 	 * later.
629 	 */
630 	if (priv->flags & KSF_CLONED) {
631 		NG_MKMESSAGE(msg, NGM_KSOCKET_INTERNAL_COOKIE,
632 		    NGM_KSOCKET_INTERNAL_UPCALL, 0, M_NOWAIT);
633 		if (msg != NULL)
634 			ng_queue_msg(node, msg, ".:");
635 	}
636 
637 	return (0);
638 }
639 
640 /*
641  * Receive a control message
642  */
643 static int
644 ng_ksocket_rcvmsg(node_p node, struct ng_mesg *msg,
645 	      const char *raddr, struct ng_mesg **rptr)
646 {
647 	struct thread *td = curthread;	/* XXX broken */
648 	const priv_p priv = node->private;
649 	struct socket *const so = priv->so;
650 	struct ng_mesg *resp = NULL;
651 	int error = 0;
652 
653 	switch (msg->header.typecookie) {
654 	case NGM_KSOCKET_COOKIE:
655 		switch (msg->header.cmd) {
656 		case NGM_KSOCKET_BIND:
657 		    {
658 			struct sockaddr *const sa
659 			    = (struct sockaddr *)msg->data;
660 
661 			/* Sanity check */
662 			if (msg->header.arglen < SADATA_OFFSET
663 			    || msg->header.arglen < sa->sa_len)
664 				ERROUT(EINVAL);
665 			if (so == NULL)
666 				ERROUT(ENXIO);
667 
668 			/* Bind */
669 			error = sobind(so, sa, td);
670 			break;
671 		    }
672 		case NGM_KSOCKET_LISTEN:
673 		    {
674 			/* Sanity check */
675 			if (msg->header.arglen != sizeof(int32_t))
676 				ERROUT(EINVAL);
677 			if (so == NULL)
678 				ERROUT(ENXIO);
679 
680 			/* Listen */
681 			error = solisten(so, *((int32_t *)msg->data), td);
682 			break;
683 		    }
684 
685 		case NGM_KSOCKET_ACCEPT:
686 		    {
687 			/* Sanity check */
688 			if (msg->header.arglen != 0)
689 				ERROUT(EINVAL);
690 			if (so == NULL)
691 				ERROUT(ENXIO);
692 
693 			/* Make sure the socket is capable of accepting */
694 			if (!(so->so_options & SO_ACCEPTCONN))
695 				ERROUT(EINVAL);
696 			if (priv->flags & KSF_ACCEPTING)
697 				ERROUT(EALREADY);
698 
699 			error = ng_ksocket_check_accept(priv);
700 			if (error != 0 && error != EWOULDBLOCK)
701 				ERROUT(error);
702 
703 			/*
704 			 * If a connection is already complete, take it.
705 			 * Otherwise let the upcall function deal with
706 			 * the connection when it comes in.
707 			 */
708 			priv->response_token = msg->header.token;
709 			strcpy(priv->response_addr, raddr);
710 			if (error == 0) {
711 				ng_ksocket_finish_accept(priv,
712 				    rptr != NULL ? &resp : NULL);
713 			} else
714 				priv->flags |= KSF_ACCEPTING;
715 			break;
716 		    }
717 
718 		case NGM_KSOCKET_CONNECT:
719 		    {
720 			struct sockaddr *const sa
721 			    = (struct sockaddr *)msg->data;
722 
723 			/* Sanity check */
724 			if (msg->header.arglen < SADATA_OFFSET
725 			    || msg->header.arglen < sa->sa_len)
726 				ERROUT(EINVAL);
727 			if (so == NULL)
728 				ERROUT(ENXIO);
729 
730 			/* Do connect */
731 			if ((so->so_state & SS_ISCONNECTING) != 0)
732 				ERROUT(EALREADY);
733 			if ((error = soconnect(so, sa, td)) != 0) {
734 				so->so_state &= ~SS_ISCONNECTING;
735 				ERROUT(error);
736 			}
737 			if ((so->so_state & SS_ISCONNECTING) != 0) {
738 				/* We will notify the sender when we connect */
739 				priv->response_token = msg->header.token;
740 				strcpy(priv->response_addr, raddr);
741 				priv->flags |= KSF_CONNECTING;
742 				ERROUT(EINPROGRESS);
743 			}
744 			break;
745 		    }
746 
747 		case NGM_KSOCKET_GETNAME:
748 		case NGM_KSOCKET_GETPEERNAME:
749 		    {
750 			int (*func)(struct socket *so, struct sockaddr **nam);
751 			struct sockaddr *sa = NULL;
752 			int len;
753 
754 			/* Sanity check */
755 			if (msg->header.arglen != 0)
756 				ERROUT(EINVAL);
757 			if (so == NULL)
758 				ERROUT(ENXIO);
759 
760 			/* Get function */
761 			if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
762 				if ((so->so_state
763 				    & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
764 					ERROUT(ENOTCONN);
765 				func = so->so_proto->pr_usrreqs->pru_peeraddr;
766 			} else
767 				func = so->so_proto->pr_usrreqs->pru_sockaddr;
768 
769 			/* Get local or peer address */
770 			if ((error = (*func)(so, &sa)) != 0)
771 				goto bail;
772 			len = (sa == NULL) ? 0 : sa->sa_len;
773 
774 			/* Send it back in a response */
775 			NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
776 			if (resp == NULL) {
777 				error = ENOMEM;
778 				goto bail;
779 			}
780 			bcopy(sa, resp->data, len);
781 
782 		bail:
783 			/* Cleanup */
784 			if (sa != NULL)
785 				FREE(sa, M_SONAME);
786 			break;
787 		    }
788 
789 		case NGM_KSOCKET_GETOPT:
790 		    {
791 			struct ng_ksocket_sockopt *ksopt =
792 			    (struct ng_ksocket_sockopt *)msg->data;
793 			struct sockopt sopt;
794 
795 			/* Sanity check */
796 			if (msg->header.arglen != sizeof(*ksopt))
797 				ERROUT(EINVAL);
798 			if (so == NULL)
799 				ERROUT(ENXIO);
800 
801 			/* Get response with room for option value */
802 			NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
803 			    + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
804 			if (resp == NULL)
805 				ERROUT(ENOMEM);
806 
807 			/* Get socket option, and put value in the response */
808 			sopt.sopt_dir = SOPT_GET;
809 			sopt.sopt_level = ksopt->level;
810 			sopt.sopt_name = ksopt->name;
811 			sopt.sopt_td = NULL;
812 			sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
813 			ksopt = (struct ng_ksocket_sockopt *)resp->data;
814 			sopt.sopt_val = ksopt->value;
815 			if ((error = sogetopt(so, &sopt)) != 0) {
816 				FREE(resp, M_NETGRAPH);
817 				break;
818 			}
819 
820 			/* Set actual value length */
821 			resp->header.arglen = sizeof(*ksopt)
822 			    + sopt.sopt_valsize;
823 			break;
824 		    }
825 
826 		case NGM_KSOCKET_SETOPT:
827 		    {
828 			struct ng_ksocket_sockopt *const ksopt =
829 			    (struct ng_ksocket_sockopt *)msg->data;
830 			const int valsize = msg->header.arglen - sizeof(*ksopt);
831 			struct sockopt sopt;
832 
833 			/* Sanity check */
834 			if (valsize < 0)
835 				ERROUT(EINVAL);
836 			if (so == NULL)
837 				ERROUT(ENXIO);
838 
839 			/* Set socket option */
840 			sopt.sopt_dir = SOPT_SET;
841 			sopt.sopt_level = ksopt->level;
842 			sopt.sopt_name = ksopt->name;
843 			sopt.sopt_val = ksopt->value;
844 			sopt.sopt_valsize = valsize;
845 			sopt.sopt_td = NULL;
846 			error = sosetopt(so, &sopt);
847 			break;
848 		    }
849 
850 		default:
851 			error = EINVAL;
852 			break;
853 		}
854 		break;
855 	case NGM_KSOCKET_INTERNAL_COOKIE:
856 		switch (msg->header.cmd) {
857 		case NGM_KSOCKET_INTERNAL_UPCALL:
858 			if (so == NULL)
859 				ERROUT(ENXIO);
860 			(*priv->so->so_upcall)(so, so->so_upcallarg, M_NOWAIT);
861 			break;
862 		default:
863 			error = EINVAL;
864 			break;
865 		}
866 		break;
867 	default:
868 		error = EINVAL;
869 		break;
870 	}
871 	if (rptr)
872 		*rptr = resp;
873 	else if (resp)
874 		FREE(resp, M_NETGRAPH);
875 
876 done:
877 	FREE(msg, M_NETGRAPH);
878 	return (error);
879 }
880 
881 /*
882  * Receive incoming data on our hook.  Send it out the socket.
883  */
884 static int
885 ng_ksocket_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
886 {
887 	struct thread *td = curthread;	/* XXX broken */
888 	const node_p node = hook->node;
889 	const priv_p priv = node->private;
890 	struct socket *const so = priv->so;
891 	struct sockaddr *sa = NULL;
892 	int error;
893 
894 	/* Avoid reentrantly sending on the socket */
895 	if ((priv->flags & KSF_SENDING) != 0) {
896 		NG_FREE_DATA(m, meta);
897 		return (EDEADLK);
898 	}
899 
900 	/* If any meta info, look for peer socket address */
901 	if (meta != NULL) {
902 		struct meta_field_header *field;
903 
904 		/* Look for peer socket address */
905 		for (field = &meta->options[0];
906 		    (caddr_t)field < (caddr_t)meta + meta->used_len;
907 		    field = (struct meta_field_header *)
908 		      ((caddr_t)field + field->len)) {
909 			if (field->cookie != NGM_KSOCKET_COOKIE
910 			    || field->type != NG_KSOCKET_META_SOCKADDR)
911 				continue;
912 			sa = (struct sockaddr *)field->data;
913 			break;
914 		}
915 	}
916 
917 	/* Send packet */
918 	priv->flags |= KSF_SENDING;
919 	error = (*so->so_proto->pr_usrreqs->pru_sosend)(so, sa, 0, m, 0, 0, td);
920 	priv->flags &= ~KSF_SENDING;
921 
922 	/* Clean up and exit */
923 	NG_FREE_META(meta);
924 	return (error);
925 }
926 
927 /*
928  * Destroy node
929  */
930 static int
931 ng_ksocket_rmnode(node_p node)
932 {
933 	const priv_p priv = node->private;
934 	priv_p embryo;
935 
936 	/* Close our socket (if any) */
937 	if (priv->so != NULL) {
938 		priv->so->so_upcall = NULL;
939 		priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
940 		priv->so->so_snd.sb_flags &= ~SB_UPCALL;
941 		soclose(priv->so);
942 		priv->so = NULL;
943 	}
944 
945 	/* If we are an embryo, take ourselves out of the parent's list */
946 	if (priv->flags & KSF_EMBRYONIC) {
947 		LIST_REMOVE(priv, siblings);
948 		priv->flags &= ~KSF_EMBRYONIC;
949 	}
950 
951 	/* Remove any embryonic children we have */
952 	while (!LIST_EMPTY(&priv->embryos)) {
953 		embryo = LIST_FIRST(&priv->embryos);
954 		ng_rmnode(embryo->node);
955 	}
956 
957 	/* Take down netgraph node */
958 	node->flags |= NG_INVALID;
959 	ng_cutlinks(node);
960 	ng_unname(node);
961 	bzero(priv, sizeof(*priv));
962 	FREE(priv, M_NETGRAPH);
963 	node->private = NULL;
964 	ng_unref(node);		/* let the node escape */
965 	return (0);
966 }
967 
968 /*
969  * Hook disconnection
970  */
971 static int
972 ng_ksocket_disconnect(hook_p hook)
973 {
974 	KASSERT(hook->node->numhooks == 0,
975 	    ("%s: numhooks=%d?", __FUNCTION__, hook->node->numhooks));
976 	ng_rmnode(hook->node);
977 	return (0);
978 }
979 
980 /************************************************************************
981 			HELPER STUFF
982  ************************************************************************/
983 
984 /*
985  * When incoming data is appended to the socket, we get notified here.
986  * This is also called whenever a significant event occurs for the socket.
987  */
988 static void
989 ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
990 {
991 	const node_p node = arg;
992 	const priv_p priv = node->private;
993 	struct mbuf *m;
994 	struct ng_mesg *response;
995 	struct uio auio;
996 	int s, flags, error;
997 
998 	s = splnet();
999 
1000 	/* Sanity check */
1001 	if ((node->flags & NG_INVALID) != 0) {
1002 		splx(s);
1003 		return;
1004 	}
1005 	KASSERT(so == priv->so, ("%s: wrong socket", __FUNCTION__));
1006 
1007 	/* Check whether a pending connect operation has completed */
1008 	if (priv->flags & KSF_CONNECTING) {
1009 		if ((error = so->so_error) != 0) {
1010 			so->so_error = 0;
1011 			so->so_state &= ~SS_ISCONNECTING;
1012 		}
1013 		if (!(so->so_state & SS_ISCONNECTING)) {
1014 			NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1015 			    NGM_KSOCKET_CONNECT, sizeof(int32_t), waitflag);
1016 			if (response != NULL) {
1017 				response->header.flags |= NGF_RESP;
1018 				response->header.token = priv->response_token;
1019 				*(int32_t *)response->data = error;
1020 				/*
1021 				 * XXX We use ng_queue_msg here because we are
1022 				 * being called from deep in the bowels of the TCP
1023 				 * stack.  Is this right, or should we let the
1024 				 * receiver of the message worry about that?
1025 				 */
1026 				ng_queue_msg(node, response,
1027 				    priv->response_addr);
1028 			}
1029 			priv->flags &= ~KSF_CONNECTING;
1030 		}
1031 	}
1032 
1033 	/* Check whether a pending accept operation has completed */
1034 	if (priv->flags & KSF_ACCEPTING) {
1035 		error = ng_ksocket_check_accept(priv);
1036 		if (error != EWOULDBLOCK)
1037 			priv->flags &= ~KSF_ACCEPTING;
1038 		if (error == 0)
1039 			ng_ksocket_finish_accept(priv, NULL);
1040 	}
1041 
1042 	/*
1043 	 * If we don't have a hook, we must handle data events later.  When
1044 	 * the hook gets created and is connected, this upcall function
1045 	 * will be called again.
1046 	 */
1047 	if (priv->hook == NULL) {
1048 		splx(s);
1049 		return;
1050 	}
1051 
1052 	/* Read and forward available mbuf's */
1053 	auio.uio_td = NULL;
1054 	auio.uio_resid = 1000000000;
1055 	flags = MSG_DONTWAIT;
1056 	while (1) {
1057 		struct sockaddr *sa = NULL;
1058 		meta_p meta = NULL;
1059 		struct mbuf *n;
1060 
1061 		/* Try to get next packet from socket */
1062 		if ((error = (*so->so_proto->pr_usrreqs->pru_soreceive)
1063 		    (so, (so->so_state & SS_ISCONNECTED) ? NULL : &sa,
1064 		    &auio, &m, (struct mbuf **)0, &flags)) != 0)
1065 			break;
1066 
1067 		/* See if we got anything */
1068 		if (m == NULL) {
1069 			if (sa != NULL)
1070 				FREE(sa, M_SONAME);
1071 			break;
1072 		}
1073 
1074 		/* Don't trust the various socket layers to get the
1075 		   packet header and length correct (eg. kern/15175) */
1076 		for (n = m, m->m_pkthdr.len = 0; n != NULL; n = n->m_next)
1077 			m->m_pkthdr.len += n->m_len;
1078 
1079 		/* Put peer's socket address (if any) into a meta info blob */
1080 		if (sa != NULL) {
1081 			struct meta_field_header *mhead;
1082 			u_int len;
1083 
1084 			len = sizeof(*meta) + sizeof(*mhead) + sa->sa_len;
1085 			MALLOC(meta, meta_p, len, M_NETGRAPH, M_NOWAIT);
1086 			if (meta == NULL) {
1087 				FREE(sa, M_SONAME);
1088 				goto sendit;
1089 			}
1090 			mhead = &meta->options[0];
1091 			bzero(meta, sizeof(*meta));
1092 			bzero(mhead, sizeof(*mhead));
1093 			meta->allocated_len = len;
1094 			meta->used_len = len;
1095 			mhead->cookie = NGM_KSOCKET_COOKIE;
1096 			mhead->type = NG_KSOCKET_META_SOCKADDR;
1097 			mhead->len = sizeof(*mhead) + sa->sa_len;
1098 			bcopy(sa, mhead->data, sa->sa_len);
1099 			FREE(sa, M_SONAME);
1100 		}
1101 sendit:		/* Forward data with optional peer sockaddr as meta info */
1102 		NG_SEND_DATA(error, priv->hook, m, meta);
1103 	}
1104 
1105 	/*
1106 	 * If the peer has closed the connection, forward a 0-length mbuf
1107 	 * to indicate end-of-file.
1108 	 */
1109 	if (so->so_state & SS_CANTRCVMORE && !(priv->flags & KSF_EOFSEEN)) {
1110 		MGETHDR(m, waitflag, MT_DATA);
1111 		if (m != NULL) {
1112 			m->m_len = m->m_pkthdr.len = 0;
1113 			NG_SEND_DATA_ONLY(error, priv->hook, m);
1114 		}
1115 		priv->flags |= KSF_EOFSEEN;
1116 	}
1117 
1118 	splx(s);
1119 }
1120 
1121 /*
1122  * Check for a completed incoming connection and return 0 if one is found.
1123  * Otherwise return the appropriate error code.
1124  */
1125 static int
1126 ng_ksocket_check_accept(priv_p priv)
1127 {
1128 	struct socket *const head = priv->so;
1129 	int error;
1130 
1131 	if ((error = head->so_error) != 0) {
1132 		head->so_error = 0;
1133 		return error;
1134 	}
1135 	if (TAILQ_EMPTY(&head->so_comp)) {
1136 		if (head->so_state & SS_CANTRCVMORE)
1137 			return ECONNABORTED;
1138 		return EWOULDBLOCK;
1139 	}
1140 	return 0;
1141 }
1142 
1143 /*
1144  * Handle the first completed incoming connection, assumed to be already
1145  * on the socket's so_comp queue.
1146  */
1147 static void
1148 ng_ksocket_finish_accept(priv_p priv, struct ng_mesg **rptr)
1149 {
1150 	struct socket *const head = priv->so;
1151 	struct socket *so;
1152 	struct sockaddr *sa = NULL;
1153 	struct ng_mesg *resp;
1154 	struct ng_ksocket_accept *resp_data;
1155 	node_p node2;
1156 	priv_p priv2;
1157 	int len;
1158 
1159 	so = TAILQ_FIRST(&head->so_comp);
1160 	if (so == NULL)		/* Should never happen */
1161 		return;
1162 	TAILQ_REMOVE(&head->so_comp, so, so_list);
1163 	head->so_qlen--;
1164 
1165 	/* XXX KNOTE(&head->so_rcv.sb_sel.si_note, 0); */
1166 
1167 	so->so_state &= ~SS_COMP;
1168 	so->so_state |= SS_NBIO;
1169 	so->so_head = NULL;
1170 
1171 	soaccept(so, &sa);
1172 
1173 	len = OFFSETOF(struct ng_ksocket_accept, addr);
1174 	if (sa != NULL)
1175 		len += sa->sa_len;
1176 
1177 	NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1178 	    M_NOWAIT);
1179 	if (resp == NULL) {
1180 		soclose(so);
1181 		goto out;
1182 	}
1183 	resp->header.flags |= NGF_RESP;
1184 	resp->header.token = priv->response_token;
1185 
1186 	/* Clone a ksocket node to wrap the new socket */
1187 	if (ng_ksocket_constructor(&node2) != 0) {
1188 		FREE(resp, M_NETGRAPH);
1189 		soclose(so);
1190 		goto out;
1191 	}
1192 	priv2 = (priv_p)node2->private;
1193 	priv2->so = so;
1194 	priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1195 
1196 	/*
1197 	 * Insert the cloned node into a list of embryonic children
1198 	 * on the parent node.  When a hook is created on the cloned
1199 	 * node it will be removed from this list.  When the parent
1200 	 * is destroyed it will destroy any embryonic children it has.
1201 	 */
1202 	LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1203 
1204 	so->so_upcallarg = (caddr_t)node2;
1205 	so->so_upcall = ng_ksocket_incoming;
1206 	so->so_rcv.sb_flags |= SB_UPCALL;
1207 	so->so_snd.sb_flags |= SB_UPCALL;
1208 
1209 	/* Fill in the response data and send it or return it to the caller */
1210 	resp_data = (struct ng_ksocket_accept *)resp->data;
1211 	resp_data->nodeid = node2->ID;
1212 	if (sa != NULL)
1213 		bcopy(sa, &resp_data->addr, sa->sa_len);
1214 	if (rptr != NULL)
1215 		*rptr = resp;
1216 	else
1217 		ng_queue_msg(priv->node, resp, priv->response_addr);
1218 
1219 out:
1220 	if (sa != NULL)
1221 		FREE(sa, M_SONAME);
1222 }
1223 
1224 /*
1225  * Parse out either an integer value or an alias.
1226  */
1227 static int
1228 ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1229 	const char *s, int family)
1230 {
1231 	int k, val;
1232 	char *eptr;
1233 
1234 	/* Try aliases */
1235 	for (k = 0; aliases[k].name != NULL; k++) {
1236 		if (strcmp(s, aliases[k].name) == 0
1237 		    && aliases[k].family == family)
1238 			return aliases[k].value;
1239 	}
1240 
1241 	/* Try parsing as a number */
1242 	val = (int)strtoul(s, &eptr, 10);
1243 	if (val < 0 || *eptr != '\0')
1244 		return (-1);
1245 	return (val);
1246 }
1247 
1248