Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A zone file, one record at a time.//!//! ```zig//! var parser = try 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//! some of it is readable while parsing: `origin` 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.ttl: ?u32 = null,/// What a record without a time to live gets when there is no `$TTL`: the/// last one a record stated (RFC 1035 §5.1), or before any had, the `minimum`/// of an `soa` that stated none either.last_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` and no default /// from the caller, before any record has stated one -- and not an `soa`, /// which would take its own `minimum`. 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,};
/// A parser reading from `reader`, which has to outlive it. Fails only if/// `options.origin` is not a domain name, or for want of memory.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;}
/// Frees everything the parser holds, including the record `next` last/// returned. The readers are the caller's and are left alone.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, or/// `null` before one is known. It borrows the parser.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, or `null` before the first. It borrows the parser.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, with the origin, owner and `$TTL` of the/// including file put back. `reader` has to outlive the parser; `file` is/// what to call it in a diagnostic. Includes nested deeper than/// `options.max_include_depth` fail with `error.IncludeTooDeep`.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() }; }}
/// Says what the lexer refused and where. The entry it was reading never/// finished, so nothing has called `at` for it yet.fn lexerFailed(self: *Parser, lexer: *const Lexer, err: Lexer.Error) void { const d = self.options.diagnostics orelse return; switch (err) { error.UnbalancedParentheses => d.note("a parenthesis is still open at the end of the file", .{}), error.UnexpectedParenthesis => d.note("a \")\" with no \"(\" before it", .{}), error.UnterminatedString => d.note("a quoted string that is not closed on the line it began on", .{}), error.BadEscape => d.note("a backslash with nothing after it", .{}), else => return, } d.at(lexer.failed_line, lexer.failed_column);}
/// 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 = source.lexer.next(self.gpa) catch |err| { self.lexerFailed(&source.lexer, err); return err; }; 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 = decimal(i64, rest[slash + 1 ..]) catch { self.note("$GENERATE {s}: the step is not a number", .{range}); return error.BadGenerate; }; rest = rest[0..slash]; } const start = decimal(i64, range[0..dash]) catch { self.note("$GENERATE {s}: the start is not a number", .{range}); return error.BadGenerate; }; const stop = decimal(i64, rest) 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. `$$`/// is a `$` that stays one too, which BIND still reads for the sake of zone/// files written before the backslash was.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; } if (i + 1 < template.len and template[i + 1] == '$') { try self.generate_text.appendSlice(self.gpa, "\\$"); i += 2; 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 = decimal(i64, offset_text) 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 = decimal(u8, width_text) catch 255; // BIND formats into 128 bytes, terminator included, and // refuses anything wider. if (width > max_generate_width) { self.note("$GENERATE: \"{s}\" is not a width of at most {d}", .{ width_text, max_generate_width, }); 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.const max_generate_width = 127;
fn format(self: *Parser, value: u64, width: usize, radix: u8) Error!void { // Wide enough for any width allowed and for any value: a u64 is twenty // decimal digits, or sixteen nibbles and the dots between them. var buffer: [max_generate_width]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. The width counts characters, dots and all, so an even // one ends in a dot -- this is BIND's `nibbles()` step for step. 'n', 'N' => blk: { var out: usize = 0; var left = value; var remaining = width; while (true) { const digit: u4 = @truncate(left); buffer[out] = if (radix == 'n') "0123456789abcdef"[digit] else "0123456789ABCDEF"[digit]; out += 1; left >>= 4; remaining -|= 1; if (remaining > 0 or left != 0) { buffer[out] = '.'; out += 1; remaining -|= 1; } if (left == 0 and remaining == 0) break; } 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; 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 { /// `null` only for an `soa` that has nothing to inherit, which takes its /// own `minimum` once its data has been read. 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;
// A `$TTL` wins over whatever came before it. Without one, a record // takes the time to live the last record stated, as RFC 1035 §5.1 has it // and as BIND and dnspython both do. if (explicit_ttl) |stated| self.last_ttl = stated; const ttl = explicit_ttl orelse self.ttl orelse self.last_ttl; if (ttl == null and record_type != .soa) { self.note("no time to live, and the file has had no $TTL", .{}); return error.MissingTtl; }
return .{ .ttl = ttl, .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, @backingInt(record_type)); try appendInt(self.gpa, &self.image, u16, @backingInt(class)); const ttl_at = self.image.items.len; try appendInt(self.gpa, &self.image, u32, ttl orelse 0); 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);
// RFC 2308 §4: an `soa` with no time to live and nothing to inherit one // from takes its own `minimum`, the last thing in its data, and so does // every record after it until one says otherwise. It is what BIND falls // back on, and what a zone file written before 1998 relies on. if (ttl == null) { std.debug.assert(record_type == .soa); if (length < 4) { self.note("an soa ends with five numbers", .{}); return error.MissingField; } const minimum = self.image.items[self.image.items.len - 4 ..][0..4]; @memcpy(self.image.items[ttl_at..][0..4], minimum); self.last_ttl = std.mem.readInt(u32, minimum, .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; } }
return parsed;}
/// A number in a `$GENERATE`: ASCII digits, and a `-` in front of one that may/// be negative. Zig's own parser also takes a `+` and a `_` between digits,/// neither of which BIND does.fn decimal(comptime T: type, written: []const u8) !T { const digits = if (@typeInfo(T).int.signedness == .signed and written.len != 0 and written[0] == '-') written[1..] else written; if (digits.len == 0) return error.InvalidCharacter; for (digits) |c| if (!std.ascii.isDigit(c)) return error.InvalidCharacter; return std.fmt.parseInt(T, written, 10);}
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;
test init { const gpa = testing.allocator; var reader: Reader = .fixed("www A 192.0.2.1\n"); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com.", .default_ttl = 3600, }); defer parser.deinit();
const rr = (try parser.next()).?.record; try testing.expectFmt("www.example.com.", "{f}", .{rr.name}); try testing.expectEqual(@as(u32, 3600), rr.ttl);}
test deinit { const gpa = testing.allocator; var reader: Reader = .fixed("$TTL 1h\n@ NS ns1\n"); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com." }); _ = try parser.next(); parser.deinit();}
test origin { const gpa = testing.allocator; var reader: Reader = .fixed( \\$TTL 1h \\www A 192.0.2.1 \\$ORIGIN example.net. \\www A 192.0.2.2 \\ ); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com." }); defer parser.deinit();
try testing.expectFmt("example.com.", "{f}", .{parser.origin().?}); _ = try parser.next(); _ = try parser.next(); try testing.expectFmt("example.net.", "{f}", .{parser.origin().?});}
test owner { const gpa = testing.allocator; var reader: Reader = .fixed( \\$TTL 1h \\www A 192.0.2.1 \\ AAAA 2001:db8::1 \\ ); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com." }); defer parser.deinit();
try testing.expectEqual(null, parser.owner()); _ = try parser.next(); // The indented entry will take this one. try testing.expectFmt("www.example.com.", "{f}", .{parser.owner().?}); const rr = (try parser.next()).?.record; try testing.expectFmt("www.example.com.", "{f}", .{rr.name});}
test pushInclude { const gpa = testing.allocator; var reader: Reader = .fixed( \\$TTL 1h \\$INCLUDE hosts.zone \\mail A 192.0.2.25 \\ ); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com.", .includes = .report, }); defer parser.deinit();
const include = (try parser.next()).?.include; try testing.expectEqualStrings("hosts.zone", include.path); // Wherever the file comes from, it arrives as a reader. var included: Reader = .fixed("www A 192.0.2.80\n"); try parser.pushInclude(&included, "hosts.zone");
try testing.expectFmt("www.example.com.", "{f}", .{(try parser.next()).?.record.name}); try testing.expectFmt("mail.example.com.", "{f}", .{(try parser.next()).?.record.name}); try testing.expectEqual(null, try parser.next());}
test next { const gpa = testing.allocator; var reader: Reader = .fixed( \\$TTL 1h \\@ SOA ns1 hostmaster 1 2h 1h 2w 1h \\$GENERATE 1-3 host$ A 192.0.2.$ \\ ); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com." }); defer parser.deinit();
var count: usize = 0; while (try parser.next()) |item| switch (item) { .record => count += 1, .include => unreachable, }; try testing.expectEqual(@as(usize, 4), count);}
/// 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 what 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." }, ); // Without a $TTL, the last time to live a record stated, as BIND does -- // not the soa's minimum, once anything has said otherwise. try expectParses( "example.com.\t60\tIN\tSOA\tns1.example.com. hostmaster.example.com. 1 7200 3600 604800 900\n" ++ "example.com.\t60\tIN\tNS\tns1.example.com.\n" ++ "a.example.com.\t30\tIN\tA\t192.0.2.1\n" ++ "b.example.com.\t30\tIN\tA\t192.0.2.2\n", \\@ 60 SOA ns1 hostmaster 1 2h 1h 1w 15m \\@ NS ns1 \\a 30 A 192.0.2.1 \\b A 192.0.2.2 \\ , .{ .origin = "example.com." }, ); // An soa with nothing to inherit takes its own minimum, and so does what // follows it. try expectParses( "example.com.\t900\tIN\tSOA\tns1.example.com. hostmaster.example.com. 1 7200 3600 604800 900\n" ++ "example.com.\t900\tIN\tNS\tns1.example.com.\n", \\@ SOA ns1 hostmaster 1 2h 1h 1w 15m \\@ NS ns1 \\ , .{ .origin = "example.com." }, ); // A $TTL, once there is one, wins over the last record's. try expectParses( "a.example.com.\t30\tIN\tA\t192.0.2.1\n" ++ "b.example.com.\t30\tIN\tA\t192.0.2.2\n" ++ "c.example.com.\t60\tIN\tA\t192.0.2.3\n", \\a 30 A 192.0.2.1 \\b A 192.0.2.2 \\$TTL 60 \\c A 192.0.2.3 \\ , .{ .origin = "example.com." }, ); try expectFails("@ NS ns1\n", .{ .origin = "example.com." }, error.MissingTtl); try expectFails("@ SOA \\# 0\n", .{ .origin = "example.com." }, error.MissingField);}
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 "what a token the lexer refuses says, and where" { const gpa = testing.allocator; const cases = [_]struct { []const u8, anyerror, []const u8 }{ .{ "@ IN A 192.0.2.1\nwww IN TXT \"no end\n@ IN A 192.0.2.2\n", error.UnterminatedString, "2:12: a quoted string that is not closed on the line it began on", }, .{ "@ IN A 192.0.2.1\nwww IN A ( 192.0.2.2\n", error.UnbalancedParentheses, "3:1: a parenthesis is still open at the end of the file", }, .{ "@ IN A 192.0.2.1\nwww IN A 192.0.2.2 )\n", error.UnexpectedParenthesis, "2:20: a \")\" with no \"(\" before it", }, .{ "@ IN TXT a\\", error.BadEscape, "1:10: a backslash with nothing after it" }, }; for (cases) |case| { var diagnostics: Diagnostics = .{}; var reader = Reader.fixed(case[0]); var parser = try Parser.init(gpa, &reader, .{ .origin = "example.com.", .default_ttl = 60, .diagnostics = &diagnostics, }); defer parser.deinit(); while (parser.next()) |item| { if (item == null) return error.TestExpectedError; } else |err| try testing.expectEqual(case[1], err); try testing.expectFmt(case[2], "{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. The width is in characters, dots // included, as BIND counts it. 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,3,n} PTR a.example.com. \\ , .{ .origin = "ip6.arpa.", .default_ttl = 60 }, ); // So an even one ends in a dot, which is how BIND's own examples join it // to what follows. try expectParses( "a.0.ip6.arpa.\t60\tIN\tPTR\ta.example.com.\n" ++ "c.2.1.ip6.arpa.\t60\tIN\tPTR\ta.example.com.\n", \\$GENERATE 10-10 ${0,4,n}ip6.arpa. PTR a.example.com. \\$GENERATE 300-300 ${0,1,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 }, ); // And neither is a doubled one, which is the older way to write it. try expectParses( "a\\$1.example.com.\t60\tIN\tTXT\t\"$\"\n", \\$GENERATE 1-1 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); // Zig's number parser takes these, and a zone file does not. try expectFails("$GENERATE 1-1_0 a$ A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE +1-2 a$ A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a${+1} A 10.0.0.1\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a${0,1_0} A 10.0.0.1\n", options, error.BadGenerate); // BIND's limit on a width, which is also what keeps the nibble form inside // its buffer: the fuzzer found 255 of them overrunning it. try expectFails("$GENERATE 1-2 a TXT ${0,128,d}\n", options, error.BadGenerate); try expectFails("$GENERATE 1-2 a TXT ${0,255,n}\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 would be one too, since the tag is written unquoted, // but `dns` refuses that before it gets this far. try expectFails("@ CAA \\# 2 0000\n", options, error.MalformedRdata); // And the shapes that are merely unusual are not refused: a ds with no // digest is writable and comes back. try expectParses( "example.com.\t60\tIN\tDS\t258 3 4 \n", "@ DS \\# 4 01020304\n", options, ); // An apl item of a family RFC 3123 gives no name to is written in // hexadecimal, and reads back as the same record. try expectParses( "example.com.\t60\tIN\tAPL\t3:e0/4\n", "@ APL \\# 5 0003 04 01 e0\n", options, ); // A txt with no strings is not one: RFC 1035 §3.3.14 asks for at least one. try expectFails("@ TXT \\# 0\n", options, error.MalformedRdata);}
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, }));}