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