// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The protocol data units: the part of a message that says what is being //! asked or answered. //! //! Eight of them, and unlike LDAP's operations they are **context**-tagged //! rather than application-tagged -- `A0` is a GetRequest, not //! `[APPLICATION 0]`. That is visible in any capture: net-snmp sending //! `snmpget -v2c` writes `30 29 02 01 01 04 06 public A0 1C ...`, and the //! `A0` is the PDU. //! //! Six of the eight share one shape, which RFC 3416 calls `PDU`: //! a request-id, an error-status, an error-index and a varbind list. //! `GetBulkRequest` reuses the same three integer slots with the middle two //! meaning something else entirely, and the v1 `Trap-PDU` is a different //! structure altogether. Those are three shapes, so this is a union of three //! rather than one struct with fields that are dead most of the time. //! //! ## The request-id matters more than it looks //! //! It is how a response is matched to its request, and over UDP that is not a //! formality: a reply to an attempt that already timed out can arrive at any //! moment, and a client that accepted it would answer the caller's question //! with the previous question's answer. `Client` drops a mismatched id and //! keeps waiting rather than treating it as a reply. 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 VarBind = @import("VarBind.zig"); const Value = @import("Value.zig"); const Version = @import("Version.zig").Version; const Pdu = @This(); /// The context tag number each PDU is carried under. These are the numbers in /// RFC 3416 §3 and RFC 1157, and they are stable across versions -- a /// GetRequest is `[0]` in v1, v2c and v3 alike. pub const Kind = enum(u32) { get_request = 0, get_next_request = 1, response = 2, set_request = 3, /// v1 only. SNMPv2 reused nothing at 4: it left the number alone and /// added `snmpv2_trap` at 7. trap_v1 = 4, get_bulk_request = 5, inform_request = 6, snmpv2_trap = 7, report = 8, pub fn tag(k: Kind) asn1.Tag { return .context(@intFromEnum(k), true); } /// Which of the three structures this PDU has. pub fn shape(k: Kind) Shape { return switch (k) { .get_bulk_request => .bulk, .trap_v1 => .trap_v1, else => .standard, }; } pub const Shape = enum { standard, bulk, trap_v1 }; /// Whether an agent is expected to answer this. pub fn isRequest(k: Kind) bool { return switch (k) { .get_request, .get_next_request, .set_request, .get_bulk_request, .inform_request => true, .response, .trap_v1, .snmpv2_trap, .report => false, }; } pub fn name(k: Kind) []const u8 { return switch (k) { .get_request => "GetRequest", .get_next_request => "GetNextRequest", .response => "Response", .set_request => "SetRequest", .trap_v1 => "Trap", .get_bulk_request => "GetBulkRequest", .inform_request => "InformRequest", .snmpv2_trap => "SNMPv2-Trap", .report => "Report", }; } }; /// RFC 3416 §3's error-status. The first six are RFC 1157's and are all a v1 /// agent can say; the rest were added by SNMPv2, which is why a v1 agent /// reports a missing object as `no_such_name` in this field while a v2c agent /// reports it as an exception marker in the varbind and leaves this /// `no_error`. pub const ErrorStatus = enum(i32) { no_error = 0, too_big = 1, no_such_name = 2, bad_value = 3, read_only = 4, gen_err = 5, // SNMPv2 and later. no_access = 6, wrong_type = 7, wrong_length = 8, wrong_encoding = 9, wrong_value = 10, no_creation = 11, inconsistent_value = 12, resource_unavailable = 13, commit_failed = 14, undo_failed = 15, authorization_error = 16, not_writable = 17, inconsistent_name = 18, /// An agent may report a status this library has never heard of, and a /// client that refused to decode the message would turn a reportable /// error into an unreportable one. _, /// The message net-snmp prints for this status. pub fn describe(s: ErrorStatus) []const u8 { return switch (s) { .no_error => "(noError) No Error", .too_big => "(tooBig) Response message would have been too large.", .no_such_name => "(noSuchName) There is no such variable name in this MIB.", .bad_value => "(badValue) The value given has the wrong type or length.", .read_only => "(readOnly) The variable cannot be written or created.", .gen_err => "(genError) A general failure occured", .no_access => "noAccess", .wrong_type => "wrongType", .wrong_length => "wrongLength", .wrong_encoding => "wrongEncoding", .wrong_value => "wrongValue", .no_creation => "noCreation", .inconsistent_value => "inconsistentValue", .resource_unavailable => "resourceUnavailable", .commit_failed => "commitFailed", .undo_failed => "undoFailed", .authorization_error => "authorizationError", .not_writable => "notWritable", .inconsistent_name => "inconsistentName", _ => "unknown error status", }; } }; /// The shape six of the eight PDUs share. pub const Standard = struct { request_id: i32, error_status: ErrorStatus = .no_error, /// Which binding the error is about, counting from one. Zero when there /// is no error, and RFC 3416 is explicit that a non-zero index with /// `no_error` is malformed. error_index: i32 = 0, bindings: []const VarBind, }; /// `GetBulkRequest`, which is the same four fields with the middle two /// renamed. That reuse is deliberate in the standard -- it keeps the encoding /// identical -- and it is also why a v1 agent handed one of these does /// something unhelpful rather than reporting an error. pub const Bulk = struct { request_id: i32, /// How many of the leading bindings are to be treated as a plain GetNext, /// with one answer each. Occupies the error-status slot. non_repeaters: u32 = 0, /// How many successive objects to return for each remaining binding. /// Occupies the error-index slot. An agent may return fewer -- the reply /// has to fit in a datagram -- so this is a request and not a promise. max_repetitions: u32 = 0, bindings: []const VarBind, }; /// The v1 `Trap-PDU`, which shares nothing with the others. /// /// SNMPv2 threw this away and replaced it with `SNMPv2-Trap`, an ordinary PDU /// whose first two bindings are `sysUpTime.0` and `snmpTrapOID.0`. The reason /// is visible here: `agent_addr` is an IPv4 address with nowhere to put an /// IPv6 one, and the generic/specific pair cannot name a trap that was not /// foreseen in 1988. pub const TrapV1 = struct { /// Which MIB the trap belongs to. enterprise: ObjectId, /// The agent's own address -- as it believes it to be, which behind NAT /// is not the address the trap arrived from. agent_addr: [4]u8, generic_trap: GenericTrap, /// Meaningful only when `generic_trap` is `enterprise_specific`. specific_trap: i32, /// `sysUpTime` when the trap was sent. time_stamp: u32, bindings: []const VarBind, pub const GenericTrap = enum(i32) { cold_start = 0, warm_start = 1, link_down = 2, link_up = 3, authentication_failure = 4, egp_neighbor_loss = 5, enterprise_specific = 6, _, }; }; kind: Kind, body: Body, pub const Body = union(enum) { standard: Standard, bulk: Bulk, trap_v1: TrapV1, }; pub const DecodeError = VarBind.ListDecodeError || error{ /// A PDU this version of SNMP does not define: a GetBulk in a v1 /// message, or a v1 Trap in a v2c one. WrongVersion, }; /// The greatest number of bindings a decoded PDU will hold. A UDP datagram is /// 65507 bytes and the smallest binding is about six, so nothing legitimate /// comes near this -- it is a bound on what a hostile peer can make us /// allocate, not a limit on what an agent may say. pub const max_bindings = 4096; pub fn get(request_id: i32, bindings: []const VarBind) Pdu { return .{ .kind = .get_request, .body = .{ .standard = .{ .request_id = request_id, .bindings = bindings } } }; } pub fn getNext(request_id: i32, bindings: []const VarBind) Pdu { return .{ .kind = .get_next_request, .body = .{ .standard = .{ .request_id = request_id, .bindings = bindings } } }; } pub fn set(request_id: i32, bindings: []const VarBind) Pdu { return .{ .kind = .set_request, .body = .{ .standard = .{ .request_id = request_id, .bindings = bindings } } }; } pub fn getBulk(request_id: i32, non_repeaters: u32, max_repetitions: u32, bindings: []const VarBind) Pdu { return .{ .kind = .get_bulk_request, .body = .{ .bulk = .{ .request_id = request_id, .non_repeaters = non_repeaters, .max_repetitions = max_repetitions, .bindings = bindings, } } }; } /// The request-id, whichever shape this is. A v1 trap has none, which is part /// of why it cannot be acknowledged. pub fn requestId(p: Pdu) ?i32 { return switch (p.body) { .standard => |s| s.request_id, .bulk => |b| b.request_id, .trap_v1 => null, }; } pub fn varBinds(p: Pdu) []const VarBind { return switch (p.body) { .standard => |s| s.bindings, .bulk => |b| b.bindings, .trap_v1 => |t| t.bindings, }; } pub fn encode(p: Pdu, e: *asn1.Encoder) asn1.Encoder.Error!void { try e.begin(p.kind.tag()); switch (p.body) { .standard => |s| { try e.integer(i32, s.request_id); try e.integerTagged(.integer, i32, @intFromEnum(s.error_status)); try e.integer(i32, s.error_index); try VarBind.encodeList(s.bindings, e); }, .bulk => |b| { try e.integer(i32, b.request_id); try e.integer(u32, b.non_repeaters); try e.integer(u32, b.max_repetitions); try VarBind.encodeList(b.bindings, e); }, .trap_v1 => |t| { try e.objectId(t.enterprise); try e.primitive(Value.application.ip_address, &t.agent_addr); try e.integerTagged(.integer, i32, @intFromEnum(t.generic_trap)); try e.integer(i32, t.specific_trap); try e.integerTagged(Value.application.timeticks, u32, t.time_stamp); try VarBind.encodeList(t.bindings, e); }, } try e.end(); } /// The bindings are allocated from `gpa`; everything they point at stays in /// the buffer `el` came from. pub fn decode(el: asn1.Element, version: Version, gpa: Allocator) DecodeError!Pdu { // Context class, not application: this is the one place SNMP's framing // differs from LDAP's in a way that would silently accept the wrong // messages if it were not checked. if (el.tag.class != .context or !el.tag.constructed) return error.UnexpectedTag; const kind: Kind = switch (el.tag.number) { 0 => .get_request, 1 => .get_next_request, 2 => .response, 3 => .set_request, 4 => .trap_v1, 5 => .get_bulk_request, 6 => .inform_request, 7 => .snmpv2_trap, 8 => .report, else => return error.UnexpectedTag, }; switch (kind) { .trap_v1 => if (!version.hasV1Trap()) return error.WrongVersion, .get_bulk_request, .inform_request, .snmpv2_trap, .report => { if (!version.hasBulkAndInform()) return error.WrongVersion; }, else => {}, } var d = el.decoder(); const body: Body = switch (kind.shape()) { .standard => blk: { const request_id = try d.integer(i32); const error_status: ErrorStatus = @enumFromInt(try d.integer(i32)); const error_index = try d.integer(i32); var list = try VarBind.decodeList(try d.next(), version, gpa, max_bindings); errdefer list.deinit(gpa); try d.expectEnd(); break :blk .{ .standard = .{ .request_id = request_id, .error_status = error_status, .error_index = error_index, .bindings = list.items, } }; }, .bulk => blk: { const request_id = try d.integer(i32); // These two occupy the error-status and error-index slots and are // unsigned there, so a negative is malformed rather than large. const non_repeaters = try d.integer(u32); const max_repetitions = try d.integer(u32); var list = try VarBind.decodeList(try d.next(), version, gpa, max_bindings); errdefer list.deinit(gpa); try d.expectEnd(); break :blk .{ .bulk = .{ .request_id = request_id, .non_repeaters = non_repeaters, .max_repetitions = max_repetitions, .bindings = list.items, } }; }, .trap_v1 => blk: { const enterprise = try d.objectId(); const addr = try d.expect(Value.application.ip_address); if (addr.content.len != 4) return error.InvalidValue; const generic: TrapV1.GenericTrap = @enumFromInt(try d.integer(i32)); const specific = try d.integer(i32); const time_stamp = try (try d.expect(Value.application.timeticks)).integer(u32); var list = try VarBind.decodeList(try d.next(), version, gpa, max_bindings); errdefer list.deinit(gpa); try d.expectEnd(); break :blk .{ .trap_v1 = .{ .enterprise = enterprise, .agent_addr = addr.content[0..4].*, .generic_trap = generic, .specific_trap = specific, .time_stamp = time_stamp, .bindings = list.items, } }; }, }; return .{ .kind = kind, .body = body }; } /// Frees what `decode` allocated. The bindings themselves point into the /// message buffer and are not freed. pub fn deinit(p: *Pdu, gpa: Allocator) void { gpa.free(p.varBinds()); p.* = undefined; } // -- tests ------------------------------------------------------------------ const oid = struct { fn parse(text: []const u8) ObjectId { return ObjectId.parse(text) catch unreachable; } }; test "a GetRequest is context-tagged, not application-tagged" { // This is the byte net-snmp actually sends, and getting the class wrong // would produce 0x60 instead -- a message every agent rejects. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); const bindings = [_]VarBind{.request(oid.parse("1.3.6.1.2.1.1.1.0"))}; try Pdu.get(0x01bd0311, &bindings).encode(&e); try testing.expectEqual(@as(u8, 0xa0), e.buffered()[0]); // And the whole PDU, byte for byte, as captured from // `snmpget -v2c -c public -d ... 1.3.6.1.2.1.1.1.0`. try testing.expectEqualSlices(u8, &.{ 0xa0, 0x1c, 0x02, 0x04, 0x01, 0xbd, 0x03, 0x11, // request-id 0x02, 0x01, 0x00, // error-status 0x02, 0x01, 0x00, // error-index 0x30, 0x0e, // varbind list 0x30, 0x0c, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x05, 0x00, }, e.buffered()); } fn roundTrip(p: Pdu, version: Version) !void { var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try p.encode(&e); var d: asn1.Decoder = .init(e.buffered()); var back = try Pdu.decode(try d.next(), version, testing.allocator); defer back.deinit(testing.allocator); try testing.expectEqual(p.kind, back.kind); try testing.expectEqual(p.requestId(), back.requestId()); try testing.expectEqual(p.varBinds().len, back.varBinds().len); // And re-encoding what was decoded gives the identical bytes, which is // the property that catches an encoder and a decoder disagreeing. var again: asn1.Encoder = .init(testing.allocator); defer again.deinit(); try back.encode(&again); try testing.expectEqualSlices(u8, e.buffered(), again.buffered()); } test "every standard PDU round-trips" { const bindings = [_]VarBind{ .request(oid.parse("1.3.6.1.2.1.1.1.0")), .{ .name = oid.parse("1.3.6.1.2.1.1.3.0"), .value = .{ .data = .{ .timeticks = 28572867 } } }, }; for ([_]Kind{ .get_request, .get_next_request, .response, .set_request, .inform_request, .snmpv2_trap, .report }) |kind| { try roundTrip(.{ .kind = kind, .body = .{ .standard = .{ .request_id = 12345, .bindings = &bindings } }, }, .v2c); } } test "GetBulk reuses the error slots for its own two numbers" { const bindings = [_]VarBind{.request(oid.parse("1.3.6.1.2.1.2.2.1.2"))}; const p = Pdu.getBulk(7, 0, 10, &bindings); try roundTrip(p, .v2c); // Encoded, the two numbers sit exactly where error-status and error-index // would. That identity is what lets an agent parse either without knowing // which it has yet. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try p.encode(&e); var d: asn1.Decoder = .init(e.buffered()); var inner = (try d.next()).decoder(); try testing.expectEqual(@as(i32, 7), try inner.integer(i32)); try testing.expectEqual(@as(u32, 0), try inner.integer(u32)); try testing.expectEqual(@as(u32, 10), try inner.integer(u32)); } test "the v1 trap, which is its own structure" { const bindings = [_]VarBind{ .{ .name = oid.parse("1.3.6.1.2.1.2.2.1.1.1"), .value = .{ .data = .{ .integer = 1 } } }, }; try roundTrip(.{ .kind = .trap_v1, .body = .{ .trap_v1 = .{ .enterprise = oid.parse("1.3.6.1.4.1.9"), .agent_addr = .{ 192, 168, 4, 64 }, .generic_trap = .link_down, .specific_trap = 0, .time_stamp = 28572867, .bindings = &bindings, } }, }, .v1); } test "a PDU in the wrong version" { const bindings = [_]VarBind{.request(oid.parse("1.3.6.1"))}; // GetBulk did not exist in v1. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try Pdu.getBulk(1, 0, 10, &bindings).encode(&e); var d: asn1.Decoder = .init(e.buffered()); try testing.expectError(error.WrongVersion, Pdu.decode(try d.next(), .v1, testing.allocator)); // And the v1 trap does not exist in v2c. var e2: asn1.Encoder = .init(testing.allocator); defer e2.deinit(); try (Pdu{ .kind = .trap_v1, .body = .{ .trap_v1 = .{ .enterprise = oid.parse("1.3.6.1.4.1.9"), .agent_addr = .{ 127, 0, 0, 1 }, .generic_trap = .cold_start, .specific_trap = 0, .time_stamp = 0, .bindings = &.{}, } } }).encode(&e2); var d2: asn1.Decoder = .init(e2.buffered()); try testing.expectError(error.WrongVersion, Pdu.decode(try d2.next(), .v2c, testing.allocator)); } test "a tag that is no PDU at all" { // [9] is undefined, and application class is the wrong class entirely. for ([_][]const u8{ "\xa9\x00", "\x60\x00", "\x30\x00" }) |bytes| { var d: asn1.Decoder = .init(bytes); try testing.expectError(error.UnexpectedTag, Pdu.decode(try d.next(), .v2c, testing.allocator)); } } test "an error status this library has never heard of" { // A non-exhaustive enum, because refusing to decode the message would // turn a reportable error into an unreportable one. const status: ErrorStatus = @enumFromInt(99); try testing.expectEqualStrings("unknown error status", status.describe()); var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try (Pdu{ .kind = .response, .body = .{ .standard = .{ .request_id = 1, .error_status = status, .error_index = 1, .bindings = &.{}, } } }).encode(&e); var d: asn1.Decoder = .init(e.buffered()); var back = try Pdu.decode(try d.next(), .v2c, testing.allocator); defer back.deinit(testing.allocator); try testing.expectEqual(status, back.body.standard.error_status); } test "which PDUs an agent is expected to answer" { try testing.expect(Kind.get_request.isRequest()); try testing.expect(Kind.get_bulk_request.isRequest()); try testing.expect(Kind.inform_request.isRequest()); try testing.expect(!Kind.response.isRequest()); try testing.expect(!Kind.snmpv2_trap.isRequest()); try testing.expect(!Kind.report.isRequest()); // A v1 trap has no request-id, which is why nothing can acknowledge it. try testing.expectEqual(@as(u32, 4), @intFromEnum(Kind.trap_v1)); }