Something went wrong. Try again.
BIND zone files for Zig 0.16: read one, edit it, write it back
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166#!/usr/bin/env python3# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Compares this library's reading of a zone file with BIND's.
Everything in `zig build test` is this library agreeing with itself, whichcannot catch the reader and the writer being wrong the same way: a type whosefields this encodes in the wrong order will be decoded back in the wrong orderand round-trip perfectly. The check for that is a second opinion, and BIND's isthe one every zone file in the world was written against.
The comparison is of records rather than of text, because the two write themout differently and neither is wrong:
1. this library reads the file and writes it in canonical form; 2. `named-compilezone` reads the same file and writes whatever it writes; 3. this library reads *that* and writes it in canonical form as well.
If the two canonical forms differ, the two libraries disagree about what thefile says. Going through our own writer for both is what removes everydifference that is only a matter of layout -- where BIND breaks a long hexstring, whether it quotes an `alpn`, which order it dumps the records in.
Run it as `zig build differential`, from inside `nix develop`, where BIND is onthe path."""
import pathlibimport subprocessimport sys
# Zone files that are not compared, and why. A file is only here because BIND# cannot read it at all: the point of this check is the disagreements, so a# skip has to be a fact about the other implementation rather than a way to# quieten a failure.NOT_COMPARED = { "legacy.test.zone": ( "BIND has removed A6 and NXT, has no mnemonic for NSAP-PTR, NINFO, " "AVC, RESINFO or WALLET, and the version in the devshell predates " "DSYNC" ),}
# RFC 2181 §5.2 says every record of an RRset must have the same time to live,# and BIND enforces it while reading: a set whose records disagree comes out# with the first record's time to live on all of them. This library does not --# it reads what is written and says so -- and neither reading is wrong, so the# comparison is made after applying BIND's rule to both sides. How many records# it moved is printed, because a difference that is normalized away silently is# a difference nobody knows about.def unify_rrset_ttls(text): seen = {} out = [] changed = 0 for line in text.splitlines(): owner, ttl, rest = line.split(" ", 2) record_type = rest.split(" ", 1)[0] key = (owner.lower(), record_type) first = seen.setdefault(key, ttl) if first != ttl: changed += 1 ttl = first out.append(f"{owner} {ttl} {rest}") return "\n".join(out) + "\n", changed
# What to tell named-compilezone not to check. All of them are checks on the# zone as a whole -- that a delegation has glue, that a name with a CNAME has# nothing else -- and this library has no opinion about any of them, so a zone# written to exercise the parser would fail them for reasons that are not what# is being compared.COMPILEZONE_FLAGS = ["-i", "none", "-k", "ignore", "-n", "ignore", "-m", "ignore"]
def run(command, stdin=None): result = subprocess.run( command, input=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) return result
def canonical(zonecat, origin, path=None, text=None): """This library's canonical form of a zone, from a file or from text.""" command = [zonecat, "--canonical", "--sort", "--origin", origin] command.append(path if path is not None else "-") result = run(command, stdin=text) if result.returncode != 0: raise RuntimeError(f"zonecat: {result.stderr.strip()}") return result.stdout
def compile_zone(origin, path): """BIND's reading of the same file, in whatever shape BIND writes.""" command = ["named-compilezone", *COMPILEZONE_FLAGS, "-o", "-", origin, str(path)] result = run(command) if result.returncode != 0: raise RuntimeError(f"named-compilezone: {result.stderr.strip()}") # The dump is on standard output with a couple of progress lines mixed in, # and those are the two that do not start a record. lines = [ line for line in result.stdout.splitlines() if not line.startswith(("zone ", "dump zone", "OK")) ] return "\n".join(lines) + "\n"
def main(argv): if len(argv) < 3: print("usage: differential.py <zonecat> <zones directory>", file=sys.stderr) return 2 zonecat = argv[1] zones = pathlib.Path(argv[2])
disagreements = 0 for path in sorted(zones.glob("*.zone")): origin = path.name[: -len(".zone")] if path.name in NOT_COMPARED: print(f"{path.name}: not compared -- {NOT_COMPARED[path.name]}") continue
try: ours = canonical(zonecat, origin, path=str(path)) theirs = canonical(zonecat, origin, text=compile_zone(origin, path)) except RuntimeError as error: print(f"{path.name}: FAILED -- {error}") disagreements += 1 continue
ours, unified = unify_rrset_ttls(ours) theirs, _ = unify_rrset_ttls(theirs)
if ours == theirs: note = "" if unified != 0: note = ( f", after giving {unified} record(s) the time to live of " "the rrset they are in, as BIND does and this does not" ) print(f"{path.name}: {len(ours.splitlines())} records, agreed{note}") continue
disagreements += 1 print(f"{path.name}: DISAGREED") mine = set(ours.splitlines()) bind = set(theirs.splitlines()) for line in sorted(mine - bind): print(f" only here: {line}") for line in sorted(bind - mine): print(f" only BIND: {line}")
if disagreements != 0: print(f"\n{disagreements} zone(s) disagreed.") return 1 print("\nEvery zone reads the same way here as it does in BIND.") return 0
if __name__ == "__main__": sys.exit(main(sys.argv))