// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The record types that were tried and not kept. //! //! Almost nothing here is served by anybody. They are implemented anyway, //! because a decoder that guesses is worse than one that knows: `loc` has a //! latitude that is not a number in any ordinary sense, `apl` has a length //! byte whose top bit is a negation, `a6` has an address with a hole in it, //! and the way to be sure none of that is being misread as something else is //! to read it properly. Several of them also carry a domain name, which means //! the difference between decoding one and treating it as opaque bytes is //! whether a compression pointer inside it is followed or ignored. //! //! What they cost is a switch arm each. What they buy is that a message //! holding one is decoded rather than half-decoded, and that this library //! agrees with the other implementations about what is in it. const std = @import("std"); const Writer = std.Io.Writer; const z46 = @import("z46"); const Builder = @import("../Builder.zig"); const Name = @import("../Name.zig"); const presentation = @import("../presentation.zig"); const types = @import("../types.zig"); const wire = @import("../wire.zig"); const Type = types.Type; const Decoder = wire.Decoder; pub const Error = wire.Error || error{ /// The record data is not the shape its type requires. MalformedRdata, }; /// Anything at all, up to 65535 bytes: `null` (RFC 1035 §3.3.10), and /// `unspec`, which is the same idea with a different number. /// /// The type exists so that a record which is deliberately shapeless is not /// confused with one whose shape this library has not been told about. Both /// print in the `\# length hex` form of RFC 3597, because there is nothing /// else true to say about them. pub const Opaque = struct { bytes: []const u8, /// Takes the rest of the record data as it is. There is no shape to /// refuse, so this cannot fail. pub fn parse(d: *Decoder) Error!Opaque { return .{ .bytes = d.takeRest() }; } test parse { var d = try Decoder.init("\x01\x02\x03"); const value = try Opaque.parse(&d); try std.testing.expectEqualSlices(u8, "\x01\x02\x03", value.bytes); } /// Writes the bytes exactly as they are. pub fn writeTo(self: Opaque, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try (Opaque{ .bytes = "\x01\x02\x03" }).writeTo(&b); try std.testing.expectEqualSlices(u8, "\x01\x02\x03", b.buffer[12..b.pos]); } /// Prints the `\# length hex` form, which is the only one these types /// have. pub fn format(self: Opaque, w: *Writer) Writer.Error!void { try presentation.writeUnknownRdata(w, self.bytes); } test format { try std.testing.expectFmt("\\# 3 010203", "{f}", .{Opaque{ .bytes = "\x01\x02\x03" }}); // Nothing at all is still written with its length. try std.testing.expectFmt("\\# 0", "{f}", .{Opaque{ .bytes = "" }}); } }; /// A bag of bytes with a presentation form of its own: `nsap`, written as /// `0x` and then hexadecimal, because an NSAP address has no other notation /// anybody agreed on. pub const Nsap = struct { bytes: []const u8, /// Takes the rest of the record data as the address. Its internal /// structure is not checked. pub fn parse(d: *Decoder) Error!Nsap { return .{ .bytes = d.takeRest() }; } test parse { var d = try Decoder.init("\x47\x00\x05\x80"); const value = try Nsap.parse(&d); try std.testing.expectEqual(@as(usize, 4), value.bytes.len); } /// Writes the address bytes as they are. pub fn writeTo(self: Nsap, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try (Nsap{ .bytes = "\x47\x00\x05\x80" }).writeTo(&b); try std.testing.expectEqualSlices(u8, "\x47\x00\x05\x80", b.buffer[12..b.pos]); } /// Prints `0x` and the address in lowercase hexadecimal, with no dots. pub fn format(self: Nsap, w: *Writer) Writer.Error!void { try w.writeAll("0x"); try presentation.writeHexLower(w, self.bytes); } test format { try std.testing.expectFmt("0x47000580", "{f}", .{Nsap{ .bytes = "\x47\x00\x05\x80" }}); } }; /// A number and a name: `afsdb`'s subtype and server, `rt`'s preference and /// intermediate host, `kx`'s preference and key exchanger, and `lp`'s /// preference and locator. /// /// Four records with four meanings and one shape. The name is not /// compressed on the way out: RFC 3597 §4 allows compression only in the types /// RFC 1035 defined, and none of these is one. pub const PrefixedName = struct { /// A preference for `rt`, `kx` and `lp`, where lower is tried first, and a /// subtype for `afsdb`, where 1 is a cell database server and 2 is a DCE /// name server. number: u16, name: Name, /// `compression` is the type's: RFC 3597 §4 asks a reader to decompress /// `afsdb` and `rt`, and `kx` and `lp` were never allowed it. /// With `.forbidden`, a pointer in the name is `error.CompressionForbidden`. pub fn parse(d: *Decoder, compression: wire.Compression) Error!PrefixedName { return .{ .number = try d.int(u16), .name = try d.nameWith(compression) }; } test parse { var afsdb = try Decoder.init("\x00\x01\x03afs\x07example\x00"); const value = try PrefixedName.parse(&afsdb, .allowed); try std.testing.expectEqual(@as(u16, 1), value.number); try std.testing.expectFmt("afs.example.", "{f}", .{value.name}); // A `kx` whose name points back at one earlier in the message. var kx = (try Decoder.init("\x03afs\x00" ++ "\x00\x0a\xc0\x00")).at(5); try std.testing.expectError(error.CompressionForbidden, PrefixedName.parse(&kx, .forbidden)); } /// Writes the number and then the name, which is never compressed. pub fn writeTo(self: PrefixedName, b: *Builder) Builder.Error!void { try b.int(u16, self.number); try b.name(self.name, .uncompressed); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const kx: PrefixedName = .{ .number = 10, .name = .literal("kx.example") }; try kx.writeTo(&b); try std.testing.expectEqualSlices(u8, "\x00\x0a\x02kx\x07example\x00", b.buffer[12..b.pos]); } /// Prints the number and then the name. pub fn format(self: PrefixedName, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.number, self.name }); } test format { const rt: PrefixedName = .{ .number = 20, .name = .literal("relay.example") }; try std.testing.expectFmt("20 relay.example.", "{f}", .{rt}); } }; /// How to reach an X.400 address through an RFC 822 one, or the other way /// about (RFC 2163). pub const Px = struct { preference: u16, /// The RFC 822 half of the mapping. map822: Name, /// The X.400 half. mapx400: Name, /// Reads the preference and the two names, following a compression pointer /// in either: RFC 3597 §4 names `px` among the types a reader should /// decompress. pub fn parse(d: *Decoder) Error!Px { return .{ .preference = try d.int(u16), .map822 = try d.name(), .mapx400 = try d.name(), }; } test parse { var d = try Decoder.init("\x00\x0a\x03foo\x00\x03bar\x00"); const px = try Px.parse(&d); try std.testing.expectEqual(@as(u16, 10), px.preference); try std.testing.expectFmt("bar.", "{f}", .{px.mapx400}); } /// Writes the preference and both names, never compressed: `px` is not one /// of the types RFC 1035 defined. pub fn writeTo(self: Px, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.name(self.map822, .uncompressed); try b.name(self.mapx400, .uncompressed); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const px: Px = .{ .preference = 10, .map822 = .literal("foo"), .mapx400 = .literal("bar") }; try px.writeTo(&b); try std.testing.expectEqualSlices(u8, "\x00\x0a\x03foo\x00\x03bar\x00", b.buffer[12..b.pos]); } /// Prints the preference, the RFC 822 half, then the X.400 half. pub fn format(self: Px, w: *Writer) Writer.Error!void { try w.print("{d} {f} {f}", .{ self.preference, self.map822, self.mapx400 }); } test format { const px: Px = .{ .preference = 10, .map822 = .literal("foo"), .mapx400 = .literal("bar") }; try std.testing.expectFmt("10 foo. bar.", "{f}", .{px}); } }; /// An X.25 address (RFC 1183), which is a character-string holding a PSDN /// number. pub const X25 = struct { address: []const u8, /// Reads the one character-string, refusing as `MalformedRdata` one that /// is not what RFC 1183 §3.1 says it is: decimal digits, beginning with /// the four of the DNIC, so four of them at least. pub fn parse(d: *Decoder) Error!X25 { const address = try d.characterString(); if (address.len < 4) return error.MalformedRdata; for (address) |c| if (!std.ascii.isDigit(c)) return error.MalformedRdata; return .{ .address = address }; } test parse { var d = try Decoder.init("\x0c311061700956"); const x25 = try X25.parse(&d); try std.testing.expectEqualStrings("311061700956", x25.address); // Letters are not an X.121 address, and three digits are not a DNIC. var letters = try Decoder.init("\x05relay"); try std.testing.expectError(error.MalformedRdata, X25.parse(&letters)); var short = try Decoder.init("\x03311"); try std.testing.expectError(error.MalformedRdata, X25.parse(&short)); } /// Writes the address as a character-string, refusing one over 255 bytes. pub fn writeTo(self: X25, b: *Builder) Builder.Error!void { try b.characterString(self.address); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try (X25{ .address = "311061700956" }).writeTo(&b); try std.testing.expectEqualSlices(u8, "\x0c311061700956", b.buffer[12..b.pos]); } /// Prints the address as a quoted string. pub fn format(self: X25, w: *Writer) Writer.Error!void { try presentation.writeCharacterString(w, self.address); } test format { try std.testing.expectFmt("\"311061700956\"", "{f}", .{X25{ .address = "311061700956" }}); } }; /// An ISDN address and, optionally, a subaddress (RFC 1183). The subaddress /// is absent rather than empty when it was not given, which is the one thing /// the encoding can say and an empty string cannot. pub const Isdn = struct { address: []const u8, subaddress: ?[]const u8 = null, /// Reads the address, and a subaddress only if there is record data left /// after it, refusing as `MalformedRdata` either one that is not what RFC /// 1183 §3.2 says it is. The address is required, and is "normally decimal /// digits" but may be any IA5 character, so it is checked only for being /// there and being seven-bit ASCII. The subaddress is hexadecimal digits, /// one at least when it is given. pub fn parse(d: *Decoder) Error!Isdn { const address = try d.characterString(); if (address.len == 0) return error.MalformedRdata; for (address) |c| if (!std.ascii.isAscii(c)) return error.MalformedRdata; const subaddress = if (d.atEnd()) null else try d.characterString(); if (subaddress) |sa| { if (sa.len == 0) return error.MalformedRdata; for (sa) |c| if (!std.ascii.isHex(c)) return error.MalformedRdata; } return .{ .address = address, .subaddress = subaddress }; } test parse { var d = try Decoder.init("\x041234\x03004"); const isdn = try Isdn.parse(&d); try std.testing.expectEqualStrings("1234", isdn.address); try std.testing.expectEqualStrings("004", isdn.subaddress.?); // A subaddress is hexadecimal; an address need not be digits. var hex = try Decoder.init("\x05+1-80\x024f"); _ = try Isdn.parse(&hex); var not_hex = try Decoder.init("\x041234\x02zz"); try std.testing.expectError(error.MalformedRdata, Isdn.parse(¬_hex)); } /// Writes the address, and the subaddress only when there is one, so that /// an absent one stays absent rather than becoming empty. pub fn writeTo(self: Isdn, b: *Builder) Builder.Error!void { try b.characterString(self.address); if (self.subaddress) |sa| try b.characterString(sa); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try (Isdn{ .address = "1234" }).writeTo(&b); try std.testing.expectEqualSlices(u8, "\x041234", b.buffer[12..b.pos]); } /// Prints the address as a quoted string, and the subaddress after it when /// there is one. pub fn format(self: Isdn, w: *Writer) Writer.Error!void { try presentation.writeCharacterString(w, self.address); if (self.subaddress) |sa| { try w.writeByte(' '); try presentation.writeCharacterString(w, sa); } } test format { try std.testing.expectFmt("\"1234\"", "{f}", .{Isdn{ .address = "1234" }}); // An empty subaddress is still one, and is printed. try std.testing.expectFmt("\"1234\" \"\"", "{f}", .{Isdn{ .address = "1234", .subaddress = "" }}); } }; /// A geographical position as three decimal strings (RFC 1712), which `loc` /// replaced with something a machine can compare. pub const Gpos = struct { longitude: []const u8, latitude: []const u8, altitude: []const u8, /// Reads the three strings, checking that each is a real number as RFC /// 1712 §3 has them: a sign if wanted, then digits with at most one /// decimal point among them, and at least one digit. Whether a latitude is /// within ±90 is not checked -- the RFC itself has the two ranges the /// wrong way round, and a value that is a number but not a place is /// carried, as `loc`'s are. pub fn parse(d: *Decoder) Error!Gpos { const out: Gpos = .{ .longitude = try d.characterString(), .latitude = try d.characterString(), .altitude = try d.characterString(), }; for ([_][]const u8{ out.longitude, out.latitude, out.altitude }) |text| { if (!isRealNumber(text)) return error.MalformedRdata; } return out; } test parse { var d = try Decoder.init("\x08-32.6882\x08116.8652\x0410.0"); const gpos = try Gpos.parse(&d); try std.testing.expectEqualStrings("116.8652", gpos.latitude); // A unit after the altitude makes it not a number. var bad = try Decoder.init("\x011\x011\x021m"); try std.testing.expectError(error.MalformedRdata, Gpos.parse(&bad)); } fn isRealNumber(text: []const u8) bool { var rest = text; if (rest.len > 0 and (rest[0] == '-' or rest[0] == '+')) rest = rest[1..]; var digits: usize = 0; var points: usize = 0; for (rest) |c| switch (c) { '0'...'9' => digits += 1, '.' => points += 1, else => return false, }; return digits > 0 and points <= 1; } /// Writes the three strings as they are. They are not checked to be /// numbers here, any more than other record data is checked on the way /// out. pub fn writeTo(self: Gpos, b: *Builder) Builder.Error!void { try b.characterString(self.longitude); try b.characterString(self.latitude); try b.characterString(self.altitude); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const gpos: Gpos = .{ .longitude = "-32.6882", .latitude = "116.8652", .altitude = "10.0" }; try gpos.writeTo(&b); try std.testing.expectEqualSlices(u8, "\x08-32.6882\x08116.8652\x0410.0", b.buffer[12..b.pos]); } /// Prints the three strings, each quoted, in the order they are sent. pub fn format(self: Gpos, w: *Writer) Writer.Error!void { try presentation.writeCharacterString(w, self.longitude); try w.writeByte(' '); try presentation.writeCharacterString(w, self.latitude); try w.writeByte(' '); try presentation.writeCharacterString(w, self.altitude); } test format { const gpos: Gpos = .{ .longitude = "-32.6882", .latitude = "116.8652", .altitude = "10.0" }; try std.testing.expectFmt("\"-32.6882\" \"116.8652\" \"10.0\"", "{f}", .{gpos}); } }; /// Which services a host offers, as a bitmap over port numbers (RFC 1035 /// §3.4.2). Obsolete, and obsolete for a good reason: a zone had to be edited /// every time a port opened, and `srv` asks the question the other way round. pub const Wks = struct { address: z46.Ipv4Address, /// An IP protocol number: 6 is TCP, 17 is UDP. protocol: u8, /// One bit per port, most significant bit of the first byte being port 0. ports: []const u8, /// Whether the bitmap claims a port. pub fn has(self: Wks, port: u16) bool { const index = port / 8; if (index >= self.ports.len) return false; return self.ports[index] & (@as(u8, 0x80) >> @truncate(port % 8)) != 0; } test has { // TCP with port 25, SMTP, and nothing else. const wks: Wks = .{ .address = .{ .octets = .{ 192, 0, 2, 1 } }, .protocol = 6, .ports = "\x00\x00\x00\x40" }; try std.testing.expect(wks.has(25)); // A port past the end of the bitmap is simply not claimed. try std.testing.expect(!wks.has(80)); } /// Reads the address, the protocol, and the rest as the bitmap, which may /// be any length, including none. pub fn parse(d: *Decoder) Error!Wks { return .{ .address = .{ .octets = (try d.take(4))[0..4].* }, .protocol = try d.int(u8), .ports = d.takeRest(), }; } test parse { var d = try Decoder.init("\xc0\x00\x02\x01\x06\x00\x00\x00\x40"); const wks = try Wks.parse(&d); try std.testing.expectEqual(@as(u8, 6), wks.protocol); try std.testing.expectEqual(@as(usize, 4), wks.ports.len); } /// Writes the address, the protocol and the bitmap as it is. pub fn writeTo(self: Wks, b: *Builder) Builder.Error!void { try b.writeAll(&self.address.octets); try b.int(u8, self.protocol); try b.writeAll(self.ports); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const wks: Wks = .{ .address = .{ .octets = .{ 192, 0, 2, 1 } }, .protocol = 6, .ports = "\x00\x00\x00\x40" }; try wks.writeTo(&b); try std.testing.expectEqualSlices(u8, "\xc0\x00\x02\x01\x06\x00\x00\x00\x40", b.buffer[12..b.pos]); } /// Prints the address, the protocol number, and then each port the bitmap /// claims as a number, in order. pub fn format(self: Wks, w: *Writer) Writer.Error!void { try w.print("{f} {d}", .{ self.address, self.protocol }); for (self.ports, 0..) |byte, index| { var bit: u4 = 0; while (bit < 8) : (bit += 1) { if (byte & (@as(u8, 0x80) >> @intCast(bit)) != 0) { try w.print(" {d}", .{index * 8 + bit}); } } } } test format { // Ports 21 and 25, FTP and SMTP. const wks: Wks = .{ .address = .{ .octets = .{ 192, 0, 2, 1 } }, .protocol = 6, .ports = "\x00\x00\x04\x40" }; try std.testing.expectFmt("192.0.2.1 6 21 25", "{f}", .{wks}); } }; /// The first attempt at authenticated denial (RFC 2535): the next name in the /// zone, and a flat bit vector of the types at this one. /// /// Flat, not windowed -- the bit for type `t` is bit `t` counting from the top /// of the first byte, so covering type 65534 would take eight kilobytes. That /// is the defect `nsec` was invented to fix, and the reason this encoding /// cannot express a type above 127 in practice. pub const Nxt = struct { next: Name, /// The bit vector, as it appeared. bitmap: []const u8, /// Whether the bitmap has the bit for `t` set. A type past the end of the /// bitmap is not there. pub fn contains(self: Nxt, t: Type) bool { const value = @backingInt(t); const index = value / 8; if (index >= self.bitmap.len) return false; return self.bitmap[index] & (@as(u8, 0x80) >> @truncate(value % 8)) != 0; } test contains { // Bits 1 (A), 15 (MX) and 30 (NXT). const nxt: Nxt = .{ .next = .literal("next"), .bitmap = "\x40\x01\x00\x02" }; try std.testing.expect(nxt.contains(.mx)); try std.testing.expect(!nxt.contains(.aaaa)); } /// Reads the next name, following a compression pointer as RFC 3597 §4 /// asks for `nxt`, and takes the rest of the record data as the bitmap. pub fn parse(d: *Decoder) Error!Nxt { return .{ .next = try d.name(), .bitmap = d.takeRest() }; } test parse { var d = try Decoder.init("\x04next\x00" ++ "\x40\x01\x00\x02"); const nxt = try Nxt.parse(&d); try std.testing.expectFmt("next.", "{f}", .{nxt.next}); try std.testing.expect(nxt.contains(.a)); } /// Writes the next name, never compressed, and the bitmap as it is. pub fn writeTo(self: Nxt, b: *Builder) Builder.Error!void { try b.name(self.next, .uncompressed); try b.writeAll(self.bitmap); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const nxt: Nxt = .{ .next = .literal("next"), .bitmap = "\x40\x01\x00\x02" }; try nxt.writeTo(&b); try std.testing.expectEqualSlices(u8, "\x04next\x00\x40\x01\x00\x02", b.buffer[12..b.pos]); } /// Prints the next name and then each type whose bit is set, by mnemonic. pub fn format(self: Nxt, w: *Writer) Writer.Error!void { try w.print("{f}", .{self.next}); for (self.bitmap, 0..) |byte, index| { var bit: u4 = 0; while (bit < 8) : (bit += 1) { if (byte & (@as(u8, 0x80) >> @intCast(bit)) != 0) { // A bitmap is the rest of the rdata, which can run past // the last bit a 16-bit type number can name. Those bits // are no type at all, and there is nothing to print. const value = std.math.cast(u16, index * 8 + bit) orelse return; const t: Type = @fromBackingInt(value); try w.print(" {f}", .{t}); } } } } test format { const nxt: Nxt = .{ .next = .literal("next"), .bitmap = "\x40\x01\x00\x02" }; try std.testing.expectFmt("next. A MX NXT", "{f}", .{nxt}); } }; /// An IPv6 address with its prefix somewhere else (RFC 2874), so that /// renumbering a network meant editing one record rather than all of them. /// /// It was never deployed and RFC 6563 made it historic: a resolver had to /// chase a chain of records to assemble one address, and the chain could /// branch. `aaaa` won by being boring. pub const A6 = struct { /// How many leading bits of the address are somewhere else, 0 to 128. prefix_len: u8, /// The bits that are here, as a whole address with the borrowed leading /// bits left as zero. suffix: z46.Ipv6Address, /// Where the leading bits are, absent when there are none to fetch. prefix: ?Name, /// Reads the prefix length, refusing one over 128, then only the suffix /// bytes that length leaves, then the prefix name when the length is not /// zero. The name may not be compressed. pub fn parse(d: *Decoder) Error!A6 { const prefix_len = try d.int(u8); if (prefix_len > 128) return error.MalformedRdata; // Only the bytes the prefix does not cover are present, rounded up. const present = (@as(usize, 128 - prefix_len) + 7) / 8; const bytes = try d.take(@intCast(present)); var octets: [16]u8 = @splat(0); @memcpy(octets[16 - present ..], bytes); return .{ .prefix_len = prefix_len, .suffix = .{ .octets = octets }, .prefix = if (prefix_len == 0) null else try d.uncompressedName(), }; } test parse { // 64 bits here, so eight bytes of address, and the rest at the name. var d = try Decoder.init("\x40\x00\x00\x00\x00\x00\x00\x00\x01\x06prefix\x00"); const a6 = try A6.parse(&d); try std.testing.expectFmt("::1", "{f}", .{a6.suffix}); try std.testing.expectFmt("prefix.", "{f}", .{a6.prefix.?}); } /// Writes the prefix length, the suffix bytes that length leaves, and the /// prefix name, never compressed, when there is one. A length over 128 is /// written as given, with no address after it, which is a record `parse` /// refuses -- `Builder` checks no record's shape, so a test can make one. pub fn writeTo(self: A6, b: *Builder) Builder.Error!void { try b.int(u8, self.prefix_len); const present = (@as(usize, 128 -| self.prefix_len) + 7) / 8; try b.writeAll(self.suffix.octets[16 - present ..]); if (self.prefix) |name| try b.name(name, .uncompressed); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const suffix: [16]u8 = @as([15]u8, @splat(0)) ++ "\x01".*; const a6: A6 = .{ .prefix_len = 120, .suffix = .{ .octets = suffix }, .prefix = .literal("p") }; try a6.writeTo(&b); // A 120-bit prefix leaves one byte of address to send. try std.testing.expectEqualSlices(u8, "\x78\x01\x01p\x00", b.buffer[12..b.pos]); } test "a prefix length over 128 is written, not a crash" { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); const a6: A6 = .{ .prefix_len = 200, .suffix = .{ .octets = @splat(0) }, .prefix = .literal("p") }; try a6.writeTo(&b); try std.testing.expectEqualSlices(u8, "\xc8\x01p\x00", b.buffer[12..b.pos]); // And what it wrote is refused on the way back in. var d = try Decoder.init(b.buffer[12..b.pos]); try std.testing.expectError(error.MalformedRdata, A6.parse(&d)); } /// Prints the prefix length, the suffix as an IPv6 address, and the prefix /// name when there is one. pub fn format(self: A6, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.prefix_len, self.suffix }); if (self.prefix) |name| try w.print(" {f}", .{name}); } test format { const suffix: [16]u8 = @as([15]u8, @splat(0)) ++ "\x01".*; const a6: A6 = .{ .prefix_len = 64, .suffix = .{ .octets = suffix }, .prefix = .literal("prefix") }; try std.testing.expectFmt("64 ::1 prefix.", "{f}", .{a6}); } }; /// An address prefix list (RFC 3123): the networks a name is in, or is /// pointedly not in. pub const Apl = struct { /// The items exactly as they appeared. bytes: []const u8, pub const empty: Apl = .{ .bytes = "" }; /// One prefix, and whether it is being excluded rather than included. pub const Item = struct { /// 1 for IPv4 and 2 for IPv6; the IANA address family numbers. family: u16, prefix_len: u8, /// True when the item is a `!`: this prefix is *not* part of the set. negated: bool, /// The leading bytes of the address, with trailing zero bytes dropped /// -- which is why this can be shorter than the prefix needs. address: []const u8, /// The prefix as a network, with everything not sent left as zero, or /// `null` for an address family this does not know or an item too /// long for its family, which `parse` refuses but an item made by hand /// can be. pub fn network(self: Item) ?z46.Network { switch (self.family) { 1 => { if (self.prefix_len > 32 or self.address.len > 4) return null; var octets: [4]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv4 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.prefix_len), } }; }, 2 => { if (self.prefix_len > 128 or self.address.len > 16) return null; var octets: [16]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv6 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.prefix_len), } }; }, else => return null, } } test network { // 192.168.32.0/21, with its last zero byte left off as sent. const item: Item = .{ .family = 1, .prefix_len = 21, .negated = false, .address = "\xc0\xa8\x20" }; try std.testing.expectFmt("192.168.32.0/21", "{f}", .{item.network().?}); const other: Item = .{ .family = 9, .prefix_len = 8, .negated = false, .address = "\x01" }; try std.testing.expectEqual(@as(?z46.Network, null), other.network()); } /// Prints `family:network/length` as RFC 3123 §5 writes it, with a `!` /// in front when negated. A family this does not know has its address /// printed as hexadecimal. pub fn format(self: Item, w: *Writer) Writer.Error!void { if (self.negated) try w.writeByte('!'); try w.print("{d}:", .{self.family}); if (self.network()) |n| { try w.print("{f}", .{n}); } else { try presentation.writeHexLower(w, self.address); try w.print("/{d}", .{self.prefix_len}); } } }; /// Reads the rest of the record data as prefixes, checking that each one /// fits in what is left and has the shape RFC 3123 §4.1 gives it: an /// address with its trailing zero bytes left off, so never ending in one, /// and for IPv4 and IPv6 a prefix and an address no longer than the /// family has. Other families are carried as they came. pub fn parse(d: *Decoder) Error!Apl { const bytes = d.takeRest(); var i: usize = 0; while (i < bytes.len) { if (i + 4 > bytes.len) return error.MalformedRdata; const family = std.mem.readInt(u16, bytes[i..][0..2], .big); const prefix_len = bytes[i + 2]; const length = bytes[i + 3] & 0x7f; const start = i + 4; i = start + @as(usize, length); if (i > bytes.len) return error.MalformedRdata; if (length > 0 and bytes[i - 1] == 0) return error.MalformedRdata; const max_bytes: ?u8 = switch (family) { 1 => 4, 2 => 16, else => null, }; if (max_bytes) |max| { if (prefix_len > max * 8 or length > max) return error.MalformedRdata; } } return .{ .bytes = bytes }; } test parse { var d = try Decoder.init("\x00\x01\x15\x03\xc0\xa8\x20"); const apl = try Apl.parse(&d); try std.testing.expectEqual(@as(usize, 7), apl.bytes.len); // A trailing zero byte should have been left off. var bad = try Decoder.init("\x00\x01\x18\x03\xc0\xa8\x00"); try std.testing.expectError(error.MalformedRdata, Apl.parse(&bad)); } /// Walks the items in the order they were sent. pub const Iterator = struct { bytes: []const u8, pos: usize = 0, /// The next item, or `null` at the end of the list or at an item that /// runs past it. pub fn next(self: *Iterator) ?Item { if (self.pos + 4 > self.bytes.len) return null; const family = std.mem.readInt(u16, self.bytes[self.pos..][0..2], .big); const prefix_len = self.bytes[self.pos + 2]; const length_byte = self.bytes[self.pos + 3]; const start = self.pos + 4; const end = start + (length_byte & 0x7f); if (end > self.bytes.len) return null; self.pos = end; return .{ .family = family, .prefix_len = prefix_len, // The top bit of the length byte is the negation, which is the // one place in DNS where a length field carries a flag. .negated = length_byte & 0x80 != 0, .address = self.bytes[start..end], }; } test next { var it: Iterator = .{ .bytes = "\x00\x01\x15\x03\xc0\xa8\x20" ++ "\x00\x01\x1c\x83\xc0\xa8\x26" }; try std.testing.expect(!it.next().?.negated); // The top bit of the second length byte makes it an exclusion. try std.testing.expect(it.next().?.negated); try std.testing.expect(it.next() == null); } }; /// The items, from the first. pub fn iterator(self: Apl) Iterator { return .{ .bytes = self.bytes }; } test iterator { const apl: Apl = .{ .bytes = "\x00\x02\x20\x02\x20\x01" }; var it = apl.iterator(); try std.testing.expectFmt("2:2001::/32", "{f}", .{it.next().?}); } /// Writes the items exactly as they were held. pub fn writeTo(self: Apl, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try (Apl{ .bytes = "\x00\x01\x15\x03\xc0\xa8\x20" }).writeTo(&b); try std.testing.expectEqualSlices(u8, "\x00\x01\x15\x03\xc0\xa8\x20", b.buffer[12..b.pos]); } /// Prints the items separated by spaces, and an empty list as nothing. pub fn format(self: Apl, w: *Writer) Writer.Error!void { var it = self.iterator(); var first = true; while (it.next()) |item| { if (!first) try w.writeByte(' '); first = false; try w.print("{f}", .{item}); } } test format { const apl: Apl = .{ .bytes = "\x00\x01\x15\x03\xc0\xa8\x20" ++ "\x00\x01\x1c\x83\xc0\xa8\x26" }; try std.testing.expectFmt("1:192.168.32.0/21 !1:192.168.38.0/28", "{f}", .{apl}); try std.testing.expectFmt("", "{f}", .{Apl.empty}); } }; /// Where a host is, on the planet (RFC 1876). /// /// The one record type that is a unit system rather than a data structure. /// Latitude and longitude are thousandths of a second of arc, offset so that /// the equator and the prime meridian are 2^31 and everything fits in an /// unsigned integer. Altitude is centimeters above a datum 100 kilometers /// below the WGS 84 spheroid, for the same reason. The three precisions are /// each one byte holding a mantissa and a power of ten, which is how a /// kilometer and a centimeter fit in the same field. pub const Loc = struct { /// Always 0. RFC 1876 defines no other version and says to ignore a record /// with one, which is why this type refuses to guess at the rest. version: u8 = 0, /// The diameter of a sphere enclosing the thing being located. size: Precision = .{ .mantissa = 1, .exponent = 2 }, /// How far the position could be out horizontally. horizontal_precision: Precision = .{ .mantissa = 1, .exponent = 6 }, /// And vertically. vertical_precision: Precision = .{ .mantissa = 1, .exponent = 3 }, /// Thousandths of a second of arc, with 2^31 at the equator and larger /// values north of it. latitude: u32, /// Thousandths of a second of arc, with 2^31 at the prime meridian and /// larger values east of it. longitude: u32, /// Centimeters above a datum 100km below the WGS 84 spheroid. altitude: u32, /// A length as one byte: a mantissa of 0 to 9 in the top nibble and a /// power of ten in the bottom one, giving centimeters. It reaches from a /// centimeter to ninety thousand kilometers in eight bits, and can express /// almost none of the values in between. pub const Precision = struct { mantissa: u4, exponent: u4, /// Splits a byte into its two halves, without checking either; see /// `isValid`. pub fn fromByte(byte: u8) Precision { return .{ .mantissa = @intCast(byte >> 4), .exponent = @truncate(byte) }; } test fromByte { // 0x13 is 1 times ten to the third: ten meters. const p: Precision = .fromByte(0x13); try std.testing.expectEqual(@as(u4, 1), p.mantissa); try std.testing.expectEqual(@as(u4, 3), p.exponent); } /// Whether both halves are the decimal digits RFC 1876 §2 has them be, /// "each ranging from zero to nine". A nibble of ten or more is not a /// larger length; it is not a length. pub fn isValid(self: Precision) bool { return self.mantissa <= 9 and self.exponent <= 9; } test isValid { try std.testing.expect(Precision.fromByte(0x99).isValid()); try std.testing.expect(!Precision.fromByte(0xa3).isValid()); } /// The byte the two halves make, mantissa on top. pub fn toByte(self: Precision) u8 { return @as(u8, self.mantissa) << 4 | self.exponent; } test toByte { const p: Precision = .{ .mantissa = 3, .exponent = 2 }; try std.testing.expectEqual(@as(u8, 0x32), p.toByte()); } /// The length in centimeters. pub fn centimeters(self: Precision) u64 { var value: u64 = self.mantissa; var left = self.exponent; while (left > 0) : (left -= 1) value *= 10; return value; } test centimeters { try std.testing.expectEqual(@as(u64, 3000), Precision.fromByte(0x33).centimeters()); } /// Prints the length in meters with two decimal places, as a zone file /// writes it. pub fn format(self: Precision, w: *Writer) Writer.Error!void { const cm = self.centimeters(); try w.print("{d}.{d:0>2}m", .{ cm / 100, cm % 100 }); } }; /// Where the equator and the prime meridian sit, so that everything south /// and west of them is still a positive number. pub const center = 1 << 31; /// How far below the spheroid altitude is measured from, in centimeters. pub const altitude_datum = 10_000_000; /// Reads the fixed sixteen bytes, refusing a version other than 0 and a /// size or precision with a half that is not a decimal digit. A latitude, /// longitude or altitude is any 32-bit number, and is carried even when it /// is past a pole. pub fn parse(d: *Decoder) Error!Loc { const version = try d.int(u8); // RFC 1876 section 2: a version this does not know has an unknown // shape, and guessing at it would be inventing data. if (version != 0) return error.MalformedRdata; const out: Loc = .{ .version = version, .size = .fromByte(try d.int(u8)), .horizontal_precision = .fromByte(try d.int(u8)), .vertical_precision = .fromByte(try d.int(u8)), .latitude = try d.int(u32), .longitude = try d.int(u32), .altitude = try d.int(u32), }; // A latitude past a pole is carried, as a value that is a number but // not a place; a precision whose digits are not digits is not a // number at all. for ([_]Precision{ out.size, out.horizontal_precision, out.vertical_precision }) |p| { if (!p.isValid()) return error.MalformedRdata; } return out; } test parse { // The Ohio State University example from RFC 1876 section 4. var d = try Decoder.init("\x00\x33\x16\x13" ++ "\x89\x17\x2d\xd0" ++ "\x70\xbe\x15\xf0" ++ "\x00\x98\x8d\x20"); const loc = try Loc.parse(&d); try std.testing.expect(loc.latitude > Loc.center); // north try std.testing.expectEqual(@as(u64, 3000), loc.size.centimeters()); } /// Writes the sixteen bytes as the fields hold them. pub fn writeTo(self: Loc, b: *Builder) Builder.Error!void { try b.int(u8, self.version); try b.int(u8, self.size.toByte()); try b.int(u8, self.horizontal_precision.toByte()); try b.int(u8, self.vertical_precision.toByte()); try b.int(u32, self.latitude); try b.int(u32, self.longitude); try b.int(u32, self.altitude); } test writeTo { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); // At the equator, on the prime meridian, a hundred kilometers down. const loc: Loc = .{ .latitude = Loc.center, .longitude = Loc.center, .altitude = 0 }; try loc.writeTo(&b); try std.testing.expectEqualSlices( u8, "\x00\x12\x16\x13" ++ "\x80\x00\x00\x00" ++ "\x80\x00\x00\x00" ++ "\x00\x00\x00\x00", b.buffer[12..b.pos], ); } /// Degrees, minutes and seconds, and which side of the line. fn writeAngle(w: *Writer, value: u32, positive: u8, negative: u8) Writer.Error!void { const north_or_east = value >= center; const from_center: u32 = if (north_or_east) value - center else center - value; const seconds = from_center / 1000; try w.print("{d} {d} {d}.{d:0>3} {c}", .{ seconds / 3600, seconds / 60 % 60, seconds % 60, from_center % 1000, if (north_or_east) positive else negative, }); } /// Prints the RFC 1876 §3 form: latitude and longitude in degrees, minutes /// and seconds, then altitude, size and both precisions in meters. All /// three precisions are always written, even when they are the defaults. pub fn format(self: Loc, w: *Writer) Writer.Error!void { try writeAngle(w, self.latitude, 'N', 'S'); try w.writeByte(' '); try writeAngle(w, self.longitude, 'E', 'W'); // Signed, because the datum is a hundred kilometers down and anywhere // at sea level is below it. const centimeters = @as(i64, self.altitude) - altitude_datum; const meters = @divTrunc(centimeters, 100); const remainder: u64 = @abs(@rem(centimeters, 100)); try w.print(" {s}{d}.{d:0>2}m", .{ if (centimeters < 0 and meters == 0) "-" else "", meters, remainder, }); try w.print(" {f} {f} {f}", .{ self.size, self.horizontal_precision, self.vertical_precision, }); } test format { // The defaults, at sea level where the equator meets the meridian. const loc: Loc = .{ .latitude = Loc.center, .longitude = Loc.center, .altitude = Loc.altitude_datum }; try std.testing.expectFmt("0 0 0.000 N 0 0 0.000 E 0.00m 1.00m 10000.00m 10.00m", "{f}", .{loc}); } }; const testing = std.testing; fn expectParses(comptime T: type, bytes: []const u8, expected: []const u8) !T { var d = try Decoder.init(bytes); const value = try T.parse(&d); try testing.expect(d.atEnd()); try testing.expectFmt(expected, "{f}", .{value}); return value; } test "the RFC 1183 shapes" { var afsdb = try Decoder.init("\x00\x01\x03afs\x07example\x00"); try testing.expectFmt("1 afs.example.", "{f}", .{try PrefixedName.parse(&afsdb, .allowed)}); try testing.expect(afsdb.atEnd()); _ = try expectParses(X25, "\x0c311061700956", "\"311061700956\""); const isdn = try expectParses(Isdn, "\x0f150862028003217", "\"150862028003217\""); try testing.expectEqual(@as(?[]const u8, null), isdn.subaddress); _ = try expectParses(Isdn, "\x041234\x03004", "\"1234\" \"004\""); _ = try expectParses( Px, "\x00\x0a\x03foo\x00\x03bar\x00", "10 foo. bar.", ); } test "well known services" { // The example from RFC 1035 section 3.4.2, near enough: TCP with SMTP. const wks = try expectParses( Wks, "\xc0\x00\x02\x01\x06\x00\x00\x00\x40", "192.0.2.1 6 25", ); try testing.expect(wks.has(25)); try testing.expect(!wks.has(80)); } test "a location" { // The Ohio State University example from RFC 1876 section 4: // 42 21 54 N 71 06 18 W -24m 30m const bytes = "\x00" ++ "\x33" ++ "\x16" ++ "\x13" ++ "\x89\x17\x2d\xd0" ++ "\x70\xbe\x15\xf0" ++ "\x00\x98\x8d\x20"; const loc = try expectParses( Loc, bytes, "42 21 54.000 N 71 6 18.000 W -24.00m 30.00m 10000.00m 10.00m", ); try testing.expectEqual(@as(u64, 3000), loc.size.centimeters()); try testing.expectEqual(@as(u64, 1000000), loc.horizontal_precision.centimeters()); // And a version nobody has defined is not a location. var d = try Decoder.init("\x01" ++ bytes[1..]); try testing.expectError(error.MalformedRdata, Loc.parse(&d)); // Nor is a size, or either precision, with a half that is not a digit. for ([_]u8{ 1, 2, 3 }, [_]u8{ 0xa3, 0x1a, 0xf3 }) |at, byte| { var copy: [bytes.len]u8 = bytes.*; copy[at] = byte; var bad = try Decoder.init(©); try testing.expectError(error.MalformedRdata, Loc.parse(&bad)); } } test "X25 and ISDN addresses are the shape RFC 1183 gives them" { for ([_][]const u8{ "\x00", // an empty X25 address "\x0431a6", // a letter in one }) |bytes| { var d = try Decoder.init(bytes); try testing.expectError(error.MalformedRdata, X25.parse(&d)); } for ([_][]const u8{ "\x00", // an empty ISDN address "\x041\xc3\xa92", // a byte that is not IA5 "\x041234\x00", // a subaddress given but empty "\x041234\x0300g", // a subaddress that is not hexadecimal }) |bytes| { var d = try Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Isdn.parse(&d)); } } test "a position as three numbers written out" { // The example from RFC 1712 section 5, which is a latitude and longitude // the right way round despite the RFC's own text. _ = try expectParses( Gpos, "\x08-32.6882\x08116.8652\x0410.0", "\"-32.6882\" \"116.8652\" \"10.0\"", ); // A number out of range is still a number. _ = try expectParses(Gpos, "\x03200\x02+1\x02.5", "\"200\" \"+1\" \".5\""); for ([_][]const u8{ "\x00\x011\x011", // an empty longitude "\x01-\x011\x011", // a sign and nothing else "\x01.\x011\x011", // a point and nothing else "\x041.2.\x011\x011", // two points "\x011\x03abc\x011", // not a number at all "\x011\x011\x021m", // a unit after the altitude }) |bytes| { var d = try Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Gpos.parse(&d)); } } test "a prefix list, including one that is excluded" { const apl = try expectParses( Apl, "\x00\x01\x15\x03\xc0\xa8\x20" ++ "\x00\x01\x1c\x83\xc0\xa8\x26", "1:192.168.32.0/21 !1:192.168.38.0/28", ); var it = apl.iterator(); try testing.expect(!it.next().?.negated); try testing.expect(it.next().?.negated); for ([_][]const u8{ "\x00\x01\x15", // an item cut short "\x00\x01\x15\x04\xc0\xa8", // an address shorter than it claims "\x00\x01\x18\x03\xc0\xa8\x00", // a trailing zero that should be left off "\x00\x01\x21\x01\x0a", // a 33-bit IPv4 prefix "\x00\x01\x08\x05\x0a\x00\x00\x00\x01", // five bytes of IPv4 "\x00\x02\x81\x01\x20", // a 129-bit IPv6 prefix }) |bytes| { var d = try Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Apl.parse(&d)); } // A family nobody has defined is carried, whatever it holds. _ = try expectParses(Apl, "\x00\x09\xff\x05\x01\x02\x03\x04\x05", "9:0102030405/255"); } test "an address with a hole in it" { // 64 bits here, the rest at the name. const a6 = try expectParses( A6, "\x40\x00\x00\x00\x00\x00\x00\x00\x01\x06prefix\x00", "64 ::1 prefix.", ); try testing.expectEqual(@as(u8, 64), a6.prefix_len); // A whole address, with nothing borrowed and so no name. const whole = try expectParses( A6, "\x00\x20\x01\x0d\xb8" ++ @as([11]u8, @splat(0)) ++ "\x01", "0 2001:db8::1", ); try testing.expectEqual(@as(?Name, null), whole.prefix); var d = try Decoder.init("\x81\x00"); try testing.expectError(error.MalformedRdata, A6.parse(&d)); } test "the first attempt at denial" { const nxt = try expectParses( Nxt, "\x04next\x00" ++ "\x40\x01\x00\x02", "next. A MX NXT", ); try testing.expect(nxt.contains(.a)); try testing.expect(nxt.contains(.mx)); try testing.expect(!nxt.contains(.aaaa)); } test "an NXT bitmap longer than any type number" { // 8193 bytes is one byte past type 65535; its first bit is no type, and // printing it used to be a panic rather than nothing. const bitmap = @as([8192]u8, @splat(0)) ++ "\x80"; _ = try expectParses(Nxt, "\x00" ++ bitmap, "."); } test "the shapeless types keep their bytes" { _ = try expectParses(Opaque, "\x01\x02\x03", "\\# 3 010203"); _ = try expectParses(Nsap, "\x47\x00\x05\x80", "0x47000580"); }