Something went wrong. Try again.
An SNMP manager library and command line tools for Zig, covering versions 1, 2c and 3.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A variable binding: an object's name and its value, which is the unit//! everything in SNMP is made of.//!//! `SEQUENCE { name ObjectName, value ObjectSyntax }`. A request sends the//! name it wants with `value` set to NULL -- there is nothing to say yet --//! and the response comes back with the same name and a value, or with an//! exception marker in the value's place.//!//! Like `Value`, a decoded binding borrows: its `octet_string` and//! `@"opaque"` values point into the datagram. A `VarBindList` is a slice of//! them and borrows twice over, from the datagram and from whatever allocated//! the slice.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const testing = std.testing;
const asn1 = @import("asn1");const ObjectId = asn1.ObjectId;
const Value = @import("Value.zig");const Version = @import("Version.zig").Version;
const VarBind = @This();
name: ObjectId,value: Value,
/// A binding asking for an object without saying anything about it, which is/// every varbind in a Get, GetNext or GetBulk request.pub fn request(name: ObjectId) VarBind { return .{ .name = name, .value = .{ .data = .null } };}
pub fn encode(vb: VarBind, e: *asn1.Encoder) asn1.Encoder.Error!void { try e.begin(.sequence); try e.objectId(vb.name); try vb.value.encode(e); try e.end();}
pub const DecodeError = Value.DecodeError;
pub fn decode(el: asn1.Element, version: Version) DecodeError!VarBind { if (!el.tag.eql(.sequence)) return error.UnexpectedTag; var d = el.decoder(); const name = try d.objectId(); const value = try Value.decode(try d.next(), version); // Anything after the value is a field this definition does not have. try d.expectEnd(); return .{ .name = name, .value = value };}
/// `<name> = <value>`, which is the line net-snmp's tools print.////// Note that this can be more than one line: an OCTET STRING may contain/// newlines, and the Catalyst's `sysDescr` contains three. Anything comparing/// this output has to compare records rather than lines.pub fn format(vb: VarBind, w: *Io.Writer) Io.Writer.Error!void { try w.print("{f} = {f}", .{ vb.name, vb.value });}
/// A decoded varbind list, and the allocation holding it.////// The bindings point into the message buffer, so this owns the slice and not/// what the slice points at -- which is why `deinit` takes the allocator back/// rather than keeping one.pub const List = struct { items: []VarBind,
pub const empty: List = .{ .items = &.{} };
pub fn deinit(list: *List, gpa: Allocator) void { gpa.free(list.items); list.* = undefined; }
/// The first binding whose name is `name`, or null. pub fn get(list: List, name: ObjectId) ?Value { for (list.items) |vb| if (vb.name.eql(name)) return vb.value; return null; }};
pub fn encodeList(bindings: []const VarBind, e: *asn1.Encoder) asn1.Encoder.Error!void { try e.begin(.sequence); for (bindings) |vb| try vb.encode(e); try e.end();}
pub const ListDecodeError = DecodeError || Allocator.Error;
/// The `VarBindList` out of a PDU.////// `max` bounds how many bindings will be held for a peer that sends a/// datagram full of them. A UDP datagram is at most 65507 bytes and the/// smallest possible binding is a handful, so the arithmetic bound is in the/// thousands -- but a caller that asked for two variables and got two thousand/// back has been answered by something that is not cooperating.pub fn decodeList(el: asn1.Element, version: Version, gpa: Allocator, max: usize) ListDecodeError!List { if (!el.tag.eql(.sequence)) return error.UnexpectedTag; var d = el.decoder(); var items: std.ArrayList(VarBind) = .empty; errdefer items.deinit(gpa); while (!d.atEnd()) { if (items.items.len == max) return error.TrailingData; try items.append(gpa, try VarBind.decode(try d.next(), version)); } return .{ .items = try items.toOwnedSlice(gpa) };}
// -- tests ------------------------------------------------------------------
test "a request binding is the name and a NULL" { const name = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try VarBind.request(name).encode(&e);
// SEQUENCE { OID sysDescr.0, NULL } -- twelve bytes, and this is the // exact shape net-snmp puts on the wire for `snmpget sysDescr.0`. try testing.expectEqualSlices(u8, &.{ 0x30, 0x0c, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x05, 0x00, }, e.buffered());
var d: asn1.Decoder = .init(e.buffered()); const back = try VarBind.decode(try d.next(), .v2c); try testing.expect(name.eql(back.name)); // `Value.Data.null` would be the tag itself rather than a value of the // union, so the comparison is between two tags. try testing.expectEqual(std.meta.Tag(Value.Data).null, std.meta.activeTag(back.value.data));}
test "a list, and finding a name in it" { const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); const sys_uptime = try ObjectId.parse("1.3.6.1.2.1.1.3.0"); const bindings = [_]VarBind{ .{ .name = sys_descr, .value = .{ .data = .{ .octet_string = "Cisco IOS Software" } } }, .{ .name = sys_uptime, .value = .{ .data = .{ .timeticks = 28572867 } } }, };
var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encodeList(&bindings, &e);
var d: asn1.Decoder = .init(e.buffered()); var list = try decodeList(try d.next(), .v2c, testing.allocator, 16); defer list.deinit(testing.allocator);
try testing.expectEqual(@as(usize, 2), list.items.len); try testing.expectEqualStrings("Cisco IOS Software", list.get(sys_descr).?.data.octet_string); try testing.expectEqual(@as(u32, 28572867), list.get(sys_uptime).?.data.timeticks); try testing.expectEqual(@as(?Value, null), list.get(try ObjectId.parse("1.3.6.1.2.1.1.9.0")));
// The decoded string points into the encoder's buffer rather than being a // copy, which is the property that makes a walk cheap. const borrowed = list.get(sys_descr).?.data.octet_string; try testing.expect(@intFromPtr(borrowed.ptr) >= @intFromPtr(e.buffered().ptr)); try testing.expect(@intFromPtr(borrowed.ptr) < @intFromPtr(e.buffered().ptr) + e.buffered().len);}
test "an empty list is legal" { var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encodeList(&.{}, &e); try testing.expectEqualSlices(u8, &.{ 0x30, 0x00 }, e.buffered());
var d: asn1.Decoder = .init(e.buffered()); var list = try decodeList(try d.next(), .v2c, testing.allocator, 16); defer list.deinit(testing.allocator); try testing.expectEqual(@as(usize, 0), list.items.len);}
test "more bindings than the caller will hold" { var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); var bindings: [8]VarBind = undefined; for (&bindings, 0..) |*vb, i| { vb.* = .request(try (try ObjectId.parse("1.3.6.1.2.1.1")).child(@intCast(i))); } try encodeList(&bindings, &e);
var d: asn1.Decoder = .init(e.buffered()); try testing.expectError(error.TrailingData, decodeList(try d.next(), .v2c, testing.allocator, 4));}
test "a binding with something extra in it" { // SEQUENCE { OID, NULL, NULL } -- a third field this definition has no // room for, which must be refused rather than ignored. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try e.begin(.sequence); try e.objectId(try ObjectId.parse("1.3.6.1")); try e.null(); try e.null(); try e.end();
var d: asn1.Decoder = .init(e.buffered()); try testing.expectError(error.TrailingData, VarBind.decode(try d.next(), .v2c));}
test "rendering a binding" { const vb: VarBind = .{ .name = try ObjectId.parse("1.3.6.1.2.1.1.3.0"), .value = .{ .data = .{ .timeticks = 28572867 } }, }; var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{vb}); try testing.expectEqualStrings( ".1.3.6.1.2.1.1.3.0 = Timeticks: (28572867) 3 days, 7:22:08.67", w.buffered(), );}