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