Something went wrong. Try again.
A small D-Bus client transport for Zig: session bus, method calls, signals, replies and file descriptor passing.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623// SPDX-FileCopyrightText: © 2026 Tim Culverhouse <tim@timculverhouse.com>// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Tests that exercise `Connection` against a real message bus.//!//! Everything here is skipped unless `MONSTAR_DBUS_INTEGRATION=1` is set, so//! `zig build test` still passes on a machine with no bus. The flake's//! `checks.<system>.dbus-broker` boots a VM whose session bus is dbus-broker,//! sets the variable, and requires that every test ran rather than skipped.
const std = @import("std");const linux = std.os.linux;const posix = std.posix;
const Connection = @import("Connection.zig");const Encoder = Connection.Encoder;const Message = Connection.Message;const MessageType = Connection.MessageType;
/// A name this test owns for as long as one test needs it. Requesting a name/// is how a client becomes reachable by something other than its unique name.const test_name = "dev.rockorager.Monstar.LiveBusTest";
/// Skip unless the caller asked for live-bus tests, then connect. Returning/// `error.SkipZigTest` rather than failing keeps the suite runnable anywhere.fn connect() !Connection { const requested = std.testing.environ.getPosix("MONSTAR_DBUS_INTEGRATION") orelse return error.SkipZigTest; if (!std.mem.eql(u8, requested, "1")) return error.SkipZigTest; return Connection.connectSession( std.testing.io, std.testing.allocator, std.testing.environ, );}
/// Address a member on the bus's own object, which every bus implements.fn busMethod(member: []const u8) Connection.Method { return .{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus", .member = member, };}
/// Call a bus method whose only argument is a string and whose reply is a/// single `u32`, which covers `RequestName`, `ReleaseName`, and friends.fn callStringToUint32( connection: *Connection, member: []const u8, argument: []const u8, flags: ?u32,) !u32 { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(argument); if (flags) |value| try body.uint32(value);
var reply = try connection.call( busMethod(member), if (flags == null) "s" else "su", body.bytes(), &.{}, 1000, ); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("u", reply.bodySignature());
var decoder = reply.bodyDecoder(); const result = try decoder.uint32(); try decoder.end(); return result;}
/// Take messages until one matches `message_type`, `interface`, and `member`,/// discarding the rest. The bus sends messages of its own — `NameAcquired`/// arrives during `Hello` — so a test cannot assume what it is waiting for is/// the next message to arrive.fn waitForMessage( connection: *Connection, message_type: MessageType, interface: []const u8, member: []const u8, timeout_ms: u32,) !Message { const started = std.Io.Clock.awake.now(std.testing.io); const timeout_ns: i96 = @as(i96, timeout_ms) * std.time.ns_per_ms; while (true) { while (try connection.nextMessage()) |taken| { var message = taken; if (message.messageType() == message_type and std.mem.eql(u8, message.header.interface orelse "", interface) and std.mem.eql(u8, message.header.member orelse "", member)) return message; message.deinit(); }
const elapsed = started.durationTo(std.Io.Clock.awake.now(std.testing.io)).nanoseconds; if (elapsed >= timeout_ns) return error.Timeout; const remaining_ms: i32 = @intCast(@divTrunc( timeout_ns - elapsed + std.time.ns_per_ms - 1, std.time.ns_per_ms, )); var poll_fd = [_]posix.pollfd{.{ .fd = connection.getFd(), .events = posix.POLL.IN, .revents = 0, }}; if (try posix.poll(&poll_fd, remaining_ms) == 0) return error.Timeout; }}
test "live bus: connecting authenticates and registers" { // `connectSession` only returns once `Hello` has been answered, so a // connection at all is evidence that authentication and registration // both worked against a real bus. var connection = try connect(); defer connection.deinit(); try std.testing.expect(connection.getFd() >= 0);}
/// Accepts a message sent by `sender`.fn isFrom(sender: []const u8, message: *const Message) bool { return std.mem.eql(u8, message.header.sender orelse "", sender);}
test "live bus: the unique name is kept and is what peers see as the sender" { // A portal predicts its Request object's path from the caller's unique // name, so the name has to be the one the bus actually stamps on what // this connection sends -- which a signal routed back to itself shows. var connection = try connect(); defer connection.deinit(); const name = connection.uniqueName(); try std.testing.expect(std.mem.startsWith(u8, name, ":"));
const interface = "dev.rockorager.Monstar.LiveBusTest.UniqueName"; try connection.addMatch("type='signal',interface='" ++ interface ++ "'"); try connection.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Ping", }, "", &.{});
var signal = try connection.waitForMessage(name, isFrom, 5000); defer signal.deinit(); try std.testing.expectEqualStrings(interface, signal.header.interface.?);}
test "live bus: GetId returns the bus identifier" { var connection = try connect(); defer connection.deinit();
var reply = try connection.call(busMethod("GetId"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("s", reply.bodySignature());
var decoder = reply.bodyDecoder(); const id = try decoder.string(); // The specification fixes the bus id at 32 hexadecimal characters. try std.testing.expectEqual(@as(usize, 32), id.len); for (id) |c| try std.testing.expect(std.ascii.isHex(c)); try decoder.end();}
test "live bus: the system bus is reached and answers" { const requested = std.testing.environ.getPosix("MONSTAR_DBUS_INTEGRATION") orelse return error.SkipZigTest; if (!std.mem.eql(u8, requested, "1")) return error.SkipZigTest; // A different bus from the session's: its own socket, its own id. var system = try Connection.connectSystem(std.testing.io, std.testing.allocator, std.testing.environ); defer system.deinit(); var session = try connect(); defer session.deinit();
var ids: [2][32]u8 = undefined; for ([_]*Connection{ &system, &session }, &ids) |connection, *id| { var reply = try connection.call(busMethod("GetId"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); var decoder = reply.bodyDecoder(); const got = try decoder.string(); try std.testing.expectEqual(@as(usize, 32), got.len); id.* = got[0..32].*; } try std.testing.expect(!std.mem.eql(u8, &ids[0], &ids[1]));}
test "live bus: ListNames includes the bus itself" { var connection = try connect(); defer connection.deinit();
var reply = try connection.call(busMethod("ListNames"), "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("as", reply.bodySignature());
var decoder = reply.bodyDecoder(); const end = try decoder.beginArray('s'); var found_bus = false; var count: usize = 0; while (!try decoder.arrayFinished(end)) { const name = try decoder.string(); if (std.mem.eql(u8, name, "org.freedesktop.DBus")) found_bus = true; count += 1; } try decoder.endArray(end); try decoder.end(); try std.testing.expect(found_bus); // Our own unique name is on the bus too, so there is more than one. try std.testing.expect(count >= 2);}
test "live bus: Introspect returns a body larger than one read" { // The bus object's introspection XML is several kilobytes, which makes it // the cheapest way to check that a body spanning more than one `recvmsg` // is reassembled correctly. var connection = try connect(); defer connection.deinit();
var reply = try connection.call(.{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus.Introspectable", .member = "Introspect", }, "", &.{}, &.{}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType());
var decoder = reply.bodyDecoder(); const xml = try decoder.string(); try decoder.end(); try std.testing.expect(xml.len > 1024); try std.testing.expect(std.mem.find(u8, xml, "org.freedesktop.DBus") != null);}
test "live bus: a requested name is owned, resolvable, and released" { var connection = try connect(); defer connection.deinit();
// 4 is DO_NOT_QUEUE: fail outright rather than wait if someone else has it. const request_result = try callStringToUint32(&connection, "RequestName", test_name, 4); // 1 is PRIMARY_OWNER. try std.testing.expectEqual(@as(u32, 1), request_result);
{ var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(test_name); var reply = try connection.call(busMethod("NameHasOwner"), "s", body.bytes(), &.{}, 1000); defer reply.deinit(); try std.testing.expectEqualStrings("b", reply.bodySignature()); var decoder = reply.bodyDecoder(); try std.testing.expect(try decoder.boolean()); try decoder.end(); }
{ // The owner of the name we just took is our own connection, so the // bus should agree that it belongs to this process. var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string(test_name); var owner_reply = try connection.call(busMethod("GetNameOwner"), "s", body.bytes(), &.{}, 1000); defer owner_reply.deinit(); try std.testing.expectEqualStrings("s", owner_reply.bodySignature()); var owner_decoder = owner_reply.bodyDecoder(); const unique_name = try owner_decoder.string(); try owner_decoder.end(); try std.testing.expect(unique_name.len > 1); try std.testing.expectEqual(@as(u8, ':'), unique_name[0]);
const pid = try callStringToUint32( &connection, "GetConnectionUnixProcessID", unique_name, null, ); try std.testing.expectEqual(@as(u32, @intCast(linux.getpid())), pid); }
// 1 is RELEASED. const release_result = try callStringToUint32(&connection, "ReleaseName", test_name, null); try std.testing.expectEqual(@as(u32, 1), release_result);}
test "live bus: a matched signal is routed back to its sender" { var connection = try connect(); defer connection.deinit();
const interface = "dev.rockorager.Monstar.LiveBusTest"; try connection.addMatch("type='signal',interface='" ++ interface ++ "'");
var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.uint32(0xfeedface); try body.string("hello from the test"); try connection.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Ping", }, "us", body.bytes());
var signal = try waitForMessage(&connection, .signal, interface, "Ping", 5000); defer signal.deinit(); try std.testing.expectEqualStrings("/dev/rockorager/Monstar/LiveBusTest", signal.header.path.?); try std.testing.expectEqualStrings("us", signal.bodySignature());
var decoder = signal.bodyDecoder(); try std.testing.expectEqual(@as(u32, 0xfeedface), try decoder.uint32()); try std.testing.expectEqualStrings("hello from the test", try decoder.string()); try decoder.end();}
test "live bus: a signal with a destination reaches that peer alone" { // A portal answers a request with a signal addressed to the caller. // The recipient installs no match rule and still receives it; a third // connection whose match rule accepts the signal does not, which a // broadcast sent afterwards shows: one sender's messages arrive in // order, so a bystander that sees the broadcast first never saw the // addressed one. var sender = try connect(); defer sender.deinit(); var recipient = try connect(); defer recipient.deinit(); var bystander = try connect(); defer bystander.deinit();
const interface = "dev.rockorager.Monstar.LiveBusTest.Unicast"; try bystander.addMatch("type='signal',interface='" ++ interface ++ "'");
var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.uint32(0); try sender.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Response", .destination = recipient.uniqueName(), }, "u", body.bytes()); try sender.sendSignal(.{ .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = interface, .member = "Broadcast", }, "", &.{});
var response = try waitForMessage(&recipient, .signal, interface, "Response", 5000); defer response.deinit(); try std.testing.expectEqualStrings(recipient.uniqueName(), response.header.destination.?); try std.testing.expectEqualStrings(sender.uniqueName(), response.header.sender.?);
while (true) { var message = try bystander.waitForMessage({}, isAnySignal, 5000); defer message.deinit(); if (!std.mem.eql(u8, message.header.interface orelse "", interface)) continue; try std.testing.expectEqualStrings("Broadcast", message.header.member.?); break; }}
/// Accepts any signal.fn isAnySignal(_: void, message: *const Message) bool { return message.messageType() == .signal;}
test "live bus: calling a name nobody owns yields an error reply" { var connection = try connect(); defer connection.deinit();
const serial = try connection.sendMethod(.{ .destination = "dev.rockorager.Monstar.Nonexistent", .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "DoesNotMatter", }, "", &.{}, &.{});
var reply = try connection.waitForReply(serial, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); try std.testing.expectEqualStrings( "org.freedesktop.DBus.Error.ServiceUnknown", reply.header.error_name.?, );}
test "live bus: replies are correlated with their own calls" { // Several calls are put in flight before any reply is read, then awaited // out of order. Each `waitForReply` must pick out its own serial and leave // the others queued rather than returning whichever reply arrived first. var connection = try connect(); defer connection.deinit();
var serials: [4]u32 = undefined; for (&serials) |*serial| { serial.* = try connection.sendMethod(busMethod("GetId"), "", &.{}, &.{}); }
var index: usize = serials.len; while (index > 0) { index -= 1; var reply = try connection.waitForReply(serials[index], 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqual(serials[index], reply.header.reply_serial.?); }}
test "live bus: a Unix fd survives the round trip to the bus" { // The bus rejects the call because nothing owns the destination, but it // only gets that far by accepting the descriptor first, which is what the // `unix_fd_passing` negotiation during authentication is for. var connection = try connect(); defer connection.deinit(); try std.testing.expect(connection.unix_fd_enabled);
const rc = linux.openat( linux.AT.FDCWD, "/dev/null", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0, ); if (linux.errno(rc) != .SUCCESS) return error.OpenFailed; const fd: posix.fd_t = @intCast(rc); defer _ = linux.close(fd);
var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.unixFd(0); var reply = try connection.call(.{ .destination = "dev.rockorager.Monstar.Nonexistent", .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "TakeFd", }, "h", body.bytes(), &.{fd}, 1000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType());}
test "live bus: a descriptor passes from one client to another" { // The bus does not copy a descriptor through the message body; it moves // the open file itself with `SCM_RIGHTS`, so what the receiver gets is a // different descriptor number onto the same file. Two connections and a // pipe are enough to show that end to end: the sender keeps the write end, // the receiver is handed the read end, and what comes out of it is what // was written in. var receiver = try connect(); defer receiver.deinit(); var sender = try connect(); defer sender.deinit();
const service = "dev.rockorager.Monstar.LiveBusTest.FdReceiver"; // 4 is DO_NOT_QUEUE, so a name left behind by an earlier run fails here // rather than making this test wait for it. try std.testing.expectEqual( @as(u32, 1), try callStringToUint32(&receiver, "RequestName", service, 4), ); defer _ = callStringToUint32(&receiver, "ReleaseName", service, null) catch {};
var pipe_fds: [2]posix.fd_t = undefined; if (linux.errno(linux.pipe2(&pipe_fds, .{ .CLOEXEC = true })) != .SUCCESS) return error.PipeFailed; const read_end = pipe_fds[0]; const write_end = pipe_fds[1]; defer _ = linux.close(write_end); // The read end is sent, which does not close it here, so this side still // owns its copy and has to let it go. defer _ = linux.close(read_end);
const secret = "a descriptor crossed the bus"; const written = linux.write(write_end, secret, secret.len); if (linux.errno(written) != .SUCCESS or written != secret.len) return error.WriteFailed;
var body: Encoder = .init(std.testing.allocator); defer body.deinit(); // The body carries an index into the descriptor array, not the descriptor. try body.unixFd(0); const serial = try sender.sendMethod(.{ .destination = service, .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = "dev.rockorager.Monstar.LiveBusTest", .member = "TakeFd", }, "h", body.bytes(), &.{read_end});
var call = try waitForMessage( &receiver, .method_call, "dev.rockorager.Monstar.LiveBusTest", "TakeFd", 5000, ); defer call.deinit(); try std.testing.expectEqualStrings("h", call.bodySignature()); try std.testing.expectEqual(@as(u32, 1), call.header.unix_fd_count); try std.testing.expectEqual(@as(usize, 1), call.fds.len);
var decoder = call.bodyDecoder(); const index = try decoder.unixFd(); try decoder.end(); try std.testing.expectEqual(@as(u32, 0), index);
const received = call.fds[index]; // A distinct number is the evidence that this arrived as ancillary data // rather than as a number copied through the body. try std.testing.expect(received != read_end);
var buffer: [secret.len]u8 = undefined; const count = linux.read(received, &buffer, buffer.len); if (linux.errno(count) != .SUCCESS) return error.ReadFailed; try std.testing.expectEqual(secret.len, count); try std.testing.expectEqualStrings(secret, &buffer);
// Answering closes the loop: the bus can only route this back because the // call carried a sender for the reply to be addressed to. try std.testing.expect(!call.noReplyExpected()); try std.testing.expect(call.header.sender != null); try std.testing.expectEqual(@as(u8, ':'), call.header.sender.?[0]);
var reply_body: Encoder = .init(std.testing.allocator); defer reply_body.deinit(); try reply_body.uint32(@intCast(count)); try receiver.sendReply(&call, "u", reply_body.bytes(), &.{});
var reply = try sender.waitForReply(serial, 5000); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); var reply_decoder = reply.bodyDecoder(); try std.testing.expectEqual(@as(u32, secret.len), try reply_decoder.uint32()); try reply_decoder.end();}
test "live bus: a client answers a call with an error" { // The error path is routed the same way as a return, but the caller gets // the name and the description back rather than a value, which is what // makes a failure on the far side distinguishable from a broken bus. var receiver = try connect(); defer receiver.deinit(); var sender = try connect(); defer sender.deinit();
const service = "dev.rockorager.Monstar.LiveBusTest.Failing"; try std.testing.expectEqual( @as(u32, 1), try callStringToUint32(&receiver, "RequestName", service, 4), ); defer _ = callStringToUint32(&receiver, "ReleaseName", service, null) catch {};
const serial = try sender.sendMethod(.{ .destination = service, .path = "/dev/rockorager/Monstar/LiveBusTest", .interface = "dev.rockorager.Monstar.LiveBusTest", .member = "Fail", }, "", &.{}, &.{});
var call = try waitForMessage( &receiver, .method_call, "dev.rockorager.Monstar.LiveBusTest", "Fail", 5000, ); defer call.deinit();
const error_name = "dev.rockorager.Monstar.LiveBusTest.Error.Refused"; try receiver.sendError(&call, error_name, "refused on purpose");
var reply = try sender.waitForReply(serial, 5000); defer reply.deinit(); try std.testing.expectEqual(MessageType.error_reply, reply.messageType()); try std.testing.expectEqual(serial, reply.header.reply_serial.?); try std.testing.expectEqualStrings(error_name, reply.header.error_name.?); try std.testing.expectEqualStrings("s", reply.bodySignature()); var reply_decoder = reply.bodyDecoder(); try std.testing.expectEqualStrings("refused on purpose", try reply_decoder.string()); try reply_decoder.end();}
test "live bus: a dictionary of variants decodes to the last byte" { // `GetConnectionCredentials` answers with `a{sv}`, the most nested shape // the bus itself will produce. Walking it to the end is what proves the // array, dict-entry, and variant decoding agree with a real encoder. // Recent buses put a `ProcessFD` pidfd in that dictionary, so the reply may // also carry a descriptor; how many it carries is checked against the // header rather than pinned to a number, since that varies by bus version. var connection = try connect(); defer connection.deinit();
var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try body.string("org.freedesktop.DBus");
var reply = try connection.call( busMethod("GetConnectionCredentials"), "s", body.bytes(), &.{}, 1000, ); defer reply.deinit(); try std.testing.expectEqual(MessageType.method_return, reply.messageType()); try std.testing.expectEqualStrings("a{sv}", reply.bodySignature()); try std.testing.expectEqual(reply.header.unix_fd_count, @as(u32, @intCast(reply.fds.len)));
// Walk the dictionary with the variant skipper so the whole body is // consumed, which is what proves the nested decoding lines up. var decoder = reply.bodyDecoder(); const end = try decoder.beginArray('{'); var entries: usize = 0; while (!try decoder.arrayFinished(end)) { try decoder.structAlignment(); _ = try decoder.string(); const variant_signature = try decoder.variantSignature(); try decoder.skipSignatureValue(variant_signature); entries += 1; } try decoder.endArray(end); try decoder.end(); try std.testing.expect(entries >= 1);}