ng_ksocket.c revision 70700
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: head/sys/netgraph/ng_ksocket.c 70700 2001-01-06 00:46:47Z julian $
40 * $Whistle: ng_ksocket.c,v 1.1 1999/11/16 20:04:40 archie Exp $
41 */
42
43/*
44 * Kernel socket node type.  This node type is basically a kernel-mode
45 * version of a socket... kindof like the reverse of the socket node type.
46 */
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/kernel.h>
51#include <sys/mbuf.h>
52#include <sys/proc.h>
53#include <sys/malloc.h>
54#include <sys/ctype.h>
55#include <sys/protosw.h>
56#include <sys/errno.h>
57#include <sys/socket.h>
58#include <sys/socketvar.h>
59#include <sys/uio.h>
60#include <sys/un.h>
61
62#include <netgraph/ng_message.h>
63#include <netgraph/netgraph.h>
64#include <netgraph/ng_parse.h>
65#include <netgraph/ng_ksocket.h>
66
67#include <netinet/in.h>
68#include <netatalk/at.h>
69
70#define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
71#define SADATA_OFFSET	(OFFSETOF(struct sockaddr, sa_data))
72
73/* Node private data */
74struct ng_ksocket_private {
75	hook_p		hook;
76	struct socket	*so;
77};
78typedef struct ng_ksocket_private *priv_p;
79
80/* Netgraph node methods */
81static ng_constructor_t	ng_ksocket_constructor;
82static ng_rcvmsg_t	ng_ksocket_rcvmsg;
83static ng_shutdown_t	ng_ksocket_shutdown;
84static ng_newhook_t	ng_ksocket_newhook;
85static ng_rcvdata_t	ng_ksocket_rcvdata;
86static ng_disconnect_t	ng_ksocket_disconnect;
87
88/* Alias structure */
89struct ng_ksocket_alias {
90	const char	*name;
91	const int	value;
92	const int	family;
93};
94
95/* Protocol family aliases */
96static const struct ng_ksocket_alias ng_ksocket_families[] = {
97	{ "local",	PF_LOCAL	},
98	{ "inet",	PF_INET		},
99	{ "inet6",	PF_INET6	},
100	{ "atalk",	PF_APPLETALK	},
101	{ "ipx",	PF_IPX		},
102	{ "atm",	PF_ATM		},
103	{ NULL,		-1		},
104};
105
106/* Socket type aliases */
107static const struct ng_ksocket_alias ng_ksocket_types[] = {
108	{ "stream",	SOCK_STREAM	},
109	{ "dgram",	SOCK_DGRAM	},
110	{ "raw",	SOCK_RAW	},
111	{ "rdm",	SOCK_RDM	},
112	{ "seqpacket",	SOCK_SEQPACKET	},
113	{ NULL,		-1		},
114};
115
116/* Protocol aliases */
117static const struct ng_ksocket_alias ng_ksocket_protos[] = {
118	{ "ip",		IPPROTO_IP,		PF_INET		},
119	{ "raw",	IPPROTO_IP,		PF_INET		},
120	{ "icmp",	IPPROTO_ICMP,		PF_INET		},
121	{ "igmp",	IPPROTO_IGMP,		PF_INET		},
122	{ "tcp",	IPPROTO_TCP,		PF_INET		},
123	{ "udp",	IPPROTO_UDP,		PF_INET		},
124	{ "gre",	IPPROTO_GRE,		PF_INET		},
125	{ "esp",	IPPROTO_ESP,		PF_INET		},
126	{ "ah",		IPPROTO_AH,		PF_INET		},
127	{ "swipe",	IPPROTO_SWIPE,		PF_INET		},
128	{ "encap",	IPPROTO_ENCAP,		PF_INET		},
129	{ "divert",	IPPROTO_DIVERT,		PF_INET		},
130	{ "ddp",	ATPROTO_DDP,		PF_APPLETALK	},
131	{ "aarp",	ATPROTO_AARP,		PF_APPLETALK	},
132	{ NULL,		-1					},
133};
134
135/* Helper functions */
136static void	ng_ksocket_incoming(struct socket *so, void *arg, int waitflag);
137static int	ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
138			const char *s, int family);
139
140/************************************************************************
141			STRUCT SOCKADDR PARSE TYPE
142 ************************************************************************/
143
144/* Get the length of the data portion of a generic struct sockaddr */
145static int
146ng_parse_generic_sockdata_getLength(const struct ng_parse_type *type,
147	const u_char *start, const u_char *buf)
148{
149	const struct sockaddr *sa;
150
151	sa = (const struct sockaddr *)(buf - SADATA_OFFSET);
152	return (sa->sa_len < SADATA_OFFSET) ? 0 : sa->sa_len - SADATA_OFFSET;
153}
154
155/* Type for the variable length data portion of a generic struct sockaddr */
156static const struct ng_parse_type ng_ksocket_generic_sockdata_type = {
157	&ng_parse_bytearray_type,
158	&ng_parse_generic_sockdata_getLength
159};
160
161/* Type for a generic struct sockaddr */
162static const struct ng_parse_struct_info ng_parse_generic_sockaddr_type_info = {
163	{
164	  { "len",	&ng_parse_uint8_type			},
165	  { "family",	&ng_parse_uint8_type			},
166	  { "data",	&ng_ksocket_generic_sockdata_type	},
167	  { NULL }
168	}
169};
170static const struct ng_parse_type ng_ksocket_generic_sockaddr_type = {
171	&ng_parse_struct_type,
172	&ng_parse_generic_sockaddr_type_info
173};
174
175/* Convert a struct sockaddr from ASCII to binary.  If its a protocol
176   family that we specially handle, do that, otherwise defer to the
177   generic parse type ng_ksocket_generic_sockaddr_type. */
178static int
179ng_ksocket_sockaddr_parse(const struct ng_parse_type *type,
180	const char *s, int *off, const u_char *const start,
181	u_char *const buf, int *buflen)
182{
183	struct sockaddr *const sa = (struct sockaddr *)buf;
184	enum ng_parse_token tok;
185	char fambuf[32];
186	int family, len;
187	char *t;
188
189	/* If next token is a left curly brace, use generic parse type */
190	if ((tok = ng_parse_get_token(s, off, &len)) == T_LBRACE) {
191		return (*ng_ksocket_generic_sockaddr_type.supertype->parse)
192		    (&ng_ksocket_generic_sockaddr_type,
193		    s, off, start, buf, buflen);
194	}
195
196	/* Get socket address family followed by a slash */
197	while (isspace(s[*off]))
198		(*off)++;
199	if ((t = index(s + *off, '/')) == NULL)
200		return (EINVAL);
201	if ((len = t - (s + *off)) > sizeof(fambuf) - 1)
202		return (EINVAL);
203	strncpy(fambuf, s + *off, len);
204	fambuf[len] = '\0';
205	*off += len + 1;
206	if ((family = ng_ksocket_parse(ng_ksocket_families, fambuf, 0)) == -1)
207		return (EINVAL);
208
209	/* Set family */
210	if (*buflen < SADATA_OFFSET)
211		return (ERANGE);
212	sa->sa_family = family;
213
214	/* Set family-specific data and length */
215	switch (sa->sa_family) {
216	case PF_LOCAL:		/* Get pathname */
217	    {
218		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
219		struct sockaddr_un *const sun = (struct sockaddr_un *)sa;
220		int toklen, pathlen;
221		char *path;
222
223		if ((path = ng_get_string_token(s, off, &toklen, NULL)) == NULL)
224			return (EINVAL);
225		pathlen = strlen(path);
226		if (pathlen > SOCK_MAXADDRLEN) {
227			FREE(path, M_NETGRAPH);
228			return (E2BIG);
229		}
230		if (*buflen < pathoff + pathlen) {
231			FREE(path, M_NETGRAPH);
232			return (ERANGE);
233		}
234		*off += toklen;
235		bcopy(path, sun->sun_path, pathlen);
236		sun->sun_len = pathoff + pathlen;
237		FREE(path, M_NETGRAPH);
238		break;
239	    }
240
241	case PF_INET:		/* Get an IP address with optional port */
242	    {
243		struct sockaddr_in *const sin = (struct sockaddr_in *)sa;
244		int i;
245
246		/* Parse this: <ipaddress>[:port] */
247		for (i = 0; i < 4; i++) {
248			u_long val;
249			char *eptr;
250
251			val = strtoul(s + *off, &eptr, 10);
252			if (val > 0xff || eptr == s + *off)
253				return (EINVAL);
254			*off += (eptr - (s + *off));
255			((u_char *)&sin->sin_addr)[i] = (u_char)val;
256			if (i < 3) {
257				if (s[*off] != '.')
258					return (EINVAL);
259				(*off)++;
260			} else if (s[*off] == ':') {
261				(*off)++;
262				val = strtoul(s + *off, &eptr, 10);
263				if (val > 0xffff || eptr == s + *off)
264					return (EINVAL);
265				*off += (eptr - (s + *off));
266				sin->sin_port = htons(val);
267			} else
268				sin->sin_port = 0;
269		}
270		bzero(&sin->sin_zero, sizeof(sin->sin_zero));
271		sin->sin_len = sizeof(*sin);
272		break;
273	    }
274
275#if 0
276	case PF_APPLETALK:	/* XXX implement these someday */
277	case PF_INET6:
278	case PF_IPX:
279#endif
280
281	default:
282		return (EINVAL);
283	}
284
285	/* Done */
286	*buflen = sa->sa_len;
287	return (0);
288}
289
290/* Convert a struct sockaddr from binary to ASCII */
291static int
292ng_ksocket_sockaddr_unparse(const struct ng_parse_type *type,
293	const u_char *data, int *off, char *cbuf, int cbuflen)
294{
295	const struct sockaddr *sa = (const struct sockaddr *)(data + *off);
296	int slen = 0;
297
298	/* Output socket address, either in special or generic format */
299	switch (sa->sa_family) {
300	case PF_LOCAL:
301	    {
302		const int pathoff = OFFSETOF(struct sockaddr_un, sun_path);
303		const struct sockaddr_un *sun = (const struct sockaddr_un *)sa;
304		const int pathlen = sun->sun_len - pathoff;
305		char pathbuf[SOCK_MAXADDRLEN + 1];
306		char *pathtoken;
307
308		bcopy(sun->sun_path, pathbuf, pathlen);
309		if ((pathtoken = ng_encode_string(pathbuf, pathlen)) == NULL)
310			return (ENOMEM);
311		slen += snprintf(cbuf, cbuflen, "local/%s", pathtoken);
312		FREE(pathtoken, M_NETGRAPH);
313		if (slen >= cbuflen)
314			return (ERANGE);
315		*off += sun->sun_len;
316		return (0);
317	    }
318
319	case PF_INET:
320	    {
321		const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
322
323		slen += snprintf(cbuf, cbuflen, "inet/%d.%d.%d.%d",
324		  ((const u_char *)&sin->sin_addr)[0],
325		  ((const u_char *)&sin->sin_addr)[1],
326		  ((const u_char *)&sin->sin_addr)[2],
327		  ((const u_char *)&sin->sin_addr)[3]);
328		if (sin->sin_port != 0) {
329			slen += snprintf(cbuf + strlen(cbuf),
330			    cbuflen - strlen(cbuf), ":%d",
331			    (u_int)ntohs(sin->sin_port));
332		}
333		if (slen >= cbuflen)
334			return (ERANGE);
335		*off += sizeof(*sin);
336		return(0);
337	    }
338
339#if 0
340	case PF_APPLETALK:	/* XXX implement these someday */
341	case PF_INET6:
342	case PF_IPX:
343#endif
344
345	default:
346		return (*ng_ksocket_generic_sockaddr_type.supertype->unparse)
347		    (&ng_ksocket_generic_sockaddr_type,
348		    data, off, cbuf, cbuflen);
349	}
350}
351
352/* Parse type for struct sockaddr */
353static const struct ng_parse_type ng_ksocket_sockaddr_type = {
354	NULL,
355	NULL,
356	NULL,
357	&ng_ksocket_sockaddr_parse,
358	&ng_ksocket_sockaddr_unparse,
359	NULL		/* no such thing as a default struct sockaddr */
360};
361
362/************************************************************************
363		STRUCT NG_KSOCKET_SOCKOPT PARSE TYPE
364 ************************************************************************/
365
366/* Get length of the struct ng_ksocket_sockopt value field, which is the
367   just the excess of the message argument portion over the length of
368   the struct ng_ksocket_sockopt. */
369static int
370ng_parse_sockoptval_getLength(const struct ng_parse_type *type,
371	const u_char *start, const u_char *buf)
372{
373	static const int offset = OFFSETOF(struct ng_ksocket_sockopt, value);
374	const struct ng_ksocket_sockopt *sopt;
375	const struct ng_mesg *msg;
376
377	sopt = (const struct ng_ksocket_sockopt *)(buf - offset);
378	msg = (const struct ng_mesg *)((const u_char *)sopt - sizeof(*msg));
379	return msg->header.arglen - sizeof(*sopt);
380}
381
382/* Parse type for the option value part of a struct ng_ksocket_sockopt
383   XXX Eventually, we should handle the different socket options specially.
384   XXX This would avoid byte order problems, eg an integer value of 1 is
385   XXX going to be "[1]" for little endian or "[3=1]" for big endian. */
386static const struct ng_parse_type ng_ksocket_sockoptval_type = {
387	&ng_parse_bytearray_type,
388	&ng_parse_sockoptval_getLength
389};
390
391/* Parse type for struct ng_ksocket_sockopt */
392static const struct ng_parse_struct_info ng_ksocket_sockopt_type_info
393	= NG_KSOCKET_SOCKOPT_INFO(&ng_ksocket_sockoptval_type);
394static const struct ng_parse_type ng_ksocket_sockopt_type = {
395	&ng_parse_struct_type,
396	&ng_ksocket_sockopt_type_info,
397};
398
399/* List of commands and how to convert arguments to/from ASCII */
400static const struct ng_cmdlist ng_ksocket_cmds[] = {
401	{
402	  NGM_KSOCKET_COOKIE,
403	  NGM_KSOCKET_BIND,
404	  "bind",
405	  &ng_ksocket_sockaddr_type,
406	  NULL
407	},
408	{
409	  NGM_KSOCKET_COOKIE,
410	  NGM_KSOCKET_LISTEN,
411	  "listen",
412	  &ng_parse_int32_type,
413	  NULL
414	},
415	{
416	  NGM_KSOCKET_COOKIE,
417	  NGM_KSOCKET_ACCEPT,
418	  "accept",
419	  NULL,
420	  &ng_ksocket_sockaddr_type
421	},
422	{
423	  NGM_KSOCKET_COOKIE,
424	  NGM_KSOCKET_CONNECT,
425	  "connect",
426	  &ng_ksocket_sockaddr_type,
427	  NULL
428	},
429	{
430	  NGM_KSOCKET_COOKIE,
431	  NGM_KSOCKET_GETNAME,
432	  "getname",
433	  NULL,
434	  &ng_ksocket_sockaddr_type
435	},
436	{
437	  NGM_KSOCKET_COOKIE,
438	  NGM_KSOCKET_GETPEERNAME,
439	  "getpeername",
440	  NULL,
441	  &ng_ksocket_sockaddr_type
442	},
443	{
444	  NGM_KSOCKET_COOKIE,
445	  NGM_KSOCKET_SETOPT,
446	  "setopt",
447	  &ng_ksocket_sockopt_type,
448	  NULL
449	},
450	{
451	  NGM_KSOCKET_COOKIE,
452	  NGM_KSOCKET_GETOPT,
453	  "getopt",
454	  &ng_ksocket_sockopt_type,
455	  &ng_ksocket_sockopt_type
456	},
457	{ 0 }
458};
459
460/* Node type descriptor */
461static struct ng_type ng_ksocket_typestruct = {
462	NG_ABI_VERSION,
463	NG_KSOCKET_NODE_TYPE,
464	NULL,
465	ng_ksocket_constructor,
466	ng_ksocket_rcvmsg,
467	ng_ksocket_shutdown,
468	ng_ksocket_newhook,
469	NULL,
470	NULL,
471	ng_ksocket_rcvdata,
472	ng_ksocket_disconnect,
473	ng_ksocket_cmds
474};
475NETGRAPH_INIT(ksocket, &ng_ksocket_typestruct);
476
477#define ERROUT(x)	do { error = (x); goto done; } while (0)
478
479/************************************************************************
480			NETGRAPH NODE STUFF
481 ************************************************************************/
482
483/*
484 * Node type constructor
485 */
486static int
487ng_ksocket_constructor(node_p node)
488{
489	priv_p priv;
490
491	/* Allocate private structure */
492	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
493	if (priv == NULL)
494		return (ENOMEM);
495
496	node->private = priv;
497
498	/* Done */
499	return (0);
500}
501
502/*
503 * Give our OK for a hook to be added. The hook name is of the
504 * form "<family>:<type>:<proto>" where the three components may
505 * be decimal numbers or else aliases from the above lists.
506 *
507 * Connecting a hook amounts to opening the socket.  Disconnecting
508 * the hook closes the socket and destroys the node as well.
509 */
510static int
511ng_ksocket_newhook(node_p node, hook_p hook, const char *name0)
512{
513	struct proc *p = curproc ? curproc : &proc0;	/* XXX broken */
514	const priv_p priv = node->private;
515	char *s1, *s2, name[NG_HOOKLEN+1];
516	int family, type, protocol, error;
517
518	/* Check if we're already connected */
519	if (priv->hook != NULL)
520		return (EISCONN);
521
522	/* Extract family, type, and protocol from hook name */
523	snprintf(name, sizeof(name), "%s", name0);
524	s1 = name;
525	if ((s2 = index(s1, '/')) == NULL)
526		return (EINVAL);
527	*s2++ = '\0';
528	if ((family = ng_ksocket_parse(ng_ksocket_families, s1, 0)) == -1)
529		return (EINVAL);
530	s1 = s2;
531	if ((s2 = index(s1, '/')) == NULL)
532		return (EINVAL);
533	*s2++ = '\0';
534	if ((type = ng_ksocket_parse(ng_ksocket_types, s1, 0)) == -1)
535		return (EINVAL);
536	s1 = s2;
537	if ((protocol = ng_ksocket_parse(ng_ksocket_protos, s1, family)) == -1)
538		return (EINVAL);
539
540	/* Create the socket */
541	if ((error = socreate(family, &priv->so, type, protocol, p)) != 0)
542		return (error);
543
544	/* XXX call soreserve() ? */
545
546	/* Add our hook for incoming data */
547	priv->so->so_upcallarg = (caddr_t)node;
548	priv->so->so_upcall = ng_ksocket_incoming;
549	priv->so->so_rcv.sb_flags |= SB_UPCALL;
550
551	/* OK */
552	priv->hook = hook;
553	return (0);
554}
555
556/*
557 * Receive a control message
558 */
559static int
560ng_ksocket_rcvmsg(node_p node, item_p item, hook_p lasthook)
561{
562	struct proc *p = curproc ? curproc : &proc0;	/* XXX broken */
563	const priv_p priv = node->private;
564	struct socket *const so = priv->so;
565	struct ng_mesg *resp = NULL;
566	int error = 0;
567	struct ng_mesg *msg;
568
569	NGI_GET_MSG(item, msg);
570	switch (msg->header.typecookie) {
571	case NGM_KSOCKET_COOKIE:
572		switch (msg->header.cmd) {
573		case NGM_KSOCKET_BIND:
574		    {
575			struct sockaddr *const sa
576			    = (struct sockaddr *)msg->data;
577
578			/* Sanity check */
579			if (msg->header.arglen < SADATA_OFFSET
580			    || msg->header.arglen < sa->sa_len)
581				ERROUT(EINVAL);
582			if (so == NULL)
583				ERROUT(ENXIO);
584
585			/* Bind */
586			error = sobind(so, sa, p);
587			break;
588		    }
589		case NGM_KSOCKET_LISTEN:
590		    {
591			/* Sanity check */
592			if (msg->header.arglen != sizeof(int))
593				ERROUT(EINVAL);
594			if (so == NULL)
595				ERROUT(ENXIO);
596
597			/* Listen */
598			if ((error = solisten(so, *((int *)msg->data), p)) != 0)
599				break;
600
601			/* Notify sender when we get a connection attempt */
602				/* XXX implement me */
603			error = ENODEV;
604			break;
605		    }
606
607		case NGM_KSOCKET_ACCEPT:
608		    {
609			/* Sanity check */
610			if (msg->header.arglen != 0)
611				ERROUT(EINVAL);
612			if (so == NULL)
613				ERROUT(ENXIO);
614
615			/* Accept on the socket in a non-blocking way */
616			/* Create a new ksocket node for the new connection */
617			/* Return a response with the peer's sockaddr and
618			   the absolute name of the newly created node */
619
620				/* XXX implement me */
621
622			error = ENODEV;
623			break;
624		    }
625
626		case NGM_KSOCKET_CONNECT:
627		    {
628			struct sockaddr *const sa
629			    = (struct sockaddr *)msg->data;
630
631			/* Sanity check */
632			if (msg->header.arglen < SADATA_OFFSET
633			    || msg->header.arglen < sa->sa_len)
634				ERROUT(EINVAL);
635			if (so == NULL)
636				ERROUT(ENXIO);
637
638			/* Do connect */
639			if ((so->so_state & SS_ISCONNECTING) != 0)
640				ERROUT(EALREADY);
641			if ((error = soconnect(so, sa, p)) != 0) {
642				so->so_state &= ~SS_ISCONNECTING;
643				ERROUT(error);
644			}
645			if ((so->so_state & SS_ISCONNECTING) != 0)
646				/* Notify sender when we connect */
647				/* XXX implement me */
648				ERROUT(EINPROGRESS);
649			break;
650		    }
651
652		case NGM_KSOCKET_GETNAME:
653		case NGM_KSOCKET_GETPEERNAME:
654		    {
655			int (*func)(struct socket *so, struct sockaddr **nam);
656			struct sockaddr *sa = NULL;
657			int len;
658
659			/* Sanity check */
660			if (msg->header.arglen != 0)
661				ERROUT(EINVAL);
662			if (so == NULL)
663				ERROUT(ENXIO);
664
665			/* Get function */
666			if (msg->header.cmd == NGM_KSOCKET_GETPEERNAME) {
667				if ((so->so_state
668				    & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0)
669					ERROUT(ENOTCONN);
670				func = so->so_proto->pr_usrreqs->pru_peeraddr;
671			} else
672				func = so->so_proto->pr_usrreqs->pru_sockaddr;
673
674			/* Get local or peer address */
675			if ((error = (*func)(so, &sa)) != 0)
676				goto bail;
677			len = (sa == NULL) ? 0 : sa->sa_len;
678
679			/* Send it back in a response */
680			NG_MKRESPONSE(resp, msg, len, M_NOWAIT);
681			if (resp == NULL) {
682				error = ENOMEM;
683				goto bail;
684			}
685			bcopy(sa, resp->data, len);
686
687		bail:
688			/* Cleanup */
689			if (sa != NULL)
690				FREE(sa, M_SONAME);
691			break;
692		    }
693
694		case NGM_KSOCKET_GETOPT:
695		    {
696			struct ng_ksocket_sockopt *ksopt =
697			    (struct ng_ksocket_sockopt *)msg->data;
698			struct sockopt sopt;
699
700			/* Sanity check */
701			if (msg->header.arglen != sizeof(*ksopt))
702				ERROUT(EINVAL);
703			if (so == NULL)
704				ERROUT(ENXIO);
705
706			/* Get response with room for option value */
707			NG_MKRESPONSE(resp, msg, sizeof(*ksopt)
708			    + NG_KSOCKET_MAX_OPTLEN, M_NOWAIT);
709			if (resp == NULL)
710				ERROUT(ENOMEM);
711
712			/* Get socket option, and put value in the response */
713			sopt.sopt_dir = SOPT_GET;
714			sopt.sopt_level = ksopt->level;
715			sopt.sopt_name = ksopt->name;
716			sopt.sopt_p = p;
717			sopt.sopt_valsize = NG_KSOCKET_MAX_OPTLEN;
718			ksopt = (struct ng_ksocket_sockopt *)resp->data;
719			sopt.sopt_val = ksopt->value;
720			if ((error = sogetopt(so, &sopt)) != 0) {
721				NG_FREE_MSG(resp);
722				break;
723			}
724
725			/* Set actual value length */
726			resp->header.arglen = sizeof(*ksopt)
727			    + sopt.sopt_valsize;
728			break;
729		    }
730
731		case NGM_KSOCKET_SETOPT:
732		    {
733			struct ng_ksocket_sockopt *const ksopt =
734			    (struct ng_ksocket_sockopt *)msg->data;
735			const int valsize = msg->header.arglen - sizeof(*ksopt);
736			struct sockopt sopt;
737
738			/* Sanity check */
739			if (valsize < 0)
740				ERROUT(EINVAL);
741			if (so == NULL)
742				ERROUT(ENXIO);
743
744			/* Set socket option */
745			sopt.sopt_dir = SOPT_SET;
746			sopt.sopt_level = ksopt->level;
747			sopt.sopt_name = ksopt->name;
748			sopt.sopt_val = ksopt->value;
749			sopt.sopt_valsize = valsize;
750			sopt.sopt_p = p;
751			error = sosetopt(so, &sopt);
752			break;
753		    }
754
755		default:
756			error = EINVAL;
757			break;
758		}
759		break;
760	default:
761		error = EINVAL;
762		break;
763	}
764done:
765	NG_RESPOND_MSG(error, node, item, resp);
766	NG_FREE_MSG(msg);
767	return (error);
768}
769
770/*
771 * Receive incoming data on our hook.  Send it out the socket.
772 */
773static int
774ng_ksocket_rcvdata(hook_p hook, item_p item)
775{
776	struct proc *p = curproc ? curproc : &proc0;	/* XXX broken */
777	const node_p node = hook->node;
778	const priv_p priv = node->private;
779	struct socket *const so = priv->so;
780	int error;
781	struct mbuf *m;
782
783	NGI_GET_M(item, m);
784	NG_FREE_ITEM(item);
785	error = (*so->so_proto->pr_usrreqs->pru_sosend)(so, 0, 0, m, 0, 0, p);
786	return (error);
787}
788
789/*
790 * Destroy node
791 */
792static int
793ng_ksocket_shutdown(node_p node)
794{
795	const priv_p priv = node->private;
796
797	/* Close our socket (if any) */
798	if (priv->so != NULL) {
799
800		priv->so->so_upcall = NULL;
801		priv->so->so_rcv.sb_flags &= ~SB_UPCALL;
802		soclose(priv->so);
803		priv->so = NULL;
804	}
805
806	/* Take down netgraph node */
807	node->flags |= NG_INVALID;
808	bzero(priv, sizeof(*priv));
809	FREE(priv, M_NETGRAPH);
810	node->private = NULL;
811	ng_unref(node);		/* let the node escape */
812	return (0);
813}
814
815/*
816 * Hook disconnection
817 */
818static int
819ng_ksocket_disconnect(hook_p hook)
820{
821	KASSERT(hook->node->numhooks == 0,
822	    ("%s: numhooks=%d?", __FUNCTION__, hook->node->numhooks));
823	if ((hook->node->flags & NG_INVALID) == 0)
824		ng_rmnode_self(hook->node);
825	return (0);
826}
827
828/************************************************************************
829			HELPER STUFF
830 ************************************************************************/
831
832/*
833 * When incoming data is appended to the socket, we get notified here.
834 */
835static void
836ng_ksocket_incoming(struct socket *so, void *arg, int waitflag)
837{
838	const node_p node = arg;
839	const priv_p priv = node->private;
840	struct mbuf *m;
841	struct uio auio;
842	int s, flags, error;
843
844	s = splnet();
845
846	/* Sanity check */
847	if ((node->flags & NG_INVALID) != 0) {
848		splx(s);
849		return;
850	}
851	KASSERT(so == priv->so, ("%s: wrong socket", __FUNCTION__));
852	KASSERT(priv->hook != NULL, ("%s: no hook", __FUNCTION__));
853
854	/* Read and forward available mbuf's */
855	auio.uio_procp = NULL;
856	auio.uio_resid = 1000000000;
857	flags = MSG_DONTWAIT;
858	do {
859		if ((error = (*so->so_proto->pr_usrreqs->pru_soreceive)
860		      (so, (struct sockaddr **)0, &auio, &m,
861		      (struct mbuf **)0, &flags)) == 0
862		    && m != NULL) {
863			struct mbuf *n;
864
865			/* Don't trust the various socket layers to get the
866			   packet header and length correct (eg. kern/15175) */
867			for (n = m, m->m_pkthdr.len = 0; n; n = n->m_next)
868				m->m_pkthdr.len += n->m_len;
869			NG_SEND_DATA_ONLY(error, priv->hook, m);
870		}
871	} while (error == 0 && m != NULL);
872	splx(s);
873}
874
875/*
876 * Parse out either an integer value or an alias.
877 */
878static int
879ng_ksocket_parse(const struct ng_ksocket_alias *aliases,
880	const char *s, int family)
881{
882	int k, val;
883	char *eptr;
884
885	/* Try aliases */
886	for (k = 0; aliases[k].name != NULL; k++) {
887		if (strcmp(s, aliases[k].name) == 0
888		    && aliases[k].family == family)
889			return aliases[k].value;
890	}
891
892	/* Try parsing as a number */
893	val = (int)strtoul(s, &eptr, 10);
894	if (val < 0 || *eptr != '\0')
895		return (-1);
896	return (val);
897}
898
899