// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! MIB modules, so that a manager can say `sysDescr.0`. //! //! The protocol knows nothing about what an OID means. `1.3.6.1.2.1.1.1.0` is //! a path through a tree that the agent and the manager have to agree about //! in advance, and the agreement is written down in MIB modules --- in a //! language of their own, which `zig-smi` reads. This is the join between the //! two: it holds a resolved set of modules and answers the only two questions //! a manager asks of them. //! //! **Which OID is this name?** `parse` takes what a person types --- a number, //! a name, a name with an instance suffix, either with a module qualifier in //! front --- and returns an `ObjectId`. These are all the same request: //! //! ``` //! 1.3.6.1.2.1.1.1.0 .1.3.6.1.2.1.1.1.0 sysDescr.0 //! SNMPv2-MIB::sysDescr.0 .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0 //! ``` //! //! **What is this OID called?** `name` writes one back out in any of the four //! styles net-snmp's `-O` flags select, longest-prefix so that the part of an //! OID which is a table index stays numeric: //! //! ``` //! .1.3.6.1.2.1.2.2.1.2.1 IF-MIB::ifDescr.1 ifDescr.1 //! .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifDescr.1 //! ``` //! //! ## Nothing is loaded unless it is asked for //! //! An empty `Mibs` answers every lookup with null and every `parse` with //! whatever the numeric parser makes of the text, so a manager that speaks //! only numbers pays nothing for this existing. That is deliberate: the //! tools' behaviour with no `-M` and no `MIBDIRS` in the environment is //! exactly what it was before MIB support was added. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const asn1 = @import("asn1"); const smi = @import("smi"); const ObjectId = asn1.ObjectId; const Mibs = @This(); gpa: Allocator, registry: smi.Registry, /// Every placed node, sorted by OID, which is what makes the longest prefix /// of an OID findable in a binary search. Built by `resolve`, empty before it. by_oid: []smi.Registry.Node, /// How many files were found but could not be read or parsed. Not an error /// --- a directory of vendor MIBs always has a few --- but worth reporting. skipped: usize, /// How to write an OID back out, matching net-snmp's `-O` flags. pub const Style = enum { /// `.1.3.6.1.2.1.2.2.1.2.1` --- net-snmp's `-On`, and the only style that /// needs no MIBs at all. numeric, /// `IF-MIB::ifDescr.1` --- net-snmp's default, and its `-OS`. module, /// `ifDescr.1` --- net-snmp's `-Os`. short, /// `.iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifDescr.1` /// --- net-snmp's `-Of`. full, }; pub const ParseError = error{ /// A component was neither a number nor a name any loaded module defines. UnknownName, /// Too many sub-identifiers, or one that will not fit in 32 bits. BadOid, }; pub fn init(gpa: Allocator) Mibs { return .{ .gpa = gpa, .registry = .init(gpa), .by_oid = &.{}, .skipped = 0, }; } pub fn deinit(m: *Mibs) void { m.gpa.free(m.by_oid); m.registry.deinit(); m.* = undefined; } /// Whether anything is loaded. A manager with nothing loaded still works; it /// just cannot translate. pub fn isEmpty(m: *const Mibs) bool { return m.by_oid.len == 0; } /// Reads one MIB file and adds its module. /// /// A file that will not open, will not parse, or holds no module at all is /// counted in `skipped` rather than returned as an error. That is not /// leniency for its own sake: a directory of vendor MIBs reliably contains a /// README, a file of nine lines of comment reading "please ignore this mib", /// and two or three that net-snmp refuses as well. Stopping on the first of /// them would mean loading no MIBs at all. pub fn addFile(m: *Mibs, io: Io, dir: Io.Dir, path: []const u8) Allocator.Error!void { const source = m.read(io, dir, path) orelse return; defer m.gpa.free(source); m.registry.addModule(source, .{}) catch |err| switch (err) { error.NoModule, error.ParseFailed => m.skipped += 1, error.OutOfMemory => return error.OutOfMemory, }; } /// Adds a module from source already in memory. /// /// What `addFile` does once the bytes are in hand, and the way to load a MIB /// that did not come from a directory: one compiled into the program, one /// fetched over the network, one written by a test. pub fn addSource(m: *Mibs, source: []const u8) Allocator.Error!void { m.registry.addModule(source, .{}) catch |err| switch (err) { error.NoModule, error.ParseFailed => m.skipped += 1, error.OutOfMemory => return error.OutOfMemory, }; } /// The largest MIB file that will be read. The biggest in Cisco's corpus is /// under 2 MB; this is room enough to be generous and small enough that a /// directory full of something else cannot exhaust memory. const max_file_bytes = 16 * 1024 * 1024; /// One MIB file, as the ordering pass sees it before anything is loaded. const Candidate = struct { /// Which of the open directories it was found in. An index rather than /// the handle, because several candidates share one directory and a /// handle closed once per candidate is a double close. dir: usize, path: []const u8, /// The module it declares, from ` DEFINITIONS ::= BEGIN`. module: []const u8, /// The modules it names after `FROM`, which is to say what it depends on. imports: []const []const u8, }; /// Reads every MIB file in a directory, dependencies first. /// /// The order is not cosmetic, and this is the part of MIB loading that took /// the longest to get right. An object defined in two modules at the same OID /// --- an SMIv1 module and the SMIv2 one that replaced it, which is the usual /// case and happens 168 times among net-snmp's own 65 modules --- is /// described by whichever module was added first. So the order decides /// whether `sysDescr` is reported as `SNMPv2-MIB::sysDescr` with `STATUS /// current` or as `RFC1213-MIB::sysDescr` with `STATUS mandatory`, and both /// are in the file. /// /// Two rules settle it, and they are net-snmp's, arrived at by asking it with /// `snmptranslate -Dparse-file`: /// /// 1. **A module's imports are loaded before the module.** That is the rule /// that matters, and it is right on its own terms rather than only by /// agreement: `IMPORTS ... FROM SNMPv2-TC` says SNMPv2-TC is a dependency, /// and a dependency belongs in front of its dependent. It is what makes /// the base modules beat the SMIv1 modules that redefine their types. /// 2. **What is left is read in reverse name order.** There is no principle /// in that one at all --- it is the order net-snmp's directory walk /// happens to produce --- but matching it is what lets the two programs /// be run with identical arguments and diffed, which is the whole reason /// these tools are named after net-snmp's. /// /// The dependency order needs each file's imports before any of them is /// loaded, so this scans every file lexically first --- module name and /// `FROM` clauses, nothing else --- and reads each file again when its turn /// comes. Twice the reading, and a flat memory cost rather than one /// proportional to the directory, which for Cisco's 1,600 modules is the /// difference that matters. pub fn addDirectory(m: *Mibs, io: Io, path: []const u8) Allocator.Error!void { return m.addDirectories(io, &.{path}); } /// Reads several directories as one set, so that a module in the first can /// satisfy an import from the second. pub fn addDirectories(m: *Mibs, io: Io, paths: []const []const u8) Allocator.Error!void { return m.addModules(io, paths, null); } /// Reads only the named modules, and whatever they import. /// /// `wanted` is net-snmp's `-m`: a list of module *names*, not file names, and /// the difference is the whole difficulty --- a module's name is inside the /// file rather than on it, so which file holds `IF-MIB` cannot be known /// without reading them. The scan that works out the load order already reads /// every header, so the name is in hand by the time it is needed and this /// costs nothing extra. /// /// A name may carry a leading `+`, which is net-snmp's way of saying "as well /// as the default set"; since there is no default set here it means the same /// as the bare name. `ALL` anywhere in the list means everything, which is /// how net-snmp spells it too. /// /// Null means everything. A name nothing defines is counted in `skipped` /// rather than raised: a `-m` naming a module that is not in the search path /// should leave a numeric OID working. pub fn addModules( m: *Mibs, io: Io, paths: []const []const u8, wanted: ?[]const []const u8, ) Allocator.Error!void { var open: std.ArrayList(Io.Dir) = .empty; defer { for (open.items) |*dir| dir.close(io); open.deinit(m.gpa); } var candidates: std.ArrayList(Candidate) = .empty; defer m.freeCandidates(&candidates); for (paths) |path| try m.scanDirectory(io, path, &open, &candidates); try m.loadInOrder(io, open.items, &candidates, wanted); } fn freeCandidates(m: *Mibs, candidates: *std.ArrayList(Candidate)) void { for (candidates.items) |c| { m.gpa.free(c.path); m.gpa.free(c.module); for (c.imports) |import| m.gpa.free(import); m.gpa.free(c.imports); } candidates.deinit(m.gpa); } fn scanDirectory( m: *Mibs, io: Io, path: []const u8, open: *std.ArrayList(Io.Dir), candidates: *std.ArrayList(Candidate), ) Allocator.Error!void { var dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch { m.skipped += 1; return; }; const dir_index = open.items.len; try open.append(m.gpa, dir); var names: std.ArrayList([]const u8) = .empty; defer { for (names.items) |item| m.gpa.free(item); names.deinit(m.gpa); } var it = dir.iterate(); while (it.next(io) catch null) |entry| { if (entry.kind == .directory) continue; if (!looksLikeMib(entry.name)) continue; try names.append(m.gpa, try m.gpa.dupe(u8, entry.name)); } // Descending, which is rule 2 above. std.mem.sort([]const u8, names.items, {}, greaterByName); for (names.items) |file_name| { const source = m.read(io, dir, file_name) orelse continue; defer m.gpa.free(source); const header = m.scanHeader(source) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, }; const scanned = header orelse { // No `DEFINITIONS ::= BEGIN` anywhere: a README, a licence, a // file of nine lines of comment reading "please ignore this mib". m.skipped += 1; continue; }; errdefer { m.gpa.free(scanned.module); for (scanned.imports) |import| m.gpa.free(import); m.gpa.free(scanned.imports); } // A duplicated module name keeps the first, which after the sort is // the one from the earlier directory, or the later file name. for (candidates.items) |existing| { if (std.mem.eql(u8, existing.module, scanned.module)) { m.gpa.free(scanned.module); for (scanned.imports) |import| m.gpa.free(import); m.gpa.free(scanned.imports); break; } } else { try candidates.append(m.gpa, .{ .dir = dir_index, .path = try m.gpa.dupe(u8, file_name), .module = scanned.module, .imports = scanned.imports, }); } } } fn loadInOrder( m: *Mibs, io: Io, open: []const Io.Dir, candidates: *std.ArrayList(Candidate), wanted: ?[]const []const u8, ) Allocator.Error!void { const order = try loadOrder(m.gpa, candidates.items, wanted); defer m.gpa.free(order); if (wanted) |names| { // A name that matched no module is worth counting: `-m IF-MIB` with // IF-MIB absent from the search path should leave numeric OIDs // working, and should not pretend it loaded something. for (names) |requested| { const bare = if (requested.len != 0 and requested[0] == '+') requested[1..] else requested; if (std.ascii.eqlIgnoreCase(bare, "ALL")) continue; for (candidates.items) |candidate| { if (std.mem.eql(u8, candidate.module, bare)) break; } else m.skipped += 1; } } for (order) |index| { try m.addFile(io, open[candidates.items[index].dir], candidates.items[index].path); } } /// The order to load a set of modules in: imports before the module that /// imports them, and otherwise the order given. /// /// Kept apart from the reading so that it can be tested on a list of names /// rather than on a directory, which is what it is really about --- the whole /// of the decision is in here, and none of it needs a file. /// /// The depth bound is not defensive tidiness. MIB imports genuinely contain /// cycles: modules that import each other, and modules that import /// themselves, both turn up in vendor trees. A cycle only means somebody has /// to go first, and stopping at a bound decides that without a second pass to /// detect it. fn loadOrder( gpa: Allocator, candidates: []const Candidate, wanted: ?[]const []const u8, ) Allocator.Error![]usize { const done = try gpa.alloc(bool, candidates.len); defer gpa.free(done); @memset(done, false); var order: std.ArrayList(usize) = .empty; errdefer order.deinit(gpa); try order.ensureTotalCapacity(gpa, candidates.len); if (wanted) |names| { var all = false; for (names) |requested| { const bare = if (requested.len != 0 and requested[0] == '+') requested[1..] else requested; if (std.ascii.eqlIgnoreCase(bare, "ALL")) all = true; } if (!all) { // Each named module in the order given, and `visit` pulls in what // each one imports before it -- so a selection is loaded in the // same dependency order everything else is. for (names) |requested| { const bare = if (requested.len != 0 and requested[0] == '+') requested[1..] else requested; for (candidates, 0..) |candidate, i| { if (std.mem.eql(u8, candidate.module, bare)) { try visit(gpa, candidates, done, &order, i, 0); break; } } } return order.toOwnedSlice(gpa); } } for (0..candidates.len) |i| try visit(gpa, candidates, done, &order, i, 0); return order.toOwnedSlice(gpa); } fn visit( gpa: Allocator, candidates: []const Candidate, done: []bool, order: *std.ArrayList(usize), index: usize, depth: usize, ) Allocator.Error!void { if (done[index]) return; if (depth >= max_import_depth) return; // Marked before the recursion rather than after, so a cycle stops here // instead of arriving back at this module. done[index] = true; for (candidates[index].imports) |needed| { for (candidates, 0..) |candidate, j| { if (std.mem.eql(u8, candidate.module, needed)) { try visit(gpa, candidates, done, order, j, depth + 1); break; } } } try order.append(gpa, index); } const max_import_depth = 64; fn greaterByName(_: void, a: []const u8, b: []const u8) bool { return std.mem.order(u8, a, b) == .gt; } const Header = struct { module: []const u8, imports: []const []const u8, }; /// The module's name and the modules it imports, read lexically. /// /// A full parse would answer this too, and would cost a parse of every file /// before the order is known --- which for a directory of vendor MIBs is most /// of the work done twice. Everything wanted here is in the first few hundred /// tokens: ` DEFINITIONS`, then each name after a `FROM` up to the /// semicolon that ends the IMPORTS clause. fn scanHeader(m: *Mibs, source: []const u8) Allocator.Error!?Header { var lexer: smi.Lexer = .init(source, .{}); var previous: ?smi.Token = null; var module: ?[]const u8 = null; // To `DEFINITIONS`, whose preceding token is the module's name. while (true) { const token = lexer.next(); if (token.tag == .end_of_file) return null; if (token.tag == .keyword and std.mem.eql(u8, token.text(source), "DEFINITIONS")) { const name_token = previous orelse return null; module = name_token.text(source); break; } previous = token; } var imports: std.ArrayList([]const u8) = .empty; errdefer { for (imports.items) |import| m.gpa.free(import); imports.deinit(m.gpa); } // `DEFINITIONS [tagging] ::= BEGIN`, then `IMPORTS` if there is one. The // clause is the first thing inside the module when it is present, so // anything else at this point means there is nothing to import -- and // scanning on would read the whole file looking for a word that is not // coming. while (true) { const token = lexer.next(); if (token.tag == .end_of_file) return emptyHeader(m, module.?); if (token.tag == .keyword and std.mem.eql(u8, token.text(source), "BEGIN")) break; // `::=` and the optional `EXPLICIT TAGS` in between. if (token.tag == .assign or token.tag == .keyword) continue; return emptyHeader(m, module.?); } { const token = lexer.next(); const is_imports = token.tag == .keyword and std.mem.eql(u8, token.text(source), "IMPORTS"); if (!is_imports) return emptyHeader(m, module.?); } // Each name after a `FROM`, to the semicolon that ends the clause. var take_next = false; while (true) { const token = lexer.next(); if (token.tag == .end_of_file or token.tag == .semicolon) break; const text = token.text(source); if (take_next) { take_next = false; if (token.tag == .type_reference or token.tag == .value_reference) { try imports.append(m.gpa, try m.gpa.dupe(u8, text)); } continue; } if (token.tag == .keyword and std.mem.eql(u8, text, "FROM")) take_next = true; } return .{ .module = try m.gpa.dupe(u8, module.?), .imports = try imports.toOwnedSlice(m.gpa), }; } fn emptyHeader(m: *Mibs, module: []const u8) Allocator.Error!?Header { return .{ .module = try m.gpa.dupe(u8, module), .imports = &.{} }; } /// Reads a whole file, or counts it as skipped and answers null. fn read(m: *Mibs, io: Io, dir: Io.Dir, path: []const u8) ?[]u8 { var file = dir.openFile(io, path, .{}) catch { m.skipped += 1; return null; }; defer file.close(io); var buffer: [4096]u8 = undefined; var reader = file.readerStreaming(io, &buffer); return reader.interface.allocRemaining(m.gpa, .limited(max_file_bytes)) catch { m.skipped += 1; return null; }; } /// Which files in a directory are MIBs. /// /// There is no reliable extension: net-snmp ships `.txt`, Cisco ships `.my`, /// and plenty of vendors ship no extension at all. So this excludes what is /// obviously not a MIB rather than including what obviously is, and lets /// `addFile` reject the rest by failing to parse them. fn looksLikeMib(file_name: []const u8) bool { if (file_name.len == 0 or file_name[0] == '.') return false; const skip = [_][]const u8{ ".md", ".html", ".gz", ".zip", ".tar", ".pdf", ".png", ".json" }; for (skip) |extension| { if (std.mem.endsWith(u8, file_name, extension)) return false; } return true; } /// Resolves everything added so far and builds the index that `name` reads. /// /// Returns how many names could not be placed, which is not necessarily a /// fault: a directory holding a module whose parent module is missing leaves /// that module's names unplaced, and that is the ordinary state of a /// directory somebody pointed at. pub fn resolve(m: *Mibs) Allocator.Error!usize { const unresolved = try m.registry.resolve(); m.gpa.free(m.by_oid); m.by_oid = &.{}; // Built from every *placed* definition rather than from the name table, // because a name defined twice is one entry there and two here. `linux` // sits under both `ucdSnmpAgent` and `netSnmpAgentOIDs`, and net-snmp's // own agent answers `sysObjectID` with the second -- so a manager holding // only the first has no name for what the agent actually sent. const placed = m.registry.placedNodes(); const list = try m.gpa.alloc(smi.Registry.Node, placed.len); errdefer m.gpa.free(list); @memcpy(list, placed); // By OID, and within one OID by the order the modules were added, so that // two modules defining the same object give the same answer here as they // do everywhere else. std.mem.sort(smi.Registry.Node, list, {}, lessByOid); m.by_oid = list; return unresolved; } fn lessByOid(_: void, a: smi.Registry.Node, b: smi.Registry.Node) bool { return switch (orderOid(a.oid, b.oid)) { .lt => true, .gt => false, .eq => a.module_order < b.module_order, }; } fn orderOid(a: []const u32, b: []const u32) std.math.Order { const shared = @min(a.len, b.len); for (a[0..shared], b[0..shared]) |x, y| { if (x != y) return if (x < y) .lt else .gt; } return std.math.order(a.len, b.len); } /// The node whose OID is the longest prefix of `oid`, or null. /// /// Longest prefix rather than exact match because an instance OID is a /// column's OID with the row's index appended, and the index is not in any /// MIB: `1.3.6.1.2.1.2.2.1.2.1` is `ifDescr` with a `.1` on the end, and /// nothing names the whole of it. pub fn longestPrefix(m: *const Mibs, oid: []const u32) ?smi.Registry.Node { if (m.by_oid.len == 0) return null; // The last entry not greater than `oid`. Any prefix of `oid` sorts at or // below `oid`, so the longest one is at or below here -- and because the // order is lexicographic, walking back finds the longest first. var low: usize = 0; var high: usize = m.by_oid.len; while (low < high) { const mid = low + (high - low) / 2; if (orderOid(m.by_oid[mid].oid, oid) == .gt) high = mid else low = mid + 1; } // Walking back finds the longest prefix first, and cannot walk far. If P // is the longest prefix of `oid`, then every entry E with P < E <= `oid` // begins with P: E and P can only differ inside P's length by having a // *larger* sub-identifier there, and that would put E above `oid` rather // than below it. So the walk passes only nodes underneath P. var i = low; while (i > 0) { i -= 1; const candidate = m.by_oid[i].oid; if (candidate.len <= oid.len and std.mem.eql(u32, candidate, oid[0..candidate.len])) { return m.by_oid[i]; } // And it stops once it drops below the arc `oid` begins in: nothing // there can share even a first sub-identifier with it. Without this // an OID under no known root would walk the whole table -- which // never happens with the three roots seeded, since every OID begins // with 0, 1 or 2 and each of those is a node, but "never happens" // is a poor reason to leave a linear scan in a lookup. if (candidate.len != 0 and candidate[0] < oid[0]) break; } return null; } /// The node of that name, or null. pub fn lookup(m: *const Mibs, symbol: []const u8) ?smi.Registry.Node { return m.registry.lookup(symbol); } /// What a person typed, as an OID. /// /// Numbers are tried first and unconditionally, because a numeric OID is /// unambiguous and must keep working whether or not any MIB is loaded. Only /// then are the components looked up as names, left to right: a name sets the /// position outright, since every name in a MIB has an absolute OID, and a /// number steps down from wherever the walk has reached. That one rule reads /// every form net-snmp accepts, including `.iso.org.dod.internet` --- which /// is four names in a row and means the same thing as its last one. pub fn parse(m: *const Mibs, text: []const u8) ParseError!ObjectId { if (ObjectId.parse(text)) |oid| return oid else |_| {} // `IF-MIB::ifDescr.1`. The qualifier is checked against the answer rather // than used to find it: this holds one node per name, so a module name // can confirm a lookup but cannot disambiguate one. var rest = text; if (std.mem.indexOf(u8, text, "::")) |at| rest = text[at + 2 ..]; if (rest.len != 0 and rest[0] == '.') rest = rest[1..]; if (rest.len == 0) return error.UnknownName; var buffer: [ObjectId.max_len]u32 = undefined; var len: usize = 0; var placed = false; var parts = std.mem.splitScalar(u8, rest, '.'); while (parts.next()) |part| { if (part.len == 0) return error.UnknownName; if (std.ascii.isDigit(part[0])) { if (!placed) return error.UnknownName; if (len == ObjectId.max_len) return error.BadOid; buffer[len] = std.fmt.parseInt(u32, part, 10) catch return error.BadOid; len += 1; continue; } const node = m.registry.lookup(part) orelse return error.UnknownName; if (node.oid.len > ObjectId.max_len) return error.BadOid; @memcpy(buffer[0..node.oid.len], node.oid); len = node.oid.len; placed = true; } if (!placed) return error.UnknownName; return ObjectId.fromSlice(buffer[0..len]) catch error.BadOid; } /// Writes an OID in the requested style. /// /// Falls back to numeric whenever the MIBs cannot do better, so a caller /// never has to ask whether anything is loaded: with an empty `Mibs` every /// style prints what `.numeric` would. pub fn name(m: *const Mibs, oid: ObjectId, style: Style, w: *Io.Writer) Io.Writer.Error!void { const subs = oid.slice(); if (style == .numeric) { for (subs) |sub| try w.print(".{d}", .{sub}); return; } if (style == .full) { // Every prefix named, longest-first at each step, which is how // `.iso.org.dod` comes out rather than `.1.3.6`. for (subs, 0..) |sub, i| { if (m.longestPrefix(subs[0 .. i + 1])) |node| { if (node.oid.len == i + 1) { try w.print(".{s}", .{node.name}); continue; } } try w.print(".{d}", .{sub}); } return; } const node = m.longestPrefix(subs) orelse { for (subs) |sub| try w.print(".{d}", .{sub}); return; }; if (style == .module and node.module.len != 0) try w.print("{s}::", .{node.module}); try w.writeAll(node.name); // Whatever is left is the instance: a table index, or the `.0` that says // a scalar has exactly one. Nothing names it, and net-snmp prints it as // digits too. for (subs[node.oid.len..]) |sub| try w.print(".{d}", .{sub}); } /// Everything the MIBs say about how one object's value should be written. /// /// Gathered in one place because the rules interlock: whether an OCTET STRING /// is quoted depends on whether it has a display hint, and whether an INTEGER /// carries a unit depends on whether it matched an enumeration first. pub const Rendering = struct { /// The `DISPLAY-HINT` of the textual convention the syntax names, if it /// names one that has one. `DisplayString` does (`255a`); /// `InternationalDisplayString`, which looks just like it, does not --- and /// that difference is exactly what decides the quoting below. display_hint: ?[]const u8 = null, /// `INTEGER { up(1), down(2) }`, so that a 1 can be printed as `up(1)`. named_numbers: []const smi.clauses.NamedNumber = &.{}, /// The `UNITS` clause: `INTEGER: 4096 Bytes`. units: ?[]const u8 = null, /// Whether the syntax is SMIv1's `NetworkAddress` rather than `IpAddress`. /// The two carry the same four octets and net-snmp prints them /// differently, so the distinction has to survive. network_address: bool = false, /// The name an enumeration gives a value, or null. pub fn label(r: Rendering, value: i64) ?[]const u8 { for (r.named_numbers) |nn| { if (nn.value == value) return nn.name; } return null; } }; /// What the MIBs say about the object at `oid`. /// /// All-default when nothing is loaded, when the OID names nothing, or when /// the OID is an instance of a column --- in which case the *column* is what /// is looked up, since `ifPhysAddress.1` is a `PhysAddress` for the same /// reason `ifPhysAddress` is. /// /// `gpa` owns what the result points at, and an arena is the natural thing to /// pass: the clauses are parsed here rather than held in the node, because a /// parsed `Clauses` in every node costs half a gigabyte over a vendor corpus /// and is wanted for the handful of objects a command actually prints. See /// `smi.Registry.Node.body`. pub fn rendering(m: *const Mibs, gpa: Allocator, oid: ObjectId) Allocator.Error!Rendering { const node = m.longestPrefix(oid.slice()) orelse return .{}; const clauses = try m.registry.clausesOf(gpa, node); const syntax = clauses.syntax orelse return .{}; const resolved = m.registry.resolveSyntax(syntax, node.module); return .{ .display_hint = resolved.display_hint, .named_numbers = resolved.named_numbers, .units = clauses.units, .network_address = resolved.base == .network_address, }; } /// `name`, as something that can be passed to a writer. pub fn formatter(m: *const Mibs, oid: ObjectId, style: Style) Formatter { return .{ .mibs = m, .oid = oid, .style = style }; } pub const Formatter = struct { mibs: *const Mibs, oid: ObjectId, style: Style, pub fn format(f: Formatter, w: *Io.Writer) Io.Writer.Error!void { return f.mibs.name(f.oid, f.style, w); } }; // -- tests ------------------------------------------------------------------ /// The shape of a real MIB, small enough to read: the spine down to `mib-2`, /// a scalar, and a table whose rows are indexed by a column. const test_mibs = [_][]const u8{ \\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 } \\END , \\SNMPv2-MIB DEFINITIONS ::= BEGIN \\IMPORTS mib-2 FROM SNMPv2-SMI; \\system OBJECT IDENTIFIER ::= { mib-2 1 } \\sysDescr OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { system 1 } \\END , \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS mib-2 FROM SNMPv2-SMI; \\interfaces OBJECT IDENTIFIER ::= { mib-2 2 } \\ifTable OBJECT-TYPE \\ SYNTAX SEQUENCE OF IfEntry \\ MAX-ACCESS not-accessible \\ STATUS current \\ ::= { interfaces 2 } \\ifEntry OBJECT-TYPE \\ SYNTAX IfEntry \\ MAX-ACCESS not-accessible \\ STATUS current \\ INDEX { ifIndex } \\ ::= { ifTable 1 } \\ifDescr OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { ifEntry 2 } \\END , }; fn testMibs(m: *Mibs) !void { for (test_mibs) |source| try m.addSource(source); _ = try m.resolve(); } fn expectName(m: *const Mibs, text: []const u8, style: Style, expected: []const u8) !void { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try m.name(try m.parse(text), style, &w); try testing.expectEqualStrings(expected, w.buffered()); } test "a numeric OID needs no MIBs at all" { var m: Mibs = .init(testing.allocator); defer m.deinit(); // Before anything is loaded, and after -- the numeric parser is tried // first either way, so a script that has always used numbers keeps // working whatever is in MIBDIRS. for (0..2) |round| { if (round == 1) try testMibs(&m); const oid = try m.parse("1.3.6.1.2.1.1.1.0"); try testing.expectEqualSlices(u32, &.{ 1, 3, 6, 1, 2, 1, 1, 1, 0 }, oid.slice()); const dotted = try m.parse(".1.3.6.1.2.1.1.1.0"); try testing.expect(dotted.eql(oid)); } } test "with nothing loaded, every style prints numerically" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try testing.expect(m.isEmpty()); for ([_]Style{ .numeric, .module, .short, .full }) |style| { try expectName(&m, "1.3.6.1.2.1.1.1.0", style, ".1.3.6.1.2.1.1.1.0"); } // And a name is simply unknown, rather than a crash or a wrong answer. try testing.expectError(error.UnknownName, m.parse("sysDescr.0")); } test "the forms a person types, all meaning one OID" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try testMibs(&m); const expected = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); for ([_][]const u8{ "1.3.6.1.2.1.1.1.0", ".1.3.6.1.2.1.1.1.0", "sysDescr.0", ".sysDescr.0", "SNMPv2-MIB::sysDescr.0", // Every label spelled out, which is what `-Of` prints and what a // person pastes back in. ".iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0", // A name partway down, with the rest numeric. "system.1.0", "mib-2.1.1.0", }) |text| { const got = m.parse(text) catch |err| { std.debug.print("\n{s} failed: {t}\n", .{ text, err }); return err; }; try testing.expect(got.eql(expected)); } } test "an OID written back out, in each style" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try testMibs(&m); // A column plus a row index: nothing names the whole thing, so the // longest prefix is the column and the index stays numeric. try expectName(&m, "1.3.6.1.2.1.2.2.1.2.7", .numeric, ".1.3.6.1.2.1.2.2.1.2.7"); try expectName(&m, "1.3.6.1.2.1.2.2.1.2.7", .module, "IF-MIB::ifDescr.7"); try expectName(&m, "1.3.6.1.2.1.2.2.1.2.7", .short, "ifDescr.7"); try expectName( &m, "1.3.6.1.2.1.2.2.1.2.7", .full, ".iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifDescr.7", ); // An OID that is named exactly, with no instance after it. try expectName(&m, "1.3.6.1.2.1.2.2", .module, "IF-MIB::ifTable"); // And one that runs off the end of everything loaded. try expectName(&m, "1.3.6.1.4.1.9.1.2191", .module, "SNMPv2-SMI::internet.4.1.9.1.2191"); } test "a name that is not there is not invented" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try testMibs(&m); try testing.expectError(error.UnknownName, m.parse("noSuchThing.0")); try testing.expectError(error.UnknownName, m.parse("IF-MIB::noSuchThing")); // A number with nothing to hang it on: `.7` alone is not an OID. try testing.expectError(error.UnknownName, m.parse("7")); } test "imports are loaded before the modules that import them" { // The whole of the ordering decision, on names rather than files. // // It matters because an object defined in two modules at the same OID -- // an SMIv1 module and the SMIv2 one that replaced it -- is described by // whichever was added first. Here RFC1213-MIB comes first in the list, as // the reverse-name-order pass would give it, and IF-MIB still loads // first, because RFC1213-MIB says it depends on it. const gpa = testing.allocator; const candidates = [_]Candidate{ .{ .dir = 0, .path = "", .module = "RFC1213-MIB", .imports = &.{"IF-MIB"} }, .{ .dir = 0, .path = "", .module = "IF-MIB", .imports = &.{"SNMPv2-SMI"} }, .{ .dir = 0, .path = "", .module = "SNMPv2-SMI", .imports = &.{} }, }; const order = try loadOrder(gpa, &candidates, null); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{ 2, 1, 0 }, order); } test "-m loads the named modules and what they import, and nothing else" { // net-snmp's `-m` restricts, and it took asking to find out: `-m IF-MIB` // against its own MIB directory parses five files rather than sixty-five, // and an OID that only HOST-RESOURCES-MIB names comes back unresolved. // SNMPv2-MIB is among the five not because net-snmp keeps a core set -- // `-m SNMPv2-SMI` parses exactly one file -- but because IF-MIB imports // it. So following imports is the whole of the rule. const gpa = testing.allocator; const candidates = [_]Candidate{ .{ .dir = 0, .path = "", .module = "UCD-SNMP-MIB", .imports = &.{"SNMPv2-TC"} }, .{ .dir = 0, .path = "", .module = "IF-MIB", .imports = &.{ "SNMPv2-SMI", "SNMPv2-MIB" } }, .{ .dir = 0, .path = "", .module = "SNMPv2-MIB", .imports = &.{"SNMPv2-SMI"} }, .{ .dir = 0, .path = "", .module = "SNMPv2-SMI", .imports = &.{} }, .{ .dir = 0, .path = "", .module = "SNMPv2-TC", .imports = &.{"SNMPv2-SMI"} }, }; { const order = try loadOrder(gpa, &candidates, &.{"IF-MIB"}); defer gpa.free(order); // SNMPv2-SMI, then SNMPv2-MIB, then IF-MIB -- and neither of the two // modules nothing asked for. try testing.expectEqualSlices(usize, &.{ 3, 2, 1 }, order); } { // A `+` prefix is net-snmp's "as well as the default set"; there is // no default set here, so it means the bare name. const order = try loadOrder(gpa, &candidates, &.{"+SNMPv2-SMI"}); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{3}, order); } { // ALL anywhere in the list means everything. const order = try loadOrder(gpa, &candidates, &.{ "IF-MIB", "all" }); defer gpa.free(order); try testing.expectEqual(candidates.len, order.len); } { // Two names, in the order given, sharing a dependency that is loaded // once. const order = try loadOrder(gpa, &candidates, &.{ "SNMPv2-MIB", "UCD-SNMP-MIB" }); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{ 3, 2, 4, 0 }, order); } { // A name nothing defines selects nothing, and must not select // everything by accident. const order = try loadOrder(gpa, &candidates, &.{"NOT-A-MODULE"}); defer gpa.free(order); try testing.expectEqual(@as(usize, 0), order.len); } } test "every module is loaded exactly once, cycle or no cycle" { const gpa = testing.allocator; { // Two modules importing each other. Somebody has to go first, and // neither may be loaded twice or dropped. const candidates = [_]Candidate{ .{ .dir = 0, .path = "", .module = "A", .imports = &.{"B"} }, .{ .dir = 0, .path = "", .module = "B", .imports = &.{"A"} }, }; const order = try loadOrder(gpa, &candidates, null); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{ 1, 0 }, order); } { // A module importing itself, and one importing something absent -- // both of which occur in real vendor MIBs. const candidates = [_]Candidate{ .{ .dir = 0, .path = "", .module = "A", .imports = &.{"A"} }, .{ .dir = 0, .path = "", .module = "B", .imports = &.{"NOT-HERE"} }, }; const order = try loadOrder(gpa, &candidates, null); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{ 0, 1 }, order); } { // A diamond: both middles come before the one that needs them, and // the shared base comes before both. const candidates = [_]Candidate{ .{ .dir = 0, .path = "", .module = "TOP", .imports = &.{ "LEFT", "RIGHT" } }, .{ .dir = 0, .path = "", .module = "LEFT", .imports = &.{"BASE"} }, .{ .dir = 0, .path = "", .module = "RIGHT", .imports = &.{"BASE"} }, .{ .dir = 0, .path = "", .module = "BASE", .imports = &.{} }, }; const order = try loadOrder(gpa, &candidates, null); defer gpa.free(order); try testing.expectEqualSlices(usize, &.{ 3, 1, 2, 0 }, order); } } test "the order a set of modules is added in decides which definition is described" { // The consequence of the ordering, once the modules are in: two modules // defining `ifNumber` at the same place, and the first added wins. var m: Mibs = .init(testing.allocator); defer m.deinit(); try m.addSource( \\SNMPv2-SMI DEFINITIONS ::= BEGIN \\mib-2 OBJECT IDENTIFIER ::= { iso 1 } \\END ); try m.addSource( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS mib-2 FROM SNMPv2-SMI; \\ifNumber OBJECT-TYPE \\ SYNTAX INTEGER \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { mib-2 2 } \\END ); try m.addSource( \\RFC1213-MIB DEFINITIONS ::= BEGIN \\IMPORTS mib-2 FROM SNMPv2-SMI; \\ifNumber OBJECT-TYPE \\ SYNTAX INTEGER \\ ACCESS read-only \\ STATUS mandatory \\ ::= { mib-2 2 } \\END ); _ = try m.resolve(); try expectName(&m, "1.1.2", .module, "IF-MIB::ifNumber"); } test "the header scan finds the module name and what it imports" { var m: Mibs = .init(testing.allocator); defer m.deinit(); { const header = (try m.scanHeader( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS \\ MODULE-IDENTITY, OBJECT-TYPE, Counter32 FROM SNMPv2-SMI \\ DisplayString, PhysAddress FROM SNMPv2-TC \\ MODULE-COMPLIANCE FROM SNMPv2-CONF; \\ifMIB MODULE-IDENTITY ::= { mib-2 31 } \\END )).?; defer { testing.allocator.free(header.module); for (header.imports) |import| testing.allocator.free(import); testing.allocator.free(header.imports); } try testing.expectEqualStrings("IF-MIB", header.module); try testing.expectEqual(@as(usize, 3), header.imports.len); try testing.expectEqualStrings("SNMPv2-SMI", header.imports[0]); try testing.expectEqualStrings("SNMPv2-CONF", header.imports[2]); } { // No IMPORTS clause. The scan has to stop rather than read the whole // file looking for a word that is not coming -- and it must not be // fooled by the `::=` in `DEFINITIONS ::= BEGIN`, which is what it // was, so that nothing imported anything and the ordering did nothing. const header = (try m.scanHeader( \\RFC1155-SMI DEFINITIONS ::= BEGIN \\internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } \\END )).?; defer { testing.allocator.free(header.module); testing.allocator.free(header.imports); } try testing.expectEqualStrings("RFC1155-SMI", header.module); try testing.expectEqual(@as(usize, 0), header.imports.len); } { // A tagging environment between DEFINITIONS and ::=. const header = (try m.scanHeader("M DEFINITIONS IMPLICIT TAGS ::= BEGIN\nEND")).?; defer { testing.allocator.free(header.module); testing.allocator.free(header.imports); } try testing.expectEqualStrings("M", header.module); } // Not a MIB at all. try testing.expectEqual(@as(?Header, null), try m.scanHeader("please ignore this file\n")); } test "a file that will not parse is counted, not fatal" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try m.addSource("M DEFINITIONS ::= BEGIN"); try m.addSource("-- please ignore this mib\n"); try testing.expectEqual(@as(usize, 2), m.skipped); // And the ones that do parse still load. try testMibs(&m); try expectName(&m, "sysDescr.0", .module, "SNMPv2-MIB::sysDescr.0"); } test "the longest prefix of an OID, and how far the search has to walk" { var m: Mibs = .init(testing.allocator); defer m.deinit(); try testMibs(&m); _ = try m.resolve(); // An instance of a column: the column is the answer, and the index is // not part of it. const instance = (try ObjectId.parse("1.3.6.1.2.1.2.2.1.2.7")).slice(); try testing.expectEqualStrings("ifDescr", m.longestPrefix(instance).?.name); // An exact node, with nothing after it. const exact = (try ObjectId.parse("1.3.6.1.2.1.2.2")).slice(); try testing.expectEqualStrings("ifTable", m.longestPrefix(exact).?.name); // Something deep under a node nothing else is near: the nearest ancestor // that is named, rather than nothing. const stranger = (try ObjectId.parse("1.3.6.1.4.1.9.1.2191")).slice(); try testing.expectEqualStrings("internet", m.longestPrefix(stranger).?.name); // The roots are one sub-identifier long, so an OID in an arc nothing else // touches still lands on one rather than on nothing. const other_arc = (try ObjectId.parse("2.999.1")).slice(); try testing.expectEqualStrings("joint-iso-ccitt", m.longestPrefix(other_arc).?.name); const ccitt = (try ObjectId.parse("0.9.1")).slice(); try testing.expectEqualStrings("ccitt", m.longestPrefix(ccitt).?.name); // With nothing loaded there is no answer, which must be a null rather // than a walk off the front of the table. var empty: Mibs = .init(testing.allocator); defer empty.deinit(); try testing.expectEqual(@as(?smi.Registry.Node, null), empty.longestPrefix(instance)); }