Merge from vendor branch CVS:
[dragonfly.git] / sys / netgraph / netgraph / ng_base.c
1
2 /*
3  * ng_base.c
4  *
5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
6  * All rights reserved.
7  * 
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  * 
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Authors: Julian Elischer <julian@freebsd.org>
38  *          Archie Cobbs <archie@freebsd.org>
39  *
40  * $FreeBSD: src/sys/netgraph/ng_base.c,v 1.11.2.17 2002/07/02 23:44:02 archie Exp $
41  * $DragonFly: src/sys/netgraph/netgraph/ng_base.c,v 1.15 2005/06/02 22:11:46 swildner Exp $
42  * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
43  */
44
45 /*
46  * This file implements the base netgraph code.
47  */
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/errno.h>
52 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/syslog.h>
55 #include <sys/linker.h>
56 #include <sys/queue.h>
57 #include <sys/mbuf.h>
58 #include <sys/ctype.h>
59 #include <sys/sysctl.h>
60 #include <machine/limits.h>
61
62 #include <sys/thread2.h>
63 #include <sys/msgport2.h>
64
65 #include <net/netisr.h>
66
67 #include <netgraph/ng_message.h>
68 #include <netgraph/netgraph.h>
69 #include <netgraph/ng_parse.h>
70
71 /* List of all nodes */
72 static LIST_HEAD(, ng_node) nodelist;
73
74 /* List of installed types */
75 static LIST_HEAD(, ng_type) typelist;
76
77 /* Hash releted definitions */
78 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
79 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
80 /* Don't nead to initialise them because it's a LIST */
81
82 /* Internal functions */
83 static int      ng_add_hook(node_p node, const char *name, hook_p * hookp);
84 static int      ng_connect(hook_p hook1, hook_p hook2);
85 static void     ng_disconnect_hook(hook_p hook);
86 static int      ng_generic_msg(node_p here, struct ng_mesg *msg,
87                         const char *retaddr, struct ng_mesg ** resp);
88 static ng_ID_t  ng_decodeidname(const char *name);
89 static int      ngb_mod_event(module_t mod, int event, void *data);
90 static int      ngintr(struct netmsg *);
91
92 /* Our own netgraph malloc type */
93 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
94
95 /* Set this to Debugger("X") to catch all errors as they occur */
96 #ifndef TRAP_ERROR
97 #define TRAP_ERROR
98 #endif
99
100 static  ng_ID_t nextID = 1;
101
102 #ifdef INVARIANTS
103 #define CHECK_DATA_MBUF(m)      do {                                    \
104                 struct mbuf *n;                                         \
105                 int total;                                              \
106                                                                         \
107                 if (((m)->m_flags & M_PKTHDR) == 0)                     \
108                         panic("%s: !PKTHDR", __func__);         \
109                 for (total = 0, n = (m); n != NULL; n = n->m_next)      \
110                         total += n->m_len;                              \
111                 if ((m)->m_pkthdr.len != total) {                       \
112                         panic("%s: %d != %d",                           \
113                             __func__, (m)->m_pkthdr.len, total);        \
114                 }                                                       \
115         } while (0)
116 #else
117 #define CHECK_DATA_MBUF(m)
118 #endif
119
120
121 /************************************************************************
122         Parse type definitions for generic messages
123 ************************************************************************/
124
125 /* Handy structure parse type defining macro */
126 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)                          \
127 static const struct ng_parse_struct_field                               \
128         ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args;  \
129 static const struct ng_parse_type ng_generic_ ## lo ## _type = {        \
130         &ng_parse_struct_type,                                          \
131         &ng_ ## lo ## _type_fields                                      \
132 }
133
134 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
135 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
136 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
137 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
138 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
139 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
140 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
141
142 /* Get length of an array when the length is stored as a 32 bit
143    value immediately preceeding the array -- as with struct namelist
144    and struct typelist. */
145 static int
146 ng_generic_list_getLength(const struct ng_parse_type *type,
147         const u_char *start, const u_char *buf)
148 {
149         return *((const u_int32_t *)(buf - 4));
150 }
151
152 /* Get length of the array of struct linkinfo inside a struct hooklist */
153 static int
154 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
155         const u_char *start, const u_char *buf)
156 {
157         const struct hooklist *hl = (const struct hooklist *)start;
158
159         return hl->nodeinfo.hooks;
160 }
161
162 /* Array type for a variable length array of struct namelist */
163 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
164         &ng_generic_nodeinfo_type,
165         &ng_generic_list_getLength
166 };
167 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
168         &ng_parse_array_type,
169         &ng_nodeinfoarray_type_info
170 };
171
172 /* Array type for a variable length array of struct typelist */
173 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
174         &ng_generic_typeinfo_type,
175         &ng_generic_list_getLength
176 };
177 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
178         &ng_parse_array_type,
179         &ng_typeinfoarray_type_info
180 };
181
182 /* Array type for array of struct linkinfo in struct hooklist */
183 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
184         &ng_generic_linkinfo_type,
185         &ng_generic_linkinfo_getLength
186 };
187 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
188         &ng_parse_array_type,
189         &ng_generic_linkinfo_array_type_info
190 };
191
192 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
193 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
194         (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
195 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
196         (&ng_generic_nodeinfoarray_type));
197
198 /* List of commands and how to convert arguments to/from ASCII */
199 static const struct ng_cmdlist ng_generic_cmds[] = {
200         {
201           NGM_GENERIC_COOKIE,
202           NGM_SHUTDOWN,
203           "shutdown",
204           NULL,
205           NULL
206         },
207         {
208           NGM_GENERIC_COOKIE,
209           NGM_MKPEER,
210           "mkpeer",
211           &ng_generic_mkpeer_type,
212           NULL
213         },
214         {
215           NGM_GENERIC_COOKIE,
216           NGM_CONNECT,
217           "connect",
218           &ng_generic_connect_type,
219           NULL
220         },
221         {
222           NGM_GENERIC_COOKIE,
223           NGM_NAME,
224           "name",
225           &ng_generic_name_type,
226           NULL
227         },
228         {
229           NGM_GENERIC_COOKIE,
230           NGM_RMHOOK,
231           "rmhook",
232           &ng_generic_rmhook_type,
233           NULL
234         },
235         {
236           NGM_GENERIC_COOKIE,
237           NGM_NODEINFO,
238           "nodeinfo",
239           NULL,
240           &ng_generic_nodeinfo_type
241         },
242         {
243           NGM_GENERIC_COOKIE,
244           NGM_LISTHOOKS,
245           "listhooks",
246           NULL,
247           &ng_generic_hooklist_type
248         },
249         {
250           NGM_GENERIC_COOKIE,
251           NGM_LISTNAMES,
252           "listnames",
253           NULL,
254           &ng_generic_listnodes_type    /* same as NGM_LISTNODES */
255         },
256         {
257           NGM_GENERIC_COOKIE,
258           NGM_LISTNODES,
259           "listnodes",
260           NULL,
261           &ng_generic_listnodes_type
262         },
263         {
264           NGM_GENERIC_COOKIE,
265           NGM_LISTTYPES,
266           "listtypes",
267           NULL,
268           &ng_generic_typeinfo_type
269         },
270         {
271           NGM_GENERIC_COOKIE,
272           NGM_TEXT_CONFIG,
273           "textconfig",
274           NULL,
275           &ng_parse_string_type
276         },
277         {
278           NGM_GENERIC_COOKIE,
279           NGM_TEXT_STATUS,
280           "textstatus",
281           NULL,
282           &ng_parse_string_type
283         },
284         {
285           NGM_GENERIC_COOKIE,
286           NGM_ASCII2BINARY,
287           "ascii2binary",
288           &ng_parse_ng_mesg_type,
289           &ng_parse_ng_mesg_type
290         },
291         {
292           NGM_GENERIC_COOKIE,
293           NGM_BINARY2ASCII,
294           "binary2ascii",
295           &ng_parse_ng_mesg_type,
296           &ng_parse_ng_mesg_type
297         },
298         { 0 }
299 };
300
301 /************************************************************************
302                         Node routines
303 ************************************************************************/
304
305 /*
306  * Instantiate a node of the requested type
307  */
308 int
309 ng_make_node(const char *typename, node_p *nodepp)
310 {
311         struct ng_type *type;
312
313         /* Check that the type makes sense */
314         if (typename == NULL) {
315                 TRAP_ERROR;
316                 return (EINVAL);
317         }
318
319         /* Locate the node type */
320         if ((type = ng_findtype(typename)) == NULL) {
321                 char *path, filename[NG_TYPELEN + 4];
322                 linker_file_t lf;
323                 int error;
324
325                 /* Not found, try to load it as a loadable module */
326                 snprintf(filename, sizeof(filename), "ng_%s.ko", typename);
327                 if ((path = linker_search_path(filename)) == NULL)
328                         return (ENXIO);
329                 error = linker_load_file(path, &lf);
330                 FREE(path, M_LINKER);
331                 if (error != 0)
332                         return (error);
333                 lf->userrefs++;         /* pretend loaded by the syscall */
334
335                 /* Try again, as now the type should have linked itself in */
336                 if ((type = ng_findtype(typename)) == NULL)
337                         return (ENXIO);
338         }
339
340         /* Call the constructor */
341         if (type->constructor != NULL)
342                 return ((*type->constructor)(nodepp));
343         else
344                 return (ng_make_node_common(type, nodepp));
345 }
346
347 /*
348  * Generic node creation. Called by node constructors.
349  * The returned node has a reference count of 1.
350  */
351 int
352 ng_make_node_common(struct ng_type *type, node_p *nodepp)
353 {
354         node_p node;
355
356         /* Require the node type to have been already installed */
357         if (ng_findtype(type->name) == NULL) {
358                 TRAP_ERROR;
359                 return (EINVAL);
360         }
361
362         /* Make a node and try attach it to the type */
363         MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT);
364         if (node == NULL) {
365                 TRAP_ERROR;
366                 return (ENOMEM);
367         }
368         bzero(node, sizeof(*node));
369         node->type = type;
370         node->refs++;                           /* note reference */
371         type->refs++;
372
373         /* Link us into the node linked list */
374         LIST_INSERT_HEAD(&nodelist, node, nodes);
375
376         /* Initialize hook list for new node */
377         LIST_INIT(&node->hooks);
378
379         /* get an ID and put us in the hash chain */
380         node->ID = nextID++; /* 137 per second for 1 year before wrap */
381         LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
382
383         /* Done */
384         *nodepp = node;
385         return (0);
386 }
387
388 /*
389  * Forceably start the shutdown process on a node. Either call
390  * it's shutdown method, or do the default shutdown if there is
391  * no type-specific method.
392  *
393  * Persistent nodes must have a type-specific method which
394  * resets the NG_INVALID flag.
395  */
396 void
397 ng_rmnode(node_p node)
398 {
399         /* Check if it's already shutting down */
400         if ((node->flags & NG_INVALID) != 0)
401                 return;
402
403         /* Add an extra reference so it doesn't go away during this */
404         node->refs++;
405
406         /* Mark it invalid so any newcomers know not to try use it */
407         node->flags |= NG_INVALID;
408
409         /* Ask the type if it has anything to do in this case */
410         if (node->type && node->type->shutdown)
411                 (*node->type->shutdown)(node);
412         else {                          /* do the default thing */
413                 ng_unname(node);
414                 ng_cutlinks(node);
415                 ng_unref(node);
416         }
417
418         /* Remove extra reference, possibly the last */
419         ng_unref(node);
420 }
421
422 /*
423  * Called by the destructor to remove any STANDARD external references
424  */
425 void
426 ng_cutlinks(node_p node)
427 {
428         hook_p  hook;
429
430         /* Make sure that this is set to stop infinite loops */
431         node->flags |= NG_INVALID;
432
433         /* If we have sleepers, wake them up; they'll see NG_INVALID */
434         if (node->sleepers)
435                 wakeup(node);
436
437         /* Notify all remaining connected nodes to disconnect */
438         while ((hook = LIST_FIRST(&node->hooks)) != NULL)
439                 ng_destroy_hook(hook);
440 }
441
442 /*
443  * Remove a reference to the node, possibly the last
444  */
445 void
446 ng_unref(node_p node)
447 {
448         crit_enter();
449         if (--node->refs <= 0) {
450                 node->type->refs--;
451                 LIST_REMOVE(node, nodes);
452                 LIST_REMOVE(node, idnodes);
453                 FREE(node, M_NETGRAPH);
454         }
455         crit_exit();
456 }
457
458 /*
459  * Wait for a node to come ready. Returns a node with a reference count;
460  * don't forget to drop it when we are done with it using ng_release_node().
461  */
462 int
463 ng_wait_node(node_p node, char *msg)
464 {
465         int error = 0;
466
467         if (msg == NULL)
468                 msg = "netgraph";
469         crit_enter();
470         node->sleepers++;
471         node->refs++;           /* the sleeping process counts as a reference */
472         while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
473                 error = tsleep(node, PCATCH, msg, 0);
474         node->sleepers--;
475         if (node->flags & NG_INVALID) {
476                 TRAP_ERROR;
477                 error = ENXIO;
478         } else {
479                 KASSERT(node->refs > 1,
480                     ("%s: refs=%d", __func__, node->refs));
481                 node->flags |= NG_BUSY;
482         }
483         crit_exit();
484
485         /* Release the reference we had on it */
486         if (error != 0)
487                 ng_unref(node);
488         return error;
489 }
490
491 /*
492  * Release a node acquired via ng_wait_node()
493  */
494 void
495 ng_release_node(node_p node)
496 {
497         /* Declare that we don't want it */
498         node->flags &= ~NG_BUSY;
499
500         /* If we have sleepers, then wake them up */
501         if (node->sleepers)
502                 wakeup(node);
503
504         /* We also have a reference.. drop it too */
505         ng_unref(node);
506 }
507
508 /************************************************************************
509                         Node ID handling
510 ************************************************************************/
511 static node_p
512 ng_ID2node(ng_ID_t ID)
513 {
514         node_p np;
515         LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
516                 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
517                         break;
518         }
519         return(np);
520 }
521
522 ng_ID_t
523 ng_node2ID(node_p node)
524 {
525         return (node->ID);
526 }
527
528 /************************************************************************
529                         Node name handling
530 ************************************************************************/
531
532 /*
533  * Assign a node a name. Once assigned, the name cannot be changed.
534  */
535 int
536 ng_name_node(node_p node, const char *name)
537 {
538         int i;
539
540         /* Check the name is valid */
541         for (i = 0; i < NG_NODELEN + 1; i++) {
542                 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
543                         break;
544         }
545         if (i == 0 || name[i] != '\0') {
546                 TRAP_ERROR;
547                 return (EINVAL);
548         }
549         if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
550                 TRAP_ERROR;
551                 return (EINVAL);
552         }
553
554         /* Check the node isn't already named */
555         if (node->name != NULL) {
556                 TRAP_ERROR;
557                 return (EISCONN);
558         }
559
560         /* Check the name isn't already being used */
561         if (ng_findname(node, name) != NULL) {
562                 TRAP_ERROR;
563                 return (EADDRINUSE);
564         }
565
566         /* Allocate space and copy it */
567         MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
568         if (node->name == NULL) {
569                 TRAP_ERROR;
570                 return (ENOMEM);
571         }
572         strcpy(node->name, name);
573
574         /* The name counts as a reference */
575         node->refs++;
576         return (0);
577 }
578
579 /*
580  * Find a node by absolute name. The name should NOT end with ':'
581  * The name "." means "this node" and "[xxx]" means "the node
582  * with ID (ie, at address) xxx".
583  *
584  * Returns the node if found, else NULL.
585  */
586 node_p
587 ng_findname(node_p this, const char *name)
588 {
589         node_p node;
590         ng_ID_t temp;
591
592         /* "." means "this node" */
593         if (strcmp(name, ".") == 0)
594                 return(this);
595
596         /* Check for name-by-ID */
597         if ((temp = ng_decodeidname(name)) != 0) {
598                 return (ng_ID2node(temp));
599         }
600
601         /* Find node by name */
602         LIST_FOREACH(node, &nodelist, nodes) {
603                 if ((node->name != NULL)
604                 && (strcmp(node->name, name) == 0)
605                 && ((node->flags & NG_INVALID) == 0))
606                         break;
607         }
608         return (node);
609 }
610
611 /*
612  * Decode a ID name, eg. "[f03034de]". Returns 0 if the
613  * string is not valid, otherwise returns the value.
614  */
615 static ng_ID_t
616 ng_decodeidname(const char *name)
617 {
618         const int len = strlen(name);
619         char *eptr;
620         u_long val;
621
622         /* Check for proper length, brackets, no leading junk */
623         if (len < 3 || name[0] != '[' || name[len - 1] != ']'
624             || !isxdigit(name[1]))
625                 return (0);
626
627         /* Decode number */
628         val = strtoul(name + 1, &eptr, 16);
629         if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
630                 return ((ng_ID_t)0);
631         return (ng_ID_t)val;
632 }
633
634 /*
635  * Remove a name from a node. This should only be called
636  * when shutting down and removing the node.
637  */
638 void
639 ng_unname(node_p node)
640 {
641         if (node->name) {
642                 FREE(node->name, M_NETGRAPH);
643                 node->name = NULL;
644                 ng_unref(node);
645         }
646 }
647
648 /************************************************************************
649                         Hook routines
650
651  Names are not optional. Hooks are always connected, except for a
652  brief moment within these routines.
653
654 ************************************************************************/
655
656 /*
657  * Remove a hook reference
658  */
659 void
660 ng_unref_hook(hook_p hook)
661 {
662         crit_enter();
663         if (--hook->refs == 0)
664                 FREE(hook, M_NETGRAPH);
665         crit_exit();
666 }
667
668 /*
669  * Add an unconnected hook to a node. Only used internally.
670  */
671 static int
672 ng_add_hook(node_p node, const char *name, hook_p *hookp)
673 {
674         hook_p hook;
675         int error = 0;
676
677         /* Check that the given name is good */
678         if (name == NULL) {
679                 TRAP_ERROR;
680                 return (EINVAL);
681         }
682         if (ng_findhook(node, name) != NULL) {
683                 TRAP_ERROR;
684                 return (EEXIST);
685         }
686
687         /* Allocate the hook and link it up */
688         MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
689         if (hook == NULL) {
690                 TRAP_ERROR;
691                 return (ENOMEM);
692         }
693         bzero(hook, sizeof(*hook));
694         hook->refs = 1;
695         hook->flags = HK_INVALID;
696         hook->node = node;
697         node->refs++;           /* each hook counts as a reference */
698
699         /* Check if the node type code has something to say about it */
700         if (node->type->newhook != NULL)
701                 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
702                         goto fail;
703
704         /*
705          * The 'type' agrees so far, so go ahead and link it in.
706          * We'll ask again later when we actually connect the hooks.
707          */
708         LIST_INSERT_HEAD(&node->hooks, hook, hooks);
709         node->numhooks++;
710
711         /* Set hook name */
712         MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
713         if (hook->name == NULL) {
714                 error = ENOMEM;
715                 LIST_REMOVE(hook, hooks);
716                 node->numhooks--;
717 fail:
718                 hook->node = NULL;
719                 ng_unref(node);
720                 ng_unref_hook(hook);    /* this frees the hook */
721                 return (error);
722         }
723         strcpy(hook->name, name);
724         if (hookp)
725                 *hookp = hook;
726         return (error);
727 }
728
729 /*
730  * Connect a pair of hooks. Only used internally.
731  */
732 static int
733 ng_connect(hook_p hook1, hook_p hook2)
734 {
735         int     error;
736
737         hook1->peer = hook2;
738         hook2->peer = hook1;
739
740         /* Give each node the opportunity to veto the impending connection */
741         if (hook1->node->type->connect) {
742                 if ((error = (*hook1->node->type->connect) (hook1))) {
743                         ng_destroy_hook(hook1); /* also zaps hook2 */
744                         return (error);
745                 }
746         }
747         if (hook2->node->type->connect) {
748                 if ((error = (*hook2->node->type->connect) (hook2))) {
749                         ng_destroy_hook(hook2); /* also zaps hook1 */
750                         return (error);
751                 }
752         }
753         hook1->flags &= ~HK_INVALID;
754         hook2->flags &= ~HK_INVALID;
755         return (0);
756 }
757
758 /*
759  * Find a hook
760  *
761  * Node types may supply their own optimized routines for finding
762  * hooks.  If none is supplied, we just do a linear search.
763  */
764 hook_p
765 ng_findhook(node_p node, const char *name)
766 {
767         hook_p hook;
768
769         if (node->type->findhook != NULL)
770                 return (*node->type->findhook)(node, name);
771         LIST_FOREACH(hook, &node->hooks, hooks) {
772                 if (hook->name != NULL
773                     && strcmp(hook->name, name) == 0
774                     && (hook->flags & HK_INVALID) == 0)
775                         return (hook);
776         }
777         return (NULL);
778 }
779
780 /*
781  * Destroy a hook
782  *
783  * As hooks are always attached, this really destroys two hooks.
784  * The one given, and the one attached to it. Disconnect the hooks
785  * from each other first.
786  */
787 void
788 ng_destroy_hook(hook_p hook)
789 {
790         hook_p peer = hook->peer;
791
792         hook->flags |= HK_INVALID;              /* as soon as possible */
793         if (peer) {
794                 peer->flags |= HK_INVALID;      /* as soon as possible */
795                 hook->peer = NULL;
796                 peer->peer = NULL;
797                 ng_disconnect_hook(peer);
798         }
799         ng_disconnect_hook(hook);
800 }
801
802 /*
803  * Notify the node of the hook's demise. This may result in more actions
804  * (e.g. shutdown) but we don't do that ourselves and don't know what
805  * happens there. If there is no appropriate handler, then just remove it
806  * (and decrement the reference count of it's node which in turn might
807  * make something happen).
808  */
809 static void
810 ng_disconnect_hook(hook_p hook)
811 {
812         node_p node = hook->node;
813
814         /*
815          * Remove the hook from the node's list to avoid possible recursion
816          * in case the disconnection results in node shutdown.
817          */
818         LIST_REMOVE(hook, hooks);
819         node->numhooks--;
820         if (node->type->disconnect) {
821                 /*
822                  * The type handler may elect to destroy the peer so don't
823                  * trust its existance after this point.
824                  */
825                 (*node->type->disconnect) (hook);
826         }
827         ng_unref(node);         /* might be the last reference */
828         if (hook->name)
829                 FREE(hook->name, M_NETGRAPH);
830         hook->node = NULL;      /* may still be referenced elsewhere */
831         ng_unref_hook(hook);
832 }
833
834 /*
835  * Take two hooks on a node and merge the connection so that the given node
836  * is effectively bypassed.
837  */
838 int
839 ng_bypass(hook_p hook1, hook_p hook2)
840 {
841         if (hook1->node != hook2->node)
842                 return (EINVAL);
843         hook1->peer->peer = hook2->peer;
844         hook2->peer->peer = hook1->peer;
845
846         /* XXX If we ever cache methods on hooks update them as well */
847         hook1->peer = NULL;
848         hook2->peer = NULL;
849         ng_destroy_hook(hook1);
850         ng_destroy_hook(hook2);
851         return (0);
852 }
853
854 /*
855  * Install a new netgraph type
856  */
857 int
858 ng_newtype(struct ng_type *tp)
859 {
860         const size_t namelen = strlen(tp->name);
861
862         /* Check version and type name fields */
863         if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
864                 TRAP_ERROR;
865                 return (EINVAL);
866         }
867
868         /* Check for name collision */
869         if (ng_findtype(tp->name) != NULL) {
870                 TRAP_ERROR;
871                 return (EEXIST);
872         }
873
874         /* Link in new type */
875         LIST_INSERT_HEAD(&typelist, tp, types);
876         tp->refs = 1;   /* first ref is linked list */
877         return (0);
878 }
879
880 /*
881  * Look for a type of the name given
882  */
883 struct ng_type *
884 ng_findtype(const char *typename)
885 {
886         struct ng_type *type;
887
888         LIST_FOREACH(type, &typelist, types) {
889                 if (strcmp(type->name, typename) == 0)
890                         break;
891         }
892         return (type);
893 }
894
895
896 /************************************************************************
897                         Composite routines
898 ************************************************************************/
899
900 /*
901  * Make a peer and connect. The order is arranged to minimise
902  * the work needed to back out in case of error.
903  */
904 int
905 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
906 {
907         node_p  node2;
908         hook_p  hook;
909         hook_p  hook2;
910         int     error;
911
912         if ((error = ng_add_hook(node, name, &hook)))
913                 return (error);
914         if ((error = ng_make_node(type, &node2))) {
915                 ng_destroy_hook(hook);
916                 return (error);
917         }
918         if ((error = ng_add_hook(node2, name2, &hook2))) {
919                 ng_rmnode(node2);
920                 ng_destroy_hook(hook);
921                 return (error);
922         }
923
924         /*
925          * Actually link the two hooks together.. on failure they are
926          * destroyed so we don't have to do that here.
927          */
928         if ((error = ng_connect(hook, hook2)))
929                 ng_rmnode(node2);
930         return (error);
931 }
932
933 /*
934  * Connect two nodes using the specified hooks
935  */
936 int
937 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
938 {
939         int     error;
940         hook_p  hook;
941         hook_p  hook2;
942
943         if ((error = ng_add_hook(node, name, &hook)))
944                 return (error);
945         if ((error = ng_add_hook(node2, name2, &hook2))) {
946                 ng_destroy_hook(hook);
947                 return (error);
948         }
949         return (ng_connect(hook, hook2));
950 }
951
952 /*
953  * Parse and verify a string of the form:  <NODE:><PATH>
954  *
955  * Such a string can refer to a specific node or a specific hook
956  * on a specific node, depending on how you look at it. In the
957  * latter case, the PATH component must not end in a dot.
958  *
959  * Both <NODE:> and <PATH> are optional. The <PATH> is a string
960  * of hook names separated by dots. This breaks out the original
961  * string, setting *nodep to "NODE" (or NULL if none) and *pathp
962  * to "PATH" (or NULL if degenerate). Also, *hookp will point to
963  * the final hook component of <PATH>, if any, otherwise NULL.
964  *
965  * This returns -1 if the path is malformed. The char ** are optional.
966  */
967
968 int
969 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
970 {
971         char   *node, *path, *hook;
972         int     k;
973
974         /*
975          * Extract absolute NODE, if any
976          */
977         for (path = addr; *path && *path != ':'; path++);
978         if (*path) {
979                 node = addr;    /* Here's the NODE */
980                 *path++ = '\0'; /* Here's the PATH */
981
982                 /* Node name must not be empty */
983                 if (!*node)
984                         return -1;
985
986                 /* A name of "." is OK; otherwise '.' not allowed */
987                 if (strcmp(node, ".") != 0) {
988                         for (k = 0; node[k]; k++)
989                                 if (node[k] == '.')
990                                         return -1;
991                 }
992         } else {
993                 node = NULL;    /* No absolute NODE */
994                 path = addr;    /* Here's the PATH */
995         }
996
997         /* Snoop for illegal characters in PATH */
998         for (k = 0; path[k]; k++)
999                 if (path[k] == ':')
1000                         return -1;
1001
1002         /* Check for no repeated dots in PATH */
1003         for (k = 0; path[k]; k++)
1004                 if (path[k] == '.' && path[k + 1] == '.')
1005                         return -1;
1006
1007         /* Remove extra (degenerate) dots from beginning or end of PATH */
1008         if (path[0] == '.')
1009                 path++;
1010         if (*path && path[strlen(path) - 1] == '.')
1011                 path[strlen(path) - 1] = 0;
1012
1013         /* If PATH has a dot, then we're not talking about a hook */
1014         if (*path) {
1015                 for (hook = path, k = 0; path[k]; k++)
1016                         if (path[k] == '.') {
1017                                 hook = NULL;
1018                                 break;
1019                         }
1020         } else
1021                 path = hook = NULL;
1022
1023         /* Done */
1024         if (nodep)
1025                 *nodep = node;
1026         if (pathp)
1027                 *pathp = path;
1028         if (hookp)
1029                 *hookp = hook;
1030         return (0);
1031 }
1032
1033 /*
1034  * Given a path, which may be absolute or relative, and a starting node,
1035  * return the destination node. Compute the "return address" if desired.
1036  */
1037 int
1038 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1039 {
1040         const   node_p start = here;
1041         char    fullpath[NG_PATHLEN + 1];
1042         char   *nodename, *path, pbuf[2];
1043         node_p  node;
1044         char   *cp;
1045
1046         /* Initialize */
1047         if (rtnp)
1048                 *rtnp = NULL;
1049         if (destp == NULL)
1050                 return EINVAL;
1051         *destp = NULL;
1052
1053         /* Make a writable copy of address for ng_path_parse() */
1054         strncpy(fullpath, address, sizeof(fullpath) - 1);
1055         fullpath[sizeof(fullpath) - 1] = '\0';
1056
1057         /* Parse out node and sequence of hooks */
1058         if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1059                 TRAP_ERROR;
1060                 return EINVAL;
1061         }
1062         if (path == NULL) {
1063                 pbuf[0] = '.';  /* Needs to be writable */
1064                 pbuf[1] = '\0';
1065                 path = pbuf;
1066         }
1067
1068         /* For an absolute address, jump to the starting node */
1069         if (nodename) {
1070                 node = ng_findname(here, nodename);
1071                 if (node == NULL) {
1072                         TRAP_ERROR;
1073                         return (ENOENT);
1074                 }
1075         } else
1076                 node = here;
1077
1078         /* Now follow the sequence of hooks */
1079         for (cp = path; node != NULL && *cp != '\0'; ) {
1080                 hook_p hook;
1081                 char *segment;
1082
1083                 /*
1084                  * Break out the next path segment. Replace the dot we just
1085                  * found with a NUL; "cp" points to the next segment (or the
1086                  * NUL at the end).
1087                  */
1088                 for (segment = cp; *cp != '\0'; cp++) {
1089                         if (*cp == '.') {
1090                                 *cp++ = '\0';
1091                                 break;
1092                         }
1093                 }
1094
1095                 /* Empty segment */
1096                 if (*segment == '\0')
1097                         continue;
1098
1099                 /* We have a segment, so look for a hook by that name */
1100                 hook = ng_findhook(node, segment);
1101
1102                 /* Can't get there from here... */
1103                 if (hook == NULL
1104                     || hook->peer == NULL
1105                     || (hook->flags & HK_INVALID) != 0) {
1106                         TRAP_ERROR;
1107                         return (ENOENT);
1108                 }
1109
1110                 /* Hop on over to the next node */
1111                 node = hook->peer->node;
1112         }
1113
1114         /* If node somehow missing, fail here (probably this is not needed) */
1115         if (node == NULL) {
1116                 TRAP_ERROR;
1117                 return (ENXIO);
1118         }
1119
1120         /* Now compute return address, i.e., the path to the sender */
1121         if (rtnp != NULL) {
1122                 MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_NOWAIT);
1123                 if (*rtnp == NULL) {
1124                         TRAP_ERROR;
1125                         return (ENOMEM);
1126                 }
1127                 if (start->name != NULL)
1128                         sprintf(*rtnp, "%s:", start->name);
1129                 else
1130                         sprintf(*rtnp, "[%x]:", ng_node2ID(start));
1131         }
1132
1133         /* Done */
1134         *destp = node;
1135         return (0);
1136 }
1137
1138 /*
1139  * Call the appropriate message handler for the object.
1140  * It is up to the message handler to free the message.
1141  * If it's a generic message, handle it generically, otherwise
1142  * call the type's message handler (if it exists)
1143  * XXX (race). Remember that a queued message may reference a node
1144  * or hook that has just been invalidated. It will exist
1145  * as the queue code is holding a reference, but..
1146  */
1147
1148 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp)               \
1149 do {                                                                    \
1150         if((msg)->header.typecookie == NGM_GENERIC_COOKIE) {            \
1151                 (error) = ng_generic_msg((node), (msg),                 \
1152                                 (retaddr), (resp));                     \
1153         } else {                                                        \
1154                 if ((node)->type->rcvmsg != NULL) {                     \
1155                         (error) = (*(node)->type->rcvmsg)((node),       \
1156                                         (msg), (retaddr), (resp));      \
1157                 } else {                                                \
1158                         TRAP_ERROR;                                     \
1159                         FREE((msg), M_NETGRAPH);                        \
1160                         (error) = EINVAL;                               \
1161                 }                                                       \
1162         }                                                               \
1163 } while (0)
1164
1165
1166 /*
1167  * Send a control message to a node
1168  */
1169 int
1170 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1171             struct ng_mesg **rptr)
1172 {
1173         node_p  dest = NULL;
1174         char   *retaddr = NULL;
1175         int     error;
1176
1177         /* Find the target node */
1178         error = ng_path2node(here, address, &dest, &retaddr);
1179         if (error) {
1180                 FREE(msg, M_NETGRAPH);
1181                 return error;
1182         }
1183
1184         /* Make sure the resp field is null before we start */
1185         if (rptr != NULL)
1186                 *rptr = NULL;
1187
1188         CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1189
1190         /* Make sure that if there is a response, it has the RESP bit set */
1191         if ((error == 0) && rptr && *rptr)
1192                 (*rptr)->header.flags |= NGF_RESP;
1193
1194         /*
1195          * If we had a return address it is up to us to free it. They should
1196          * have taken a copy if they needed to make a delayed response.
1197          */
1198         if (retaddr)
1199                 FREE(retaddr, M_NETGRAPH);
1200         return (error);
1201 }
1202
1203 /*
1204  * Implement the 'generic' control messages
1205  */
1206 static int
1207 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1208                struct ng_mesg **resp)
1209 {
1210         int error = 0;
1211
1212         if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1213                 TRAP_ERROR;
1214                 FREE(msg, M_NETGRAPH);
1215                 return (EINVAL);
1216         }
1217         switch (msg->header.cmd) {
1218         case NGM_SHUTDOWN:
1219                 ng_rmnode(here);
1220                 break;
1221         case NGM_MKPEER:
1222             {
1223                 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1224
1225                 if (msg->header.arglen != sizeof(*mkp)) {
1226                         TRAP_ERROR;
1227                         return (EINVAL);
1228                 }
1229                 mkp->type[sizeof(mkp->type) - 1] = '\0';
1230                 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1231                 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1232                 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1233                 break;
1234             }
1235         case NGM_CONNECT:
1236             {
1237                 struct ngm_connect *const con =
1238                         (struct ngm_connect *) msg->data;
1239                 node_p node2;
1240
1241                 if (msg->header.arglen != sizeof(*con)) {
1242                         TRAP_ERROR;
1243                         return (EINVAL);
1244                 }
1245                 con->path[sizeof(con->path) - 1] = '\0';
1246                 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1247                 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1248                 error = ng_path2node(here, con->path, &node2, NULL);
1249                 if (error)
1250                         break;
1251                 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1252                 break;
1253             }
1254         case NGM_NAME:
1255             {
1256                 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1257
1258                 if (msg->header.arglen != sizeof(*nam)) {
1259                         TRAP_ERROR;
1260                         return (EINVAL);
1261                 }
1262                 nam->name[sizeof(nam->name) - 1] = '\0';
1263                 error = ng_name_node(here, nam->name);
1264                 break;
1265             }
1266         case NGM_RMHOOK:
1267             {
1268                 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1269                 hook_p hook;
1270
1271                 if (msg->header.arglen != sizeof(*rmh)) {
1272                         TRAP_ERROR;
1273                         return (EINVAL);
1274                 }
1275                 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1276                 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1277                         ng_destroy_hook(hook);
1278                 break;
1279             }
1280         case NGM_NODEINFO:
1281             {
1282                 struct nodeinfo *ni;
1283                 struct ng_mesg *rp;
1284
1285                 /* Get response struct */
1286                 if (resp == NULL) {
1287                         error = EINVAL;
1288                         break;
1289                 }
1290                 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1291                 if (rp == NULL) {
1292                         error = ENOMEM;
1293                         break;
1294                 }
1295
1296                 /* Fill in node info */
1297                 ni = (struct nodeinfo *) rp->data;
1298                 if (here->name != NULL)
1299                         strncpy(ni->name, here->name, NG_NODELEN);
1300                 strncpy(ni->type, here->type->name, NG_TYPELEN);
1301                 ni->id = ng_node2ID(here);
1302                 ni->hooks = here->numhooks;
1303                 *resp = rp;
1304                 break;
1305             }
1306         case NGM_LISTHOOKS:
1307             {
1308                 const int nhooks = here->numhooks;
1309                 struct hooklist *hl;
1310                 struct nodeinfo *ni;
1311                 struct ng_mesg *rp;
1312                 hook_p hook;
1313
1314                 /* Get response struct */
1315                 if (resp == NULL) {
1316                         error = EINVAL;
1317                         break;
1318                 }
1319                 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1320                     + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1321                 if (rp == NULL) {
1322                         error = ENOMEM;
1323                         break;
1324                 }
1325                 hl = (struct hooklist *) rp->data;
1326                 ni = &hl->nodeinfo;
1327
1328                 /* Fill in node info */
1329                 if (here->name)
1330                         strncpy(ni->name, here->name, NG_NODELEN);
1331                 strncpy(ni->type, here->type->name, NG_TYPELEN);
1332                 ni->id = ng_node2ID(here);
1333
1334                 /* Cycle through the linked list of hooks */
1335                 ni->hooks = 0;
1336                 LIST_FOREACH(hook, &here->hooks, hooks) {
1337                         struct linkinfo *const link = &hl->link[ni->hooks];
1338
1339                         if (ni->hooks >= nhooks) {
1340                                 log(LOG_ERR, "%s: number of %s changed\n",
1341                                     __func__, "hooks");
1342                                 break;
1343                         }
1344                         if ((hook->flags & HK_INVALID) != 0)
1345                                 continue;
1346                         strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1347                         strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1348                         if (hook->peer->node->name != NULL)
1349                                 strncpy(link->nodeinfo.name,
1350                                     hook->peer->node->name, NG_NODELEN);
1351                         strncpy(link->nodeinfo.type,
1352                            hook->peer->node->type->name, NG_TYPELEN);
1353                         link->nodeinfo.id = ng_node2ID(hook->peer->node);
1354                         link->nodeinfo.hooks = hook->peer->node->numhooks;
1355                         ni->hooks++;
1356                 }
1357                 *resp = rp;
1358                 break;
1359             }
1360
1361         case NGM_LISTNAMES:
1362         case NGM_LISTNODES:
1363             {
1364                 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1365                 struct namelist *nl;
1366                 struct ng_mesg *rp;
1367                 node_p node;
1368                 int num = 0;
1369
1370                 if (resp == NULL) {
1371                         error = EINVAL;
1372                         break;
1373                 }
1374
1375                 /* Count number of nodes */
1376                 LIST_FOREACH(node, &nodelist, nodes) {
1377                         if ((node->flags & NG_INVALID) == 0
1378                             && (unnamed || node->name != NULL))
1379                                 num++;
1380                 }
1381
1382                 /* Get response struct */
1383                 if (resp == NULL) {
1384                         error = EINVAL;
1385                         break;
1386                 }
1387                 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1388                     + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1389                 if (rp == NULL) {
1390                         error = ENOMEM;
1391                         break;
1392                 }
1393                 nl = (struct namelist *) rp->data;
1394
1395                 /* Cycle through the linked list of nodes */
1396                 nl->numnames = 0;
1397                 LIST_FOREACH(node, &nodelist, nodes) {
1398                         struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1399
1400                         if (nl->numnames >= num) {
1401                                 log(LOG_ERR, "%s: number of %s changed\n",
1402                                     __func__, "nodes");
1403                                 break;
1404                         }
1405                         if ((node->flags & NG_INVALID) != 0)
1406                                 continue;
1407                         if (!unnamed && node->name == NULL)
1408                                 continue;
1409                         if (node->name != NULL)
1410                                 strncpy(np->name, node->name, NG_NODELEN);
1411                         strncpy(np->type, node->type->name, NG_TYPELEN);
1412                         np->id = ng_node2ID(node);
1413                         np->hooks = node->numhooks;
1414                         nl->numnames++;
1415                 }
1416                 *resp = rp;
1417                 break;
1418             }
1419
1420         case NGM_LISTTYPES:
1421             {
1422                 struct typelist *tl;
1423                 struct ng_mesg *rp;
1424                 struct ng_type *type;
1425                 int num = 0;
1426
1427                 if (resp == NULL) {
1428                         error = EINVAL;
1429                         break;
1430                 }
1431
1432                 /* Count number of types */
1433                 LIST_FOREACH(type, &typelist, types)
1434                         num++;
1435
1436                 /* Get response struct */
1437                 if (resp == NULL) {
1438                         error = EINVAL;
1439                         break;
1440                 }
1441                 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1442                     + (num * sizeof(struct typeinfo)), M_NOWAIT);
1443                 if (rp == NULL) {
1444                         error = ENOMEM;
1445                         break;
1446                 }
1447                 tl = (struct typelist *) rp->data;
1448
1449                 /* Cycle through the linked list of types */
1450                 tl->numtypes = 0;
1451                 LIST_FOREACH(type, &typelist, types) {
1452                         struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1453
1454                         if (tl->numtypes >= num) {
1455                                 log(LOG_ERR, "%s: number of %s changed\n",
1456                                     __func__, "types");
1457                                 break;
1458                         }
1459                         strncpy(tp->type_name, type->name, NG_TYPELEN);
1460                         tp->numnodes = type->refs - 1; /* don't count list */
1461                         tl->numtypes++;
1462                 }
1463                 *resp = rp;
1464                 break;
1465             }
1466
1467         case NGM_BINARY2ASCII:
1468             {
1469                 int bufSize = 20 * 1024;        /* XXX hard coded constant */
1470                 const struct ng_parse_type *argstype;
1471                 const struct ng_cmdlist *c;
1472                 struct ng_mesg *rp, *binary, *ascii;
1473
1474                 /* Data area must contain a valid netgraph message */
1475                 binary = (struct ng_mesg *)msg->data;
1476                 if (msg->header.arglen < sizeof(struct ng_mesg)
1477                     || msg->header.arglen - sizeof(struct ng_mesg) 
1478                       < binary->header.arglen) {
1479                         error = EINVAL;
1480                         break;
1481                 }
1482
1483                 /* Get a response message with lots of room */
1484                 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1485                 if (rp == NULL) {
1486                         error = ENOMEM;
1487                         break;
1488                 }
1489                 ascii = (struct ng_mesg *)rp->data;
1490
1491                 /* Copy binary message header to response message payload */
1492                 bcopy(binary, ascii, sizeof(*binary));
1493
1494                 /* Find command by matching typecookie and command number */
1495                 for (c = here->type->cmdlist;
1496                     c != NULL && c->name != NULL; c++) {
1497                         if (binary->header.typecookie == c->cookie
1498                             && binary->header.cmd == c->cmd)
1499                                 break;
1500                 }
1501                 if (c == NULL || c->name == NULL) {
1502                         for (c = ng_generic_cmds; c->name != NULL; c++) {
1503                                 if (binary->header.typecookie == c->cookie
1504                                     && binary->header.cmd == c->cmd)
1505                                         break;
1506                         }
1507                         if (c->name == NULL) {
1508                                 FREE(rp, M_NETGRAPH);
1509                                 error = ENOSYS;
1510                                 break;
1511                         }
1512                 }
1513
1514                 /* Convert command name to ASCII */
1515                 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1516                     "%s", c->name);
1517
1518                 /* Convert command arguments to ASCII */
1519                 argstype = (binary->header.flags & NGF_RESP) ?
1520                     c->respType : c->mesgType;
1521                 if (argstype == NULL)
1522                         *ascii->data = '\0';
1523                 else {
1524                         if ((error = ng_unparse(argstype,
1525                             (u_char *)binary->data,
1526                             ascii->data, bufSize)) != 0) {
1527                                 FREE(rp, M_NETGRAPH);
1528                                 break;
1529                         }
1530                 }
1531
1532                 /* Return the result as struct ng_mesg plus ASCII string */
1533                 bufSize = strlen(ascii->data) + 1;
1534                 ascii->header.arglen = bufSize;
1535                 rp->header.arglen = sizeof(*ascii) + bufSize;
1536                 *resp = rp;
1537                 break;
1538             }
1539
1540         case NGM_ASCII2BINARY:
1541             {
1542                 int bufSize = 2000;     /* XXX hard coded constant */
1543                 const struct ng_cmdlist *c;
1544                 const struct ng_parse_type *argstype;
1545                 struct ng_mesg *rp, *ascii, *binary;
1546                 int off = 0;
1547
1548                 /* Data area must contain at least a struct ng_mesg + '\0' */
1549                 ascii = (struct ng_mesg *)msg->data;
1550                 if (msg->header.arglen < sizeof(*ascii) + 1
1551                     || ascii->header.arglen < 1
1552                     || msg->header.arglen
1553                       < sizeof(*ascii) + ascii->header.arglen) {
1554                         error = EINVAL;
1555                         break;
1556                 }
1557                 ascii->data[ascii->header.arglen - 1] = '\0';
1558
1559                 /* Get a response message with lots of room */
1560                 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1561                 if (rp == NULL) {
1562                         error = ENOMEM;
1563                         break;
1564                 }
1565                 binary = (struct ng_mesg *)rp->data;
1566
1567                 /* Copy ASCII message header to response message payload */
1568                 bcopy(ascii, binary, sizeof(*ascii));
1569
1570                 /* Find command by matching ASCII command string */
1571                 for (c = here->type->cmdlist;
1572                     c != NULL && c->name != NULL; c++) {
1573                         if (strcmp(ascii->header.cmdstr, c->name) == 0)
1574                                 break;
1575                 }
1576                 if (c == NULL || c->name == NULL) {
1577                         for (c = ng_generic_cmds; c->name != NULL; c++) {
1578                                 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1579                                         break;
1580                         }
1581                         if (c->name == NULL) {
1582                                 FREE(rp, M_NETGRAPH);
1583                                 error = ENOSYS;
1584                                 break;
1585                         }
1586                 }
1587
1588                 /* Convert command name to binary */
1589                 binary->header.cmd = c->cmd;
1590                 binary->header.typecookie = c->cookie;
1591
1592                 /* Convert command arguments to binary */
1593                 argstype = (binary->header.flags & NGF_RESP) ?
1594                     c->respType : c->mesgType;
1595                 if (argstype == NULL)
1596                         bufSize = 0;
1597                 else {
1598                         if ((error = ng_parse(argstype, ascii->data,
1599                             &off, (u_char *)binary->data, &bufSize)) != 0) {
1600                                 FREE(rp, M_NETGRAPH);
1601                                 break;
1602                         }
1603                 }
1604
1605                 /* Return the result */
1606                 binary->header.arglen = bufSize;
1607                 rp->header.arglen = sizeof(*binary) + bufSize;
1608                 *resp = rp;
1609                 break;
1610             }
1611
1612         case NGM_TEXT_CONFIG:
1613         case NGM_TEXT_STATUS:
1614                 /*
1615                  * This one is tricky as it passes the command down to the
1616                  * actual node, even though it is a generic type command.
1617                  * This means we must assume that the msg is already freed
1618                  * when control passes back to us.
1619                  */
1620                 if (resp == NULL) {
1621                         error = EINVAL;
1622                         break;
1623                 }
1624                 if (here->type->rcvmsg != NULL)
1625                         return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1626                 /* Fall through if rcvmsg not supported */
1627         default:
1628                 TRAP_ERROR;
1629                 error = EINVAL;
1630         }
1631         FREE(msg, M_NETGRAPH);
1632         return (error);
1633 }
1634
1635 /*
1636  * Send a data packet to a node. If the recipient has no
1637  * 'receive data' method, then silently discard the packet.
1638  */
1639 int 
1640 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1641 {
1642         int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1643         int error;
1644
1645         CHECK_DATA_MBUF(m);
1646         if (hook && (hook->flags & HK_INVALID) == 0) {
1647                 rcvdata = hook->peer->node->type->rcvdata;
1648                 if (rcvdata != NULL)
1649                         error = (*rcvdata)(hook->peer, m, meta);
1650                 else {
1651                         error = 0;
1652                         NG_FREE_DATA(m, meta);
1653                 }
1654         } else {
1655                 TRAP_ERROR;
1656                 error = ENOTCONN;
1657                 NG_FREE_DATA(m, meta);
1658         }
1659         return (error);
1660 }
1661
1662 /*
1663  * Send a queued data packet to a node. If the recipient has no
1664  * 'receive queued data' method, then try the 'receive data' method above.
1665  */
1666 int 
1667 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1668 {
1669         int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1670         int error;
1671
1672         CHECK_DATA_MBUF(m);
1673         if (hook && (hook->flags & HK_INVALID) == 0) {
1674                 rcvdataq = hook->peer->node->type->rcvdataq;
1675                 if (rcvdataq != NULL)
1676                         error = (*rcvdataq)(hook->peer, m, meta);
1677                 else {
1678                         error = ng_send_data(hook, m, meta);
1679                 }
1680         } else {
1681                 TRAP_ERROR;
1682                 error = ENOTCONN;
1683                 NG_FREE_DATA(m, meta);
1684         }
1685         return (error);
1686 }
1687
1688 /*
1689  * Copy a 'meta'.
1690  *
1691  * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1692  */
1693 meta_p
1694 ng_copy_meta(meta_p meta)
1695 {
1696         meta_p meta2;
1697
1698         if (meta == NULL)
1699                 return (NULL);
1700         MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1701         if (meta2 == NULL)
1702                 return (NULL);
1703         meta2->allocated_len = meta->used_len;
1704         bcopy(meta, meta2, meta->used_len);
1705         return (meta2);
1706 }
1707
1708 /************************************************************************
1709                         Module routines
1710 ************************************************************************/
1711
1712 /*
1713  * Handle the loading/unloading of a netgraph node type module
1714  */
1715 int
1716 ng_mod_event(module_t mod, int event, void *data)
1717 {
1718         struct ng_type *const type = data;
1719         int error = 0;
1720
1721         switch (event) {
1722         case MOD_LOAD:
1723
1724                 /* Register new netgraph node type */
1725                 crit_enter();
1726                 if ((error = ng_newtype(type)) != 0) {
1727                         crit_exit();
1728                         break;
1729                 }
1730
1731                 /* Call type specific code */
1732                 if (type->mod_event != NULL)
1733                         if ((error = (*type->mod_event)(mod, event, data))) {
1734                                 type->refs--;   /* undo it */
1735                                 LIST_REMOVE(type, types);
1736                         }
1737                 crit_exit();
1738                 break;
1739
1740         case MOD_UNLOAD:
1741                 crit_enter();
1742                 if (type->refs > 1) {           /* make sure no nodes exist! */
1743                         error = EBUSY;
1744                 } else {
1745                         if (type->refs == 0) {
1746                                 /* failed load, nothing to undo */
1747                                 crit_exit();
1748                                 break;
1749                         }
1750                         if (type->mod_event != NULL) {  /* check with type */
1751                                 error = (*type->mod_event)(mod, event, data);
1752                                 if (error != 0) {       /* type refuses.. */
1753                                         crit_exit();
1754                                         break;
1755                                 }
1756                         }
1757                         LIST_REMOVE(type, types);
1758                 }
1759                 crit_exit();
1760                 break;
1761
1762         default:
1763                 if (type->mod_event != NULL)
1764                         error = (*type->mod_event)(mod, event, data);
1765                 else
1766                         error = 0;              /* XXX ? */
1767                 break;
1768         }
1769         return (error);
1770 }
1771
1772 /*
1773  * Handle loading and unloading for this code.
1774  * The only thing we need to link into is the NETISR strucure.
1775  */
1776 static int
1777 ngb_mod_event(module_t mod, int event, void *data)
1778 {
1779         int error = 0;
1780
1781         switch (event) {
1782         case MOD_LOAD:
1783                 /* Register line discipline */
1784                 crit_enter();
1785                 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1786                 error = 0;
1787                 crit_exit();
1788                 break;
1789         case MOD_UNLOAD:
1790                 /* You cant unload it because an interface may be using it.  */
1791                 error = EBUSY;
1792                 break;
1793         default:
1794                 error = EOPNOTSUPP;
1795                 break;
1796         }
1797         return (error);
1798 }
1799
1800 static moduledata_t netgraph_mod = {
1801         "netgraph",
1802         ngb_mod_event,
1803         (NULL)
1804 };
1805 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1806 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1807 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1808 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1809
1810 /************************************************************************
1811                         Queueing routines
1812 ************************************************************************/
1813
1814 /* The structure for queueing across ISR switches */
1815 struct ng_queue_entry {
1816         u_long  flags;
1817         struct ng_queue_entry *next;
1818         union {
1819                 struct {
1820                         hook_p          da_hook;        /*  target hook */
1821                         struct mbuf     *da_m;
1822                         meta_p          da_meta;
1823                 } data;
1824                 struct {
1825                         struct ng_mesg  *msg_msg;
1826                         node_p          msg_node;
1827                         void            *msg_retaddr;
1828                 } msg;
1829         } body;
1830 };
1831 #define NGQF_DATA       0x01            /* the queue element is data */
1832 #define NGQF_MESG       0x02            /* the queue element is a message */
1833
1834 static struct ng_queue_entry   *ngqbase;        /* items to be unqueued */
1835 static struct ng_queue_entry   *ngqlast;        /* last item queued */
1836 static const int                ngqroom = 256;  /* max items to queue */
1837 static int                      ngqsize;        /* number of items in queue */
1838
1839 static struct ng_queue_entry   *ngqfree;        /* free ones */
1840 static const int                ngqfreemax = 256;/* cache at most this many */
1841 static int                      ngqfreesize;    /* number of cached entries */
1842
1843 /*
1844  * Get a queue entry
1845  */
1846 static struct ng_queue_entry *
1847 ng_getqblk(void)
1848 {
1849         struct ng_queue_entry *q;
1850
1851         /* Could be guarding against tty ints or whatever */
1852         crit_enter();
1853
1854         /* Try get a cached queue block, or else allocate a new one */
1855         if ((q = ngqfree) == NULL) {
1856                 crit_exit();
1857                 if (ngqsize < ngqroom) {        /* don't worry about races */
1858                         MALLOC(q, struct ng_queue_entry *,
1859                             sizeof(*q), M_NETGRAPH, M_NOWAIT);
1860                 }
1861         } else {
1862                 ngqfree = q->next;
1863                 ngqfreesize--;
1864                 crit_exit();
1865         }
1866         return (q);
1867 }
1868
1869 /*
1870  * Release a queue entry
1871  */
1872 #define RETURN_QBLK(q)                                                  \
1873 do {                                                                    \
1874         if (ngqfreesize < ngqfreemax) { /* don't worry about races */   \
1875                 crit_enter();                                           \
1876                 (q)->next = ngqfree;                                    \
1877                 ngqfree = (q);                                          \
1878                 ngqfreesize++;                                          \
1879                 crit_exit();                                            \
1880         } else {                                                        \
1881                 FREE((q), M_NETGRAPH);                                  \
1882         }                                                               \
1883 } while (0)
1884
1885 /*
1886  * Running at a raised (but we don't know which) processor priority level,
1887  * put the data onto a queue to be picked up by another PPL (probably splnet)
1888  */
1889 int
1890 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1891 {
1892         struct ng_queue_entry *q;
1893
1894         if (hook == NULL) {
1895                 NG_FREE_DATA(m, meta);
1896                 return (0);
1897         }
1898         if ((q = ng_getqblk()) == NULL) {
1899                 NG_FREE_DATA(m, meta);
1900                 return (ENOBUFS);
1901         }
1902
1903         /* Fill out the contents */
1904         q->flags = NGQF_DATA;
1905         q->next = NULL;
1906         q->body.data.da_hook = hook;
1907         q->body.data.da_m = m;
1908         q->body.data.da_meta = meta;
1909         crit_enter();           /* protect refs and queue */
1910         hook->refs++;           /* don't let it go away while on the queue */
1911
1912         /* Put it on the queue */
1913         if (ngqbase) {
1914                 ngqlast->next = q;
1915         } else {
1916                 ngqbase = q;
1917         }
1918         ngqlast = q;
1919         ngqsize++;
1920         crit_exit();
1921
1922         /* Schedule software interrupt to handle it later */
1923         schednetisr(NETISR_NETGRAPH);
1924         return (0);
1925 }
1926
1927 /*
1928  * Running at a raised (but we don't know which) processor priority level,
1929  * put the msg onto a queue to be picked up by another PPL (probably splnet)
1930  */
1931 int
1932 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1933 {
1934         struct ng_queue_entry *q;
1935         node_p  dest = NULL;
1936         char   *retaddr = NULL;
1937         int     error;
1938
1939         /* Find the target node. */
1940         error = ng_path2node(here, address, &dest, &retaddr);
1941         if (error) {
1942                 FREE(msg, M_NETGRAPH);
1943                 return (error);
1944         }
1945         if ((q = ng_getqblk()) == NULL) {
1946                 FREE(msg, M_NETGRAPH);
1947                 if (retaddr)
1948                         FREE(retaddr, M_NETGRAPH);
1949                 return (ENOBUFS);
1950         }
1951
1952         /* Fill out the contents */
1953         q->flags = NGQF_MESG;
1954         q->next = NULL;
1955         q->body.msg.msg_node = dest;
1956         q->body.msg.msg_msg = msg;
1957         q->body.msg.msg_retaddr = retaddr;
1958         crit_enter();           /* protect refs and queue */
1959         dest->refs++;           /* don't let it go away while on the queue */
1960
1961         /* Put it on the queue */
1962         if (ngqbase) {
1963                 ngqlast->next = q;
1964         } else {
1965                 ngqbase = q;
1966         }
1967         ngqlast = q;
1968         ngqsize++;
1969         crit_exit();
1970
1971         /* Schedule software interrupt to handle it later */
1972         schednetisr(NETISR_NETGRAPH);
1973         return (0);
1974 }
1975
1976 /*
1977  * Pick an item off the queue, process it, and dispose of the queue entry.
1978  * Should be running at splnet.
1979  */
1980 static int
1981 ngintr(struct netmsg *pmsg)
1982 {
1983         struct mbuf *m = ((struct netmsg_packet *)pmsg)->nm_packet;
1984         hook_p  hook;
1985         struct ng_queue_entry *ngq;
1986         meta_p  meta;
1987         void   *retaddr;
1988         struct ng_mesg *msg;
1989         node_p  node;
1990         int     error = 0;
1991
1992         while (1) {
1993                 crit_enter();
1994                 if ((ngq = ngqbase)) {
1995                         ngqbase = ngq->next;
1996                         ngqsize--;
1997                 }
1998                 crit_exit();
1999                 if (ngq == NULL)
2000                         goto out;
2001                 switch (ngq->flags) {
2002                 case NGQF_DATA:
2003                         hook = ngq->body.data.da_hook;
2004                         m = ngq->body.data.da_m;
2005                         meta = ngq->body.data.da_meta;
2006                         RETURN_QBLK(ngq);
2007                         NG_SEND_DATAQ(error, hook, m, meta);
2008                         ng_unref_hook(hook);
2009                         break;
2010                 case NGQF_MESG:
2011                         node = ngq->body.msg.msg_node;
2012                         msg = ngq->body.msg.msg_msg;
2013                         retaddr = ngq->body.msg.msg_retaddr;
2014                         RETURN_QBLK(ngq);
2015                         if (node->flags & NG_INVALID) {
2016                                 FREE(msg, M_NETGRAPH);
2017                         } else {
2018                                 CALL_MSG_HANDLER(error, node, msg,
2019                                                  retaddr, NULL);
2020                         }
2021                         ng_unref(node);
2022                         if (retaddr)
2023                                 FREE(retaddr, M_NETGRAPH);
2024                         break;
2025                 default:
2026                         RETURN_QBLK(ngq);
2027                 }
2028         }
2029 out:
2030         lwkt_replymsg(&pmsg->nm_lmsg, 0);
2031         return(EASYNC);
2032 }
2033
2034