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