// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A zone file, one record at a time. //! //! ```zig //! var parser: zone.Parser = .init(gpa, &reader, .{ .origin = "example.com." }); //! defer parser.deinit(); //! while (try parser.next()) |item| switch (item) { //! .record => |rr| std.debug.print("{f}\n", .{rr}), //! .include => {}, //! } //! ``` //! //! What comes out is a `dns.Record`: the record in wire form, with its data //! already encoded and already decoded again to check that it could be. That //! is the whole trick of this library -- a parsed zone is a pile of records //! exactly as a message would carry them, so everything `dns` can do to a //! record read off a socket it can do to one read out of a file. //! //! **A record borrows the parser until the next call.** `next` reuses one //! buffer for the record it is building, so the one before it is gone. Copy it //! out -- `Zone` does -- or use it and move on. //! //! ### State the file carries //! //! A zone file is not a list of records so much as a program that produces //! them. `$ORIGIN` decides what a relative name means, `$TTL` decides what a //! record with no time to live means, an entry beginning with whitespace takes //! the owner of the entry above it, `$INCLUDE` splices in another file with //! the origin it names and gives the old one back afterwards, and `$GENERATE` //! stands in for a hundred near-identical records -- one line of a reverse //! zone that `next` hands back a record at a time. All of that is here, and //! all of it is readable while parsing: `origin`, `ttl` and `owner` say what //! the file has said so far. //! //! ### `$INCLUDE` without opening a file //! //! This library reads no files, so an include is reported rather than //! followed. Ask for it with `.includes = .report`, open whatever the //! directive names however your program wants to, and hand the reader back: //! //! ```zig //! .include => |include| { //! var file = try dir.openFile(include.path, .{}); //! defer file.close(); //! var buffer: [4096]u8 = undefined; //! var file_reader = file.reader(&buffer); //! try parser.pushInclude(&file_reader.interface, include.path); //! }, //! ``` //! //! Handing back nothing is allowed too: the file is simply not read, which is //! what a tool that only wants to know what a zone includes should do. The //! default is `.refuse`, because a zone silently missing the records another //! file holds is worse than one that will not load. const std = @import("std"); const Allocator = std.mem.Allocator; const Reader = std.Io.Reader; const dns = @import("dns"); const Diagnostics = @import("Diagnostics.zig"); const Lexer = @import("Lexer.zig"); const name = @import("name.zig"); const rdata_text = @import("rdata_text.zig"); const Parser = @This(); gpa: Allocator, options: Options, /// The file being read, and the files it was included from. sources: std.ArrayList(Source) = .empty, /// The record being built, in wire form: owner, type, class, time to live, /// length, data. image: std.ArrayList(u8) = .empty, /// Working space for whichever field needs its pieces joined up. scratch: std.ArrayList(u8) = .empty, /// The tokens of the entry being read. tokens: std.ArrayList(Lexer.Token) = .empty, /// Those of them that are record data, resolved to text. fields: std.ArrayList(rdata_text.Field) = .empty, /// The current origin in wire form, which is empty only before one is known. origin_buffer: dns.Name.Buffer = undefined, origin_len: usize = 0, /// The owner of the last record, for an entry that begins with whitespace. owner_buffer: dns.Name.Buffer = undefined, owner_len: usize = 0, /// What `$TTL` last said, or what the caller said, or the `minimum` of the /// `soa` if neither of them said anything. ttl: ?u32 = null, /// The origin an `$INCLUDE` asked for, kept until the caller hands back a /// reader for the file. include_origin: dns.Name.Buffer = undefined, include_origin_len: usize = 0, /// The `$GENERATE` being expanded, if one is. generate: ?Generate = null, /// The text one turn of that expansion produced, owner name and data both. generate_text: std.ArrayList(u8) = .empty, /// Where each piece of it begins, because appending the next piece may move /// the one before it. generate_spans: std.ArrayList(Span) = .empty, pub const Error = error{ /// An entry began with whitespace, and there is no record above it to take /// an owner name from. NoPreviousOwner, /// The entry ran out before it said what type of record it is. MissingType, /// A type mnemonic this library has no number for. Every type in the /// registry can be written as `TYPE1234` instead. UnknownType, /// A record with no time to live, in a file with no `$TTL`, in a zone /// whose `soa` has not been seen yet. MissingTtl, /// A `$` directive that is not one of the four. UnknownDirective, /// A directive with the wrong number of arguments, or an argument that is /// not what that directive takes. BadDirective, /// `$INCLUDE`, when the caller did not ask to be told about them. IncludeNotAllowed, /// `$INCLUDE` inside `$INCLUDE` inside... beyond the depth allowed, which /// is the only defence against a file that includes itself. IncludeTooDeep, /// A `$GENERATE` whose range is not `start-stop` or `start-stop/step`, or /// whose `${...}` substitution is not `${offset,width,radix}`. BadGenerate, /// A record whose data is legal on the wire and has no presentation form: /// see `rdata_text.representable`. It can only be reached through the /// `\#` syntax. NotWritableAsText, /// The record is bigger than a DNS message could carry it in. The limit is /// 65535 bytes for the whole record, owner name and all. RecordTooLong, } || Lexer.Error || rdata_text.Error || dns.rdata.Error; pub const Options = struct { /// Where relative names start out, as presentation text: `example.com.`. /// A `$ORIGIN` in the file replaces it. Without either, a relative name is /// an error rather than a name quietly rooted one label short. origin: ?[]const u8 = null, /// What a record with no time to live in front of it means, before any /// `$TTL`. RFC 2308 §4 wants every zone file to carry a `$TTL`; this is /// for the ones that do not. default_ttl: ?u32 = null, /// The class of a record that does not say. In practice `in`, always. default_class: dns.Class = .in, /// What to do about `$INCLUDE`. includes: Includes = .refuse, /// How deep includes may nest. max_include_depth: u8 = 8, /// Whether to decode each record's data after encoding it, which catches /// everything that is the right shape and the wrong meaning: a `svcb` /// whose `mandatory` names a parameter it does not carry, a `\#` whose /// bytes are not what its type needs. Leave it on unless the profile says /// otherwise; it is one pass over bytes that are already in cache. validate: bool = true, /// What to call the file in a diagnostic. file: ?[]const u8 = null, diagnostics: ?*Diagnostics = null, }; pub const Includes = enum { /// `$INCLUDE` is an error. refuse, /// `$INCLUDE` comes back from `next`, and the caller may hand back a /// reader for the file with `pushInclude`. report, }; pub const Item = union(enum) { record: dns.Record, include: Include, }; pub const Include = struct { /// The file the directive named, exactly as it was written. It borrows the /// parser and is gone at the next call to `next`, which is after /// `pushInclude` would have been called with it. path: []const u8, /// The origin the directive gave for it, or `null` when it gave none and /// the file is to be read with the origin already in force. origin: ?dns.Name, }; const Source = struct { lexer: Lexer, /// What to call it in a diagnostic. file: ?[]const u8, /// The origin, owner and time to live to put back when this file ends. An /// included file may change all three and none of it escapes into the file /// that included it. saved_origin: dns.Name.Buffer = undefined, saved_origin_len: usize = 0, saved_owner: dns.Name.Buffer = undefined, saved_owner_len: usize = 0, saved_ttl: ?u32 = null, }; pub fn init(gpa: Allocator, reader: *Reader, options: Options) Error!Parser { var self: Parser = .{ .gpa = gpa, .options = options }; errdefer self.deinit(); if (options.origin) |written| { const encoded = name.encodeAbsolute(&self.origin_buffer, written) catch |err| { self.note("the origin \"{s}\" is not a domain name ({s})", .{ written, @errorName(err) }); return err; }; self.origin_len = encoded.message.len; } self.ttl = options.default_ttl; try self.sources.append(gpa, .{ .lexer = .{ .reader = reader }, .file = options.file, }); if (options.diagnostics) |d| d.file = options.file; return self; } pub fn deinit(self: *Parser) void { for (self.sources.items) |*source| source.lexer.deinit(self.gpa); self.sources.deinit(self.gpa); self.image.deinit(self.gpa); self.scratch.deinit(self.gpa); self.tokens.deinit(self.gpa); self.fields.deinit(self.gpa); self.generate_text.deinit(self.gpa); self.generate_spans.deinit(self.gpa); self.* = undefined; } /// The origin in force, which is what a relative name is relative to. pub fn origin(self: *const Parser) ?dns.Name { if (self.origin_len == 0) return null; return .{ .message = self.origin_buffer[0..self.origin_len], .offset = 0 }; } /// The owner of the last record read, which is what an entry beginning with /// whitespace will take. pub fn owner(self: *const Parser) ?dns.Name { if (self.owner_len == 0) return null; return .{ .message = self.owner_buffer[0..self.owner_len], .offset = 0 }; } fn note(self: *Parser, comptime fmt: []const u8, args: anytype) void { if (self.options.diagnostics) |d| d.note(fmt, args); } fn top(self: *Parser) *Source { return &self.sources.items[self.sources.items.len - 1]; } fn text(self: *Parser, token: Lexer.Token) []const u8 { return self.top().lexer.text(token); } /// Hands the parser the file an `$INCLUDE` named. Reading carries on inside it /// and comes back out when it ends. pub fn pushInclude(self: *Parser, reader: *Reader, file: ?[]const u8) Error!void { if (self.sources.items.len > self.options.max_include_depth) { self.note("includes are nested more than {d} deep", .{self.options.max_include_depth}); return error.IncludeTooDeep; } var source: Source = .{ .lexer = .{ .reader = reader }, .file = file, .saved_origin_len = self.origin_len, .saved_owner_len = self.owner_len, .saved_ttl = self.ttl, }; source.saved_origin = self.origin_buffer; source.saved_owner = self.owner_buffer; try self.sources.append(self.gpa, source); // An `$INCLUDE` with an origin sets it for the file it names, and only for // that file. if (self.include_origin_len != 0) { self.origin_buffer = self.include_origin; self.origin_len = self.include_origin_len; self.include_origin_len = 0; } if (self.options.diagnostics) |d| d.file = file; } fn popInclude(self: *Parser) void { var source = self.sources.pop().?; self.origin_buffer = source.saved_origin; self.origin_len = source.saved_origin_len; self.owner_buffer = source.saved_owner; self.owner_len = source.saved_owner_len; self.ttl = source.saved_ttl; source.lexer.deinit(self.gpa); if (self.options.diagnostics) |d| d.file = self.top().file; } /// The next record, or the next `$INCLUDE`, or `null` at the end of the last /// file. pub fn next(self: *Parser) Error!?Item { while (true) { // A `$GENERATE` hands out one record per turn of its range, and the // templates it is working from are the tokens of that entry -- so // nothing may read another entry until the range is spent. if (self.generate != null) { if (try self.generateOne()) |rr| return .{ .record = rr }; self.generate = null; continue; } if (!try self.readEntry()) { // The end of an included file is not the end of the zone. if (self.sources.items.len > 1) { self.popInclude(); continue; } return null; } const first = self.tokens.items[0]; if (self.options.diagnostics) |d| d.at(first.line, first.column); const first_text = self.text(first); if (!first.quoted and first_text.len > 1 and first_text[0] == '$') { if (try self.directive(first_text)) |include| return .{ .include = include }; continue; } return .{ .record = try self.record() }; } } /// Reads one entry's worth of tokens. False at the end of the file. fn readEntry(self: *Parser) Error!bool { const source = self.top(); source.lexer.reset(); self.tokens.clearRetainingCapacity(); while (true) { const token = try source.lexer.next(self.gpa); switch (token.kind) { .string => try self.tokens.append(self.gpa, token), .end_of_entry => if (self.tokens.items.len != 0) return true, .end_of_file => return false, } } } // -- directives ---------------------------------------------------------------- fn directive(self: *Parser, keyword: []const u8) Error!?Include { const arguments = self.tokens.items[1..]; if (std.ascii.eqlIgnoreCase(keyword, "$ORIGIN")) { if (arguments.len != 1) { self.note("$ORIGIN takes one name", .{}); return error.BadDirective; } const argument = self.text(arguments[0]); var buffer: dns.Name.Buffer = undefined; const encoded = name.encode(&buffer, argument, self.origin()) catch |err| { self.note("$ORIGIN {s}: not a domain name ({s})", .{ argument, @errorName(err) }); return err; }; @memcpy(self.origin_buffer[0..encoded.message.len], encoded.message); self.origin_len = encoded.message.len; return null; } if (std.ascii.eqlIgnoreCase(keyword, "$TTL")) { if (arguments.len != 1) { self.note("$TTL takes one time", .{}); return error.BadDirective; } const argument = self.text(arguments[0]); self.ttl = rdata_text.parseTtl(argument) catch { self.note("$TTL {s}: not a time", .{argument}); return error.BadDirective; }; return null; } if (std.ascii.eqlIgnoreCase(keyword, "$INCLUDE")) { if (arguments.len < 1 or arguments.len > 2) { self.note("$INCLUDE takes a file name and an optional origin", .{}); return error.BadDirective; } if (self.options.includes == .refuse) { self.note("$INCLUDE, and this parser was not told what to do about one", .{}); return error.IncludeNotAllowed; } self.include_origin_len = 0; var included_origin: ?dns.Name = null; if (arguments.len == 2) { const argument = self.text(arguments[1]); const encoded = name.encode( &self.include_origin, argument, self.origin(), ) catch |err| { self.note("$INCLUDE origin {s}: not a domain name ({s})", .{ argument, @errorName(err), }); return err; }; self.include_origin_len = encoded.message.len; included_origin = encoded; } return .{ .path = self.text(arguments[0]), .origin = included_origin }; } if (std.ascii.eqlIgnoreCase(keyword, "$GENERATE")) { try self.generateDirective(); return null; } self.note("no directive is called {s}", .{keyword}); return error.UnknownDirective; } // -- $GENERATE ----------------------------------------------------------------- const Span = struct { start: u32, len: u32 }; /// A `$GENERATE` part way through its range. The templates are the entry's own /// tokens, held as indices because that entry is not read again until the /// range is spent. const Generate = struct { current: i64, stop: i64, step: i64, /// Which token is the owner name template. lhs: usize, /// Which token the record data template starts at. rhs: usize, ttl: u32, class: dns.Class, type: dns.Type, }; /// `$GENERATE range lhs [ttl] [class] type rhs`, which is BIND's rather than /// anybody's standard, and is how a reverse zone of 254 near-identical `ptr` /// records is written as one line. fn generateDirective(self: *Parser) Error!void { if (self.tokens.items.len < 4) { self.note("$GENERATE takes a range, an owner, a type and the data", .{}); return error.BadGenerate; } const range = self.text(self.tokens.items[1]); var i: usize = 3; const what = try self.typeAndClass(&i); if (i >= self.tokens.items.len) { self.note("$GENERATE has no record data to make records out of", .{}); return error.BadGenerate; } // start-stop, or start-stop/step. const dash = std.mem.indexOfScalar(u8, range, '-') orelse { self.note("$GENERATE {s}: a range is start-stop or start-stop/step", .{range}); return error.BadGenerate; }; var rest = range[dash + 1 ..]; var step: i64 = 1; if (std.mem.indexOfScalar(u8, rest, '/')) |slash| { step = std.fmt.parseInt(i64, rest[slash + 1 ..], 10) catch { self.note("$GENERATE {s}: the step is not a number", .{range}); return error.BadGenerate; }; rest = rest[0..slash]; } const start = std.fmt.parseInt(i64, range[0..dash], 10) catch { self.note("$GENERATE {s}: the start is not a number", .{range}); return error.BadGenerate; }; const stop = std.fmt.parseInt(i64, rest, 10) catch { self.note("$GENERATE {s}: the stop is not a number", .{range}); return error.BadGenerate; }; if (step < 1 or stop < start) { self.note("$GENERATE {s}: the range does not count upwards", .{range}); return error.BadGenerate; } self.generate = .{ .current = start, .stop = stop, .step = step, .lhs = 2, .rhs = i, .ttl = what.ttl, .class = what.class, .type = what.type, }; } /// The next record of the range, or `null` when it is spent. fn generateOne(self: *Parser) Error!?dns.Record { const generate = &self.generate.?; if (generate.current > generate.stop) return null; const value = generate.current; generate.current += generate.step; self.generate_text.clearRetainingCapacity(); self.generate_spans.clearRetainingCapacity(); for (self.tokens.items[generate.lhs .. generate.lhs + 1]) |token| { try self.expand(self.text(token), value); } for (self.tokens.items[generate.rhs..]) |token| { try self.expand(self.text(token), value); } const spans = self.generate_spans.items; const owner_text = self.generate_text.items[spans[0].start..][0..spans[0].len]; var buffer: dns.Name.Buffer = undefined; const encoded = name.encode(&buffer, owner_text, self.origin()) catch |err| { self.note("$GENERATE made \"{s}\", which is not a domain name ({s})", .{ owner_text, @errorName(err), }); return err; }; @memcpy(self.owner_buffer[0..encoded.message.len], encoded.message); self.owner_len = encoded.message.len; self.fields.clearRetainingCapacity(); for (spans[1..], self.tokens.items[generate.rhs..]) |span, token| { try self.fields.append(self.gpa, .{ .text = self.generate_text.items[span.start..][0..span.len], .quoted = token.quoted, }); } return try self.build(generate.type, generate.class, generate.ttl); } /// Substitutes the iterator's value into one template, appending the result to /// `generate_text` and recording where it went. /// /// `$` is the value, `${offset,width,radix}` is the value shifted and /// formatted, and a backslash escapes whatever follows it -- including a `$` /// that is meant to stay one, which is passed through still escaped so that /// whoever reads the field next undoes it as they would any other escape. fn expand(self: *Parser, template: []const u8, value: i64) Error!void { const start: u32 = @intCast(self.generate_text.items.len); var i: usize = 0; while (i < template.len) { const c = template[i]; if (c == '\\') { if (i + 1 >= template.len) return error.BadEscape; try self.generate_text.appendSlice(self.gpa, template[i..][0..2]); i += 2; continue; } if (c != '$') { try self.generate_text.append(self.gpa, c); i += 1; continue; } i += 1; var offset: i64 = 0; var width: usize = 0; var radix: u8 = 'd'; if (i < template.len and template[i] == '{') { const end = std.mem.indexOfScalarPos(u8, template, i, '}') orelse { self.note("$GENERATE: a ${{ with no }}", .{}); return error.BadGenerate; }; var parts = std.mem.splitScalar(u8, template[i + 1 .. end], ','); const offset_text = parts.next() orelse ""; if (offset_text.len != 0) { offset = std.fmt.parseInt(i64, offset_text, 10) catch { self.note("$GENERATE: \"{s}\" is not an offset", .{offset_text}); return error.BadGenerate; }; } if (parts.next()) |width_text| { if (width_text.len != 0) { width = std.fmt.parseUnsigned(u8, width_text, 10) catch { self.note("$GENERATE: \"{s}\" is not a width", .{width_text}); return error.BadGenerate; }; } } if (parts.next()) |radix_text| { if (radix_text.len != 1) { self.note("$GENERATE: \"{s}\" is not one of d, o, x, X, n, N", .{radix_text}); return error.BadGenerate; } radix = radix_text[0]; } if (parts.next() != null) { self.note("$GENERATE: a ${{}} takes an offset, a width and a radix", .{}); return error.BadGenerate; } i = end + 1; } const shifted = std.math.add(i64, value, offset) catch { self.note("$GENERATE: the offset takes the value out of range", .{}); return error.BadGenerate; }; if (shifted < 0) { self.note("$GENERATE: the offset takes the value below zero", .{}); return error.BadGenerate; } try self.format(@intCast(shifted), width, radix); } try self.generate_spans.append(self.gpa, .{ .start = start, .len = @intCast(self.generate_text.items.len - start), }); } /// One substituted value, in the radix the template asked for. fn format(self: *Parser, value: u64, width: usize, radix: u8) Error!void { var buffer: [128]u8 = undefined; const written = switch (radix) { 'd' => std.fmt.bufPrint(&buffer, "{d}", .{value}), 'o' => std.fmt.bufPrint(&buffer, "{o}", .{value}), 'x' => std.fmt.bufPrint(&buffer, "{x}", .{value}), 'X' => std.fmt.bufPrint(&buffer, "{X}", .{value}), // The nibble form, which exists for `ip6.arpa`: one hexadecimal digit // per label, least significant first, which is the order that tree is // written in. 'n', 'N' => blk: { var out: usize = 0; var left = value; var nibbles: usize = 0; while (nibbles < @max(width, 1) or left != 0) : (nibbles += 1) { if (out != 0) { buffer[out] = '.'; out += 1; } const digit: u4 = @truncate(left); buffer[out] = if (radix == 'n') "0123456789abcdef"[digit] else "0123456789ABCDEF"[digit]; out += 1; left >>= 4; } break :blk buffer[0..out]; }, else => { self.note("$GENERATE: \"{c}\" is not one of d, o, x, X, n, N", .{radix}); return error.BadGenerate; }, } catch { self.note("$GENERATE: the substituted value does not fit", .{}); return error.BadGenerate; }; // The nibble form has already spent the width on how many nibbles to // write; everything else pads with zeros on the left. if (radix != 'n' and radix != 'N') { var pad = width -| written.len; while (pad > 0) : (pad -= 1) try self.generate_text.append(self.gpa, '0'); } try self.generate_text.appendSlice(self.gpa, written); } // -- records ------------------------------------------------------------------- fn record(self: *Parser) Error!dns.Record { var i: usize = 0; // An entry that begins in the first column names an owner; one that begins // with whitespace is another record for the owner above it. if (!self.tokens.items[0].leading_whitespace) { const owner_text = self.text(self.tokens.items[0]); var buffer: dns.Name.Buffer = undefined; const encoded = name.encode(&buffer, owner_text, self.origin()) catch |err| { self.note("the owner \"{s}\" is not a domain name ({s})", .{ owner_text, @errorName(err), }); return err; }; @memcpy(self.owner_buffer[0..encoded.message.len], encoded.message); self.owner_len = encoded.message.len; i = 1; } else if (self.owner_len == 0) { self.note("this entry takes the owner of the one above it, and it is the first", .{}); return error.NoPreviousOwner; } const what = try self.typeAndClass(&i); self.fields.clearRetainingCapacity(); for (self.tokens.items[i..]) |token| { try self.fields.append(self.gpa, .{ .text = self.text(token), .quoted = token.quoted, }); } return self.build(what.type, what.class, what.ttl); } const Preamble = struct { ttl: u32, class: dns.Class, type: dns.Type, }; /// The time to live, the class and the type, in that order or with the first /// two the other way round or missing. Neither can be confused with a type: a /// type is never a number, and no class is spelled like one. /// /// `i` is left at the first field of the record data. fn typeAndClass(self: *Parser, i: *usize) Error!Preamble { var explicit_ttl: ?u32 = null; var class: ?dns.Class = null; while (i.* < self.tokens.items.len) { const token_text = self.text(self.tokens.items[i.*]); if (explicit_ttl == null and looksLikeTtl(token_text)) { explicit_ttl = rdata_text.parseTtl(token_text) catch { self.note("\"{s}\" is not a time to live", .{token_text}); return error.BadNumber; }; i.* += 1; continue; } if (class == null) { if (dns.Class.fromName(token_text)) |found| { class = found; i.* += 1; continue; } } break; } if (i.* >= self.tokens.items.len) { self.note("the entry ends before it says what type of record it is", .{}); return error.MissingType; } const type_text = self.text(self.tokens.items[i.*]); const record_type = dns.Type.fromName(type_text) orelse { self.note("no record type is called \"{s}\"", .{type_text}); return error.UnknownType; }; i.* += 1; return .{ .ttl = explicit_ttl orelse self.ttl orelse { self.note("no time to live, and the file has had no $TTL", .{}); return error.MissingTtl; }, .class = class orelse self.options.default_class, .type = record_type, }; } /// Assembles the record in wire form and reads it back as a `dns.Record`. /// /// Reading it back is not a formality. The bytes were written field by field /// from text; decoding them is the only thing that checks the record as a /// whole -- that its length agrees with its type, that a `svcb` does not /// require a parameter it left out, that a `\#` for a known type holds what /// that type needs. fn build(self: *Parser, record_type: dns.Type, class: dns.Class, ttl: u32) Error!dns.Record { self.image.clearRetainingCapacity(); try self.image.appendSlice(self.gpa, self.owner_buffer[0..self.owner_len]); try appendInt(self.gpa, &self.image, u16, @intFromEnum(record_type)); try appendInt(self.gpa, &self.image, u16, @intFromEnum(class)); try appendInt(self.gpa, &self.image, u32, ttl); const length_at = self.image.items.len; try appendInt(self.gpa, &self.image, u16, 0); try rdata_text.encode( self.gpa, &self.image, &self.scratch, record_type, self.fields.items, self.origin(), self.options.diagnostics, ); const length = self.image.items.len - length_at - 2; if (length > std.math.maxInt(u16)) return error.RdataTooLong; std.mem.writeInt(u16, self.image.items[length_at..][0..2], @intCast(length), .big); // A record longer than a message could carry is refused here rather than // by whatever tries to send it: it has an owner name and 65535 bytes of // data, and there is nowhere it could go. var decoder = dns.wire.Decoder.init(self.image.items) catch { self.note("the record is {d} bytes, and 65535 is the most", .{self.image.items.len}); return error.RecordTooLong; }; const parsed = try dns.Record.parse(&decoder); std.debug.assert(decoder.atEnd()); if (self.options.validate) { const data = parsed.data() catch |err| { self.note("the data is not what a {f} record holds ({s})", .{ record_type, @errorName(err), }); return err; }; // And that it is a record which could be written down again. See // `rdata_text.representable`: a handful of shapes are readable off the // wire and unwritable as text, and accepting one would mean this // library held a record it could not hand back. if (rdata_text.representable(data)) |why| { self.note("{s}, which cannot be written in a zone file", .{why}); return error.NotWritableAsText; } } // RFC 2308 §4: without a `$TTL` the `soa`'s own minimum becomes the // default, which is what BIND falls back on and what a zone file written // before 1998 relies on. if (self.ttl == null and record_type == .soa) { if (parsed.data()) |data| { self.ttl = data.soa.minimum; } else |_| {} } return parsed; } fn appendInt(gpa: Allocator, out: *std.ArrayList(u8), comptime T: type, value: T) !void { var buffer: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined; std.mem.writeInt(T, &buffer, value, .big); try out.appendSlice(gpa, &buffer); } /// Whether a token is in the place a time to live goes and is shaped like one. /// A type mnemonic never is: it does not begin with a digit. fn looksLikeTtl(token_text: []const u8) bool { if (token_text.len == 0) return false; if (!std.ascii.isDigit(token_text[0])) return false; _ = rdata_text.parseTtl(token_text) catch return false; return true; } // -- tests --------------------------------------------------------------------- const testing = std.testing; /// Every record of a zone file, printed the way `dns` prints one, joined by /// newlines -- which is the shortest way to say what a parse produced. fn parseToText(gpa: Allocator, input: []const u8, options: Options) ![]u8 { var reader = Reader.fixed(input); var parser = try Parser.init(gpa, &reader, options); defer parser.deinit(); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); while (try parser.next()) |item| switch (item) { .record => |rr| try out.writer.print("{f}\n", .{rr}), .include => |include| try out.writer.print("$INCLUDE {s}\n", .{include.path}), }; return gpa.dupe(u8, out.written()); } fn expectParses(expected: []const u8, input: []const u8, options: Options) !void { const gpa = testing.allocator; var diagnostics: Diagnostics = .{}; var with = options; with.diagnostics = &diagnostics; const actual = parseToText(gpa, input, with) catch |err| { std.debug.print("{s}: {f}\n", .{ @errorName(err), diagnostics }); return err; }; defer gpa.free(actual); try testing.expectEqualStrings(expected, actual); } fn expectFails(input: []const u8, options: Options, expected: anyerror) !void { const gpa = testing.allocator; try testing.expectError(expected, parseToText(gpa, input, options)); } test "the shape of an entry" { try expectParses( "www.example.com.\t3600\tIN\tA\t192.0.2.1\n", "www 3600 IN A 192.0.2.1\n", .{ .origin = "example.com." }, ); // The class and the time to live are optional and may be either way round. try expectParses( "www.example.com.\t300\tIN\tA\t192.0.2.1\n", "www IN 300 A 192.0.2.1\n", .{ .origin = "example.com.", .default_ttl = 3600 }, ); try expectParses( "www.example.com.\t3600\tIN\tA\t192.0.2.1\n", "www A 192.0.2.1\n", .{ .origin = "example.com.", .default_ttl = 3600 }, ); try expectParses( "www.example.com.\t3600\tCH\tA\t192.0.2.1\n", "www CH A 192.0.2.1\n", .{ .origin = "example.com.", .default_ttl = 3600 }, ); } test "an entry beginning with whitespace takes the owner above it" { try expectParses( "www.example.com.\t60\tIN\tA\t192.0.2.1\n" ++ "www.example.com.\t60\tIN\tA\t192.0.2.2\n" ++ "www.example.com.\t60\tIN\tAAAA\t2001:db8::1\n", \\www A 192.0.2.1 \\ A 192.0.2.2 \\ AAAA 2001:db8::1 \\ , .{ .origin = "example.com.", .default_ttl = 60 }, ); try expectFails(" A 192.0.2.1\n", .{ .origin = "x.", .default_ttl = 1 }, error.NoPreviousOwner); } test "the origin, and the @ that stands for it" { try expectParses( "example.com.\t60\tIN\tNS\tns1.example.com.\n" ++ "other.test.\t60\tIN\tNS\tns1.other.test.\n", \\@ NS ns1 \\$ORIGIN other.test. \\@ NS ns1 \\ , .{ .origin = "example.com.", .default_ttl = 60 }, ); // A $ORIGIN that is itself relative is relative to the one before it. try expectParses( "www.sub.example.com.\t60\tIN\tA\t192.0.2.1\n", \\$ORIGIN sub \\www A 192.0.2.1 \\ , .{ .origin = "example.com.", .default_ttl = 60 }, ); try expectFails("www A 192.0.2.1\n", .{ .default_ttl = 60 }, error.NoOrigin); } test "$TTL, and the soa minimum a file without one falls back on" { try expectParses( "example.com.\t7200\tIN\tNS\tns1.example.com.\n" ++ "example.com.\t300\tIN\tNS\tns2.example.com.\n", \\$TTL 2h \\@ NS ns1 \\@ 300 NS ns2 \\ , .{ .origin = "example.com." }, ); try expectParses( "example.com.\t60\tIN\tSOA\tns1.example.com. hostmaster.example.com. 1 7200 3600 604800 900\n" ++ "example.com.\t900\tIN\tNS\tns1.example.com.\n", \\@ 60 SOA ns1 hostmaster 1 2h 1h 1w 15m \\@ NS ns1 \\ , .{ .origin = "example.com." }, ); try expectFails("@ NS ns1\n", .{ .origin = "example.com." }, error.MissingTtl); } test "an soa written across lines, with comments in it" { try expectParses( "example.com.\t3600\tIN\tSOA\tns1.example.com. hostmaster.example.com. " ++ "2024010101 7200 3600 1209600 3600\n", \\$TTL 1h \\@ IN SOA ns1.example.com. hostmaster.example.com. ( \\ 2024010101 ; serial \\ 2h ; refresh \\ 1h ; retry \\ 2w ; expire \\ 1h ) ; negative caching \\ , .{ .origin = "example.com." }, ); } test "$INCLUDE is reported and the caller decides" { try expectFails( "$INCLUDE other.zone\n", .{ .origin = "example.com.", .default_ttl = 60 }, error.IncludeNotAllowed, ); try expectParses( "$INCLUDE other.zone\n", "$INCLUDE other.zone\n", .{ .origin = "example.com.", .default_ttl = 60, .includes = .report }, ); } test "an included file is read with the origin the directive gave it" { const gpa = testing.allocator; var outer = Reader.fixed( \\$TTL 60 \\@ NS ns1 \\$INCLUDE sub.zone sub \\@ NS ns2 \\ ); var parser = try Parser.init(gpa, &outer, .{ .origin = "example.com.", .includes = .report, }); defer parser.deinit(); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); var inner = Reader.fixed( \\$TTL 30 \\www A 192.0.2.1 \\ ); while (try parser.next()) |item| switch (item) { .record => |rr| try out.writer.print("{f}\n", .{rr}), .include => |include| { try testing.expectEqualStrings("sub.zone", include.path); try testing.expectFmt("sub.example.com.", "{f}", .{include.origin.?}); try parser.pushInclude(&inner, include.path); }, }; // The included file's own $TTL and $ORIGIN do not escape it, and neither // does the owner name it left behind. try testing.expectEqualStrings( "example.com.\t60\tIN\tNS\tns1.example.com.\n" ++ "www.sub.example.com.\t30\tIN\tA\t192.0.2.1\n" ++ "example.com.\t60\tIN\tNS\tns2.example.com.\n", out.written(), ); } test "what a bad entry says" { const gpa = testing.allocator; var diagnostics: Diagnostics = .{}; var reader = Reader.fixed( \\$TTL 60 \\@ IN A 192.0.2.1 \\www IN A nonsense \\ ); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com.", .file = "example.zone", .diagnostics = &diagnostics, }); defer parser.deinit(); _ = try parser.next(); try testing.expectError(error.BadAddress, parser.next()); try testing.expectFmt( "example.zone:3:1: the address is not an IPv4 address: \"nonsense\"", "{f}", .{diagnostics}, ); } test "the directives that are not" { try expectFails("$NOPE x\n", .{ .origin = "x." }, error.UnknownDirective); try expectFails("$TTL\n", .{ .origin = "x." }, error.BadDirective); try expectFails("$TTL soon\n", .{ .origin = "x." }, error.BadDirective); try expectFails("$ORIGIN a. b.\n", .{ .origin = "x." }, error.BadDirective); } test "a type nobody has a name for, and one nobody has a parser for" { try expectParses( "example.com.\t60\tIN\tTYPE65280\t\\# 3 010203\n", "@ TYPE65280 \\# 3 010203\n", .{ .origin = "example.com.", .default_ttl = 60 }, ); try expectFails( "@ NOSUCHTYPE 1\n", .{ .origin = "example.com.", .default_ttl = 60 }, error.UnknownType, ); } test "$GENERATE, one line standing in for a hundred" { try expectParses( "1.2.0.192.in-addr.arpa.\t3600\tIN\tPTR\thost-1.example.com.\n" ++ "2.2.0.192.in-addr.arpa.\t3600\tIN\tPTR\thost-2.example.com.\n" ++ "3.2.0.192.in-addr.arpa.\t3600\tIN\tPTR\thost-3.example.com.\n", \\$GENERATE 1-3 $ PTR host-$.example.com. \\ , .{ .origin = "2.0.192.in-addr.arpa.", .default_ttl = 3600 }, ); } test "$GENERATE with an offset, a width and a radix" { try expectParses( "host-010.example.com.\t60\tIN\tA\t10.0.0.1\n" ++ "host-011.example.com.\t60\tIN\tA\t10.0.0.2\n", \\$GENERATE 1-2 host-${9,3,d} A 10.0.0.$ \\ , .{ .origin = "example.com.", .default_ttl = 60 }, ); // The nibble radix, which exists for ip6.arpa: one hexadecimal digit per // label, least significant first. try expectParses( "e.0.ip6.arpa.\t60\tIN\tPTR\ta.example.com.\n" ++ "f.0.ip6.arpa.\t60\tIN\tPTR\ta.example.com.\n", \\$GENERATE 14-15 ${0,2,n} PTR a.example.com. \\ , .{ .origin = "ip6.arpa.", .default_ttl = 60 }, ); } test "$GENERATE counts by its step, and an escaped dollar is not one" { try expectParses( "a1.example.com.\t60\tIN\tTXT\t\"$\"\n" ++ "a3.example.com.\t60\tIN\tTXT\t\"$\"\n" ++ "a5.example.com.\t60\tIN\tTXT\t\"$\"\n", \\$GENERATE 1-5/2 a$ TXT "\$" \\ , .{ .origin = "example.com.", .default_ttl = 60 }, ); } test "a $GENERATE that is not one" { const options: Options = .{ .origin = "example.com.", .default_ttl = 60 }; try expectFails("$GENERATE 1 a$ A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 5-1 a$ A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2/0 a$ A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a$ A\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a${0,3 A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a${0,3,z} A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 ${-9} A 10.0.0.1\n", options, error.BadGenerate); } test "a record that could be read and could not be written is refused" { const options: Options = .{ .origin = "example.com.", .default_ttl = 60 }; // A hip with no host identity tag: legal on the wire, and the // presentation form has no way to say "nothing here" for a field in the // middle of a record. try expectFails("@ HIP \\# 4 00020000\n", options, error.NotWritableAsText); // A caa with no tag, for the same reason: the tag is written unquoted, so // an empty one disappears and the value moves up into its place. try expectFails("@ CAA \\# 2 0000\n", options, error.NotWritableAsText); // And the shapes that are merely unusual are not refused: a ds with no // digest and a txt with no strings are both writable and both come back. try expectParses( "example.com.\t60\tIN\tDS\t258 3 4 \n", "@ DS \\# 4 01020304\n", options, ); try expectParses("example.com.\t60\tIN\tTXT\t\n", "@ TXT \\# 0\n", options); } test "a record too long to carry" { const gpa = testing.allocator; // 65535 bytes of data is legal on its own and cannot be, once an owner // name and ten bytes of header are in front of it. var input: std.ArrayList(u8) = .empty; defer input.deinit(gpa); try input.appendSlice(gpa, "@ TYPE65280 \\# 65535 "); try input.appendNTimes(gpa, 'a', 65535 * 2); try input.append(gpa, '\n'); try testing.expectError(error.RecordTooLong, parseToText(gpa, input.items, .{ .origin = "example.com.", .default_ttl = 60, })); }