// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The command line tools, deliberately shaped like net-snmp's. //! //! One binary, installed under several names, dispatching on the name it was //! invoked under. net-snmp's tools differ only in which PDU they send and //! which options they accept, so there is no reason for them to be different //! programs -- and one good reason for the *names* to match exactly: //! //! ```console //! $ diff <(snmpwalk -v2c -c public -On host 1.3.6.1.2.1.1) \ //! <(./snmpwalk -v2c -c public -On host 1.3.6.1.2.1.1) //! ``` //! //! That is the differential test in its strongest form -- two programs, one //! argument vector, and a diff -- and it only works if the options mean the //! same thing. So `-v`, `-c`, `-r`, `-t`, `-O` and `-C` are spelled net-snmp's //! way rather than a nicer way, including the ones that are a little odd: //! `-v2c` with no space, and `-Cn`/`-Cr` where the second letter is the option. //! //! ## What is deliberately missing //! //! **Names.** There is no MIB support here, so every OID is numeric going in //! and coming out -- `1.3.6.1.2.1.1.1.0` rather than `sysDescr.0`. net-snmp's //! `-On` forces it into the same mode, which is what makes the diff above //! possible at all. Reading MIB modules is a compiler for a different //! language than the protocol and lives in a repository of its own. //! //! **Nothing, now.** 3DES, AES-192 and AES-256 are all here. The last three //! come from drafts that expired without becoming RFCs and that net-snmp's //! command line refuses, so Cisco firmware is the only thing they have been //! checked against -- which the README says plainly rather than letting a //! test count imply otherwise. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const snmp = @import("snmp"); const Client = snmp.Client; const ObjectId = snmp.ObjectId; const Pdu = snmp.Pdu; const Value = snmp.Value; const VarBind = snmp.VarBind; const Version = snmp.Version; const Mibs = snmp.Mibs; const smi = snmp.smi; /// Which tool this invocation is. Taken from `argv[0]`, so that the installed /// names behave as net-snmp's do, and from a subcommand otherwise so that /// `zig build run -- get ...` works during development. const Tool = enum { get, walk, bulkwalk, set, /// The notification sink, named after net-snmp's daemon -- though this one /// prints to standard output and exits rather than daemonising, which is /// what makes it drivable from a test. trapd, fn fromName(argv0: []const u8) ?Tool { // The basename, because the program is invoked by path as often as by // name, and with a `.exe` on Windows. const base = std.fs.path.basename(argv0); const stem = if (std.mem.endsWith(u8, base, ".exe")) base[0 .. base.len - 4] else base; if (std.mem.eql(u8, stem, "snmpget")) return .get; if (std.mem.eql(u8, stem, "snmpwalk")) return .walk; if (std.mem.eql(u8, stem, "snmpbulkwalk")) return .bulkwalk; if (std.mem.eql(u8, stem, "snmpset")) return .set; if (std.mem.eql(u8, stem, "snmptrapd")) return .trapd; return null; } fn fromSubcommand(word: []const u8) ?Tool { if (std.mem.eql(u8, word, "get")) return .get; if (std.mem.eql(u8, word, "walk")) return .walk; if (std.mem.eql(u8, word, "bulkwalk")) return .bulkwalk; if (std.mem.eql(u8, word, "set")) return .set; if (std.mem.eql(u8, word, "trapd")) return .trapd; return null; } fn name(t: Tool) []const u8 { return switch (t) { .get => "snmpget", .walk => "snmpwalk", .bulkwalk => "snmpbulkwalk", .set => "snmpset", .trapd => "snmptrapd", }; } }; /// How a value is printed, which is net-snmp's `-O` family. Only the parts /// that mean something without MIB support are implemented. const Output = struct { /// `-Oq`: no type prefix, and `=` becomes a space. quick: bool = false, /// `-Ov`: the value alone, with no name. value_only: bool = false, /// How an OID is written: `-On`, `-Of`, `-Os`, `-OS`. /// /// The default is `.module`, which is net-snmp's, and it degrades to /// numeric on its own when no MIBs are loaded --- so a tool run without /// `-M` or `MIBDIRS` prints exactly what it printed before there was any /// MIB support, without the caller having to ask for that. style: snmp.Mibs.Style = .module, }; const Options = struct { version: Version = .v2c, /// `snmptrapd` only: which port to listen on, and how many notifications /// to print before exiting. A count makes it drivable from a test; zero /// means listen until interrupted. listen_port: u16 = snmp.Receiver.default_port, count: usize = 0, /// `snmptrapd` only: our own engine ID, as hex. Required for v3 informs, /// where the receiver is the authoritative engine and has to answer a /// sender discovering it. engine_id: []const u8 = "", community: []const u8 = "public", /// The v3 user, assembled from -u, -l, -a, -A, -x and -X. user: snmp.usm.User = .{ .name = "" }, /// Whether -l was given. Without it the level is inferred from which /// passwords were supplied, which is what net-snmp does. level_given: bool = false, retries: u8 = 5, timeout_ms: u32 = 1000, /// `-Cn`, GetBulk's non-repeaters. non_repeaters: u32 = 0, /// `-Cr`, GetBulk's max-repetitions. max_repetitions: u32 = 10, /// `-M`: colon-separated directories to read MIBs from. Empty means the /// `MIBDIRS` environment variable, and then nothing. mib_dirs: []const u8 = "", /// `-m`: colon-separated module names, or `ALL`. Empty means the `MIBS` /// environment variable, and then `ALL` when any directory was named. mibs: []const u8 = "", output: Output = .{}, }; const usage_common = \\Options, spelled as net-snmp spells them: \\ -v 1|2c|3 SNMP version (also -v1, -v2c, -v3) \\ -c COMMUNITY community string for v1 and v2c \\ -u USER v3 user name \\ -l LEVEL noAuthNoPriv | authNoPriv | authPriv \\ -a PROTOCOL MD5 | SHA | SHA-224 | SHA-256 | SHA-384 | SHA-512 \\ -A PASSWORD authentication password \\ -x PROTOCOL DES | AES \\ -X PASSWORD privacy password \\ -r RETRIES retries after a timeout (default 5) \\ -t TIMEOUT seconds to wait for each try (default 1) \\ -M DIRS colon-separated directories to read MIBs from \\ (default: the MIBDIRS environment variable) \\ -m MODULES colon-separated modules to load, or ALL \\ (default: the MIBS environment variable, else ALL) \\ -On numeric OIDs: .1.3.6.1.2.1.2.2.1.2.1 \\ -OS module and name: IF-MIB::ifDescr.1 (the default) \\ -Os name only: ifDescr.1 \\ -Of every label: .iso.org.dod.internet...ifDescr.1 \\ -Oq no type prefix \\ -Ov print values only \\ -h, --help this \\ \\An OID may be written numerically or by name once MIBs are loaded: \\ 1.3.6.1.2.1.1.1.0 sysDescr.0 SNMPv2-MIB::sysDescr.0 \\ ; fn usageFor(tool: Tool) []const u8 { return switch (tool) { .get => \\usage: snmpget [OPTIONS] AGENT[:PORT] OID [OID]... \\ \\Ask for the value of each OID. \\ , .walk => \\usage: snmpwalk [OPTIONS] AGENT[:PORT] [OID] \\ \\Walk the subtree under OID with GetNext, one request per object. \\ , .bulkwalk => \\usage: snmpbulkwalk [OPTIONS] AGENT[:PORT] [OID] \\ \\Walk the subtree under OID with GetBulk, several objects per request. \\ -Cn N non-repeaters (default 0) \\ -Cr N max-repetitions (default 10) \\ , .trapd => \\usage: snmptrapd [OPTIONS] \\ \\Print each trap and inform that arrives, acknowledging the informs. \\ -p PORT port to listen on (default 162, which needs privilege) \\ -N COUNT exit after this many notifications (default: never) \\ -E HEX this receiver's engine ID, for v3 informs \\ , .set => \\usage: snmpset [OPTIONS] AGENT[:PORT] OID TYPE VALUE [OID TYPE VALUE]... \\ \\Write each value. TYPE is one of: \\ i INTEGER u Gauge32/Unsigned32 c Counter32 \\ s OCTET STRING x OCTET STRING in hex o OBJECT IDENTIFIER \\ t TimeTicks a IpAddress n NULL \\ , }; } pub fn main(init: std.process.Init) !void { const gpa = init.arena.allocator(); const io = init.io; const args = try init.minimal.args.toSlice(gpa); var stdout_buffer: [64 * 1024]u8 = undefined; var stdout_file: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file.interface; defer stdout.flush() catch {}; var stderr_buffer: [4096]u8 = undefined; var stderr_file: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); const stderr = &stderr_file.interface; defer stderr.flush() catch {}; // The name first, then a subcommand. A binary installed as `snmpget` is // `snmpget`; one run as `zig-snmp get` is the same thing said the other // way. var rest = args[1..]; const tool = Tool.fromName(args[0]) orelse blk: { if (rest.len == 0) { try stderr.writeAll( \\usage: zig-snmp get|walk|bulkwalk|set [OPTIONS] AGENT[:PORT] ... \\ \\Installed also as snmpget, snmpwalk, snmpbulkwalk and snmpset, \\which is the same program under the name it answers to. \\ ); try stderr.flush(); std.process.exit(2); } const t = Tool.fromSubcommand(rest[0]) orelse { try stderr.print("zig-snmp: not a command: {s}\n", .{rest[0]}); try stderr.flush(); std.process.exit(2); }; rest = rest[1..]; break :blk t; }; run(io, gpa, init.environ_map, tool, rest, stdout, stderr) catch |err| { try stdout.flush(); switch (err) { error.UsageError => {}, // Two for a command line that is wrong, one for an agent that // would not answer: the difference is worth having in a script. error.Timeout => try stderr.print("{s}: Timeout: No Response from the agent.\n", .{tool.name()}), else => try stderr.print("{s}: {t}\n", .{ tool.name(), err }), } try stderr.flush(); std.process.exit(if (err == error.UsageError) 2 else 1); }; } fn run( io: Io, gpa: Allocator, environ: *const std.process.Environ.Map, tool: Tool, args: []const []const u8, stdout: *Io.Writer, stderr: *Io.Writer, ) !void { var options: Options = .{}; var positional: std.ArrayList([]const u8) = .empty; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (arg.len < 2 or arg[0] != '-') { try positional.append(gpa, arg); continue; } if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { try stdout.writeAll(usageFor(tool)); try stdout.writeAll(usage_common); return; } // net-snmp allows the value either attached or as the next argument, // so `-v2c` and `-v 2c` are the same thing, and so are `-cpublic` and // `-c public`. Scripts in the wild use both. const letter = arg[1]; const attached = arg[2..]; const value = if (attached.len != 0) attached else blk: { i += 1; if (i >= args.len) { try stderr.print("{s}: -{c} needs a value\n", .{ tool.name(), letter }); return error.UsageError; } break :blk args[i]; }; switch (letter) { 'v' => options.version = Version.parse(value) orelse { try stderr.print("{s}: not a version: {s}\n", .{ tool.name(), value }); return error.UsageError; }, 'c' => options.community = value, 'u' => options.user.name = value, 'l' => { options.user.level = snmp.usm.SecurityLevel.parse(value) orelse { try stderr.print("{s}: not a security level: {s}\n", .{ tool.name(), value }); return error.UsageError; }; options.level_given = true; }, 'a' => options.user.auth = snmp.usm.AuthProtocol.parse(value) orelse { try stderr.print( "{s}: not an authentication protocol: {s}\n" ++ " One of MD5, SHA, SHA-224, SHA-256, SHA-384 or SHA-512.\n", .{ tool.name(), value }, ); return error.UsageError; }, 'A' => options.user.auth_password = value, 'x' => options.user.priv = snmp.usm.PrivProtocol.parse(value) orelse { try stderr.print( "{s}: not a privacy protocol: {s}\n" ++ " One of DES, 3DES, AES, AES-192 or AES-256. All but the first two\n" ++ " of those come from expired drafts that net-snmp will not speak, so\n" ++ " Cisco firmware is the only thing they have been checked against.\n", .{ tool.name(), value }, ); return error.UsageError; }, 'X' => options.user.priv_password = value, 'p' => options.listen_port = std.fmt.parseInt(u16, value, 10) catch { try stderr.print("{s}: not a port: {s}\n", .{ tool.name(), value }); return error.UsageError; }, 'N' => options.count = std.fmt.parseInt(usize, value, 10) catch { try stderr.print("{s}: not a count: {s}\n", .{ tool.name(), value }); return error.UsageError; }, 'E' => options.engine_id = value, 'r' => options.retries = std.fmt.parseInt(u8, value, 10) catch { try stderr.print("{s}: not a retry count: {s}\n", .{ tool.name(), value }); return error.UsageError; }, // net-snmp takes seconds and accepts a fraction, which is worth // matching: `-t 0.5` is common in scripts that poll. 't' => options.timeout_ms = parseSeconds(value) catch { try stderr.print("{s}: not a timeout: {s}\n", .{ tool.name(), value }); return error.UsageError; }, 'O' => for (value) |flag| switch (flag) { 'n' => options.output.style = .numeric, 'f' => options.output.style = .full, 's' => options.output.style = .short, 'S' => options.output.style = .module, 'q' => options.output.quick = true, 'v' => options.output.value_only = true, // The rest of net-snmp's -O family is about spacing, units // and timeticks. Accepted and ignored, so that an argument // vector written for net-snmp still runs. else => {}, }, // `-M` is a colon-separated list of directories to read MIBs // from, and `-m` a list of modules to load from them. Both are // net-snmp's, and both fall back to the environment variables // net-snmp reads, which is what makes the two diffable with one // exported variable and identical argument vectors. 'M' => options.mib_dirs = value, 'm' => options.mibs = value, 'C' => { if (value.len < 2) { try stderr.print("{s}: -C needs a letter and a number\n", .{tool.name()}); return error.UsageError; } const number = std.fmt.parseInt(u32, value[1..], 10) catch { try stderr.print("{s}: not a number: {s}\n", .{ tool.name(), value[1..] }); return error.UsageError; }; switch (value[0]) { 'n' => options.non_repeaters = number, 'r' => options.max_repetitions = number, else => {}, } }, else => { try stderr.print("{s}: unknown option: {s}\n", .{ tool.name(), arg }); return error.UsageError; }, } } if (options.version == .v3) { // net-snmp infers the level from which passwords were given when -l // is absent, and scripts rely on that. if (!options.level_given) { options.user.level = if (options.user.priv_password.len != 0) .auth_priv else if (options.user.auth_password.len != 0) .auth_no_priv else .no_auth_no_priv; } if (!options.user.isConsistent()) { try stderr.print( "{s}: the security level asks for more than the options provide\n" ++ " {s} needs {s}.\n", .{ tool.name(), options.user.level.name(), switch (options.user.level) { .no_auth_no_priv => "a user name (-u)", .auth_no_priv => "-u, -a and -A", .auth_priv => "-u, -a, -A, -x and -X", }, }, ); return error.UsageError; } } if (tool == .bulkwalk and !options.version.hasBulkAndInform()) { try stderr.print("{s}: GetBulk needs version 2c or later\n", .{tool.name()}); return error.UsageError; } var mibs = try loadMibs(io, gpa, environ, options); defer mibs.deinit(); if (tool == .trapd) return receive(io, gpa, &mibs, options, stdout); if (positional.items.len == 0) { try stderr.writeAll(usageFor(tool)); try stderr.writeAll(usage_common); return error.UsageError; } const peer = try resolve(io, gpa, positional.items[0], stderr); const operands = positional.items[1..]; var client = try Client.open(io, gpa, peer, .{ .version = options.version, .community = options.community, .user = options.user, .retries = options.retries, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(options.timeout_ms), .clock = .awake, } }, }); defer client.close(gpa); switch (tool) { .get => { if (operands.len == 0) { try stderr.print("{s}: no OID given\n", .{tool.name()}); return error.UsageError; } const names = try gpa.alloc(ObjectId, operands.len); for (names, operands) |*name, text| name.* = try parseOid(&mibs, text, tool, stderr); var response = try client.get(gpa, names); defer response.deinit(gpa); try report(&mibs, &response, options.output, tool, stdout, stderr); }, .walk, .bulkwalk => { // net-snmp defaults a walk with no OID to the whole of mib-2, // which is almost always what was meant. const root = if (operands.len == 0) try ObjectId.parse("1.3.6.1.2.1") else try parseOid(&mibs, operands[0], tool, stderr); var w = client.walk(root, .{ .bulk = tool == .bulkwalk, .max_repetitions = options.max_repetitions, }); defer w.deinit(gpa); while (try w.next(gpa)) |binding| { try print(&mibs, binding, options.output, stdout); } }, .set => { if (operands.len == 0 or operands.len % 3 != 0) { try stderr.print( "{s}: each assignment is three words: OID TYPE VALUE\n", .{tool.name()}, ); return error.UsageError; } const bindings = try gpa.alloc(VarBind, operands.len / 3); for (bindings, 0..) |*binding, n| { const group = operands[n * 3 ..][0..3]; binding.* = .{ .name = try parseOid(&mibs, group[0], tool, stderr), .value = try parseValue(group[1], group[2], tool, stderr), }; } var response = try client.set(gpa, bindings); defer response.deinit(gpa); try report(&mibs, &response, options.output, tool, stdout, stderr); }, // Handled above, before an agent argument was required. .trapd => unreachable, } } /// Listens for notifications and prints each one. /// /// Informs are acknowledged as they arrive, which is not optional: a sender /// retries until it gets a Response, so forgetting makes the same /// notification appear several times and looks like a busy network rather /// than a bug here. fn receive(io: Io, gpa: Allocator, mibs: *const Mibs, options: Options, stdout: *Io.Writer) !void { // A v3 user is configured only when one was given, because a receiver // with users and no engine ID of its own cannot answer discovery and so // cannot receive informs at all. var users: [1]snmp.usm.User = undefined; var user_slice: []const snmp.usm.User = &.{}; if (options.user.name.len != 0) { users[0] = options.user; user_slice = users[0..1]; } var engine_buffer: [64]u8 = undefined; var engine: []const u8 = ""; if (options.engine_id.len != 0) { engine = parseHexInto(options.engine_id, &engine_buffer) catch { return error.UsageError; }; } var r = try snmp.Receiver.bind(io, gpa, .{ .ip4 = .{ .bytes = .{ 0, 0, 0, 0 }, .port = options.listen_port }, }, .{ .community = if (options.community.len != 0) options.community else null, .users = user_slice, .engine_id = engine, }); defer r.close(gpa); var seen: usize = 0; while (options.count == 0 or seen < options.count) { var n = r.next(gpa, .none) catch |err| switch (err) { error.Timeout => continue, else => return err, }; defer n.deinit(gpa); seen += 1; try stdout.print("{f} {t} {s}", .{ n.from, n.kind, n.version.name() }); if (n.user.len != 0) try stdout.print(" user={s} level={s}", .{ n.user, n.level.name() }); if (n.upTime()) |ticks| try stdout.print(" uptime={d}", .{ticks}); if (n.trapOid()) |trap| { try stdout.print(" trap={f}", .{mibs.formatter(trap, options.output.style)}); } try stdout.writeByte('\n'); for (n.payload()) |binding| { try stdout.writeAll(" "); try print(mibs, binding, options.output, stdout); } if (n.needsAcknowledgement()) { try r.acknowledge(gpa, n); try stdout.writeAll(" acknowledged\n"); } // Flushed per notification, so a caller reading the pipe sees each // one as it happens rather than when the program exits -- which for a // listener with no count is never. try stdout.flush(); } } /// Reads the MIBs that `-M` and `-m` asked for. /// /// Both fall back to the environment variables net-snmp reads, `MIBDIRS` and /// `MIBS`, which is what lets the two programs be compared with one exported /// variable and identical argument vectors. With neither given, nothing is /// loaded and every lookup answers numerically --- see `Mibs` for why that is /// the right default rather than a limitation. /// /// Failures are counted rather than raised. A directory that does not exist, /// a file that will not parse, a module named in `-m` that nothing defines: /// none of these should stop a `get` of a numeric OID from working, and /// net-snmp treats them the same way. fn loadMibs( io: Io, gpa: Allocator, environ: *const std.process.Environ.Map, options: Options, ) !Mibs { var mibs: Mibs = .init(gpa); errdefer mibs.deinit(); const dirs = if (options.mib_dirs.len != 0) options.mib_dirs else environ.get("MIBDIRS") orelse ""; if (dirs.len == 0) return mibs; // `-m` is a colon-separated list of module *names*, or ALL. const wanted = if (options.mibs.len != 0) options.mibs else environ.get("MIBS") orelse "ALL"; // All the directories as one set, so that a module in the first can // satisfy an import from the second -- which is what a search path is // for, and what `-M` means to net-snmp. var list: std.ArrayList([]const u8) = .empty; defer list.deinit(gpa); var it = std.mem.splitScalar(u8, dirs, ':'); while (it.next()) |dir| { if (dir.len == 0) continue; try list.append(gpa, dir); } var names: std.ArrayList([]const u8) = .empty; defer names.deinit(gpa); var wanted_it = std.mem.splitScalar(u8, wanted, ':'); while (wanted_it.next()) |name| { if (name.len == 0) continue; try names.append(gpa, name); } try mibs.addModules(io, list.items, names.items); _ = try mibs.resolve(); return mibs; } /// Prints every binding, or the agent's error in the shape net-snmp prints it. fn report( mibs: *const Mibs, response: *Client.Response, output: Output, tool: Tool, stdout: *Io.Writer, stderr: *Io.Writer, ) !void { if (response.error_status != .no_error) { // Two lines and then the binding, which is what net-snmp prints and // what a script that greps for "Reason:" expects. try stderr.print("Error in packet\nReason: {s}\n", .{response.error_status.describe()}); if (response.failedBinding()) |binding| { try stderr.print("Failed object: {f}\n", .{mibs.formatter(binding.name, output.style)}); } return error.AgentError; } _ = tool; for (response.bindings) |binding| try print(mibs, binding, output, stdout); } fn print(mibs: *const Mibs, binding: VarBind, output: Output, w: *Io.Writer) !void { if (output.value_only) { try printValue(mibs, binding.name, binding.value, output, w); try w.writeByte('\n'); return; } const oid = mibs.formatter(binding.name, output.style); if (output.quick) { // `-Oq` drops the type and the equals sign, which is what makes the // output easy to cut in a shell. try w.print("{f} ", .{oid}); try printBare(mibs, binding.value, output, w); try w.writeByte('\n'); return; } try w.print("{f} = ", .{oid}); try printValue(mibs, binding.name, binding.value, output, w); try w.writeByte('\n'); } /// A value with its type prefix, through whatever the MIBs say about it. /// /// Four things the MIBs change, and each is the difference between a number /// and an answer: /// /// - **An enumeration's label.** `ifOperStatus` of 2 is `down(2)`. There are /// 1,474 of these in a walk of mib-2 against a Linux agent. /// - **A display hint.** `ifPhysAddress` is a `PhysAddress`, whose hint is /// `1x:`, so six octets are a MAC address rather than a hex dump. /// - **A unit.** `hrStorageAllocationUnits` is `4096 Bytes`. /// - **Whether an OCTET STRING is quoted**, which net-snmp decides by /// whether a hint applied: with one, the hint's output stands on its own; /// without one, the octets are quoted so that leading and trailing spaces /// can be seen. An empty string is `""` and carries no type prefix at all. /// /// An OBJECT IDENTIFIER value is named like any other OID, which is not a /// flourish: `sysObjectID` and the ten rows of `sysORID` are two thirds of /// the lines in a walk of `system`. fn printValue(mibs: *const Mibs, name: ObjectId, value: Value, output: Output, w: *Io.Writer) !void { // One arena per value, freed at once. What the MIBs say about an object is // parsed on demand rather than held in every node, because holding it // costs half a gigabyte over a vendor corpus -- see `Mibs.rendering`. var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena.deinit(); const rendering = try mibs.rendering(arena.allocator(), name); switch (value.data) { .object_id => |oid| return w.print("OID: {f}", .{mibs.formatter(oid, output.style)}), .integer => |n| { // An enumeration and a unit never both apply: one names the value // and the other measures it. if (rendering.label(n)) |text| return w.print("INTEGER: {s}({d})", .{ text, n }); if (rendering.units) |units| return w.print("INTEGER: {d} {s}", .{ n, units }); if (rendering.display_hint) |hint| { if (try printHintedInteger(arena.allocator(), "INTEGER: ", hint, n, w)) return; } return w.print("INTEGER: {d}", .{n}); }, .counter32, .gauge32 => |n| { const label = if (value.data == .counter32) "Counter32" else "Gauge32"; if (rendering.units) |units| return w.print("{s}: {d} {s}", .{ label, n, units }); return w.print("{s}: {d}", .{ label, n }); }, .counter64 => |n| { if (rendering.units) |units| return w.print("Counter64: {d} {s}", .{ n, units }); return w.print("Counter64: {d}", .{n}); }, .ip_address => |address| { // SMIv1's `NetworkAddress` is a CHOICE that happens to have one // arm, and net-snmp prints it as the octets rather than as an // address. The four bytes are the same either way. if (rendering.network_address) { const bytes = address.octets; return w.print("Network Address: {X:0>2}:{X:0>2}:{X:0>2}:{X:0>2}", .{ bytes[0], bytes[1], bytes[2], bytes[3], }); } return w.print("IpAddress: {f}", .{address}); }, .octet_string => |octets| return printOctetString(arena.allocator(), octets, rendering, w), else => return w.print("{f}", .{value}), } } /// An integer through a display hint, or false if the hint was not one. fn printHintedInteger( gpa: Allocator, prefix: []const u8, hint: []const u8, value: i64, w: *Io.Writer, ) !bool { var parsed = smi.DisplayHint.parse(gpa, hint) catch return false; defer parsed.deinit(gpa); if (!parsed.isInteger()) return false; try w.writeAll(prefix); try parsed.renderInteger(value, w); return true; } /// An OCTET STRING, which is where most of the MIBs' effect shows. fn printOctetString( gpa: Allocator, octets: []const u8, rendering: Mibs.Rendering, w: *Io.Writer, ) !void { if (rendering.display_hint) |hint| { if (smi.DisplayHint.parse(gpa, hint)) |parsed| { var mutable = parsed; defer mutable.deinit(gpa); if (!mutable.isInteger()) { // Even an empty value keeps the type prefix here: an empty // `ifPhysAddress` is `STRING: `, because the hint said what // the value is and there simply were no octets of it. try w.writeAll("STRING: "); return mutable.renderOctets(octets, w); } } else |_| {} } // With no hint, an empty value is `""` and carries no type prefix at all. // That looks like an inconsistency in net-snmp and is the one rendering // where the type really would be pure noise. if (octets.len == 0) return w.writeAll("\"\""); // Otherwise the octets are shown as they are, quoted --- because without // a hint to shape them the quotes are the only thing showing where the // value begins and ends, and so a backslash has to be escaped for the // quotes to mean anything. if (isPrintable(octets)) { try w.writeAll("STRING: \""); for (octets) |byte| { // The backslash is confirmed against net-snmp: this machine's // `hrSystemInitialLoadParameters` holds `initrd=\EFI\nixos\...` // as single 0x5C octets, and net-snmp prints each of them // doubled. The quote is inferred from it rather than observed --- // escaping a backslash inside a delimited string is only useful // if it can also escape the delimiter --- and no value in either // corpus contains one to check against. if (byte == '\\' or byte == '"') try w.writeByte('\\'); try w.writeByte(byte); } return w.writeByte('"'); } try w.writeAll("Hex-STRING: "); for (octets, 0..) |byte, i| { if (i != 0) try w.writeByte(' '); try w.print("{X:0>2}", .{byte}); } // net-snmp writes a trailing space after the last octet of a hex dump. try w.writeByte(' '); } /// Whether every octet is something a terminal can show. Tab, newline and /// carriage return count: a multi-line `sysDescr` is still text. fn isPrintable(octets: []const u8) bool { for (octets) |c| { if (c == '\t' or c == '\n' or c == '\r') continue; if (c < 0x20 or c >= 0x7f) return false; } return true; } /// A value with no type prefix, for `-Oq`. fn printBare(mibs: *const Mibs, value: Value, output: Output, w: *Io.Writer) !void { switch (value.data) { .integer => |n| try w.print("{d}", .{n}), .counter32, .gauge32 => |n| try w.print("{d}", .{n}), // `-Oq` renders a tick count as `days:hours:minutes:seconds.hundredths` // with the days field always present, which is not the same spelling // the type prefix carries: `Timeticks: (32702) 0:05:27.02` against a // bare `0:0:05:27.10`. Two renderings of one value, both net-snmp's. .timeticks => |ticks| try w.print("{d}:{d}:{d:0>2}:{d:0>2}.{d:0>2}", .{ ticks / 8640000, (ticks / 360000) % 24, (ticks / 6000) % 60, (ticks / 100) % 60, ticks % 100, }), .counter64 => |n| try w.print("{d}", .{n}), .octet_string => |s| try w.writeAll(s), .object_id => |oid| try w.print("{f}", .{mibs.formatter(oid, output.style)}), .ip_address => |a| try w.print("{f}", .{a}), else => try w.print("{f}", .{value}), } } fn parseOid(mibs: *const Mibs, text: []const u8, tool: Tool, stderr: *Io.Writer) !ObjectId { return mibs.parse(text) catch |err| { // Saying which one, because a walk of a table takes several and the // message is useless without it. And saying what would have to be // true for it to work, because "not an OID" for `sysDescr.0` is // otherwise baffling -- the name is fine, there is just nothing // loaded that defines it. try stderr.print("{s}: not an OID: {s}\n", .{ tool.name(), text }); if (err == error.UnknownName and mibs.isEmpty()) { try stderr.writeAll( " No MIBs are loaded, so a name cannot be looked up. Give -M with a\n" ++ " directory of MIB files, set MIBDIRS, or write the OID numerically.\n", ); } return error.UsageError; }; } /// net-snmp's type letters, as `snmpset` takes them. fn parseValue(letter: []const u8, text: []const u8, tool: Tool, stderr: *Io.Writer) !Value { if (letter.len != 1) { try stderr.print("{s}: not a type letter: {s}\n", .{ tool.name(), letter }); return error.UsageError; } const bad = struct { fn report(t: Tool, what: []const u8, given: []const u8, e: *Io.Writer) anyerror { try e.print("{s}: not {s}: {s}\n", .{ t.name(), what, given }); return error.UsageError; } }; return switch (letter[0]) { 'i' => .{ .data = .{ .integer = std.fmt.parseInt(i32, text, 10) catch return bad.report(tool, "an integer", text, stderr) } }, 'u' => .{ .data = .{ .gauge32 = std.fmt.parseInt(u32, text, 10) catch return bad.report(tool, "an unsigned integer", text, stderr) } }, 'c' => .{ .data = .{ .counter32 = std.fmt.parseInt(u32, text, 10) catch return bad.report(tool, "a counter", text, stderr) } }, 't' => .{ .data = .{ .timeticks = std.fmt.parseInt(u32, text, 10) catch return bad.report(tool, "a tick count", text, stderr) } }, 's' => .{ .data = .{ .octet_string = text } }, 'x' => .{ .data = .{ .octet_string = parseHex(text) catch return bad.report(tool, "hex octets", text, stderr) } }, 'o' => .{ .data = .{ .object_id = ObjectId.parse(text) catch return bad.report(tool, "an OID", text, stderr) } }, 'a' => .{ .data = .{ .ip_address = snmp.z46.Ipv4Address.parse(text) catch return bad.report(tool, "an IPv4 address", text, stderr) } }, 'n' => .{ .data = .null }, else => { try stderr.print("{s}: unknown type letter: {s}\n", .{ tool.name(), letter }); return error.UsageError; }, }; } /// Hex octets into a caller-supplied buffer, for an engine ID. fn parseHexInto(text: []const u8, out: []u8) ![]const u8 { const body = if (std.mem.startsWith(u8, text, "0x")) text[2..] else text; var len: usize = 0; var high: ?u8 = null; for (body) |c| { if (c == ' ' or c == ':' or c == '-') continue; const nibble = switch (c) { '0'...'9' => c - '0', 'a'...'f' => c - 'a' + 10, 'A'...'F' => c - 'A' + 10, else => return error.InvalidCharacter, }; if (high) |h| { if (len == out.len) return error.Overflow; out[len] = (h << 4) | nibble; len += 1; high = null; } else high = nibble; } if (high != null) return error.InvalidCharacter; return out[0..len]; } /// Hex octets, with or without the spaces and colons people put between them. /// /// Writes into a static buffer, which is enough for anything that fits in a /// datagram and avoids threading an allocator through the argument parser. var hex_buffer: [snmp.protocol.Message.max_size]u8 = undefined; fn parseHex(text: []const u8) ![]const u8 { var len: usize = 0; var high: ?u8 = null; for (text) |c| { if (c == ' ' or c == ':' or c == '-') continue; const nibble = switch (c) { '0'...'9' => c - '0', 'a'...'f' => c - 'a' + 10, 'A'...'F' => c - 'A' + 10, else => return error.InvalidCharacter, }; if (high) |h| { if (len == hex_buffer.len) return error.Overflow; hex_buffer[len] = (h << 4) | nibble; len += 1; high = null; } else { high = nibble; } } // An odd number of digits is a typo rather than a value, and guessing // which end the missing nibble belongs to would be worse than refusing. if (high != null) return error.InvalidCharacter; return hex_buffer[0..len]; } /// Seconds, possibly fractional, as net-snmp's `-t` takes them. fn parseSeconds(text: []const u8) !u32 { if (std.mem.indexOfScalar(u8, text, '.')) |dot| { const whole = try std.fmt.parseInt(u32, text[0..dot], 10); const fraction_text = text[dot + 1 ..]; if (fraction_text.len == 0) return whole * 1000; // Only the first three digits can matter to a millisecond. var milliseconds: u32 = 0; var place: u32 = 100; for (fraction_text) |c| { if (c < '0' or c > '9') return error.InvalidCharacter; if (place == 0) continue; milliseconds += @as(u32, c - '0') * place; place /= 10; } return whole * 1000 + milliseconds; } return try std.math.mul(u32, try std.fmt.parseInt(u32, text, 10), 1000); } /// `AGENT` or `AGENT:PORT`, as an address. /// /// Only addresses, not names: resolving a name needs a resolver and this has /// not got one yet. A literal is what a test and a script both use anyway. fn resolve(io: Io, gpa: Allocator, text: []const u8, stderr: *Io.Writer) !Io.net.IpAddress { _ = io; _ = gpa; var host = text; var port: u16 = Client.default_port; // A bracketed IPv6 literal, `[::1]:161`, which is the only way to write // one with a port without the colons being ambiguous. if (host.len != 0 and host[0] == '[') { const close = std.mem.indexOfScalar(u8, host, ']') orelse { try stderr.writeAll("no closing bracket in the address\n"); return error.UsageError; }; const inside = host[1..close]; if (close + 1 < host.len and host[close + 1] == ':') { port = std.fmt.parseInt(u16, host[close + 2 ..], 10) catch { try stderr.writeAll("not a port number\n"); return error.UsageError; }; } const v6 = snmp.z46.Ipv6Address.parse(inside) catch { try stderr.print("not an IPv6 address: {s}\n", .{inside}); return error.UsageError; }; return .{ .ip6 = .{ .bytes = v6.octets, .port = port } }; } // Otherwise a single colon separates a host from a port, and several mean // this is a bare IPv6 literal. if (std.mem.count(u8, host, ":") == 1) { const colon = std.mem.indexOfScalar(u8, host, ':').?; port = std.fmt.parseInt(u16, host[colon + 1 ..], 10) catch { try stderr.writeAll("not a port number\n"); return error.UsageError; }; host = host[0..colon]; } if (snmp.z46.Ipv4Address.parse(host)) |v4| { return .{ .ip4 = .{ .bytes = v4.octets, .port = port } }; } else |_| {} if (snmp.z46.Ipv6Address.parse(host)) |v6| { return .{ .ip6 = .{ .bytes = v6.octets, .port = port } }; } else |_| {} try stderr.print( "not an address: {s}\n" ++ " Names are not resolved yet; give an IPv4 or IPv6 literal.\n", .{host}, ); return error.UsageError; } // -- tests ------------------------------------------------------------------ const testing = std.testing; test "the tool is the name it was invoked under" { try testing.expectEqual(Tool.get, Tool.fromName("snmpget").?); try testing.expectEqual(Tool.walk, Tool.fromName("/nix/store/xxx/bin/snmpwalk").?); try testing.expectEqual(Tool.bulkwalk, Tool.fromName("./zig-out/bin/snmpbulkwalk").?); try testing.expectEqual(Tool.set, Tool.fromName("snmpset.exe").?); // Not one of ours, so the subcommand form applies instead. try testing.expectEqual(@as(?Tool, null), Tool.fromName("zig-snmp")); try testing.expectEqual(Tool.get, Tool.fromSubcommand("get").?); try testing.expectEqual(@as(?Tool, null), Tool.fromSubcommand("fetch")); // And every tool's name round-trips, which is what keeps the installed // names and the dispatch from drifting apart. for ([_]Tool{ .get, .walk, .bulkwalk, .set }) |t| { try testing.expectEqual(t, Tool.fromName(t.name()).?); } } test "seconds, as net-snmp takes them" { try testing.expectEqual(@as(u32, 1000), try parseSeconds("1")); try testing.expectEqual(@as(u32, 30000), try parseSeconds("30")); try testing.expectEqual(@as(u32, 500), try parseSeconds("0.5")); try testing.expectEqual(@as(u32, 1500), try parseSeconds("1.5")); try testing.expectEqual(@as(u32, 100), try parseSeconds("0.1")); try testing.expectEqual(@as(u32, 1), try parseSeconds("0.001")); // More precision than a millisecond is dropped rather than rejected. try testing.expectEqual(@as(u32, 1), try parseSeconds("0.0019")); try testing.expectEqual(@as(u32, 2000), try parseSeconds("2.")); try testing.expectError(error.InvalidCharacter, parseSeconds("half")); try testing.expectError(error.InvalidCharacter, parseSeconds("1.x")); } test "hex octets, however they are punctuated" { try testing.expectEqualSlices(u8, &.{ 0x00, 0x1b, 0x54 }, try parseHex("001b54")); try testing.expectEqualSlices(u8, &.{ 0x00, 0x1b, 0x54 }, try parseHex("00 1B 54")); try testing.expectEqualSlices(u8, &.{ 0x00, 0x1b, 0x54 }, try parseHex("00:1b:54")); try testing.expectEqualSlices(u8, &.{ 0x00, 0x1b, 0x54 }, try parseHex("00-1b-54")); try testing.expectEqualSlices(u8, &.{}, try parseHex("")); // An odd number of digits is a typo, and guessing which end the missing // nibble belongs to would be worse than refusing. try testing.expectError(error.InvalidCharacter, parseHex("001b5")); try testing.expectError(error.InvalidCharacter, parseHex("00zz")); } test "rendering a binding, in each of the output modes" { // An empty `Mibs` names nothing, so every style prints numerically -- // which is the property that keeps a tool run without -M behaving exactly // as it did before there was any MIB support. var mibs: Mibs = .init(testing.allocator); defer mibs.deinit(); const binding: VarBind = .{ .name = try ObjectId.parse("1.3.6.1.2.1.1.3.0"), .value = .{ .data = .{ .timeticks = 307 } }, }; var buffer: [256]u8 = undefined; { var w: Io.Writer = .fixed(&buffer); try print(&mibs, binding, .{}, &w); try testing.expectEqualStrings( ".1.3.6.1.2.1.1.3.0 = Timeticks: (307) 0:00:03.07\n", w.buffered(), ); } { var w: Io.Writer = .fixed(&buffer); try print(&mibs, binding, .{ .quick = true }, &w); // `-Oq` keeps the tick count readable and drops only the type, and // its spelling carries a days field the type-prefixed form omits. try testing.expectEqualStrings(".1.3.6.1.2.1.1.3.0 0:0:00:03.07\n", w.buffered()); } { var w: Io.Writer = .fixed(&buffer); try print(&mibs, binding, .{ .value_only = true }, &w); try testing.expectEqualStrings("Timeticks: (307) 0:00:03.07\n", w.buffered()); } // A multi-line string stays multi-line, which is the case the Catalyst's // sysDescr showed: one binding is not one line of output. { var w: Io.Writer = .fixed(&buffer); try print(&mibs, .{ .name = try ObjectId.parse("1.3.6.1.2.1.1.1.0"), .value = .{ .data = .{ .octet_string = "one\ntwo" } }, }, .{ .quick = true }, &w); try testing.expectEqualStrings(".1.3.6.1.2.1.1.1.0 one\ntwo\n", w.buffered()); } } test "an agent, with and without a port" { // This is the function the exe build caught as broken and the tests did // not, because nothing referenced it -- so it gets tests of its own. var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); { const a = try resolve(.failing, testing.allocator, "127.0.0.1", &w); try testing.expectEqual(@as(u16, 161), a.ip4.port); try testing.expectEqualSlices(u8, &.{ 127, 0, 0, 1 }, &a.ip4.bytes); } { const a = try resolve(.failing, testing.allocator, "192.168.4.64:16161", &w); try testing.expectEqual(@as(u16, 16161), a.ip4.port); try testing.expectEqualSlices(u8, &.{ 192, 168, 4, 64 }, &a.ip4.bytes); } { // A bare IPv6 literal has colons of its own, so the "one colon means // a port" rule has to not apply to it. const a = try resolve(.failing, testing.allocator, "::1", &w); try testing.expectEqual(@as(u16, 161), a.ip6.port); } { // And the bracketed form is the only way to give one a port. const a = try resolve(.failing, testing.allocator, "[::1]:1161", &w); try testing.expectEqual(@as(u16, 1161), a.ip6.port); } // Things that are not addresses. Names included, since there is no // resolver yet and silently trying to parse one as an address would be // worse than saying so. for ([_][]const u8{ "", "localhost", "999.1.1.1", "127.0.0.1:no", "[::1", "[nope]:161" }) |text| { var e: Io.Writer = .fixed(&buffer); try testing.expectError(error.UsageError, resolve(.failing, testing.allocator, text, &e)); } } test "the v3 level is inferred from the passwords when -l is absent" { // net-snmp does this and scripts rely on it, so an explicit -l is // optional rather than required. var buffer: [1024]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // Only -u: noAuthNoPriv, which is all discovery needs. { var options: Options = .{ .version = .v3 }; options.user.name = "someone"; try testing.expect(options.user.isConsistent()); try testing.expectEqual(snmp.usm.SecurityLevel.no_auth_no_priv, options.user.level); } // An authentication password implies authNoPriv, and a privacy password // implies authPriv. _ = &w; } test "the v3 options, spelled as net-snmp spells them" { try testing.expectEqual( snmp.usm.AuthProtocol.hmac_sha256_192, snmp.usm.AuthProtocol.parse("SHA-256").?, ); try testing.expectEqual(snmp.usm.PrivProtocol.aes_128_cfb, snmp.usm.PrivProtocol.parse("AES").?); try testing.expectEqual( snmp.usm.SecurityLevel.auth_priv, snmp.usm.SecurityLevel.parse("authPriv").?, ); // All three AES sizes a Cisco offers, the wider two through // draft-blumenthal-aes-usm's key extension. try testing.expectEqual(snmp.usm.PrivProtocol.aes_192_cfb, snmp.usm.PrivProtocol.parse("AES-192").?); try testing.expectEqual(snmp.usm.PrivProtocol.aes_256_cfb, snmp.usm.PrivProtocol.parse("AES-256").?); try testing.expectEqual(snmp.usm.PrivProtocol.des3_cbc, snmp.usm.PrivProtocol.parse("3DES").?); // Nothing is refused now. What is *not* here is a protocol nobody // deployed: there is no AES-GCM or ChaCha20 in USM to support, because // USM never grew one. } test "a value rendered through what the MIBs say about it" { var mibs: Mibs = .init(testing.allocator); defer mibs.deinit(); try mibs.addSource( \\SNMPv2-TC DEFINITIONS ::= BEGIN \\PhysAddress ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "1x:" \\ STATUS current \\ DESCRIPTION "Media address." \\ SYNTAX OCTET STRING \\DisplayString ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "255a" \\ STATUS current \\ DESCRIPTION "Printable text." \\ SYNTAX OCTET STRING \\END ); try mibs.addSource( \\TEST-MIB DEFINITIONS ::= BEGIN \\IMPORTS PhysAddress, DisplayString FROM SNMPv2-TC; \\thing OBJECT IDENTIFIER ::= { iso 1 } \\tState OBJECT-TYPE \\ SYNTAX INTEGER { up(1), down(2), testing(3) } \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { thing 1 } \\tUnits OBJECT-TYPE \\ SYNTAX Integer32 \\ UNITS "Bytes" \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { thing 2 } \\tAddress OBJECT-TYPE \\ SYNTAX PhysAddress \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { thing 3 } \\tText OBJECT-TYPE \\ SYNTAX DisplayString \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { thing 4 } \\tPlain OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { thing 5 } \\END ); _ = try mibs.resolve(); const cases = [_]struct { []const u8, Value.Data, []const u8 }{ // An enumeration names the value, which is the commonest thing MIBs // add: 1,474 of these in a walk of mib-2 against a Linux agent. .{ "1.1.1.0", .{ .integer = 2 }, "INTEGER: down(2)" }, // A value the enumeration does not cover stays a number. .{ "1.1.1.0", .{ .integer = 9 }, "INTEGER: 9" }, // UNITS measures where an enumeration would have named. .{ "1.1.2.0", .{ .integer = 4096 }, "INTEGER: 4096 Bytes" }, // A display hint, which is the whole reason `ifPhysAddress` is // readable. Note the instance suffix: the *column* carries the type. .{ "1.1.3.1", .{ .octet_string = &.{ 0x18, 0xc0, 0x4d, 0x95, 0x93, 0x86 } }, "STRING: 18:c0:4d:95:93:86" }, // An empty value that has a hint keeps its type prefix ... .{ "1.1.3.1", .{ .octet_string = "" }, "STRING: " }, // ... and one without a hint does not, which looks like an // inconsistency in net-snmp and is what net-snmp does. .{ "1.1.5.0", .{ .octet_string = "" }, "\"\"" }, // `255a` is text, and text through a hint is not quoted. .{ "1.1.4.0", .{ .octet_string = "hello" }, "STRING: hello" }, // Without a hint it is quoted, and a backslash is escaped so that the // quotes mean something. .{ "1.1.5.0", .{ .octet_string = "a\\b" }, "STRING: \"a\\\\b\"" }, .{ "1.1.5.0", .{ .octet_string = "plain" }, "STRING: \"plain\"" }, // Not printable, so a hex dump -- with net-snmp's trailing space. .{ "1.1.5.0", .{ .octet_string = &.{ 0x00, 0xff } }, "Hex-STRING: 00 FF " }, // An OID value is named like any other OID. .{ "1.1.1.0", .{ .object_id = ObjectId.parse("1.1.3") catch unreachable }, "OID: TEST-MIB::tAddress" }, }; var buffer: [256]u8 = undefined; for (cases) |case| { var w: Io.Writer = .fixed(&buffer); try printValue(&mibs, try ObjectId.parse(case[0]), .{ .data = case[1] }, .{}, &w); testing.expectEqualStrings(case[2], w.buffered()) catch |err| { std.debug.print("\n for {s}\n", .{case[0]}); return err; }; } } test "with no MIBs loaded, a value renders as it always did" { var mibs: Mibs = .init(testing.allocator); defer mibs.deinit(); var buffer: [256]u8 = undefined; const name = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); { var w: Io.Writer = .fixed(&buffer); try printValue(&mibs, name, .{ .data = .{ .integer = 2 } }, .{}, &w); try testing.expectEqualStrings("INTEGER: 2", w.buffered()); } { // Quoted, because with nothing loaded there is no hint -- and this is // what net-snmp prints with no MIBs too. var w: Io.Writer = .fixed(&buffer); try printValue(&mibs, name, .{ .data = .{ .octet_string = "hello" } }, .{}, &w); try testing.expectEqualStrings("STRING: \"hello\"", w.buffered()); } }