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