Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A zone file in, a zone file out.//!//! It is the library's own command line, and it is the program the//! differential check drives: `--canonical` prints one record per line, every//! name in full, nothing implied, which is the shape two zone files have to be//! in before `diff` can say anything sensible about them.//!//! ```console//! $ zonecat --origin example.com. db.example.com//! $ zonecat --canonical --sort db.example.com | diff - other.canonical//! $ named-compilezone -o - example.com db.example.com | zonecat --canonical -//! ```//!//! It is also where `$INCLUDE` is shown working. The library opens no files,//! so an include comes back from the parser and this opens it -- relative to//! the directory the file that included it is in, which is what BIND does and//! what anybody writing one expects.
const std = @import("std");const Io = std.Io;
const dns = @import("dns");const zone = @import("zone");
const usage = \\usage: zonecat [options] [file] \\ \\Reads a zone file and writes it back. With no file, or with `-`, it reads \\standard input. \\ \\ --origin NAME the apex, for a file that does not say \\ --ttl SECONDS the default time to live, for a file with no $TTL \\ --canonical one record per line, every name in full, nothing implied \\ --sort in the canonical order of RFC 4034 section 6 \\ --include follow $INCLUDE, relative to the file that asked \\ --count print how many records there are and nothing else \\ --help this \\;
/// Enough for any zone file line; the reader refills it as it goes.const read_buffer_size = 64 * 1024;
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator());
var stderr_buffer: [1024]u8 = undefined; var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); const stderr = &stderr_writer.interface;
var path: ?[]const u8 = null; var origin: ?[]const u8 = null; var ttl: ?u32 = null; var canonical = false; var sort = false; var follow_includes = false; var count_only = false;
var i: usize = 1; while (i < args.len) : (i += 1) { const argument = args[i]; if (std.mem.eql(u8, argument, "--help")) { try stderr.writeAll(usage); try stderr.flush(); return; } else if (std.mem.eql(u8, argument, "--canonical")) { canonical = true; } else if (std.mem.eql(u8, argument, "--sort")) { sort = true; } else if (std.mem.eql(u8, argument, "--include")) { follow_includes = true; } else if (std.mem.eql(u8, argument, "--count")) { count_only = true; } else if (std.mem.eql(u8, argument, "--origin")) { i += 1; if (i >= args.len) return fail(stderr, "--origin takes a name", .{}); origin = args[i]; } else if (std.mem.eql(u8, argument, "--ttl")) { i += 1; if (i >= args.len) return fail(stderr, "--ttl takes a number", .{}); ttl = std.fmt.parseUnsigned(u32, args[i], 10) catch return fail(stderr, "--ttl takes a number, not \"{s}\"", .{args[i]}); } else if (std.mem.startsWith(u8, argument, "--")) { return fail(stderr, "no option is called {s}", .{argument}); } else if (path == null) { path = argument; } else { return fail(stderr, "one file at a time", .{}); } } if (path != null and std.mem.eql(u8, path.?, "-")) path = null;
// The directory an `$INCLUDE` is relative to: the one the file is in, and // the working directory for standard input. var base = Io.Dir.cwd(); var opened_base = false; if (path) |p| { if (std.fs.path.dirname(p)) |directory| { base = Io.Dir.cwd().openDir(io, directory, .{}) catch |err| return fail(stderr, "cannot open {s}: {s}", .{ directory, @errorName(err) }); opened_base = true; } } defer if (opened_base) base.close(io);
var input: Io.File = if (path) |p| Io.Dir.cwd().openFile(io, p, .{}) catch |err| return fail(stderr, "cannot open {s}: {s}", .{ p, @errorName(err) }) else .stdin(); defer if (path != null) input.close(io);
const buffer = try gpa.alloc(u8, read_buffer_size); defer gpa.free(buffer); var input_reader: Io.File.Reader = .init(input, io, buffer);
var diagnostics: zone.Diagnostics = .{}; var parser = zone.Parser.init(gpa, &input_reader.interface, .{ .origin = origin, .default_ttl = ttl, .includes = if (follow_includes) .report else .refuse, .file = path orelse "<stdin>", .diagnostics = &diagnostics, }) catch |err| return report(stderr, err, diagnostics); defer parser.deinit();
var z = try zone.Zone.init(gpa, origin); defer z.deinit();
// Every file this opened, kept until the parse is over: the parser is // reading out of them. var included: std.ArrayList(Included) = .empty; defer { for (included.items) |*one| one.close(io, gpa); included.deinit(gpa); }
while (parser.next() catch |err| return report(stderr, err, diagnostics)) |item| switch (item) { .record => |rr| try z.add(rr), .include => |include| { var one = Included.open(io, gpa, base, include.path) catch |err| return fail(stderr, "cannot open {s}: {s}", .{ include.path, @errorName(err) }); try included.append(gpa, one); parser.pushInclude(&one.reader.interface, include.path) catch |err| return report(stderr, err, diagnostics); }, };
// The zone was built a record at a time rather than by `Zone.parse`, so // nothing has worked out its apex yet. Without one every name is written // in full, which is correct and unreadable. if (z.origin() == null) { z.setOriginFromSoa(); if (z.origin() == null) { try stderr.writeAll( "warning: no --origin and no soa, so every name is written in full\n", ); try stderr.flush(); } }
var stdout_buffer: [64 * 1024]u8 = undefined; var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_writer.interface;
if (count_only) { try stdout.print("{d}\n", .{z.count()}); try stdout.flush(); return; }
if (sort or canonical) z.sortCanonical(); if (!canonical) z.soaFirst(); try z.write(stdout, if (canonical) .canonical else .{}); try stdout.flush();}
/// A file opened because a `$INCLUDE` named it. The reader has to stay where/// it is while the parser reads out of it, so both it and its buffer are on/// the heap.const Included = struct { file: Io.File, reader: *Io.File.Reader, buffer: []u8,
fn open( io: Io, gpa: std.mem.Allocator, base: Io.Dir, path: []const u8, ) !Included { const file = try base.openFile(io, path, .{}); errdefer file.close(io); const buffer = try gpa.alloc(u8, read_buffer_size); errdefer gpa.free(buffer); const reader = try gpa.create(Io.File.Reader); reader.* = .init(file, io, buffer); return .{ .file = file, .reader = reader, .buffer = buffer }; }
fn close(self: *Included, io: Io, gpa: std.mem.Allocator) void { self.file.close(io); gpa.destroy(self.reader); gpa.free(self.buffer); }};
fn fail(stderr: *Io.Writer, comptime fmt: []const u8, args: anytype) noreturn { stderr.print("zonecat: " ++ fmt ++ "\n", args) catch {}; stderr.flush() catch {}; std.process.exit(2);}
/// What the parser refused, said the way a compiler says it, so that an editor/// can jump to the line.fn report(stderr: *Io.Writer, err: anyerror, diagnostics: zone.Diagnostics) noreturn { stderr.print("{f}\n", .{diagnostics}) catch {}; stderr.print("zonecat: {s}\n", .{@errorName(err)}) catch {}; stderr.flush() catch {}; std.process.exit(1);}
test { // Nothing here is worth a test of its own -- it is argument parsing and // file opening around a library that is tested elsewhere -- but it does // have to keep compiling, which is what `zig build check` is for. std.testing.refAllDecls(@This());}