Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What this library makes of a message, in one line, so that another//! implementation can be asked the same question.//!//! `tests/differential.py` is the other half: it mutates the captured messages//! and puts the same bytes to this and to dnspython, and a disagreement about//! whether a message is well formed is either a bug or a strictness choice//! worth having written down. The reason it needs a program rather than a test//! is that the comparison happens outside Zig; the reason the program is this//! small is that everything it knows how to say has to be something the other//! implementation can be asked too.//!//! ```console//! $ verdict --corpus > cases.hex # the captured messages//! $ verdict cases.hex # a verdict per line//! OK 1 3//! ERR Truncated//! ```//!//! `OK` is followed by how many questions and how many records were decoded,//! not counting the `opt` pseudo-record -- because the implementation on the//! other side lifts that out of the additional section rather than counting it//! as a record, and a count that means two different things compares two//! different things.
const std = @import("std");const Io = std.Io;
const corpus = @import("corpus");const dns = @import("dns");
/// The longest line of hex a message can be written as.const max_line = 2 * dns.max_message_len;
pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa;
var stdout_buffer: [64 * 1024]u8 = undefined; var stdout_file: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file.interface; defer stdout.flush() catch {};
var path: ?[]const u8 = null; var corpus_wanted = false;
var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); while (args.next()) |argument| { if (std.mem.eql(u8, argument, "--corpus")) { corpus_wanted = true; } else if (std.mem.startsWith(u8, argument, "-")) { path = null; break; } else { path = argument; } }
if (!corpus_wanted and path == null) { try stdout.writeAll( \\usage: verdict [--corpus | FILE] \\ \\ --corpus write the captured messages as hex, one per line \\ FILE a file of hex messages, one per line: writes a \\ verdict for each, in the same order \\ ); return; }
if (corpus_wanted) { for (corpus.all) |capture| { try stdout.print("{x}\n", .{capture.bytes}); } return stdout.flush(); }
// A line at a time, rather than the whole file: a run of a million cases // is a hex file of several hundred megabytes, and reading it in one piece // put a limit on `--count` that had nothing to do with DNS -- it failed // with `StreamTooLong` from whatever allocation cap was chosen here. const file = try Io.Dir.cwd().openFile(io, path.?, .{}); defer file.close(io);
// Big enough for the longest line that is not already too long, so that // `StreamTooLong` means the line itself is malformed rather than that the // buffer was small. const line_buffer = try gpa.alloc(u8, max_line + 1); defer gpa.free(line_buffer); var file_reader: Io.File.Reader = .init(file, io, line_buffer); const in = &file_reader.interface;
var bytes: [dns.max_message_len]u8 = undefined; while (true) { // `takeDelimiter` treats the end of the stream as one, so a last line // without a newline is still a case, and answers null only when there // is nothing left at all. const line = in.takeDelimiter('\n') catch |err| switch (err) { // A line with no newline within the buffer, so longer than any // message can be written as. Say so and step over the rest of it. // The length check below catches the same thing for a last line // that ends the file instead of ending with a newline. error.StreamTooLong => { try stdout.writeAll("BADHEX\n"); _ = in.discardDelimiterInclusive('\n') catch break; continue; }, else => |e| return e, } orelse break; const trimmed = std.mem.trim(u8, line, " \r\t"); if (trimmed.len == 0) continue; if (trimmed.len > max_line or trimmed.len % 2 != 0) { try stdout.writeAll("BADHEX\n"); continue; } const decoded = std.fmt.hexToBytes(bytes[0 .. trimmed.len / 2], trimmed) catch { try stdout.writeAll("BADHEX\n"); continue; }; if (verdict(decoded)) |counts| { try stdout.print("OK {d} {d}\n", .{ counts.questions, counts.records }); } else |err| { try stdout.print("ERR {s}\n", .{@errorName(err)}); } } try stdout.flush();}
const Counts = struct { questions: u16, records: usize };
/// Decode a message and everything in it. Anything that goes wrong is the/// verdict; nothing here is lenient that the library is not.fn verdict(bytes: []const u8) !Counts { const message = try dns.Message.parse(bytes); // Trailing bytes are not an error to `parse`, which reports them rather // than refusing the message. They are one here, because the comparison is // against a decoder that was asked not to ignore them. if (message.trailing().len != 0) return error.TrailingBytes;
var questions = message.questions(); while (try questions.next()) |_| {}
// The EDNS rules as well as the framing: at most one `opt` record, and // its owner name the root. The decoder on the other side enforces both, // and a verdict that leaves out a check the library offers is comparing // less than it could. _ = try message.opt();
var records: usize = 0; inline for ([_]dns.Section{ .answer, .authority, .additional }) |which| { var it = message.section(which); while (try it.next()) |record| { _ = try record.data(); if (which == .additional and record.type == .opt) continue; records += 1; } } return .{ .questions = message.header.counts.question, .records = records };}
const testing = std.testing;
test "every captured message gets a verdict" { for (corpus.all) |capture| { _ = verdict(capture.bytes) catch |err| { std.debug.print("{s}: {s}\n", .{ capture.what, @errorName(err) }); return err; }; }}
test "the OPT record is not counted as a record" { // The captured query holds one question and one record, and that record is // the OPT. const counts = try verdict(corpus.query.bytes); try testing.expectEqual(@as(u16, 1), counts.questions); try testing.expectEqual(@as(usize, 0), counts.records);}
test "a message that does not decode says why" { try testing.expectError(error.Truncated, verdict("\x12\x34"));}