modules: pull in most of FreeBSD's module linker changes
[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.28 2008/09/24 14:26:39 sephe 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 void     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_TYPESIZ + 3];
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         ksnprintf(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_TYPESIZ + 3];
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         ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
356         if ((lf = linker_find_file_by_name(filename)) == NULL)
357                 return (ENXIO);
358         lf->userrefs--;         /* pretend kldunload'ed */
359         error = linker_file_unload(lf);
360         if (error)
361                 lf->userrefs++;
362
363         return (error);
364 }
365
366 /*
367  * Instantiate a node of the requested type
368  */
369 int
370 ng_make_node(const char *typename, node_p *nodepp)
371 {
372         struct ng_type *type;
373
374         /* Check that the type makes sense */
375         if (typename == NULL) {
376                 TRAP_ERROR;
377                 return (EINVAL);
378         }
379
380         /* Locate the node type */
381         if ((type = ng_findtype(typename)) == NULL)
382                 return (ENXIO);
383
384         /* Call the constructor */
385         if (type->constructor != NULL)
386                 return ((*type->constructor)(nodepp));
387         else
388                 return (ng_make_node_common(type, nodepp));
389 }
390
391 /*
392  * Generic node creation. Called by node constructors.
393  * The returned node has a reference count of 1.
394  */
395 int
396 ng_make_node_common(struct ng_type *type, node_p *nodepp)
397 {
398         node_p node;
399
400         /* Require the node type to have been already installed */
401         if (ng_findtype(type->name) == NULL) {
402                 TRAP_ERROR;
403                 return (EINVAL);
404         }
405
406         /* Make a node and try attach it to the type */
407         MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT | M_ZERO);
408         if (node == NULL) {
409                 TRAP_ERROR;
410                 return (ENOMEM);
411         }
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_NODESIZ; 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 | M_ZERO);
732         if (hook == NULL) {
733                 TRAP_ERROR;
734                 return (ENOMEM);
735         }
736         hook->refs = 1;
737         hook->flags = HK_INVALID;
738         hook->node = node;
739         node->refs++;           /* each hook counts as a reference */
740
741         /* Check if the node type code has something to say about it */
742         if (node->type->newhook != NULL)
743                 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
744                         goto fail;
745
746         /*
747          * The 'type' agrees so far, so go ahead and link it in.
748          * We'll ask again later when we actually connect the hooks.
749          */
750         LIST_INSERT_HEAD(&node->hooks, hook, hooks);
751         node->numhooks++;
752
753         /* Set hook name */
754         MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
755         if (hook->name == NULL) {
756                 error = ENOMEM;
757                 LIST_REMOVE(hook, hooks);
758                 node->numhooks--;
759 fail:
760                 hook->node = NULL;
761                 ng_unref(node);
762                 ng_unref_hook(hook);    /* this frees the hook */
763                 return (error);
764         }
765         strcpy(hook->name, name);
766         if (hookp)
767                 *hookp = hook;
768         return (error);
769 }
770
771 /*
772  * Connect a pair of hooks. Only used internally.
773  */
774 static int
775 ng_connect(hook_p hook1, hook_p hook2)
776 {
777         int     error;
778
779         hook1->peer = hook2;
780         hook2->peer = hook1;
781
782         /* Give each node the opportunity to veto the impending connection */
783         if (hook1->node->type->connect) {
784                 if ((error = (*hook1->node->type->connect) (hook1))) {
785                         ng_destroy_hook(hook1); /* also zaps hook2 */
786                         return (error);
787                 }
788         }
789         if (hook2->node->type->connect) {
790                 if ((error = (*hook2->node->type->connect) (hook2))) {
791                         ng_destroy_hook(hook2); /* also zaps hook1 */
792                         return (error);
793                 }
794         }
795         hook1->flags &= ~HK_INVALID;
796         hook2->flags &= ~HK_INVALID;
797         return (0);
798 }
799
800 /*
801  * Find a hook
802  *
803  * Node types may supply their own optimized routines for finding
804  * hooks.  If none is supplied, we just do a linear search.
805  */
806 hook_p
807 ng_findhook(node_p node, const char *name)
808 {
809         hook_p hook;
810
811         if (node->type->findhook != NULL)
812                 return (*node->type->findhook)(node, name);
813         LIST_FOREACH(hook, &node->hooks, hooks) {
814                 if (hook->name != NULL
815                     && strcmp(hook->name, name) == 0
816                     && (hook->flags & HK_INVALID) == 0)
817                         return (hook);
818         }
819         return (NULL);
820 }
821
822 /*
823  * Destroy a hook
824  *
825  * As hooks are always attached, this really destroys two hooks.
826  * The one given, and the one attached to it. Disconnect the hooks
827  * from each other first.
828  */
829 void
830 ng_destroy_hook(hook_p hook)
831 {
832         hook_p peer = hook->peer;
833
834         hook->flags |= HK_INVALID;              /* as soon as possible */
835         if (peer) {
836                 peer->flags |= HK_INVALID;      /* as soon as possible */
837                 hook->peer = NULL;
838                 peer->peer = NULL;
839                 ng_disconnect_hook(peer);
840         }
841         ng_disconnect_hook(hook);
842 }
843
844 /*
845  * Notify the node of the hook's demise. This may result in more actions
846  * (e.g. shutdown) but we don't do that ourselves and don't know what
847  * happens there. If there is no appropriate handler, then just remove it
848  * (and decrement the reference count of it's node which in turn might
849  * make something happen).
850  */
851 static void
852 ng_disconnect_hook(hook_p hook)
853 {
854         node_p node = hook->node;
855
856         /*
857          * Remove the hook from the node's list to avoid possible recursion
858          * in case the disconnection results in node shutdown.
859          */
860         LIST_REMOVE(hook, hooks);
861         node->numhooks--;
862         if (node->type->disconnect) {
863                 /*
864                  * The type handler may elect to destroy the peer so don't
865                  * trust its existance after this point.
866                  */
867                 (*node->type->disconnect) (hook);
868         }
869         ng_unref(node);         /* might be the last reference */
870         if (hook->name)
871                 FREE(hook->name, M_NETGRAPH);
872         hook->node = NULL;      /* may still be referenced elsewhere */
873         ng_unref_hook(hook);
874 }
875
876 /*
877  * Take two hooks on a node and merge the connection so that the given node
878  * is effectively bypassed.
879  */
880 int
881 ng_bypass(hook_p hook1, hook_p hook2)
882 {
883         if (hook1->node != hook2->node)
884                 return (EINVAL);
885         hook1->peer->peer = hook2->peer;
886         hook2->peer->peer = hook1->peer;
887
888         /* XXX If we ever cache methods on hooks update them as well */
889         hook1->peer = NULL;
890         hook2->peer = NULL;
891         ng_destroy_hook(hook1);
892         ng_destroy_hook(hook2);
893         return (0);
894 }
895
896 /*
897  * Install a new netgraph type
898  */
899 int
900 ng_newtype(struct ng_type *tp)
901 {
902         const size_t namelen = strlen(tp->name);
903
904         /* Check version and type name fields */
905         if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
906                 TRAP_ERROR;
907                 return (EINVAL);
908         }
909
910         /* Check for name collision */
911         if (ng_findtype(tp->name) != NULL) {
912                 TRAP_ERROR;
913                 return (EEXIST);
914         }
915
916         /* Link in new type */
917         LIST_INSERT_HEAD(&typelist, tp, types);
918         tp->refs = 1;   /* first ref is linked list */
919         return (0);
920 }
921
922 /*
923  * Look for a type of the name given
924  */
925 struct ng_type *
926 ng_findtype(const char *typename)
927 {
928         struct ng_type *type;
929
930         LIST_FOREACH(type, &typelist, types) {
931                 if (strcmp(type->name, typename) == 0)
932                         break;
933         }
934         return (type);
935 }
936
937
938 /************************************************************************
939                         Composite routines
940 ************************************************************************/
941
942 /*
943  * Make a peer and connect. The order is arranged to minimise
944  * the work needed to back out in case of error.
945  */
946 int
947 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
948 {
949         node_p  node2;
950         hook_p  hook;
951         hook_p  hook2;
952         int     error;
953
954         if ((error = ng_add_hook(node, name, &hook)))
955                 return (error);
956
957         /* make sure we have the module needed */
958         if (ng_findtype(type) == NULL) {
959                 /* Not found, try to load it as a loadable module */
960                 error = ng_load_module(type);
961                 if (error != 0) {
962                         kprintf("required netgraph module ng_%s not loaded\n",
963                             type);
964                         return (error);
965                 }
966         }
967         if ((error = ng_make_node(type, &node2))) {
968                 ng_destroy_hook(hook);
969                 return (error);
970         }
971         if ((error = ng_add_hook(node2, name2, &hook2))) {
972                 ng_rmnode(node2);
973                 ng_destroy_hook(hook);
974                 return (error);
975         }
976
977         /*
978          * Actually link the two hooks together.. on failure they are
979          * destroyed so we don't have to do that here.
980          */
981         if ((error = ng_connect(hook, hook2)))
982                 ng_rmnode(node2);
983         return (error);
984 }
985
986 /*
987  * Connect two nodes using the specified hooks
988  */
989 int
990 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
991 {
992         int     error;
993         hook_p  hook;
994         hook_p  hook2;
995
996         if ((error = ng_add_hook(node, name, &hook)))
997                 return (error);
998         if ((error = ng_add_hook(node2, name2, &hook2))) {
999                 ng_destroy_hook(hook);
1000                 return (error);
1001         }
1002         return (ng_connect(hook, hook2));
1003 }
1004
1005 /*
1006  * Parse and verify a string of the form:  <NODE:><PATH>
1007  *
1008  * Such a string can refer to a specific node or a specific hook
1009  * on a specific node, depending on how you look at it. In the
1010  * latter case, the PATH component must not end in a dot.
1011  *
1012  * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1013  * of hook names separated by dots. This breaks out the original
1014  * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1015  * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1016  * the final hook component of <PATH>, if any, otherwise NULL.
1017  *
1018  * This returns -1 if the path is malformed. The char ** are optional.
1019  */
1020
1021 int
1022 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1023 {
1024         char   *node, *path, *hook;
1025         int     k;
1026
1027         /*
1028          * Extract absolute NODE, if any
1029          */
1030         for (path = addr; *path && *path != ':'; path++);
1031         if (*path) {
1032                 node = addr;    /* Here's the NODE */
1033                 *path++ = '\0'; /* Here's the PATH */
1034
1035                 /* Node name must not be empty */
1036                 if (!*node)
1037                         return -1;
1038
1039                 /* A name of "." is OK; otherwise '.' not allowed */
1040                 if (strcmp(node, ".") != 0) {
1041                         for (k = 0; node[k]; k++)
1042                                 if (node[k] == '.')
1043                                         return -1;
1044                 }
1045         } else {
1046                 node = NULL;    /* No absolute NODE */
1047                 path = addr;    /* Here's the PATH */
1048         }
1049
1050         /* Snoop for illegal characters in PATH */
1051         for (k = 0; path[k]; k++)
1052                 if (path[k] == ':')
1053                         return -1;
1054
1055         /* Check for no repeated dots in PATH */
1056         for (k = 0; path[k]; k++)
1057                 if (path[k] == '.' && path[k + 1] == '.')
1058                         return -1;
1059
1060         /* Remove extra (degenerate) dots from beginning or end of PATH */
1061         if (path[0] == '.')
1062                 path++;
1063         if (*path && path[strlen(path) - 1] == '.')
1064                 path[strlen(path) - 1] = 0;
1065
1066         /* If PATH has a dot, then we're not talking about a hook */
1067         if (*path) {
1068                 for (hook = path, k = 0; path[k]; k++)
1069                         if (path[k] == '.') {
1070                                 hook = NULL;
1071                                 break;
1072                         }
1073         } else
1074                 path = hook = NULL;
1075
1076         /* Done */
1077         if (nodep)
1078                 *nodep = node;
1079         if (pathp)
1080                 *pathp = path;
1081         if (hookp)
1082                 *hookp = hook;
1083         return (0);
1084 }
1085
1086 /*
1087  * Given a path, which may be absolute or relative, and a starting node,
1088  * return the destination node. Compute the "return address" if desired.
1089  */
1090 int
1091 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1092 {
1093         const   node_p start = here;
1094         char    fullpath[NG_PATHSIZ];
1095         char   *nodename, *path, pbuf[2];
1096         node_p  node;
1097         char   *cp;
1098
1099         /* Initialize */
1100         if (rtnp)
1101                 *rtnp = NULL;
1102         if (destp == NULL)
1103                 return EINVAL;
1104         *destp = NULL;
1105
1106         /* Make a writable copy of address for ng_path_parse() */
1107         strncpy(fullpath, address, sizeof(fullpath) - 1);
1108         fullpath[sizeof(fullpath) - 1] = '\0';
1109
1110         /* Parse out node and sequence of hooks */
1111         if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1112                 TRAP_ERROR;
1113                 return EINVAL;
1114         }
1115         if (path == NULL) {
1116                 pbuf[0] = '.';  /* Needs to be writable */
1117                 pbuf[1] = '\0';
1118                 path = pbuf;
1119         }
1120
1121         /* For an absolute address, jump to the starting node */
1122         if (nodename) {
1123                 node = ng_findname(here, nodename);
1124                 if (node == NULL) {
1125                         TRAP_ERROR;
1126                         return (ENOENT);
1127                 }
1128         } else
1129                 node = here;
1130
1131         /* Now follow the sequence of hooks */
1132         for (cp = path; node != NULL && *cp != '\0'; ) {
1133                 hook_p hook;
1134                 char *segment;
1135
1136                 /*
1137                  * Break out the next path segment. Replace the dot we just
1138                  * found with a NUL; "cp" points to the next segment (or the
1139                  * NUL at the end).
1140                  */
1141                 for (segment = cp; *cp != '\0'; cp++) {
1142                         if (*cp == '.') {
1143                                 *cp++ = '\0';
1144                                 break;
1145                         }
1146                 }
1147
1148                 /* Empty segment */
1149                 if (*segment == '\0')
1150                         continue;
1151
1152                 /* We have a segment, so look for a hook by that name */
1153                 hook = ng_findhook(node, segment);
1154
1155                 /* Can't get there from here... */
1156                 if (hook == NULL
1157                     || hook->peer == NULL
1158                     || (hook->flags & HK_INVALID) != 0) {
1159                         TRAP_ERROR;
1160                         return (ENOENT);
1161                 }
1162
1163                 /* Hop on over to the next node */
1164                 node = hook->peer->node;
1165         }
1166
1167         /* If node somehow missing, fail here (probably this is not needed) */
1168         if (node == NULL) {
1169                 TRAP_ERROR;
1170                 return (ENXIO);
1171         }
1172
1173         /* Now compute return address, i.e., the path to the sender */
1174         if (rtnp != NULL) {
1175                 MALLOC(*rtnp, char *, NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1176                 if (*rtnp == NULL) {
1177                         TRAP_ERROR;
1178                         return (ENOMEM);
1179                 }
1180                 if (start->name != NULL)
1181                         ksprintf(*rtnp, "%s:", start->name);
1182                 else
1183                         ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1184         }
1185
1186         /* Done */
1187         *destp = node;
1188         return (0);
1189 }
1190
1191 /*
1192  * Call the appropriate message handler for the object.
1193  * It is up to the message handler to free the message.
1194  * If it's a generic message, handle it generically, otherwise
1195  * call the type's message handler (if it exists)
1196  * XXX (race). Remember that a queued message may reference a node
1197  * or hook that has just been invalidated. It will exist
1198  * as the queue code is holding a reference, but..
1199  */
1200
1201 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp)               \
1202 do {                                                                    \
1203         if((msg)->header.typecookie == NGM_GENERIC_COOKIE) {            \
1204                 (error) = ng_generic_msg((node), (msg),                 \
1205                                 (retaddr), (resp));                     \
1206         } else {                                                        \
1207                 if ((node)->type->rcvmsg != NULL) {                     \
1208                         (error) = (*(node)->type->rcvmsg)((node),       \
1209                                         (msg), (retaddr), (resp));      \
1210                 } else {                                                \
1211                         TRAP_ERROR;                                     \
1212                         FREE((msg), M_NETGRAPH);                        \
1213                         (error) = EINVAL;                               \
1214                 }                                                       \
1215         }                                                               \
1216 } while (0)
1217
1218
1219 /*
1220  * Send a control message to a node
1221  */
1222 int
1223 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1224             struct ng_mesg **rptr)
1225 {
1226         node_p  dest = NULL;
1227         char   *retaddr = NULL;
1228         int     error;
1229
1230         /* Find the target node */
1231         error = ng_path2node(here, address, &dest, &retaddr);
1232         if (error) {
1233                 FREE(msg, M_NETGRAPH);
1234                 return error;
1235         }
1236
1237         /* Make sure the resp field is null before we start */
1238         if (rptr != NULL)
1239                 *rptr = NULL;
1240
1241         CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1242
1243         /* Make sure that if there is a response, it has the RESP bit set */
1244         if ((error == 0) && rptr && *rptr)
1245                 (*rptr)->header.flags |= NGF_RESP;
1246
1247         /*
1248          * If we had a return address it is up to us to free it. They should
1249          * have taken a copy if they needed to make a delayed response.
1250          */
1251         if (retaddr)
1252                 FREE(retaddr, M_NETGRAPH);
1253         return (error);
1254 }
1255
1256 /*
1257  * Implement the 'generic' control messages
1258  */
1259 static int
1260 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1261                struct ng_mesg **resp)
1262 {
1263         int error = 0;
1264
1265         if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1266                 TRAP_ERROR;
1267                 FREE(msg, M_NETGRAPH);
1268                 return (EINVAL);
1269         }
1270         switch (msg->header.cmd) {
1271         case NGM_SHUTDOWN:
1272                 ng_rmnode(here);
1273                 break;
1274         case NGM_MKPEER:
1275             {
1276                 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1277
1278                 if (msg->header.arglen != sizeof(*mkp)) {
1279                         TRAP_ERROR;
1280                         return (EINVAL);
1281                 }
1282                 mkp->type[sizeof(mkp->type) - 1] = '\0';
1283                 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1284                 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1285                 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1286                 break;
1287             }
1288         case NGM_CONNECT:
1289             {
1290                 struct ngm_connect *const con =
1291                         (struct ngm_connect *) msg->data;
1292                 node_p node2;
1293
1294                 if (msg->header.arglen != sizeof(*con)) {
1295                         TRAP_ERROR;
1296                         return (EINVAL);
1297                 }
1298                 con->path[sizeof(con->path) - 1] = '\0';
1299                 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1300                 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1301                 error = ng_path2node(here, con->path, &node2, NULL);
1302                 if (error)
1303                         break;
1304                 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1305                 break;
1306             }
1307         case NGM_NAME:
1308             {
1309                 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1310
1311                 if (msg->header.arglen != sizeof(*nam)) {
1312                         TRAP_ERROR;
1313                         return (EINVAL);
1314                 }
1315                 nam->name[sizeof(nam->name) - 1] = '\0';
1316                 error = ng_name_node(here, nam->name);
1317                 break;
1318             }
1319         case NGM_RMHOOK:
1320             {
1321                 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1322                 hook_p hook;
1323
1324                 if (msg->header.arglen != sizeof(*rmh)) {
1325                         TRAP_ERROR;
1326                         return (EINVAL);
1327                 }
1328                 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1329                 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1330                         ng_destroy_hook(hook);
1331                 break;
1332             }
1333         case NGM_NODEINFO:
1334             {
1335                 struct nodeinfo *ni;
1336                 struct ng_mesg *rp;
1337
1338                 /* Get response struct */
1339                 if (resp == NULL) {
1340                         error = EINVAL;
1341                         break;
1342                 }
1343                 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1344                 if (rp == NULL) {
1345                         error = ENOMEM;
1346                         break;
1347                 }
1348
1349                 /* Fill in node info */
1350                 ni = (struct nodeinfo *) rp->data;
1351                 if (here->name != NULL)
1352                         strlcpy(ni->name, here->name, NG_NODESIZ);
1353                 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1354                 ni->id = ng_node2ID(here);
1355                 ni->hooks = here->numhooks;
1356                 *resp = rp;
1357                 break;
1358             }
1359         case NGM_LISTHOOKS:
1360             {
1361                 const int nhooks = here->numhooks;
1362                 struct hooklist *hl;
1363                 struct nodeinfo *ni;
1364                 struct ng_mesg *rp;
1365                 hook_p hook;
1366
1367                 /* Get response struct */
1368                 if (resp == NULL) {
1369                         error = EINVAL;
1370                         break;
1371                 }
1372                 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1373                     + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1374                 if (rp == NULL) {
1375                         error = ENOMEM;
1376                         break;
1377                 }
1378                 hl = (struct hooklist *) rp->data;
1379                 ni = &hl->nodeinfo;
1380
1381                 /* Fill in node info */
1382                 if (here->name)
1383                         strlcpy(ni->name, here->name, NG_NODESIZ);
1384                 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1385                 ni->id = ng_node2ID(here);
1386
1387                 /* Cycle through the linked list of hooks */
1388                 ni->hooks = 0;
1389                 LIST_FOREACH(hook, &here->hooks, hooks) {
1390                         struct linkinfo *const link = &hl->link[ni->hooks];
1391
1392                         if (ni->hooks >= nhooks) {
1393                                 log(LOG_ERR, "%s: number of %s changed\n",
1394                                     __func__, "hooks");
1395                                 break;
1396                         }
1397                         if ((hook->flags & HK_INVALID) != 0)
1398                                 continue;
1399                         strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1400                         strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1401                         if (hook->peer->node->name != NULL)
1402                                 strlcpy(link->nodeinfo.name,
1403                                     hook->peer->node->name, NG_NODESIZ);
1404                         strlcpy(link->nodeinfo.type,
1405                            hook->peer->node->type->name, NG_TYPESIZ);
1406                         link->nodeinfo.id = ng_node2ID(hook->peer->node);
1407                         link->nodeinfo.hooks = hook->peer->node->numhooks;
1408                         ni->hooks++;
1409                 }
1410                 *resp = rp;
1411                 break;
1412             }
1413
1414         case NGM_LISTNAMES:
1415         case NGM_LISTNODES:
1416             {
1417                 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1418                 struct namelist *nl;
1419                 struct ng_mesg *rp;
1420                 node_p node;
1421                 int num = 0;
1422
1423                 if (resp == NULL) {
1424                         error = EINVAL;
1425                         break;
1426                 }
1427
1428                 /* Count number of nodes */
1429                 LIST_FOREACH(node, &nodelist, nodes) {
1430                         if ((node->flags & NG_INVALID) == 0
1431                             && (unnamed || node->name != NULL))
1432                                 num++;
1433                 }
1434
1435                 /* Get response struct */
1436                 if (resp == NULL) {
1437                         error = EINVAL;
1438                         break;
1439                 }
1440                 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1441                     + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1442                 if (rp == NULL) {
1443                         error = ENOMEM;
1444                         break;
1445                 }
1446                 nl = (struct namelist *) rp->data;
1447
1448                 /* Cycle through the linked list of nodes */
1449                 nl->numnames = 0;
1450                 LIST_FOREACH(node, &nodelist, nodes) {
1451                         struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1452
1453                         if (nl->numnames >= num) {
1454                                 log(LOG_ERR, "%s: number of %s changed\n",
1455                                     __func__, "nodes");
1456                                 break;
1457                         }
1458                         if ((node->flags & NG_INVALID) != 0)
1459                                 continue;
1460                         if (!unnamed && node->name == NULL)
1461                                 continue;
1462                         if (node->name != NULL)
1463                                 strlcpy(np->name, node->name, NG_NODESIZ);
1464                         strlcpy(np->type, node->type->name, NG_TYPESIZ);
1465                         np->id = ng_node2ID(node);
1466                         np->hooks = node->numhooks;
1467                         nl->numnames++;
1468                 }
1469                 *resp = rp;
1470                 break;
1471             }
1472
1473         case NGM_LISTTYPES:
1474             {
1475                 struct typelist *tl;
1476                 struct ng_mesg *rp;
1477                 struct ng_type *type;
1478                 int num = 0;
1479
1480                 if (resp == NULL) {
1481                         error = EINVAL;
1482                         break;
1483                 }
1484
1485                 /* Count number of types */
1486                 LIST_FOREACH(type, &typelist, types)
1487                         num++;
1488
1489                 /* Get response struct */
1490                 if (resp == NULL) {
1491                         error = EINVAL;
1492                         break;
1493                 }
1494                 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1495                     + (num * sizeof(struct typeinfo)), M_NOWAIT);
1496                 if (rp == NULL) {
1497                         error = ENOMEM;
1498                         break;
1499                 }
1500                 tl = (struct typelist *) rp->data;
1501
1502                 /* Cycle through the linked list of types */
1503                 tl->numtypes = 0;
1504                 LIST_FOREACH(type, &typelist, types) {
1505                         struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1506
1507                         if (tl->numtypes >= num) {
1508                                 log(LOG_ERR, "%s: number of %s changed\n",
1509                                     __func__, "types");
1510                                 break;
1511                         }
1512                         strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1513                         tp->numnodes = type->refs - 1; /* don't count list */
1514                         tl->numtypes++;
1515                 }
1516                 *resp = rp;
1517                 break;
1518             }
1519
1520         case NGM_BINARY2ASCII:
1521             {
1522                 int bufSize = 20 * 1024;        /* XXX hard coded constant */
1523                 const struct ng_parse_type *argstype;
1524                 const struct ng_cmdlist *c;
1525                 struct ng_mesg *rp, *binary, *ascii;
1526
1527                 /* Data area must contain a valid netgraph message */
1528                 binary = (struct ng_mesg *)msg->data;
1529                 if (msg->header.arglen < sizeof(struct ng_mesg)
1530                     || msg->header.arglen - sizeof(struct ng_mesg) 
1531                       < binary->header.arglen) {
1532                         error = EINVAL;
1533                         break;
1534                 }
1535
1536                 /* Get a response message with lots of room */
1537                 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1538                 if (rp == NULL) {
1539                         error = ENOMEM;
1540                         break;
1541                 }
1542                 ascii = (struct ng_mesg *)rp->data;
1543
1544                 /* Copy binary message header to response message payload */
1545                 bcopy(binary, ascii, sizeof(*binary));
1546
1547                 /* Find command by matching typecookie and command number */
1548                 for (c = here->type->cmdlist;
1549                     c != NULL && c->name != NULL; c++) {
1550                         if (binary->header.typecookie == c->cookie
1551                             && binary->header.cmd == c->cmd)
1552                                 break;
1553                 }
1554                 if (c == NULL || c->name == NULL) {
1555                         for (c = ng_generic_cmds; c->name != NULL; c++) {
1556                                 if (binary->header.typecookie == c->cookie
1557                                     && binary->header.cmd == c->cmd)
1558                                         break;
1559                         }
1560                         if (c->name == NULL) {
1561                                 FREE(rp, M_NETGRAPH);
1562                                 error = ENOSYS;
1563                                 break;
1564                         }
1565                 }
1566
1567                 /* Convert command name to ASCII */
1568                 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1569                     "%s", c->name);
1570
1571                 /* Convert command arguments to ASCII */
1572                 argstype = (binary->header.flags & NGF_RESP) ?
1573                     c->respType : c->mesgType;
1574                 if (argstype == NULL)
1575                         *ascii->data = '\0';
1576                 else {
1577                         if ((error = ng_unparse(argstype,
1578                             (u_char *)binary->data,
1579                             ascii->data, bufSize)) != 0) {
1580                                 FREE(rp, M_NETGRAPH);
1581                                 break;
1582                         }
1583                 }
1584
1585                 /* Return the result as struct ng_mesg plus ASCII string */
1586                 bufSize = strlen(ascii->data) + 1;
1587                 ascii->header.arglen = bufSize;
1588                 rp->header.arglen = sizeof(*ascii) + bufSize;
1589                 *resp = rp;
1590                 break;
1591             }
1592
1593         case NGM_ASCII2BINARY:
1594             {
1595                 int bufSize = 2000;     /* XXX hard coded constant */
1596                 const struct ng_cmdlist *c;
1597                 const struct ng_parse_type *argstype;
1598                 struct ng_mesg *rp, *ascii, *binary;
1599                 int off = 0;
1600
1601                 /* Data area must contain at least a struct ng_mesg + '\0' */
1602                 ascii = (struct ng_mesg *)msg->data;
1603                 if (msg->header.arglen < sizeof(*ascii) + 1
1604                     || ascii->header.arglen < 1
1605                     || msg->header.arglen
1606                       < sizeof(*ascii) + ascii->header.arglen) {
1607                         error = EINVAL;
1608                         break;
1609                 }
1610                 ascii->data[ascii->header.arglen - 1] = '\0';
1611
1612                 /* Get a response message with lots of room */
1613                 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1614                 if (rp == NULL) {
1615                         error = ENOMEM;
1616                         break;
1617                 }
1618                 binary = (struct ng_mesg *)rp->data;
1619
1620                 /* Copy ASCII message header to response message payload */
1621                 bcopy(ascii, binary, sizeof(*ascii));
1622
1623                 /* Find command by matching ASCII command string */
1624                 for (c = here->type->cmdlist;
1625                     c != NULL && c->name != NULL; c++) {
1626                         if (strcmp(ascii->header.cmdstr, c->name) == 0)
1627                                 break;
1628                 }
1629                 if (c == NULL || c->name == NULL) {
1630                         for (c = ng_generic_cmds; c->name != NULL; c++) {
1631                                 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1632                                         break;
1633                         }
1634                         if (c->name == NULL) {
1635                                 FREE(rp, M_NETGRAPH);
1636                                 error = ENOSYS;
1637                                 break;
1638                         }
1639                 }
1640
1641                 /* Convert command name to binary */
1642                 binary->header.cmd = c->cmd;
1643                 binary->header.typecookie = c->cookie;
1644
1645                 /* Convert command arguments to binary */
1646                 argstype = (binary->header.flags & NGF_RESP) ?
1647                     c->respType : c->mesgType;
1648                 if (argstype == NULL)
1649                         bufSize = 0;
1650                 else {
1651                         if ((error = ng_parse(argstype, ascii->data,
1652                             &off, (u_char *)binary->data, &bufSize)) != 0) {
1653                                 FREE(rp, M_NETGRAPH);
1654                                 break;
1655                         }
1656                 }
1657
1658                 /* Return the result */
1659                 binary->header.arglen = bufSize;
1660                 rp->header.arglen = sizeof(*binary) + bufSize;
1661                 *resp = rp;
1662                 break;
1663             }
1664
1665         case NGM_TEXT_CONFIG:
1666         case NGM_TEXT_STATUS:
1667                 /*
1668                  * This one is tricky as it passes the command down to the
1669                  * actual node, even though it is a generic type command.
1670                  * This means we must assume that the msg is already freed
1671                  * when control passes back to us.
1672                  */
1673                 if (resp == NULL) {
1674                         error = EINVAL;
1675                         break;
1676                 }
1677                 if (here->type->rcvmsg != NULL)
1678                         return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1679                 /* Fall through if rcvmsg not supported */
1680         default:
1681                 TRAP_ERROR;
1682                 error = EINVAL;
1683         }
1684         FREE(msg, M_NETGRAPH);
1685         return (error);
1686 }
1687
1688 /*
1689  * Send a data packet to a node. If the recipient has no
1690  * 'receive data' method, then silently discard the packet.
1691  */
1692 int 
1693 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1694 {
1695         int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1696         int error;
1697
1698         CHECK_DATA_MBUF(m);
1699         if (hook && (hook->flags & HK_INVALID) == 0) {
1700                 rcvdata = hook->peer->node->type->rcvdata;
1701                 if (rcvdata != NULL)
1702                         error = (*rcvdata)(hook->peer, m, meta);
1703                 else {
1704                         error = 0;
1705                         NG_FREE_DATA(m, meta);
1706                 }
1707         } else {
1708                 TRAP_ERROR;
1709                 error = ENOTCONN;
1710                 NG_FREE_DATA(m, meta);
1711         }
1712         return (error);
1713 }
1714
1715 /*
1716  * Send a queued data packet to a node. If the recipient has no
1717  * 'receive queued data' method, then try the 'receive data' method above.
1718  */
1719 int 
1720 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1721 {
1722         int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1723         int error;
1724
1725         CHECK_DATA_MBUF(m);
1726         if (hook && (hook->flags & HK_INVALID) == 0) {
1727                 rcvdataq = hook->peer->node->type->rcvdataq;
1728                 if (rcvdataq != NULL)
1729                         error = (*rcvdataq)(hook->peer, m, meta);
1730                 else {
1731                         error = ng_send_data(hook, m, meta);
1732                 }
1733         } else {
1734                 TRAP_ERROR;
1735                 error = ENOTCONN;
1736                 NG_FREE_DATA(m, meta);
1737         }
1738         return (error);
1739 }
1740
1741 /*
1742  * Copy a 'meta'.
1743  *
1744  * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1745  */
1746 meta_p
1747 ng_copy_meta(meta_p meta)
1748 {
1749         meta_p meta2;
1750
1751         if (meta == NULL)
1752                 return (NULL);
1753         MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1754         if (meta2 == NULL)
1755                 return (NULL);
1756         meta2->allocated_len = meta->used_len;
1757         bcopy(meta, meta2, meta->used_len);
1758         return (meta2);
1759 }
1760
1761 /************************************************************************
1762                         Module routines
1763 ************************************************************************/
1764
1765 /*
1766  * Handle the loading/unloading of a netgraph node type module
1767  */
1768 int
1769 ng_mod_event(module_t mod, int event, void *data)
1770 {
1771         struct ng_type *const type = data;
1772         int error = 0;
1773
1774         switch (event) {
1775         case MOD_LOAD:
1776
1777                 /* Register new netgraph node type */
1778                 crit_enter();
1779                 if ((error = ng_newtype(type)) != 0) {
1780                         crit_exit();
1781                         break;
1782                 }
1783
1784                 /* Call type specific code */
1785                 if (type->mod_event != NULL)
1786                         if ((error = (*type->mod_event)(mod, event, data))) {
1787                                 type->refs--;   /* undo it */
1788                                 LIST_REMOVE(type, types);
1789                         }
1790                 crit_exit();
1791                 break;
1792
1793         case MOD_UNLOAD:
1794                 crit_enter();
1795                 if (type->refs > 1) {           /* make sure no nodes exist! */
1796                         error = EBUSY;
1797                 } else {
1798                         if (type->refs == 0) {
1799                                 /* failed load, nothing to undo */
1800                                 crit_exit();
1801                                 break;
1802                         }
1803                         if (type->mod_event != NULL) {  /* check with type */
1804                                 error = (*type->mod_event)(mod, event, data);
1805                                 if (error != 0) {       /* type refuses.. */
1806                                         crit_exit();
1807                                         break;
1808                                 }
1809                         }
1810                         LIST_REMOVE(type, types);
1811                 }
1812                 crit_exit();
1813                 break;
1814
1815         default:
1816                 if (type->mod_event != NULL)
1817                         error = (*type->mod_event)(mod, event, data);
1818                 else
1819                         error = 0;              /* XXX ? */
1820                 break;
1821         }
1822         return (error);
1823 }
1824
1825 /*
1826  * Handle loading and unloading for this code.
1827  * The only thing we need to link into is the NETISR strucure.
1828  */
1829 static int
1830 ngb_mod_event(module_t mod, int event, void *data)
1831 {
1832         int error = 0;
1833
1834         switch (event) {
1835         case MOD_LOAD:
1836                 /* Register line discipline */
1837                 crit_enter();
1838                 error = ng_load_module("ksocket");
1839                 if (error != 0) {
1840                         crit_exit();
1841                         break;
1842                 }
1843                 netisr_register(NETISR_NETGRAPH, cpu0_portfn,
1844                                 pktinfo_portfn_notsupp, ngintr,
1845                                 NETISR_FLAG_NOTMPSAFE);
1846                 error = 0;
1847                 crit_exit();
1848                 break;
1849         case MOD_UNLOAD:
1850                 ng_unload_module("ksocket");
1851                 /* You cant unload it because an interface may be using it.  */
1852                 error = EBUSY;
1853                 break;
1854         default:
1855                 error = EOPNOTSUPP;
1856                 break;
1857         }
1858         return (error);
1859 }
1860
1861 static moduledata_t netgraph_mod = {
1862         "netgraph",
1863         ngb_mod_event,
1864         (NULL)
1865 };
1866 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1867 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1868 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1869 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1870
1871 /************************************************************************
1872                         Queueing routines
1873 ************************************************************************/
1874
1875 /* The structure for queueing across ISR switches */
1876 struct ng_queue_entry {
1877         u_long  flags;
1878         struct ng_queue_entry *next;
1879         union {
1880                 struct {
1881                         hook_p          da_hook;        /*  target hook */
1882                         struct mbuf     *da_m;
1883                         meta_p          da_meta;
1884                 } data;
1885                 struct {
1886                         struct ng_mesg  *msg_msg;
1887                         node_p          msg_node;
1888                         void            *msg_retaddr;
1889                 } msg;
1890         } body;
1891 };
1892 #define NGQF_DATA       0x01            /* the queue element is data */
1893 #define NGQF_MESG       0x02            /* the queue element is a message */
1894
1895 static struct ng_queue_entry   *ngqbase;        /* items to be unqueued */
1896 static struct ng_queue_entry   *ngqlast;        /* last item queued */
1897 static const int                ngqroom = 256;  /* max items to queue */
1898 static int                      ngqsize;        /* number of items in queue */
1899
1900 static struct ng_queue_entry   *ngqfree;        /* free ones */
1901 static const int                ngqfreemax = 256;/* cache at most this many */
1902 static int                      ngqfreesize;    /* number of cached entries */
1903
1904 /*
1905  * Get a queue entry
1906  */
1907 static struct ng_queue_entry *
1908 ng_getqblk(void)
1909 {
1910         struct ng_queue_entry *q;
1911
1912         /* Could be guarding against tty ints or whatever */
1913         crit_enter();
1914
1915         /* Try get a cached queue block, or else allocate a new one */
1916         if ((q = ngqfree) == NULL) {
1917                 crit_exit();
1918                 if (ngqsize < ngqroom) {        /* don't worry about races */
1919                         MALLOC(q, struct ng_queue_entry *,
1920                             sizeof(*q), M_NETGRAPH, M_NOWAIT);
1921                 }
1922         } else {
1923                 ngqfree = q->next;
1924                 ngqfreesize--;
1925                 crit_exit();
1926         }
1927         return (q);
1928 }
1929
1930 /*
1931  * Release a queue entry
1932  */
1933 #define RETURN_QBLK(q)                                                  \
1934 do {                                                                    \
1935         if (ngqfreesize < ngqfreemax) { /* don't worry about races */   \
1936                 crit_enter();                                           \
1937                 (q)->next = ngqfree;                                    \
1938                 ngqfree = (q);                                          \
1939                 ngqfreesize++;                                          \
1940                 crit_exit();                                            \
1941         } else {                                                        \
1942                 FREE((q), M_NETGRAPH);                                  \
1943         }                                                               \
1944 } while (0)
1945
1946 /*
1947  * Running at a raised (but we don't know which) processor priority level,
1948  * put the data onto a queue to be picked up by another PPL (probably splnet)
1949  */
1950 int
1951 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1952 {
1953         struct ng_queue_entry *q;
1954
1955         if (hook == NULL) {
1956                 NG_FREE_DATA(m, meta);
1957                 return (0);
1958         }
1959         if ((q = ng_getqblk()) == NULL) {
1960                 NG_FREE_DATA(m, meta);
1961                 return (ENOBUFS);
1962         }
1963
1964         /* Fill out the contents */
1965         q->flags = NGQF_DATA;
1966         q->next = NULL;
1967         q->body.data.da_hook = hook;
1968         q->body.data.da_m = m;
1969         q->body.data.da_meta = meta;
1970         crit_enter();           /* protect refs and queue */
1971         hook->refs++;           /* don't let it go away while on the queue */
1972
1973         /* Put it on the queue */
1974         if (ngqbase) {
1975                 ngqlast->next = q;
1976         } else {
1977                 ngqbase = q;
1978         }
1979         ngqlast = q;
1980         ngqsize++;
1981         crit_exit();
1982
1983         /* Schedule software interrupt to handle it later */
1984         schednetisr(NETISR_NETGRAPH);
1985         return (0);
1986 }
1987
1988 /*
1989  * Running at a raised (but we don't know which) processor priority level,
1990  * put the msg onto a queue to be picked up by another PPL (probably splnet)
1991  */
1992 int
1993 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1994 {
1995         struct ng_queue_entry *q;
1996         node_p  dest = NULL;
1997         char   *retaddr = NULL;
1998         int     error;
1999
2000         /* Find the target node. */
2001         error = ng_path2node(here, address, &dest, &retaddr);
2002         if (error) {
2003                 FREE(msg, M_NETGRAPH);
2004                 return (error);
2005         }
2006         if ((q = ng_getqblk()) == NULL) {
2007                 FREE(msg, M_NETGRAPH);
2008                 if (retaddr)
2009                         FREE(retaddr, M_NETGRAPH);
2010                 return (ENOBUFS);
2011         }
2012
2013         /* Fill out the contents */
2014         q->flags = NGQF_MESG;
2015         q->next = NULL;
2016         q->body.msg.msg_node = dest;
2017         q->body.msg.msg_msg = msg;
2018         q->body.msg.msg_retaddr = retaddr;
2019         crit_enter();           /* protect refs and queue */
2020         dest->refs++;           /* don't let it go away while on the queue */
2021
2022         /* Put it on the queue */
2023         if (ngqbase) {
2024                 ngqlast->next = q;
2025         } else {
2026                 ngqbase = q;
2027         }
2028         ngqlast = q;
2029         ngqsize++;
2030         crit_exit();
2031
2032         /* Schedule software interrupt to handle it later */
2033         schednetisr(NETISR_NETGRAPH);
2034         return (0);
2035 }
2036
2037 /*
2038  * Pick an item off the queue, process it, and dispose of the queue entry.
2039  */
2040 static void
2041 ngintr(struct netmsg *pmsg)
2042 {
2043         hook_p  hook;
2044         struct mbuf *m;
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         /*
2053          * Packets are never sent to this netisr so the message must always
2054          * be replied.  Interlock processing and notification by replying
2055          * the message first.
2056          */
2057         lwkt_replymsg(&pmsg->nm_lmsg, 0);
2058
2059         while (1) {
2060                 crit_enter();
2061                 if ((ngq = ngqbase)) {
2062                         ngqbase = ngq->next;
2063                         ngqsize--;
2064                 }
2065                 crit_exit();
2066                 if (ngq == NULL)
2067                         goto out;
2068                 switch (ngq->flags) {
2069                 case NGQF_DATA:
2070                         hook = ngq->body.data.da_hook;
2071                         m = ngq->body.data.da_m;
2072                         meta = ngq->body.data.da_meta;
2073                         RETURN_QBLK(ngq);
2074                         NG_SEND_DATAQ(error, hook, m, meta);
2075                         ng_unref_hook(hook);
2076                         break;
2077                 case NGQF_MESG:
2078                         node = ngq->body.msg.msg_node;
2079                         msg = ngq->body.msg.msg_msg;
2080                         retaddr = ngq->body.msg.msg_retaddr;
2081                         RETURN_QBLK(ngq);
2082                         if (node->flags & NG_INVALID) {
2083                                 FREE(msg, M_NETGRAPH);
2084                         } else {
2085                                 CALL_MSG_HANDLER(error, node, msg,
2086                                                  retaddr, NULL);
2087                         }
2088                         ng_unref(node);
2089                         if (retaddr)
2090                                 FREE(retaddr, M_NETGRAPH);
2091                         break;
2092                 default:
2093                         RETURN_QBLK(ngq);
2094                 }
2095         }
2096 out:
2097         ;
2098 }
2099
2100