NETGRAPH(4)

πŸ¦‹ NETGRAPH(4) πŸ¦‹

okay so bestie, welcome to the Kernel Interfaces Manual entry for netgraph, aka the graph based kernel networking subsystem. πŸ’…βœ¨ It's giving kernel networking, but make it modular.


✨ NAME ✨

netgraph β€” graph based kernel networking subsystem πŸ¦‹


πŸ’– DESCRIPTION πŸ’–

okay so the netgraph system is literally a uniform and modular system for implementing kernel objects that do various networking functions. Those objects? They're called nodes, and you can arrange them into arbitrarily complicated graphs. Nodes have hooks that connect two nodes together, and those hooks form the edges in the graph. Nodes communicate along the edges to process data, implement protocols, etc. periodt. 🫢

The aim of netgraph is to supplement rather than replace the existing kernel networking infrastructure. It provides:

  • A flexible way of combining protocol and link level drivers. πŸ’…
  • A modular way to implement new protocols.
  • A common framework for kernel entities to inter-communicate.
  • A reasonably fast, kernel-based implementation.

🧚 Nodes and Types 🧚

The most fundamental concept in netgraph is that of a node. All nodes implement a number of predefined methods which allow them to interact with other nodes in a well defined manner. ✨

Each node has a type, which is a static property of the node determined at node creation time. A node's type is described by a unique ASCII type name. The type implies what the node does and how it may be connected to other nodes. πŸ¦‹

In object-oriented language, types are classes, and nodes are instances of their respective class. All node types are subclasses of the generic node type, and hence inherit certain common functionality and capabilities (e.g., the ability to have an ASCII name). iykyk. πŸ’…

Nodes may be assigned a globally unique ASCII name which can be used to refer to the node. The name must not contain the characters . or :, and is limited to NG_NODESIZ characters (including the terminating NUL character).

Each node instance has a unique ID number which is expressed as a 32-bit hexadecimal value. This value may be used to refer to a node when there is no ASCII name assigned to it. πŸ‘‘


πŸͺ Hooks πŸͺ

Nodes are connected to other nodes by connecting a pair of hooks, one from each node. Data flows bidirectionally between nodes along connected pairs of hooks. A node may have as many hooks as it needs, and may assign whatever meaning it wants to a hook. 🌈

Hooks have these properties:

  • A hook has an ASCII name which is unique among all hooks on that node (other hooks on other nodes may have the same name). The name must not contain the characters . or :, and is limited to NG_HOOKSIZ characters (including the terminating NUL character).
  • A hook is always connected to another hook. That is, hooks are created at the time they are connected, and breaking an edge by removing either hook destroys both hooks.
  • A hook can be set into a state where incoming packets are always queued by the input queueing system, rather than being delivered directly. This can be used when the data is sent from an interrupt handler, and processing must be quick so as not to block other interrupts.
  • A hook may supply overriding receive data and receive message functions, which should be used for data and messages received through that hook in preference to the general node-wide methods.

A node may decide to assign special meaning to some hooks. For example, connecting to the hook named debug might trigger the node to start sending debugging information to that hook. main character energy. πŸ›βœ¨


🌊 Data Flow 🌊

Two types of information flow between nodes: data messages and control messages. Data messages are passed in mbuf chains along the edges in the graph, one edge at a time. The first mbuf in a chain must have the M_PKTHDR flag set. Each node decides how to handle data received through one of its hooks. πŸ’…

Along with data, nodes can also receive control messages. There are generic and type-specific control messages. Control messages have a common header format, followed by type-specific data, and are binary structures for efficiency. However, node types may also support conversion of the type-specific data between binary and ASCII formats, for debugging and human interface purposes (see the NGM_ASCII2BINARY and NGM_BINARY2ASCII generic control messages below). Nodes are not required to support these conversions. 😭

There are three ways to address a control message. no cap. If there is a sequence of edges connecting the two nodes, the message may be β€œsource routed” by specifying the corresponding sequence of ASCII hook names as the destination address for the message (relative addressing). If the destination is adjacent to the source, then the source node may simply specify (as a pointer in the code) the hook across which the message should be sent. Otherwise, the recipient node's global ASCII name (or equivalent ID-based name) is used as the destination address for the message (absolute addressing). The two types of ASCII addressing may be combined, by specifying an absolute start node and a sequence of hooks. Only the ASCII addressing modes are available to control programs outside the kernel; use of direct pointers is limited to kernel modules. 🧠✨

Messages often represent commands that are followed by a reply message in the reverse direction. To facilitate this, the recipient of a control message is supplied with a β€œreturn address” that is suitable for addressing a reply. πŸ’Œ

Each control message contains a 32-bit value, called a β€œtypecookie”, indicating the type of the message, i.e. how to interpret it. Typically each type defines a unique typecookie for the messages that it understands. However, a node may choose to recognize and implement more than one type of messages. πŸͺ

If a message is delivered to an address that implies that it arrived at that node through a particular hook (as opposed to having been directly addressed using its ID or global name) then that hook is identified to the receiving node. This allows a message to be re-routed or passed on, should a node decide that this is required, in much the same way that data packets are passed around between nodes. A set of standard messages for flow control and link management purposes are defined by the base system that are usually passed around in this manner. Flow control message would usually travel in the opposite direction to the data to which they pertain. πŸŒŠπŸ’œ


😭 Netgraph is (Usually) Functional 😭

In order to minimize latency, most netgraph operations are functional. That is, data and control messages are delivered by making function calls rather than by using queues and mailboxes. For example, if node A wishes to send a data mbuf to neighboring node B, it calls the generic netgraph data delivery function. This function in turn locates node B and calls B's β€œreceive data” method. There are exceptions to this. not me being shocked. πŸ™ˆ

Each node has an input queue, and some operations can be considered to be writers in that they alter the state of the node. Obviously, in an SMP world it would be bad if the state of a node were changed while another data packet were transiting the node. For this purpose, the input queue implements a reader/writer semantic so that when there is a writer in the node, all other requests are queued, and while there are readers, a writer, and any following packets are queued. In the case where there is no reason to queue the data, the input method is called directly, as mentioned above. πŸ’…

A node may declare that all requests should be considered as writers, or that requests coming in over a particular hook should be considered to be a writer, or even that packets leaving or entering across a particular hook should always be queued, rather than delivered directly (often useful for interrupt routines who want to get back to the hardware quickly). By default, all control message packets are considered to be writers unless specifically declared to be a reader in their definition. (See NGM_READONLY in <netgraph/ng_message.h>.) πŸ‘‘

While this mode of operation results in good performance, it has a few implications for node developers:

  • Whenever a node delivers a data or control message, the node may need to allow for the possibility of receiving a returning message before the original delivery function call returns.
  • Netgraph provides internal synchronization between nodes. Data always enters a β€œgraph” at an edge node. An edge node is a node that interfaces between netgraph and some other part of the system. Examples of β€œedge nodes” include device drivers, the socket, ether, tty, and ksocket node type. In these edge nodes, the calling thread directly executes code in the node, and from that code calls upon the netgraph framework to deliver data across some edge in the graph. From an execution point of view, the calling thread will execute the netgraph framework methods, and if it can acquire a lock to do so, the input methods of the next node. This continues until either the data is discarded or queued for some device or system entity, or the thread is unable to acquire a lock on the next node. In that case, the data is queued for the node, and execution rewinds back to the original calling entity. The queued data will be picked up and processed by either the current holder of the lock when they have completed their operations, or by a special netgraph thread that is activated when there are such items queued.
  • It is possible for an infinite loop to occur if the graph contains cycles. πŸ’€

So far, these issues have not proven problematical in practice. ✨


🫢 Interaction with Other Parts of the Kernel 🫢

A node may have a hidden interaction with other components of the kernel outside of the netgraph subsystem, such as device hardware, kernel protocol stacks, etc. In fact, one of the benefits of netgraph is the ability to join disparate kernel networking entities together in a consistent communication framework. 🌈

An example is the socket node type which is both a netgraph node and a socket(2) in the protocol family PF_NETGRAPH. Socket nodes allow user processes to participate in netgraph. Other nodes communicate with socket nodes using the usual methods, and the node hides the fact that it is also passing information to and from a cooperating user process. 🫢

Another example is a device driver that presents a node interface to the hardware. iconic. πŸ’…


🧡 Node Methods 🧡

Nodes are notified of the following actions via function calls to the following node methods, and may accept or reject that action (by returning the appropriate error code):

🌱 Creation of a new node

okay so the constructor for the type gets called. if making a new node is allowed, that constructor method can go ahead and allocate whatever special resources it needs. for nodes that are basically hardware in a trench coat, this typically happens during the device attach routine. and often a global ASCII name that matches the device name gets assigned right here too. πŸ’–

πŸͺ Creation of a new hook

the hook gets created and tentatively linked to the node, and the node is told the name that's gonna describe this hook. the node then sets up whatever special data structures it needs β€” or it can straight up reject the connection, based on the name of the hook. yes bestie, the name alone can be a dealbreaker. πŸ™ˆ

🀝 Successful connection of two hooks

once both ends have accepted their hooks and the links are made, the nodes get their moment to find out who their peer is across the link, and then they can decide to reject the connection. tear-down is automatic, don't stress. this is also the exact moment when a node can decide whether to set a particular hook (or its peer) into queueing mode. ✨

πŸ’” Destruction of a hook

the node gets notified that a connection broke. and here's the vibe: the node may treat some hooks as critical to operation and others as fully expendable β€” one hook disconnecting might be a totally fine, acceptable event, while for another hook it could mean a total shutdown of the node. different hooks, different energy. 😭

πŸ‘‹ Preshutdown of a node

this method runs before the real shutdown (which we get to below). while it's running, the node is fully operational and can send a "goodbye" message to its peers β€” or it can exclude itself from the chain and reconnect its peers together, exactly like the ng_tee(4) node type does. iconic exit behavior tbh. 🫢

πŸͺ¦ Shutdown of a node

this one lets a node clean up and make sure any actions that need to happen at this time actually happen. it's called by the generic (i.e., superclass) node destructor, which will get rid of the generic components of the node.

some nodes (usually the ones attached to a piece of hardware) may be persistent β€” meaning a shutdown breaks all edges and resets the node, but does not remove it. in that case, the shutdown method should not free its resources. instead it should clean up and then call the NG_NODE_REVIVE() macro to signal to the generic code that the shutdown is aborted.

and when the shutdown is started by the node itself, because of hardware removal or unloading (via ng_rmnode_self()), it should set the NGF_REALLY_DIE flag to signal to its own shutdown method that it is not to persist. like, no bestie, we're actually leaving this time. πŸ’€


πŸ“¨ Sending and Receiving Data

two other methods are also supported by all nodes:

πŸ“₯ Receive data message

a netgraph queueable request item β€” usually just called an item β€” is received by this function. the item contains a pointer to an mbuf.

the node is notified on which hook the item arrived, and can use that info in its processing decision.

the receiving node must always NG_FREE_M() the mbuf chain on completion or error, or pass it on to another node (or kernel module) which will then be responsible for freeing it. similarly, the item must be freed if it's not going to be passed on to another node, by using the NG_FREE_ITEM() macro.

if the item still holds references to mbufs at the time of freeing, then they'll be appropriately freed too. so if there's any chance the mbuf is gonna be changed or freed separately from the item, it is very important that it be retrieved using the NGI_GET_M() macro, which also removes the reference inside the item. (otherwise you get multiple frees of the same object. not cute. πŸ’€)

if you only need to peek at the contents of the mbufs, then it's fine to use the NGI_M() macro, which both reads and rewrites the mbuf pointer inside the item. πŸ‘‘

if a developer needs to pass any meta information along with the mbuf chain, they should use the mbuf_tags(9) framework. note that the old netgraph-specific meta-data format is obsoleted now. periodt.

the receiving node may also decide to defer the data by queueing it in the netgraph NETISR system (see below). it pulls this off by setting the HK_QUEUE flag in the flags word of the hook on which that data will arrive. the infrastructure will respect that bit and queue the data for delivery at a later time, rather than delivering it directly. a node may even decide to set the bit on the peer node, so that its own output packets get queued. sneaky but legal. ✨

and if a node wants to simplify its coding, it may elect to nominate a different receive data function for data received on a particular hook. it does this with the NG_HOOK_SET_RCVDATA(hook, fn) macro. the function receives the same arguments in every way, other than it will receive all (and only) packets from that hook. slay. πŸ’…

πŸ“¬ Receive control message

this method is called when a control message is addressed to the node. same as with received data, an item is received, with a pointer to the control message.

the message can be examined using the NGI_MSG() macro, or completely extracted from the item using the NGI_GET_MSG(), which also removes the reference within the item. if the item still holds a reference to the message when it's freed (using the NG_FREE_ITEM() macro), then the message will also be freed appropriately. if the reference has been removed, the node must free the message itself using the NG_FREE_MSG() macro.

a return address is always supplied, giving the address of the node that originated the message, so a reply message can be sent anytime later. the return address is retrieved from the item using the NGI_RETADDR() macro and is of type ng_ID_t. all control messages and replies are allocated with the malloc(9) type M_NETGRAPH_MSG β€” however, it's way more convenient to use the NG_MKMESSAGE() and NG_MKRESPONSE() macros to allocate and fill out a message. messages must be freed using the NG_FREE_MSG() macro.

if the message was delivered via a specific hook, that hook will also be made known β€” which lets you do things like flow-control messages and status change messages, where the node may want to forward the message out another hook to the one on which it arrived. 🌈

and just like with data, the node may elect to nominate a different receive message function for messages received on a particular hook, to simplify coding. it uses the NG_HOOK_SET_RCVMSG(hook, fn) macro for that. the function receives the same arguments in every way, other than it will receive all (and only) messages from that hook. πŸ’–

much use has been made of reference counts, so that nodes being freed of all references are automatically freed. and this behaviour has been tested and debugged to present a consistent and trustworthy framework for the "type module" writer to use. we love a reliable framework. 🫢


🧭 Addressing

the netgraph framework provides an unambiguous and simple-to-use method of specifically addressing any single node in the graph. the naming of a node is independent of its type, in that another node, or an external component, doesn't need to know anything about the node's type in order to address it so as to send it a generic message type. node and hook names should be chosen so as to make addresses meaningful. naming matters, bestie.

addresses are either absolute or relative.

  • an absolute address begins with a node name or ID, followed by a colon, followed by a sequence of hook names separated by periods. this addresses the node reached by starting at the named node and following the specified sequence of hooks.
  • a relative address includes only the sequence of hook names, implicitly starting hook traversal at the local node.

there are a couple of special possibilities for the node name. the name . (referred to as .:) always refers to the local node. also, nodes that have no global name may be addressed by their ID numbers, by enclosing the hexadecimal representation of the ID number within the square brackets. here are some examples of valid netgraph addresses:

.:
[3f]:
foo:
.:hook1
foo:hook1.hook2
[d80]:hook1

the following set of nodes might be created for a site with a single physical frame relay line having two active logical DLCI channels, with RFC 1490 frames on DLCI 16 and PPP frames over DLCI 20:

[type SYNC ]                  [type FRAME]                 [type RFC1490]
[ "Frame1" ](uplink)<-->(data)[<un-named>](dlci16)<-->(mux)[<un-named>  ]
[    A     ]                  [    B     ](dlci20)<---+    [     C      ]
                                                      |
                                                      |      [ type PPP ]
                                                      +>(mux)[<un-named>]
                                                             [    D     ]

you could always send a control message to node C from anywhere by using the name Frame1:uplink.dlci16. in this case, node C would also be notified that the message reached it via its hook mux. similarly, Frame1:uplink.dlci20 could reliably be used to reach node D, and node A could refer to node B as .:uplink, or simply uplink. conversely, B can refer to A as data. the address mux.data could be used by both nodes C and D to address a message to node A. πŸ”₯

note that this is only for control messages. in each of these cases, where a relative addressing mode is used, the recipient is notified of the hook on which the message arrived, as well as the originating node. this allows the option of hop-by-hop distribution of messages and state information.

data messages are only routed one hop at a time, by specifying the departing hook, with each node making the next routing decision. so when B receives a frame on hook data, it decodes the frame relay header to determine the DLCI, and then forwards the unwrapped frame to either C or D. πŸ¦‹

in a similar way, flow control messages may be routed in the reverse direction to outgoing data. for example, a "buffer nearly full" message from Frame1: would be passed to node B, which might decide to send similar messages to both nodes C and D. the nodes would use direct hook pointer addressing to route the messages. the message may have travelled from Frame1: to B as a synchronous reply, saving time and cycles. efficiency icon behavior. πŸ‘‘


πŸ—οΈ Netgraph Structures

structures are defined in <netgraph/netgraph.h> (for kernel structures only of interest to nodes) and <netgraph/ng_message.h> (for message definitions also of interest to user programs).

the two basic object types that are of interest to node authors are nodes and hooks. these two objects have the following properties that are also of interest to the node writers.

struct ng_node 🌸

okay bestie, node authors: you always use this typedef to declare your pointers, and you should never actually declare the structure itself. fr fr. that's the rule.

typedef struct ng_node *node_p;

So here's the tea β€” a node has these properties, and you get at them like this:

  • Validity β€” a driver or an interrupt routine might wanna vibe-check whether the node is still valid. the assumption is that whoever's calling is holding a reference on the node, so it hasn't been freed β€” but it could have been disabled or otherwise shut down. the NG_NODE_IS_VALID(node) macro hands you this state. eventually it should be basically impossible for code to run in an invalid node, but rn? that work is not done. not yet. πŸ™ˆ
  • Node ID (ng_ID_t) β€” grab it with the macro NG_NODE_ID(node).
  • Node name β€” optional, globally unique, a NUL terminated string. if there's a value in there, that's the name of the node. iconic.
if (NG_NODE_NAME(node)[0] != '\0') ...
if (strcmp(NG_NODE_NAME(node), "fred") == 0) ...
  • A node dependent opaque cookie β€” literally anything of the pointer type can live here. NG_NODE_SET_PRIVATE(node, value) sets it, NG_NODE_PRIVATE(node) gets it back. set and retrieve respectively, bestie.
  • Number of hooks β€” the NG_NODE_NUMHOOKS(node) macro retrieves this value.
  • Hooks β€” a node can have a bunch of hooks. there's a traversal method so you can test all of them for some condition: NG_NODE_FOREACH_HOOK(node, fn, arg, rethook) where fn is a function that gets called for each hook, takes the form fn(hook, arg), and returns 0 to terminate the search. if the search does get terminated, then rethook gets set to the hook where the search stopped. slay.

struct ng_hook πŸŽ€

node authors, same deal β€” always use this typedef to declare your hook pointers:

typedef struct ng_hook *hook_p;

The properties of a hook, and how you access them:

  • A hook dependent opaque cookie β€” anything of the pointer type, same energy as the node one. NG_HOOK_SET_PRIVATE(hook, value) sets it, NG_HOOK_PRIVATE(hook) retrieves it. respectively, obviously. πŸ’…
  • An associate node β€” the macro NG_HOOK_NODE(hook) finds the associated node.
  • A peer hook (hook_p) β€” the other hook in this connected pair. NG_HOOK_PEER(hook) finds the peer. it's giving soulmates ngl.
  • References β€” NG_HOOK_REF(hook) and NG_HOOK_UNREF(hook) increment and decrement the hook reference count accordingly. > ⚠️ after you decrement, you should always assume the hook has been freed unless you've got another reference still valid. do not play with this one.
  • Override receive functions β€” NG_HOOK_SET_RCVDATA(hook, fn) and NG_HOOK_SET_RCVMSG(hook, fn) let you set override methods that get used in preference to the generic receive data and receive message functions. to unset them, use the macros to set them to NULL. and heads up: they'll only be used for data and messages received on the hook on which they're set.

The maintenance of the names, reference counts, and the linked list of hooks for each node is all handled automatically by the netgraph subsystem. 🫢 typically a node's private info contains a back-pointer to the node or hook structure, and that counts as a new reference that has to be included in the reference count for the node. when the node constructor gets called, there's already a reference for this calculated in β€” so when the node is destroyed, it should remember to do a NG_NODE_UNREF() on the node. don't forget, bestie, the refcount will absolutely notice.

From a hook you can obtain the corresponding node, and from a node it's possible to traverse all the active hooks. the way that works is lowkey elegant.

A current example of how to define a node can always be seen in src/sys/netgraph/ng_sample.c and should be used as a starting point for new node writers. go read it, it's the blueprint. πŸ‘‘


Netgraph Message Structure ✨

Control messages have this structure:

#define NG_CMDSTRSIZ    32      /* Max command string (including null) */

struct ng_mesg {
  struct ng_msghdr {
    u_char      version;        /* Must equal NG_VERSION */
    u_char      spare;          /* Pad to 4 bytes */
    uint16_t    spare2;
    uint32_t    arglen;         /* Length of cmd/resp data */
    uint32_t    cmd;            /* Command identifier */
    uint32_t    flags;          /* Message status flags */
    uint32_t    token;          /* Reply should have the same token */
    uint32_t    typecookie;     /* Node type understanding this message */
    u_char      cmdstr[NG_CMDSTRSIZ];  /* cmd string +   */
  } header;
  char  data[];                 /* placeholder for actual data */
};

#define NG_ABI_VERSION  12              /* Netgraph kernel ABI version */
#define NG_VERSION      8               /* Netgraph message version */
#define NGF_ORIG        0x00000000      /* The msg is the original request */
#define NGF_RESP        0x00000001      /* The message is a response */

Control messages have that fixed header up there, followed by a variable length data section which depends on the type cookie and the command. every field, explained, no cap:

  • version β€” indicates the version of the netgraph message protocol itself. the current version is NG_VERSION.
  • arglen β€” this is the length of any extra arguments, which begin at data.
  • flags β€” indicates whether this is a command or a response control message.
  • token β€” the token is a means by which a sender can match a reply message to the corresponding command message; the reply always has the same token. it's the "which one is mine" tag. πŸ’–
  • typecookie β€” the corresponding node type's unique 32-bit value. if a node does not recognize the type cookie it must reject the message by returning EINVAL.

Each type should have an include file that defines the commands, argument format, and cookie for its own messages. the typecookie ensures that the same header file was included by both sender and receiver; when an incompatible change in the header file is made, the typecookie must be changed. the de-facto method for generating unique type cookies is to take the seconds from the Epoch at the time the header file is written (i.e., the output of date -u +%s).

There is a predefined typecookie NGM_GENERIC_COOKIE for the generic node type, and a corresponding set of generic messages which all nodes understand. the handling of these messages is automatic. πŸͺ„

  • cmd β€” the identifier for the message command. this is type specific, and is defined in the same header file as the typecookie.
  • cmdstr β€” room for a short human readable version of command (for debugging purposes only).

Some modules may choose to implement messages from more than one of the header files and thus recognize more than one type cookie. overachievers, we love them. πŸ’œ


Control Message ASCII Form 🌈

Control messages are in binary format for efficiency. however β€” for debugging and human interface purposes, and if the node type supports it β€” control messages may be converted to and from an equivalent ASCII form. the ASCII form is similar to the binary form, with two exceptions:

  1. The cmdstr header field must contain the ASCII name of the command, corresponding to the cmd header field.
  2. The arguments field contains a NUL-terminated ASCII string version of the message arguments.

In general, the arguments field of a control message can be any arbitrary C data type. netgraph includes parsing routines to support some pre-defined datatypes in ASCII with this simple syntax:

  • Integer types are represented by base 8, 10, or 16 numbers.
  • Strings are enclosed in double quotes and respect the normal C language backslash escapes.
  • IP addresses have the obvious form.
  • Arrays are enclosed in square brackets, with the elements listed consecutively starting at index zero. an element may have an optional index and equals sign (=) preceding it. whenever an element does not have an explicit index, the index is implicitly the previous element's index plus one.
  • Structures are enclosed in curly braces, and each field is specified in the form fieldname=value.
  • Any array element or structure field whose value is equal to its "default value" may be omitted. for integer types, the default value is usually zero; for string types, the empty string.
  • Array elements and structure fields may be specified in any order.

Each node type may define its own arbitrary types by providing the necessary routines to parse and unparse. ASCII forms defined for a specific node type are documented in the corresponding man page. πŸ“–


Generic Control Messages πŸ”₯

There are a number of standard predefined messages that will work for any node, because they're supported directly by the framework itself. these are defined in <netgraph/ng_message.h> along with the basic layout of messages and other similar information.

  • NGM_CONNECT β€” connect to another node, using the supplied hook names on either end.
  • NGM_MKPEER β€” construct a node of the given type and then connect to it using the supplied hook names.
  • NGM_SHUTDOWN β€” the target node should disconnect from all its neighbours and shut down. persistent nodes, like the ones representing physical hardware, might not disappear from the node namespace, but only reset themselves. the node must disconnect all of its hooks. > ⚠️ this may result in neighbors shutting themselves down, and possibly a cascading shutdown of the entire connected graph. yes really, it dominoes. 😭
  • NGM_NAME β€” assign a name to a node. nodes can exist without having a name, and this is the default for nodes created using the NGM_MKPEER method. such nodes can only be addressed relatively or by their ID number.
  • NGM_RMHOOK β€” ask the node to break a hook connection to one of its neighbours. both nodes will have their "disconnect" method invoked. either node may elect to totally shut down as a result.
  • NGM_NODEINFO β€” bestie, this one just asks the target node to describe itself. You get four fields back: the node name (only if it's actually named, ok), the node type, the node ID, and how many hooks are attached. That ID? It's an internal number that's unique to that node. Periodt. πŸͺͺ
  • NGM_LISTHOOKS β€” same tea as NGM_NODEINFO, but extra: you also get an array of fields describing each link, plus the description for the node sitting at the far end of that link. Full picture energy. πŸ”—
  • NGM_LISTNAMES β€” hands you an array of node descriptions (same shape as NGM_NODEINFO), where each entry describes a named node. And like… all named nodes get described. No one left out. πŸ’–
  • NGM_LISTNODES β€” literally NGM_LISTNAMES but with zero name-based gatekeeping: every node is listed, named or not. 🫢
  • NGM_LISTTYPES β€” returns a list of every netgraph type currently installed. The whole roster. πŸ‘‘
  • NGM_TEXT_STATUS β€” a node may hand back a text-formatted status message. Heads up though: the status info is determined entirely by the node type, it's not a universal thing. This is the only "generic" message that requires any support within the node itself, so a node can absolutely elect to not support it. If it does, the text response must be less than NG_TEXTRESPONSE bytes in length (presently 1024). It's there so you can return general status info in human readable form. πŸ“
  • NGM_BINARY2ASCII β€” converts a binary control message into its ASCII form. The entire control message that's getting converted is contained within the arguments field of the NGM_BINARY2ASCII message itself. If it works, the reply holds that same control message, in ASCII form. And here's the lowkey important bit: a node will typically only know how to translate messages that it itself understands, so the target node of the NGM_BINARY2ASCII is often the same node that would actually receive that message. iykyk. πŸ”„
  • NGM_ASCII2BINARY β€” the opposite of NGM_BINARY2ASCII, obviously. The entire control message to be converted, in ASCII form, lives in the arguments section of the NGM_ASCII2BINARY, and it only needs the flags, cmdstr, and arglen header fields filled in, plus the NUL-terminated string version of the arguments in the arguments field. If it succeeds, the reply contains the binary version of the control message. πŸ’…

πŸŒ€ Flow Control Messages πŸŒ€

So, on top of the control messages that affect nodes with respect to the graph, there are also a bunch of flow control messages defined. Right now? They're not handled automatically by the system, so if your nodes are gonna live in a graph that utilises flow control β€” and they'll be in the likely path of these messages β€” then those nodes need to handle them themselves. 😭

The default move for a node that doesn't understand these messages should be to pass them onto the next node. And hopefully some helper functions will assist in this eventually. Fingers crossed bestie. 🫢

These messages are also defined in <netgraph/ng_message.h> and they have a separate cookie, NG_FLOW_COOKIE, to help identify them. We're not going in depth on them here though. ✨


🌱 INITIALIZATION 🌱

The base netgraph code can either be statically compiled into the kernel, or else loaded dynamically as a KLD via kldload(8). πŸ’«

In the former case, include this in your kernel configuration file:

options NETGRAPH

You can also include selected node types in the kernel compilation, like for example:

options NETGRAPH
options NETGRAPH_SOCKET
options NETGRAPH_ECHO

Once the netgraph subsystem is loaded, individual node types may be loaded at any time as KLD modules via kldload(8). And here's the slay part: netgraph knows how to automatically do this. When a request to create a new node of unknown type type is made, netgraph will attempt to load the KLD module ng_⟨type⟩.ko. πŸ€–

Types can also be installed at boot time, since certain device drivers may want to export each instance of the device as a netgraph node. πŸš€

In general, new types can be installed at any time from within the kernel by calling ng_newtype(), supplying a pointer to the type's struct ng_type structure. And the NETGRAPH_INIT() macro automates this whole process by using a linker set. Iconic. ✨


πŸ‘‘ EXISTING NODE TYPES πŸ‘‘

Several node types currently exist. Each one is fully documented in its own man page, so go read those too:

  • SOCKET β€” this type implements two new sockets in the new protocol domain PF_NETGRAPH. The new sockets protocols are NG_DATA and NG_CONTROL, both of type SOCK_DGRAM. Typically one of each is associated with a socket node. When both sockets have closed, the node will shut down. The NG_DATA socket is used for sending and receiving data, while the NG_CONTROL socket is used for sending and receiving control messages. Data and control messages are passed using the sendto(2) and recvfrom(2) system calls, using a struct sockaddr_ng socket address. 🧦
  • HOLE β€” responds only to generic messages and is a "black hole" for data. Useful for testing. Always accepts new hooks. πŸ•³οΈ
  • ECHO β€” responds only to generic messages and always echoes data back through the hook from which it arrived. It returns any non-generic messages as their own response. Useful for testing. Always accepts new hooks. πŸ”Š
  • TEE β€” this node is useful for "snooping". It has 4 hooks: left, right, left2right, and right2left. Data entering from the right is passed to the left and duplicated on right2left, and data entering from the left is passed to the right and duplicated on left2right. Data entering from left2right is sent to the right and data from right2left to left. πŸ‘€
  • RFC1490 MUX β€” encapsulates/de-encapsulates frames encoded according to RFC 1490. Has a hook for the encapsulated packets (downstream) and one hook for each protocol (i.e., IP, PPP, etc.). πŸ“¦
  • FRAME RELAY MUX β€” encapsulates/de-encapsulates Frame Relay frames. Has a hook for the encapsulated packets (downstream) and one hook for each DLCI. 🚚
  • FRAME RELAY LMI β€” automatically handles frame relay "LMI" (link management interface) operations and packets. Automatically probes and detects which of several LMI standards is in use at the exchange. πŸ”
  • TTY β€” this node is also a line discipline. It simply converts between mbuf frames and sequential serial data, allowing a TTY to appear as a netgraph node. It has a programmable "hotkey" character. ⌨️
  • ASYNC β€” this node encapsulates and de-encapsulates asynchronous frames according to RFC 1662. This is used in conjunction with the TTY node type for supporting PPP links over asynchronous serial lines. πŸŒ€
  • ETHERNET β€” this node is attached to every Ethernet interface in the system. It allows capturing raw Ethernet frames from the network, as well as sending frames out of the interface. πŸ“‘
  • INTERFACE β€” this node is also a system networking interface. It has hooks representing each protocol family (IP, IPv6) and appears in the output of ifconfig(8). The interfaces are named "ng0", "ng1", etc. 🏷️
  • ONE2MANY β€” this node implements a simple round-robin multiplexer. You can use it, for example, to make several LAN ports act together to get a higher speed link between two machines. ⚑
  • Various PPP related nodes β€” there is a full multilink PPP implementation that runs in netgraph. The net/mpd5 port can use these modules to make a very low latency high capacity PPP system. It also supports PPTP VPNs using the PPTP node. πŸ›°οΈ
  • PPPOE β€” a server and client side implementation of PPPoE. Used in conjunction with either ppp(8) or the net/mpd5 port. 🌐
  • BRIDGE β€” this node, together with the Ethernet nodes, allows a very flexible bridging system to be implemented. πŸŒ‰
  • KSOCKET β€” this intriguing node looks like a socket to the system but diverts all data to and from the netgraph system for further processing. This allows such things as UDP tunnels to be almost trivially implemented from the command line. πŸŽ€

Refer to the section at the end of this man page for more nodes types. πŸ“–


πŸ“ NOTES πŸ“

Wanna know whether a named node exists? Try sending a control message to it (e.g., NGM_NODEINFO). If it doesn't exist, ENOENT will be returned. Simple as. πŸ’…

All data messages are mbuf chains with the M_PKTHDR flag set. 🧡

Nodes are responsible for freeing what they allocate. There are three exceptions though:

  1. Mbufs sent across a data link are never to be freed by the sender. In the case of error, they should be considered freed. ⚠️
  2. Messages sent using one of NG_SEND_MSG_*() family macros are freed by the recipient. As in the case above, the addresses associated with the message are freed by whatever allocated them, so the recipient should copy them if it wants to keep that information. πŸ“¬
  3. Both control messages and data are delivered and queued with a netgraph item. The item must be freed using NG_FREE_ITEM(item) or passed on to another node. πŸ—‘οΈ

πŸ—‚οΈ FILES πŸ—‚οΈ

  • <netgraph/netgraph.h> β€” Definitions for use solely within the kernel by netgraph nodes. 🧠
  • <netgraph/ng_message.h> β€” Definitions needed by any file that needs to deal with netgraph messages. βœ‰οΈ
  • <netgraph/ng_socket.h> β€” Definitions needed to use netgraph socket type nodes. 🧦
  • <netgraph/ng_>⟨type⟩.h β€” Definitions needed to use netgraph type nodes, including the type cookie definition. πŸͺ
  • /boot/kernel/netgraph.ko β€” The netgraph subsystem loadable KLD module. πŸ“¦
  • /boot/kernel/ng_⟨type⟩.ko β€” Loadable KLD module for node type type. πŸ“¦
  • src/sys/netgraph/ng_sample.c β€” Skeleton netgraph node. Use this as a starting point for new node types. 🦴

🫢 USER MODE SUPPORT 🫢

There's a library for supporting user-mode programs that wish to interact with the netgraph system. See netgraph(3) for details. πŸ“š

Two user-mode support programs, ngctl(8) and nghook(8), are available to assist manual configuration and debugging. πŸ› οΈ

And there are a few useful techniques for debugging new node types. First: implementing new node types in user-mode first makes debugging easier. The tee node type is also useful for debugging, especially in conjunction with ngctl(8) and nghook(8). πŸ›

Also look in /usr/share/examples/netgraph for solutions to several common networking problems, solved using netgraph. πŸŽ€

πŸ‘€ SEE ALSO πŸ’–

okay bestie, this is the part where the page goes "and here's the ENTIRE extended family, say hi" β€” because netgraph is nothing without its node-type girlies. every single one of these is a real manual page you can go read, no cap:

that's fifty-four references, babe. fifty-four. the netgraph cinematic universe is MASSIVE and it has a page for literally every single member of the cast. stan a modular framework that documents itself fr fr 🫢

and yeah, note the case on ng_UI(4) β€” that uppercase UI is not a typo, it is exactly how it's spelled, so type it how you see it, bestie. lowercase it and the man page will simply not find you. πŸ’€

πŸ“œ HISTORY 🌸

okay so storytime, gather round, this is genuinely iconic:

  • the netgraph system was designed and first implemented at Whistle Communications, Inc. β€” in a version of FreeBSD 2.2 that was customized for the Whistle InterJet. πŸŽ€
  • and then it made its debut in the main tree in FreeBSD 3.4. ✨

so yeah. it was built for one specific little box and then it ate and became a whole general-purpose kernel subsystem. glow-up of the century, no notes, periodt. πŸ‘‘


πŸ’œ AUTHORS πŸ’…

give it up for the main characters:

  • Julian Elischer <julian@FreeBSD.org> β€” the originator, the blueprint, the moment.
  • with contributions by Archie Cobbs <archie@FreeBSD.org>. πŸ’–

two names, one framework, legendary behaviour. if you ever ship a node type of your own, you're standing on their shoulders, iykyk. πŸ¦‹


aaaand that's the whole page, bestie!! πŸŽ‰ you just read NETGRAPH(4) top to bottom, which honestly makes you lowkey unstoppable. go forth, make nodes, connect hooks, and remember: the graph is a graph, not a tree. 🧚

this copy came from the Debian folks, dated November 25, 2013, and it's filed under NETGRAPH(4) in section 4 (kernel interfaces). mwah, take care of her. πŸ’‹ bye babes 🫢✨

πŸ“¦ where this page comes from