Something went wrong. Try again.
Avahi for Zig: publish and browse mDNS services through the system's Avahi daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the client must do with whatever the Avahi daemon's signals carry.//!//! The daemon is trusted, but what it relays is not: a service's name, host//! and TXT come from whatever answered on the network. So each signal body//! the client decodes -- an item found or lost, a resolved service, a//! state, the daemon's owner changing -- is fed any bytes, and whatever//! arrives, decoding returns, reads only inside the body, and what it keeps//! of a TXT record is bounded.//!//! And what the client must do with all of it together: the second target//! drives a `Client` against a daemon the fuzzer plays, and is described//! where it starts, below.//!//! Each target is an ordinary test as well as a fuzz target. Without//! `--fuzz` the first runs the seeds `tools/fuzz_corpus.zig` makes -- a body//! of every signal -- and the second a few hundred scripts, so `zig build//! test` checks the same properties. `zig build fuzz --fuzz` hands them to//! Zig's fuzzer, and `zig build fuzz-run` to the loop in `tools/fuzz.zig`.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;const Smith = std.testing.Smith;
const avahi = @import("avahi");const mdbus = @import("mdbus");const corpus = @import("fuzz_corpus");
const wire = avahi.wire;
/// The allocator and the `Io` the target runs against: the testing ones/// under `zig build test`, and `tools/fuzz.zig`'s own otherwise.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;pub var io: Io = if (builtin.is_test) testing.io else undefined;
/// Where a body lies, which every string decoded from it must lie inside.const Span = struct { lo: usize, hi: usize,
fn of(outer: []const u8) Span { const lo = @intFromPtr(outer.ptr); return .{ .lo = lo, .hi = lo + outer.len }; }
fn holds(self: Span, inner: []const u8) bool { if (inner.len == 0) return true; const i = @intFromPtr(inner.ptr); return i >= self.lo and i <= self.hi and inner.len <= self.hi - i; }};
/// The first byte says which signal the rest is the body of.fn signalProperty(input: []const u8) !void { if (input.len == 0) return; const body = input[1..]; const span: Span = .of(body); var d: wire.Decoder = .{ .data = body, .endian = if (input[0] & 0x80 != 0) .big else .little }; switch (input[0] % 4) { 0 => { const item = wire.Item.decode(&d) catch return; for ([_][]const u8{ item.name, item.type, item.domain }) |s| try testing.expect(span.holds(s)); }, 1 => { const r = wire.Resolved.decode(&d) catch return; for ([_][]const u8{ r.name, r.type, r.domain, r.host, r.address }) |s| try testing.expect(span.holds(s)); try testing.expect(r.txt().len <= wire.max_txt); for (r.txt()) |t| try testing.expect(span.holds(t)); _ = r.txtValue("path"); }, 2 => { const s = wire.StateChanged.decode(&d) catch return; try testing.expect(span.holds(s.@"error")); }, else => { const n = wire.NameOwnerChanged.decode(&d) catch return; for ([_][]const u8{ n.name, n.old_owner, n.new_owner }) |s| try testing.expect(span.holds(s)); }, }}
test "fuzz the daemon's signals" { try testing.fuzz({}, fuzzSignals, .{ .corpus = &corpus.signal_inputs });}
fn fuzzSignals(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; try signalProperty(buffer[0..smith.slice(&buffer)]);}
test "a TXT key found without regard to case, and not by prefix" { const txt = [_][]const u8{ "pathology=no", "PATH=/sendspin", "=x", "empty" }; try testing.expectEqualStrings("/sendspin", avahi.findTxt(&txt, "path").?); try testing.expectEqualStrings("", avahi.findTxt(&txt, "EMPTY").?); try testing.expect(avahi.findTxt(&txt, "") == null);}
// The client, against a daemon the fuzzer plays.//// Everything `Client` decides is made of a message arriving and the calls// it makes in answer, so the fuzzer chooses both: a script of steps --// publish, browse, remove, and every signal the daemon sends -- and how the// daemon answers each call the client makes, a collision, a refusal, a// timeout or an object path too long to keep included. Whatever it chooses,// the client must not crash or leak, must send only messages the bus would// take, must not loop, and must keep its lists consistent: no resolver// outliving its browser, no group or browser kept that it was told to drop.
/// Most of each a script holds at once, which bounds the work in one input.const max_groups = 4;const max_browsers = 4;const max_steps = 64;/// Calls one step may make before the daemon stops answering: several times/// what a step needs -- the daemon coming back with every group colliding/// all the way to the last rename is a few hundred -- so reaching it is a/// loop.const max_calls_per_step = 1000;
const long_name: [80]u8 = @splat('k');const long_path: [140]u8 = @splat('p');
/// The strings a script is made of: ordinary ones first, so an input that/// asks for little gets them, then the edges -- empty, long, not UTF-8, a/// NUL inside.const names = [_][]const u8{ "Kitchen", "Kitchen #2", "", &long_name, "\xff\xfe", "a\x00b" };const service_types = [_][]const u8{ "_sendspin._tcp", "_http._tcp", "", "\xff" };const txts = [_][]const u8{ "path=/sendspin", "name=Kitchen", "PATH=x", "=", "", "a\x00b", "\xc3" };const domains = [_][]const u8{ "local", "" };const errors = [_][]const u8{ "", "Local name collision" };const owners = [_][]const u8{ ":1.42", "" };/// A daemon's state, and an entry group's: the same numbers, and one past.const states = [_]i32{ 2, 1, 0, 3, 4, -1, 99 };const flag_sets = [_]u32{ 0, wire.lookup_result_our_own, wire.lookup_result_local };const interfaces = [_]i32{ 2, wire.if_unspec };const protocols = [_]i32{ 0, 1, -1, 7 };const txt_counts = [_]usize{ 2, 0, 1, wire.max_txt, wire.max_txt + 8 };
fn pick(s: *Smith, comptime T: type, table: []const T) T { return table[s.index(table.len)];}
/// Whether the script goes on. On a fixed input, for as long as a whole/// value is left, rather than `eos`, which reads one byte and leaves every/// value after it out of alignment.fn more(s: *Smith) bool { if (s.in) |in| return in.len >= 8; return !s.eos();}
/// How the daemon answers a call when it does not answer as asked.const Trouble = enum(u8) { collision, not_permitted, service_unknown, other_error, timeout, closed, wrong_type };
/// Whether the rare one of two things happens. Weighted for the fuzzer; on a/// fixed input it is a value of exactly one, every other value being out of/// range and so the common case -- which is what keeps a script of small/// numbers from making publishing, three calls answered as asked in a row,/// a thing that almost never happens.fn rarely(s: *Smith) bool { return s.boolWeighted(7, 1);}
/// The Avahi daemon, as far as the client can see it.const Fake = struct { smith: *Smith, serial: u32 = 0, issued: u32 = 0, /// Every object path handed out, so a signal can be addressed to one. objects: std.ArrayList([]u8) = .empty, calls: usize = 0, /// Set when the client sent what the bus would have refused. violation: ?anyerror = null,
fn deinit(self: *Fake) void { for (self.objects.items) |p| backing.free(p); self.objects.deinit(backing); }
fn daemon(self: *Fake) avahi.Client.Daemon { return .{ .context = self, .call = call }; }
fn nextSerial(self: *Fake) u32 { self.serial +%= 1; if (self.serial == 0) self.serial = 1; return self.serial; }
fn message(self: *Fake, metadata: mdbus.wire.Metadata, body: []const u8) !avahi.Client.Message { const data = try mdbus.wire.encodeMessage(backing, metadata, self.nextSerial(), body, 0); errdefer backing.free(data); return mdbus.wire.parseMessage(backing, data, &.{}); }
fn call(context: *anyopaque, method: avahi.Client.Method, signature: []const u8, body: []const u8) avahi.Client.Daemon.CallError!avahi.Client.Message { const self: *Fake = @ptrCast(@alignCast(context)); // What the client sends has to be a message the bus would take. // The connection refuses to encode a bad one, and that is an error // the client handles like any other; one that encodes and does not // parse would have the bus disconnect it. const request = try mdbus.wire.encodeMessage(backing, .{ .message_type = .method_call, .path = method.path, .interface = method.interface, .member = method.member, .destination = method.destination, .signature = signature, }, 1, body, 0); if (mdbus.wire.parseMessage(backing, request, &.{})) |parsed| { var m = parsed; m.deinit(); } else |err| { backing.free(request); self.violation = err; return error.ProtocolError; }
self.calls += 1; if (self.calls > max_calls_per_step) { self.violation = error.TooManyCalls; return error.Timeout; }
const s = self.smith; const reply_to = 1; if (rarely(s)) switch (s.value(Trouble)) { .collision => return self.errorReply("org.freedesktop.Avahi.CollisionError"), .not_permitted => return self.errorReply("org.freedesktop.Avahi.NotPermittedError"), .service_unknown => return self.errorReply("org.freedesktop.DBus.Error.ServiceUnknown"), .other_error => return self.errorReply("org.freedesktop.Avahi.InvalidServiceNameError"), .timeout => return error.Timeout, .closed => return error.ConnectionClosed, // A well-formed reply of the wrong type: the bus checks a body // against its signature, not against what the caller expected. .wrong_type => { var e: wire.Encoder = .init(backing); defer e.deinit(); try e.string("/not/what/was/asked"); return self.message(.{ .message_type = .method_return, .reply_serial = reply_to, .signature = "s" }, e.bytes()); }, };
var e: wire.Encoder = .init(backing); defer e.deinit(); const member = method.member; const eql = std.mem.eql; var sig: []const u8 = ""; if (eql(u8, member, "GetState")) { try e.int32(pick(s, i32, &states)); sig = "i"; } else if (eql(u8, member, "EntryGroupNew") or eql(u8, member, "ServiceBrowserNew") or eql(u8, member, "ServiceResolverNew")) { var buf: [64]u8 = undefined; const path: []const u8 = if (!rarely(s)) std.fmt.bufPrint(&buf, "/Client1/{s}{d}", .{ member[0 .. member.len - 3], self.issued }) catch unreachable else switch (s.index(3)) { 0 => if (self.objects.items.len == 0) "/Client1/Reused" else pick(s, []u8, self.objects.items), 1 => "/" ++ &long_path, else => "/", }; self.issued += 1; try e.objectPath(path); const owned = try backing.dupe(u8, path); errdefer backing.free(owned); try self.objects.append(backing, owned); sig = "o"; } else if (eql(u8, member, "GetAlternativeServiceName")) { var d: wire.Decoder = .{ .data = body, .endian = .little }; const name = d.string() catch ""; var buf: [256]u8 = undefined; try e.string(if (!rarely(s)) std.fmt.bufPrint(&buf, "{s} #2", .{name}) catch "Kitchen #3" else if (s.index(2) == 0) name else pick(s, []const u8, &names)); sig = "s"; } else if (eql(u8, member, "Free")) { // Gone, so no longer somewhere a signal is likely to go. for (self.objects.items, 0..) |p, i| if (eql(u8, p, method.path)) { backing.free(self.objects.swapRemove(i)); break; }; } return self.message(.{ .message_type = .method_return, .reply_serial = reply_to, .signature = sig }, e.bytes()); }
fn errorReply(self: *Fake, name: []const u8) !avahi.Client.Message { return self.message(.{ .message_type = .error_reply, .error_name = name, .reply_serial = 1 }, ""); }
/// A path a signal from an object of `kind` goes to: mostly one of the /// daemon's objects of that kind, sometimes any of its objects, and now /// and then one it never made. A browser's item arriving at the browser /// and its resolver's answer arriving at the resolver are two steps in a /// row that each have to find the one object that is waiting. fn target(self: *Fake, kind: []const u8) []const u8 { const s = self.smith; if (!rarely(s)) { var of_kind: [16][]const u8 = undefined; var n: usize = 0; for (self.objects.items) |p| if (n < of_kind.len and std.mem.find(u8, p, kind) != null) { of_kind[n] = p; n += 1; }; if (n != 0) return pick(s, []const u8, of_kind[0..n]); } if (self.objects.items.len != 0 and !rarely(s)) return pick(s, []u8, self.objects.items); return pick(s, []const u8, &.{ "/Client1/EntryGroup0", "/", "/Client9/ServiceBrowser1" }); }};
/// What the browsers' handlers were told, and whether any of it was wrong.const Seen = struct { n_found: usize = 0, n_lost: usize = 0, bad: bool = false, checksum: u64 = 0,
fn handler(self: *Seen) avahi.Client.Handler { return .{ .context = self, .found = onFound, .lost = onLost }; }
/// Read every byte, so that a string the client freed or never copied /// is a crash here rather than a quiet success. fn touch(self: *Seen, s: []const u8) void { for (s) |b| self.checksum +%= b; }
fn onFound(context: *anyopaque, service: *const avahi.Resolved) void { const self: *Seen = @ptrCast(@alignCast(context)); self.n_found += 1; if (service.txt().len > wire.max_txt) self.bad = true; for ([_][]const u8{ service.name, service.type, service.domain, service.host, service.address }) |s| self.touch(s); for (service.txt()) |t| self.touch(t); }
fn onLost(context: *anyopaque, item: *const avahi.Item) void { const self: *Seen = @ptrCast(@alignCast(context)); self.n_lost += 1; for ([_][]const u8{ item.name, item.type, item.domain }) |s| self.touch(s); }};
const Step = enum { publish, browse, group_state, item_new, item_remove, found, resolver_failure, server_state, owner, remove_group, remove_browser, stray };
const Script = struct { fake: *Fake, client: *avahi.Client, seen: *Seen, groups: std.ArrayList(*avahi.Client.EntryGroup) = .empty, browsers: std.ArrayList(*avahi.Client.Browser) = .empty,
fn signal(self: *Script, path: []const u8, interface: []const u8, member: []const u8, signature: []const u8, body: []const u8) !void { var m = self.fake.message(.{ .message_type = .signal, .path = path, .interface = interface, .member = member, .signature = signature, }, body) catch return; defer m.deinit(); self.client.handle(&m); }
fn step(self: *Script) !void { const s = self.fake.smith; var e: wire.Encoder = .init(backing); defer e.deinit(); switch (s.value(Step)) { .publish => { if (self.groups.items.len == max_groups) return; var txt_buf: [3][]const u8 = undefined; const n_txt = s.index(txt_buf.len + 1); for (txt_buf[0..n_txt]) |*t| t.* = pick(s, []const u8, &txts); const g = self.client.publish(.{ .name = pick(s, []const u8, &names), .type = pick(s, []const u8, &service_types), .domain = pick(s, []const u8, &.{ "", "local", "\xff" }), .host = pick(s, []const u8, &.{ "", "kitchen.local" }), .port = s.value(u16), .txt = txt_buf[0..n_txt], .interface = pick(s, i32, &interfaces), .protocol = @fromBackingInt(pick(s, i32, &protocols)), }) catch return; try self.groups.append(backing, g); }, .browse => { if (self.browsers.items.len == max_browsers) return; const b = self.client.browse(pick(s, []const u8, &service_types), .{ .domain = pick(s, []const u8, &domains), .protocol = @fromBackingInt(pick(s, i32, &protocols)), .address_protocol = @fromBackingInt(pick(s, i32, &protocols)), .include_own = s.index(2) == 0, }, self.seen.handler()) catch return; try self.browsers.append(backing, b); }, .group_state, .server_state => |which| { try e.int32(pick(s, i32, &states)); try e.string(pick(s, []const u8, &errors)); if (which == .group_state) { try self.signal(self.fake.target("EntryGroup"), "org.freedesktop.Avahi.EntryGroup", "StateChanged", "is", e.bytes()); } else { try self.signal("/", "org.freedesktop.Avahi.Server", "StateChanged", "is", e.bytes()); } }, .item_new, .item_remove => |which| { try e.int32(pick(s, i32, &interfaces)); try e.int32(pick(s, i32, &protocols)); try e.string(pick(s, []const u8, &names)); try e.string(pick(s, []const u8, &service_types)); try e.string(pick(s, []const u8, &domains)); try e.uint32(pick(s, u32, &flag_sets)); const member = if (which == .item_new) "ItemNew" else "ItemRemove"; try self.signal(self.fake.target("ServiceBrowser"), "org.freedesktop.Avahi.ServiceBrowser", member, "iisssu", e.bytes()); }, .found => { try e.int32(pick(s, i32, &interfaces)); try e.int32(pick(s, i32, &protocols)); try e.string(pick(s, []const u8, &names)); try e.string(pick(s, []const u8, &service_types)); try e.string(pick(s, []const u8, &domains)); try e.string("kitchen.local"); try e.int32(pick(s, i32, &protocols)); try e.string(pick(s, []const u8, &.{ "192.168.1.20", "fe80::1", "" })); try e.uint16(s.value(u16)); var txt_buf: [wire.max_txt + 8][]const u8 = undefined; const n_txt = pick(s, usize, &txt_counts); for (txt_buf[0..n_txt], 0..) |*t, i| t.* = txts[i % 3]; try wire.encodeTxt(&e, txt_buf[0..n_txt]); try e.uint32(pick(s, u32, &flag_sets)); try self.signal(self.fake.target("ServiceResolver"), "org.freedesktop.Avahi.ServiceResolver", "Found", wire.Resolved.signature, e.bytes()); }, .resolver_failure => { try e.string("Timeout reached"); try self.signal(self.fake.target("ServiceResolver"), "org.freedesktop.Avahi.ServiceResolver", "Failure", "s", e.bytes()); }, .owner => { try e.string(pick(s, []const u8, &.{ "org.freedesktop.Avahi", "org.example.Other" })); try e.string(pick(s, []const u8, &owners)); try e.string(pick(s, []const u8, &owners)); try self.signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged", "sss", e.bytes()); }, .remove_group => { if (self.groups.items.len == 0) return; self.groups.swapRemove(s.index(self.groups.items.len)).remove(); }, .remove_browser => { if (self.browsers.items.len == 0) return; self.browsers.swapRemove(s.index(self.browsers.items.len)).remove(); }, // A signal the client knows the name of with a body it does not // expect, or one it has never heard of. .stray => { try e.string("unexpected"); const member = pick(s, []const u8, &.{ "ItemNew", "Found", "StateChanged", "AllForNow", "CacheExhausted" }); const interface = pick(s, []const u8, &.{ "org.freedesktop.Avahi.ServiceBrowser", "org.freedesktop.Avahi.ServiceResolver", "org.freedesktop.Avahi.EntryGroup", "org.freedesktop.Avahi.Server", "org.freedesktop.DBus", }); try self.signal(self.fake.target(""), interface, member, "s", e.bytes()); }, } }
/// What has to be true after every step. fn check(self: *Script) !void { if (self.fake.violation) |err| return err; if (self.seen.bad) return error.TooManyTxt; const c = self.client; try testing.expectEqual(self.groups.items.len, c.groups.items.len); try testing.expectEqual(self.browsers.items.len, c.browsers.items.len); for (self.groups.items) |g| { try testing.expect(std.mem.findScalar(*avahi.Client.EntryGroup, c.groups.items, g) != null); try testing.expect(g.path_len <= g.path_buf.len); } for (self.browsers.items) |b| try testing.expect(std.mem.findScalar(*avahi.Client.Browser, c.browsers.items, b) != null); for (c.resolvers.items) |r| { try testing.expect(std.mem.findScalar(*avahi.Client.Browser, c.browsers.items, r.browser) != null); try testing.expect(r.path_len <= r.path_buf.len); } }};
fn fuzzClient(_: void, smith: *Smith) !void { // The client warns of every refusal it is handed, and here that is // every other call. if (builtin.is_test) testing.log_level = .err; var fake: Fake = .{ .smith = smith }; defer fake.deinit(); const client = avahi.Client.initDaemon(io, backing, fake.daemon()) catch return; defer client.deinit(); var seen: Seen = .{}; var script: Script = .{ .fake = &fake, .client = client, .seen = &seen }; defer script.groups.deinit(backing); defer script.browsers.deinit(backing);
var steps: usize = 0; while (steps < max_steps and more(smith)) : (steps += 1) { fake.calls = 0; // A signal with a string the bus could not carry is one the daemon // cannot send: skipped, not failed. script.step() catch |err| switch (err) { error.InvalidString => {}, else => return err, }; try script.check(); }}
test "fuzz the client against a daemon the fuzzer plays" { // Scripts of small numbers, which is what a fixed input has to be made // of: one out of a choice's range answers with its first option. var prng: std.Random.DefaultPrng = .init(0x5eed); const random = prng.random(); var words: [1024]u64 = undefined; for (0..200) |_| { const n = random.uintAtMost(usize, words.len); for (words[0..n]) |*w| w.* = random.uintLessThan(u64, 12); var smith: Smith = .{ .in = std.mem.sliceAsBytes(words[0..n]) }; try fuzzClient({}, &smith); } try testing.fuzz({}, fuzzClient, .{});}
/// A target, as `tools/fuzz.zig` drives it.pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating, which stand in for the coverage feedback a /// real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. `Smith.slice` yields /// an *empty* slice for a length larger than that, not a truncated /// one, so a generator that does not know it feeds the target nothing. content_max: usize = 0, /// What it reads: one slice, or nothing but small values, eight bytes /// each -- for which random bytes are useless, every one of them out of /// range and so answered with a choice's first option. input: enum { slice, values } = .slice,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "signals", .run = Driven(fuzzSignals).run, .corpus = &corpus.signals, .content_max = 4096 }, .{ .name = "client", .run = Driven(fuzzClient).run, .corpus = &.{}, .input = .values },};