// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Record data, from the text a zone file holds to the bytes a message //! carries. //! //! This is the half of the format that `dns` deliberately does not have: it //! writes the presentation form of everything and reads none of it back. The //! mapping is per field rather than per type -- a digest is hexadecimal, a key //! is base64, a hashed owner name is base32 with the extended hex alphabet, //! and a `txt` is a list of character-strings that may or may not be quoted -- //! so what follows is one function per shape and a table mapping types onto //! them. //! //! Three things worth knowing before reading it. //! //! **Everything is written as wire bytes.** Nothing here builds a //! `dns.rdata.Data`: the output is the record data exactly as it would appear //! in a message, which is what the rest of this library stores and what lets //! `dns` do the decoding, the printing and the comparing. The check that the //! two agree is that every record this encodes is decoded again by `dns` //! before it is handed back -- see `Parser.Options.validate`. //! //! **`\# length hex` works for every type**, known or not (RFC 3597 §5). A //! record written that way for a type this library does know is still decoded //! as that type, which is how a zone file can carry a record whose //! presentation syntax nobody has agreed on yet, and how the output of one //! name server is read by another. //! //! **A trailing field the wire lets be empty may be empty here too.** A //! `dnskey` with no key or a `ds` with no digest: both //! are shapes a message can carry, so all are shapes this can read -- because //! what this library can hold, it has to be able to write down and read back. //! `representable` is the other half of that promise: the handful of records //! that *cannot* be written down are refused rather than quietly changed. //! //! **A few types are refused.** `opt`, `tsig` and `tkey` are messages' //! business and have no place in a zone; `any`, `axfr`, `ixfr`, `maila` and //! `mailb` name questions, `nxname` is only ever a bit in an `nsec` type //! bitmap, and there is no such record. The generic syntax //! will not get them in either, because `dns` refuses to decode them. const std = @import("std"); const Allocator = std.mem.Allocator; const ascii = std.ascii; const dns = @import("dns"); const z46 = @import("z46"); const Diagnostics = @import("Diagnostics.zig"); const name = @import("name.zig"); pub const Error = error{ /// The data ran out before the type's fields did. MissingField, /// There was more data than the type has fields. TrailingField, /// A number that is not one, or one too large for its field. BadNumber, /// An address that is not one. BadAddress, /// A `\DDD` that is not three digits, or a backslash at the end -- or, /// inside a comma-separated service parameter value, a backslash in front /// of anything but a comma or another backslash. BadEscape, /// Text that is not base64, or not hexadecimal, or not base32. BadEncoding, /// A character-string longer than the 255 bytes its length byte can count. StringTooLong, /// A mnemonic -- a record type, an algorithm, a certificate type -- that /// this library has no number for. Every one of them can be written as a /// number instead. UnknownMnemonic, /// A date that is not `YYYYMMDDHHmmSS` and not a count of seconds. BadTimestamp, /// The data is longer than the 65535 bytes a record can hold. RdataTooLong, /// A `\#` whose length does not match the hexadecimal after it. BadGenericRdata, /// A service parameter that is not `key`, `key=value`, or a value of the /// shape that key requires. BadServiceParameter, /// A `loc` that is not degrees, minutes, seconds and a hemisphere. BadLocation, /// An address prefix list item that is not `[!]family:address/length`. BadAddressPrefix, /// A type bitmap holding a type that the encoding cannot express. BadTypeBitmap, /// A type that has no zone file syntax at all: the pseudo-records, the /// types that are only ever questions, and `nxname`, which is only ever a /// bit in a type bitmap. TypeNotInZones, } || name.Error || Allocator.Error; /// One token of the record data, as the lexer found it. pub const Field = struct { /// The text exactly as written, quotes removed and escapes still in place. text: []const u8, /// Whether it was written in double quotes. It matters for exactly one /// thing: `""` is an empty character-string, where an empty unquoted token /// cannot happen at all. quoted: bool = false, }; /// The fields of one record, read in order. pub const Fields = struct { items: []const Field, pos: usize = 0, /// The next field, or `null` once they are all used up. pub fn next(self: *Fields) ?Field { if (self.pos >= self.items.len) return null; defer self.pos += 1; return self.items[self.pos]; } /// The field `next` would return, without taking it. pub fn peek(self: Fields) ?Field { if (self.pos >= self.items.len) return null; return self.items[self.pos]; } /// Whether every field has been taken. pub fn atEnd(self: Fields) bool { return self.pos >= self.items.len; } /// How many fields are left to take. pub fn remaining(self: Fields) usize { return self.items.len - self.pos; } test next { var fields: Fields = .{ .items = &.{ .{ .text = "10" }, .{ .text = "mail" } } }; try testing.expectEqualStrings("10", fields.next().?.text); try testing.expectEqualStrings("mail", fields.next().?.text); try testing.expectEqual(null, fields.next()); } test peek { var fields: Fields = .{ .items = &.{.{ .text = "\\#" }} }; try testing.expectEqualStrings("\\#", fields.peek().?.text); try testing.expectEqual(@as(usize, 1), fields.remaining()); } test atEnd { var fields: Fields = .{ .items = &.{.{ .text = "192.0.2.1" }} }; try testing.expect(!fields.atEnd()); _ = fields.next(); try testing.expect(fields.atEnd()); } test remaining { var fields: Fields = .{ .items = &.{ .{ .text = "a" }, .{ .text = "b" }, .{ .text = "c" } } }; _ = fields.next(); try testing.expectEqual(@as(usize, 2), fields.remaining()); } }; /// Writes the wire form of one record's data onto the end of `out`. /// /// `fields` are the tokens after the type, as the lexer found them. A first /// field of `\#` reads the rest in the generic form of RFC 3597 §5, for any /// type at all. `origin` is the current `$ORIGIN`, for the relative names a /// zone file is full of, or `null` when every name in the data must be /// absolute. `scratch` is working space whose contents are not kept, and /// `diagnostics`, when given, says what was wrong with a field that fails. /// /// The data is not decoded again here; `Parser` does that, and is the place /// to start for anything short of writing a parser of its own. pub fn encode( gpa: Allocator, out: *std.ArrayList(u8), scratch: *std.ArrayList(u8), record_type: dns.Type, fields: []const Field, origin: ?dns.Name, diagnostics: ?*Diagnostics, ) Error!void { var e: Encoder = .{ .gpa = gpa, .out = out, .scratch = scratch, .fields = .{ .items = fields }, .origin = origin, .diagnostics = diagnostics, }; const start = out.items.len; if (e.fields.peek()) |first| { // RFC 3597 §5. Checked before the type is looked at, because it is // legal for every type and is how a record nobody has a parser for // gets written down. if (!first.quoted and std.mem.eql(u8, first.text, "\\#")) { _ = e.fields.next(); try e.generic(); return e.finish(start); } } if (record_type.isRecordless()) { e.note("{f} is a type with no record data, and there is no such record", .{record_type}); return error.TypeNotInZones; } try e.byType(record_type); return e.finish(start); } /// Whether a record's data can be written in presentation form and read back /// as the same record. /// /// Almost everything can. What cannot is a record with an **empty field in the /// middle of one**: the presentation form of such a field is nothing at all, /// so it disappears and the field after it moves up into its place. The wire /// format has a length in front of each of them and does not care; the text /// has only whitespace, and cannot say "nothing here". /// /// Every one of these is a record no generator produces and no specification /// allows -- a `hip` with no host identity tag or no public key -- and each is /// reachable only through the `\#` syntax, which is how they turn up here. `Parser` refuses them, so /// that a zone this library reads is a zone it can write. /// /// The list came from the fuzzer and may not be complete, which is why the /// fuzzer keeps running. pub fn representable(data: dns.rdata.Data) ?[]const u8 { switch (data) { .hip => |value| { if (value.hit.len == 0) return "a hip with no host identity tag"; if (value.public_key.len == 0) return "a hip with no public key"; }, else => {}, } return null; } const Encoder = struct { gpa: Allocator, out: *std.ArrayList(u8), /// Somewhere to put bytes that are needed all at once -- the pieces of a /// base64 value split across lines, say. Whatever was in it before is /// gone: every use starts by clearing it. scratch: *std.ArrayList(u8), fields: Fields, origin: ?dns.Name, diagnostics: ?*Diagnostics, fn note(self: *Encoder, comptime fmt: []const u8, args: anytype) void { if (self.diagnostics) |d| d.note(fmt, args); } fn finish(self: *Encoder, start: usize) Error!void { if (!self.fields.atEnd()) { self.note("{d} more field(s) than this type has", .{self.fields.remaining()}); return error.TrailingField; } if (self.out.items.len - start > std.math.maxInt(u16)) return error.RdataTooLong; } fn need(self: *Encoder, what: []const u8) Error!Field { return self.fields.next() orelse { self.note("missing the {s}", .{what}); return error.MissingField; }; } // -- the pieces a record is made of -------------------------------------- fn append(self: *Encoder, bytes: []const u8) Error!void { try self.out.appendSlice(self.gpa, bytes); } fn appendInt(self: *Encoder, comptime T: type, value: T) Error!void { var buf: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined; std.mem.writeInt(T, &buf, value, .big); try self.append(&buf); } fn number(self: *Encoder, comptime T: type, what: []const u8) Error!T { const field = try self.need(what); return parseInt(T, field.text) catch { self.note("the {s} is not a number that fits: \"{s}\"", .{ what, field.text }); return error.BadNumber; }; } /// An unsigned field written as a decimal number. fn int(self: *Encoder, comptime T: type, what: []const u8) Error!void { try self.appendInt(T, try self.number(T, what)); } /// A time to live, which may be written with units: `1h30m`, `2w`. fn ttl(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const value = parseTtl(field.text) catch { self.note("the {s} is not a time: \"{s}\"", .{ what, field.text }); return error.BadNumber; }; try self.appendInt(u32, value); } fn ipv4(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const address = z46.Ipv4Address.parse(field.text) catch { self.note("the {s} is not an IPv4 address: \"{s}\"", .{ what, field.text }); return error.BadAddress; }; try self.append(&address.octets); } fn ipv6(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const address = z46.Ipv6Address.parse(field.text) catch { self.note("the {s} is not an IPv6 address: \"{s}\"", .{ what, field.text }); return error.BadAddress; }; try self.append(&address.octets); } /// A domain name. Never compressed: RFC 3597 §4 forbids compressing a name /// inside any type defined after RFC 1035, and a record held on its own /// has nothing to point back at in any case. fn domainName(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); var buf: dns.Name.Buffer = undefined; const encoded = name.encode(&buf, field.text, self.origin) catch |err| { self.note("the {s} is not a domain name ({s}): \"{s}\"", .{ what, @errorName(err), field.text, }); return err; }; try self.append(encoded.message); } /// Undoes the escapes of RFC 1035 §5.1, appending the bytes they stand /// for, and answers how many there were. fn unescapeOnto(self: *Encoder, text: []const u8) Error!usize { var count: usize = 0; var i: usize = 0; while (i < text.len) { var c = text[i]; i += 1; if (c == '\\') { if (i >= text.len) return error.BadEscape; if (ascii.isDigit(text[i])) { if (i + 3 > text.len) return error.BadEscape; var value: u16 = 0; for (text[i..][0..3]) |digit| { if (!ascii.isDigit(digit)) return error.BadEscape; value = value * 10 + (digit - '0'); } if (value > 255) return error.BadEscape; c = @intCast(value); i += 3; } else { c = text[i]; i += 1; } } try self.out.append(self.gpa, c); count += 1; } return count; } /// A character-string: a length byte and up to 255 bytes after it. fn characterString(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const length_at = self.out.items.len; try self.out.append(self.gpa, 0); const written = self.unescapeOnto(field.text) catch |err| { self.note("the {s} has a bad escape in it: \"{s}\"", .{ what, field.text }); return err; }; if (written > 255) { self.note("the {s} is {d} bytes, and a character-string holds 255", .{ what, written, }); return error.StringTooLong; } self.out.items[length_at] = @intCast(written); } /// Every remaining field as a character-string, which is what `txt` and /// the types shaped like it are. RFC 1035 §3.3.14 asks for one or more: /// `""` is one empty string, and nothing at all is not a `txt`. fn characterStrings(self: *Encoder) Error!void { try self.characterString("text"); while (!self.fields.atEnd()) try self.characterString("text"); } /// Everything left, with its escapes undone and no length in front of it. /// `caa` and `uri` both end in one, which is how they carry a value longer /// than 255 bytes. fn textRest(self: *Encoder, what: []const u8) Error!void { if (self.fields.atEnd()) { self.note("missing the {s}", .{what}); return error.MissingField; } var first = true; while (self.fields.next()) |field| { // Written across several tokens only when it was written with // spaces in it and no quotes, which is legal and rare. if (!first) try self.out.append(self.gpa, ' '); first = false; _ = self.unescapeOnto(field.text) catch |err| { self.note("the {s} has a bad escape in it", .{what}); return err; }; } } /// The remaining fields joined end to end, which is what a base64 value /// split across lines by parentheses needs before it can be decoded. fn joinRest(self: *Encoder) Error![]const u8 { self.scratch.clearRetainingCapacity(); while (self.fields.next()) |field| { try self.scratch.appendSlice(self.gpa, field.text); } return self.scratch.items; } fn appendBase64(self: *Encoder, text: []const u8) Error!void { const decoder = std.base64.standard.Decoder; const size = decoder.calcSizeForSlice(text) catch { self.note("not base64: \"{s}\"", .{text}); return error.BadEncoding; }; const at = self.out.items.len; try self.out.resize(self.gpa, at + size); decoder.decode(self.out.items[at..], text) catch { self.note("not base64: \"{s}\"", .{text}); return error.BadEncoding; }; } /// Everything left, as base64. Empty is allowed, because a `ipseckey` with /// no algorithm carries no key. fn base64Rest(self: *Encoder, required: bool) Error!void { const joined = try self.joinRest(); if (joined.len == 0) { if (!required) return; self.note("missing the base64 value", .{}); return error.MissingField; } try self.appendBase64(joined); } fn appendHex(self: *Encoder, text: []const u8) Error!void { if (text.len % 2 != 0) { self.note("hexadecimal with an odd number of digits: \"{s}\"", .{text}); return error.BadEncoding; } const at = self.out.items.len; try self.out.resize(self.gpa, at + text.len / 2); _ = std.fmt.hexToBytes(self.out.items[at..], text) catch { self.note("not hexadecimal: \"{s}\"", .{text}); return error.BadEncoding; }; } /// Everything left, as hexadecimal. fn hexRest(self: *Encoder, required: bool) Error!void { const joined = try self.joinRest(); if (joined.len == 0) { if (!required) return; self.note("missing the hexadecimal value", .{}); return error.MissingField; } try self.appendHex(joined); } /// One field of hexadecimal, for the types that have something after it. fn hexField(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); try self.appendHex(field.text); } /// A salt, which is hexadecimal or a lone `-` for no salt at all. fn salt(self: *Encoder) Error!void { const field = try self.need("salt"); const length_at = self.out.items.len; try self.out.append(self.gpa, 0); if (!std.mem.eql(u8, field.text, "-")) { try self.appendHex(field.text); const written = self.out.items.len - length_at - 1; if (written > 255) return error.StringTooLong; self.out.items[length_at] = @intCast(written); } } /// Unpadded base32 over the extended hex alphabet: the next hashed owner /// name of an `nsec3`, and nothing else. fn base32hex(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const length_at = self.out.items.len; try self.out.append(self.gpa, 0); var accumulator: u16 = 0; var bits: u4 = 0; for (field.text) |c| { const value = base32hexValue(c) orelse { self.note("the {s} is not base32: \"{s}\"", .{ what, field.text }); return error.BadEncoding; }; accumulator = accumulator << 5 | value; bits += 5; if (bits >= 8) { bits -= 8; try self.out.append(self.gpa, @truncate(accumulator >> bits)); } } // What is left over is the zero padding of the last character, and a // bit set in it means the text was not an encoding of whole bytes. if (accumulator & (@as(u16, 1) << bits) -| 1 != 0) { self.note("the {s} does not encode whole bytes", .{what}); return error.BadEncoding; } const written = self.out.items.len - length_at - 1; if (written > 255) return error.StringTooLong; self.out.items[length_at] = @intCast(written); } /// A record type by mnemonic or by `TYPE1234`. fn typeField(self: *Encoder, what: []const u8) Error!dns.Type { const field = try self.need(what); return dns.Type.fromName(field.text) orelse { self.note("no record type is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; } /// A DNSSEC algorithm, by number or by the mnemonic BIND accepts. fn algorithm(self: *Encoder) Error!void { const field = try self.need("algorithm"); if (parseInt(u8, field.text)) |value| { return self.appendInt(u8, value); } else |_| {} const value = algorithmNumber(field.text) orelse { self.note("no DNSSEC algorithm is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; try self.appendInt(u8, value); } /// The list of types an `nsec`, an `nsec3` or a `csync` claims, as the /// windowed bitmap of RFC 4034 §4.1.2. fn typeBitmap(self: *Encoder) Error!void { // One bit per type number: eight kilobytes, which is why it is built // in the scratch buffer and not on the stack. self.scratch.clearRetainingCapacity(); try self.scratch.appendNTimes(self.gpa, 0, 8192); const bits = self.scratch.items; var any = false; while (self.fields.next()) |field| { const t = dns.Type.fromName(field.text) orelse { self.note("no record type is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; const value = @backingInt(t); bits[value / 8] |= @as(u8, 0x80) >> @truncate(value % 8); any = true; } if (!any) return; // A bitmap claiming nothing is legal and is empty. var window: usize = 0; while (window < 256) : (window += 1) { const bytes = bits[window * 32 ..][0..32]; var length: usize = 0; for (bytes, 0..) |b, i| if (b != 0) { length = i + 1; }; if (length == 0) continue; try self.out.append(self.gpa, @intCast(window)); try self.out.append(self.gpa, @intCast(length)); try self.append(bytes[0..length]); } } /// The flat bit vector of RFC 2535's `nxt`, which has a bit for type zero /// and no way to say anything about a type above 127 without eight /// kilobytes of zeros. That is the defect `nsec` was invented to fix. fn flatBitmap(self: *Encoder) Error!void { var bits: [16]u8 = @splat(0); var length: usize = 0; while (self.fields.next()) |field| { const t = dns.Type.fromName(field.text) orelse { self.note("no record type is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; const value = @backingInt(t); if (value > 127) { self.note("an nxt bitmap cannot hold {f}, which is type {d}", .{ t, value }); return error.BadTypeBitmap; } bits[value / 8] |= @as(u8, 0x80) >> @truncate(value % 8); length = @max(length, value / 8 + 1); } try self.append(bits[0..length]); } /// The `\# length hex...` of RFC 3597 §5. fn generic(self: *Encoder) Error!void { const length = try self.number(u16, "length"); const at = self.out.items.len; try self.hexRest(length != 0); const written = self.out.items.len - at; if (written != length) { self.note("\\# says {d} bytes and {d} follow", .{ length, written }); return error.BadGenericRdata; } } // -- the types ----------------------------------------------------------- fn byType(self: *Encoder, t: dns.Type) Error!void { switch (t) { .a => try self.ipv4("address"), .aaaa => try self.ipv6("address"), .ns, .md, .mf, .cname, .mb, .mg, .mr, .ptr, .dname, .@"nsap-ptr", => try self.domainName("name"), .soa => { try self.domainName("primary server"); try self.domainName("responsible mailbox"); try self.int(u32, "serial"); try self.ttl("refresh time"); try self.ttl("retry time"); try self.ttl("expire time"); try self.ttl("negative caching time"); }, .minfo, .rp => { try self.domainName("first name"); try self.domainName("second name"); }, .mx => { try self.int(u16, "preference"); try self.domainName("exchange"); }, .afsdb, .rt, .kx, .lp => { try self.int(u16, "preference"); try self.domainName("name"); }, .txt, .spf, .ninfo, .avc, .resinfo, .wallet => try self.characterStrings(), .hinfo => { try self.characterString("cpu"); try self.characterString("operating system"); }, .srv => { try self.int(u16, "priority"); try self.int(u16, "weight"); try self.int(u16, "port"); try self.domainName("target"); }, .naptr => { try self.int(u16, "order"); try self.int(u16, "preference"); try self.characterString("flags"); try self.characterString("services"); try self.characterString("regular expression"); try self.domainName("replacement"); }, .caa => { try self.int(u8, "flags"); try self.caaTag(); try self.textRest("value"); }, .uri => { try self.int(u16, "priority"); try self.int(u16, "weight"); try self.textRest("target"); }, .x25 => try self.characterString("PSDN address"), .isdn => { try self.characterString("ISDN address"); // The subaddress is optional, and there is nothing after it, // so its absence is simply the end of the record. if (!self.fields.atEnd()) try self.characterString("subaddress"); }, .gpos => { try self.characterString("longitude"); try self.characterString("latitude"); try self.characterString("altitude"); }, .nsap => try self.nsap(), .px => { try self.int(u16, "preference"); try self.domainName("RFC 822 name"); try self.domainName("X.400 name"); }, .wks => try self.wks(), .loc => try self.loc(), .apl => try self.apl(), .a6 => try self.a6(), .nxt => { try self.domainName("next name"); try self.flatBitmap(); }, .dhcid, .openpgpkey => try self.base64Rest(false), .cert => { try self.certificateType(); try self.int(u16, "key tag"); try self.algorithm(); try self.base64Rest(false); }, .ipseckey => try self.ipseckey(), .amtrelay => try self.amtrelay(), .hip => try self.hip(), .nid, .l64 => { try self.int(u16, "preference"); try self.locator64(); }, .l32 => { try self.int(u16, "preference"); try self.ipv4("locator"); }, .eui48 => try self.eui(6), .eui64 => try self.eui(8), .dsync => { const covered = try self.typeField("type"); try self.appendInt(u16, @backingInt(covered)); try self.int(u8, "scheme"); try self.int(u16, "port"); try self.domainName("target"); }, .sshfp => { try self.int(u8, "algorithm"); try self.int(u8, "fingerprint type"); try self.hexRest(false); }, .tlsa, .smimea => { try self.int(u8, "usage"); try self.int(u8, "selector"); try self.int(u8, "matching type"); try self.hexRest(false); }, .ds, .cds, .dlv, .ta => { try self.int(u16, "key tag"); try self.algorithm(); try self.int(u8, "digest type"); try self.hexRest(false); }, .dnskey, .cdnskey, .key => { try self.int(u16, "flags"); try self.int(u8, "protocol"); try self.algorithm(); try self.base64Rest(false); }, .rrsig, .sig => { const covered = try self.typeField("type covered"); try self.appendInt(u16, @backingInt(covered)); try self.algorithm(); try self.int(u8, "label count"); try self.ttl("original time to live"); try self.timestamp("expiration"); try self.timestamp("inception"); try self.int(u16, "key tag"); try self.domainName("signer"); try self.base64Rest(false); }, .nsec => { try self.domainName("next name"); try self.typeBitmap(); }, .nsec3param => { try self.int(u8, "hash algorithm"); try self.int(u8, "flags"); try self.int(u16, "iterations"); try self.salt(); }, .nsec3 => { try self.int(u8, "hash algorithm"); try self.int(u8, "flags"); try self.int(u16, "iterations"); try self.salt(); try self.base32hex("next hashed owner name"); try self.typeBitmap(); }, .csync => { try self.int(u32, "serial"); try self.int(u16, "flags"); try self.typeBitmap(); }, .zonemd => { try self.int(u32, "serial"); try self.int(u8, "scheme"); try self.int(u8, "hash algorithm"); try self.hexRest(false); }, .svcb, .https => { try self.int(u16, "priority"); try self.domainName("target"); try self.serviceParameters(); }, // A `null` holds anything at all and has no syntax for it, and // `unspec` never had one either; RFC 3597's `\#` is the only way // to write one down. The pseudo-records belong to a message rather // than to a zone. .null, .unspec, .opt, .tsig, .tkey => { self.note("{f} has no zone file syntax; write it as \\# length hex", .{t}); return error.TypeNotInZones; }, // Everything else is a type this library has no parser for, and // the generic syntax was its only way in -- which was checked // before we got here. else => { self.note( "{f} is not a type this library knows; write it as \\# length hex", .{t}, ); return error.UnknownMnemonic; }, } } /// The property tag of a `caa`, which RFC 8659 §4.1 says is one to fifteen /// letters and digits and nothing else. /// /// It is checked rather than carried through, because it is the one field /// in this library whose presentation form is written without quotes or /// escapes -- a tag holding a space would be read back as a tag and the /// beginning of the value, and a record that changes when it is written /// out is worse than one that is refused. The fuzzer found this; the /// value after it needs no such rule, because that one is quoted. fn caaTag(self: *Encoder) Error!void { const field = try self.need("tag"); if (field.text.len == 0 or field.text.len > 15) { self.note("a caa tag is 1 to 15 letters and digits", .{}); return error.BadServiceParameter; } for (field.text) |c| { if (!ascii.isAlphanumeric(c)) { self.note("a caa tag is letters and digits: \"{s}\"", .{field.text}); return error.BadServiceParameter; } } try self.out.append(self.gpa, @intCast(field.text.len)); try self.append(field.text); } /// RFC 1706: an NSAP is written `0x` and then hexadecimal, in which dots /// may appear anywhere as thousands separators do. fn nsap(self: *Encoder) Error!void { const field = try self.need("NSAP address"); if (field.text.len < 2 or !ascii.eqlIgnoreCase(field.text[0..2], "0x")) { self.note("an NSAP address begins with 0x: \"{s}\"", .{field.text}); return error.BadEncoding; } self.scratch.clearRetainingCapacity(); for (field.text[2..]) |c| { if (c == '.') continue; try self.scratch.append(self.gpa, c); } try self.appendHex(self.scratch.items); } /// RFC 1035 §3.4.2: an address, a protocol, and the services it offers, /// each named or numbered. fn wks(self: *Encoder) Error!void { try self.ipv4("address"); const protocol_field = try self.need("protocol"); const protocol = parseInt(u8, protocol_field.text) catch protocolNumber(protocol_field.text) orelse { self.note("no IP protocol is called \"{s}\"", .{protocol_field.text}); return error.UnknownMnemonic; }; try self.appendInt(u8, protocol); // One bit per port, most significant bit of the first byte being port // zero. 8192 bytes would cover every port; only as many as the highest // one needs are written. self.scratch.clearRetainingCapacity(); try self.scratch.appendNTimes(self.gpa, 0, 8192); var length: usize = 0; while (self.fields.next()) |field| { const port = parseInt(u16, field.text) catch serviceNumber(field.text, protocol) orelse { self.note("no service is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; self.scratch.items[port / 8] |= @as(u8, 0x80) >> @truncate(port % 8); length = @max(length, @as(usize, port) / 8 + 1); } try self.append(self.scratch.items[0..length]); } /// RFC 1876: degrees, minutes, seconds and a hemisphere, twice, then an /// altitude and up to three precisions, each in meters. fn loc(self: *Encoder) Error!void { const latitude = try self.angle('N', 'S', 90); const longitude = try self.angle('E', 'W', 180); const altitude_field = try self.need("altitude"); const centimeters = parseMeters(altitude_field.text) catch { self.note("the altitude is not a distance: \"{s}\"", .{altitude_field.text}); return error.BadLocation; }; const altitude = centimeters + dns.rdata.Loc.altitude_datum; if (altitude < 0 or altitude > std.math.maxInt(u32)) { self.note("the altitude is outside what a loc can hold", .{}); return error.BadLocation; } // The defaults of RFC 1876: a one metre sphere, ten kilometers of // horizontal doubt and ten meters of vertical. var precision: [3]u8 = .{ 0x12, 0x16, 0x13 }; for (&precision) |*p| { const field = self.fields.next() orelse break; const value = parseMeters(field.text) catch { self.note("the precision is not a distance: \"{s}\"", .{field.text}); return error.BadLocation; }; if (value < 0) { self.note("a precision cannot be negative: \"{s}\"", .{field.text}); return error.BadLocation; } p.* = precisionByte(@intCast(value)); } try self.appendInt(u8, 0); // the version, of which there is one try self.append(&precision); try self.appendInt(u32, latitude); try self.appendInt(u32, longitude); try self.appendInt(u32, @intCast(altitude)); } /// Degrees, then optionally minutes, then optionally seconds, then the /// hemisphere -- which is what says the angle has ended. fn angle(self: *Encoder, positive: u8, negative: u8, limit: u32) Error!u32 { var thousandths: u64 = 0; var part: u8 = 0; while (true) : (part += 1) { const field = try self.need("latitude or longitude"); if (field.text.len == 1) { const c = ascii.toUpper(field.text[0]); if (c == positive or c == negative) { if (part == 0) { self.note("a hemisphere with no angle in front of it", .{}); return error.BadLocation; } if (thousandths > @as(u64, limit) * 3600 * 1000) { self.note("{d} degrees is outside the hemisphere", .{limit}); return error.BadLocation; } const center = @as(i64, dns.rdata.Loc.center); const signed = if (c == positive) center + @as(i64, @intCast(thousandths)) else center - @as(i64, @intCast(thousandths)); return @intCast(signed); } } if (part == 3) { self.note("expected {c} or {c} after the seconds", .{ positive, negative }); return error.BadLocation; } // Degrees and minutes are whole; only the seconds have a fraction, // and it goes down to a thousandth. const scale: u64 = switch (part) { 0 => 3600 * 1000, 1 => 60 * 1000, else => 1000, }; const value = parseFixed(field.text, if (part == 2) 1000 else 1) catch { self.note("not an angle: \"{s}\"", .{field.text}); return error.BadLocation; }; if (value < 0) { self.note("an angle is written with a hemisphere, not a sign", .{}); return error.BadLocation; } thousandths += @as(u64, @intCast(value)) * (if (part == 2) 1 else scale); if (thousandths > std.math.maxInt(u32)) { self.note("the angle is far larger than the planet", .{}); return error.BadLocation; } } } /// RFC 3123: `[!]family:address/prefix`, and the address is written the /// way that family writes one. fn apl(self: *Encoder) Error!void { while (self.fields.next()) |field| { var text = field.text; var negated = false; if (text.len > 0 and text[0] == '!') { negated = true; text = text[1..]; } const colon = std.mem.indexOfScalar(u8, text, ':') orelse { self.note("an address prefix is family:address/length: \"{s}\"", .{field.text}); return error.BadAddressPrefix; }; const slash = std.mem.lastIndexOfScalar(u8, text, '/') orelse { self.note("an address prefix needs a /length: \"{s}\"", .{field.text}); return error.BadAddressPrefix; }; if (slash < colon) return error.BadAddressPrefix; const family = parseInt(u16, text[0..colon]) catch { self.note("not an address family: \"{s}\"", .{text[0..colon]}); return error.BadAddressPrefix; }; const address_text = text[colon + 1 .. slash]; const prefix_len = parseInt(u8, text[slash + 1 ..]) catch { self.note("not a prefix length: \"{s}\"", .{text[slash + 1 ..]}); return error.BadAddressPrefix; }; // RFC 3123 gives a presentation form to IPv4 and IPv6 and to // nothing else, and the wire carries any family. Anything else is // the address in hexadecimal, which is how `dns` writes one and // how dnspython reads it -- without it, a record read through `\#` // could be written and not read back. if (family != 1 and family != 2) { const item_at = self.out.items.len; try self.appendInt(u16, family); try self.appendInt(u8, prefix_len); try self.appendInt(u8, 0); const address_at = self.out.items.len; try self.appendHex(address_text); var length = self.out.items.len - address_at; while (length > 0 and self.out.items[address_at + length - 1] == 0) length -= 1; if (length > 127) { self.note("an address prefix holds at most 127 bytes", .{}); return error.BadAddressPrefix; } self.out.shrinkRetainingCapacity(address_at + length); self.out.items[item_at + 3] = @as(u8, @intFromBool(negated)) << 7 | @as(u8, @intCast(length)); continue; } var octets: [16]u8 = @splat(0); const width: usize = switch (family) { 1 => blk: { const address = z46.Ipv4Address.parse(address_text) catch { self.note("not an IPv4 address: \"{s}\"", .{address_text}); return error.BadAddressPrefix; }; @memcpy(octets[0..4], &address.octets); break :blk 4; }, 2 => blk: { const address = z46.Ipv6Address.parse(address_text) catch { self.note("not an IPv6 address: \"{s}\"", .{address_text}); return error.BadAddressPrefix; }; @memcpy(&octets, &address.octets); break :blk 16; }, else => unreachable, }; if (prefix_len > width * 8) { self.note("a /{d} is longer than the address", .{prefix_len}); return error.BadAddressPrefix; } // Only the bytes the prefix covers are sent, and the trailing // zeros among those are dropped as well, which is what makes an // apl item shorter than the address it names. var length: usize = (@as(usize, prefix_len) + 7) / 8; if (prefix_len % 8 != 0) { const drop: u3 = @intCast(8 - prefix_len % 8); octets[length - 1] &= @as(u8, 0xff) << drop; } while (length > 0 and octets[length - 1] == 0) length -= 1; try self.appendInt(u16, family); try self.appendInt(u8, prefix_len); try self.appendInt(u8, @as(u8, @intFromBool(negated)) << 7 | @as(u8, @intCast(length))); try self.append(octets[0..length]); } } /// RFC 2874: how many leading bits are somewhere else, the bits that are /// here, and where the rest of them are. fn a6(self: *Encoder) Error!void { const prefix_len = try self.number(u8, "prefix length"); if (prefix_len > 128) { self.note("a prefix length is 0 to 128, not {d}", .{prefix_len}); return error.BadNumber; } try self.appendInt(u8, prefix_len); if (prefix_len < 128) { const field = try self.need("address suffix"); const address = z46.Ipv6Address.parse(field.text) catch { self.note("not an IPv6 address: \"{s}\"", .{field.text}); return error.BadAddress; }; const present = (@as(usize, 128 - prefix_len) + 7) / 8; try self.append(address.octets[16 - present ..]); } if (prefix_len > 0) try self.domainName("prefix name"); } fn certificateType(self: *Encoder) Error!void { const field = try self.need("certificate type"); if (parseInt(u16, field.text)) |value| { return self.appendInt(u16, value); } else |_| {} const value = certificateTypeNumber(field.text) orelse { self.note("no certificate type is called \"{s}\"", .{field.text}); return error.UnknownMnemonic; }; try self.appendInt(u16, value); } /// The gateway of an `ipseckey` or the relay of an `amtrelay`: nothing, an /// address of either family, or a name, with a number beside it saying /// which. The number comes first in the text and first on the wire, but /// not in the same place, so it is read here and written by the caller. fn gateway(self: *Encoder, kind: u8) Error!void { switch (kind) { 0 => { // Written as `.`, which is also how a gateway that really is // the root would be written -- a collision RFC 4025 lives // with. The type byte is what decides. const field = try self.need("gateway"); if (!std.mem.eql(u8, field.text, ".")) { self.note("gateway type 0 is written as a lone dot", .{}); return error.BadServiceParameter; } }, 1 => try self.ipv4("gateway"), 2 => try self.ipv6("gateway"), 3 => try self.domainName("gateway"), else => { self.note("gateway type {d} is not one of 0, 1, 2 or 3", .{kind}); return error.BadNumber; }, } } fn ipseckey(self: *Encoder) Error!void { const precedence = try self.number(u8, "precedence"); const kind = try self.number(u8, "gateway type"); const algorithm_number = try self.number(u8, "algorithm"); try self.appendInt(u8, precedence); try self.appendInt(u8, kind); try self.appendInt(u8, algorithm_number); try self.gateway(kind); // No algorithm means no key, and a record saying only where the // gateway is, is a thing RFC 4025 allows. try self.base64Rest(algorithm_number != 0); } fn amtrelay(self: *Encoder) Error!void { const precedence = try self.number(u8, "precedence"); const discovery = try self.number(u8, "discovery optional flag"); const kind = try self.number(u8, "relay type"); if (discovery > 1) { self.note("the discovery flag is 0 or 1, not {d}", .{discovery}); return error.BadNumber; } if (kind > 0x7f) { self.note("the relay type is 0 to 3, not {d}", .{kind}); return error.BadNumber; } try self.appendInt(u8, precedence); try self.appendInt(u8, @as(u8, @intCast(discovery)) << 7 | kind); try self.gateway(kind); } /// RFC 8005: the tag, the key, and the rendezvous servers. The two lengths /// go in front of data that has not been read yet, so they are written as /// zeros and filled in once it has. fn hip(self: *Encoder) Error!void { const algorithm_number = try self.number(u8, "algorithm"); const header = self.out.items.len; try self.append(&.{ 0, algorithm_number, 0, 0 }); try self.hexField("host identity tag"); const hit_len = self.out.items.len - header - 4; if (hit_len > std.math.maxInt(u8)) return error.RdataTooLong; self.out.items[header] = @intCast(hit_len); const key_field = try self.need("public key"); try self.appendBase64(key_field.text); const key_len = self.out.items.len - header - 4 - hit_len; if (key_len > std.math.maxInt(u16)) return error.RdataTooLong; std.mem.writeInt(u16, self.out.items[header + 2 ..][0..2], @intCast(key_len), .big); while (!self.fields.atEnd()) try self.domainName("rendezvous server"); } /// Sixty-four bits as four colon-separated groups of four hexadecimal /// digits, which is how ILNP writes the half of an IPv6 address it is /// talking about. fn locator64(self: *Encoder) Error!void { const field = try self.need("locator"); var groups = std.mem.splitScalar(u8, field.text, ':'); var count: usize = 0; while (groups.next()) |group| { if (count == 4) { self.note("a 64-bit locator has four groups: \"{s}\"", .{field.text}); return error.BadNumber; } const value = parseHex(u16, group) catch { self.note("not four hexadecimal digits: \"{s}\"", .{group}); return error.BadNumber; }; try self.appendInt(u16, value); count += 1; } if (count != 4) { self.note("a 64-bit locator has four groups: \"{s}\"", .{field.text}); return error.BadNumber; } } /// A MAC address, which is written with dashes rather than the colons an /// IPv6 address uses. fn eui(self: *Encoder, length: usize) Error!void { const field = try self.need("address"); var parts = std.mem.splitScalar(u8, field.text, '-'); var count: usize = 0; while (parts.next()) |part| { if (count == length or part.len != 2) { self.note("a EUI-{d} is {d} hexadecimal pairs joined by dashes", .{ length * 8, length, }); return error.BadNumber; } const value = parseHex(u8, part) catch { self.note("not two hexadecimal digits: \"{s}\"", .{part}); return error.BadNumber; }; try self.appendInt(u8, value); count += 1; } if (count != length) { self.note("a EUI-{d} is {d} hexadecimal pairs joined by dashes", .{ length * 8, length, }); return error.BadNumber; } } /// A signature's inception or expiry: `YYYYMMDDHHmmSS`, or a count of /// seconds since the epoch for a signer that could not be bothered. fn timestamp(self: *Encoder, what: []const u8) Error!void { const field = try self.need(what); const value = parseTimestamp(field.text) catch { self.note("the {s} is not a date: \"{s}\"", .{ what, field.text }); return error.BadTimestamp; }; try self.appendInt(u32, value); } // -- service parameters --------------------------------------------------- const max_parameters = 64; const Parameter = struct { key: u16, start: u32, len: u32, }; /// The `key=value` list of a `svcb` or an `https` (RFC 9460 §2.1). /// /// The wire wants them ordered by key and the text does not have to be, so /// the values are built in the scratch buffer, sorted, and only then /// written out. A value may be quoted, and a quoted one is a token of its /// own as far as the lexer is concerned -- `alpn="h2,h3"` arrives as /// `alpn=` and then `h2,h3` -- which is why a field ending in `=` takes /// the one after it as its value. fn serviceParameters(self: *Encoder) Error!void { self.scratch.clearRetainingCapacity(); var parameters: [max_parameters]Parameter = undefined; var count: usize = 0; while (self.fields.next()) |field| { if (count == max_parameters) { self.note("more than {d} service parameters", .{max_parameters}); return error.BadServiceParameter; } var key_text = field.text; var value_text: ?[]const u8 = null; if (std.mem.indexOfScalar(u8, field.text, '=')) |at| { key_text = field.text[0..at]; const rest = field.text[at + 1 ..]; if (rest.len == 0) { // `key=` followed by a quoted string, or by nothing at all, // which RFC 9460 §A.1 says is an empty value and not the // absence of one. value_text = if (self.fields.peek()) |following| blk: { if (!following.quoted) break :blk ""; _ = self.fields.next(); break :blk following.text; } else ""; } else { value_text = rest; } } const key = parameterKey(key_text) orelse { self.note("no service parameter is called \"{s}\"", .{key_text}); return error.BadServiceParameter; }; const start: u32 = @intCast(self.scratch.items.len); try self.parameterValue(@fromBackingInt(@intCast(key)), value_text); parameters[count] = .{ .key = key, .start = start, .len = @intCast(self.scratch.items.len - start), }; count += 1; } const found = parameters[0..count]; std.mem.sort(Parameter, found, {}, struct { fn lessThan(_: void, a: Parameter, b: Parameter) bool { return a.key < b.key; } }.lessThan); for (found, 0..) |parameter, i| { if (i > 0 and found[i - 1].key == parameter.key) { self.note("the service parameter key {d} is given twice", .{parameter.key}); return error.BadServiceParameter; } try self.appendInt(u16, parameter.key); try self.appendInt(u16, @intCast(parameter.len)); try self.append(self.scratch.items[parameter.start..][0..parameter.len]); } } /// One parameter's value, in the shape that key requires, appended to the /// scratch buffer rather than to the output -- the keys have to be sorted /// before any of them can be written. /// The next item of a comma-separated value, decoded into `buf`. fn listItem(self: *Encoder, items: *ListIterator, buf: []u8) Error!?[]const u8 { return items.next(buf) catch |err| { switch (err) { error.BadEscape => self.note( "in a list, a backslash escapes only a comma or a backslash: \"{s}\"", .{items.text}, ), error.StringTooLong => self.note("a list item longer than 255 bytes", .{}), } return err; }; } fn parameterValue(self: *Encoder, key: dns.rdata.svcb.ParamKey, text: ?[]const u8) Error!void { switch (key) { .@"no-default-alpn", .ohttp => { if (text != null and text.?.len != 0) { self.note("{f} takes no value", .{key}); return error.BadServiceParameter; } }, .mandatory => { const value = text orelse { self.note("mandatory needs a list of keys", .{}); return error.BadServiceParameter; }; var keys: [max_parameters]u16 = undefined; var count: usize = 0; var items = listIterator(value); var buf: [255]u8 = undefined; while (try self.listItem(&items, &buf)) |item| { if (count == max_parameters) return error.BadServiceParameter; keys[count] = parameterKey(item) orelse { self.note("no service parameter is called \"{s}\"", .{item}); return error.BadServiceParameter; }; count += 1; } if (count == 0) { self.note("mandatory needs a list of keys", .{}); return error.BadServiceParameter; } std.mem.sort(u16, keys[0..count], {}, std.sort.asc(u16)); for (keys[0..count]) |k| { var wire: [2]u8 = undefined; std.mem.writeInt(u16, &wire, k, .big); try self.scratch.appendSlice(self.gpa, &wire); } }, .alpn => { const value = text orelse { self.note("alpn needs at least one protocol", .{}); return error.BadServiceParameter; }; var items = listIterator(value); var buf: [255]u8 = undefined; var any = false; while (try self.listItem(&items, &buf)) |item| { try self.scratch.append(self.gpa, @intCast(item.len)); try self.scratch.appendSlice(self.gpa, item); any = true; } if (!any) { self.note("alpn needs at least one protocol", .{}); return error.BadServiceParameter; } }, .port => { const value = text orelse { self.note("port needs a number", .{}); return error.BadServiceParameter; }; const port = parseInt(u16, value) catch { self.note("not a port number: \"{s}\"", .{value}); return error.BadNumber; }; var buf: [2]u8 = undefined; std.mem.writeInt(u16, &buf, port, .big); try self.scratch.appendSlice(self.gpa, &buf); }, .ipv4hint, .ipv6hint => { const value = text orelse { self.note("{f} needs at least one address", .{key}); return error.BadServiceParameter; }; var items = listIterator(value); var buf: [255]u8 = undefined; var any = false; while (try self.listItem(&items, &buf)) |item| { if (key == .ipv4hint) { const address = z46.Ipv4Address.parse(item) catch { self.note("not an IPv4 address: \"{s}\"", .{item}); return error.BadAddress; }; try self.scratch.appendSlice(self.gpa, &address.octets); } else { const address = z46.Ipv6Address.parse(item) catch { self.note("not an IPv6 address: \"{s}\"", .{item}); return error.BadAddress; }; try self.scratch.appendSlice(self.gpa, &address.octets); } any = true; } if (!any) { self.note("{f} needs at least one address", .{key}); return error.BadServiceParameter; } }, .ech => { const value = text orelse { self.note("ech needs a base64 configuration", .{}); return error.BadServiceParameter; }; // Decoded into the output and then moved, because the base64 // helper writes where the record is being built. Doing it the // other way round would need a second decoder. const at = self.out.items.len; try self.appendBase64(value); try self.scratch.appendSlice(self.gpa, self.out.items[at..]); self.out.shrinkRetainingCapacity(at); }, // Anything else -- `dohpath`, and every key this library has no // name for -- is a string of bytes and nothing more. else => { const value = text orelse ""; var buf: [512]u8 = undefined; if (value.len > buf.len) { self.note("a service parameter value longer than {d} bytes", .{buf.len}); return error.StringTooLong; } const decoded = unescape(&buf, value) catch return error.BadEscape; try self.scratch.appendSlice(self.gpa, decoded); }, } } }; // -- the small parsers --------------------------------------------------------- fn parseInt(comptime T: type, text: []const u8) !T { // Zig's parser takes a leading `+`, which nothing in a zone file means to // write, and a `_` as a digit separator, which is a Zig idea rather than a // DNS one. if (text.len == 0) return error.InvalidCharacter; for (text) |c| if (!ascii.isDigit(c)) return error.InvalidCharacter; return std.fmt.parseUnsigned(T, text, 10); } /// Hexadecimal digits and nothing else, for the same reason as `parseInt`. fn parseHex(comptime T: type, text: []const u8) !T { if (text.len == 0) return error.InvalidCharacter; for (text) |c| if (!ascii.isHex(c)) return error.InvalidCharacter; return std.fmt.parseUnsigned(T, text, 16); } /// A time to live as BIND writes one: a plain count of seconds, or a sequence /// of numbers each with a unit after it, which add up. `1h30m` is 5400. pub fn parseTtl(text: []const u8) !u32 { if (text.len == 0) return error.InvalidCharacter; if (parseInt(u32, text)) |value| return value else |_| {} var total: u64 = 0; var value: ?u64 = null; for (text) |c| { if (ascii.isDigit(c)) { value = (value orelse 0) * 10 + (c - '0'); if (value.? > std.math.maxInt(u32)) return error.Overflow; continue; } const multiplier: u64 = switch (ascii.toLower(c)) { 's' => 1, 'm' => 60, 'h' => 60 * 60, 'd' => 24 * 60 * 60, 'w' => 7 * 24 * 60 * 60, else => return error.InvalidCharacter, }; total += (value orelse return error.InvalidCharacter) * multiplier; if (total > std.math.maxInt(u32)) return error.Overflow; value = null; } // A trailing number with no unit -- `1h30` -- is a typo rather than thirty // of something, and is refused rather than guessed at. if (value != null) return error.InvalidCharacter; return @intCast(total); } /// `YYYYMMDDHHmmSS`, or a count of seconds since the epoch. RFC 4034 §3.1.5 /// allows both, and says the fourteen-digit form is what a signer should /// write. pub fn parseTimestamp(text: []const u8) !u32 { if (text.len != 14) return parseInt(u32, text); // Narrowed only after the range has been checked: `@intCast` into a field // too small is a panic and not an error, so a month of 99 has to be // refused while it is still wide enough to hold. const year = try parseInt(u16, text[0..4]); const month = try parseInt(u16, text[4..6]); const day = try parseInt(u16, text[6..8]); const hour = try parseInt(u16, text[8..10]); const minute = try parseInt(u16, text[10..12]); const second = try parseInt(u16, text[12..14]); if (month < 1 or month > 12) return error.InvalidCharacter; if (day < 1 or day > daysInMonth(year, @intCast(month))) return error.InvalidCharacter; if (hour > 23 or minute > 59 or second > 60) return error.InvalidCharacter; const days = daysFromCivil(year, @intCast(month), @intCast(day)); const seconds = days * 86400 + @as(i64, hour) * 3600 + @as(i64, minute) * 60 + second; if (seconds < 0 or seconds > std.math.maxInt(u32)) return error.Overflow; return @intCast(seconds); } fn isLeap(year: u16) bool { return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0); } fn daysInMonth(year: u16, month: u4) u8 { return switch (month) { 1, 3, 5, 7, 8, 10, 12 => 31, 4, 6, 9, 11 => 30, 2 => if (isLeap(year)) 29 else 28, else => 0, }; } /// Howard Hinnant's civil-from-days, run backwards: the number of days from /// 1970-01-01 to a date. `std.time.epoch` only goes the other way, and only /// from 1970, so this is the fifteen lines that has to exist here. fn daysFromCivil(year: u16, month: u4, day: u8) i64 { const y: i64 = @as(i64, year) - @intFromBool(month <= 2); const era = @divFloor(y, 400); const year_of_era = y - era * 400; // 0..399 const m: i64 = month; const day_of_year = @divTrunc(153 * (m + (if (m > 2) @as(i64, -3) else 9)) + 2, 5) + day - 1; const day_of_era = year_of_era * 365 + @divTrunc(year_of_era, 4) - @divTrunc(year_of_era, 100) + day_of_year; return era * 146097 + day_of_era - 719468; } /// A decimal number scaled by a power of ten, as a whole number: `1.5` with a /// scale of 100 is 150. Digits beyond the scale are dropped rather than /// rounded, which is what BIND does. fn parseFixed(text: []const u8, scale: u32) !i64 { if (text.len == 0) return error.InvalidCharacter; var i: usize = 0; var negative = false; if (text[0] == '-') { negative = true; i = 1; } else if (text[0] == '+') { i = 1; } var whole: i64 = 0; var digits: usize = 0; while (i < text.len and ascii.isDigit(text[i])) : (i += 1) { whole = try std.math.add(i64, try std.math.mul(i64, whole, 10), text[i] - '0'); digits += 1; } if (digits == 0) return error.InvalidCharacter; var value = try std.math.mul(i64, whole, scale); if (i < text.len and text[i] == '.') { // A field with no places to put a fraction in -- the degrees and the // minutes of a `loc` -- refuses one rather than dropping it, because // silently reading 42.5 as 42 moves the thing being located. if (scale < 10) return error.InvalidCharacter; i += 1; var place = scale / 10; while (i < text.len and ascii.isDigit(text[i])) : (i += 1) { if (place > 0) { value = try std.math.add(i64, value, @as(i64, text[i] - '0') * place); place /= 10; } } } if (i != text.len) return error.InvalidCharacter; return if (negative) -value else value; } /// A distance in meters, as centimeters. The `m` on the end is optional, /// because RFC 1876's own examples leave it off the precisions. fn parseMeters(text: []const u8) !i64 { var without = text; if (without.len > 0 and ascii.toLower(without[without.len - 1]) == 'm') { without = without[0 .. without.len - 1]; } return parseFixed(without, 100); } /// A length in centimeters as the one byte RFC 1876 gives it: a mantissa of /// nought to nine and a power of ten. Values it cannot express exactly are /// truncated towards a shorter mantissa, which is what BIND does with them. fn precisionByte(centimeters: u64) u8 { var mantissa = centimeters; var exponent: u8 = 0; while (mantissa > 9 and exponent < 9) { mantissa /= 10; exponent += 1; } if (mantissa > 9) mantissa = 9; return @as(u8, @intCast(mantissa)) << 4 | exponent; } fn base32hexValue(c: u8) ?u5 { return switch (c) { '0'...'9' => @intCast(c - '0'), 'A'...'V' => @intCast(c - 'A' + 10), 'a'...'v' => @intCast(c - 'a' + 10), else => null, }; } /// Undoes the escapes of RFC 1035 §5.1 into a buffer the caller owns. fn unescape(buf: []u8, text: []const u8) ![]u8 { var out: usize = 0; var i: usize = 0; while (i < text.len) { var c = text[i]; i += 1; if (c == '\\') { if (i >= text.len) return error.BadEscape; if (ascii.isDigit(text[i])) { if (i + 3 > text.len) return error.BadEscape; var value: u16 = 0; for (text[i..][0..3]) |digit| { if (!ascii.isDigit(digit)) return error.BadEscape; value = value * 10 + (digit - '0'); } if (value > 255) return error.BadEscape; c = @intCast(value); i += 3; } else { c = text[i]; i += 1; } } if (out == buf.len) return error.NoSpaceLeft; buf[out] = c; out += 1; } return buf[0..out]; } /// The items of a comma-separated service parameter value (RFC 9460 §A.1), /// with both of its levels of escaping undone. /// /// The value is a character-string first, and its `\DDD` and `\c` escapes /// come off as they would anywhere else. What is left is the list, in which a /// backslash escapes a comma or another backslash and nothing else. So a comma /// inside an `alpn` protocol name is `\\,` in a zone file -- which is how /// `dns` writes one, and how BIND and dnspython read it -- while a lone `\,` /// is only a comma, and separates. const ListIterator = struct { text: []const u8, pos: usize = 0, done: bool, fn next(self: *ListIterator, buf: []u8) !?[]const u8 { if (self.done) return null; var out: usize = 0; while (self.pos < self.text.len) { var c = try self.byte(); if (c == ',') return buf[0..out]; if (c == '\\') { if (self.pos >= self.text.len) return error.BadEscape; c = try self.byte(); if (c != ',' and c != '\\') return error.BadEscape; } if (out == buf.len) return error.StringTooLong; buf[out] = c; out += 1; } self.done = true; return buf[0..out]; } /// One byte of the character-string, with its escape undone. fn byte(self: *ListIterator) !u8 { const c = self.text[self.pos]; self.pos += 1; if (c != '\\') return c; if (self.pos >= self.text.len) return error.BadEscape; if (!ascii.isDigit(self.text[self.pos])) { defer self.pos += 1; return self.text[self.pos]; } if (self.pos + 3 > self.text.len) return error.BadEscape; var value: u16 = 0; for (self.text[self.pos..][0..3]) |digit| { if (!ascii.isDigit(digit)) return error.BadEscape; value = value * 10 + (digit - '0'); } if (value > 255) return error.BadEscape; self.pos += 3; return @intCast(value); } }; /// An empty value is no items at all, rather than one empty one. fn listIterator(text: []const u8) ListIterator { return .{ .text = text, .done = text.len == 0 }; } /// A service parameter key by name, or by the `keyNNNNN` syntax of RFC 9460 /// §2.1 for one with no name. fn parameterKey(text: []const u8) ?u16 { const info = @typeInfo(dns.rdata.svcb.ParamKey).@"enum"; inline for (info.field_names, info.field_values) |field_name, value| { if (std.mem.eql(u8, text, field_name)) return value; } if (text.len > 3 and std.mem.eql(u8, text[0..3], "key")) { return parseInt(u16, text[3..]) catch null; } return null; } /// The DNSSEC algorithm mnemonics, as BIND spells them. Every one of them can /// be written as its number instead, and `dig` always prints the number, so /// this table is for reading zone files people wrote by hand. fn algorithmNumber(text: []const u8) ?u8 { const table = .{ .{ "RSAMD5", 1 }, .{ "DH", 2 }, .{ "DSA", 3 }, .{ "ECC", 4 }, .{ "RSASHA1", 5 }, .{ "DSA-NSEC3-SHA1", 6 }, .{ "NSEC3DSA", 6 }, .{ "RSASHA1-NSEC3-SHA1", 7 }, .{ "NSEC3RSASHA1", 7 }, .{ "RSASHA256", 8 }, .{ "RSASHA512", 10 }, .{ "ECC-GOST", 12 }, .{ "ECDSAP256SHA256", 13 }, .{ "ECDSAP384SHA384", 14 }, .{ "ED25519", 15 }, .{ "ED448", 16 }, .{ "SM2SM3", 17 }, .{ "ECC-GOST12", 23 }, .{ "INDIRECT", 252 }, .{ "PRIVATEDNS", 253 }, .{ "PRIVATEOID", 254 }, }; inline for (table) |entry| { if (ascii.eqlIgnoreCase(text, entry[0])) return entry[1]; } return null; } fn certificateTypeNumber(text: []const u8) ?u16 { const info = @typeInfo(dns.rdata.Cert.CertType).@"enum"; inline for (info.field_names, info.field_values) |field_name, value| { if (ascii.eqlIgnoreCase(text, field_name)) return value; } return null; } /// The protocols a `wks` names. The list is short because the record is: it /// was only ever written for TCP and UDP, and a number works for anything /// else. fn protocolNumber(text: []const u8) ?u8 { const table = .{ .{ "icmp", 1 }, .{ "igmp", 2 }, .{ "ggp", 3 }, .{ "ipv4", 4 }, .{ "tcp", 6 }, .{ "egp", 8 }, .{ "pup", 12 }, .{ "udp", 17 }, .{ "hmp", 20 }, .{ "xns-idp", 22 }, .{ "rdp", 27 }, .{ "rvd", 66 }, }; inline for (table) |entry| { if (ascii.eqlIgnoreCase(text, entry[0])) return entry[1]; } return null; } /// The service names a `wks` is likely to hold. BIND reads these out of /// `/etc/services`, which this library has no way to open and no business /// depending on; the well known ones are here and everything else is written /// as its port number. fn serviceNumber(text: []const u8, protocol: u8) ?u16 { _ = protocol; // None of these differ between TCP and UDP. const table = .{ .{ "echo", 7 }, .{ "discard", 9 }, .{ "systat", 11 }, .{ "daytime", 13 }, .{ "netstat", 15 }, .{ "qotd", 17 }, .{ "chargen", 19 }, .{ "ftp-data", 20 }, .{ "ftp", 21 }, .{ "ssh", 22 }, .{ "telnet", 23 }, .{ "smtp", 25 }, .{ "time", 37 }, .{ "whois", 43 }, .{ "tacacs", 49 }, .{ "domain", 53 }, .{ "bootps", 67 }, .{ "bootpc", 68 }, .{ "tftp", 69 }, .{ "gopher", 70 }, .{ "finger", 79 }, .{ "http", 80 }, .{ "kerberos", 88 }, .{ "pop2", 109 }, .{ "pop3", 110 }, .{ "sunrpc", 111 }, .{ "auth", 113 }, .{ "nntp", 119 }, .{ "ntp", 123 }, .{ "netbios-ns", 137 }, .{ "netbios-dgm", 138 }, .{ "netbios-ssn", 139 }, .{ "imap", 143 }, .{ "snmp", 161 }, .{ "snmp-trap", 162 }, .{ "bgp", 179 }, .{ "ldap", 389 }, .{ "https", 443 }, .{ "smtps", 465 }, .{ "syslog", 514 }, .{ "printer", 515 }, .{ "submission", 587 }, .{ "ldaps", 636 }, .{ "imaps", 993 }, .{ "pop3s", 995 }, }; inline for (table) |entry| { if (ascii.eqlIgnoreCase(text, entry[0])) return entry[1]; } return null; } // -- tests --------------------------------------------------------------------- const testing = std.testing; test encode { const gpa = testing.allocator; var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var scratch: std.ArrayList(u8) = .empty; defer scratch.deinit(gpa); var origin_buffer: dns.Name.Buffer = undefined; const origin = try name.encodeAbsolute(&origin_buffer, "example.com."); const fields: []const Field = &.{ .{ .text = "10" }, .{ .text = "mail" } }; try encode(gpa, &out, &scratch, .mx, fields, origin, null); try testing.expectEqualSlices(u8, "\x00\x0a\x04mail\x07example\x03com\x00", out.items); } test representable { // A hip with an empty host identity tag: legal on the wire, and with no // way to write the empty field in the middle of the text. var empty_hit = try dns.wire.Decoder.init("\x00\x02\x00\x00"); const hip = try dns.rdata.Data.parse(.hip, &empty_hit); try testing.expectEqualStrings("a hip with no host identity tag", representable(hip).?); var address = try dns.wire.Decoder.init("\xc0\x00\x02\x01"); try testing.expectEqual(null, representable(try dns.rdata.Data.parse(.a, &address))); } test parseTtl { try testing.expectEqual(@as(u32, 3600), try parseTtl("3600")); try testing.expectEqual(@as(u32, 5400), try parseTtl("1h30m")); try testing.expectEqual(@as(u32, 1209600), try parseTtl("2W")); // Thirty of what? try testing.expectError(error.InvalidCharacter, parseTtl("1h30")); } test parseTimestamp { try testing.expectEqual(@as(u32, 1704067200), try parseTimestamp("20240101000000")); try testing.expectEqual(@as(u32, 1704067200), try parseTimestamp("1704067200")); try testing.expectError(error.InvalidCharacter, parseTimestamp("20241301000000")); } /// Splits a line of record data the way the lexer would, which is enough for a /// test that is about the encoding rather than about the lexing: a quoted /// string is one field, and everything else splits on spaces. fn split(gpa: Allocator, text: []const u8, out: *std.ArrayList(Field)) !void { var i: usize = 0; while (i < text.len) { while (i < text.len and text[i] == ' ') i += 1; if (i >= text.len) break; if (text[i] == '"') { i += 1; const start = i; while (i < text.len and text[i] != '"') { if (text[i] == '\\') i += 1; i += 1; } try out.append(gpa, .{ .text = text[start..i], .quoted = true }); i += 1; } else { const start = i; while (i < text.len and text[i] != ' ' and text[i] != '"') { if (text[i] == '\\') i += 1; i += 1; } try out.append(gpa, .{ .text = text[start..@min(i, text.len)] }); } } } /// The text is encoded, the bytes are compared, and then the bytes are decoded /// by `dns` and printed -- so every one of these checks the presentation form /// this library reads against the one it writes. fn expectEncodes(t: dns.Type, text: []const u8, expected: []const u8) !void { const gpa = testing.allocator; var fields: std.ArrayList(Field) = .empty; defer fields.deinit(gpa); try split(gpa, text, &fields); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var scratch: std.ArrayList(u8) = .empty; defer scratch.deinit(gpa); var diagnostics: Diagnostics = .{}; encode(gpa, &out, &scratch, t, fields.items, null, &diagnostics) catch |err| { std.debug.print("{s}: {f}\n", .{ @errorName(err), diagnostics }); return err; }; try testing.expectEqualSlices(u8, expected, out.items); var decoder = try dns.wire.Decoder.init(out.items); const data = try dns.rdata.Data.parse(t, &decoder); try testing.expectEqual(t, data.recordType()); } fn expectFails(t: dns.Type, text: []const u8, expected: anyerror) !void { const gpa = testing.allocator; var fields: std.ArrayList(Field) = .empty; defer fields.deinit(gpa); try split(gpa, text, &fields); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var scratch: std.ArrayList(u8) = .empty; defer scratch.deinit(gpa); try testing.expectError(expected, encode(gpa, &out, &scratch, t, fields.items, null, null)); } /// Encodes, and expects `dns` to refuse the bytes that came out -- which is /// how a record whose fields are each fine but whose meaning is not gets /// caught. fn expectDecodeFails(t: dns.Type, text: []const u8, expected: anyerror) !void { const gpa = testing.allocator; var fields: std.ArrayList(Field) = .empty; defer fields.deinit(gpa); try split(gpa, text, &fields); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var scratch: std.ArrayList(u8) = .empty; defer scratch.deinit(gpa); try encode(gpa, &out, &scratch, t, fields.items, null, null); var decoder = try dns.wire.Decoder.init(out.items); try testing.expectError(expected, dns.rdata.Data.parse(t, &decoder)); } test "addresses" { try expectEncodes(.a, "192.0.2.1", "\xc0\x00\x02\x01"); try expectEncodes(.aaaa, "2001:db8::1", "\x20\x01\x0d\xb8" ++ @as([11]u8, @splat(0)) ++ "\x01"); try expectFails(.a, "2001:db8::1", error.BadAddress); try expectFails(.a, "192.0.2.1 192.0.2.2", error.TrailingField); try expectFails(.a, "", error.MissingField); } test "names, and the origin they are relative to" { try expectEncodes(.cname, "www.example.com.", "\x03www\x07example\x03com\x00"); try expectEncodes(.ns, ".", "\x00"); try expectFails(.ns, "relative", error.NoOrigin); } test "the start of authority, with units in its timers" { try expectEncodes( .soa, "ns1.example.com. hostmaster.example.com. 2024010101 2h 1h 1000h 5m", "\x03ns1\x07example\x03com\x00\x0ahostmaster\x07example\x03com\x00" ++ "\x78\xa3\xf1\x75\x00\x00\x1c\x20\x00\x00\x0e\x10\x00\x36\xee\x80\x00\x00\x01\x2c", ); try expectFails(.soa, "a. b. 1 2 3 4", error.MissingField); } test "text arrives as one string or several" { try expectEncodes(.txt, "\"hello\"", "\x05hello"); try expectEncodes(.txt, "hello world", "\x05hello\x05world"); try expectEncodes(.txt, "\"hello world\"", "\x0bhello world"); try expectEncodes(.txt, "\"\"", "\x00"); try expectEncodes(.txt, "\"a\\\"b\"", "\x03a\"b"); try expectEncodes(.txt, "a\\032b", "\x03a b"); // No strings at all is not a txt; one empty string is. try expectFails(.txt, "", error.MissingField); try expectFails(.txt, "\"" ++ @as([256]u8, @splat('x')) ++ "\"", error.StringTooLong); } test "the types with a number and a name" { try expectEncodes(.mx, "10 mail.example.com.", "\x00\x0a\x04mail\x07example\x03com\x00"); try expectEncodes( .srv, "1 0 5201 sip1.example.com.", "\x00\x01\x00\x00\x14\x51\x04sip1\x07example\x03com\x00", ); try expectFails(.mx, "70000 mail.example.com.", error.BadNumber); try expectFails(.mx, "ten mail.example.com.", error.BadNumber); } test "the text-carrying types" { try expectEncodes(.hinfo, "\"amd64\" \"linux\"", "\x05amd64\x05linux"); try expectEncodes(.caa, "0 issue \"letsencrypt.org\"", "\x00\x05issue" ++ "letsencrypt.org"); // A tag is letters and digits, and nothing else: it is written back // without quotes, so a tag with a space in it would not read back as // itself. try expectFails(.caa, "0 \"iss ue\" \"letsencrypt.org\"", error.BadServiceParameter); try expectFails(.caa, "0 \"\" \"letsencrypt.org\"", error.BadServiceParameter); try expectFails(.caa, "0 abcdefghijklmnop \"letsencrypt.org\"", error.BadServiceParameter); try expectEncodes( .uri, "10 1 \"https://example.com/\"", "\x00\x0a\x00\x01https://example.com/", ); try expectEncodes( .naptr, "100 10 \"u\" \"E2U+sip\" \"!^.*$!sip:info@example.com!\" .", "\x00\x64\x00\x0a\x01u\x07E2U+sip\x1b!^.*$!sip:info@example.com!\x00", ); } test "the DNSSEC types, by number and by mnemonic" { try expectEncodes( .ds, "12345 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE", "\x30\x39\x08\x02\x49\xfd\x46\xe6\xc4\xb4\x5c\x55\xd4\xac\x69\xcb" ++ "\xd3\xcd\x34\xac\x1a\xfe\x51\xde", ); try expectEncodes( .ds, "12345 RSASHA256 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE", "\x30\x39\x08\x02\x49\xfd\x46\xe6\xc4\xb4\x5c\x55\xd4\xac\x69\xcb" ++ "\xd3\xcd\x34\xac\x1a\xfe\x51\xde", ); try expectEncodes(.dnskey, "256 3 8 AwEAAQ==", "\x01\x00\x03\x08\x03\x01\x00\x01"); // The base64 of a key is written across lines, and arrives as pieces. try expectEncodes(.dnskey, "256 3 8 AwEA AQ==", "\x01\x00\x03\x08\x03\x01\x00\x01"); try expectFails(.dnskey, "256 3 8 not-base64!", error.BadEncoding); try expectFails(.ds, "12345 NOSUCHALGORITHM 2 00", error.UnknownMnemonic); } test "a signature, and the two ways its dates are written" { const expected = "\x00\x01\x08\x03\x00\x00\x0e\x10" ++ "\x67\x8d\x3d\xa0\x67\x85\x54\xa0\x30\x39" ++ "\x07example\x03com\x00" ++ "\x01\x02\x03"; try expectEncodes( .rrsig, "A 8 3 3600 20250119180000 20250113180000 12345 example.com. AQID", expected, ); try expectEncodes( .rrsig, "A 8 3 3600 1737309600 1736791200 12345 example.com. AQID", expected, ); try expectFails( .rrsig, "A 8 3 3600 20259919180000 20250113180000 12345 example.com. AQID", error.BadTimestamp, ); } test "the types that carry a bitmap of other types" { try expectEncodes( .nsec, "host.example.com. A MX RRSIG NSEC TYPE1234", "\x04host\x07example\x03com\x00" ++ "\x00\x06\x40\x01\x00\x00\x00\x03" ++ "\x04\x1b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" ++ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20", ); try expectEncodes(.nsec, "a.example. A", "\x01a\x07example\x00\x00\x01\x40"); try expectEncodes(.csync, "66 3 A NS AAAA", "\x00\x00\x00\x42\x00\x03\x00\x04\x60\x00\x00\x08"); try expectFails(.nsec, "a.example. NOSUCHTYPE", error.UnknownMnemonic); } test "nsec3, whose salt may be a dash and whose next name is base32" { try expectEncodes( .nsec3, "1 1 12 aabbccdd 2vptu5timamqttgl4luu9kg21e0aor3s A RRSIG", "\x01\x01\x00\x0c\x04\xaa\xbb\xcc\xdd" ++ "\x14\x17\xf3\xdf\x17\xb2\xb2\xad\xae\xf6\x15\x25\x7d\xe4\xd2\x02" ++ "\x0b\x80\xac\x6c\x7c" ++ "\x00\x06\x40\x00\x00\x00\x00\x02", ); try expectEncodes( .nsec3param, "1 0 0 -", "\x01\x00\x00\x00\x00", ); } test "service bindings, whose parameters are sorted by key" { try expectEncodes(.https, "0 example.com.", "\x00\x00\x07example\x03com\x00"); try expectEncodes( .https, "1 . alpn=h2,h3 port=8443", "\x00\x01\x00" ++ "\x00\x01\x00\x06\x02h2\x02h3" ++ "\x00\x03\x00\x02\x20\xfb", ); // Given out of order, written in order. try expectEncodes( .svcb, "1 . port=443 alpn=h2", "\x00\x01\x00" ++ "\x00\x01\x00\x03\x02h2" ++ "\x00\x03\x00\x02\x01\xbb", ); try expectEncodes( .https, "1 . no-default-alpn ipv4hint=192.0.2.1,192.0.2.2", "\x00\x01\x00" ++ "\x00\x02\x00\x00" ++ "\x00\x04\x00\x08\xc0\x00\x02\x01\xc0\x00\x02\x02", ); // A quoted value is a token of its own, and is still that parameter's. try expectEncodes( .https, "1 . alpn=\"h2,h3\"", "\x00\x01\x00" ++ "\x00\x01\x00\x06\x02h2\x02h3", ); // RFC 9460 §A.1: the value is a character-string first and a list // second, so a comma inside a protocol name is escaped twice, `\\,`. Once // is only a comma, and separates -- as BIND and dnspython both read it. try expectEncodes( .https, "1 . alpn=\"h2\\\\,h3\"", "\x00\x01\x00" ++ "\x00\x01\x00\x06\x05h2,h3", ); try expectEncodes( .https, "1 . alpn=h2\\,h3", "\x00\x01\x00" ++ "\x00\x01\x00\x06\x02h2\x02h3", ); // A backslash in one is escaped twice as well. try expectEncodes( .https, "1 . alpn=\"a\\\\\\\\b\"", "\x00\x01\x00" ++ "\x00\x01\x00\x04\x03a\\b", ); // In the list, a backslash escapes a comma or a backslash and nothing // else. BIND lets this one go as `h2x`; dnspython and the RFC do not. try expectFails(.https, "1 . alpn=\"h2\\\\x\"", error.BadEscape); // A trailing comma leaves an empty protocol name, which `dns` refuses. try expectDecodeFails(.https, "1 . alpn=h2,", error.MalformedRdata); try expectEncodes( .https, "1 . mandatory=alpn alpn=h2 key65000=hello", "\x00\x01\x00" ++ "\x00\x00\x00\x02\x00\x01" ++ "\x00\x01\x00\x03\x02h2" ++ "\xfd\xe8\x00\x05hello", ); try expectFails(.https, "1 . port=443 port=444", error.BadServiceParameter); try expectFails(.https, "1 . nosuchkey=1", error.BadServiceParameter); try expectFails(.https, "1 . key1_0=x", error.BadServiceParameter); try expectFails(.https, "1 . key+10=x", error.BadServiceParameter); try expectFails(.https, "1 . no-default-alpn=yes", error.BadServiceParameter); // mandatory names a key the record does not have, which `dns` refuses. try expectDecodeFails(.https, "1 . mandatory=port alpn=h2", error.MalformedRdata); } test "the generic syntax works for a type that has a parser of its own" { try expectEncodes(.a, "\\# 4 C0000201", "\xc0\x00\x02\x01"); try expectEncodes(.a, "\\# 4 C000 0201", "\xc0\x00\x02\x01"); // And for one that does not. try expectEncodes(@fromBackingInt(@intCast(64000)), "\\# 3 010203", "\x01\x02\x03"); try expectEncodes(.null, "\\# 0", ""); try expectFails(.a, "\\# 5 C0000201", error.BadGenericRdata); try expectFails(.a, "\\# 4 C00002", error.BadGenericRdata); // A known type whose generic bytes are not what the type needs is caught // by `dns` rather than here, which is the point of decoding them again. try expectDecodeFails(.a, "\\# 3 C00002", error.Truncated); } test "the types with no syntax at all" { try expectFails(.null, "anything", error.TypeNotInZones); try expectFails(.opt, "anything", error.TypeNotInZones); try expectFails(.tsig, "anything", error.TypeNotInZones); try expectFails(.any, "anything", error.TypeNotInZones); try expectFails(.axfr, "anything", error.TypeNotInZones); try expectFails(.nxname, "anything", error.TypeNotInZones); try expectFails(@fromBackingInt(@intCast(64000)), "anything", error.UnknownMnemonic); } test "where a host is" { // The RFC 1876 example, which is the one everything else checks against. try expectEncodes( .loc, "42 21 54 N 71 06 18 W -24m 30m", "\x00\x33\x16\x13\x89\x17\x2d\xd0\x70\xbe\x15\xf0\x00\x98\x8d\x20", ); // Degrees alone, and the defaults for everything after the altitude. try expectEncodes( .loc, "42 N 71 W 0", "\x00\x12\x16\x13\x89\x03\x21\x00\x70\xc3\xda\x80\x00\x98\x96\x80", ); try expectFails(.loc, "42 21 54 71 06 18 W 0", error.BadLocation); try expectFails(.loc, "200 N 71 W 0", error.BadLocation); // Degrees and minutes are whole numbers; only the seconds have a // fraction, and reading 42.5 as 42 would move the thing being located. try expectFails(.loc, "42.5 N 71 W 0", error.BadLocation); try expectEncodes( .loc, "42 21 54.321 N 71 06 18 W 0", "\x00\x12\x16\x13\x89\x17\x2f\x11\x70\xbe\x15\xf0\x00\x98\x96\x80", ); } test "the types that were tried and not kept" { try expectEncodes(.afsdb, "1 afs.example.", "\x00\x01\x03afs\x07example\x00"); try expectEncodes(.x25, "\"311061700956\"", "\x0c311061700956"); try expectEncodes(.isdn, "\"150862028003217\"", "\x0f150862028003217"); try expectEncodes(.isdn, "\"1234\" \"004\"", "\x041234\x03004"); try expectEncodes(.nsap, "0x47.0005.80.005a00", "\x47\x00\x05\x80\x00\x5a\x00"); try expectEncodes(.wks, "192.0.2.1 tcp smtp domain", "\xc0\x00\x02\x01\x06\x00\x00\x00\x40\x00\x00\x04"); try expectEncodes(.wks, "192.0.2.1 6 25", "\xc0\x00\x02\x01\x06\x00\x00\x00\x40"); try expectEncodes(.a6, "0 2001:db8::1", "\x00\x20\x01\x0d\xb8" ++ @as([11]u8, @splat(0)) ++ "\x01"); try expectEncodes( .a6, "64 ::1 prefix.example.", "\x40\x00\x00\x00\x00\x00\x00\x00\x01\x06prefix\x07example\x00", ); try expectEncodes(.nxt, "big.example. A MX SIG NXT", "\x03big\x07example\x00\x40\x01\x00\x82"); try expectEncodes( .apl, "1:192.0.2.0/24 !1:192.0.2.128/25 2:2001:db8::/32", "\x00\x01\x18\x03\xc0\x00\x02" ++ "\x00\x01\x19\x84\xc0\x00\x02\x80" ++ "\x00\x02\x20\x04\x20\x01\x0d\xb8", ); // Any other family is its address in hexadecimal, with the trailing zero // bytes dropped as they are for the two RFC 3123 names. try expectEncodes(.apl, "3:e0/4 !16:0102ff00/255", "\x00\x03\x04\x01\xe0" ++ "\x00\x10\xff\x83\x01\x02\xff"); try expectEncodes(.apl, "3:/0", "\x00\x03\x00\x00"); try expectFails(.apl, "3:1.2.3.4/8", error.BadEncoding); try expectFails(.apl, "3:e/4", error.BadEncoding); try expectFails(.apl, "1:192.0.2.0/33", error.BadAddressPrefix); } test "keys published for somewhere else" { try expectEncodes( .sshfp, "2 1 123456789abcdef67890123456789abcdef67890", "\x02\x01\x12\x34\x56\x78\x9a\xbc\xde\xf6\x78\x90\x12\x34\x56\x78" ++ "\x9a\xbc\xde\xf6\x78\x90", ); try expectEncodes(.tlsa, "3 1 1 0123", "\x03\x01\x01\x01\x23"); try expectEncodes(.cert, "PKIX 0 0 AQID", "\x00\x01\x00\x00\x00\x01\x02\x03"); try expectEncodes(.cert, "1 0 0 AQID", "\x00\x01\x00\x00\x00\x01\x02\x03"); try expectEncodes(.openpgpkey, "AQID", "\x01\x02\x03"); try expectEncodes( .ipseckey, "10 1 2 192.0.2.38 AQID", "\x0a\x01\x02\xc0\x00\x02\x26\x01\x02\x03", ); try expectEncodes(.ipseckey, "10 0 0 .", "\x0a\x00\x00"); try expectEncodes( .ipseckey, "10 3 2 mygateway.example.com. AQID", "\x0a\x03\x02\x09mygateway\x07example\x03com\x00\x01\x02\x03", ); try expectEncodes(.amtrelay, "10 0 1 192.0.2.38", "\x0a\x01\xc0\x00\x02\x26"); try expectEncodes(.amtrelay, "10 1 0 .", "\x0a\x80"); try expectEncodes( .hip, "2 200100107B1A74DF365639CC39F1D578 AQID rvs.example.com.", "\x10\x02\x00\x03" ++ "\x20\x01\x00\x10\x7b\x1a\x74\xdf\x36\x56\x39\xcc\x39\xf1\xd5\x78" ++ "\x01\x02\x03" ++ "\x03rvs\x07example\x03com\x00", ); } test "identifiers and locators" { try expectEncodes(.nid, "10 0014:4fff:ff20:ee64", "\x00\x0a\x00\x14\x4f\xff\xff\x20\xee\x64"); try expectEncodes(.l32, "10 10.1.2.0", "\x00\x0a\x0a\x01\x02\x00"); try expectEncodes(.eui48, "00-00-5e-00-53-2a", "\x00\x00\x5e\x00\x53\x2a"); try expectEncodes(.eui64, "00-00-5e-ef-10-00-00-2a", "\x00\x00\x5e\xef\x10\x00\x00\x2a"); try expectFails(.eui48, "00-00-5e-00-53", error.BadNumber); try expectFails(.nid, "10 0014:4fff:ff20", error.BadNumber); // Zig reads a `_` between digits as a separator; a zone file does not. try expectFails(.nid, "10 0_14:4fff:ff20:ee64", error.BadNumber); try expectFails(.l64, "10 +014:4fff:ff20:ee64", error.BadNumber); try expectFails(.eui48, "00-00-5e-00-53-+1", error.BadNumber); } test "times are read the way BIND writes them" { try testing.expectEqual(@as(u32, 3600), try parseTtl("3600")); try testing.expectEqual(@as(u32, 3600), try parseTtl("1h")); try testing.expectEqual(@as(u32, 5400), try parseTtl("1h30m")); try testing.expectEqual(@as(u32, 604800), try parseTtl("1w")); try testing.expectEqual(@as(u32, 0), try parseTtl("0")); try testing.expectError(error.InvalidCharacter, parseTtl("1h30")); try testing.expectError(error.InvalidCharacter, parseTtl("h")); try testing.expectError(error.InvalidCharacter, parseTtl("")); try testing.expectError(error.Overflow, parseTtl("4294967296")); } test "dates are read the way a signer writes them" { try testing.expectEqual(@as(u32, 0), try parseTimestamp("19700101000000")); try testing.expectEqual(@as(u32, 946684800), try parseTimestamp("20000101000000")); try testing.expectEqual(@as(u32, 951782400), try parseTimestamp("20000229000000")); try testing.expectEqual(@as(u32, 1234567890), try parseTimestamp("1234567890")); try testing.expectError(error.InvalidCharacter, parseTimestamp("20010229000000")); try testing.expectError(error.InvalidCharacter, parseTimestamp("20000001000000")); try testing.expectError(error.InvalidCharacter, parseTimestamp("20000101250000")); }