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.5 2003/08/07 21:17:32 dillon 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 <machine/limits.h>
62 #include <net/netisr.h>
64 #include <netgraph/ng_message.h>
65 #include <netgraph/netgraph.h>
68 /* List of all nodes */
69 static LIST_HEAD(, ng_node) nodelist;
71 /* List of installed types */
72 static LIST_HEAD(, ng_type) typelist;
74 /* Hash releted definitions */
75 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
76 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
77 /* Don't nead to initialise them because it's a LIST */
79 /* Internal functions */
80 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
81 static int ng_connect(hook_p hook1, hook_p hook2);
82 static void ng_disconnect_hook(hook_p hook);
83 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
84 const char *retaddr, struct ng_mesg ** resp);
85 static ng_ID_t ng_decodeidname(const char *name);
86 static int ngb_mod_event(module_t mod, int event, void *data);
87 static void ngintr(void);
89 /* Our own netgraph malloc type */
90 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
92 /* Set this to Debugger("X") to catch all errors as they occur */
97 static ng_ID_t nextID = 1;
100 #define CHECK_DATA_MBUF(m) do { \
104 if (((m)->m_flags & M_PKTHDR) == 0) \
105 panic("%s: !PKTHDR", __FUNCTION__); \
106 for (total = 0, n = (m); n != NULL; n = n->m_next) \
108 if ((m)->m_pkthdr.len != total) { \
109 panic("%s: %d != %d", \
110 __FUNCTION__, (m)->m_pkthdr.len, total); \
114 #define CHECK_DATA_MBUF(m)
118 /************************************************************************
119 Parse type definitions for generic messages
120 ************************************************************************/
122 /* Handy structure parse type defining macro */
123 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
124 static const struct ng_parse_struct_field \
125 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
126 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
127 &ng_parse_struct_type, \
128 &ng_ ## lo ## _type_fields \
131 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
132 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
133 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
134 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
135 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
136 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
137 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
139 /* Get length of an array when the length is stored as a 32 bit
140 value immediately preceeding the array -- as with struct namelist
141 and struct typelist. */
143 ng_generic_list_getLength(const struct ng_parse_type *type,
144 const u_char *start, const u_char *buf)
146 return *((const u_int32_t *)(buf - 4));
149 /* Get length of the array of struct linkinfo inside a struct hooklist */
151 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
152 const u_char *start, const u_char *buf)
154 const struct hooklist *hl = (const struct hooklist *)start;
156 return hl->nodeinfo.hooks;
159 /* Array type for a variable length array of struct namelist */
160 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
161 &ng_generic_nodeinfo_type,
162 &ng_generic_list_getLength
164 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
165 &ng_parse_array_type,
166 &ng_nodeinfoarray_type_info
169 /* Array type for a variable length array of struct typelist */
170 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
171 &ng_generic_typeinfo_type,
172 &ng_generic_list_getLength
174 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
175 &ng_parse_array_type,
176 &ng_typeinfoarray_type_info
179 /* Array type for array of struct linkinfo in struct hooklist */
180 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
181 &ng_generic_linkinfo_type,
182 &ng_generic_linkinfo_getLength
184 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
185 &ng_parse_array_type,
186 &ng_generic_linkinfo_array_type_info
189 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
190 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
191 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
192 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
193 (&ng_generic_nodeinfoarray_type));
195 /* List of commands and how to convert arguments to/from ASCII */
196 static const struct ng_cmdlist ng_generic_cmds[] = {
208 &ng_generic_mkpeer_type,
215 &ng_generic_connect_type,
222 &ng_generic_name_type,
229 &ng_generic_rmhook_type,
237 &ng_generic_nodeinfo_type
244 &ng_generic_hooklist_type
251 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
258 &ng_generic_listnodes_type
265 &ng_generic_typeinfo_type
272 &ng_parse_string_type
279 &ng_parse_string_type
285 &ng_parse_ng_mesg_type,
286 &ng_parse_ng_mesg_type
292 &ng_parse_ng_mesg_type,
293 &ng_parse_ng_mesg_type
298 /************************************************************************
300 ************************************************************************/
303 * Instantiate a node of the requested type
306 ng_make_node(const char *typename, node_p *nodepp)
308 struct ng_type *type;
310 /* Check that the type makes sense */
311 if (typename == NULL) {
316 /* Locate the node type */
317 if ((type = ng_findtype(typename)) == NULL) {
318 char *path, filename[NG_TYPELEN + 4];
322 /* Not found, try to load it as a loadable module */
323 snprintf(filename, sizeof(filename), "ng_%s.ko", typename);
324 if ((path = linker_search_path(filename)) == NULL)
326 error = linker_load_file(path, &lf);
327 FREE(path, M_LINKER);
330 lf->userrefs++; /* pretend loaded by the syscall */
332 /* Try again, as now the type should have linked itself in */
333 if ((type = ng_findtype(typename)) == NULL)
337 /* Call the constructor */
338 if (type->constructor != NULL)
339 return ((*type->constructor)(nodepp));
341 return (ng_make_node_common(type, nodepp));
345 * Generic node creation. Called by node constructors.
346 * The returned node has a reference count of 1.
349 ng_make_node_common(struct ng_type *type, node_p *nodepp)
353 /* Require the node type to have been already installed */
354 if (ng_findtype(type->name) == NULL) {
359 /* Make a node and try attach it to the type */
360 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT);
365 bzero(node, sizeof(*node));
367 node->refs++; /* note reference */
370 /* Link us into the node linked list */
371 LIST_INSERT_HEAD(&nodelist, node, nodes);
373 /* Initialize hook list for new node */
374 LIST_INIT(&node->hooks);
376 /* get an ID and put us in the hash chain */
377 node->ID = nextID++; /* 137 per second for 1 year before wrap */
378 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
386 * Forceably start the shutdown process on a node. Either call
387 * it's shutdown method, or do the default shutdown if there is
388 * no type-specific method.
390 * Persistent nodes must have a type-specific method which
391 * resets the NG_INVALID flag.
394 ng_rmnode(node_p node)
396 /* Check if it's already shutting down */
397 if ((node->flags & NG_INVALID) != 0)
400 /* Add an extra reference so it doesn't go away during this */
403 /* Mark it invalid so any newcomers know not to try use it */
404 node->flags |= NG_INVALID;
406 /* Ask the type if it has anything to do in this case */
407 if (node->type && node->type->shutdown)
408 (*node->type->shutdown)(node);
409 else { /* do the default thing */
415 /* Remove extra reference, possibly the last */
420 * Called by the destructor to remove any STANDARD external references
423 ng_cutlinks(node_p node)
427 /* Make sure that this is set to stop infinite loops */
428 node->flags |= NG_INVALID;
430 /* If we have sleepers, wake them up; they'll see NG_INVALID */
434 /* Notify all remaining connected nodes to disconnect */
435 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
436 ng_destroy_hook(hook);
440 * Remove a reference to the node, possibly the last
443 ng_unref(node_p node)
448 if (--node->refs <= 0) {
450 LIST_REMOVE(node, nodes);
451 LIST_REMOVE(node, idnodes);
452 FREE(node, M_NETGRAPH);
458 * Wait for a node to come ready. Returns a node with a reference count;
459 * don't forget to drop it when we are done with it using ng_release_node().
462 ng_wait_node(node_p node, char *msg)
470 node->refs++; /* the sleeping process counts as a reference */
471 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
472 error = tsleep(node, PCATCH, msg, 0);
474 if (node->flags & NG_INVALID) {
478 KASSERT(node->refs > 1,
479 ("%s: refs=%d", __FUNCTION__, node->refs));
480 node->flags |= NG_BUSY;
484 /* Release the reference we had on it */
491 * Release a node acquired via ng_wait_node()
494 ng_release_node(node_p node)
496 /* Declare that we don't want it */
497 node->flags &= ~NG_BUSY;
499 /* If we have sleepers, then wake them up */
503 /* We also have a reference.. drop it too */
507 /************************************************************************
509 ************************************************************************/
511 ng_ID2node(ng_ID_t ID)
514 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
515 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
522 ng_node2ID(node_p node)
527 /************************************************************************
529 ************************************************************************/
532 * Assign a node a name. Once assigned, the name cannot be changed.
535 ng_name_node(node_p node, const char *name)
539 /* Check the name is valid */
540 for (i = 0; i < NG_NODELEN + 1; i++) {
541 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
544 if (i == 0 || name[i] != '\0') {
548 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
553 /* Check the node isn't already named */
554 if (node->name != NULL) {
559 /* Check the name isn't already being used */
560 if (ng_findname(node, name) != NULL) {
565 /* Allocate space and copy it */
566 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
567 if (node->name == NULL) {
571 strcpy(node->name, name);
573 /* The name counts as a reference */
579 * Find a node by absolute name. The name should NOT end with ':'
580 * The name "." means "this node" and "[xxx]" means "the node
581 * with ID (ie, at address) xxx".
583 * Returns the node if found, else NULL.
586 ng_findname(node_p this, const char *name)
591 /* "." means "this node" */
592 if (strcmp(name, ".") == 0)
595 /* Check for name-by-ID */
596 if ((temp = ng_decodeidname(name)) != 0) {
597 return (ng_ID2node(temp));
600 /* Find node by name */
601 LIST_FOREACH(node, &nodelist, nodes) {
602 if ((node->name != NULL)
603 && (strcmp(node->name, name) == 0)
604 && ((node->flags & NG_INVALID) == 0))
611 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
612 * string is not valid, otherwise returns the value.
615 ng_decodeidname(const char *name)
617 const int len = strlen(name);
621 /* Check for proper length, brackets, no leading junk */
622 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
623 || !isxdigit(name[1]))
627 val = strtoul(name + 1, &eptr, 16);
628 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
634 * Remove a name from a node. This should only be called
635 * when shutting down and removing the node.
638 ng_unname(node_p node)
641 FREE(node->name, M_NETGRAPH);
647 /************************************************************************
650 Names are not optional. Hooks are always connected, except for a
651 brief moment within these routines.
653 ************************************************************************/
656 * Remove a hook reference
659 ng_unref_hook(hook_p hook)
664 if (--hook->refs == 0)
665 FREE(hook, M_NETGRAPH);
670 * Add an unconnected hook to a node. Only used internally.
673 ng_add_hook(node_p node, const char *name, hook_p *hookp)
678 /* Check that the given name is good */
683 if (ng_findhook(node, name) != NULL) {
688 /* Allocate the hook and link it up */
689 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
694 bzero(hook, sizeof(*hook));
696 hook->flags = HK_INVALID;
698 node->refs++; /* each hook counts as a reference */
700 /* Check if the node type code has something to say about it */
701 if (node->type->newhook != NULL)
702 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
706 * The 'type' agrees so far, so go ahead and link it in.
707 * We'll ask again later when we actually connect the hooks.
709 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
713 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
714 if (hook->name == NULL) {
716 LIST_REMOVE(hook, hooks);
721 ng_unref_hook(hook); /* this frees the hook */
724 strcpy(hook->name, name);
731 * Connect a pair of hooks. Only used internally.
734 ng_connect(hook_p hook1, hook_p hook2)
741 /* Give each node the opportunity to veto the impending connection */
742 if (hook1->node->type->connect) {
743 if ((error = (*hook1->node->type->connect) (hook1))) {
744 ng_destroy_hook(hook1); /* also zaps hook2 */
748 if (hook2->node->type->connect) {
749 if ((error = (*hook2->node->type->connect) (hook2))) {
750 ng_destroy_hook(hook2); /* also zaps hook1 */
754 hook1->flags &= ~HK_INVALID;
755 hook2->flags &= ~HK_INVALID;
762 * Node types may supply their own optimized routines for finding
763 * hooks. If none is supplied, we just do a linear search.
766 ng_findhook(node_p node, const char *name)
770 if (node->type->findhook != NULL)
771 return (*node->type->findhook)(node, name);
772 LIST_FOREACH(hook, &node->hooks, hooks) {
773 if (hook->name != NULL
774 && strcmp(hook->name, name) == 0
775 && (hook->flags & HK_INVALID) == 0)
784 * As hooks are always attached, this really destroys two hooks.
785 * The one given, and the one attached to it. Disconnect the hooks
786 * from each other first.
789 ng_destroy_hook(hook_p hook)
791 hook_p peer = hook->peer;
793 hook->flags |= HK_INVALID; /* as soon as possible */
795 peer->flags |= HK_INVALID; /* as soon as possible */
798 ng_disconnect_hook(peer);
800 ng_disconnect_hook(hook);
804 * Notify the node of the hook's demise. This may result in more actions
805 * (e.g. shutdown) but we don't do that ourselves and don't know what
806 * happens there. If there is no appropriate handler, then just remove it
807 * (and decrement the reference count of it's node which in turn might
808 * make something happen).
811 ng_disconnect_hook(hook_p hook)
813 node_p node = hook->node;
816 * Remove the hook from the node's list to avoid possible recursion
817 * in case the disconnection results in node shutdown.
819 LIST_REMOVE(hook, hooks);
821 if (node->type->disconnect) {
823 * The type handler may elect to destroy the peer so don't
824 * trust its existance after this point.
826 (*node->type->disconnect) (hook);
828 ng_unref(node); /* might be the last reference */
830 FREE(hook->name, M_NETGRAPH);
831 hook->node = NULL; /* may still be referenced elsewhere */
836 * Take two hooks on a node and merge the connection so that the given node
837 * is effectively bypassed.
840 ng_bypass(hook_p hook1, hook_p hook2)
842 if (hook1->node != hook2->node)
844 hook1->peer->peer = hook2->peer;
845 hook2->peer->peer = hook1->peer;
847 /* XXX If we ever cache methods on hooks update them as well */
850 ng_destroy_hook(hook1);
851 ng_destroy_hook(hook2);
856 * Install a new netgraph type
859 ng_newtype(struct ng_type *tp)
861 const size_t namelen = strlen(tp->name);
863 /* Check version and type name fields */
864 if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
869 /* Check for name collision */
870 if (ng_findtype(tp->name) != NULL) {
875 /* Link in new type */
876 LIST_INSERT_HEAD(&typelist, tp, types);
877 tp->refs = 1; /* first ref is linked list */
882 * Look for a type of the name given
885 ng_findtype(const char *typename)
887 struct ng_type *type;
889 LIST_FOREACH(type, &typelist, types) {
890 if (strcmp(type->name, typename) == 0)
897 /************************************************************************
899 ************************************************************************/
902 * Make a peer and connect. The order is arranged to minimise
903 * the work needed to back out in case of error.
906 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
913 if ((error = ng_add_hook(node, name, &hook)))
915 if ((error = ng_make_node(type, &node2))) {
916 ng_destroy_hook(hook);
919 if ((error = ng_add_hook(node2, name2, &hook2))) {
921 ng_destroy_hook(hook);
926 * Actually link the two hooks together.. on failure they are
927 * destroyed so we don't have to do that here.
929 if ((error = ng_connect(hook, hook2)))
935 * Connect two nodes using the specified hooks
938 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
944 if ((error = ng_add_hook(node, name, &hook)))
946 if ((error = ng_add_hook(node2, name2, &hook2))) {
947 ng_destroy_hook(hook);
950 return (ng_connect(hook, hook2));
954 * Parse and verify a string of the form: <NODE:><PATH>
956 * Such a string can refer to a specific node or a specific hook
957 * on a specific node, depending on how you look at it. In the
958 * latter case, the PATH component must not end in a dot.
960 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
961 * of hook names separated by dots. This breaks out the original
962 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
963 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
964 * the final hook component of <PATH>, if any, otherwise NULL.
966 * This returns -1 if the path is malformed. The char ** are optional.
970 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
972 char *node, *path, *hook;
976 * Extract absolute NODE, if any
978 for (path = addr; *path && *path != ':'; path++);
980 node = addr; /* Here's the NODE */
981 *path++ = '\0'; /* Here's the PATH */
983 /* Node name must not be empty */
987 /* A name of "." is OK; otherwise '.' not allowed */
988 if (strcmp(node, ".") != 0) {
989 for (k = 0; node[k]; k++)
994 node = NULL; /* No absolute NODE */
995 path = addr; /* Here's the PATH */
998 /* Snoop for illegal characters in PATH */
999 for (k = 0; path[k]; k++)
1003 /* Check for no repeated dots in PATH */
1004 for (k = 0; path[k]; k++)
1005 if (path[k] == '.' && path[k + 1] == '.')
1008 /* Remove extra (degenerate) dots from beginning or end of PATH */
1011 if (*path && path[strlen(path) - 1] == '.')
1012 path[strlen(path) - 1] = 0;
1014 /* If PATH has a dot, then we're not talking about a hook */
1016 for (hook = path, k = 0; path[k]; k++)
1017 if (path[k] == '.') {
1035 * Given a path, which may be absolute or relative, and a starting node,
1036 * return the destination node. Compute the "return address" if desired.
1039 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1041 const node_p start = here;
1042 char fullpath[NG_PATHLEN + 1];
1043 char *nodename, *path, pbuf[2];
1054 /* Make a writable copy of address for ng_path_parse() */
1055 strncpy(fullpath, address, sizeof(fullpath) - 1);
1056 fullpath[sizeof(fullpath) - 1] = '\0';
1058 /* Parse out node and sequence of hooks */
1059 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1064 pbuf[0] = '.'; /* Needs to be writable */
1069 /* For an absolute address, jump to the starting node */
1071 node = ng_findname(here, nodename);
1079 /* Now follow the sequence of hooks */
1080 for (cp = path; node != NULL && *cp != '\0'; ) {
1085 * Break out the next path segment. Replace the dot we just
1086 * found with a NUL; "cp" points to the next segment (or the
1089 for (segment = cp; *cp != '\0'; cp++) {
1097 if (*segment == '\0')
1100 /* We have a segment, so look for a hook by that name */
1101 hook = ng_findhook(node, segment);
1103 /* Can't get there from here... */
1105 || hook->peer == NULL
1106 || (hook->flags & HK_INVALID) != 0) {
1111 /* Hop on over to the next node */
1112 node = hook->peer->node;
1115 /* If node somehow missing, fail here (probably this is not needed) */
1121 /* Now compute return address, i.e., the path to the sender */
1123 MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_NOWAIT);
1124 if (*rtnp == NULL) {
1128 if (start->name != NULL)
1129 sprintf(*rtnp, "%s:", start->name);
1131 sprintf(*rtnp, "[%x]:", ng_node2ID(start));
1140 * Call the appropriate message handler for the object.
1141 * It is up to the message handler to free the message.
1142 * If it's a generic message, handle it generically, otherwise
1143 * call the type's message handler (if it exists)
1144 * XXX (race). Remember that a queued message may reference a node
1145 * or hook that has just been invalidated. It will exist
1146 * as the queue code is holding a reference, but..
1149 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1151 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1152 (error) = ng_generic_msg((node), (msg), \
1153 (retaddr), (resp)); \
1155 if ((node)->type->rcvmsg != NULL) { \
1156 (error) = (*(node)->type->rcvmsg)((node), \
1157 (msg), (retaddr), (resp)); \
1160 FREE((msg), M_NETGRAPH); \
1168 * Send a control message to a node
1171 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1172 struct ng_mesg **rptr)
1175 char *retaddr = NULL;
1178 /* Find the target node */
1179 error = ng_path2node(here, address, &dest, &retaddr);
1181 FREE(msg, M_NETGRAPH);
1185 /* Make sure the resp field is null before we start */
1189 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1191 /* Make sure that if there is a response, it has the RESP bit set */
1192 if ((error == 0) && rptr && *rptr)
1193 (*rptr)->header.flags |= NGF_RESP;
1196 * If we had a return address it is up to us to free it. They should
1197 * have taken a copy if they needed to make a delayed response.
1200 FREE(retaddr, M_NETGRAPH);
1205 * Implement the 'generic' control messages
1208 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1209 struct ng_mesg **resp)
1213 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1215 FREE(msg, M_NETGRAPH);
1218 switch (msg->header.cmd) {
1224 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1226 if (msg->header.arglen != sizeof(*mkp)) {
1230 mkp->type[sizeof(mkp->type) - 1] = '\0';
1231 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1232 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1233 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1238 struct ngm_connect *const con =
1239 (struct ngm_connect *) msg->data;
1242 if (msg->header.arglen != sizeof(*con)) {
1246 con->path[sizeof(con->path) - 1] = '\0';
1247 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1248 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1249 error = ng_path2node(here, con->path, &node2, NULL);
1252 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1257 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1259 if (msg->header.arglen != sizeof(*nam)) {
1263 nam->name[sizeof(nam->name) - 1] = '\0';
1264 error = ng_name_node(here, nam->name);
1269 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1272 if (msg->header.arglen != sizeof(*rmh)) {
1276 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1277 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1278 ng_destroy_hook(hook);
1283 struct nodeinfo *ni;
1286 /* Get response struct */
1291 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1297 /* Fill in node info */
1298 ni = (struct nodeinfo *) rp->data;
1299 if (here->name != NULL)
1300 strncpy(ni->name, here->name, NG_NODELEN);
1301 strncpy(ni->type, here->type->name, NG_TYPELEN);
1302 ni->id = ng_node2ID(here);
1303 ni->hooks = here->numhooks;
1309 const int nhooks = here->numhooks;
1310 struct hooklist *hl;
1311 struct nodeinfo *ni;
1315 /* Get response struct */
1320 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1321 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1326 hl = (struct hooklist *) rp->data;
1329 /* Fill in node info */
1331 strncpy(ni->name, here->name, NG_NODELEN);
1332 strncpy(ni->type, here->type->name, NG_TYPELEN);
1333 ni->id = ng_node2ID(here);
1335 /* Cycle through the linked list of hooks */
1337 LIST_FOREACH(hook, &here->hooks, hooks) {
1338 struct linkinfo *const link = &hl->link[ni->hooks];
1340 if (ni->hooks >= nhooks) {
1341 log(LOG_ERR, "%s: number of %s changed\n",
1342 __FUNCTION__, "hooks");
1345 if ((hook->flags & HK_INVALID) != 0)
1347 strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1348 strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1349 if (hook->peer->node->name != NULL)
1350 strncpy(link->nodeinfo.name,
1351 hook->peer->node->name, NG_NODELEN);
1352 strncpy(link->nodeinfo.type,
1353 hook->peer->node->type->name, NG_TYPELEN);
1354 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1355 link->nodeinfo.hooks = hook->peer->node->numhooks;
1365 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1366 struct namelist *nl;
1376 /* Count number of nodes */
1377 LIST_FOREACH(node, &nodelist, nodes) {
1378 if ((node->flags & NG_INVALID) == 0
1379 && (unnamed || node->name != NULL))
1383 /* Get response struct */
1388 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1389 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1394 nl = (struct namelist *) rp->data;
1396 /* Cycle through the linked list of nodes */
1398 LIST_FOREACH(node, &nodelist, nodes) {
1399 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1401 if (nl->numnames >= num) {
1402 log(LOG_ERR, "%s: number of %s changed\n",
1403 __FUNCTION__, "nodes");
1406 if ((node->flags & NG_INVALID) != 0)
1408 if (!unnamed && node->name == NULL)
1410 if (node->name != NULL)
1411 strncpy(np->name, node->name, NG_NODELEN);
1412 strncpy(np->type, node->type->name, NG_TYPELEN);
1413 np->id = ng_node2ID(node);
1414 np->hooks = node->numhooks;
1423 struct typelist *tl;
1425 struct ng_type *type;
1433 /* Count number of types */
1434 LIST_FOREACH(type, &typelist, types)
1437 /* Get response struct */
1442 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1443 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1448 tl = (struct typelist *) rp->data;
1450 /* Cycle through the linked list of types */
1452 LIST_FOREACH(type, &typelist, types) {
1453 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1455 if (tl->numtypes >= num) {
1456 log(LOG_ERR, "%s: number of %s changed\n",
1457 __FUNCTION__, "types");
1460 strncpy(tp->type_name, type->name, NG_TYPELEN);
1461 tp->numnodes = type->refs - 1; /* don't count list */
1468 case NGM_BINARY2ASCII:
1470 int bufSize = 20 * 1024; /* XXX hard coded constant */
1471 const struct ng_parse_type *argstype;
1472 const struct ng_cmdlist *c;
1473 struct ng_mesg *rp, *binary, *ascii;
1475 /* Data area must contain a valid netgraph message */
1476 binary = (struct ng_mesg *)msg->data;
1477 if (msg->header.arglen < sizeof(struct ng_mesg)
1478 || msg->header.arglen - sizeof(struct ng_mesg)
1479 < binary->header.arglen) {
1484 /* Get a response message with lots of room */
1485 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1490 ascii = (struct ng_mesg *)rp->data;
1492 /* Copy binary message header to response message payload */
1493 bcopy(binary, ascii, sizeof(*binary));
1495 /* Find command by matching typecookie and command number */
1496 for (c = here->type->cmdlist;
1497 c != NULL && c->name != NULL; c++) {
1498 if (binary->header.typecookie == c->cookie
1499 && binary->header.cmd == c->cmd)
1502 if (c == NULL || c->name == NULL) {
1503 for (c = ng_generic_cmds; c->name != NULL; c++) {
1504 if (binary->header.typecookie == c->cookie
1505 && binary->header.cmd == c->cmd)
1508 if (c->name == NULL) {
1509 FREE(rp, M_NETGRAPH);
1515 /* Convert command name to ASCII */
1516 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1519 /* Convert command arguments to ASCII */
1520 argstype = (binary->header.flags & NGF_RESP) ?
1521 c->respType : c->mesgType;
1522 if (argstype == NULL)
1523 *ascii->data = '\0';
1525 if ((error = ng_unparse(argstype,
1526 (u_char *)binary->data,
1527 ascii->data, bufSize)) != 0) {
1528 FREE(rp, M_NETGRAPH);
1533 /* Return the result as struct ng_mesg plus ASCII string */
1534 bufSize = strlen(ascii->data) + 1;
1535 ascii->header.arglen = bufSize;
1536 rp->header.arglen = sizeof(*ascii) + bufSize;
1541 case NGM_ASCII2BINARY:
1543 int bufSize = 2000; /* XXX hard coded constant */
1544 const struct ng_cmdlist *c;
1545 const struct ng_parse_type *argstype;
1546 struct ng_mesg *rp, *ascii, *binary;
1549 /* Data area must contain at least a struct ng_mesg + '\0' */
1550 ascii = (struct ng_mesg *)msg->data;
1551 if (msg->header.arglen < sizeof(*ascii) + 1
1552 || ascii->header.arglen < 1
1553 || msg->header.arglen
1554 < sizeof(*ascii) + ascii->header.arglen) {
1558 ascii->data[ascii->header.arglen - 1] = '\0';
1560 /* Get a response message with lots of room */
1561 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1566 binary = (struct ng_mesg *)rp->data;
1568 /* Copy ASCII message header to response message payload */
1569 bcopy(ascii, binary, sizeof(*ascii));
1571 /* Find command by matching ASCII command string */
1572 for (c = here->type->cmdlist;
1573 c != NULL && c->name != NULL; c++) {
1574 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1577 if (c == NULL || c->name == NULL) {
1578 for (c = ng_generic_cmds; c->name != NULL; c++) {
1579 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1582 if (c->name == NULL) {
1583 FREE(rp, M_NETGRAPH);
1589 /* Convert command name to binary */
1590 binary->header.cmd = c->cmd;
1591 binary->header.typecookie = c->cookie;
1593 /* Convert command arguments to binary */
1594 argstype = (binary->header.flags & NGF_RESP) ?
1595 c->respType : c->mesgType;
1596 if (argstype == NULL)
1599 if ((error = ng_parse(argstype, ascii->data,
1600 &off, (u_char *)binary->data, &bufSize)) != 0) {
1601 FREE(rp, M_NETGRAPH);
1606 /* Return the result */
1607 binary->header.arglen = bufSize;
1608 rp->header.arglen = sizeof(*binary) + bufSize;
1613 case NGM_TEXT_CONFIG:
1614 case NGM_TEXT_STATUS:
1616 * This one is tricky as it passes the command down to the
1617 * actual node, even though it is a generic type command.
1618 * This means we must assume that the msg is already freed
1619 * when control passes back to us.
1625 if (here->type->rcvmsg != NULL)
1626 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1627 /* Fall through if rcvmsg not supported */
1632 FREE(msg, M_NETGRAPH);
1637 * Send a data packet to a node. If the recipient has no
1638 * 'receive data' method, then silently discard the packet.
1641 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1643 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1647 if (hook && (hook->flags & HK_INVALID) == 0) {
1648 rcvdata = hook->peer->node->type->rcvdata;
1649 if (rcvdata != NULL)
1650 error = (*rcvdata)(hook->peer, m, meta);
1653 NG_FREE_DATA(m, meta);
1658 NG_FREE_DATA(m, meta);
1664 * Send a queued data packet to a node. If the recipient has no
1665 * 'receive queued data' method, then try the 'receive data' method above.
1668 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1670 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1674 if (hook && (hook->flags & HK_INVALID) == 0) {
1675 rcvdataq = hook->peer->node->type->rcvdataq;
1676 if (rcvdataq != NULL)
1677 error = (*rcvdataq)(hook->peer, m, meta);
1679 error = ng_send_data(hook, m, meta);
1684 NG_FREE_DATA(m, meta);
1692 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1695 ng_copy_meta(meta_p meta)
1701 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1704 meta2->allocated_len = meta->used_len;
1705 bcopy(meta, meta2, meta->used_len);
1709 /************************************************************************
1711 ************************************************************************/
1714 * Handle the loading/unloading of a netgraph node type module
1717 ng_mod_event(module_t mod, int event, void *data)
1719 struct ng_type *const type = data;
1725 /* Register new netgraph node type */
1727 if ((error = ng_newtype(type)) != 0) {
1732 /* Call type specific code */
1733 if (type->mod_event != NULL)
1734 if ((error = (*type->mod_event)(mod, event, data))) {
1735 type->refs--; /* undo it */
1736 LIST_REMOVE(type, types);
1743 if (type->refs > 1) { /* make sure no nodes exist! */
1746 if (type->refs == 0) {
1747 /* failed load, nothing to undo */
1751 if (type->mod_event != NULL) { /* check with type */
1752 error = (*type->mod_event)(mod, event, data);
1753 if (error != 0) { /* type refuses.. */
1758 LIST_REMOVE(type, types);
1764 if (type->mod_event != NULL)
1765 error = (*type->mod_event)(mod, event, data);
1767 error = 0; /* XXX ? */
1774 * Handle loading and unloading for this code.
1775 * The only thing we need to link into is the NETISR strucure.
1778 ngb_mod_event(module_t mod, int event, void *data)
1784 /* Register line discipline */
1786 error = register_netisr(NETISR_NETGRAPH, ngintr);
1790 /* You cant unload it because an interface may be using it. */
1800 static moduledata_t netgraph_mod = {
1805 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1806 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1807 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1808 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1810 /************************************************************************
1812 ************************************************************************/
1814 /* The structure for queueing across ISR switches */
1815 struct ng_queue_entry {
1817 struct ng_queue_entry *next;
1820 hook_p da_hook; /* target hook */
1825 struct ng_mesg *msg_msg;
1831 #define NGQF_DATA 0x01 /* the queue element is data */
1832 #define NGQF_MESG 0x02 /* the queue element is a message */
1834 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1835 static struct ng_queue_entry *ngqlast; /* last item queued */
1836 static const int ngqroom = 256; /* max items to queue */
1837 static int ngqsize; /* number of items in queue */
1839 static struct ng_queue_entry *ngqfree; /* free ones */
1840 static const int ngqfreemax = 256;/* cache at most this many */
1841 static int ngqfreesize; /* number of cached entries */
1846 static struct ng_queue_entry *
1849 struct ng_queue_entry *q;
1852 /* Could be guarding against tty ints or whatever */
1855 /* Try get a cached queue block, or else allocate a new one */
1856 if ((q = ngqfree) == NULL) {
1858 if (ngqsize < ngqroom) { /* don't worry about races */
1859 MALLOC(q, struct ng_queue_entry *,
1860 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1871 * Release a queue entry
1873 #define RETURN_QBLK(q) \
1876 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1878 (q)->next = ngqfree; \
1883 FREE((q), M_NETGRAPH); \
1888 * Running at a raised (but we don't know which) processor priority level,
1889 * put the data onto a queue to be picked up by another PPL (probably splnet)
1892 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1894 struct ng_queue_entry *q;
1898 NG_FREE_DATA(m, meta);
1901 if ((q = ng_getqblk()) == NULL) {
1902 NG_FREE_DATA(m, meta);
1906 /* Fill out the contents */
1907 q->flags = NGQF_DATA;
1909 q->body.data.da_hook = hook;
1910 q->body.data.da_m = m;
1911 q->body.data.da_meta = meta;
1912 s = splhigh(); /* protect refs and queue */
1913 hook->refs++; /* don't let it go away while on the queue */
1915 /* Put it on the queue */
1925 /* Schedule software interrupt to handle it later */
1926 schednetisr(NETISR_NETGRAPH);
1931 * Running at a raised (but we don't know which) processor priority level,
1932 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1935 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1937 struct ng_queue_entry *q;
1940 char *retaddr = NULL;
1943 /* Find the target node. */
1944 error = ng_path2node(here, address, &dest, &retaddr);
1946 FREE(msg, M_NETGRAPH);
1949 if ((q = ng_getqblk()) == NULL) {
1950 FREE(msg, M_NETGRAPH);
1952 FREE(retaddr, M_NETGRAPH);
1956 /* Fill out the contents */
1957 q->flags = NGQF_MESG;
1959 q->body.msg.msg_node = dest;
1960 q->body.msg.msg_msg = msg;
1961 q->body.msg.msg_retaddr = retaddr;
1962 s = splhigh(); /* protect refs and queue */
1963 dest->refs++; /* don't let it go away while on the queue */
1965 /* Put it on the queue */
1975 /* Schedule software interrupt to handle it later */
1976 schednetisr(NETISR_NETGRAPH);
1981 * Pick an item off the queue, process it, and dispose of the queue entry.
1982 * Should be running at splnet.
1988 struct ng_queue_entry *ngq;
1992 struct ng_mesg *msg;
1999 if ((ngq = ngqbase)) {
2000 ngqbase = ngq->next;
2006 switch (ngq->flags) {
2008 hook = ngq->body.data.da_hook;
2009 m = ngq->body.data.da_m;
2010 meta = ngq->body.data.da_meta;
2012 NG_SEND_DATAQ(error, hook, m, meta);
2013 ng_unref_hook(hook);
2016 node = ngq->body.msg.msg_node;
2017 msg = ngq->body.msg.msg_msg;
2018 retaddr = ngq->body.msg.msg_retaddr;
2020 if (node->flags & NG_INVALID) {
2021 FREE(msg, M_NETGRAPH);
2023 CALL_MSG_HANDLER(error, node, msg,
2028 FREE(retaddr, M_NETGRAPH);