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