1155852Sgallatin/*
2155852Sgallatin * ng_ksocket.c
3155852Sgallatin */
4155852Sgallatin
5155852Sgallatin/*-
6155852Sgallatin * Copyright (c) 1996-1999 Whistle Communications, Inc.
7155852Sgallatin * All rights reserved.
8155852Sgallatin *
9155852Sgallatin * Subject to the following obligations and disclaimer of warranty, use and
10155852Sgallatin * redistribution of this software, in source or object code forms, with or
11155852Sgallatin * without modifications are expressly permitted by Whistle Communications;
12155852Sgallatin * provided, however, that:
13155852Sgallatin * 1. Any and all reproductions of the source or object code must include the
14155852Sgallatin *    copyright notice above and the following disclaimer of warranties; and
15155852Sgallatin * 2. No rights are granted, in any manner or form, to use Whistle
16155852Sgallatin *    Communications, Inc. trademarks, including the mark "WHISTLE
17155852Sgallatin *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18155852Sgallatin *    such appears in the above copyright notice or in the software.
19155852Sgallatin *
20155852Sgallatin * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21155852Sgallatin * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22155852Sgallatin * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23155852Sgallatin * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24155852Sgallatin * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25155852Sgallatin * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26155852Sgallatin * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27155852Sgallatin * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28155852Sgallatin * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29155852Sgallatin * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30155852Sgallatin * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31155852Sgallatin * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32155852Sgallatin * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33155852Sgallatin * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34155852Sgallatin * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35159612Sgallatin * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36159612Sgallatin * OF SUCH DAMAGE.
37155852Sgallatin *
38159612Sgallatin * Author: Archie Cobbs <archie@freebsd.org>
39159612Sgallatin *
40159612Sgallatin * $FreeBSD$
41159612Sgallatin * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
42155852Sgallatin */
43155852Sgallatin
44155852Sgallatin/*
45155852Sgallatin * Kernel socket node type.  This node type is basically a kernel-mode
46155852Sgallatin * version of a socket... kindof like the reverse of the socket node type.
47155852Sgallatin */
48155852Sgallatin
49155852Sgallatin#include <sys/param.h>
50155852Sgallatin#include <sys/systm.h>
51155852Sgallatin#include <sys/kernel.h>
52155852Sgallatin#include <sys/mbuf.h>
53159612Sgallatin#include <sys/proc.h>
54155852Sgallatin#include <sys/malloc.h>
55155852Sgallatin#include <sys/ctype.h>
56159612Sgallatin#include <sys/protosw.h>
57159612Sgallatin#include <sys/errno.h>
58155852Sgallatin#include <sys/socket.h>
59159612Sgallatin#include <sys/socketvar.h>
60159612Sgallatin#include <sys/uio.h>
61159612Sgallatin#include <sys/un.h>
62159612Sgallatin
63159612Sgallatin#include <netgraph/ng_message.h>
64159612Sgallatin#include <netgraph/netgraph.h>
65155852Sgallatin#include <netgraph/ng_parse.h>
66155852Sgallatin#include <netgraph/ng_ksocket.h>
67159612Sgallatin
68155852Sgallatin#include <netinet/in.h>
69155852Sgallatin#include <netinet/ip.h>
70155852Sgallatin
71155852Sgallatin#ifdef NG_SEPARATE_MALLOC
72155852Sgallatinstatic MALLOC_DEFINE(M_NETGRAPH_KSOCKET, "netgraph_ksock",
73155852Sgallatin    "netgraph ksock node");
74159612Sgallatin#else
75155852Sgallatin#define M_NETGRAPH_KSOCKET M_NETGRAPH
76155852Sgallatin#endif
77159612Sgallatin
78159612Sgallatin#define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
79155852Sgallatin#define SADATA_OFFSET	(OFFSETOF(struct sockaddr, sa_data))
80155852Sgallatin
81159612Sgallatin/* Node private data */
82155852Sgallatinstruct ng_ksocket_private {
83155852Sgallatin	node_p		node;
84159612Sgallatin	hook_p		hook;
85159612Sgallatin	struct socket	*so;
86155852Sgallatin	int		fn_sent;	/* FN call on incoming event was sent */
87155852Sgallatin	LIST_HEAD(, ng_ksocket_private)	embryos;
88155852Sgallatin	LIST_ENTRY(ng_ksocket_private)	siblings;
89155852Sgallatin	u_int32_t	flags;
90155852Sgallatin	u_int32_t	response_token;
91155852Sgallatin	ng_ID_t		response_addr;
92155852Sgallatin};
93155852Sgallatintypedef struct ng_ksocket_private *priv_p;
94155852Sgallatin
95155852Sgallatin/* Flags for priv_p */
96155852Sgallatin#define	KSF_CONNECTING	0x00000001	/* Waiting for connection complete */
97155852Sgallatin#define	KSF_ACCEPTING	0x00000002	/* Waiting for accept complete */
98155852Sgallatin#define	KSF_EOFSEEN	0x00000004	/* Have sent 0-length EOF mbuf */
99155852Sgallatin#define	KSF_CLONED	0x00000008	/* Cloned from an accepting socket */
100159612Sgallatin#define	KSF_EMBRYONIC	0x00000010	/* Cloned node with no hooks yet */
101155852Sgallatin
102155852Sgallatin/* Netgraph node methods */
103155852Sgallatinstatic ng_constructor_t	ng_ksocket_constructor;
104155852Sgallatinstatic ng_rcvmsg_t	ng_ksocket_rcvmsg;
105159612Sgallatinstatic ng_shutdown_t	ng_ksocket_shutdown;
106159612Sgallatinstatic ng_newhook_t	ng_ksocket_newhook;
107159612Sgallatinstatic ng_rcvdata_t	ng_ksocket_rcvdata;
108159612Sgallatinstatic ng_connect_t	ng_ksocket_connect;
109159612Sgallatinstatic ng_disconnect_t	ng_ksocket_disconnect;
110159612Sgallatin
111159612Sgallatin/* Alias structure */
112159612Sgallatinstruct ng_ksocket_alias {
113159612Sgallatin	const char	*name;
114155852Sgallatin	const int	value;
115159612Sgallatin	const int	family;
116159612Sgallatin};
117155852Sgallatin
118159612Sgallatin/* Protocol family aliases */
119155852Sgallatinstatic const struct ng_ksocket_alias ng_ksocket_families[] = {
120155852Sgallatin	{ "local",	PF_LOCAL	},
121159612Sgallatin	{ "inet",	PF_INET		},
122159612Sgallatin	{ "inet6",	PF_INET6	},
123155852Sgallatin	{ "atm",	PF_ATM		},
124159612Sgallatin	{ NULL,		-1		},
125159612Sgallatin};
126155852Sgallatin
127155852Sgallatin/* Socket type aliases */
128159612Sgallatinstatic const struct ng_ksocket_alias ng_ksocket_types[] = {
129155852Sgallatin	{ "stream",	SOCK_STREAM	},
130155852Sgallatin	{ "dgram",	SOCK_DGRAM	},
131159612Sgallatin	{ "raw",	SOCK_RAW	},
132155852Sgallatin	{ "rdm",	SOCK_RDM	},
133159612Sgallatin	{ "seqpacket",	SOCK_SEQPACKET	},
134159612Sgallatin	{ NULL,		-1		},
135155852Sgallatin};
136159612Sgallatin
137159612Sgallatin/* Protocol aliases */
138159612Sgallatinstatic const struct ng_ksocket_alias ng_ksocket_protos[] = {
139155852Sgallatin	{ "ip",		IPPROTO_IP,		PF_INET		},
140155852Sgallatin	{ "raw",	IPPROTO_RAW,		PF_INET		},
141159612Sgallatin	{ "icmp",	IPPROTO_ICMP,		PF_INET		},
142155852Sgallatin	{ "igmp",	IPPROTO_IGMP,		PF_INET		},
143155852Sgallatin	{ "tcp",	IPPROTO_TCP,		PF_INET		},
144159612Sgallatin	{ "udp",	IPPROTO_UDP,		PF_INET		},
145159612Sgallatin	{ "gre",	IPPROTO_GRE,		PF_INET		},
146155852Sgallatin	{ "esp",	IPPROTO_ESP,		PF_INET		},
147155852Sgallatin	{ "ah",		IPPROTO_AH,		PF_INET		},
148155852Sgallatin	{ "swipe",	IPPROTO_SWIPE,		PF_INET		},
149155852Sgallatin	{ "encap",	IPPROTO_ENCAP,		PF_INET		},
150162328Sgallatin	{ "divert",	IPPROTO_DIVERT,		PF_INET		},
151162328Sgallatin	{ "pim",	IPPROTO_PIM,		PF_INET		},
152155852Sgallatin	{ NULL,		-1					},
153162328Sgallatin};
154162328Sgallatin
155162328Sgallatin/* Helper functions */
156162328Sgallatinstatic int	ng_ksocket_check_accept(priv_p);
157162328Sgallatinstatic void	ng_ksocket_finish_accept(priv_p);
158162328Sgallatinstatic int	ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
159162328Sgallatinstatic int	ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
160162328Sgallatin			const char *s, int family);
161162328Sgallatinstatic void	ng_ksocket_incoming2(node_p node, hook_p hook,
162162328Sgallatin			void *arg1, int arg2);
163162328Sgallatin
164159612Sgallatin/************************************************************************
165159612Sgallatin			STRUCT SOCKADDR PARSE TYPE
166155852Sgallatin ************************************************************************/
167155852Sgallatin
168159612Sgallatin/* Get the length of the data portion of a generic struct sockaddr */
169155852Sgallatinstatic int
170155852Sgallatinng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
171155852Sgallatin	const u_char *start, const u_char *buf)
172159612Sgallatin{
173155852Sgallatin	const struct sockaddr *sa;
174155852Sgallatin
175155852Sgallatin	sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
176159612Sgallatin	return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
177159612Sgallatin}
178155852Sgallatin
179159612Sgallatin/* Type for the variable length data portion of a generic struct sockaddr */
180159612Sgallatinstatic const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
181159612Sgallatin	&ng_parse_bytearray_type,
182155852Sgallatin	&ng_parse_generic_sockdata_getLength
183155852Sgallatin};
184155852Sgallatin
185155852Sgallatin/* Type for a generic struct sockaddr */
186155852Sgallatinstatic const struct ng_parse_struct_field
187159612Sgallatin    ng_parse_generic_sockaddr_type_fields[] = {
188159612Sgallatin	  { "len",	&ng_parse_uint8_type			},
189159612Sgallatin	  { "family",	&ng_parse_uint8_type			},
190159612Sgallatin	  { "data",	&ng_ksocket_generic_sockdata_type	},
191159612Sgallatin	  { NULL }
192155852Sgallatin};
193155852Sgallatinstatic const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
194155852Sgallatin	&ng_parse_struct_type,
195155852Sgallatin	&ng_parse_generic_sockaddr_type_fields
196159612Sgallatin};
197159612Sgallatin
198155852Sgallatin/* Convert a struct sockaddr from ASCII to binary.  If its a protocol
199155852Sgallatin   family that we specially handle, do that, otherwise defer to the
200155852Sgallatin   generic parse type ng_ksocket_generic_sockaddr_type. */
201155852Sgallatinstatic int
202155852Sgallatinng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
203155852Sgallatin	const char *s, int *off, const u_char *const start,
204159612Sgallatin	u_char *const buf, int *buflen)
205155852Sgallatin{
206155852Sgallatin	struct sockaddr *const sa = (struct sockaddr *)buf;
207155852Sgallatin	enum ng_parse_token tok;
208155852Sgallatin	char fambuf[32];
209159612Sgallatin	int family, len;
210155852Sgallatin	char *t;
211155852Sgallatin
212159612Sgallatin	/* If next token is a left curly brace, use generic parse type */
213155852Sgallatin	if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
214155852Sgallatin		return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
215155852Sgallatin		    (&ng_ksocket_generic_sockaddr_type,
216159612Sgallatin		    s, off, start, buf, buflen);
217155852Sgallatin	}
218155852Sgallatin
219155852Sgallatin	/* Get socket address family followed by a slash */
220155852Sgallatin	while (isspace(s[*off]))
221155852Sgallatin		(*off)++;
222155852Sgallatin	if ((t = strchr(s + *off, '/')) == NULL)
223155852Sgallatin		return (EINVAL);
224159612Sgallatin	if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
225159612Sgallatin		return (EINVAL);
226159612Sgallatin	strncpy(fambuf, s + *off, len);
227162328Sgallatin	fambuf[len] = '\0';
228155852Sgallatin	*off += len + 1;
229159612Sgallatin	if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
230159612Sgallatin		return (EINVAL);
231159612Sgallatin
232155852Sgallatin	/* Set family */
233159612Sgallatin	if (*buflen < SADATA_OFFSET)
234159612Sgallatin		return (ERANGE);
235155852Sgallatin	sa->sa_family = family;
236159612Sgallatin
237159612Sgallatin	/* Set family-specific data and length */
238159612Sgallatin	switch (sa->sa_family) {
239159612Sgallatin	case PF_LOCAL:		/* Get pathname */
240159612Sgallatin	    {
241162328Sgallatin		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
242162328Sgallatin		struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
243162328Sgallatin		int toklen, pathlen;
244162328Sgallatin		char *path;
245162328Sgallatin
246162328Sgallatin		if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
247162328Sgallatin			return (EINVAL);
248162328Sgallatin		pathlen = strlen(path);
249162328Sgallatin		if (pathlen > SOCK_MAXADDRLEN) {
250162328Sgallatin			free(path, M_NETGRAPH_KSOCKET);
251162328Sgallatin			return (E2BIG);
252162328Sgallatin		}
253162328Sgallatin		if (*buflen < pathoff + pathlen) {
254162328Sgallatin			free(path, M_NETGRAPH_KSOCKET);
255162328Sgallatin			return (ERANGE);
256162328Sgallatin		}
257162328Sgallatin		*off += toklen;
258162328Sgallatin		bcopy(path, sun->sun_path, pathlen);
259162328Sgallatin		sun->sun_len = pathoff + pathlen;
260162328Sgallatin		free(path, M_NETGRAPH_KSOCKET);
261159612Sgallatin		break;
262159612Sgallatin	    }
263155852Sgallatin
264155852Sgallatin	case PF_INET:		/* Get an IP address with optional port */
265159612Sgallatin	    {
266159612Sgallatin		struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
267159612Sgallatin		int i;
268159612Sgallatin
269159612Sgallatin		/* Parse this: <ipaddress>[:port] */
270159612Sgallatin		for (i = 0; i < 4; i++) {
271159612Sgallatin			u_long val;
272159612Sgallatin			char *eptr;
273159612Sgallatin
274162328Sgallatin			val = strtoul(s + *off, &eptr, 10);
275162328Sgallatin			if (val > 0xff || eptr == s + *off)
276159612Sgallatin				return (EINVAL);
277159612Sgallatin			*off += (eptr - (s + *off));
278155852Sgallatin			((u_char *)&sin->sin_addr)[i] = (u_char)val;
279155852Sgallatin			if (i < 3) {
280162328Sgallatin				if (s[*off] != '.')
281162328Sgallatin					return (EINVAL);
282162328Sgallatin				(*off)++;
283162328Sgallatin			} else if (s[*off] == ':') {
284162328Sgallatin				(*off)++;
285162328Sgallatin				val = strtoul(s + *off, &eptr, 10);
286159612Sgallatin				if (val > 0xffff || eptr == s + *off)
287159612Sgallatin					return (EINVAL);
288159612Sgallatin				*off += (eptr - (s + *off));
289155852Sgallatin				sin->sin_port = htons(val);
290155852Sgallatin			} else
291155852Sgallatin				sin->sin_port = 0;
292155852Sgallatin		}
293155852Sgallatin		bzero(&sin->sin_zero, sizeof(sin->sin_zero));
294155852Sgallatin		sin->sin_len = sizeof(*sin);
295155852Sgallatin		break;
296155852Sgallatin	    }
297155852Sgallatin
298159612Sgallatin#if 0
299159612Sgallatin	case PF_INET6:	/* XXX implement this someday */
300159612Sgallatin#endif
301159612Sgallatin
302159612Sgallatin	default:
303159612Sgallatin		return (EINVAL);
304155852Sgallatin	}
305159612Sgallatin
306159612Sgallatin	/* Done */
307	*buflen = sa->sa_len;
308	return (0);
309}
310
311/* Convert a struct sockaddr from binary to ASCII */
312static int
313ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
314	const u_char *data, int *off, char *cbuf, int cbuflen)
315{
316	const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
317	int slen = 0;
318
319	/* Output socket address, either in special or generic format */
320	switch (sa->sa_family) {
321	case PF_LOCAL:
322	    {
323		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
324		const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
325		const int pathlen = sun->sun_len - pathoff;
326		char pathbuf[SOCK_MAXADDRLEN + 1];
327		char *pathtoken;
328
329		bcopy(sun->sun_path, pathbuf, pathlen);
330		if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
331			return (ENOMEM);
332		slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
333		free(pathtoken, M_NETGRAPH_KSOCKET);
334		if (slen >= cbuflen)
335			return (ERANGE);
336		*off += sun->sun_len;
337		return (0);
338	    }
339
340	case PF_INET:
341	    {
342		const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
343
344		slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
345		  ((const u_char *)&sin->sin_addr)[0],
346		  ((const u_char *)&sin->sin_addr)[1],
347		  ((const u_char *)&sin->sin_addr)[2],
348		  ((const u_char *)&sin->sin_addr)[3]);
349		if (sin->sin_port != 0) {
350			slen += snprintf(cbuf + strlen(cbuf),
351			    cbuflen - strlen(cbuf), ":%d",
352			    (u_int)ntohs(sin->sin_port));
353		}
354		if (slen >= cbuflen)
355			return (ERANGE);
356		*off += sizeof(*sin);
357		return(0);
358	    }
359
360#if 0
361	case PF_INET6:	/* XXX implement this someday */
362#endif
363
364	default:
365		return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
366		    (&ng_ksocket_generic_sockaddr_type,
367		    data, off, cbuf, cbuflen);
368	}
369}
370
371/* Parse type for struct sockaddr */
372static const struct ng_parse_type ng_ksocket_sockaddr_type = {
373	NULL,
374	NULL,
375	NULL,
376	&ng_ksocket_sockaddr_parse,
377	&ng_ksocket_sockaddr_unparse,
378	NULL		/* no such thing as a default struct sockaddr */
379};
380
381/************************************************************************
382		STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
383 ************************************************************************/
384
385/* Get length of the struct ng_ksocket_sockopt value field, which is the
386   just the excess of the message argument portion over the length of
387   the struct ng_ksocket_sockopt. */
388static int
389ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
390	const u_char *start, const u_char *buf)
391{
392	static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
393	const struct ng_ksocket_sockopt *sopt;
394	const struct ng_mesg *msg;
395
396	sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
397	msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
398	return msg->header.arglen - sizeof(*sopt);
399}
400
401/* Parse type for the option value part of a struct ng_ksocket_sockopt
402   XXX Eventually, we should handle the different socket options specially.
403   XXX This would avoid byte order problems, eg an integer value of 1 is
404   XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
405static const struct ng_parse_type ng_ksocket_sockoptval_type = {
406	&ng_parse_bytearray_type,
407	&ng_parse_sockoptval_getLength
408};
409
410/* Parse type for struct ng_ksocket_sockopt */
411static const struct ng_parse_struct_field ng_ksocket_sockopt_type_fields[]
412	= NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
413static const struct ng_parse_type ng_ksocket_sockopt_type = {
414	&ng_parse_struct_type,
415	&ng_ksocket_sockopt_type_fields
416};
417
418/* Parse type for struct ng_ksocket_accept */
419static const struct ng_parse_struct_field ng_ksocket_accept_type_fields[]
420	= NGM_KSOCKET_ACCEPT_INFO;
421static const struct ng_parse_type ng_ksocket_accept_type = {
422	&ng_parse_struct_type,
423	&ng_ksocket_accept_type_fields
424};
425
426/* List of commands and how to convert arguments to/from ASCII */
427static const struct ng_cmdlist ng_ksocket_cmds[] = {
428	{
429	  NGM_KSOCKET_COOKIE,
430	  NGM_KSOCKET_BIND,
431	  "bind",
432	  &ng_ksocket_sockaddr_type,
433	  NULL
434	},
435	{
436	  NGM_KSOCKET_COOKIE,
437	  NGM_KSOCKET_LISTEN,
438	  "listen",
439	  &ng_parse_int32_type,
440	  NULL
441	},
442	{
443	  NGM_KSOCKET_COOKIE,
444	  NGM_KSOCKET_ACCEPT,
445	  "accept",
446	  NULL,
447	  &ng_ksocket_accept_type
448	},
449	{
450	  NGM_KSOCKET_COOKIE,
451	  NGM_KSOCKET_CONNECT,
452	  "connect",
453	  &ng_ksocket_sockaddr_type,
454	  &ng_parse_int32_type
455	},
456	{
457	  NGM_KSOCKET_COOKIE,
458	  NGM_KSOCKET_GETNAME,
459	  "getname",
460	  NULL,
461	  &ng_ksocket_sockaddr_type
462	},
463	{
464	  NGM_KSOCKET_COOKIE,
465	  NGM_KSOCKET_GETPEERNAME,
466	  "getpeername",
467	  NULL,
468	  &ng_ksocket_sockaddr_type
469	},
470	{
471	  NGM_KSOCKET_COOKIE,
472	  NGM_KSOCKET_SETOPT,
473	  "setopt",
474	  &ng_ksocket_sockopt_type,
475	  NULL
476	},
477	{
478	  NGM_KSOCKET_COOKIE,
479	  NGM_KSOCKET_GETOPT,
480	  "getopt",
481	  &ng_ksocket_sockopt_type,
482	  &ng_ksocket_sockopt_type
483	},
484	{ 0 }
485};
486
487/* Node type descriptor */
488static struct ng_type ng_ksocket_typestruct = {
489	.version =	NG_ABI_VERSION,
490	.name =		NG_KSOCKET_NODE_TYPE,
491	.constructor =	ng_ksocket_constructor,
492	.rcvmsg =	ng_ksocket_rcvmsg,
493	.shutdown =	ng_ksocket_shutdown,
494	.newhook =	ng_ksocket_newhook,
495	.connect =	ng_ksocket_connect,
496	.rcvdata =	ng_ksocket_rcvdata,
497	.disconnect =	ng_ksocket_disconnect,
498	.cmdlist =	ng_ksocket_cmds,
499};
500NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
501
502#define ERROUT(x)	do { error = (x); goto done; } while (0)
503
504/************************************************************************
505			NETGRAPH NODE STUFF
506 ************************************************************************/
507
508/*
509 * Node type constructor
510 * The NODE part is assumed to be all set up.
511 * There is already a reference to the node for us.
512 */
513static int
514ng_ksocket_constructor(node_p node)
515{
516	priv_p priv;
517
518	/* Allocate private structure */
519	priv = malloc(sizeof(*priv), M_NETGRAPH_KSOCKET, M_NOWAIT | M_ZERO);
520	if (priv == NULL)
521		return (ENOMEM);
522
523	LIST_INIT(&priv->embryos);
524	/* cross link them */
525	priv->node = node;
526	NG_NODE_SET_PRIVATE(node, priv);
527
528	/* Done */
529	return (0);
530}
531
532/*
533 * Give our OK for a hook to be added. The hook name is of the
534 * form "<family>/<type>/<proto>" where the three components may
535 * be decimal numbers or else aliases from the above lists.
536 *
537 * Connecting a hook amounts to opening the socket.  Disconnecting
538 * the hook closes the socket and destroys the node as well.
539 */
540static int
541ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
542{
543	struct thread *td = curthread;	/* XXX broken */
544	const priv_p priv = NG_NODE_PRIVATE(node);
545	char *s1, *s2, name[NG_HOOKSIZ];
546	int family, type, protocol, error;
547
548	/* Check if we're already connected */
549	if (priv->hook != NULL)
550		return (EISCONN);
551
552	if (priv->flags & KSF_CLONED) {
553		if (priv->flags & KSF_EMBRYONIC) {
554			/* Remove ourselves from our parent's embryo list */
555			LIST_REMOVE(priv, siblings);
556			priv->flags &= ~KSF_EMBRYONIC;
557		}
558	} else {
559		/* Extract family, type, and protocol from hook name */
560		snprintf(name, sizeof(name), "%s", name0);
561		s1 = name;
562		if ((s2 = strchr(s1, '/')) == NULL)
563			return (EINVAL);
564		*s2++ = '\0';
565		family = ng_ksocket_parse(ng_ksocket_families, s1, 0);
566		if (family == -1)
567			return (EINVAL);
568		s1 = s2;
569		if ((s2 = strchr(s1, '/')) == NULL)
570			return (EINVAL);
571		*s2++ = '\0';
572		type = ng_ksocket_parse(ng_ksocket_types, s1, 0);
573		if (type == -1)
574			return (EINVAL);
575		s1 = s2;
576		protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family);
577		if (protocol == -1)
578			return (EINVAL);
579
580		/* Create the socket */
581		error = socreate(family, &priv->so, type, protocol,
582		   td->td_ucred, td);
583		if (error != 0)
584			return (error);
585
586		/* XXX call soreserve() ? */
587
588	}
589
590	/* OK */
591	priv->hook = hook;
592
593	/*
594	 * In case of misconfigured routing a packet may reenter
595	 * ksocket node recursively. Decouple stack to avoid possible
596	 * panics about sleeping with locks held.
597	 */
598	NG_HOOK_FORCE_QUEUE(hook);
599
600	return(0);
601}
602
603static int
604ng_ksocket_connect(hook_p hook)
605{
606	node_p node = NG_HOOK_NODE(hook);
607	const priv_p priv = NG_NODE_PRIVATE(node);
608	struct socket *const so = priv->so;
609
610	/* Add our hook for incoming data and other events */
611	SOCKBUF_LOCK(&priv->so->so_rcv);
612	soupcall_set(priv->so, SO_RCV, ng_ksocket_incoming, node);
613	SOCKBUF_UNLOCK(&priv->so->so_rcv);
614	SOCKBUF_LOCK(&priv->so->so_snd);
615	soupcall_set(priv->so, SO_SND, ng_ksocket_incoming, node);
616	SOCKBUF_UNLOCK(&priv->so->so_snd);
617	SOCK_LOCK(priv->so);
618	priv->so->so_state |= SS_NBIO;
619	SOCK_UNLOCK(priv->so);
620	/*
621	 * --Original comment--
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.
625	 * We cannot call the upcall function directly
626	 * from here, because until this function has returned our
627	 * hook isn't connected.
628	 *
629	 * ---meta comment for -current ---
630	 * XXX This is dubius.
631	 * Upcalls between the time that the hook was
632	 * first created and now (on another processesor) will
633	 * be earlier on the queue than the request to finalise the hook.
634	 * By the time the hook is finalised,
635	 * The queued upcalls will have happened and the code
636	 * will have discarded them because of a lack of a hook.
637	 * (socket not open).
638	 *
639	 * This is a bad byproduct of the complicated way in which hooks
640	 * are now created (3 daisy chained async events).
641	 *
642	 * Since we are a netgraph operation
643	 * We know that we hold a lock on this node. This forces the
644	 * request we make below to be queued rather than implemented
645	 * immediately which will cause the upcall function to be called a bit
646	 * later.
647	 * However, as we will run any waiting queued operations immediately
648	 * after doing this one, if we have not finalised the other end
649	 * of the hook, those queued operations will fail.
650	 */
651	if (priv->flags & KSF_CLONED) {
652		ng_send_fn(node, NULL, &ng_ksocket_incoming2, so, M_NOWAIT);
653	}
654
655	return (0);
656}
657
658/*
659 * Receive a control message
660 */
661static int
662ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
663{
664	struct thread *td = curthread;	/* XXX broken */
665	const priv_p priv = NG_NODE_PRIVATE(node);
666	struct socket *const so = priv->so;
667	struct ng_mesg *resp = NULL;
668	int error = 0;
669	struct ng_mesg *msg;
670	ng_ID_t raddr;
671
672	NGI_GET_MSG(item, msg);
673	switch (msg->header.typecookie) {
674	case NGM_KSOCKET_COOKIE:
675		switch (msg->header.cmd) {
676		case NGM_KSOCKET_BIND:
677		    {
678			struct sockaddr *const sa
679			    = (struct sockaddr *)msg->data;
680
681			/* Sanity check */
682			if (msg->header.arglen < SADATA_OFFSET
683			    || msg->header.arglen < sa->sa_len)
684				ERROUT(EINVAL);
685			if (so == NULL)
686				ERROUT(ENXIO);
687
688			/* Bind */
689			error = sobind(so, sa, td);
690			break;
691		    }
692		case NGM_KSOCKET_LISTEN:
693		    {
694			/* Sanity check */
695			if (msg->header.arglen != sizeof(int32_t))
696				ERROUT(EINVAL);
697			if (so == NULL)
698				ERROUT(ENXIO);
699
700			/* Listen */
701			error = solisten(so, *((int32_t *)msg->data), td);
702			break;
703		    }
704
705		case NGM_KSOCKET_ACCEPT:
706		    {
707			/* Sanity check */
708			if (msg->header.arglen != 0)
709				ERROUT(EINVAL);
710			if (so == NULL)
711				ERROUT(ENXIO);
712
713			/* Make sure the socket is capable of accepting */
714			if (!(so->so_options & SO_ACCEPTCONN))
715				ERROUT(EINVAL);
716			if (priv->flags & KSF_ACCEPTING)
717				ERROUT(EALREADY);
718
719			error = ng_ksocket_check_accept(priv);
720			if (error != 0 && error != EWOULDBLOCK)
721				ERROUT(error);
722
723			/*
724			 * If a connection is already complete, take it.
725			 * Otherwise let the upcall function deal with
726			 * the connection when it comes in.
727			 */
728			priv->response_token = msg->header.token;
729			raddr = priv->response_addr = NGI_RETADDR(item);
730			if (error == 0) {
731				ng_ksocket_finish_accept(priv);
732			} else
733				priv->flags |= KSF_ACCEPTING;
734			break;
735		    }
736
737		case NGM_KSOCKET_CONNECT:
738		    {
739			struct sockaddr *const sa
740			    = (struct sockaddr *)msg->data;
741
742			/* Sanity check */
743			if (msg->header.arglen < SADATA_OFFSET
744			    || msg->header.arglen < sa->sa_len)
745				ERROUT(EINVAL);
746			if (so == NULL)
747				ERROUT(ENXIO);
748
749			/* Do connect */
750			if ((so->so_state & SS_ISCONNECTING) != 0)
751				ERROUT(EALREADY);
752			if ((error = soconnect(so, sa, td)) != 0) {
753				so->so_state &= ~SS_ISCONNECTING;
754				ERROUT(error);
755			}
756			if ((so->so_state & SS_ISCONNECTING) != 0) {
757				/* We will notify the sender when we connect */
758				priv->response_token = msg->header.token;
759				raddr = priv->response_addr = NGI_RETADDR(item);
760				priv->flags |= KSF_CONNECTING;
761				ERROUT(EINPROGRESS);
762			}
763			break;
764		    }
765
766		case NGM_KSOCKET_GETNAME:
767		case NGM_KSOCKET_GETPEERNAME:
768		    {
769			int (*func)(struct socket *so, struct sockaddr **nam);
770			struct sockaddr *sa = NULL;
771			int len;
772
773			/* Sanity check */
774			if (msg->header.arglen != 0)
775				ERROUT(EINVAL);
776			if (so == NULL)
777				ERROUT(ENXIO);
778
779			/* Get function */
780			if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
781				if ((so->so_state
782				    & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
783					ERROUT(ENOTCONN);
784				func = so->so_proto->pr_usrreqs->pru_peeraddr;
785			} else
786				func = so->so_proto->pr_usrreqs->pru_sockaddr;
787
788			/* Get local or peer address */
789			if ((error = (*func)(so, &sa)) != 0)
790				goto bail;
791			len = (sa == NULL) ? 0 : sa->sa_len;
792
793			/* Send it back in a response */
794			NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
795			if (resp == NULL) {
796				error = ENOMEM;
797				goto bail;
798			}
799			bcopy(sa, resp->data, len);
800
801		bail:
802			/* Cleanup */
803			if (sa != NULL)
804				free(sa, M_SONAME);
805			break;
806		    }
807
808		case NGM_KSOCKET_GETOPT:
809		    {
810			struct ng_ksocket_sockopt *ksopt =
811			    (struct ng_ksocket_sockopt *)msg->data;
812			struct sockopt sopt;
813
814			/* Sanity check */
815			if (msg->header.arglen != sizeof(*ksopt))
816				ERROUT(EINVAL);
817			if (so == NULL)
818				ERROUT(ENXIO);
819
820			/* Get response with room for option value */
821			NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
822			    + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
823			if (resp == NULL)
824				ERROUT(ENOMEM);
825
826			/* Get socket option, and put value in the response */
827			sopt.sopt_dir = SOPT_GET;
828			sopt.sopt_level = ksopt->level;
829			sopt.sopt_name = ksopt->name;
830			sopt.sopt_td = NULL;
831			sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
832			ksopt = (struct ng_ksocket_sockopt *)resp->data;
833			sopt.sopt_val = ksopt->value;
834			if ((error = sogetopt(so, &sopt)) != 0) {
835				NG_FREE_MSG(resp);
836				break;
837			}
838
839			/* Set actual value length */
840			resp->header.arglen = sizeof(*ksopt)
841			    + sopt.sopt_valsize;
842			break;
843		    }
844
845		case NGM_KSOCKET_SETOPT:
846		    {
847			struct ng_ksocket_sockopt *const ksopt =
848			    (struct ng_ksocket_sockopt *)msg->data;
849			const int valsize = msg->header.arglen - sizeof(*ksopt);
850			struct sockopt sopt;
851
852			/* Sanity check */
853			if (valsize < 0)
854				ERROUT(EINVAL);
855			if (so == NULL)
856				ERROUT(ENXIO);
857
858			/* Set socket option */
859			sopt.sopt_dir = SOPT_SET;
860			sopt.sopt_level = ksopt->level;
861			sopt.sopt_name = ksopt->name;
862			sopt.sopt_val = ksopt->value;
863			sopt.sopt_valsize = valsize;
864			sopt.sopt_td = NULL;
865			error = sosetopt(so, &sopt);
866			break;
867		    }
868
869		default:
870			error = EINVAL;
871			break;
872		}
873		break;
874	default:
875		error = EINVAL;
876		break;
877	}
878done:
879	NG_RESPOND_MSG(error, node, item, resp);
880	NG_FREE_MSG(msg);
881	return (error);
882}
883
884/*
885 * Receive incoming data on our hook.  Send it out the socket.
886 */
887static int
888ng_ksocket_rcvdata(hook_p hook, item_p item)
889{
890	struct thread *td = curthread;	/* XXX broken */
891	const node_p node = NG_HOOK_NODE(hook);
892	const priv_p priv = NG_NODE_PRIVATE(node);
893	struct socket *const so = priv->so;
894	struct sockaddr *sa = NULL;
895	int error;
896	struct mbuf *m;
897#ifdef ALIGNED_POINTER
898	struct mbuf *n;
899#endif /* ALIGNED_POINTER */
900	struct sa_tag *stag;
901
902	/* Extract data */
903	NGI_GET_M(item, m);
904	NG_FREE_ITEM(item);
905#ifdef ALIGNED_POINTER
906	if (!ALIGNED_POINTER(mtod(m, caddr_t), uint32_t)) {
907		n = m_defrag(m, M_NOWAIT);
908		if (n == NULL) {
909			m_freem(m);
910			return (ENOBUFS);
911		}
912		m = n;
913	}
914#endif /* ALIGNED_POINTER */
915	/*
916	 * Look if socket address is stored in packet tags.
917	 * If sockaddr is ours, or provided by a third party (zero id),
918	 * then we accept it.
919	 */
920	if (((stag = (struct sa_tag *)m_tag_locate(m, NGM_KSOCKET_COOKIE,
921	    NG_KSOCKET_TAG_SOCKADDR, NULL)) != NULL) &&
922	    (stag->id == NG_NODE_ID(node) || stag->id == 0))
923		sa = &stag->sa;
924
925	/* Reset specific mbuf flags to prevent addressing problems. */
926	m->m_flags &= ~(M_BCAST|M_MCAST);
927
928	/* Send packet */
929	error = sosend(so, sa, 0, m, 0, 0, td);
930
931	return (error);
932}
933
934/*
935 * Destroy node
936 */
937static int
938ng_ksocket_shutdown(node_p node)
939{
940	const priv_p priv = NG_NODE_PRIVATE(node);
941	priv_p embryo;
942
943	/* Close our socket (if any) */
944	if (priv->so != NULL) {
945		SOCKBUF_LOCK(&priv->so->so_rcv);
946		soupcall_clear(priv->so, SO_RCV);
947		SOCKBUF_UNLOCK(&priv->so->so_rcv);
948		SOCKBUF_LOCK(&priv->so->so_snd);
949		soupcall_clear(priv->so, SO_SND);
950		SOCKBUF_UNLOCK(&priv->so->so_snd);
951		soclose(priv->so);
952		priv->so = NULL;
953	}
954
955	/* If we are an embryo, take ourselves out of the parent's list */
956	if (priv->flags & KSF_EMBRYONIC) {
957		LIST_REMOVE(priv, siblings);
958		priv->flags &= ~KSF_EMBRYONIC;
959	}
960
961	/* Remove any embryonic children we have */
962	while (!LIST_EMPTY(&priv->embryos)) {
963		embryo = LIST_FIRST(&priv->embryos);
964		ng_rmnode_self(embryo->node);
965	}
966
967	/* Take down netgraph node */
968	bzero(priv, sizeof(*priv));
969	free(priv, M_NETGRAPH_KSOCKET);
970	NG_NODE_SET_PRIVATE(node, NULL);
971	NG_NODE_UNREF(node);		/* let the node escape */
972	return (0);
973}
974
975/*
976 * Hook disconnection
977 */
978static int
979ng_ksocket_disconnect(hook_p hook)
980{
981	KASSERT(NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0,
982	    ("%s: numhooks=%d?", __func__,
983	    NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook))));
984	if (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
985		ng_rmnode_self(NG_HOOK_NODE(hook));
986	return (0);
987}
988
989/************************************************************************
990			HELPER STUFF
991 ************************************************************************/
992/*
993 * You should not "just call" a netgraph node function from an external
994 * asynchronous event. This is because in doing so you are ignoring the
995 * locking on the netgraph nodes. Instead call your function via ng_send_fn().
996 * This will call the function you chose, but will first do all the
997 * locking rigmarole. Your function MAY only be called at some distant future
998 * time (several millisecs away) so don't give it any arguments
999 * that may be revoked soon (e.g. on your stack).
1000 *
1001 * To decouple stack, we use queue version of ng_send_fn().
1002 */
1003
1004static int
1005ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
1006{
1007	const node_p node = arg;
1008	const priv_p priv = NG_NODE_PRIVATE(node);
1009	int wait = ((waitflag & M_WAITOK) ? NG_WAITOK : 0) | NG_QUEUE;
1010
1011	/*
1012	 * Even if node is not locked, as soon as we are called, we assume
1013	 * it exist and it's private area is valid. With some care we can
1014	 * access it. Mark node that incoming event for it was sent to
1015	 * avoid unneded queue trashing.
1016	 */
1017	if (atomic_cmpset_int(&priv->fn_sent, 0, 1) &&
1018	    ng_send_fn1(node, NULL, &ng_ksocket_incoming2, so, 0, wait)) {
1019		atomic_store_rel_int(&priv->fn_sent, 0);
1020	}
1021	return (SU_OK);
1022}
1023
1024
1025/*
1026 * When incoming data is appended to the socket, we get notified here.
1027 * This is also called whenever a significant event occurs for the socket.
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 and guarantied to be valid.
1031 */
1032static void
1033ng_ksocket_incoming2(node_p node, hook_p hook, void *arg1, int arg2)
1034{
1035	struct socket *so = arg1;
1036	const priv_p priv = NG_NODE_PRIVATE(node);
1037	struct ng_mesg *response;
1038	int error;
1039
1040	KASSERT(so == priv->so, ("%s: wrong socket", __func__));
1041
1042	/* Allow next incoming event to be queued. */
1043	atomic_store_rel_int(&priv->fn_sent, 0);
1044
1045	/* Check whether a pending connect operation has completed */
1046	if (priv->flags & KSF_CONNECTING) {
1047		if ((error = so->so_error) != 0) {
1048			so->so_error = 0;
1049			so->so_state &= ~SS_ISCONNECTING;
1050		}
1051		if (!(so->so_state & SS_ISCONNECTING)) {
1052			NG_MKMESSAGE(response, NGM_KSOCKET_COOKIE,
1053			    NGM_KSOCKET_CONNECT, sizeof(int32_t), M_NOWAIT);
1054			if (response != NULL) {
1055				response->header.flags |= NGF_RESP;
1056				response->header.token = priv->response_token;
1057				*(int32_t *)response->data = error;
1058				/*
1059				 * send an async "response" message
1060				 * to the node that set us up
1061				 * (if it still exists)
1062				 */
1063				NG_SEND_MSG_ID(error, node,
1064				    response, priv->response_addr, 0);
1065			}
1066			priv->flags &= ~KSF_CONNECTING;
1067		}
1068	}
1069
1070	/* Check whether a pending accept operation has completed */
1071	if (priv->flags & KSF_ACCEPTING) {
1072		error = ng_ksocket_check_accept(priv);
1073		if (error != EWOULDBLOCK)
1074			priv->flags &= ~KSF_ACCEPTING;
1075		if (error == 0)
1076			ng_ksocket_finish_accept(priv);
1077	}
1078
1079	/*
1080	 * If we don't have a hook, we must handle data events later.  When
1081	 * the hook gets created and is connected, this upcall function
1082	 * will be called again.
1083	 */
1084	if (priv->hook == NULL)
1085		return;
1086
1087	/* Read and forward available mbufs. */
1088	while (1) {
1089		struct uio uio;
1090		struct sockaddr *sa;
1091		struct mbuf *m;
1092		int flags;
1093
1094		/* Try to get next packet from socket. */
1095		uio.uio_td = NULL;
1096		uio.uio_resid = IP_MAXPACKET;
1097		flags = MSG_DONTWAIT;
1098		sa = NULL;
1099		if ((error = soreceive(so, (so->so_state & SS_ISCONNECTED) ?
1100		    NULL : &sa, &uio, &m, NULL, &flags)) != 0)
1101			break;
1102
1103		/* See if we got anything. */
1104		if (flags & MSG_TRUNC) {
1105			m_freem(m);
1106			m = NULL;
1107		}
1108		if (m == NULL) {
1109			if (sa != NULL)
1110				free(sa, M_SONAME);
1111			break;
1112		}
1113
1114		KASSERT(m->m_nextpkt == NULL, ("%s: nextpkt", __func__));
1115
1116		/*
1117		 * Stream sockets do not have packet boundaries, so
1118		 * we have to allocate a header mbuf and attach the
1119		 * stream of data to it.
1120		 */
1121		if (so->so_type == SOCK_STREAM) {
1122			struct mbuf *mh;
1123
1124			mh = m_gethdr(M_NOWAIT, MT_DATA);
1125			if (mh == NULL) {
1126				m_freem(m);
1127				if (sa != NULL)
1128					free(sa, M_SONAME);
1129				break;
1130			}
1131
1132			mh->m_next = m;
1133			for (; m; m = m->m_next)
1134				mh->m_pkthdr.len += m->m_len;
1135			m = mh;
1136		}
1137
1138		/* Put peer's socket address (if any) into a tag */
1139		if (sa != NULL) {
1140			struct sa_tag	*stag;
1141
1142			stag = (struct sa_tag *)m_tag_alloc(NGM_KSOCKET_COOKIE,
1143			    NG_KSOCKET_TAG_SOCKADDR, sizeof(ng_ID_t) +
1144			    sa->sa_len, M_NOWAIT);
1145			if (stag == NULL) {
1146				free(sa, M_SONAME);
1147				goto sendit;
1148			}
1149			bcopy(sa, &stag->sa, sa->sa_len);
1150			free(sa, M_SONAME);
1151			stag->id = NG_NODE_ID(node);
1152			m_tag_prepend(m, &stag->tag);
1153		}
1154
1155sendit:		/* Forward data with optional peer sockaddr as packet tag */
1156		NG_SEND_DATA_ONLY(error, priv->hook, m);
1157	}
1158
1159	/*
1160	 * If the peer has closed the connection, forward a 0-length mbuf
1161	 * to indicate end-of-file.
1162	 */
1163	if (so->so_rcv.sb_state & SBS_CANTRCVMORE &&
1164	    !(priv->flags & KSF_EOFSEEN)) {
1165		struct mbuf *m;
1166
1167		m = m_gethdr(M_NOWAIT, MT_DATA);
1168		if (m != NULL)
1169			NG_SEND_DATA_ONLY(error, priv->hook, m);
1170		priv->flags |= KSF_EOFSEEN;
1171	}
1172}
1173
1174/*
1175 * Check for a completed incoming connection and return 0 if one is found.
1176 * Otherwise return the appropriate error code.
1177 */
1178static int
1179ng_ksocket_check_accept(priv_p priv)
1180{
1181	struct socket *const head = priv->so;
1182	int error;
1183
1184	if ((error = head->so_error) != 0) {
1185		head->so_error = 0;
1186		return error;
1187	}
1188	/* Unlocked read. */
1189	if (TAILQ_EMPTY(&head->so_comp)) {
1190		if (head->so_rcv.sb_state & SBS_CANTRCVMORE)
1191			return ECONNABORTED;
1192		return EWOULDBLOCK;
1193	}
1194	return 0;
1195}
1196
1197/*
1198 * Handle the first completed incoming connection, assumed to be already
1199 * on the socket's so_comp queue.
1200 */
1201static void
1202ng_ksocket_finish_accept(priv_p priv)
1203{
1204	struct socket *const head = priv->so;
1205	struct socket *so;
1206	struct sockaddr *sa = NULL;
1207	struct ng_mesg *resp;
1208	struct ng_ksocket_accept *resp_data;
1209	node_p node;
1210	priv_p priv2;
1211	int len;
1212	int error;
1213
1214	ACCEPT_LOCK();
1215	so = TAILQ_FIRST(&head->so_comp);
1216	if (so == NULL) {	/* Should never happen */
1217		ACCEPT_UNLOCK();
1218		return;
1219	}
1220	TAILQ_REMOVE(&head->so_comp, so, so_list);
1221	head->so_qlen--;
1222	so->so_qstate &= ~SQ_COMP;
1223	so->so_head = NULL;
1224	SOCK_LOCK(so);
1225	soref(so);
1226	so->so_state |= SS_NBIO;
1227	SOCK_UNLOCK(so);
1228	ACCEPT_UNLOCK();
1229
1230	/* XXX KNOTE_UNLOCKED(&head->so_rcv.sb_sel.si_note, 0); */
1231
1232	soaccept(so, &sa);
1233
1234	len = OFFSETOF(struct ng_ksocket_accept, addr);
1235	if (sa != NULL)
1236		len += sa->sa_len;
1237
1238	NG_MKMESSAGE(resp, NGM_KSOCKET_COOKIE, NGM_KSOCKET_ACCEPT, len,
1239	    M_NOWAIT);
1240	if (resp == NULL) {
1241		soclose(so);
1242		goto out;
1243	}
1244	resp->header.flags |= NGF_RESP;
1245	resp->header.token = priv->response_token;
1246
1247	/* Clone a ksocket node to wrap the new socket */
1248	error = ng_make_node_common(&ng_ksocket_typestruct, &node);
1249	if (error) {
1250		free(resp, M_NETGRAPH);
1251		soclose(so);
1252		goto out;
1253	}
1254
1255	if (ng_ksocket_constructor(node) != 0) {
1256		NG_NODE_UNREF(node);
1257		free(resp, M_NETGRAPH);
1258		soclose(so);
1259		goto out;
1260	}
1261
1262	priv2 = NG_NODE_PRIVATE(node);
1263	priv2->so = so;
1264	priv2->flags |= KSF_CLONED | KSF_EMBRYONIC;
1265
1266	/*
1267	 * Insert the cloned node into a list of embryonic children
1268	 * on the parent node.  When a hook is created on the cloned
1269	 * node it will be removed from this list.  When the parent
1270	 * is destroyed it will destroy any embryonic children it has.
1271	 */
1272	LIST_INSERT_HEAD(&priv->embryos, priv2, siblings);
1273
1274	SOCKBUF_LOCK(&so->so_rcv);
1275	soupcall_set(so, SO_RCV, ng_ksocket_incoming, node);
1276	SOCKBUF_UNLOCK(&so->so_rcv);
1277	SOCKBUF_LOCK(&so->so_snd);
1278	soupcall_set(so, SO_SND, ng_ksocket_incoming, node);
1279	SOCKBUF_UNLOCK(&so->so_snd);
1280
1281	/* Fill in the response data and send it or return it to the caller */
1282	resp_data = (struct ng_ksocket_accept *)resp->data;
1283	resp_data->nodeid = NG_NODE_ID(node);
1284	if (sa != NULL)
1285		bcopy(sa, &resp_data->addr, sa->sa_len);
1286	NG_SEND_MSG_ID(error, node, resp, priv->response_addr, 0);
1287
1288out:
1289	if (sa != NULL)
1290		free(sa, M_SONAME);
1291}
1292
1293/*
1294 * Parse out either an integer value or an alias.
1295 */
1296static int
1297ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
1298	const char *s, int family)
1299{
1300	int k, val;
1301	char *eptr;
1302
1303	/* Try aliases */
1304	for (k = 0; aliases[k].name != NULL; k++) {
1305		if (strcmp(s, aliases[k].name) == 0
1306		    && aliases[k].family == family)
1307			return aliases[k].value;
1308	}
1309
1310	/* Try parsing as a number */
1311	val = (int)strtoul(s, &eptr, 10);
1312	if (val < 0 || *eptr != '\0')
1313		return (-1);
1314	return (val);
1315}
1316
1317