// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A client of the Avahi daemon, over the system bus: publish a service, //! and browse for the services of a type, resolving each one found. //! //! ```zig //! const client = try avahi.Client.connect(io, gpa, environ); //! defer client.deinit(); //! var running = try io.concurrent(avahi.Client.run, .{client}); //! defer { //! client.stop(); //! running.await(io) catch {}; //! } //! const group = try client.publish(.{ .name = "Kitchen", .type = "_sendspin._tcp", .port = 8928, .txt = &.{"path=/sendspin"} }); //! const browser = try client.browse("_sendspin-server._tcp", .{}, handler); //! ``` //! //! Avahi addresses every signal about an object -- a group's state, a //! browser's items, a resolver's answer -- to the client that made it, so //! they arrive with no match rule to install first, and one that comes //! before the reply naming its object waits in the connection's queue until //! that reply has been read. `run` reads them; `publish` and `browse` may be //! called from any task, before or while it runs. //! //! What the daemon does is its own to decide. It may refuse publishing //! altogether -- `disable-user-service-publishing`, which NixOS sets unless //! `services.avahi.publish.userServices` is on -- and `publish` then fails //! with `error.NotPermitted`, which is the cue for a program to answer mDNS //! itself. A name another host has is changed, `Kitchen #2` and on, and the //! group's `name` says what it became. If the daemon restarts, every group is //! published again and every browser made again, since the objects were the //! old daemon's. const Client = @This(); const std = @import("std"); const Io = std.Io; const linux = std.os.linux; const posix = std.posix; const mdbus = @import("mdbus"); const wire = @import("wire.zig"); const Connection = mdbus.Connection; const Encoder = Connection.Encoder; pub const Message = Connection.Message; pub const Method = Connection.Method; const log = std.log.scoped(.avahi); pub const Service = wire.Service; pub const Item = wire.Item; pub const Resolved = wire.Resolved; pub const Protocol = wire.Protocol; pub const EntryGroupState = wire.EntryGroupState; pub const ServerState = wire.ServerState; const avahi_name = "org.freedesktop.Avahi"; const server_interface = "org.freedesktop.Avahi.Server"; const group_interface = "org.freedesktop.Avahi.EntryGroup"; const browser_interface = "org.freedesktop.Avahi.ServiceBrowser"; const resolver_interface = "org.freedesktop.Avahi.ServiceResolver"; const call_timeout_ms = 5000; /// Tries at another name, when one collides locally, before giving up. const max_renames = 16; io: Io, gpa: std.mem.Allocator, /// Where the calls to the daemon go: the system bus, or a stand-in. bus: union(enum) { connection: Connection, daemon: Daemon, }, /// Held over the connection and the lists: `run` and `publish`/`browse` /// share both. Never held while a handler is called. lock: Io.Mutex = .init, /// Written to wake `run` from its poll: to stop, or to read what a call /// from another task left queued. Null for a client on a `Daemon`, which /// has no `run` to wake. wake_fd: ?posix.fd_t, stopping: std.atomic.Value(bool) = .init(false), groups: std.ArrayList(*EntryGroup) = .empty, browsers: std.ArrayList(*Browser) = .empty, resolvers: std.ArrayList(Resolver) = .empty, /// Connect to the system bus and check that the Avahi daemon is there. /// `error.AvahiUnavailable` if there is no bus or no daemon. A daemon still /// probing for its host's name will do: what is published before it is /// running is published once it is. pub fn connect(io: Io, gpa: std.mem.Allocator, environ: std.process.Environ) !*Client { const self = try gpa.create(Client); errdefer gpa.destroy(self); const rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK); if (linux.errno(rc) != .SUCCESS) return error.SystemResources; const wake_fd: posix.fd_t = @intCast(rc); errdefer _ = linux.close(wake_fd); // Connected in place, and released from there on an error: the calls // below grow the connection's buffers, so a copy made before them would // no longer own what has to be freed. const connection = Connection.connectSystem(io, gpa, environ) catch return error.AvahiUnavailable; self.* = .{ .io = io, .gpa = gpa, .bus = .{ .connection = connection }, .wake_fd = wake_fd }; errdefer self.bus.connection.deinit(); // The one signal that is broadcast rather than addressed to us: the // daemon coming and going, after which its objects are gone. self.bus.connection.addMatch("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='" ++ avahi_name ++ "'") catch return error.AvahiUnavailable; // And the daemon's own state, which is broadcast too: groups can only // be committed while it is running. self.bus.connection.addMatch("type='signal',sender='" ++ avahi_name ++ "',interface='" ++ server_interface ++ "',member='StateChanged'") catch return error.AvahiUnavailable; _ = self.serverStateLocked() catch return error.AvahiUnavailable; return self; } /// A stand-in for the Avahi daemon: what each call to it answers. A client /// made on one with `initDaemon` has no bus, so that the tests and the fuzz /// target in `tests/fuzz.zig` can drive everything `run` would -- every /// reply, and every signal through `handle` -- with no I/O at all. pub const Daemon = struct { context: *anyopaque, /// The reply to `method`, an error reply included, as a message the /// caller frees; or an error, as the connection would give one. call: *const fn (context: *anyopaque, method: Method, signature: []const u8, body: []const u8) CallError!Message, pub const CallError = Connection.Error || mdbus.wire.Error || std.mem.Allocator.Error; }; /// A client whose calls go to `daemon` rather than over a bus. Asks the /// daemon's state, as `connect` does. `run` is not for it: hand it what the /// daemon would send with `handle`. pub fn initDaemon(io: Io, gpa: std.mem.Allocator, daemon: Daemon) !*Client { const self = try gpa.create(Client); errdefer gpa.destroy(self); self.* = .{ .io = io, .gpa = gpa, .bus = .{ .daemon = daemon }, .wake_fd = null }; _ = try self.serverStateLocked(); return self; } /// Close the connection -- which has the daemon withdraw everything /// published and drop every browser -- and free everything. `run` must have /// returned. pub fn deinit(self: *Client) void { const gpa = self.gpa; for (self.groups.items) |g| g.destroy(); self.groups.deinit(gpa); for (self.browsers.items) |b| b.destroy(); self.browsers.deinit(gpa); self.resolvers.deinit(gpa); switch (self.bus) { .connection => |*c| c.deinit(), .daemon => {}, } if (self.wake_fd) |fd| _ = linux.close(fd); gpa.destroy(self); } /// The daemon's state. pub fn serverState(self: *Client) !ServerState { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); return self.serverStateLocked(); } fn serverStateLocked(self: *Client) !ServerState { var reply = try self.call("/", server_interface, "GetState", "", &.{}); defer reply.deinit(); var d = reply.bodyDecoder(); const state: ServerState = @fromBackingInt(try d.int32()); try d.end(); return state; } /// Read and act on what the daemon says -- groups' states, browsers' items, /// resolvers' answers -- and call the browsers' handlers, until `stop`. /// Only for a client made by `connect`. pub fn run(self: *Client) !void { const connection = &self.bus.connection; var batch: std.heap.ArenaAllocator = .init(self.gpa); defer batch.deinit(); var events: std.ArrayList(Event) = .empty; while (!self.stopping.load(.acquire)) { _ = batch.reset(.retain_capacity); events = .empty; { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); while (try connection.nextMessage()) |received| { var message = received; defer message.deinit(); self.dispatch(&message, batch.allocator(), &events) catch |err| { log.warn("a message from the daemon: {t}", .{err}); }; } } deliver(events.items); if (self.stopping.load(.acquire)) break; if (connection.hasQueuedMessages()) continue; var fds = [_]posix.pollfd{ .{ .fd = connection.getFd(), .events = posix.POLL.IN, .revents = 0 }, .{ .fd = self.wake_fd.?, .events = posix.POLL.IN, .revents = 0 }, }; _ = try posix.poll(&fds, -1); if (fds[1].revents != 0) { var buf: [8]u8 = undefined; _ = linux.read(self.wake_fd.?, &buf, buf.len); } if (fds[0].revents & (posix.POLL.HUP | posix.POLL.ERR | posix.POLL.NVAL) != 0) return error.ConnectionClosed; } } /// Act on one message as `run` does, the browsers' handlers called before /// it returns: for a client on a `Daemon`, which has no `run`. The message /// stays the caller's. pub fn handle(self: *Client, message: *Message) void { var batch: std.heap.ArenaAllocator = .init(self.gpa); defer batch.deinit(); var events: std.ArrayList(Event) = .empty; { self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); self.dispatch(message, batch.allocator(), &events) catch |err| { log.warn("a message from the daemon: {t}", .{err}); }; } deliver(events.items); } /// Hand `events` to their handlers. Outside the lock, so that a handler may /// publish or browse. fn deliver(events: []Event) void { for (events) |*e| switch (e.*) { .found => |*f| f.handler.found(f.handler.context, &f.service), .lost => |*l| l.handler.lost(l.handler.context, &l.item), }; } /// Have `run` return. Safe from any task. pub fn stop(self: *Client) void { self.stopping.store(true, .release); self.nudge(); } fn nudge(self: *Client) void { const fd = self.wake_fd orelse return; const one: u64 = 1; _ = linux.write(fd, std.mem.asBytes(&one), 8); } /// Publish `service`. Its strings are copied. A name taken by another /// client of the same daemon is changed at once; one taken on the network /// is changed when the daemon says so, from `run`. `error.NotPermitted` if /// the daemon does not let this user publish. pub fn publish(self: *Client, service: Service) !*EntryGroup { const g = try self.gpa.create(EntryGroup); errdefer self.gpa.destroy(g); g.* = .{ .client = self, .arena = .init(self.gpa), .service = undefined, .name = undefined }; errdefer g.arena.deinit(); const a = g.arena.allocator(); var txt = try a.alloc([]const u8, service.txt.len); for (service.txt, 0..) |t, i| txt[i] = try a.dupe(u8, t); g.service = service; g.service.name = try a.dupe(u8, service.name); g.service.type = try a.dupe(u8, service.type); g.service.domain = try a.dupe(u8, service.domain); g.service.host = try a.dupe(u8, service.host); g.service.txt = txt; g.name = g.service.name; self.lock.lockUncancelable(self.io); defer { self.lock.unlock(self.io); self.nudge(); } // Before the daemon is running there is nothing to commit to; the group // waits, and `run` publishes it when the daemon says it is. if (try self.serverStateLocked() == .running) try self.establish(g); try self.groups.append(self.gpa, g); return g; } /// A group of the daemon's with one service in it. pub const EntryGroup = struct { client: *Client, arena: std.heap.ArenaAllocator, service: Service, /// The name it is published under now: the service's own, or what a /// collision changed it to. Lives in `arena`. name: []const u8, path_buf: [128]u8 = undefined, path_len: usize = 0, state: std.atomic.Value(i32) = .init(@backingInt(EntryGroupState.uncommitted)), fn path(self: *const EntryGroup) []const u8 { return self.path_buf[0..self.path_len]; } /// Where the daemon has got to with it: `established` once the name is /// probed for and announced. pub fn currentState(self: *const EntryGroup) EntryGroupState { return @fromBackingInt(self.state.load(.acquire)); } /// Withdraw it, with goodbyes on the network, and free it. pub fn remove(self: *EntryGroup) void { const c = self.client; c.lock.lockUncancelable(c.io); defer c.lock.unlock(c.io); if (c.call(self.path(), group_interface, "Free", "", &.{})) |reply| { var r = reply; r.deinit(); } else |_| {} for (c.groups.items, 0..) |g, i| if (g == self) { _ = c.groups.swapRemove(i); break; }; self.destroy(); } fn destroy(self: *EntryGroup) void { const gpa = self.client.gpa; self.arena.deinit(); gpa.destroy(self); } }; /// A new group on the daemon for `g`, its service added under its name -- /// another if that is taken locally -- and committed. fn establish(self: *Client, g: *EntryGroup) !void { var reply = try self.call("/", server_interface, "EntryGroupNew", "", &.{}); { defer reply.deinit(); var d = reply.bodyDecoder(); const p = try d.objectPath(); if (p.len > g.path_buf.len) return error.AvahiError; @memcpy(g.path_buf[0..p.len], p); g.path_len = p.len; } errdefer if (self.call(g.path(), group_interface, "Free", "", &.{})) |r| { var rr = r; rr.deinit(); } else |_| {}; try self.addAndCommit(g); } fn addAndCommit(self: *Client, g: *EntryGroup) !void { var renames: usize = 0; while (true) { var body: Encoder = .init(self.gpa); defer body.deinit(); try wire.encodeAddService(&body, g.service, g.name); if (self.call(g.path(), group_interface, "AddService", wire.add_service_signature, body.bytes())) |reply| { var r = reply; r.deinit(); break; } else |err| { if (err != error.Collision or renames == max_renames) return err; renames += 1; try self.rename(g); } } var reply = try self.call(g.path(), group_interface, "Commit", "", &.{}); reply.deinit(); g.state.store(@backingInt(EntryGroupState.registering), .release); } /// The next name the daemon offers for `g`'s: `Kitchen #2`, `#3`. fn rename(self: *Client, g: *EntryGroup) !void { var body: Encoder = .init(self.gpa); defer body.deinit(); try body.string(g.name); var reply = try self.call("/", server_interface, "GetAlternativeServiceName", "s", body.bytes()); defer reply.deinit(); var d = reply.bodyDecoder(); const next = try g.arena.allocator().dupe(u8, try d.string()); log.info("the name {s} is taken; publishing as {s}", .{ g.name, next }); g.name = next; } /// What a browser is told of: found, resolved, and lost. pub const Handler = struct { context: *anyopaque, /// A service resolved: its host, address, port and TXT. Called from /// `run`, once for each interface and protocol it is seen on; the /// service borrows memory that lasts until the call returns. found: *const fn (context: *anyopaque, service: *const Resolved) void, /// A service gone, on one interface and protocol. lost: *const fn (context: *anyopaque, item: *const Item) void, }; pub const BrowseOptions = struct { domain: []const u8 = "", /// Which protocol to browse with. protocol: Protocol = .unspec, /// Which kind of address to resolve each service to: aiosendspin, say, /// dials only IPv4. address_protocol: Protocol = .unspec, /// Whether to report this host's own services too. include_own: bool = true, }; /// A browser for one service type. pub const Browser = struct { client: *Client, arena: std.heap.ArenaAllocator, service_type: []const u8, options: BrowseOptions, handler: Handler, path_buf: [128]u8 = undefined, path_len: usize = 0, fn path(self: *const Browser) []const u8 { return self.path_buf[0..self.path_len]; } /// Stop browsing and free it. pub fn remove(self: *Browser) void { const c = self.client; c.lock.lockUncancelable(c.io); defer c.lock.unlock(c.io); c.freeObject(self.path(), browser_interface); var i: usize = 0; while (i < c.resolvers.items.len) { if (c.resolvers.items[i].browser == self) { c.freeObject(c.resolvers.items[i].path(), resolver_interface); _ = c.resolvers.swapRemove(i); } else i += 1; } for (c.browsers.items, 0..) |b, j| if (b == self) { _ = c.browsers.swapRemove(j); break; }; self.destroy(); } fn destroy(self: *Browser) void { const gpa = self.client.gpa; self.arena.deinit(); gpa.destroy(self); } }; /// Browse for services of `service_type`, `_sendspin._tcp` say, each found /// one resolved and handed to `handler.found`, from `run`. pub fn browse(self: *Client, service_type: []const u8, options: BrowseOptions, handler: Handler) !*Browser { const b = try self.gpa.create(Browser); errdefer self.gpa.destroy(b); b.* = .{ .client = self, .arena = .init(self.gpa), .service_type = undefined, .options = options, .handler = handler }; errdefer b.arena.deinit(); b.service_type = try b.arena.allocator().dupe(u8, service_type); b.options.domain = try b.arena.allocator().dupe(u8, options.domain); self.lock.lockUncancelable(self.io); defer { self.lock.unlock(self.io); self.nudge(); } try self.startBrowser(b); try self.browsers.append(self.gpa, b); return b; } fn startBrowser(self: *Client, b: *Browser) !void { var body: Encoder = .init(self.gpa); defer body.deinit(); try wire.encodeServiceBrowserNew(&body, b.options.protocol, b.service_type, b.options.domain); var reply = try self.call("/", server_interface, "ServiceBrowserNew", wire.service_browser_new_signature, body.bytes()); defer reply.deinit(); var d = reply.bodyDecoder(); const p = try d.objectPath(); if (p.len > b.path_buf.len) return error.AvahiError; @memcpy(b.path_buf[0..p.len], p); b.path_len = p.len; } /// A resolver the daemon is running for a browser's item. const Resolver = struct { browser: *Browser, path_buf: [128]u8 = undefined, path_len: usize = 0, fn path(self: *const Resolver) []const u8 { return self.path_buf[0..self.path_len]; } }; /// What `run` hands the handlers once the lock is let go: copies, in the /// batch's arena. const Event = union(enum) { found: struct { handler: Handler, service: Resolved }, lost: struct { handler: Handler, item: Item }, }; fn dispatch(self: *Client, m: *Message, batch: std.mem.Allocator, events: *std.ArrayList(Event)) !void { if (m.messageType() != .signal) return; const iface = m.header.interface orelse return; const member = m.header.member orelse return; const obj = m.header.path orelse return; var d = m.bodyDecoder(); if (std.mem.eql(u8, iface, "org.freedesktop.DBus") and std.mem.eql(u8, member, "NameOwnerChanged")) { if (!std.mem.eql(u8, m.bodySignature(), wire.NameOwnerChanged.signature)) return; const n = try wire.NameOwnerChanged.decode(&d); if (!std.mem.eql(u8, n.name, avahi_name)) return; if (n.new_owner.len == 0) { log.info("the Avahi daemon has gone", .{}); for (self.groups.items) |g| g.state.store(@backingInt(EntryGroupState.failure), .release); } else { log.info("the Avahi daemon is back; publishing and browsing again", .{}); self.reestablish(); } return; } if (std.mem.eql(u8, iface, server_interface) and std.mem.eql(u8, member, "StateChanged")) { if (!std.mem.eql(u8, m.bodySignature(), wire.StateChanged.signature)) return; const s = try wire.StateChanged.decode(&d); if (@as(ServerState, @fromBackingInt(s.state)) != .running) return; // Running: every group not yet out there -- waiting from before, or // withdrawn by a collision of the host's name -- goes out now. for (self.groups.items) |g| switch (g.currentState()) { .established, .registering => {}, else => { if (g.path_len > 0) self.freeObject(g.path(), group_interface); g.path_len = 0; self.establish(g) catch |err| log.warn("publishing {s}: {t}", .{ g.name, err }); }, }; return; } if (std.mem.eql(u8, iface, group_interface) and std.mem.eql(u8, member, "StateChanged")) { if (!std.mem.eql(u8, m.bodySignature(), wire.StateChanged.signature)) return; const s = try wire.StateChanged.decode(&d); const g = for (self.groups.items) |g| { if (std.mem.eql(u8, g.path(), obj)) break g; } else return; g.state.store(s.state, .release); switch (@as(EntryGroupState, @fromBackingInt(s.state))) { .established => log.info("published {s} as {s}", .{ g.service.type, g.name }), .collision => { // Taken on the network: withdrawn, so another name. try self.rename(g); var reset = try self.call(g.path(), group_interface, "Reset", "", &.{}); reset.deinit(); try self.addAndCommit(g); }, .failure => log.warn("publishing {s} failed: {s}", .{ g.name, s.@"error" }), else => {}, } return; } if (std.mem.eql(u8, iface, browser_interface)) { const b = for (self.browsers.items) |b| { if (std.mem.eql(u8, b.path(), obj)) break b; } else return; if (std.mem.eql(u8, member, "ItemNew") or std.mem.eql(u8, member, "ItemRemove")) { if (!std.mem.eql(u8, m.bodySignature(), Item.signature)) return; const item = try Item.decode(&d); if (item.ourOwn() and !b.options.include_own) return; if (std.mem.eql(u8, member, "ItemNew")) { try self.startResolver(b, item); } else { try events.append(batch, .{ .lost = .{ .handler = b.handler, .item = try copyItem(batch, item) } }); } } else if (std.mem.eql(u8, member, "Failure")) { log.warn("browsing {s} failed", .{b.service_type}); } return; } if (std.mem.eql(u8, iface, resolver_interface)) { const index = for (self.resolvers.items, 0..) |*r, i| { if (std.mem.eql(u8, r.path(), obj)) break i; } else return; const r = self.resolvers.swapRemove(index); defer self.freeObject(r.path(), resolver_interface); if (std.mem.eql(u8, member, "Found") and std.mem.eql(u8, m.bodySignature(), Resolved.signature)) { const found = try Resolved.decode(&d); if (found.ourOwn() and !r.browser.options.include_own) return; try events.append(batch, .{ .found = .{ .handler = r.browser.handler, .service = try copyResolved(batch, found) } }); } return; } } fn startResolver(self: *Client, b: *Browser, item: Item) !void { var body: Encoder = .init(self.gpa); defer body.deinit(); try wire.encodeServiceResolverNew(&body, item, b.options.address_protocol); var reply = try self.call("/", server_interface, "ServiceResolverNew", wire.service_resolver_new_signature, body.bytes()); defer reply.deinit(); var d = reply.bodyDecoder(); const p = try d.objectPath(); var r: Resolver = .{ .browser = b }; if (p.len > r.path_buf.len) return error.AvahiError; @memcpy(r.path_buf[0..p.len], p); r.path_len = p.len; try self.resolvers.append(self.gpa, r); } /// The daemon restarted: its objects went with it, so every group is /// published again and every browser made again. fn reestablish(self: *Client) void { self.resolvers.clearRetainingCapacity(); for (self.groups.items) |g| { g.name = g.service.name; self.establish(g) catch |err| { log.warn("publishing {s} again: {t}", .{ g.name, err }); g.state.store(@backingInt(EntryGroupState.failure), .release); }; } for (self.browsers.items) |b| self.startBrowser(b) catch |err| { log.warn("browsing {s} again: {t}", .{ b.service_type, err }); }; } fn freeObject(self: *Client, obj: []const u8, iface: []const u8) void { if (self.call(obj, iface, "Free", "", &.{})) |reply| { var r = reply; r.deinit(); } else |_| {} } fn copyItem(a: std.mem.Allocator, item: Item) !Item { var out = item; out.name = try a.dupe(u8, item.name); out.type = try a.dupe(u8, item.type); out.domain = try a.dupe(u8, item.domain); return out; } fn copyResolved(a: std.mem.Allocator, r: Resolved) !Resolved { var out = r; out.name = try a.dupe(u8, r.name); out.type = try a.dupe(u8, r.type); out.domain = try a.dupe(u8, r.domain); out.host = try a.dupe(u8, r.host); out.address = try a.dupe(u8, r.address); for (r.txt(), 0..) |t, i| out.txt_buf[i] = try a.dupe(u8, t); return out; } /// Call `member` on the daemon's object `obj`, an error reply turned into a /// Zig error: `NotPermitted`, `Collision`, `AvahiUnavailable` for no /// daemon, `AvahiError` for the rest. The reply is the caller's to free. fn call(self: *Client, obj: []const u8, iface: []const u8, member: []const u8, signature: []const u8, body: []const u8) !Message { const method: Method = .{ .destination = avahi_name, .path = obj, .interface = iface, .member = member }; var reply = switch (self.bus) { .connection => |*c| try c.call(method, signature, body, &.{}, call_timeout_ms), .daemon => |d| try d.call(d.context, method, signature, body), }; if (reply.messageType() != .error_reply) return reply; defer reply.deinit(); const name = reply.header.error_name orelse ""; log.debug("{s}.{s}: {s}", .{ iface, member, name }); if (std.mem.eql(u8, name, "org.freedesktop.Avahi.NotPermittedError")) return error.NotPermitted; if (std.mem.eql(u8, name, "org.freedesktop.Avahi.CollisionError")) return error.Collision; if (std.mem.eql(u8, name, "org.freedesktop.DBus.Error.ServiceUnknown") or std.mem.eql(u8, name, "org.freedesktop.DBus.Error.NameHasNoOwner")) return error.AvahiUnavailable; return error.AvahiError; }