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