Something went wrong. Try again.
A reader for SNMP MIB modules: SMIv1 and SMIv2, in Zig.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A set of MIB modules, stitched into one tree.//!//! A module on its own says almost nothing about where its objects live.//! `IF-MIB` places `ifTable` at `{ interfaces 2 }`, and `interfaces` is//! defined in `RFC1213-MIB`, which places it under `mib-2`, which//! `SNMPv2-SMI` places under `mgmt`, and so on to `iso`. So resolution is a//! pass over a *collection*, and no module can be resolved alone.//!//! ## Why this is a fixpoint rather than a walk//!//! There is no ordering anywhere. An assignment may name a parent defined//! later in the same file, or in a module not yet read, or in one that names//! something back. So resolution repeats until a pass resolves nothing new,//! which terminates because each pass either places at least one name or is//! the last.//!//! In practice it converges in a handful of passes over thousands of modules,//! because MIBs are written roughly top-down even though nothing requires it.//!//! ## Names are global, which is net-snmp's model and not ASN.1's//!//! ASN.1 scopes a name to its module and `IMPORTS` brings it in. net-snmp//! does not work that way: it keeps one table, and `snmptranslate -Tz` prints//! a flat list of every name it knows. Two modules defining the same name//! collide, which net-snmp reports as a warning and which this resolves by//! keeping the first definition seen.//!//! The reason to match net-snmp rather than the standard is that the point of//! this library is to agree with net-snmp about what `sysDescr.0` means, and//! a stricter scoping would disagree on exactly the files where vendors are//! sloppy -- which is most of them.
const std = @import("std");const Allocator = std.mem.Allocator;const assert = std.debug.assert;const testing = std.testing;
const Clauses = @import("Clauses.zig");const Lexer = @import("Lexer.zig");const Parser = @import("Parser.zig");
const Registry = @This();
/// The longest OID this will build. RFC 3416 caps an SNMP OID at 128/// sub-identifiers, and a MIB defining something deeper could not be queried/// anyway.pub const max_depth = 128;
gpa: Allocator,arena: std.heap.ArenaAllocator,modules: std.ArrayList(Parser.Module),/// Every name that has a place, by name.nodes: std.StringHashMapUnmanaged(Node),/// Every definition that got a place, including the ones `nodes` discarded.////// The two differ for exactly the reason a name and an OID are not the same/// kind of question. `linux` is defined twice --- under `ucdSnmpAgent` at/// 1.3.6.1.4.1.2021.250.10 and under `netSnmpAgentOIDs` at/// 1.3.6.1.4.1.8072.3.2.10 --- so a map from *name* to node has to choose,/// and choosing is right: somebody writing `linux` on a command line means/// one of them. But going the other way there is nothing to choose between:/// the two OIDs are different, and an agent answering `sysObjectID` with/// 8072.3.2.10 is naming the second one whichever the map kept.////// So `nodes` answers "which OID is this name" and this answers "what is this/// OID called", and the 18 names net-snmp's `-Tz` lists twice are exactly the/// ones where that distinction shows.placed: std.ArrayList(Node),/// Every *type* definition -- textual conventions and type assignments -- in/// the order the modules were added.////// Kept apart from `nodes` because a type has no position: `DisplayString`/// names no object and appears nowhere in the OID tree, and putting it in the/// same table would put it in `-Tz` output that net-snmp does not list. The/// two namespaces do not collide in practice either, ASN.1 requiring a type/// to be capitalised and an object not to be.////// Unlike `nodes` this keeps *every* definition rather than the first,/// because which one is meant depends on who is asking. `DisplayString` is a/// plain `OCTET STRING` in RFC1213-MIB and a textual convention with a/// DISPLAY-HINT in SNMPv2-TC, and an object in a module importing it from/// SNMPv2-TC means the second whichever was read first.types: std.ArrayList(Type),/// Name to the first definition of it in `types`; the rest follow `Type.next`.type_index: std.StringHashMapUnmanaged(u32),/// Module name to its entry in `modules`, for reading its IMPORTS.module_index: std.StringHashMapUnmanaged(u32),/// Assignments not yet placed, retried each pass.pending: std.ArrayList(Pending),/// Names defined more than once, kept so a caller can report them the way/// net-snmp's `-Pw` does.conflicts: std.ArrayList(Conflict),
pub const Node = struct { name: []const u8, /// Which module defined it. Empty for the roots, which no module does. module: []const u8, /// The absolute OID. oid: []const u32, kind: Parser.Kind, /// The macro's clauses, still as the span of source the parser kept. /// Empty for the roots and for a plain `OBJECT IDENTIFIER` assignment, /// neither of which has a body. Read it with `clausesOf`. /// /// A span rather than a parsed `Clauses`, and the difference is 800 /// megabytes. A `Clauses` is around 250 bytes --- twenty-odd fields, most /// of them slices, two of them whole `Syntax` structs --- and a `Node` /// lives in the name table, in `placed`, and in whatever array a caller /// sorts, so every byte of it is paid for three times or more. Over /// Cisco's corpus that is 152,050 nodes, and measuring it gave a peak of /// 885 MB against net-snmp's 75 MB for the same files. /// /// Keeping the span restores what `Parser` was built for: it stops at the /// shape every macro shares and keeps the body unparsed *so that* the /// clause pass can be separate. Parsing it eagerly into every node threw /// that away, and parsing it on demand costs microseconds at the point /// where somebody actually wants to know what an object's syntax is. body: []const u8 = "", /// Which module this came from, as a position in the order they were /// added. `std.math.maxInt(u32)` for the roots, which came from none. module_order: u32 = std.math.maxInt(u32),};
/// A textual convention or a plain type assignment.pub const Type = struct { name: []const u8, module: []const u8, /// The next definition of this same name, if a later module gave one. next: ?u32 = null, /// Whether it was written as a `TEXTUAL-CONVENTION` or as `Name ::= /// <type>`. Only the former may carry a DISPLAY-HINT. kind: Parser.Kind, /// What it is defined as, which may itself name another type. syntax: ?Clauses.Syntax, clauses: Clauses.Clauses = .{},};
/// A `SYNTAX` followed through the textual conventions to a base type.pub const ResolvedSyntax = struct { /// The base type it bottoms out in, or null if the chain left this set of /// modules before reaching one. base: ?Clauses.Base, /// The last type named on the way down, which is what net-snmp prints as /// `-- TEXTUAL CONVENTION <name>`. Null when the syntax was already a /// base type. convention: ?[]const u8, /// The first DISPLAY-HINT found on the way down. An object has none of /// its own; it inherits its type's. display_hint: ?[]const u8, /// The enumeration or bit list, from wherever in the chain it was given. named_numbers: []const Clauses.NamedNumber, /// The narrowest constraint found, which is the first: a textual /// convention may only narrow what it refines. constraint: ?Clauses.Constraint,};
pub const Conflict = struct { name: []const u8, /// The module that defined it first and therefore won. kept: []const u8, /// The module whose definition was discarded. discarded: []const u8,};
const Pending = struct { assignment: Parser.Assignment, module: []const u8, /// Where that module came in the order they were added. Carried because /// the *resolution* order is not the add order -- an assignment whose /// parent is defined in a later module waits a pass -- and which of two /// identical definitions is described should be a decision rather than a /// side effect of that. module_order: u32,};
pub fn init(gpa: Allocator) Registry { return .{ .gpa = gpa, .arena = .init(gpa), .modules = .empty, .nodes = .empty, .placed = .empty, .types = .empty, .type_index = .empty, .module_index = .empty, .pending = .empty, .conflicts = .empty, };}
pub fn deinit(r: *Registry) void { r.modules.deinit(r.gpa); r.nodes.deinit(r.gpa); r.placed.deinit(r.gpa); r.types.deinit(r.gpa); r.type_index.deinit(r.gpa); r.module_index.deinit(r.gpa); r.pending.deinit(r.gpa); r.conflicts.deinit(r.gpa); r.arena.deinit(); r.* = undefined;}
/// The three roots, which no module defines because they are where ASN.1/// itself begins.////// net-snmp seeds the same three. Without them nothing resolves: every MIB's/// chain of parents ends at `iso`, and `iso` is defined nowhere.pub const roots = [_]struct { []const u8, u32 }{ .{ "ccitt", 0 }, .{ "iso", 1 }, .{ "joint-iso-ccitt", 2 },};
pub const AddError = Parser.Error;
/// Parses `source` and adds its assignments to the set. Nothing is resolved/// until `resolve` is called, because a module may depend on one not yet/// added.pub fn addModule(r: *Registry, source: []const u8, options: Lexer.Options) AddError!void { const arena = r.arena.allocator(); // The source is copied because the module's every slice points into it, // and a caller is entitled to free what it handed over. const owned = try arena.dupe(u8, source); const module = try Parser.parse(arena, owned, options); const order: u32 = @intCast(r.modules.items.len); if (!r.module_index.contains(module.name)) { try r.module_index.put(r.gpa, module.name, @intCast(r.modules.items.len)); } try r.modules.append(r.gpa, module); for (module.assignments) |a| { if (!a.kind.hasOid()) { // A type names no object, so it is not placed; it is recorded so // that a SYNTAX naming it can be followed down to a base type. // A TRAP-TYPE reaches here too and is neither -- its `::= 5` is a // trap number, not a position -- so it is skipped outright. if (a.kind == .trap_type) continue; try r.addType(arena, a, module.name); continue; } try r.pending.append(r.gpa, .{ .assignment = a, .module = module.name, .module_order = order, }); }}
/// Records a type assignment or textual convention. Every definition is kept;/// see `types` for why.fn addType(r: *Registry, arena: Allocator, a: Parser.Assignment, module: []const u8) AddError!void { const entry: Type = switch (a.kind) { // A textual convention's body is a clause list ending in its SYNTAX. .textual_convention => blk: { const c = try Clauses.parse(arena, a.body, .{}); break :blk .{ .name = a.name, .module = module, .kind = a.kind, .syntax = c.syntax, .clauses = c, }; }, // A plain type assignment's body is the type and nothing else. else => .{ .name = a.name, .module = module, .kind = a.kind, .syntax = try Clauses.parseSyntax(arena, a.body, .{}), }, }; const index: u32 = @intCast(r.types.items.len); try r.types.append(r.gpa, entry); const got = try r.type_index.getOrPut(r.gpa, a.name); if (!got.found_existing) { got.value_ptr.* = index; return; } // Onto the end of the chain, so the order is the order the modules were // added, which is the order a caller controls. var i = got.value_ptr.*; while (r.types.items[i].next) |next| i = next; r.types.items[i].next = index;}
/// Places every name that can be placed.////// Returns how many are still unresolved, which is not necessarily a fault: a/// set of modules that does not include everything it imports will leave the/// dependents unplaced, and that is the normal state of a directory somebody/// pointed at.pub fn resolve(r: *Registry) Allocator.Error!usize { const arena = r.arena.allocator();
for (roots) |root| { const oid = try arena.dupe(u32, &.{root[1]}); const node: Node = .{ .name = root[0], .module = "", .oid = oid, .kind = .object_identifier, }; try r.nodes.put(r.gpa, root[0], node); try r.placed.append(r.gpa, node); }
// Until a pass places nothing new. Each pass is O(pending), and the // number of passes is the depth of the deepest forward reference -- // small, because MIBs are written roughly top-down. while (true) { var placed: usize = 0; // Compacted in place rather than `swapRemove`d, because the order of // this list is what decides a conflict: the first definition of a // name wins, and `swapRemove` moves the last element into the hole, // so which of two definitions was tried first came down to how many // names happened to resolve before them. That made the result depend // on nothing a caller could see or control. var write: usize = 0; for (r.pending.items) |p| { if (try r.place(p)) { placed += 1; continue; } r.pending.items[write] = p; write += 1; } r.pending.shrinkRetainingCapacity(write); if (placed == 0) break; } return r.pending.items.len;}
/// Tries to give one assignment an absolute OID. Returns false if its parent/// is not yet known.fn place(r: *Registry, p: Pending) Allocator.Error!bool { const arena = r.arena.allocator(); const parts = p.assignment.oid.?;
var buffer: [max_depth]u32 = undefined; var len: usize = 0;
for (parts, 0..) |part, index| { switch (part) { .number => |n| { // A leading bare number is an absolute OID -- `{ 1 3 6 1 }` -- // and a later one is a step down from what came before. if (len == max_depth) return true; // too deep; drop it rather than overflow buffer[len] = n; len += 1; }, .name => |name| { if (index == 0) { const parent = r.nodes.get(name) orelse return false; if (parent.oid.len > max_depth) return true; @memcpy(buffer[0..parent.oid.len], parent.oid); len = parent.oid.len; } else { // A bare name after the first element has no number, so // there is nothing to descend by. Real MIBs do not do // this; a malformed one might. return true; } }, .named_number => |nn| { if (index == 0) { // `{ iso(1) ... }` -- the number is the whole answer. buffer[0] = nn.number; len = 1; } else { if (len == max_depth) return true; buffer[len] = nn.number; len += 1; } // A named number *defines* that name too. `{ iso org(3) // dod(6) 1 }` is where `org` and `dod` come from in // RFC1155-SMI, and without registering them nothing under // them resolves. if (!r.nodes.contains(nn.name)) { const oid = try arena.dupe(u32, buffer[0..len]); try r.nodes.put(r.gpa, nn.name, .{ .name = nn.name, .module = p.module, .oid = oid, .kind = .object_identifier, }); } }, } }
if (len == 0) return true;
if (r.nodes.getPtr(p.assignment.name)) |existing| { // Defined twice at different places. net-snmp warns and this keeps // the first, which is the same answer for the case that matters -- a // vendor MIB redefining a standard name -- provided the standard // modules were added first. if (!std.mem.eql(u32, existing.oid, buffer[0..len])) { try r.conflicts.append(r.gpa, .{ .name = p.assignment.name, .kept = existing.module, .discarded = p.module, }); // Discarded as an answer to "which OID is `linux`", kept as an // answer to "what is 1.3.6.1.4.1.8072.3.2.10 called". See // `placed`. try r.placed.append(r.gpa, .{ .name = p.assignment.name, .module = p.module, .oid = try arena.dupe(u32, buffer[0..len]), .kind = p.assignment.kind, .body = p.assignment.body, .module_order = p.module_order, }); return true; }
// Defined twice at the *same* place, which is not a conflict and is // extremely common: RFC1213-MIB and IF-MIB both define `ifDescr`, the // first in SMIv1 and the second in SMIv2, and they agree about where // it is and differ about almost everything else -- `ACCESS` against // `MAX-ACCESS`, `mandatory` against `current`, `Counter` against // `Counter32`. // // Which one is described has to be decided, because otherwise it is // decided by the fixpoint: a definition whose parent chain is // complete within its own module is placed a pass earlier than one // reaching into another, so RFC1213-MIB beat IF-MIB for no better // reason than being self-contained. Taking the earlier module makes // it the caller's choice, expressed by the order they add modules in. if (p.module_order < existing.module_order) { existing.module = p.module; existing.kind = p.assignment.kind; existing.body = p.assignment.body; existing.module_order = p.module_order; } return true; }
const oid = try arena.dupe(u32, buffer[0..len]); const node: Node = .{ .name = p.assignment.name, .module = p.module, .oid = oid, .kind = p.assignment.kind, .body = p.assignment.body, .module_order = p.module_order, }; try r.nodes.put(r.gpa, p.assignment.name, node); try r.placed.append(r.gpa, node); return true;}
/// Every definition that got a place, in the order they were placed. See/// `placed` for why this is not the same set as `nodes`.pub fn placedNodes(r: *const Registry) []const Node { return r.placed.items;}
/// The clauses of a node, parsed on demand.////// `gpa` owns what comes back, and `Clauses` has no `deinit` of its own/// because everything in it is either a slice of the source or one array ---/// so an arena is the natural thing to pass, and freeing it is the whole of/// the cleanup. See `Node.body` for why this is not done once at load time.pub fn clausesOf(r: *const Registry, gpa: Allocator, node: Node) Allocator.Error!Clauses.Clauses { _ = r; if (node.body.len == 0) return .{}; return Clauses.parse(gpa, node.body, .{});}
/// The type of that name as seen from `from_module`, or null.////// A MIB's type names are resolved through its `IMPORTS`, and that is not a/// formality: `DisplayString` is a bare `OCTET STRING` in RFC1213-MIB and a/// textual convention carrying `DISPLAY-HINT "255a"` in SNMPv2-TC, and/// `OwnerString` is a different length in IF-MIB and in RMON-MIB. A module/// means the one it imported, and answering with whichever was read first/// gives an object in RMON-MIB the wrong string length.////// The three steps are the ones RFC 2578 §3.2 describes: a name defined in/// the module itself, then a name the module imports and the module it/// imports it from, then -- because a corpus is never complete and half the/// vendor MIBs forget an import -- any definition at all.pub fn lookupType(r: *const Registry, name: []const u8, from_module: []const u8) ?Type { const first = r.type_index.get(name) orelse return null;
if (from_module.len != 0) { // Defined here. var i: ?u32 = first; while (i) |index| : (i = r.types.items[index].next) { if (std.mem.eql(u8, r.types.items[index].module, from_module)) { return r.types.items[index]; } } // Imported from somewhere named. if (r.module_index.get(from_module)) |module_index| { for (r.modules.items[module_index].imports) |import| { for (import.symbols) |symbol| { if (!std.mem.eql(u8, symbol, name)) continue; var j: ?u32 = first; while (j) |index| : (j = r.types.items[index].next) { if (std.mem.eql(u8, r.types.items[index].module, import.from)) { return r.types.items[index]; } } } } } }
return r.types.items[first];}
/// Follows a `SYNTAX` down through the textual conventions to a base type.////// `ifPhysAddress SYNTAX PhysAddress` is `PhysAddress ::= TEXTUAL-CONVENTION/// DISPLAY-HINT "1x:" SYNTAX OCTET STRING`, and what a manager needs from/// that is all three things at once: the base type to decode the value, the/// display hint to render it, and the convention's name to say why. net-snmp/// prints exactly those three, which is what makes this checkable:////// ```/// -- TEXTUAL CONVENTION PhysAddress/// SYNTAX OCTET STRING/// DISPLAY-HINT "1x:"/// ```////// A chain that leaves this set of modules -- a MIB importing a convention/// from one not loaded -- stops with a null `base` rather than an error,/// because that is the normal state of a directory somebody pointed at.pub fn resolveSyntax( r: *const Registry, syntax: Clauses.Syntax, from_module: []const u8,) ResolvedSyntax { var result: ResolvedSyntax = .{ .base = syntax.base, .convention = null, .display_hint = null, .named_numbers = syntax.named_numbers, .constraint = syntax.constraint, }; if (syntax.base != null) return result;
var name = syntax.name; // Each step is resolved from the module that named it, not from the one // that started the chain: if RMON-MIB's `OwnerString` is defined in terms // of `DisplayString`, which `DisplayString` it meant is RMON-MIB's // question to answer. var module = from_module; // Bounded because a MIB may define `A ::= B` and `B ::= A`, and a corpus // of thousands of vendor files is not a place to assume otherwise. var steps: usize = 0; while (steps < max_type_depth) : (steps += 1) { const t = r.lookupType(name, module) orelse return result; // Only a TEXTUAL-CONVENTION is one. `IfEntry ::= SEQUENCE { ... }` is // an ordinary type assignment, and calling a row type a convention // would say something false about it. if (t.kind == .textual_convention) result.convention = t.name; if (t.clauses.display_hint) |hint| { if (result.display_hint == null) result.display_hint = hint; } const next = t.syntax orelse return result; if (result.named_numbers.len == 0) result.named_numbers = next.named_numbers; if (result.constraint == null) result.constraint = next.constraint; if (next.base) |base| { result.base = base; return result; } if (std.mem.eql(u8, next.name, name) and std.mem.eql(u8, t.module, module)) return result; name = next.name; module = t.module; } return result;}
/// How many textual conventions may be chained before this gives up. Real/// MIBs go two or three deep; anything beyond that is a cycle.const max_type_depth = 32;
/// The node of that name.pub fn lookup(r: *const Registry, name: []const u8) ?Node { return r.nodes.get(name);}
/// How many names have a place.pub fn count(r: *const Registry) usize { return r.nodes.count();}
/// Every node, in an order nothing should depend on.pub fn iterator(r: *const Registry) std.StringHashMapUnmanaged(Node).ValueIterator { return r.nodes.valueIterator();}
/// Writes an OID in dotted decimal.pub fn formatOid(oid: []const u32, w: *std.Io.Writer) std.Io.Writer.Error!void { for (oid, 0..) |sub, i| { if (i != 0) try w.writeByte('.'); try w.print("{d}", .{sub}); }}
// -- tests ------------------------------------------------------------------
/// The tests parse clauses with the testing allocator, which reports a leak,/// so what `Clauses.parse` allocated has to go back. A caller with an arena/// -- which is what the doc comment recommends -- needs none of this.fn freeClauses(c: Clauses.Clauses) void { const gpa = testing.allocator; if (c.syntax) |x| { gpa.free(x.named_numbers); gpa.free(x.fields); if (x.constraint) |k| gpa.free(k.ranges); } if (c.write_syntax) |x| { gpa.free(x.named_numbers); gpa.free(x.fields); if (x.constraint) |k| gpa.free(k.ranges); } if (c.index) |i| gpa.free(i); gpa.free(c.objects); gpa.free(c.revisions);}
fn expectOid(r: *const Registry, name: []const u8, expected: []const u32) !void { const node = r.lookup(name) orelse { std.debug.print("\n{s} was not resolved\n", .{name}); return error.NotResolved; }; try testing.expectEqualSlices(u32, expected, node.oid);}
test "the roots, which no module defines" { var r: Registry = .init(testing.allocator); defer r.deinit(); _ = try r.resolve(); // Without these nothing resolves at all: every chain of parents ends at // iso, and iso is defined nowhere. try expectOid(&r, "iso", &.{1}); try expectOid(&r, "ccitt", &.{0}); try expectOid(&r, "joint-iso-ccitt", &.{2});}
test "the path down to mib-2, which is the shape of every MIB" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\SNMPv2-SMI DEFINITIONS ::= BEGIN \\org OBJECT IDENTIFIER ::= { iso 3 } \\dod OBJECT IDENTIFIER ::= { org 6 } \\internet OBJECT IDENTIFIER ::= { dod 1 } \\mgmt OBJECT IDENTIFIER ::= { internet 2 } \\mib-2 OBJECT IDENTIFIER ::= { mgmt 1 } \\private OBJECT IDENTIFIER ::= { internet 4 } \\enterprises OBJECT IDENTIFIER ::= { private 1 } \\END , .{}); try testing.expectEqual(@as(usize, 0), try r.resolve());
try expectOid(&r, "internet", &.{ 1, 3, 6, 1 }); try expectOid(&r, "mib-2", &.{ 1, 3, 6, 1, 2, 1 }); try expectOid(&r, "enterprises", &.{ 1, 3, 6, 1, 4, 1 });}
test "a named number defines the name as well as the step" { // RFC1155-SMI writes the whole path in one line, and `org` and `dod` // exist only because of the parenthesised numbers. Without registering // them, nothing that names them resolves. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\RFC1155-SMI DEFINITIONS ::= BEGIN \\internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } \\directory OBJECT IDENTIFIER ::= { internet 1 } \\END , .{}); try testing.expectEqual(@as(usize, 0), try r.resolve()); try expectOid(&r, "org", &.{ 1, 3 }); try expectOid(&r, "dod", &.{ 1, 3, 6 }); try expectOid(&r, "internet", &.{ 1, 3, 6, 1 }); try expectOid(&r, "directory", &.{ 1, 3, 6, 1, 1 });}
test "order does not matter, which is why this is a fixpoint" { // Written bottom-up, so every assignment names a parent defined later. // A single pass would place only `org`. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\M DEFINITIONS ::= BEGIN \\deepest OBJECT IDENTIFIER ::= { deeper 1 } \\deeper OBJECT IDENTIFIER ::= { deep 2 } \\deep OBJECT IDENTIFIER ::= { org 3 } \\org OBJECT IDENTIFIER ::= { iso 3 } \\END , .{}); try testing.expectEqual(@as(usize, 0), try r.resolve()); try expectOid(&r, "deepest", &.{ 1, 3, 3, 2, 1 });}
test "across modules, in either order" { // IF-MIB names `interfaces`, which RFC1213-MIB defines. Added the wrong // way round on purpose. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS OBJECT-TYPE FROM SNMPv2-SMI; \\ifTable OBJECT-TYPE \\ SYNTAX SEQUENCE OF IfEntry \\ ::= { interfaces 2 } \\END , .{}); try r.addModule( \\RFC1213-MIB DEFINITIONS ::= BEGIN \\mib-2 OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 2 1 } \\interfaces OBJECT IDENTIFIER ::= { mib-2 2 } \\END , .{}); try testing.expectEqual(@as(usize, 0), try r.resolve()); try expectOid(&r, "ifTable", &.{ 1, 3, 6, 1, 2, 1, 2, 2 }); // And the kind is carried, so a caller can tell an object from a branch. try testing.expectEqual(Parser.Kind.object_type, r.lookup("ifTable").?.kind); try testing.expectEqual(Parser.Kind.object_identifier, r.lookup("interfaces").?.kind);}
test "an absolute OID, written in numbers" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\M DEFINITIONS ::= BEGIN \\thing OBJECT IDENTIFIER ::= { 1 3 6 1 4 1 9 } \\under OBJECT IDENTIFIER ::= { thing 1 } \\END , .{}); try testing.expectEqual(@as(usize, 0), try r.resolve()); try expectOid(&r, "thing", &.{ 1, 3, 6, 1, 4, 1, 9 }); try expectOid(&r, "under", &.{ 1, 3, 6, 1, 4, 1, 9, 1 });}
test "what cannot be resolved is counted, not an error" { // A directory somebody pointed at will not contain everything it // imports, and that is normal rather than a fault. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\M DEFINITIONS ::= BEGIN \\orphan OBJECT IDENTIFIER ::= { somethingNeverDefined 1 } \\rooted OBJECT IDENTIFIER ::= { iso 9 } \\END , .{}); try testing.expectEqual(@as(usize, 1), try r.resolve()); try expectOid(&r, "rooted", &.{ 1, 9 }); try testing.expectEqual(@as(?Node, null), r.lookup("orphan"));}
test "a name defined twice keeps the first and records the collision" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\STANDARD DEFINITIONS ::= BEGIN \\thing OBJECT IDENTIFIER ::= { iso 1 } \\END , .{}); try r.addModule( \\VENDOR DEFINITIONS ::= BEGIN \\thing OBJECT IDENTIFIER ::= { iso 2 } \\END , .{}); _ = try r.resolve();
// First wins, which is the right answer for the case that matters -- a // vendor MIB redefining a standard name -- provided the standard modules // were added first. try expectOid(&r, "thing", &.{ 1, 1 }); try testing.expectEqual(@as(usize, 1), r.conflicts.items.len); try testing.expectEqualStrings("STANDARD", r.conflicts.items[0].kept); try testing.expectEqualStrings("VENDOR", r.conflicts.items[0].discarded);}
test "the same name at the same place twice is not a conflict" { // Two modules agreeing is common: RFC1213-MIB and SNMPv2-SMI both place // `mib-2`, and net-snmp does not complain about that either. var r: Registry = .init(testing.allocator); defer r.deinit(); for (0..2) |_| { try r.addModule( \\M DEFINITIONS ::= BEGIN \\mib-2 OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 2 1 } \\END , .{}); } _ = try r.resolve(); try expectOid(&r, "mib-2", &.{ 1, 3, 6, 1, 2, 1 }); try testing.expectEqual(@as(usize, 0), r.conflicts.items.len);}
test "types and traps have no place, and are not in the tree" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\M DEFINITIONS ::= BEGIN \\IfEntry ::= SEQUENCE { ifIndex INTEGER } \\DisplayString ::= TEXTUAL-CONVENTION \\ STATUS current \\ DESCRIPTION "text" \\ SYNTAX OCTET STRING \\linkDown TRAP-TYPE \\ ENTERPRISE snmp \\ ::= 2 \\real OBJECT IDENTIFIER ::= { iso 5 } \\END , .{}); _ = try r.resolve(); try testing.expectEqual(@as(?Node, null), r.lookup("IfEntry")); try testing.expectEqual(@as(?Node, null), r.lookup("DisplayString")); try testing.expectEqual(@as(?Node, null), r.lookup("linkDown")); try expectOid(&r, "real", &.{ 1, 5 });}
test "an OID too deep to be queried is dropped rather than overflowing" { var r: Registry = .init(testing.allocator); defer r.deinit(); var source: std.ArrayList(u8) = .empty; defer source.deinit(testing.allocator); try source.appendSlice(testing.allocator, "M DEFINITIONS ::= BEGIN\ndeep OBJECT IDENTIFIER ::= { iso"); for (0..max_depth + 10) |_| try source.appendSlice(testing.allocator, " 1"); try source.appendSlice(testing.allocator, " }\nEND");
try r.addModule(source.items, .{}); _ = try r.resolve(); // Dropped, not truncated to something plausible and not a panic: a name // with a wrong OID is worse than a name with none. try testing.expectEqual(@as(?Node, null), r.lookup("deep"));}
test "dotted decimal, as everything prints it" { var buffer: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buffer); try formatOid(&.{ 1, 3, 6, 1, 2, 1, 1, 1, 0 }, &w); try testing.expectEqualStrings("1.3.6.1.2.1.1.1.0", w.buffered());}
test "which of two definitions wins does not depend on resolution order" { // `resolve` used to drop a placed entry with `swapRemove`, which moves // the last pending entry into the hole. That reversed the relative order // of whatever was left, so across passes the list no longer resembled the // order the modules were added in, and "the first definition wins" came // to mean "whichever definition the shuffling happened to reach first". // // Here both definitions of `thing` need a second pass, because `late` is // added after them. With `swapRemove` the survivors reach pass two as // [VENDOR, STANDARD] and the vendor's definition wins; in the order the // modules were added, the standard one does. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\STANDARD DEFINITIONS ::= BEGIN \\thing OBJECT IDENTIFIER ::= { late 1 } \\END , .{}); // Two fillers, placeable straight away, to give the shuffling something // to shuffle. try r.addModule("F1 DEFINITIONS ::= BEGIN f1 OBJECT IDENTIFIER ::= { iso 20 } END", .{}); try r.addModule("F2 DEFINITIONS ::= BEGIN f2 OBJECT IDENTIFIER ::= { iso 21 } END", .{}); try r.addModule( \\VENDOR DEFINITIONS ::= BEGIN \\thing OBJECT IDENTIFIER ::= { late 2 } \\END , .{}); try r.addModule("PARENT DEFINITIONS ::= BEGIN late OBJECT IDENTIFIER ::= { iso 30 } END", .{});
try testing.expectEqual(@as(usize, 0), try r.resolve()); try expectOid(&r, "thing", &.{ 1, 30, 1 }); try testing.expectEqual(@as(usize, 1), r.conflicts.items.len); try testing.expectEqualStrings("STANDARD", r.conflicts.items[0].kept); try testing.expectEqualStrings("VENDOR", r.conflicts.items[0].discarded);}
test "a SYNTAX is followed through the textual conventions to a base type" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\SNMPv2-TC DEFINITIONS ::= BEGIN \\PhysAddress ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "1x:" \\ STATUS current \\ DESCRIPTION "Media address." \\ SYNTAX OCTET STRING \\END , .{}); try r.addModule( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS PhysAddress FROM SNMPv2-TC; \\ifPhysAddress OBJECT-TYPE \\ SYNTAX PhysAddress \\ MAX-ACCESS read-only \\ STATUS current \\ DESCRIPTION "The interface's address." \\ ::= { iso 1 } \\END , .{}); _ = try r.resolve();
const node = r.lookup("ifPhysAddress").?; const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); const resolved = r.resolveSyntax(c.syntax.?, node.module); // All three at once, which is what a manager needs: the base type to // decode the value, the hint to render it, and the convention's name to // say why it is rendered that way. try testing.expectEqual(Clauses.Base.octet_string, resolved.base.?); try testing.expectEqualStrings("PhysAddress", resolved.convention.?); try testing.expectEqualStrings("1x:", resolved.display_hint.?);}
test "which DisplayString a module means is decided by its IMPORTS" { // This is not a corner case. RFC1213-MIB defines `DisplayString ::= // OCTET STRING` -- a plain type assignment with no hint -- and SNMPv2-TC // defines it as a textual convention with DISPLAY-HINT "255a". Both are // loaded by every tool that loads the base MIBs, so answering with // whichever was read first gives half the corpus the wrong answer. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\RFC1213-MIB DEFINITIONS ::= BEGIN \\DisplayString ::= OCTET STRING \\sysDescr OBJECT-TYPE \\ SYNTAX DisplayString \\ ACCESS read-only \\ STATUS mandatory \\ ::= { iso 1 } \\END , .{}); try r.addModule( \\SNMPv2-TC DEFINITIONS ::= BEGIN \\DisplayString ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "255a" \\ STATUS current \\ DESCRIPTION "Printable text." \\ SYNTAX OCTET STRING (SIZE (0..255)) \\END , .{}); try r.addModule( \\RMON-MIB DEFINITIONS ::= BEGIN \\IMPORTS DisplayString FROM SNMPv2-TC; \\channelDescription OBJECT-TYPE \\ SYNTAX DisplayString (SIZE (0..127)) \\ MAX-ACCESS read-create \\ STATUS current \\ ::= { iso 2 } \\END , .{}); _ = try r.resolve();
// RFC1213-MIB defines its own and imports nothing, so it means its own: // no convention and no hint. { const node = r.lookup("sysDescr").?; const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); const resolved = r.resolveSyntax(c.syntax.?, node.module); try testing.expectEqual(Clauses.Base.octet_string, resolved.base.?); try testing.expectEqual(@as(?[]const u8, null), resolved.display_hint); try testing.expectEqual(@as(?[]const u8, null), resolved.convention); } // RMON-MIB imports it from SNMPv2-TC, so it means that one -- hint and // all -- even though RFC1213-MIB's definition was added first. { const node = r.lookup("channelDescription").?; const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); const resolved = r.resolveSyntax(c.syntax.?, node.module); try testing.expectEqualStrings("DisplayString", resolved.convention.?); try testing.expectEqualStrings("255a", resolved.display_hint.?); // The object's own constraint wins over the convention's: a textual // convention may only be narrowed by what refines it. try testing.expectEqual(@as(i64, 127), resolved.constraint.?.ranges[0].high.number); }}
test "a row type is not a textual convention" { // `IfEntry ::= SEQUENCE { ... }` is an ordinary type assignment, and // calling it a convention would say something false: there is no // DISPLAY-HINT to inherit and no base type to decode into. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\IF-MIB DEFINITIONS ::= BEGIN \\IfEntry ::= SEQUENCE { ifIndex Integer32, ifDescr OCTET STRING } \\ifEntry OBJECT-TYPE \\ SYNTAX IfEntry \\ MAX-ACCESS not-accessible \\ STATUS current \\ INDEX { ifIndex } \\ ::= { iso 1 } \\END , .{}); _ = try r.resolve(); const node = r.lookup("ifEntry").?; const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); const resolved = r.resolveSyntax(c.syntax.?, node.module); try testing.expectEqual(Clauses.Base.sequence, resolved.base.?); try testing.expectEqual(@as(?[]const u8, null), resolved.convention);
const row = r.lookupType("IfEntry", "IF-MIB").?; try testing.expectEqual(@as(usize, 2), row.syntax.?.fields.len); try testing.expectEqualStrings("ifIndex", row.syntax.?.fields[0].name);}
test "one object defined twice in the same place is described by the earlier module" { // RFC1213-MIB and IF-MIB both define `ifDescr`, at the same OID, in // different SMIs. That is not a conflict and both are right; which one is // *described* has to be chosen, and it is chosen by the order the modules // were added rather than by which resolved first. Here the SMIv2 module // is added first and its clauses are the ones kept, even though the SMIv1 // module's chain is self-contained and resolves a pass earlier. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\IF-MIB DEFINITIONS ::= BEGIN \\ifDescr OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { interfaces 2 } \\END , .{}); try r.addModule( \\RFC1213-MIB DEFINITIONS ::= BEGIN \\interfaces OBJECT IDENTIFIER ::= { iso 2 } \\ifDescr OBJECT-TYPE \\ SYNTAX OCTET STRING \\ ACCESS read-only \\ STATUS mandatory \\ ::= { interfaces 2 } \\END , .{}); _ = try r.resolve();
const node = r.lookup("ifDescr").?; try testing.expectEqualStrings("IF-MIB", node.module); const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); try testing.expectEqual(Clauses.Status.current, c.status.?); // Agreeing about the place is not a conflict. try testing.expectEqual(@as(usize, 0), r.conflicts.items.len); try expectOid(&r, "ifDescr", &.{ 1, 2, 2 });}
test "a cycle between two type assignments terminates" { var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\M DEFINITIONS ::= BEGIN \\A ::= B \\B ::= A \\thing OBJECT-TYPE \\ SYNTAX A \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { iso 1 } \\END , .{}); _ = try r.resolve(); const node = r.lookup("thing").?; const c = try r.clausesOf(testing.allocator, node); defer freeClauses(c); const resolved = r.resolveSyntax(c.syntax.?, node.module); // No base was reached, and saying so is the right answer. try testing.expectEqual(@as(?Clauses.Base, null), resolved.base);}
test "a name defined twice is one node by name and two by OID" { // `linux` is the real case: UCD-SNMP-MIB puts it under `ucdSnmpAgent` and // NET-SNMP-TC under `netSnmpAgentOIDs`, and net-snmp's agent answers // `sysObjectID` with the second. A manager that kept only the first would // have no name for the OID the agent actually sent, and would fall back // to `netSnmpAgentOIDs.10` -- which is not wrong, and is not what the // agent meant either. var r: Registry = .init(testing.allocator); defer r.deinit(); try r.addModule( \\NET-SNMP-TC DEFINITIONS ::= BEGIN \\netSnmpAgentOIDs OBJECT IDENTIFIER ::= { iso 8072 } \\linux OBJECT IDENTIFIER ::= { netSnmpAgentOIDs 10 } \\END , .{}); try r.addModule( \\UCD-SNMP-MIB DEFINITIONS ::= BEGIN \\ucdSnmpAgent OBJECT IDENTIFIER ::= { iso 2021 } \\linux OBJECT IDENTIFIER ::= { ucdSnmpAgent 10 } \\END , .{}); _ = try r.resolve();
// By name there is one answer, and it is the module added first. try expectOid(&r, "linux", &.{ 1, 8072, 10 }); try testing.expectEqual(@as(usize, 1), r.conflicts.items.len);
// By OID there are two, and neither had to lose. var found: usize = 0; for (r.placedNodes()) |node| { if (std.mem.eql(u8, node.name, "linux")) found += 1; } try testing.expectEqual(@as(usize, 2), found);}
test "the roots can be named as well as looked up" { var r: Registry = .init(testing.allocator); defer r.deinit(); _ = try r.resolve(); var seen = false; for (r.placedNodes()) |node| { if (std.mem.eql(u8, node.name, "iso")) seen = true; } // Without this, `-Of` output stops at `.1` instead of `.iso`. try testing.expect(seen);}