Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Names as a zone file writes them, which is not quite as the wire does.//!//! The escape rules and the relative-name rule both live in `dns.Name` --//! `fromTextRelative` is the loop, and `textIsAbsolute` the question it turns//! on -- because a resolver's search list needs exactly the same two and//! neither library should own them. What is left here is what is master file//! syntax rather than name syntax://!//! **`@` is the origin.** On its own, and only on its own: an `@` anywhere//! else in a name is an ordinary character, which is why the escaping here//! puts a backslash in front of one when it writes a name back out.//!//! **A relative name with no origin is an error.** A message never has one and//! a resolver would append its search list; a zone file with no `$ORIGIN` and//! no origin from the caller has nothing to append, and a name quietly rooted//! one label short is worse than a refusal.//!//! **Writing can go the other way.** `writeRelative` is how a zone comes out//! looking like the one that went in: a name at or below the origin loses the//! origin's labels and its trailing dot, and the origin itself becomes `@`.//! Everything else is written in full, because a name that is not below the//! origin has no shorter form that means the same thing.
const std = @import("std");const Writer = std.Io.Writer;
const dns = @import("dns");
/// What a name written in a zone file can be wrong in. Everything `dns` can/// say about a name, and the one thing only a zone file can be missing.pub const Error = dns.Name.TextError || error{ /// A relative name -- or a bare `@` -- where no origin has been set. /// Either the zone file is missing a `$ORIGIN` or the caller did not say /// what the origin is. NoOrigin,};
/// Encodes a name written in a zone file into wire form in `buf`.////// `origin` is the origin in force, or `null` when there is none -- in which/// case a name that is not absolute is refused rather than rooted one label/// short. The escapes of RFC 1035 §5.1 are `dns.Name.fromTextRelative`'s/// business and are understood exactly as they are everywhere else.////// The returned name borrows `buf`, which must outlive it.pub fn encode(buf: *dns.Name.Buffer, text: []const u8, origin: ?dns.Name) Error!dns.Name { // `@` is the whole of what a zone file adds to the syntax of a name. if (text.len == 1 and text[0] == '@') { const apex = origin orelse return error.NoOrigin; return .{ .message = apex.toBytes(buf), .offset = 0 }; } // An empty token is a name a zone file cannot mean: `@` is how the origin // is written, and `.` is how the root is. if (text.len == 0) return error.EmptyLabel;
const under = origin orelse under: { if (dns.Name.textIsAbsolute(text)) break :under dns.Name.root; // Encoded against the root and thrown away, for the error: a name that // is not a name at all should say which way it is wrong rather than // blame the origin that is missing. It is only ever reached on the way // to failing. _ = try dns.Name.fromTextRelative(buf, text, dns.Name.root); return error.NoOrigin; }; return dns.Name.fromTextRelative(buf, text, under);}
/// The wire form of a name that must be absolute -- what `$ORIGIN` and the/// `origin` a caller hands the parser both have to be.pub fn encodeAbsolute(buf: *dns.Name.Buffer, text: []const u8) Error!dns.Name { return encode(buf, text, dns.Name.root);}
/// The characters a zone file gives a meaning of its own, and which therefore/// have to be escaped inside a label. The same set `dns.Name.format` escapes,/// because a name this library writes has to be one it can read back.fn needsEscape(c: u8) bool { return switch (c) { '.', '\\', '"', '(', ')', ';', '@', '$', ' ' => true, else => c < 0x21 or c > 0x7e, };}
fn writeLabel(w: *Writer, label: []const u8) Writer.Error!void { for (label) |c| { if (!needsEscape(c)) { try w.writeByte(c); } else if (c >= 0x21 and c <= 0x7e) { try w.writeByte('\\'); try w.writeByte(c); } else { try w.print("\\{d:0>3}", .{c}); } }}
/// Writes a name the way a zone file with this origin would: `@` for the/// origin itself, the leading labels alone for anything below it, and the/// whole name with its trailing dot for anything else.////// Passing `null` for the origin writes every name in full, which is what/// `$ORIGIN`-less output and the canonical form both want.pub fn writeRelative(w: *Writer, name: dns.Name, origin: ?dns.Name) Writer.Error!void { const under = origin orelse return w.print("{f}", .{name}); if (!name.isSubdomainOf(under)) return w.print("{f}", .{name});
const mine = name.labelCount(); const theirs = under.labelCount(); if (mine == theirs) return w.writeByte('@');
var it = name.labels(); var left = mine - theirs; var first = true; while (left > 0) : (left -= 1) { const label = it.next() orelse break; if (!first) try w.writeByte('.'); first = false; try writeLabel(w, label); }}
const testing = std.testing;
test encode { var origin_buffer: dns.Name.Buffer = undefined; const origin = try encodeAbsolute(&origin_buffer, "example.com.");
var buffer: dns.Name.Buffer = undefined; try testing.expectFmt("www.example.com.", "{f}", .{try encode(&buffer, "www", origin)}); try testing.expectFmt("example.com.", "{f}", .{try encode(&buffer, "@", origin)}); try testing.expectFmt("ns1.example.net.", "{f}", .{try encode(&buffer, "ns1.example.net.", origin)}); try testing.expectError(error.NoOrigin, encode(&buffer, "www", null));}
test encodeAbsolute { var buffer: dns.Name.Buffer = undefined; // Rooted whether or not it ends in a dot. try testing.expectFmt("example.com.", "{f}", .{try encodeAbsolute(&buffer, "example.com")}); try testing.expectFmt("example.com.", "{f}", .{try encodeAbsolute(&buffer, "example.com.")});}
test writeRelative { const origin = dns.Name.literal("example.com"); var buffer: [64]u8 = undefined;
var w: Writer = .fixed(&buffer); try writeRelative(&w, dns.Name.literal("www.example.com"), origin); try testing.expectEqualStrings("www", w.buffered());
w = .fixed(&buffer); try writeRelative(&w, origin, origin); try testing.expectEqualStrings("@", w.buffered());
w = .fixed(&buffer); try writeRelative(&w, dns.Name.literal("example.net"), origin); try testing.expectEqualStrings("example.net.", w.buffered());}
/// The origin is given in wire form here because that is what the expected/// values beside it are written in, and a test that says both in the same/// alphabet is easier to read than one that does not.fn expectEncoded(expected: []const u8, text: []const u8, origin: ?[]const u8) !void { var buf: dns.Name.Buffer = undefined; const under: ?dns.Name = if (origin) |wire| try dns.Name.fromBytes(wire) else null; const encoded = try encode(&buf, text, under); try testing.expectEqualSlices(u8, expected, encoded.message);}
test "absolute, relative and the origin" { const origin = "\x07example\x03com\x00"; try expectEncoded("\x03www\x07example\x03com\x00", "www.example.com.", null); try expectEncoded("\x03www\x07example\x03com\x00", "www", origin); try expectEncoded("\x07example\x03com\x00", "@", origin); try expectEncoded("\x00", ".", null); try expectEncoded("\x01*\x07example\x03com\x00", "*", origin); try testing.expectError(error.NoOrigin, expectEncoded("", "www", null)); try testing.expectError(error.NoOrigin, expectEncoded("", "@", null));}
test "a dot is only a separator when it is not escaped" { const origin = "\x07example\x03com\x00"; // An escaped dot is part of the label, so this name is still relative. try expectEncoded("\x05a.b.c\x07example\x03com\x00", "a\\.b\\.c", origin); // And a trailing escaped dot does not make it absolute either. try expectEncoded("\x02a.\x07example\x03com\x00", "a\\.", origin);}
test "the escapes RFC 1035 defines" { try expectEncoded("\x03a b\x00", "a\\032b.", null); try expectEncoded("\x03a\\b\x00", "a\\\\b.", null); try expectEncoded("\x01\x00\x00", "\\000.", null); try testing.expectError(error.BadEscape, expectEncoded("", "a\\", null)); try testing.expectError(error.BadEscape, expectEncoded("", "a\\99.", null)); try testing.expectError(error.BadEscape, expectEncoded("", "\\256.", null));}
test "the limits" { const long_label: [64]u8 = @splat('a'); try testing.expectError(error.LabelTooLong, expectEncoded("", &long_label, null)); try testing.expectError(error.EmptyLabel, expectEncoded("", "a..b.", null)); try testing.expectError(error.EmptyLabel, expectEncoded("", ".a.", null));
// 255 bytes is the whole name including the root, and the origin counts. const label: [63]u8 = @splat('a'); const four = label ++ "." ++ label ++ "." ++ label ++ "." ++ label ++ "."; try testing.expectError(error.NameTooLong, expectEncoded("", four ++ "b.", null));}
fn expectRelative(expected: []const u8, name: []const u8, origin: ?[]const u8) !void { var name_buf: dns.Name.Buffer = undefined; var origin_buf: dns.Name.Buffer = undefined; const n = try encode(&name_buf, name, null); const o = if (origin) |text| try encode(&origin_buf, text, null) else null; var buf: dns.Name.TextBuffer = undefined; var w = Writer.fixed(&buf); try writeRelative(&w, n, o); try testing.expectEqualStrings(expected, w.buffered());}
test "writing a name back out against an origin" { try expectRelative("www", "www.example.com.", "example.com."); try expectRelative("@", "example.com.", "example.com."); try expectRelative("a.b", "a.b.example.com.", "example.com."); // Not below the origin, so it is written in full. try expectRelative("other.test.", "other.test.", "example.com."); try expectRelative("www.example.com.", "www.example.com.", null); // The root as an origin relativizes everything, minus the trailing dot. try expectRelative("www.example.com", "www.example.com.", ".");}
test "a label that needs escaping gets it back" { try expectRelative("a\\.b", "a\\.b.example.com.", "example.com."); try expectRelative("a\\@b", "a\\@b.example.com.", "example.com."); try expectRelative("\\009", "\\009.example.com.", "example.com.");}