Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Writing records back out as a zone file.//!//! The reader's job is to accept everything BIND accepts; the writer's is to//! produce one shape, and to produce it so that reading it back gives the//! records that went in. Between those two there is a lot of latitude, and//! this is what is done with it://!//! * Owner names are written relative to the origin, and an owner the same as//! the one above it is left out entirely, which is what makes a zone file//! readable rather than a column of repetition.//! * **Names inside record data are always written in full.** Relativizing//! them would mean a presentation writer for every type, and would make the//! output depend on an origin that is only stated at the top of the file. An//! absolute name means the same thing wherever it is read.//! * A time to live equal to the `$TTL` in force is left out; every other one//! is written as a plain count of seconds rather than in units, because a//! number cannot be misread.//! * The `soa` is written across lines with its five timers labeled, which is//! the one place a comment in the output is worth more than the space it//! takes.//!//! `Options.canonical` turns all of that off: every name absolute, every field//! present, one record per line, no directives and no comments. That is the//! form to compare two zones in, and what `zonecat --canonical` writes.
const std = @import("std");const Writer = std.Io.Writer;
const dns = @import("dns");
const name = @import("name.zig");
pub const Options = struct { /// What owner names are written relative to, and what `$ORIGIN` says. /// Without one every name is written in full. origin: ?dns.Name = null, /// Whether to relativize at all. `Zone.write` fills `origin` in from the /// zone when this is set and it was left out, so this is what turns that /// off -- an origin of `null` would otherwise mean "use the zone's". relativize: bool = true, /// The `$TTL` to write and to leave out of records that match it. `null` /// means work one out: the `soa`'s own time to live if there is an `soa`, /// and otherwise the first record's. ttl: ?u32 = null, /// Whether to write the `$ORIGIN` and `$TTL` lines at all. directives: bool = true, /// Whether a record whose owner is the same as the one above it may leave /// it out. omit_repeated_owner: bool = true, /// Whether to leave out a time to live that matches the `$TTL`. omit_default_ttl: bool = true, /// Whether to line the columns up. align_columns: bool = true, /// Whether to write the `soa` across several lines with its timers /// labeled. soa_comments: bool = true,
/// One record per line, everything spelled out, nothing implied: the form /// to compare two zones in. pub const canonical: Options = .{ .origin = null, .relativize = false, .directives = false, .omit_repeated_owner = false, .omit_default_ttl = false, .align_columns = false, .soa_comments = false, };};
/// How wide the columns are when they are being lined up. Twenty-three is what/// a name of up to three short labels needs, and is what BIND's own output/// uses; a longer owner simply pushes the rest of the line along.const owner_width = 23;const ttl_width = 7;const class_width = 3;const type_width = 7;
/// Writes every record as a zone file: the `$ORIGIN` and `$TTL` lines if the/// options ask for them, then the records in the order they are given.pub fn zone(w: *Writer, records: []const dns.Record, options: Options) Writer.Error!void { const ttl = options.ttl orelse defaultTtl(records);
if (options.directives) { if (options.origin) |origin| try w.print("$ORIGIN {f}\n", .{origin}); if (ttl) |value| try w.print("$TTL {d}\n", .{value}); if (options.origin != null or ttl != null) try w.writeByte('\n'); }
var previous: ?dns.Name = null; for (records) |rr| { const same_owner = options.omit_repeated_owner and previous != null and previous.?.eqlExact(rr.name); try one(w, rr, options, ttl, same_owner); previous = rr.name; }}
/// Writes one record, followed by a newline. With the default options its/// owner and its time to live are written in full, which is the whole of what/// a caller outside a zone wants: a line that means the same thing wherever it/// is pasted. An `origin` or a `ttl` in the options shortens it as `zone`/// would.pub fn record(w: *Writer, rr: dns.Record, options: Options) Writer.Error!void { return one(w, rr, options, options.ttl, false);}
fn one( w: *Writer, rr: dns.Record, options: Options, ttl: ?u32, same_owner: bool,) Writer.Error!void { if (same_owner) { // The columns still line up: the owner column is simply blank. A line // beginning with whitespace is exactly how a zone file says "the same // owner as the line above", so this reads back as what it means. try pad(w, 0, owner_width, options); } else { try name.writeRelative(w, rr.name, options.origin); try pad(w, relativeWidth(rr.name, options.origin), owner_width, options); }
if (options.omit_default_ttl and ttl != null and rr.ttl == ttl.?) { try pad(w, 0, ttl_width, options); } else { try w.print("{d}", .{rr.ttl}); try pad(w, decimalWidth(rr.ttl), ttl_width, options); }
try w.print("{f}", .{rr.class}); try pad(w, classWidth(rr.class), class_width, options); try w.print("{f}", .{rr.type}); try pad(w, typeWidth(rr.type), type_width, options);
if (rr.data()) |data| { if (options.soa_comments and data == .soa) { try soa(w, data.soa); } else { try w.print("{f}", .{data}); } } else |_| { // Cannot happen for a record this library parsed, and is the honest // thing to write for one that came from somewhere else. try dns.presentation.writeUnknownRdata(w, rr.rdata); } try w.writeByte('\n');}
/// The five timers, one to a line, each with what it is for beside it. The/// numbers are the only part of a zone file people edit by hand and get wrong.fn soa(w: *Writer, value: dns.rdata.Soa) Writer.Error!void { const indent = owner_width + ttl_width + class_width + type_width; try w.print("{f} {f} (\n", .{ value.mname, value.rname }); const timers = [_]struct { value: u32, what: []const u8 }{ .{ .value = value.serial, .what = "serial" }, .{ .value = value.refresh, .what = "refresh" }, .{ .value = value.retry, .what = "retry" }, .{ .value = value.expire, .what = "expire" }, .{ .value = value.minimum, .what = "negative caching time to live" }, }; for (timers) |timer| { try w.splatByteAll(' ', indent); try w.print("{d}", .{timer.value}); try w.splatByteAll(' ', 12 -| decimalWidth(timer.value)); try w.print("; {s}\n", .{timer.what}); } try w.splatByteAll(' ', indent); try w.writeByte(')');}
fn pad(w: *Writer, written: usize, want: usize, options: Options) Writer.Error!void { if (!options.align_columns) return w.writeByte(' '); // Always at least one space: a column that has overflowed its width must // not run into the next one. try w.splatByteAll(' ', @max(1, want -| written));}
/// How wide a name will be once written, without writing it anywhere.fn relativeWidth(value: dns.Name, origin: ?dns.Name) usize { var nothing: [0]u8 = .{}; var counting: Writer.Discarding = .init(¬hing); // A writer that discards cannot fail. name.writeRelative(&counting.writer, value, origin) catch unreachable; return @intCast(counting.fullCount());}
fn decimalWidth(value: u32) usize { var width: usize = 1; var left = value; while (left >= 10) : (left /= 10) width += 1; return width;}
fn classWidth(class: dns.Class) usize { return if (class.name()) |n| n.len else "CLASS65535".len;}
fn typeWidth(t: dns.Type) usize { return if (t.name()) |n| n.len else "TYPE65535".len;}
/// The time to live to write as `$TTL`: the `soa`'s, because the apex is what/// a zone is written around, and the first record's if there is no `soa`.fn defaultTtl(records: []const dns.Record) ?u32 { for (records) |rr| if (rr.type == .soa) return rr.ttl; if (records.len != 0) return records[0].ttl; return null;}
const testing = std.testing;
test zone { const gpa = testing.allocator; const Zone = @import("Zone.zig"); var z = try Zone.init(gpa, "example.com."); defer z.deinit(); try z.addText( \\$TTL 3600 \\@ NS ns1 \\www A 192.0.2.1 \\ 60 TXT "hello" \\ , .{});
var out: Writer.Allocating = .init(gpa); defer out.deinit(); try zone(&out.writer, z.records(), .{ .origin = z.origin() }); try testing.expectEqualStrings( \\$ORIGIN example.com. \\$TTL 3600 \\ \\@ IN NS ns1.example.com. \\www IN A 192.0.2.1 \\ 60 IN TXT "hello" \\ , out.written());}
test record { const gpa = testing.allocator; const Zone = @import("Zone.zig"); 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 record(&out.writer, z.records()[0], .canonical); try testing.expectEqualStrings("www.example.com. 3600 IN A 192.0.2.1\n", out.written());}
test "a record on its own" { var buffer: [256]u8 = undefined; var w = Writer.fixed(&buffer); const message = "\x03www\x07example\x03com\x00\x00\x01\x00\x01\x00\x00\x01\x2c" ++ "\x00\x04\xc0\x00\x02\x01"; var decoder = try dns.wire.Decoder.init(message); const rr = try dns.Record.parse(&decoder);
try record(&w, rr, .canonical); try testing.expectEqualStrings("www.example.com. 300 IN A 192.0.2.1\n", w.buffered());}