5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
37 * Authors: Julian Elischer <julian@freebsd.org>
38 * Archie Cobbs <archie@freebsd.org>
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 $
46 * This file implements the base netgraph code.
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>
58 #include <sys/ctype.h>
59 #include <sys/sysctl.h>
60 #include <sys/vnode.h>
61 #include <machine/limits.h>
63 #include <sys/thread2.h>
64 #include <sys/msgport2.h>
65 #include <sys/mplock2.h>
67 #include <net/netisr.h>
69 #include <netgraph/ng_message.h>
70 #include <netgraph/netgraph.h>
71 #include <netgraph/ng_parse.h>
73 MODULE_VERSION(netgraph, NG_ABI_VERSION);
77 /* List of all nodes */
78 static LIST_HEAD(, ng_node) nodelist;
80 /* List of installed types */
81 static LIST_HEAD(, ng_type) typelist;
83 /* Hash releted definitions */
84 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
85 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
86 /* Don't nead to initialise them because it's a LIST */
88 /* Internal functions */
89 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
90 static int ng_connect(hook_p hook1, hook_p hook2);
91 static void ng_disconnect_hook(hook_p hook);
92 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
93 const char *retaddr, struct ng_mesg ** resp);
94 static ng_ID_t ng_decodeidname(const char *name);
95 static int ngb_mod_event(module_t mod, int event, void *data);
96 static void ngintr(union netmsg *);
97 static int ng_load_module(const char *);
98 static int ng_unload_module(const char *);
100 /* Our own netgraph malloc type */
101 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
103 /* Set this to Debugger("X") to catch all errors as they occur */
108 static ng_ID_t nextID = 1;
111 #define CHECK_DATA_MBUF(m) do { \
115 if (((m)->m_flags & M_PKTHDR) == 0) \
116 panic("%s: !PKTHDR", __func__); \
117 for (total = 0, n = (m); n != NULL; n = n->m_next) \
119 if ((m)->m_pkthdr.len != total) { \
120 panic("%s: %d != %d", \
121 __func__, (m)->m_pkthdr.len, total); \
125 #define CHECK_DATA_MBUF(m)
129 /************************************************************************
130 Parse type definitions for generic messages
131 ************************************************************************/
133 /* Handy structure parse type defining macro */
134 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
135 static const struct ng_parse_struct_field \
136 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
137 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
138 &ng_parse_struct_type, \
139 &ng_ ## lo ## _type_fields \
142 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
143 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
144 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
145 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
146 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
147 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
148 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
150 /* Get length of an array when the length is stored as a 32 bit
151 value immediately preceeding the array -- as with struct namelist
152 and struct typelist. */
154 ng_generic_list_getLength(const struct ng_parse_type *type,
155 const u_char *start, const u_char *buf)
157 return *((const u_int32_t *)(buf - 4));
160 /* Get length of the array of struct linkinfo inside a struct hooklist */
162 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
163 const u_char *start, const u_char *buf)
165 const struct hooklist *hl = (const struct hooklist *)start;
167 return hl->nodeinfo.hooks;
170 /* Array type for a variable length array of struct namelist */
171 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
172 &ng_generic_nodeinfo_type,
173 &ng_generic_list_getLength
175 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
176 &ng_parse_array_type,
177 &ng_nodeinfoarray_type_info
180 /* Array type for a variable length array of struct typelist */
181 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
182 &ng_generic_typeinfo_type,
183 &ng_generic_list_getLength
185 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
186 &ng_parse_array_type,
187 &ng_typeinfoarray_type_info
190 /* Array type for array of struct linkinfo in struct hooklist */
191 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
192 &ng_generic_linkinfo_type,
193 &ng_generic_linkinfo_getLength
195 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
196 &ng_parse_array_type,
197 &ng_generic_linkinfo_array_type_info
200 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
201 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
202 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
203 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
204 (&ng_generic_nodeinfoarray_type));
206 /* List of commands and how to convert arguments to/from ASCII */
207 static const struct ng_cmdlist ng_generic_cmds[] = {
219 &ng_generic_mkpeer_type,
226 &ng_generic_connect_type,
233 &ng_generic_name_type,
240 &ng_generic_rmhook_type,
248 &ng_generic_nodeinfo_type
255 &ng_generic_hooklist_type
262 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
269 &ng_generic_listnodes_type
276 &ng_generic_typeinfo_type
283 &ng_parse_string_type
290 &ng_parse_string_type
296 &ng_parse_ng_mesg_type,
297 &ng_parse_ng_mesg_type
303 &ng_parse_ng_mesg_type,
304 &ng_parse_ng_mesg_type
309 /************************************************************************
311 ************************************************************************/
314 linker_api_available(void)
316 /* linker_* API won't work without a process context */
320 * nlookup_init() relies on namei_oc to be initialized,
321 * but it's not when the netgraph module is loaded during boot.
323 if (namei_oc == NULL)
329 ng_load_module(const char *name)
331 char *path, filename[NG_TYPESIZ + 3];
335 if (!linker_api_available())
338 /* Not found, try to load it as a loadable module */
339 ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
340 if ((path = linker_search_path(filename)) == NULL)
342 error = linker_load_file(path, &lf);
343 FREE(path, M_LINKER);
345 lf->userrefs++; /* pretend kldload'ed */
350 ng_unload_module(const char *name)
352 char filename[NG_TYPESIZ + 3];
356 if (!linker_api_available())
359 /* Not found, try to load it as a loadable module */
360 ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
361 if ((lf = linker_find_file_by_name(filename)) == NULL)
363 lf->userrefs--; /* pretend kldunload'ed */
364 error = linker_file_unload(lf);
372 * Instantiate a node of the requested type
375 ng_make_node(const char *typename, node_p *nodepp)
377 struct ng_type *type;
379 /* Check that the type makes sense */
380 if (typename == NULL) {
385 /* Locate the node type */
386 if ((type = ng_findtype(typename)) == NULL)
389 /* Call the constructor */
390 if (type->constructor != NULL)
391 return ((*type->constructor)(nodepp));
393 return (ng_make_node_common(type, nodepp));
397 * Generic node creation. Called by node constructors.
398 * The returned node has a reference count of 1.
401 ng_make_node_common(struct ng_type *type, node_p *nodepp)
405 /* Require the node type to have been already installed */
406 if (ng_findtype(type->name) == NULL) {
411 /* Make a node and try attach it to the type */
412 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT | M_ZERO);
418 node->refs++; /* note reference */
421 /* Link us into the node linked list */
422 LIST_INSERT_HEAD(&nodelist, node, nodes);
424 /* Initialize hook list for new node */
425 LIST_INIT(&node->hooks);
427 /* get an ID and put us in the hash chain */
428 node->ID = nextID++; /* 137 per second for 1 year before wrap */
429 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
437 * Forceably start the shutdown process on a node. Either call
438 * it's shutdown method, or do the default shutdown if there is
439 * no type-specific method.
441 * Persistent nodes must have a type-specific method which
442 * resets the NG_INVALID flag.
445 ng_rmnode(node_p node)
447 /* Check if it's already shutting down */
448 if ((node->flags & NG_INVALID) != 0)
451 /* Add an extra reference so it doesn't go away during this */
454 /* Mark it invalid so any newcomers know not to try use it */
455 node->flags |= NG_INVALID;
457 /* Ask the type if it has anything to do in this case */
458 if (node->type && node->type->shutdown)
459 (*node->type->shutdown)(node);
460 else { /* do the default thing */
466 /* Remove extra reference, possibly the last */
471 * Called by the destructor to remove any STANDARD external references
474 ng_cutlinks(node_p node)
478 /* Make sure that this is set to stop infinite loops */
479 node->flags |= NG_INVALID;
481 /* If we have sleepers, wake them up; they'll see NG_INVALID */
485 /* Notify all remaining connected nodes to disconnect */
486 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
487 ng_destroy_hook(hook);
491 * Remove a reference to the node, possibly the last
494 ng_unref(node_p node)
497 if (--node->refs <= 0) {
499 LIST_REMOVE(node, nodes);
500 LIST_REMOVE(node, idnodes);
501 FREE(node, M_NETGRAPH);
507 * Wait for a node to come ready. Returns a node with a reference count;
508 * don't forget to drop it when we are done with it using ng_release_node().
511 ng_wait_node(node_p node, char *msg)
519 node->refs++; /* the sleeping process counts as a reference */
520 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
521 error = tsleep(node, PCATCH, msg, 0);
523 if (node->flags & NG_INVALID) {
527 KASSERT(node->refs > 1,
528 ("%s: refs=%d", __func__, node->refs));
529 node->flags |= NG_BUSY;
533 /* Release the reference we had on it */
540 * Release a node acquired via ng_wait_node()
543 ng_release_node(node_p node)
545 /* Declare that we don't want it */
546 node->flags &= ~NG_BUSY;
548 /* If we have sleepers, then wake them up */
552 /* We also have a reference.. drop it too */
556 /************************************************************************
558 ************************************************************************/
560 ng_ID2node(ng_ID_t ID)
563 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
564 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
571 ng_node2ID(node_p node)
576 /************************************************************************
578 ************************************************************************/
581 * Assign a node a name. Once assigned, the name cannot be changed.
584 ng_name_node(node_p node, const char *name)
588 /* Check the name is valid */
589 for (i = 0; i < NG_NODESIZ; i++) {
590 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
593 if (i == 0 || name[i] != '\0') {
597 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
602 /* Check the node isn't already named */
603 if (node->name != NULL) {
608 /* Check the name isn't already being used */
609 if (ng_findname(node, name) != NULL) {
614 /* Allocate space and copy it */
615 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
616 if (node->name == NULL) {
620 strcpy(node->name, name);
622 /* The name counts as a reference */
628 * Find a node by absolute name. The name should NOT end with ':'
629 * The name "." means "this node" and "[xxx]" means "the node
630 * with ID (ie, at address) xxx".
632 * Returns the node if found, else NULL.
635 ng_findname(node_p this, const char *name)
640 /* "." means "this node" */
641 if (strcmp(name, ".") == 0)
644 /* Check for name-by-ID */
645 if ((temp = ng_decodeidname(name)) != 0) {
646 return (ng_ID2node(temp));
649 /* Find node by name */
650 LIST_FOREACH(node, &nodelist, nodes) {
651 if ((node->name != NULL)
652 && (strcmp(node->name, name) == 0)
653 && ((node->flags & NG_INVALID) == 0))
660 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
661 * string is not valid, otherwise returns the value.
664 ng_decodeidname(const char *name)
666 const int len = strlen(name);
670 /* Check for proper length, brackets, no leading junk */
671 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
672 || !isxdigit(name[1]))
676 val = strtoul(name + 1, &eptr, 16);
677 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
683 * Remove a name from a node. This should only be called
684 * when shutting down and removing the node.
687 ng_unname(node_p node)
690 FREE(node->name, M_NETGRAPH);
696 /************************************************************************
699 Names are not optional. Hooks are always connected, except for a
700 brief moment within these routines.
702 ************************************************************************/
705 * Remove a hook reference
708 ng_unref_hook(hook_p hook)
711 if (--hook->refs == 0)
712 FREE(hook, M_NETGRAPH);
717 * Add an unconnected hook to a node. Only used internally.
720 ng_add_hook(node_p node, const char *name, hook_p *hookp)
725 /* Check that the given name is good */
730 if (ng_findhook(node, name) != NULL) {
735 /* Allocate the hook and link it up */
736 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT | M_ZERO);
742 hook->flags = HK_INVALID;
744 node->refs++; /* each hook counts as a reference */
746 /* Check if the node type code has something to say about it */
747 if (node->type->newhook != NULL)
748 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
752 * The 'type' agrees so far, so go ahead and link it in.
753 * We'll ask again later when we actually connect the hooks.
755 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
759 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
760 if (hook->name == NULL) {
762 LIST_REMOVE(hook, hooks);
767 ng_unref_hook(hook); /* this frees the hook */
770 strcpy(hook->name, name);
777 * Connect a pair of hooks. Only used internally.
780 ng_connect(hook_p hook1, hook_p hook2)
787 /* Give each node the opportunity to veto the impending connection */
788 if (hook1->node->type->connect) {
789 if ((error = (*hook1->node->type->connect) (hook1))) {
790 ng_destroy_hook(hook1); /* also zaps hook2 */
794 if (hook2->node->type->connect) {
795 if ((error = (*hook2->node->type->connect) (hook2))) {
796 ng_destroy_hook(hook2); /* also zaps hook1 */
800 hook1->flags &= ~HK_INVALID;
801 hook2->flags &= ~HK_INVALID;
808 * Node types may supply their own optimized routines for finding
809 * hooks. If none is supplied, we just do a linear search.
812 ng_findhook(node_p node, const char *name)
816 if (node->type->findhook != NULL)
817 return (*node->type->findhook)(node, name);
818 LIST_FOREACH(hook, &node->hooks, hooks) {
819 if (hook->name != NULL
820 && strcmp(hook->name, name) == 0
821 && (hook->flags & HK_INVALID) == 0)
830 * As hooks are always attached, this really destroys two hooks.
831 * The one given, and the one attached to it. Disconnect the hooks
832 * from each other first.
835 ng_destroy_hook(hook_p hook)
837 hook_p peer = hook->peer;
839 hook->flags |= HK_INVALID; /* as soon as possible */
841 peer->flags |= HK_INVALID; /* as soon as possible */
844 ng_disconnect_hook(peer);
846 ng_disconnect_hook(hook);
850 * Notify the node of the hook's demise. This may result in more actions
851 * (e.g. shutdown) but we don't do that ourselves and don't know what
852 * happens there. If there is no appropriate handler, then just remove it
853 * (and decrement the reference count of it's node which in turn might
854 * make something happen).
857 ng_disconnect_hook(hook_p hook)
859 node_p node = hook->node;
862 * Remove the hook from the node's list to avoid possible recursion
863 * in case the disconnection results in node shutdown.
865 LIST_REMOVE(hook, hooks);
867 if (node->type->disconnect) {
869 * The type handler may elect to destroy the peer so don't
870 * trust its existance after this point.
872 (*node->type->disconnect) (hook);
874 ng_unref(node); /* might be the last reference */
876 FREE(hook->name, M_NETGRAPH);
877 hook->node = NULL; /* may still be referenced elsewhere */
882 * Take two hooks on a node and merge the connection so that the given node
883 * is effectively bypassed.
886 ng_bypass(hook_p hook1, hook_p hook2)
888 if (hook1->node != hook2->node)
890 hook1->peer->peer = hook2->peer;
891 hook2->peer->peer = hook1->peer;
893 /* XXX If we ever cache methods on hooks update them as well */
896 ng_destroy_hook(hook1);
897 ng_destroy_hook(hook2);
902 * Install a new netgraph type
905 ng_newtype(struct ng_type *tp)
907 const size_t namelen = strlen(tp->name);
909 /* Check version and type name fields */
910 if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
915 /* Check for name collision */
916 if (ng_findtype(tp->name) != NULL) {
921 /* Link in new type */
922 LIST_INSERT_HEAD(&typelist, tp, types);
923 tp->refs = 1; /* first ref is linked list */
928 * Look for a type of the name given
931 ng_findtype(const char *typename)
933 struct ng_type *type;
935 LIST_FOREACH(type, &typelist, types) {
936 if (strcmp(type->name, typename) == 0)
943 /************************************************************************
945 ************************************************************************/
948 * Make a peer and connect. The order is arranged to minimise
949 * the work needed to back out in case of error.
952 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
959 if ((error = ng_add_hook(node, name, &hook)))
962 /* make sure we have the module needed */
963 if (ng_findtype(type) == NULL) {
964 /* Not found, try to load it as a loadable module */
965 error = ng_load_module(type);
967 kprintf("required netgraph module ng_%s not loaded\n",
972 if ((error = ng_make_node(type, &node2))) {
973 ng_destroy_hook(hook);
976 if ((error = ng_add_hook(node2, name2, &hook2))) {
978 ng_destroy_hook(hook);
983 * Actually link the two hooks together.. on failure they are
984 * destroyed so we don't have to do that here.
986 if ((error = ng_connect(hook, hook2)))
992 * Connect two nodes using the specified hooks
995 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
1001 if ((error = ng_add_hook(node, name, &hook)))
1003 if ((error = ng_add_hook(node2, name2, &hook2))) {
1004 ng_destroy_hook(hook);
1007 return (ng_connect(hook, hook2));
1011 * Parse and verify a string of the form: <NODE:><PATH>
1013 * Such a string can refer to a specific node or a specific hook
1014 * on a specific node, depending on how you look at it. In the
1015 * latter case, the PATH component must not end in a dot.
1017 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1018 * of hook names separated by dots. This breaks out the original
1019 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1020 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1021 * the final hook component of <PATH>, if any, otherwise NULL.
1023 * This returns -1 if the path is malformed. The char ** are optional.
1027 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1029 char *node, *path, *hook;
1033 * Extract absolute NODE, if any
1035 for (path = addr; *path && *path != ':'; path++);
1037 node = addr; /* Here's the NODE */
1038 *path++ = '\0'; /* Here's the PATH */
1040 /* Node name must not be empty */
1044 /* A name of "." is OK; otherwise '.' not allowed */
1045 if (strcmp(node, ".") != 0) {
1046 for (k = 0; node[k]; k++)
1051 node = NULL; /* No absolute NODE */
1052 path = addr; /* Here's the PATH */
1055 /* Snoop for illegal characters in PATH */
1056 for (k = 0; path[k]; k++)
1060 /* Check for no repeated dots in PATH */
1061 for (k = 0; path[k]; k++)
1062 if (path[k] == '.' && path[k + 1] == '.')
1065 /* Remove extra (degenerate) dots from beginning or end of PATH */
1068 if (*path && path[strlen(path) - 1] == '.')
1069 path[strlen(path) - 1] = 0;
1071 /* If PATH has a dot, then we're not talking about a hook */
1073 for (hook = path, k = 0; path[k]; k++)
1074 if (path[k] == '.') {
1092 * Given a path, which may be absolute or relative, and a starting node,
1093 * return the destination node. Compute the "return address" if desired.
1096 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1098 const node_p start = here;
1099 char fullpath[NG_PATHSIZ];
1100 char *nodename, *path, pbuf[2];
1111 /* Make a writable copy of address for ng_path_parse() */
1112 strncpy(fullpath, address, sizeof(fullpath) - 1);
1113 fullpath[sizeof(fullpath) - 1] = '\0';
1115 /* Parse out node and sequence of hooks */
1116 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1121 pbuf[0] = '.'; /* Needs to be writable */
1126 /* For an absolute address, jump to the starting node */
1128 node = ng_findname(here, nodename);
1136 /* Now follow the sequence of hooks */
1137 for (cp = path; node != NULL && *cp != '\0'; ) {
1142 * Break out the next path segment. Replace the dot we just
1143 * found with a NUL; "cp" points to the next segment (or the
1146 for (segment = cp; *cp != '\0'; cp++) {
1154 if (*segment == '\0')
1157 /* We have a segment, so look for a hook by that name */
1158 hook = ng_findhook(node, segment);
1160 /* Can't get there from here... */
1162 || hook->peer == NULL
1163 || (hook->flags & HK_INVALID) != 0) {
1168 /* Hop on over to the next node */
1169 node = hook->peer->node;
1172 /* If node somehow missing, fail here (probably this is not needed) */
1178 /* Now compute return address, i.e., the path to the sender */
1180 MALLOC(*rtnp, char *, NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1181 if (*rtnp == NULL) {
1185 if (start->name != NULL)
1186 ksprintf(*rtnp, "%s:", start->name);
1188 ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1197 * Call the appropriate message handler for the object.
1198 * It is up to the message handler to free the message.
1199 * If it's a generic message, handle it generically, otherwise
1200 * call the type's message handler (if it exists)
1201 * XXX (race). Remember that a queued message may reference a node
1202 * or hook that has just been invalidated. It will exist
1203 * as the queue code is holding a reference, but..
1206 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1208 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1209 (error) = ng_generic_msg((node), (msg), \
1210 (retaddr), (resp)); \
1212 if ((node)->type->rcvmsg != NULL) { \
1213 (error) = (*(node)->type->rcvmsg)((node), \
1214 (msg), (retaddr), (resp)); \
1217 FREE((msg), M_NETGRAPH); \
1225 * Send a control message to a node
1228 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1229 struct ng_mesg **rptr)
1232 char *retaddr = NULL;
1235 /* Find the target node */
1236 error = ng_path2node(here, address, &dest, &retaddr);
1238 FREE(msg, M_NETGRAPH);
1242 /* Make sure the resp field is null before we start */
1246 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1248 /* Make sure that if there is a response, it has the RESP bit set */
1249 if ((error == 0) && rptr && *rptr)
1250 (*rptr)->header.flags |= NGF_RESP;
1253 * If we had a return address it is up to us to free it. They should
1254 * have taken a copy if they needed to make a delayed response.
1257 FREE(retaddr, M_NETGRAPH);
1262 * Implement the 'generic' control messages
1265 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1266 struct ng_mesg **resp)
1270 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1272 FREE(msg, M_NETGRAPH);
1275 switch (msg->header.cmd) {
1281 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1283 if (msg->header.arglen != sizeof(*mkp)) {
1287 mkp->type[sizeof(mkp->type) - 1] = '\0';
1288 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1289 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1290 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1295 struct ngm_connect *const con =
1296 (struct ngm_connect *) msg->data;
1299 if (msg->header.arglen != sizeof(*con)) {
1303 con->path[sizeof(con->path) - 1] = '\0';
1304 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1305 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1306 error = ng_path2node(here, con->path, &node2, NULL);
1309 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1314 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1316 if (msg->header.arglen != sizeof(*nam)) {
1320 nam->name[sizeof(nam->name) - 1] = '\0';
1321 error = ng_name_node(here, nam->name);
1326 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1329 if (msg->header.arglen != sizeof(*rmh)) {
1333 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1334 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1335 ng_destroy_hook(hook);
1340 struct nodeinfo *ni;
1343 /* Get response struct */
1348 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1354 /* Fill in node info */
1355 ni = (struct nodeinfo *) rp->data;
1356 if (here->name != NULL)
1357 strlcpy(ni->name, here->name, NG_NODESIZ);
1358 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1359 ni->id = ng_node2ID(here);
1360 ni->hooks = here->numhooks;
1366 const int nhooks = here->numhooks;
1367 struct hooklist *hl;
1368 struct nodeinfo *ni;
1372 /* Get response struct */
1377 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1378 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1383 hl = (struct hooklist *) rp->data;
1386 /* Fill in node info */
1388 strlcpy(ni->name, here->name, NG_NODESIZ);
1389 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1390 ni->id = ng_node2ID(here);
1392 /* Cycle through the linked list of hooks */
1394 LIST_FOREACH(hook, &here->hooks, hooks) {
1395 struct linkinfo *const link = &hl->link[ni->hooks];
1397 if (ni->hooks >= nhooks) {
1398 log(LOG_ERR, "%s: number of %s changed\n",
1402 if ((hook->flags & HK_INVALID) != 0)
1404 strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1405 strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1406 if (hook->peer->node->name != NULL)
1407 strlcpy(link->nodeinfo.name,
1408 hook->peer->node->name, NG_NODESIZ);
1409 strlcpy(link->nodeinfo.type,
1410 hook->peer->node->type->name, NG_TYPESIZ);
1411 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1412 link->nodeinfo.hooks = hook->peer->node->numhooks;
1422 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1423 struct namelist *nl;
1433 /* Count number of nodes */
1434 LIST_FOREACH(node, &nodelist, nodes) {
1435 if ((node->flags & NG_INVALID) == 0
1436 && (unnamed || node->name != NULL))
1440 /* Get response struct */
1445 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1446 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1451 nl = (struct namelist *) rp->data;
1453 /* Cycle through the linked list of nodes */
1455 LIST_FOREACH(node, &nodelist, nodes) {
1456 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1458 if (nl->numnames >= num) {
1459 log(LOG_ERR, "%s: number of %s changed\n",
1463 if ((node->flags & NG_INVALID) != 0)
1465 if (!unnamed && node->name == NULL)
1467 if (node->name != NULL)
1468 strlcpy(np->name, node->name, NG_NODESIZ);
1469 strlcpy(np->type, node->type->name, NG_TYPESIZ);
1470 np->id = ng_node2ID(node);
1471 np->hooks = node->numhooks;
1480 struct typelist *tl;
1482 struct ng_type *type;
1490 /* Count number of types */
1491 LIST_FOREACH(type, &typelist, types)
1494 /* Get response struct */
1499 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1500 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1505 tl = (struct typelist *) rp->data;
1507 /* Cycle through the linked list of types */
1509 LIST_FOREACH(type, &typelist, types) {
1510 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1512 if (tl->numtypes >= num) {
1513 log(LOG_ERR, "%s: number of %s changed\n",
1517 strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1518 tp->numnodes = type->refs - 1; /* don't count list */
1525 case NGM_BINARY2ASCII:
1527 int bufSize = 20 * 1024; /* XXX hard coded constant */
1528 const struct ng_parse_type *argstype;
1529 const struct ng_cmdlist *c;
1530 struct ng_mesg *rp, *binary, *ascii;
1532 /* Data area must contain a valid netgraph message */
1533 binary = (struct ng_mesg *)msg->data;
1534 if (msg->header.arglen < sizeof(struct ng_mesg)
1535 || msg->header.arglen - sizeof(struct ng_mesg)
1536 < binary->header.arglen) {
1541 /* Get a response message with lots of room */
1542 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1547 ascii = (struct ng_mesg *)rp->data;
1549 /* Copy binary message header to response message payload */
1550 bcopy(binary, ascii, sizeof(*binary));
1552 /* Find command by matching typecookie and command number */
1553 for (c = here->type->cmdlist;
1554 c != NULL && c->name != NULL; c++) {
1555 if (binary->header.typecookie == c->cookie
1556 && binary->header.cmd == c->cmd)
1559 if (c == NULL || c->name == NULL) {
1560 for (c = ng_generic_cmds; c->name != NULL; c++) {
1561 if (binary->header.typecookie == c->cookie
1562 && binary->header.cmd == c->cmd)
1565 if (c->name == NULL) {
1566 FREE(rp, M_NETGRAPH);
1572 /* Convert command name to ASCII */
1573 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1576 /* Convert command arguments to ASCII */
1577 argstype = (binary->header.flags & NGF_RESP) ?
1578 c->respType : c->mesgType;
1579 if (argstype == NULL)
1580 *ascii->data = '\0';
1582 if ((error = ng_unparse(argstype,
1583 (u_char *)binary->data,
1584 ascii->data, bufSize)) != 0) {
1585 FREE(rp, M_NETGRAPH);
1590 /* Return the result as struct ng_mesg plus ASCII string */
1591 bufSize = strlen(ascii->data) + 1;
1592 ascii->header.arglen = bufSize;
1593 rp->header.arglen = sizeof(*ascii) + bufSize;
1598 case NGM_ASCII2BINARY:
1600 int bufSize = 2000; /* XXX hard coded constant */
1601 const struct ng_cmdlist *c;
1602 const struct ng_parse_type *argstype;
1603 struct ng_mesg *rp, *ascii, *binary;
1606 /* Data area must contain at least a struct ng_mesg + '\0' */
1607 ascii = (struct ng_mesg *)msg->data;
1608 if (msg->header.arglen < sizeof(*ascii) + 1
1609 || ascii->header.arglen < 1
1610 || msg->header.arglen
1611 < sizeof(*ascii) + ascii->header.arglen) {
1615 ascii->data[ascii->header.arglen - 1] = '\0';
1617 /* Get a response message with lots of room */
1618 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1623 binary = (struct ng_mesg *)rp->data;
1625 /* Copy ASCII message header to response message payload */
1626 bcopy(ascii, binary, sizeof(*ascii));
1628 /* Find command by matching ASCII command string */
1629 for (c = here->type->cmdlist;
1630 c != NULL && c->name != NULL; c++) {
1631 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1634 if (c == NULL || c->name == NULL) {
1635 for (c = ng_generic_cmds; c->name != NULL; c++) {
1636 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1639 if (c->name == NULL) {
1640 FREE(rp, M_NETGRAPH);
1646 /* Convert command name to binary */
1647 binary->header.cmd = c->cmd;
1648 binary->header.typecookie = c->cookie;
1650 /* Convert command arguments to binary */
1651 argstype = (binary->header.flags & NGF_RESP) ?
1652 c->respType : c->mesgType;
1653 if (argstype == NULL)
1656 if ((error = ng_parse(argstype, ascii->data,
1657 &off, (u_char *)binary->data, &bufSize)) != 0) {
1658 FREE(rp, M_NETGRAPH);
1663 /* Return the result */
1664 binary->header.arglen = bufSize;
1665 rp->header.arglen = sizeof(*binary) + bufSize;
1670 case NGM_TEXT_CONFIG:
1671 case NGM_TEXT_STATUS:
1673 * This one is tricky as it passes the command down to the
1674 * actual node, even though it is a generic type command.
1675 * This means we must assume that the msg is already freed
1676 * when control passes back to us.
1682 if (here->type->rcvmsg != NULL)
1683 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1684 /* Fall through if rcvmsg not supported */
1689 FREE(msg, M_NETGRAPH);
1694 * Send a data packet to a node. If the recipient has no
1695 * 'receive data' method, then silently discard the packet.
1698 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1700 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1704 if (hook && (hook->flags & HK_INVALID) == 0) {
1705 rcvdata = hook->peer->node->type->rcvdata;
1706 if (rcvdata != NULL)
1707 error = (*rcvdata)(hook->peer, m, meta);
1710 NG_FREE_DATA(m, meta);
1715 NG_FREE_DATA(m, meta);
1721 * Send a queued data packet to a node. If the recipient has no
1722 * 'receive queued data' method, then try the 'receive data' method above.
1725 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1727 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1731 if (hook && (hook->flags & HK_INVALID) == 0) {
1732 rcvdataq = hook->peer->node->type->rcvdataq;
1733 if (rcvdataq != NULL)
1734 error = (*rcvdataq)(hook->peer, m, meta);
1736 error = ng_send_data(hook, m, meta);
1741 NG_FREE_DATA(m, meta);
1749 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1752 ng_copy_meta(meta_p meta)
1758 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1761 meta2->allocated_len = meta->used_len;
1762 bcopy(meta, meta2, meta->used_len);
1766 /************************************************************************
1768 ************************************************************************/
1771 * Handle the loading/unloading of a netgraph node type module
1774 ng_mod_event(module_t mod, int event, void *data)
1776 struct ng_type *const type = data;
1782 /* Register new netgraph node type */
1784 if ((error = ng_newtype(type)) != 0) {
1789 /* Call type specific code */
1790 if (type->mod_event != NULL)
1791 if ((error = (*type->mod_event)(mod, event, data))) {
1792 type->refs--; /* undo it */
1793 LIST_REMOVE(type, types);
1800 if (type->refs > 1) { /* make sure no nodes exist! */
1803 if (type->refs == 0) {
1804 /* failed load, nothing to undo */
1808 if (type->mod_event != NULL) { /* check with type */
1809 error = (*type->mod_event)(mod, event, data);
1810 if (error != 0) { /* type refuses.. */
1815 LIST_REMOVE(type, types);
1821 if (type->mod_event != NULL)
1822 error = (*type->mod_event)(mod, event, data);
1824 error = 0; /* XXX ? */
1831 * Handle loading and unloading for this code.
1832 * The only thing we need to link into is the NETISR strucure.
1835 ngb_mod_event(module_t mod, int event, void *data)
1841 /* Register line discipline */
1843 error = ng_load_module("ksocket");
1848 netisr_register(NETISR_NETGRAPH, ngintr, NULL);
1853 ng_unload_module("ksocket");
1854 /* You cant unload it because an interface may be using it. */
1864 static moduledata_t netgraph_mod = {
1869 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1870 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1871 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1872 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1874 /************************************************************************
1876 ************************************************************************/
1878 /* The structure for queueing across ISR switches */
1879 struct ng_queue_entry {
1881 struct ng_queue_entry *next;
1884 hook_p da_hook; /* target hook */
1889 struct ng_mesg *msg_msg;
1895 #define NGQF_DATA 0x01 /* the queue element is data */
1896 #define NGQF_MESG 0x02 /* the queue element is a message */
1898 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1899 static struct ng_queue_entry *ngqlast; /* last item queued */
1900 static const int ngqroom = 256; /* max items to queue */
1901 static int ngqsize; /* number of items in queue */
1903 static struct ng_queue_entry *ngqfree; /* free ones */
1904 static const int ngqfreemax = 256;/* cache at most this many */
1905 static int ngqfreesize; /* number of cached entries */
1910 static struct ng_queue_entry *
1913 struct ng_queue_entry *q;
1915 /* Could be guarding against tty ints or whatever */
1918 /* Try get a cached queue block, or else allocate a new one */
1919 if ((q = ngqfree) == NULL) {
1921 if (ngqsize < ngqroom) { /* don't worry about races */
1922 MALLOC(q, struct ng_queue_entry *,
1923 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1934 * Release a queue entry
1936 #define RETURN_QBLK(q) \
1938 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1940 (q)->next = ngqfree; \
1945 FREE((q), M_NETGRAPH); \
1950 * Running at a raised (but we don't know which) processor priority level,
1951 * put the data onto a queue to be picked up by another PPL (probably splnet)
1954 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1956 struct ng_queue_entry *q;
1959 NG_FREE_DATA(m, meta);
1962 if ((q = ng_getqblk()) == NULL) {
1963 NG_FREE_DATA(m, meta);
1967 /* Fill out the contents */
1968 q->flags = NGQF_DATA;
1970 q->body.data.da_hook = hook;
1971 q->body.data.da_m = m;
1972 q->body.data.da_meta = meta;
1973 crit_enter(); /* protect refs and queue */
1974 hook->refs++; /* don't let it go away while on the queue */
1976 /* Put it on the queue */
1986 /* Schedule software interrupt to handle it later */
1987 schednetisr(NETISR_NETGRAPH);
1992 * Running at a raised (but we don't know which) processor priority level,
1993 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1996 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1998 struct ng_queue_entry *q;
2000 char *retaddr = NULL;
2003 /* Find the target node. */
2004 error = ng_path2node(here, address, &dest, &retaddr);
2006 FREE(msg, M_NETGRAPH);
2009 if ((q = ng_getqblk()) == NULL) {
2010 FREE(msg, M_NETGRAPH);
2012 FREE(retaddr, M_NETGRAPH);
2016 /* Fill out the contents */
2017 q->flags = NGQF_MESG;
2019 q->body.msg.msg_node = dest;
2020 q->body.msg.msg_msg = msg;
2021 q->body.msg.msg_retaddr = retaddr;
2022 crit_enter(); /* protect refs and queue */
2023 dest->refs++; /* don't let it go away while on the queue */
2025 /* Put it on the queue */
2035 /* Schedule software interrupt to handle it later */
2036 schednetisr(NETISR_NETGRAPH);
2041 * Pick an item off the queue, process it, and dispose of the queue entry.
2044 ngintr(netmsg_t pmsg)
2048 struct ng_queue_entry *ngq;
2051 struct ng_mesg *msg;
2056 * Packets are never sent to this netisr so the message must always
2057 * be replied. Interlock processing and notification by replying
2058 * the message first.
2060 lwkt_replymsg(&pmsg->lmsg, 0);
2066 if ((ngq = ngqbase)) {
2067 ngqbase = ngq->next;
2073 switch (ngq->flags) {
2075 hook = ngq->body.data.da_hook;
2076 m = ngq->body.data.da_m;
2077 meta = ngq->body.data.da_meta;
2079 NG_SEND_DATAQ(error, hook, m, meta);
2080 ng_unref_hook(hook);
2083 node = ngq->body.msg.msg_node;
2084 msg = ngq->body.msg.msg_msg;
2085 retaddr = ngq->body.msg.msg_retaddr;
2087 if (node->flags & NG_INVALID) {
2088 FREE(msg, M_NETGRAPH);
2090 CALL_MSG_HANDLER(error, node, msg,
2095 FREE(retaddr, M_NETGRAPH);