// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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()); }