Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A zone: an origin and the records under it, in the order they were written.//!//! ```zig//! var z = try zone.Zone.parse(gpa, &reader, .{ .origin = "example.com." });//! defer z.deinit();//!//! try z.addText("www 3600 IN A 192.0.2.1", .{});//! _ = z.removeRrset(dns.Name.literal("old.example.com"), .a);//! try z.write(&out.writer, .{});//! ```//!//! **A record is a `dns.Record` over bytes this zone owns**, in exactly the//! form a message carries: owner name, type, class, time to live, length,//! data. Each one is its own allocation, so a record keeps working when the//! list grows, when another is removed, and when the zone is sorted -- and so//! that handing a record to `dns.Builder` is a copy rather than a conversion.//!//! **Lookup is a linear scan.** A zone here is a list to read and edit, not//! the data structure a name server answers out of: `find` walks it. For a//! zone of a few thousand records that is nothing, and for a zone of a few//! million the right answer is an index built for whatever the program//! actually asks, which is not something this can guess.//!//! **Nothing is checked beyond each record.** That a zone has exactly one//! `soa`, at the apex; that a name with a `cname` has nothing else; that every//! delegation has glue -- all of that is a policy this does not hold. It reads//! what is written and writes what it holds.
const std = @import("std");const Allocator = std.mem.Allocator;const Reader = std.Io.Reader;const Writer = std.Io.Writer;
const dns = @import("dns");
const Diagnostics = @import("Diagnostics.zig");const Parser = @import("Parser.zig");const name = @import("name.zig");const writing = @import("write.zig");
const Zone = @This();
gpa: Allocator,/// The apex, in wire form. Empty when the zone has no origin, which is legal/// and means every name in it was written out in full.origin_buffer: dns.Name.Buffer = undefined,origin_len: usize = 0,/// The records, each borrowing an allocation of its own.list: std.ArrayList(dns.Record) = .empty,/// Where `add` re-encodes a record before it is copied to its own allocation./// It is kept rather than allocated each time because it is a message's worth/// of memory and adding a record is something done in a loop -- a zone of two/// hundred thousand records was spending most of its time in the kernel/// asking for this buffer and giving it back.scratch: []u8 = &.{},
pub const Error = Parser.Error || error{ /// A record whose data could not be re-encoded, which for `add` means it /// came from a message this library cannot make sense of. BadRecord,};
pub const ParseOptions = Parser.Options;pub const WriteOptions = writing.Options;
/// An empty zone. The origin is presentation text and must be absolute; pass/// `null` for a zone that has none.pub fn init(gpa: Allocator, apex: ?[]const u8) name.Error!Zone { var self: Zone = .{ .gpa = gpa }; if (apex) |text| { const encoded = try name.encodeAbsolute(&self.origin_buffer, text); self.origin_len = encoded.message.len; } return self;}
/// Frees every record, and with them every `dns.Record` the zone handed out.pub fn deinit(self: *Zone) void { for (self.list.items) |rr| self.gpa.free(rr.message); self.list.deinit(self.gpa); self.gpa.free(self.scratch); self.* = undefined;}
/// A message's worth of room to encode one record in, made once.fn scratchBuffer(self: *Zone) Error![]u8 { if (self.scratch.len == 0) self.scratch = try self.gpa.alloc(u8, dns.max_message_len); return self.scratch;}
/// Reads a whole zone file.////// `$INCLUDE` is refused by default; to follow one, drive `Parser` directly/// and `add` what it gives back, which is all this does.pub fn parse(gpa: Allocator, reader: *Reader, options: ParseOptions) Error!Zone { var self: Zone = .{ .gpa = gpa }; errdefer self.deinit();
var parser = try Parser.init(gpa, reader, options); defer parser.deinit();
while (try parser.next()) |item| switch (item) { .record => |rr| try self.append(rr), // Unreachable with the default options, and the honest thing to do // with one when a caller has asked to be told: this is the convenience // function, and following includes is not convenient. .include => return error.IncludeNotAllowed, };
if (options.origin) |text| { try self.setOrigin(text); } else { self.setOriginFromSoa(); } return self;}
/// Sets the apex from presentation text. A relative name is rooted, since/// there is nothing for it to be relative to.pub fn setOrigin(self: *Zone, apex: []const u8) name.Error!void { const encoded = try name.encodeAbsolute(&self.origin_buffer, apex); self.origin_len = encoded.message.len;}
/// Sets the apex to the owner of the zone's first `soa`, which is what a zone/// file with no `$ORIGIN` in it still says. Does nothing if there is no `soa`.////// `parse` does this for a zone that was not given an origin; a caller driving/// `Parser` itself wants it too, or the zone it builds will have no apex to/// write names relative to.pub fn setOriginFromSoa(self: *Zone) void { // Deliberately not `soa()`, which only looks at the apex -- which is the // thing being worked out. for (self.list.items) |rr| { if (rr.type != .soa) continue; self.origin_len = rr.name.toBytes(&self.origin_buffer).len; return; }}
/// The apex, or `null` for a zone that has none. It borrows the zone.pub fn origin(self: *const Zone) ?dns.Name { if (self.origin_len == 0) return null; return .{ .message = self.origin_buffer[0..self.origin_len], .offset = 0 };}
/// Every record, in the order they were read or added. The slice is the zone's/// own and lasts until the next change to it; the records in it last until/// they are removed.pub fn records(self: *const Zone) []const dns.Record { return self.list.items;}
/// How many records the zone holds.pub fn count(self: *const Zone) usize { return self.list.items.len;}
/// The zone's `soa`, which is the first one at the apex -- or the first one/// anywhere, for a zone with no origin.pub fn soa(self: *const Zone) ?dns.Record { for (self.list.items) |rr| { if (rr.type != .soa) continue; if (self.origin()) |apex| if (!rr.name.eql(apex)) continue; return rr; } return null;}
/// The serial of the zone's `soa`, which is the one number a secondary looks/// at, or `null` when there is no `soa`.pub fn serial(self: *const Zone) ?u32 { const record = self.soa() orelse return null; const data = record.data() catch return null; return data.soa.serial;}
// -- adding and removing --------------------------------------------------------
/// Takes a copy of a record from anywhere -- a message, another zone -- and/// adds it.////// The copy is re-encoded rather than memcpy'd, because a record read out of a/// message may have compression pointers in its data that mean nothing outside/// that message.pub fn add(self: *Zone, rr: dns.Record) Error!void { const data = rr.data() catch return error.BadRecord;
// A record cannot be longer than a message, so a message-sized buffer is // always enough. const scratch = try self.scratchBuffer();
var builder = dns.Builder.init(scratch, .{ .id = 0 }, .{ .compression = false }) catch return error.BadRecord; builder.record(.answer, .{ .name = rr.name, .class = rr.class, .ttl = rr.ttl, .data = data, }) catch return error.RecordTooLong;
try self.appendImage(scratch[dns.Header.len..builder.pos]);}
/// Adds a record built from its parts, which is how a program that knows what/// it wants says so without going through text:////// ```zig/// try z.addData(.{/// .name = dns.Name.literal("www.example.com"),/// .ttl = 3600,/// .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } },/// });/// ```pub fn addData(self: *Zone, spec: dns.Builder.RecordSpec) Error!void { const scratch = try self.scratchBuffer();
var builder = dns.Builder.init(scratch, .{ .id = 0 }, .{ .compression = false }) catch return error.BadRecord; builder.record(.answer, spec) catch return error.RecordTooLong;
try self.appendImage(scratch[dns.Header.len..builder.pos]);}
/// Adds the records one entry of a zone file describes, read with this zone's/// origin: `"www 3600 IN A 192.0.2.1"`.////// Several entries separated by newlines work as well, and so do the/// directives, which is what makes this the general way to edit a zone by hand/// without writing the whole file out and reading it back.pub fn addText(self: *Zone, text: []const u8, options: ParseOptions) Error!void { var reader = Reader.fixed(text); var with = options; // The zone's own origin, written out as text, because that is what // `Parser` takes and it is the one thing it cannot work out for itself. // The buffer has to outlive the parse, which is why it is here and not in // an `if`. var buffer: dns.Name.TextBuffer = undefined; if (with.origin == null) { if (self.origin()) |apex| with.origin = apex.toText(&buffer) catch unreachable; } return self.addFrom(&reader, with);}
/// Reads records from anywhere and adds them. The zone's origin is not touched/// and neither is anything else about it -- and nor is it used: unlike/// `addText`, relative names are read against `options.origin` alone.pub fn addFrom(self: *Zone, reader: *Reader, options: ParseOptions) Error!void { var parser = try Parser.init(self.gpa, reader, options); defer parser.deinit(); while (try parser.next()) |item| switch (item) { .record => |rr| try self.append(rr), .include => return error.IncludeNotAllowed, };}
/// Takes a copy of a record this library produced, whose data is already/// uncompressed. `add` is the one to use for anything else.fn append(self: *Zone, rr: dns.Record) Error!void { try self.appendImage(rr.message);}
fn appendImage(self: *Zone, image: []const u8) Error!void { const owned = try self.gpa.dupe(u8, image); errdefer self.gpa.free(owned);
var decoder = dns.wire.Decoder.init(owned) catch return error.RecordTooLong; const parsed = try dns.Record.parse(&decoder); std.debug.assert(decoder.atEnd()); try self.list.append(self.gpa, parsed);}
/// Removes the record at an index, keeping the order of the rest.pub fn remove(self: *Zone, index: usize) void { const rr = self.list.orderedRemove(index); self.gpa.free(rr.message);}
/// Removes one record -- the first that matches -- and answers whether there/// was one.////// Matching is on the owner, the class, the type and the data, and **not** on/// the TTL: RFC 2181 §5.2 says two records of an RRset that disagree about/// their TTL are still the same records, so a copy that arrived with a/// different one is still this record.////// The data is compared after re-encoding, which is the whole reason this is/// not four lines at the call site. A record read out of a message may have/// compression pointers inside its data, and those bytes mean nothing here --/// so comparing `rdata` as it arrived against `rdata` as this zone stores it/// answers "not found" for a record that is plainly there. That is the failure/// an incremental zone transfer would hit first and notice last: the delta/// says remove this, the removal silently does nothing, and the zone quietly/// keeps a record the primary dropped.////// This is what an IXFR deletion needs. `removeRrset` is the wrong tool for/// one -- a delta names a record, and removing the whole RRset because one/// member of it changed is how a transfer loses data.pub fn removeRecord(self: *Zone, rr: dns.Record) Error!bool { const wanted = try self.reencode(rr); for (self.list.items, 0..) |held, i| { if (held.type != wanted.type or held.class != wanted.class) continue; if (!held.name.eql(wanted.name)) continue; if (!std.mem.eql(u8, held.rdata, wanted.rdata)) continue; self.remove(i); return true; } return false;}
/// Re-encodes a record into the scratch buffer and hands back a view of it,/// with no compression anywhere in it. The view is valid until the next call/// that uses the scratch buffer, which is every one of `add`, `addData`,/// `setSerial` and this.fn reencode(self: *Zone, rr: dns.Record) Error!dns.Record { const data = rr.data() catch return error.BadRecord; const scratch = try self.scratchBuffer();
var builder = dns.Builder.init(scratch, .{ .id = 0 }, .{ .compression = false }) catch return error.BadRecord; builder.record(.answer, .{ .name = rr.name, .class = rr.class, .ttl = rr.ttl, .data = data, }) catch return error.RecordTooLong;
var decoder = dns.wire.Decoder.init(scratch[dns.Header.len..builder.pos]) catch return error.RecordTooLong; return dns.Record.parse(&decoder);}
/// Makes room for `n` more records, so that adding them cannot fail for want/// of it.////// What this is for is applying a set of changes atomically. Reserving first/// turns the one fallible step of `adopt` into something that happens before/// anything has been removed, which is the difference between a zone that is/// updated and a zone that is half updated -- and RFC 1995 §2 is explicit that/// an incremental transfer may not leave one of those behind.pub fn ensureUnusedCapacity(self: *Zone, n: usize) Allocator.Error!void { try self.list.ensureUnusedCapacity(self.gpa, n);}
/// Adds a record from an image this zone's allocator already owns, taking the/// allocation with it.////// `image` is one record in wire form with nothing compressed in it -- what/// `dns.Builder` writes with `.{ .compression = false }`, minus the header./// Ownership transfers whatever happens: an image that will not parse is freed/// here rather than handed back, because a caller that has already given it/// away has nothing left to free it with.////// This is `add` for something that has already been copied. A transfer that/// stages its changes before applying them has copies in hand and would/// otherwise make a second one.pub fn adopt(self: *Zone, image: []u8) Error!void { errdefer self.gpa.free(image);
var decoder = dns.wire.Decoder.init(image) catch return error.RecordTooLong; const parsed = try dns.Record.parse(&decoder); if (!decoder.atEnd()) return error.BadRecord; try self.list.append(self.gpa, parsed);}
/// Removes every record with this owner and type, and answers how many there/// were. A `null` type removes every record at the name.pub fn removeRrset(self: *Zone, owner: dns.Name, record_type: ?dns.Type) usize { var removed: usize = 0; var i: usize = 0; while (i < self.list.items.len) { const rr = self.list.items[i]; if (rr.name.eql(owner) and (record_type == null or rr.type == record_type.?)) { self.remove(i); removed += 1; } else { i += 1; } } return removed;}
/// Replaces the zone's `soa` with the same record carrying a different serial,/// and answers what it was -- or `null`, changing nothing, when there is no/// `soa`.////// Every other field is kept exactly as it was, including the record's place/// in the zone, because a serial is the one number in an `soa` that is changed/// on its own.pub fn setSerial(self: *Zone, value: u32) Error!?u32 { const current = self.soa() orelse return null; var data = current.data() catch return error.BadRecord; const was = data.soa.serial; data.soa.serial = value;
const scratch = try self.scratchBuffer(); var builder = dns.Builder.init(scratch, .{ .id = 0 }, .{ .compression = false }) catch return error.BadRecord; builder.record(.answer, .{ .name = current.name, .class = current.class, .ttl = current.ttl, .data = data, }) catch return error.RecordTooLong;
const image = scratch[dns.Header.len..builder.pos]; const owned = try self.gpa.dupe(u8, image); errdefer self.gpa.free(owned); var decoder = dns.wire.Decoder.init(owned) catch return error.RecordTooLong; const parsed = try dns.Record.parse(&decoder);
for (self.list.items) |*rr| { if (rr.message.ptr != current.message.ptr) continue; self.gpa.free(rr.message); rr.* = parsed; return was; } unreachable; // `soa` returned a record that is in the list.}
/// Adds one to the zone's serial, wrapping the way RFC 1982 says serial/// numbers wrap -- which is what makes a zone that has been edited two billion/// times still look newer to a secondary than the one before it.////// A serial that is a date, `2024010101`, is usually bumped by hand or by/// whatever wrote the zone; this is for the zones whose serial is a counter.////// Answers the serial as it was, or `null` when there is no `soa`.pub fn bumpSerial(self: *Zone) Error!?u32 { const current = self.soa() orelse return null; const data = current.data() catch return error.BadRecord; return self.setSerial(data.soa.serial +% 1);}
// -- looking --------------------------------------------------------------------
/// The records `find` matched, one at a time and in zone order.pub const Iterator = struct { list: []const dns.Record, owner: dns.Name, record_type: ?dns.Type, index: usize = 0,
/// The next record that matches, or `null` when there are no more. pub fn next(self: *Iterator) ?dns.Record { while (self.index < self.list.len) { const rr = self.list[self.index]; self.index += 1; if (!rr.name.eql(self.owner)) continue; if (self.record_type) |t| if (rr.type != t) continue; return rr; } return null; }
test next { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 1h\n@ NS ns1\n@ NS ns2\n", .{});
var it = z.find(dns.Name.literal("example.com"), .ns); try testing.expectFmt("ns1.example.com.", "{f}", .{(try it.next().?.data()).ns}); try testing.expectFmt("ns2.example.com.", "{f}", .{(try it.next().?.data()).ns}); try testing.expectEqual(null, it.next()); }};
/// Every record at a name, or every record of one type at it -- which is an/// RRset, the unit everything above the DNS actually deals in.////// The comparison is the DNS's own: case is ignored, as RFC 4343 requires.pub fn find(self: *const Zone, owner: dns.Name, record_type: ?dns.Type) Iterator { return .{ .list = self.list.items, .owner = owner, .record_type = record_type };}
/// The first record at a name of a type, or `null`.pub fn first(self: *const Zone, owner: dns.Name, record_type: dns.Type) ?dns.Record { var it = self.find(owner, record_type); return it.next();}
// -- ordering ---------------------------------------------------------------------
/// Puts the records in the canonical order of RFC 4034 §6: by owner name read/// right to left a label at a time, then by type, then -- within an RRset --/// by the data itself, as §6.3 orders the records of a set before they are/// signed.////// Ordering by the data as well is what makes this a canonical form rather/// than merely a sorted one: two zone files holding the same records come out/// as the same text, whatever order they happened to be written in.pub fn sortCanonical(self: *Zone) void { std.mem.sort(dns.Record, self.list.items, {}, lessThanCanonical);}
fn lessThanCanonical(_: void, a: dns.Record, b: dns.Record) bool { return switch (a.name.order(b.name)) { .lt => true, .gt => false, .eq => switch (std.math.order(@backingInt(a.type), @backingInt(b.type))) { .lt => true, .gt => false, // The data as bytes, which for records of one type is the order // RFC 4034 §6.3 asks for: every name in them is uncompressed here, // so there is nothing to expand first. .eq => std.mem.order(u8, a.rdata, b.rdata) == .lt, }, };}
/// Puts the `soa` first and leaves everything else where it is, which is what/// a zone file wants at the top and what `sortCanonical` will not do on its/// own -- the apex sorts first, but `ns` comes before `soa` by type number.pub fn soaFirst(self: *Zone) void { const apex = self.soa() orelse return; for (self.list.items, 0..) |rr, i| { if (rr.message.ptr != apex.message.ptr) continue; if (i != 0) { const record = self.list.orderedRemove(i); self.list.insertAssumeCapacity(0, record); } return; }}
// -- writing ----------------------------------------------------------------------
/// Writes the zone as a zone file. The origin is the zone's own unless the/// options name another.pub fn write(self: *const Zone, w: *Writer, options: WriteOptions) Writer.Error!void { var with = options; if (with.relativize and with.origin == null) with.origin = self.origin(); return writing.zone(w, self.list.items, with);}
// -- tests ---------------------------------------------------------------------
const testing = std.testing;
test init { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try testing.expectFmt("example.com.", "{f}", .{z.origin().?}); try testing.expectEqual(@as(usize, 0), z.count());}
test deinit { var z = try Zone.init(testing.allocator, "example.com."); try z.addText("www 3600 A 192.0.2.1", .{}); z.deinit();}
test parse { var reader: Reader = .fixed( \\$ORIGIN example.com. \\$TTL 3600 \\@ SOA ns1 hostmaster 2024010101 2h 1h 2w 1h \\ NS ns1 \\ns1 A 192.0.2.1 \\ ); var z = try Zone.parse(testing.allocator, &reader, .{}); defer z.deinit(); try testing.expectEqual(@as(usize, 3), z.count()); // No origin was given, so the soa's owner is the apex. try testing.expectFmt("example.com.", "{f}", .{z.origin().?});}
test setOrigin { var z = try Zone.init(testing.allocator, null); defer z.deinit(); try z.setOrigin("example.com"); try testing.expectFmt("example.com.", "{f}", .{z.origin().?});}
test setOriginFromSoa { var z = try Zone.init(testing.allocator, null); defer z.deinit(); try z.addText("example.com. 3600 SOA ns1.example.com. hostmaster.example.com. 1 2h 1h 2w 1h", .{}); try testing.expectEqual(null, z.origin()); z.setOriginFromSoa(); try testing.expectFmt("example.com.", "{f}", .{z.origin().?});}
test origin { var z = try Zone.init(testing.allocator, null); defer z.deinit(); try testing.expectEqual(null, z.origin()); try z.setOrigin("example.com."); try testing.expectFmt("example.com.", "{f}", .{z.origin().?});}
test records { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 3600\nwww A 192.0.2.1\nmail A 192.0.2.25\n", .{}); try testing.expectFmt("www.example.com.", "{f}", .{z.records()[0].name}); try testing.expectFmt("mail.example.com.", "{f}", .{z.records()[1].name});}
test count { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 3600\n$GENERATE 1-10 host$ A 192.0.2.$\n", .{}); try testing.expectEqual(@as(usize, 10), z.count());}
test soa { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try testing.expectEqual(null, z.soa()); try z.addText("@ 3600 SOA ns1 hostmaster 2024010101 2h 1h 2w 1h", .{}); try testing.expectFmt("ns1.example.com.", "{f}", .{(try z.soa().?.data()).soa.mname});}
test serial { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("@ 3600 SOA ns1 hostmaster 2024010101 2h 1h 2w 1h", .{}); try testing.expectEqual(@as(?u32, 2024010101), z.serial());}
test add { var from = try Zone.init(testing.allocator, "example.com."); defer from.deinit(); try from.addText("www 3600 A 192.0.2.1", .{});
var to = try Zone.init(testing.allocator, "example.com."); defer to.deinit(); // A copy: the record outlives the zone it came from. try to.add(from.records()[0]); from.remove(0); try testing.expectFmt("www.example.com.", "{f}", .{to.records()[0].name});}
test addData { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addData(.{ .name = dns.Name.literal("www.example.com"), .ttl = 3600, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); try testing.expectFmt("192.0.2.1", "{f}", .{(try z.records()[0].data()).a});}
test addText { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); // Relative to the zone's own origin, and directives work too. try z.addText("$TTL 300\nwww A 192.0.2.1\n", .{}); try testing.expectFmt("www.example.com.", "{f}", .{z.records()[0].name}); try testing.expectEqual(@as(u32, 300), z.records()[0].ttl);}
test addFrom { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); var reader: Reader = .fixed("www 3600 A 192.0.2.1\n"); // The zone's origin is not used, so the reader's has to be given. try z.addFrom(&reader, .{ .origin = "example.net." }); try testing.expectFmt("www.example.net.", "{f}", .{z.records()[0].name});}
test remove { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 3600\na A 192.0.2.1\nb A 192.0.2.2\nc A 192.0.2.3\n", .{}); z.remove(1); try testing.expectFmt("a.example.com.", "{f}", .{z.records()[0].name}); try testing.expectFmt("c.example.com.", "{f}", .{z.records()[1].name});}
test removeRecord { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 300\nwww A 192.0.2.1\nwww A 192.0.2.2\n", .{});
// The record as a transfer might deliver it, with a different TTL. var delta = try Zone.init(testing.allocator, "example.com."); defer delta.deinit(); try delta.addText("www 60 A 192.0.2.1", .{});
try testing.expect(try z.removeRecord(delta.records()[0])); try testing.expect(!try z.removeRecord(delta.records()[0])); try testing.expectFmt("192.0.2.2", "{f}", .{(try z.records()[0].data()).a});}
test ensureUnusedCapacity { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.ensureUnusedCapacity(2); try testing.expect(z.list.capacity >= 2);}
test adopt { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit();
var buffer: [512]u8 = undefined; var builder = try dns.Builder.init(&buffer, .{ .id = 0 }, .{ .compression = false }); try builder.record(.answer, .{ .name = dns.Name.literal("www.example.com"), .ttl = 3600, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); const image = try gpa.dupe(u8, buffer[dns.Header.len..builder.pos]);
try z.ensureUnusedCapacity(1); // The zone owns the image now, and frees it. try z.adopt(image); try testing.expectFmt("www.example.com.", "{f}", .{z.records()[0].name});}
test removeRrset { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText( \\$TTL 3600 \\www A 192.0.2.1 \\www A 192.0.2.2 \\www AAAA 2001:db8::1 \\ , .{}); try testing.expectEqual(@as(usize, 2), z.removeRrset(dns.Name.literal("www.example.com"), .a)); try testing.expectEqual(@as(usize, 1), z.removeRrset(dns.Name.literal("www.example.com"), null)); try testing.expectEqual(@as(usize, 0), z.count());}
test setSerial { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("@ 3600 SOA ns1 hostmaster 2024010101 2h 1h 2w 1h", .{}); try testing.expectEqual(@as(?u32, 2024010101), try z.setSerial(2024010201)); try testing.expectEqual(@as(?u32, 2024010201), z.serial());}
test bumpSerial { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("@ 3600 SOA ns1 hostmaster 4294967295 2h 1h 2w 1h", .{}); try testing.expectEqual(@as(?u32, 4294967295), try z.bumpSerial()); // RFC 1982 arithmetic: the counter wraps. try testing.expectEqual(@as(?u32, 0), z.serial());}
test find { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 3600\nwww A 192.0.2.1\nwww AAAA 2001:db8::1\n", .{});
// Case does not matter, and a null type is every record at the name. var it = z.find(dns.Name.literal("WWW.Example.COM"), null); var n: usize = 0; while (it.next()) |_| n += 1; try testing.expectEqual(@as(usize, 2), n);}
test first { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText("$TTL 3600\nwww A 192.0.2.1\n", .{}); const www = dns.Name.literal("www.example.com"); try testing.expectFmt("192.0.2.1", "{f}", .{(try z.first(www, .a).?.data()).a}); try testing.expectEqual(null, z.first(www, .aaaa));}
test sortCanonical { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText( \\$TTL 3600 \\b.a A 192.0.2.2 \\z A 192.0.2.3 \\a A 192.0.2.1 \\ , .{}); z.sortCanonical(); // Right to left a label at a time: b.a sorts after a and before z. try testing.expectFmt("a.example.com.", "{f}", .{z.records()[0].name}); try testing.expectFmt("b.a.example.com.", "{f}", .{z.records()[1].name}); try testing.expectFmt("z.example.com.", "{f}", .{z.records()[2].name});}
test soaFirst { var z = try Zone.init(testing.allocator, "example.com."); defer z.deinit(); try z.addText( \\$TTL 3600 \\@ NS ns1 \\@ SOA ns1 hostmaster 1 2h 1h 2w 1h \\ , .{}); z.sortCanonical(); try testing.expectEqual(dns.Type.ns, z.records()[0].type); z.soaFirst(); try testing.expectEqual(dns.Type.soa, z.records()[0].type);}
test write { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText("www 3600 A 192.0.2.1", .{});
var out: Writer.Allocating = .init(gpa); defer out.deinit(); try z.write(&out.writer, .{}); try testing.expectEqualStrings( \\$ORIGIN example.com. \\$TTL 3600 \\ \\www IN A 192.0.2.1 \\ , out.written());}
const example = \\$ORIGIN example.com. \\$TTL 3600 \\@ IN SOA ns1 hostmaster ( \\ 2024010101 ; serial \\ 2h 1h 2w 1h ) \\ IN NS ns1 \\ IN NS ns2 \\ns1 IN A 192.0.2.1 \\ns2 IN A 192.0.2.2 \\www IN CNAME ns1 \\ 60 IN TXT "hello" "world" \\;
fn parseExample(gpa: Allocator) !Zone { var reader = Reader.fixed(example); return Zone.parse(gpa, &reader, .{ .origin = "example.com." });}
test "a zone is the records it holds" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
try testing.expectEqual(@as(usize, 7), z.count()); try testing.expectFmt("example.com.", "{f}", .{z.origin().?}); try testing.expectEqual(@as(?u32, 2024010101), z.serial()); try testing.expectFmt( "www.example.com.\t3600\tIN\tCNAME\tns1.example.com.", "{f}", .{z.first(dns.Name.literal("www.example.com"), .cname).?}, );}
test "finding an rrset, without regard to case" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
var it = z.find(dns.Name.literal("EXAMPLE.COM"), .ns); try testing.expectFmt("ns1.example.com.", "{f}", .{(try it.next().?.data()).ns}); try testing.expectFmt("ns2.example.com.", "{f}", .{(try it.next().?.data()).ns}); try testing.expectEqual(@as(?dns.Record, null), it.next());
var all = z.find(dns.Name.literal("www.example.com"), null); try testing.expectEqual(dns.Type.cname, all.next().?.type); try testing.expectEqual(dns.Type.txt, all.next().?.type); try testing.expectEqual(@as(?dns.Record, null), all.next());}
test "records survive the list growing and being edited around them" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
const kept = z.first(dns.Name.literal("ns1.example.com"), .a).?; for (0..64) |i| { var buffer: [64]u8 = undefined; const line = try std.fmt.bufPrint(&buffer, "filler{d} 60 IN TXT \"x\"", .{i}); try z.addText(line, .{}); } try testing.expectEqual(@as(usize, 1), z.removeRrset(dns.Name.literal("ns2.example.com"), null)); try testing.expectFmt("192.0.2.1", "{f}", .{(try kept.data()).a});}
test "adding a record from its parts, and from a line of text" { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit();
try z.addData(.{ .name = dns.Name.literal("www.example.com"), .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); try z.addText("www 300 IN AAAA 2001:db8::1", .{});
try testing.expectEqual(@as(usize, 2), z.count()); try testing.expectFmt( "www.example.com.\t300\tIN\tA\t192.0.2.1", "{f}", .{z.records()[0]}, ); try testing.expectFmt( "www.example.com.\t300\tIN\tAAAA\t2001:db8::1", "{f}", .{z.records()[1]}, );}
test "a record copied out of a message loses its compression" { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit();
// A message whose second record's data is a pointer back to the first // name: nothing that can be stored on its own. const message = "\x07example\x03com\x00" ++ // 0: the name, uncompressed "\x03www\xc0\x00" ++ // 13: www.example.com, compressed "\x00\x05\x00\x01\x00\x00\x00\x3c\x00\x02\xc0\x00"; // 19: a cname of it var decoder = dns.wire.Decoder.init(message) catch unreachable; decoder.pos = 13; const rr = try dns.Record.parse(&decoder); try testing.expectFmt("www.example.com.", "{f}", .{rr.name}); try testing.expectEqual(@as(usize, 2), rr.rdata.len);
try z.add(rr); const copied = z.records()[0]; try testing.expectEqual(@as(usize, 13), copied.rdata.len); try testing.expectFmt( "www.example.com.\t60\tIN\tCNAME\texample.com.", "{f}", .{copied}, );}
test "removing one record of an RRset leaves the rest" { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText( \\@ 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5 \\www 60 IN A 192.0.2.1 \\www 60 IN A 192.0.2.2 \\www 60 IN A 192.0.2.3 , .{});
const wanted = z.records()[2]; try testing.expect(try z.removeRecord(wanted)); try testing.expectEqual(@as(usize, 3), z.count());
// The other two are still there, in the order they were in. Reaching for // `removeRrset` here would have taken all three. var it = z.find(dns.Name.literal("www.example.com"), .a); try testing.expectFmt("192.0.2.1", "{f}", .{(try it.next().?.data()).a}); try testing.expectFmt("192.0.2.3", "{f}", .{(try it.next().?.data()).a}); try testing.expectEqual(@as(?dns.Record, null), it.next());
// And removing it again says there was nothing to remove. try testing.expect(!try z.removeRecord(wanted));}
test "a record removed by a copy whose data is compressed" { // The reason `removeRecord` re-encodes rather than comparing `rdata` as it // arrived. This is the same message as the compression test above, and the // record in it has two bytes of data -- a pointer -- where the zone holds // thirteen. A comparison on those bytes finds nothing and the zone quietly // keeps a record a transfer said to drop. const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText("www 60 IN CNAME example.com.", .{}); try testing.expectEqual(@as(usize, 1), z.count());
const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00" ++ "\x00\x05\x00\x01\x00\x00\x00\x3c\x00\x02\xc0\x00"; var decoder = dns.wire.Decoder.init(message) catch unreachable; decoder.pos = 13; const compressed = try dns.Record.parse(&decoder); try testing.expectEqual(@as(usize, 2), compressed.rdata.len); try testing.expect(!std.mem.eql(u8, compressed.rdata, z.records()[0].rdata));
try testing.expect(try z.removeRecord(compressed)); try testing.expectEqual(@as(usize, 0), z.count());}
test "a TTL is not part of what makes a record that record" { // RFC 2181 §5.2: two copies of a record that disagree about the TTL are // the same record. An incremental transfer's deletions routinely carry a // different one from the copy on hand. const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText("www 3600 IN A 192.0.2.1", .{});
var other = z.records()[0]; other.ttl = 60; try testing.expect(try z.removeRecord(other)); try testing.expectEqual(@as(usize, 0), z.count());}
test "a record that differs in class, type or name is a different record" { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText("www 60 IN A 192.0.2.1", .{});
// Built in a zone of their own, because a `Record` is a view into the // bytes it was decoded from and editing its fields does not edit those. var others = try Zone.init(gpa, "example.com."); defer others.deinit(); try others.addText("www 60 IN A 192.0.2.2", .{}); try others.addText("other 60 IN A 192.0.2.1", .{}); try others.addText("www 60 IN TXT \"192.0.2.1\"", .{}); try others.addData(.{ .name = dns.Name.literal("www.example.com"), .class = .ch, .ttl = 60, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, });
for (others.records()) |other| try testing.expect(!try z.removeRecord(other)); try testing.expectEqual(@as(usize, 1), z.count());
// And the one that does match still does. try testing.expect(try z.removeRecord(z.records()[0]));}
test "a reserved zone takes what it is given without allocating again" { // What applying a staged change needs: the one step that can fail happens // before anything has been removed, so what follows cannot leave a zone // half updated. const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText("@ 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5", .{});
try z.ensureUnusedCapacity(4); const before = z.list.capacity;
// Four images, built the way a transfer would build them: one record // each, uncompressed, allocated with the zone's own allocator. for (0..4) |i| { var buffer: [512]u8 = undefined; var names: dns.Name.Buffer = undefined; var builder = try dns.Builder.init(&buffer, .{ .id = 0 }, .{ .compression = false }); try builder.record(.answer, .{ .name = try .fromText(&names, "www.example.com"), .ttl = 60, .data = .{ .a = .{ .octets = .{ 192, 0, 2, @intCast(i + 1) } } }, }); const image = builder.finish()[dns.Header.len..]; try z.adopt(try gpa.dupe(u8, image)); }
try testing.expectEqual(@as(usize, 5), z.count()); try testing.expectEqual(before, z.list.capacity); try testing.expectFmt( "www.example.com.\t60\tIN\tA\t192.0.2.4", "{f}", .{z.records()[4]}, );}
test "an image that is not a record is freed rather than kept" { // `adopt` takes the allocation whatever happens, because a caller that has // already handed it over has nothing left to free it with. The leak check // in this test is the assertion. const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit();
// A compression pointer, which is what 0xc0 begins and which cannot mean // anything in an image that is one record on its own. try testing.expectError(error.BadPointer, z.adopt(try gpa.dupe(u8, "\xc0\x00\x00"))); // And bytes that stop in the middle of a record. try testing.expectError(error.Truncated, z.adopt(try gpa.dupe(u8, "\x01a\x00\x00\x01"))); try testing.expectEqual(@as(usize, 0), z.count());}
test "canonical order is by name read backwards, then by type" { const gpa = testing.allocator; var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText( \\b 60 IN A 192.0.2.1 \\@ 60 IN NS ns1.example.com. \\a.b 60 IN A 192.0.2.2 \\@ 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5 \\a 60 IN A 192.0.2.3 , .{});
z.sortCanonical(); var out: Writer.Allocating = .init(gpa); defer out.deinit(); try z.write(&out.writer, .canonical); try testing.expectEqualStrings( \\example.com. 60 IN NS ns1.example.com. \\example.com. 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5 \\a.example.com. 60 IN A 192.0.2.3 \\b.example.com. 60 IN A 192.0.2.1 \\a.b.example.com. 60 IN A 192.0.2.2 \\ , out.written());
z.soaFirst(); try testing.expectEqual(dns.Type.soa, z.records()[0].type);}
test "the serial is the one field that is edited on its own" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
const before = z.count(); try testing.expectEqual(@as(?u32, 2024010101), try z.bumpSerial()); try testing.expectEqual(@as(?u32, 2024010102), z.serial()); try testing.expectEqual(@as(?u32, 2024010102), try z.setSerial(7)); try testing.expectEqual(@as(?u32, 7), z.serial());
// The record is the same record otherwise, and is still where it was. try testing.expectEqual(before, z.count()); try testing.expectEqual(dns.Type.soa, z.records()[0].type); try testing.expectFmt( "example.com.\t3600\tIN\tSOA\tns1.example.com. hostmaster.example.com. " ++ "7 7200 3600 1209600 3600", "{f}", .{z.records()[0]}, );
// And a zone with no soa says so rather than inventing one. var empty = try Zone.init(gpa, "example.com."); defer empty.deinit(); try testing.expectEqual(@as(?u32, null), try empty.bumpSerial());}
test "a zone built a record at a time still finds its apex" { const gpa = testing.allocator; var z = try Zone.init(gpa, null); defer z.deinit(); try testing.expectEqual(@as(?dns.Name, null), z.origin());
try z.addText( \\example.com. 60 IN SOA ns1.example.com. h.example.com. 1 2 3 4 5 \\www.example.com. 60 IN A 192.0.2.1 , .{}); // Nothing has worked the apex out yet: the records were added one by one. try testing.expectEqual(@as(?dns.Name, null), z.origin());
z.setOriginFromSoa(); try testing.expectFmt("example.com.", "{f}", .{z.origin().?});
var out: Writer.Allocating = .init(gpa); defer out.deinit(); try z.write(&out.writer, .{}); try testing.expect(std.mem.startsWith(u8, out.written(), "$ORIGIN example.com.\n"));}
test "a zone written out and read back is the same zone" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
var out: Writer.Allocating = .init(gpa); defer out.deinit(); try z.write(&out.writer, .{});
var again = try Zone.parse(gpa, @constCast(&Reader.fixed(out.written())), .{}); defer again.deinit();
try testing.expectEqual(z.count(), again.count()); for (z.records(), again.records()) |before, after| { try testing.expect(before.eql(after)); try testing.expectEqual(before.ttl, after.ttl); }}
test "what the writer writes" { const gpa = testing.allocator; var z = try parseExample(gpa); defer z.deinit();
var out: Writer.Allocating = .init(gpa); defer out.deinit(); try z.write(&out.writer, .{}); try testing.expectEqualStrings( \\$ORIGIN example.com. \\$TTL 3600 \\ \\@ IN SOA ns1.example.com. hostmaster.example.com. ( \\ 2024010101 ; serial \\ 7200 ; refresh \\ 3600 ; retry \\ 1209600 ; expire \\ 3600 ; negative caching time to live \\ ) \\ IN NS ns1.example.com. \\ IN NS ns2.example.com. \\ns1 IN A 192.0.2.1 \\ns2 IN A 192.0.2.2 \\www IN CNAME ns1.example.com. \\ 60 IN TXT "hello" "world" \\ , out.written());}