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