// SPDX-FileCopyrightText: © 2026 Tim Culverhouse // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One authenticated connection to the D-Bus session bus. //! //! This is deliberately a client transport, not a general D-Bus binding: it //! supports Linux Unix-domain session buses, method calls, signals, correlated //! replies, and Unix file-descriptor passing. Service-specific messages remain //! in their owning modules. const Connection = @This(); const std = @import("std"); const linux = std.os.linux; const posix = std.posix; const wire = @import("wire.zig"); /// Re-exported so callers can build message bodies without importing `wire`. pub const Encoder = wire.Encoder; /// A received message and the resources it owns; see `wire.Message`. pub const Message = wire.Message; /// Whether a message is a method call, return, error, or signal. pub const MessageType = wire.MessageType; const max_queued_messages = 256; const max_message_fds = 16; const receive_buffer_size = 16 * 1024; const auth_line_max = 1024; const cmsg_header_size = std.mem.alignForward(usize, @sizeOf(linux.cmsghdr), @sizeOf(usize)); const receive_control_size = cmsg_header_size + std.mem.alignForward(usize, max_message_fds * @sizeOf(posix.fd_t), @sizeOf(usize)); /// Every error this transport originates. Encoding and decoding errors from /// `wire`, and allocation failures, pass through unchanged. pub const Error = error{ AddressUnavailable, AuthenticationFailed, ConnectionClosed, InvalidAddress, ProtocolError, RemoteError, Timeout, UnixFdUnsupported, WriteFailed, }; /// Addresses a method on a service: which peer to send to, and which object, /// interface, and member on that peer. pub const Method = struct { destination: []const u8, path: []const u8, interface: []const u8, member: []const u8, }; /// Addresses a signal being emitted. Signals are broadcast, so unlike /// `Method` there is no destination. pub const Signal = struct { path: []const u8, interface: []const u8, member: []const u8, }; /// Owns the receive buffer and every queued message. allocator: std.mem.Allocator, /// Used to connect the socket and to read the clock while waiting for replies. io: std.Io, /// The connected Unix-domain socket, left non-blocking after setup. fd: posix.fd_t, /// Serial for the next outgoing message. Serials wrap but never reach zero, /// which the protocol reserves as "no serial". next_serial: u32 = 1, /// Whether the bus agreed to file-descriptor passing during authentication. unix_fd_enabled: bool = false, /// Set once a write fails, after which the connection refuses to send. broken: bool = false, /// Bytes read from the socket that do not yet form a complete message. receive_buffer: std.ArrayList(u8) = .empty, /// Descriptors received out of band, held until the message that claims them /// is parsed. Ancillary data can arrive before the message body it belongs to. received_fds: std.ArrayList(posix.fd_t) = .empty, /// Parsed messages waiting to be taken by `nextMessage` or `waitForReply`. messages: std.ArrayList(Message) = .empty, /// Connect, authenticate, and register with the session bus. The caller owns /// the returned connection and must call `deinit`. Only Unix socket addresses /// are supported; multiple alternatives are tried in order. pub fn connectSession( io: std.Io, allocator: std.mem.Allocator, environ: std.process.Environ, ) !Connection { var path_buf: [std.fs.max_path_bytes + 16]u8 = undefined; const addresses = environ.getPosix("DBUS_SESSION_BUS_ADDRESS") orelse fallback: { const runtime_dir = environ.getPosix("XDG_RUNTIME_DIR") orelse return error.AddressUnavailable; break :fallback std.fmt.bufPrint(&path_buf, "unix:path={s}/bus", .{runtime_dir}) catch return error.AddressUnavailable; }; return connectAddress(io, allocator, addresses); } /// The system bus's address when `DBUS_SYSTEM_BUS_ADDRESS` names none, as /// the D-Bus specification fixes it. pub const default_system_bus_address = "unix:path=/run/dbus/system_bus_socket"; /// Connect, authenticate, and register with the system bus, where system /// services -- Avahi, NetworkManager, logind -- are found: the address in /// `DBUS_SYSTEM_BUS_ADDRESS`, or `default_system_bus_address`. What an /// unprivileged client may do there is the bus's policy to say. pub fn connectSystem( io: std.Io, allocator: std.mem.Allocator, environ: std.process.Environ, ) !Connection { const addresses = environ.getPosix("DBUS_SYSTEM_BUS_ADDRESS") orelse default_system_bus_address; return connectAddress(io, allocator, addresses); } /// Connect, authenticate, and say `Hello` to the bus at `addresses`, a D-Bus /// server address: alternatives separated by `;`, each tried in order until /// one answers. Only Unix socket addresses are supported. pub fn connectAddress( io: std.Io, allocator: std.mem.Allocator, addresses: []const u8, ) !Connection { var arena_state: std.heap.ArenaAllocator = .init(allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var alternatives = std.mem.splitScalar(u8, addresses, ';'); while (alternatives.next()) |address| { if (address.len == 0) continue; const fd = connectUnixAddress(io, arena, address) catch continue; var connection: Connection = .{ .allocator = allocator, .io = io, .fd = fd, }; errdefer connection.deinit(); connection.authenticate() catch { connection.deinit(); continue; }; connection.setNonblocking() catch { connection.deinit(); continue; }; connection.hello() catch { connection.deinit(); continue; }; return connection; } return error.AddressUnavailable; } /// Close the socket, free queued messages, and close any descriptors that /// were received but never claimed. pub fn deinit(self: *Connection) void { for (self.messages.items) |*message| message.deinit(); self.messages.deinit(self.allocator); for (self.received_fds.items) |fd| _ = linux.close(fd); self.received_fds.deinit(self.allocator); self.receive_buffer.deinit(self.allocator); _ = linux.close(self.fd); self.* = undefined; } /// The socket to register with an event loop. Poll it for readability and /// drain the connection with `nextMessage` when it fires. pub fn getFd(self: *const Connection) posix.fd_t { return self.fd; } /// Whether messages are already buffered. A caller that polls should check /// this first, since those messages will not make the socket readable again. pub fn hasQueuedMessages(self: *const Connection) bool { return self.messages.items.len != 0; } /// Send a method call and return its nonzero serial number, which identifies /// the reply and can be handed to `waitForReply`. pub fn sendMethod( self: *Connection, method: Method, signature: []const u8, body: []const u8, fds: []const posix.fd_t, ) !u32 { return self.sendMessage(.{ .message_type = .method_call, .path = method.path, .interface = method.interface, .member = method.member, .destination = method.destination, .signature = signature, }, body, fds); } /// Send a method call and wait for its corresponding return or error reply. /// `timeout_ms` bounds the wait for that reply. An error reply is returned as a /// message rather than as a Zig error, so the caller can read why it failed. /// The caller owns the returned message and must call `Message.deinit`. pub fn call( self: *Connection, method: Method, signature: []const u8, body: []const u8, fds: []const posix.fd_t, timeout_ms: u32, ) !Message { const serial = try self.sendMethod(method, signature, body, fds); return self.waitForReply(serial, timeout_ms); } /// Emit a signal. Signals are fire-and-forget: there is no reply to await and /// no serial worth returning. pub fn sendSignal( self: *Connection, signal: Signal, signature: []const u8, body: []const u8, ) !void { _ = try self.sendMessage(.{ .message_type = .signal, .path = signal.path, .interface = signal.interface, .member = signal.member, .signature = signature, }, body, &.{}); } /// Answer a method call with its return value. The reply is addressed back to /// whoever sent `to`, which is why a message parsed from the bus carries its /// sender. `to` must be a method call; anything else is a programming error /// rather than something the bus could have caused. /// /// A caller that set NO_REPLY_EXPECTED is not waiting for this, so check /// `Message.noReplyExpected` before spending the write. pub fn sendReply( self: *Connection, to: *const Message, signature: []const u8, body: []const u8, fds: []const posix.fd_t, ) !void { if (to.messageType() != .method_call) return error.ProtocolError; _ = try self.sendMessage(.{ .message_type = .method_return, .reply_serial = to.header.serial, .destination = to.header.sender, .signature = signature, }, body, fds); } /// Answer a method call with an error instead of a return value. `error_name` /// is an interface-style name such as `org.freedesktop.DBus.Error.Failed`, and /// `description` is the human-readable string that conventionally accompanies /// it as the error's single argument. pub fn sendError( self: *Connection, to: *const Message, error_name: []const u8, description: []const u8, ) !void { if (to.messageType() != .method_call) return error.ProtocolError; var body: Encoder = .init(self.allocator); defer body.deinit(); try body.string(description); _ = try self.sendMessage(.{ .message_type = .error_reply, .error_name = error_name, .reply_serial = to.header.serial, .destination = to.header.sender, .signature = "s", }, body.bytes(), &.{}); } /// Install a bus match rule and confirm that the bus accepted it. pub fn addMatch(self: *Connection, rule: []const u8) !void { var body: Encoder = .init(self.allocator); defer body.deinit(); try body.string(rule); var reply = try self.call(.{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus", .member = "AddMatch", }, "s", body.bytes(), &.{}, 1000); defer reply.deinit(); if (reply.messageType() != .method_return) return error.RemoteError; } /// Wait for the reply to `serial`, returning `error.Timeout` if it does not /// arrive in time. Messages that arrive meanwhile stay queued for `nextMessage` /// rather than being dropped. pub fn waitForReply(self: *Connection, serial: u32, timeout_ms: u32) !Message { const started = std.Io.Clock.awake.now(self.io); const timeout_ns: i96 = @as(i96, timeout_ms) * std.time.ns_per_ms; while (true) { if (self.takeReply(serial)) |reply| return reply; try self.readAvailable(); if (self.takeReply(serial)) |reply| return reply; const elapsed = started.durationTo(std.Io.Clock.awake.now(self.io)).nanoseconds; if (elapsed >= timeout_ns) return error.Timeout; const remaining_ns = timeout_ns - elapsed; const remaining_ms: i32 = @intCast(@min( @as(i96, std.math.maxInt(i32)), @divTrunc(remaining_ns + std.time.ns_per_ms - 1, std.time.ns_per_ms), )); var poll_fd = [_]posix.pollfd{.{ .fd = self.fd, .events = posix.POLL.IN, .revents = 0, }}; if (try posix.poll(&poll_fd, remaining_ms) == 0) return error.Timeout; if (poll_fd[0].revents & posix.POLL.NVAL != 0) return error.ConnectionClosed; } } /// Return one queued or newly received message without blocking. The caller /// owns a returned message and must call `Message.deinit`. pub fn nextMessage(self: *Connection) !?Message { if (self.messages.items.len == 0) try self.readAvailable(); if (self.messages.items.len == 0) return null; return self.messages.orderedRemove(0); } /// Complete registration by calling `Hello`, which the bus requires before it /// will route any other message. The assigned unique name is discarded; this /// transport never needs to name itself. fn hello(self: *Connection) !void { var reply = try self.call(.{ .destination = "org.freedesktop.DBus", .path = "/org/freedesktop/DBus", .interface = "org.freedesktop.DBus", .member = "Hello", }, "", &.{}, &.{}, 1000); defer reply.deinit(); if (reply.messageType() != .method_return or !std.mem.eql(u8, reply.bodySignature(), "s")) return error.AuthenticationFailed; var decoder = reply.bodyDecoder(); _ = decoder.string() catch return error.AuthenticationFailed; decoder.end() catch return error.AuthenticationFailed; } /// Assign a serial, encode, and write one message. Descriptors may only be /// sent if the bus agreed to them during authentication. fn sendMessage( self: *Connection, metadata: wire.Metadata, body: []const u8, fds: []const posix.fd_t, ) !u32 { if (self.broken) return error.ConnectionClosed; if (fds.len > max_message_fds) return error.ProtocolError; if (fds.len != 0 and !self.unix_fd_enabled) return error.UnixFdUnsupported; const serial = self.next_serial; self.next_serial +%= 1; if (self.next_serial == 0) self.next_serial = 1; // Only the header is assembled; the body goes to the socket straight // from the caller's bytes, gathered by `writeMessage`, so a large body // is never copied into a full-message buffer. const header = try wire.encodeHeader( self.allocator, metadata, serial, body.len, @intCast(fds.len), ); defer self.allocator.free(header); try self.writeMessage(header, body, fds); return serial; } /// Write a message in full as the gather of its header and its body, /// attaching `fds` as ancillary data to the first `sendmsg` only, since the /// kernel would otherwise duplicate them on every partial write. Any failure /// marks the connection broken. fn writeMessage(self: *Connection, header: []const u8, body: []const u8, fds: []const posix.fd_t) !void { errdefer self.broken = true; const total = header.len + body.len; var offset: usize = 0; var send_fds = fds.len != 0; var control: [receive_control_size]u8 align(@alignOf(linux.cmsghdr)) = @splat(0); const control_len = if (send_fds) cmsgLength(fds.len * @sizeOf(posix.fd_t)) else 0; if (send_fds) { const cmsg: *linux.cmsghdr = @ptrCast(&control); cmsg.* = .{ .len = control_len, .level = linux.SOL.SOCKET, .type = linux.SCM.RIGHTS, }; @memcpy(control[cmsg_header_size..][0 .. fds.len * @sizeOf(posix.fd_t)], std.mem.sliceAsBytes(fds)); } while (offset < total) { // A partial write can land anywhere, including inside the header, so // the vector is rebuilt from wherever the write is up to. var iov: [2]posix.iovec_const = undefined; var iov_count: usize = 0; if (offset < header.len) { iov[iov_count] = .{ .base = header[offset..].ptr, .len = header.len - offset }; iov_count += 1; if (body.len != 0) { iov[iov_count] = .{ .base = body.ptr, .len = body.len }; iov_count += 1; } } else { iov[iov_count] = .{ .base = body[offset - header.len ..].ptr, .len = total - offset }; iov_count += 1; } const message: linux.msghdr_const = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = iov_count, .control = if (send_fds) &control else null, .controllen = if (send_fds) cmsgSpace(fds.len * @sizeOf(posix.fd_t)) else 0, .flags = 0, }; const rc = linux.sendmsg(self.fd, &message, linux.MSG.NOSIGNAL); switch (linux.errno(rc)) { .SUCCESS => { if (rc == 0) return error.ConnectionClosed; offset += rc; send_fds = false; }, .INTR => continue, .AGAIN => try self.waitWritable(), .PIPE, .CONNRESET, .NOTCONN => return error.ConnectionClosed, else => return error.WriteFailed, } } } /// Block until the socket accepts more data, so a partial write can resume. fn waitWritable(self: *Connection) !void { var poll_fd = [_]posix.pollfd{.{ .fd = self.fd, .events = posix.POLL.OUT, .revents = 0, }}; if (try posix.poll(&poll_fd, 1000) == 0) return error.Timeout; if (poll_fd[0].revents & (posix.POLL.ERR | posix.POLL.HUP | posix.POLL.NVAL) != 0) return error.ConnectionClosed; } /// Drain everything the socket currently holds, parsing complete messages as /// they accumulate. Returns once the socket would block. fn readAvailable(self: *Connection) !void { while (true) { var data: [receive_buffer_size]u8 = undefined; var control: [receive_control_size]u8 align(@alignOf(linux.cmsghdr)) = undefined; var iov = [_]posix.iovec{.{ .base = &data, .len = data.len }}; var message: linux.msghdr = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = &control, .controllen = control.len, .flags = 0, }; const rc = linux.recvmsg(self.fd, &message, linux.MSG.DONTWAIT | linux.MSG.CMSG_CLOEXEC); switch (linux.errno(rc)) { .SUCCESS => { if (rc == 0) return error.ConnectionClosed; if (message.flags & linux.MSG.CTRUNC != 0) { closeControlFds(control[0..message.controllen]); return error.ProtocolError; } try self.collectFds(control[0..message.controllen]); try self.receive_buffer.appendSlice(self.allocator, data[0..rc]); try self.parseMessages(); }, .INTR => continue, .AGAIN => return, .CONNRESET, .NOTCONN => return error.ConnectionClosed, else => return error.ProtocolError, } } } /// Take the descriptors out of one message's ancillary data. On any failure /// the descriptors are closed rather than leaked, including when the peer /// sends more than this connection is willing to hold. fn collectFds(self: *Connection, control: []const u8) !void { const count = countControlFds(control) catch |err| { closeControlFds(control); return err; }; if (self.received_fds.items.len + count > max_message_fds) { closeControlFds(control); return error.ProtocolError; } self.received_fds.ensureUnusedCapacity(self.allocator, count) catch |err| { closeControlFds(control); return err; }; var offset: usize = 0; while (offset + @sizeOf(linux.cmsghdr) <= control.len) { const header: *align(1) const linux.cmsghdr = @ptrCast(control[offset..].ptr); if (header.level == linux.SOL.SOCKET and header.type == linux.SCM.RIGHTS) { const bytes = control[offset + cmsg_header_size .. offset + header.len]; var index: usize = 0; while (index < bytes.len) : (index += @sizeOf(posix.fd_t)) { const fd = std.mem.readInt( posix.fd_t, @ptrCast(bytes[index..][0..@sizeOf(posix.fd_t)]), .native, ); self.received_fds.appendAssumeCapacity(fd); } } offset = std.mem.alignForward(usize, offset + header.len, @sizeOf(usize)); } } /// Count the descriptors in ancillary data, validating each header's length /// before it is trusted, so the count can be reserved up front. fn countControlFds(control: []const u8) !usize { var count: usize = 0; var offset: usize = 0; while (offset + @sizeOf(linux.cmsghdr) <= control.len) { const header: *align(1) const linux.cmsghdr = @ptrCast(control[offset..].ptr); if (header.len < cmsg_header_size or header.len > control.len - offset) return error.ProtocolError; if (header.level == linux.SOL.SOCKET and header.type == linux.SCM.RIGHTS) { const bytes_len = header.len - cmsg_header_size; if (bytes_len % @sizeOf(posix.fd_t) != 0) return error.ProtocolError; count += bytes_len / @sizeOf(posix.fd_t); } offset = std.mem.alignForward(usize, offset + header.len, @sizeOf(usize)); } return count; } /// Close every descriptor in ancillary data that will not be kept. Stops at /// the first malformed header rather than erroring, as there is nothing left /// to report to. fn closeControlFds(control: []const u8) void { var offset: usize = 0; while (offset + @sizeOf(linux.cmsghdr) <= control.len) { const header: *align(1) const linux.cmsghdr = @ptrCast(control[offset..].ptr); if (header.len < cmsg_header_size or header.len > control.len - offset) return; if (header.level == linux.SOL.SOCKET and header.type == linux.SCM.RIGHTS) { const bytes = control[offset + cmsg_header_size .. offset + header.len]; if (bytes.len % @sizeOf(posix.fd_t) != 0) return; var index: usize = 0; while (index < bytes.len) : (index += @sizeOf(posix.fd_t)) { const fd = std.mem.readInt( posix.fd_t, @ptrCast(bytes[index..][0..@sizeOf(posix.fd_t)]), .native, ); _ = linux.close(fd); } } offset = std.mem.alignForward(usize, offset + header.len, @sizeOf(usize)); } } /// Split every complete message out of the receive buffer and queue it, except /// for messages of an unknown type, which are discarded. Each /// message's header is decoded once here to learn how many of the pending /// descriptors belong to it, since they are handed over in arrival order. fn parseMessages(self: *Connection) !void { while (true) { // A framing or validity error means the peer is not speaking the // protocol -- a version this side does not know, or bytes no valid // message contains -- and the stream cannot recover from either, so // the connection is marked broken, which is this side of the // disconnect the specification requires. const complete = wire.messageLength(self.receive_buffer.items) catch |err| { self.broken = true; return err; }; const length = complete orelse return; if (self.messages.items.len >= max_queued_messages) return error.ProtocolError; try self.messages.ensureUnusedCapacity(self.allocator, 1); const owned_data = try self.allocator.dupe(u8, self.receive_buffer.items[0..length]); errdefer self.allocator.free(owned_data); const fd_count = messageFdCount(owned_data) catch |err| { self.broken = true; return err; }; if (fd_count > max_message_fds or fd_count > self.received_fds.items.len) { self.broken = true; return error.ProtocolError; } const owned_fds = try self.allocator.alloc(posix.fd_t, fd_count); errdefer self.allocator.free(owned_fds); @memcpy(owned_fds, self.received_fds.items[0..fd_count]); const remaining_fds = self.received_fds.items.len - fd_count; std.mem.copyForwards( posix.fd_t, self.received_fds.items[0..remaining_fds], self.received_fds.items[fd_count..], ); self.received_fds.items.len = remaining_fds; var parsed = wire.parseMessage(self.allocator, owned_data, owned_fds) catch |err| { for (owned_fds) |fd| _ = linux.close(fd); self.broken = true; return err; }; switch (parsed.messageType()) { .method_call, .method_return, .error_reply, .signal => { self.messages.appendAssumeCapacity(parsed); }, // The specification requires that a message of an unknown type be // ignored, so it is dropped here rather than queued: no caller // could act on it, and leaving it in the queue would eventually // fill it. Its descriptors are closed with it. _ => parsed.deinit(), } const remaining = self.receive_buffer.items.len - length; std.mem.copyForwards( u8, self.receive_buffer.items[0..remaining], self.receive_buffer.items[length..], ); self.receive_buffer.items.len = remaining; } } /// How many descriptors `message` declares in its UNIX_FDS header field, /// scanned ahead of the full parse because pending descriptors are handed /// over in arrival order. fn messageFdCount(message: []const u8) !u32 { const endian: std.builtin.Endian = if (message[0] == 'l') .little else .big; const fields_len = std.mem.readInt(u32, message[12..16], endian); var header_decoder: wire.Decoder = .{ .data = message[16 .. 16 + fields_len], .endian = endian, .base_offset = 16, }; var fd_count: u32 = 0; while (!header_decoder.finished()) { try header_decoder.structAlignment(); const code = try header_decoder.byte(); const signature = try header_decoder.variantSignature(); if (code == 9) { if (!std.mem.eql(u8, signature, "u")) return error.ProtocolError; fd_count = try header_decoder.uint32(); } else { try header_decoder.skipSignatureValue(signature); } } return fd_count; } /// Remove the queued return or error reply matching `serial`, leaving every /// other message queued. fn takeReply(self: *Connection, serial: u32) ?Message { for (self.messages.items, 0..) |message, index| { if ((message.messageType() == .method_return or message.messageType() == .error_reply) and message.header.reply_serial == serial) { return self.messages.orderedRemove(index); } } return null; } /// Run the SASL handshake: the leading NUL byte, EXTERNAL authentication with /// the hex-encoded uid the kernel already vouches for, then an attempt to /// negotiate descriptor passing, which the bus is free to refuse. fn authenticate(self: *Connection) !void { var uid_buffer: [32]u8 = undefined; const uid = try std.fmt.bufPrint(&uid_buffer, "{d}", .{linux.getuid()}); var auth_buffer: [2 * uid_buffer.len + 32]u8 = undefined; var stream = std.Io.Writer.fixed(&auth_buffer); try stream.writeByte(0); try stream.writeAll("AUTH EXTERNAL "); for (uid) |byte| try stream.print("{x:0>2}", .{byte}); try stream.writeAll("\r\n"); try writeBlocking(self.fd, stream.buffered()); var line_buffer: [auth_line_max]u8 = undefined; const response = try readAuthLine(self.fd, &line_buffer); if (!std.mem.startsWith(u8, response, "OK ")) return error.AuthenticationFailed; try writeBlocking(self.fd, "NEGOTIATE_UNIX_FD\r\n"); const negotiation = try readAuthLine(self.fd, &line_buffer); if (std.mem.eql(u8, negotiation, "AGREE_UNIX_FD")) { self.unix_fd_enabled = true; } else if (!std.mem.startsWith(u8, negotiation, "ERROR")) { return error.AuthenticationFailed; } try writeBlocking(self.fd, "BEGIN\r\n"); } /// Switch the socket to non-blocking mode, which is done only after /// authentication so the handshake can use simple blocking reads and writes. fn setNonblocking(self: *Connection) !void { const flags = linux.fcntl(self.fd, linux.F.GETFL, 0); if (linux.errno(flags) != .SUCCESS) return error.ProtocolError; const nonblock: usize = @as(u32, @bitCast(linux.O{ .NONBLOCK = true })); const rc = linux.fcntl(self.fd, linux.F.SETFL, flags | nonblock); if (linux.errno(rc) != .SUCCESS) return error.ProtocolError; } /// Connect to one `unix:` address from the bus address list. Exactly one of /// `path` or `abstract` must be given; an abstract name is passed to the /// kernel with a leading NUL. fn connectUnixAddress(io: std.Io, allocator: std.mem.Allocator, address: []const u8) !posix.fd_t { if (!std.mem.startsWith(u8, address, "unix:")) return error.InvalidAddress; var path: ?[]const u8 = null; var abstract: ?[]const u8 = null; var options = std.mem.splitScalar(u8, address["unix:".len..], ','); while (options.next()) |option| { const separator = std.mem.indexOfScalar(u8, option, '=') orelse return error.InvalidAddress; const key = option[0..separator]; const value = try unescapeAddress(allocator, option[separator + 1 ..]); if (std.mem.eql(u8, key, "path")) path = value else if (std.mem.eql(u8, key, "abstract")) abstract = value; } if ((path == null) == (abstract == null)) return error.InvalidAddress; const socket_path = if (path) |value| value else value: { const name = abstract.?; const storage = try allocator.alloc(u8, name.len + 1); storage[0] = 0; @memcpy(storage[1..], name); break :value storage; }; const unix_address = try std.Io.net.UnixAddress.init(socket_path); const network_stream = try unix_address.connect(io); return network_stream.socket.handle; } /// Decode the percent-escaping used in bus addresses. The caller owns the /// returned slice. fn unescapeAddress(allocator: std.mem.Allocator, value: []const u8) ![]u8 { const output = try allocator.alloc(u8, value.len); errdefer allocator.free(output); var input_index: usize = 0; var output_index: usize = 0; while (input_index < value.len) { if (value[input_index] == '%') { if (input_index + 2 >= value.len) return error.InvalidAddress; output[output_index] = std.fmt.parseInt(u8, value[input_index + 1 .. input_index + 3], 16) catch return error.InvalidAddress; input_index += 3; } else { output[output_index] = value[input_index]; input_index += 1; } output_index += 1; } return allocator.realloc(output, output_index); } /// Write all of `data`, used during authentication while the socket still /// blocks. fn writeBlocking(fd: posix.fd_t, data: []const u8) !void { var offset: usize = 0; while (offset < data.len) { const rc = linux.write(fd, data[offset..].ptr, data.len - offset); switch (linux.errno(rc)) { .SUCCESS => { if (rc == 0) return error.ConnectionClosed; offset += rc; }, .INTR => continue, .PIPE, .CONNRESET, .NOTCONN => return error.ConnectionClosed, else => return error.WriteFailed, } } } /// Read one CRLF-terminated authentication line, returning it without the /// terminator. Reads a byte at a time so that no part of the first message /// is consumed along with the handshake. fn readAuthLine(fd: posix.fd_t, buffer: []u8) ![]const u8 { var length: usize = 0; while (length < buffer.len) { const rc = linux.read(fd, buffer[length..].ptr, 1); switch (linux.errno(rc)) { .SUCCESS => { if (rc == 0) return error.ConnectionClosed; length += 1; if (length >= 2 and buffer[length - 2] == '\r' and buffer[length - 1] == '\n') return buffer[0 .. length - 2]; }, .INTR => continue, .CONNRESET, .NOTCONN => return error.ConnectionClosed, else => return error.AuthenticationFailed, } } return error.AuthenticationFailed; } /// The `cmsg_len` for a payload of `data_len` bytes: the header plus the /// payload, without trailing padding. fn cmsgLength(data_len: usize) usize { return cmsg_header_size + data_len; } /// The buffer space a payload of `data_len` bytes occupies, which unlike /// `cmsgLength` includes the padding to the next alignment boundary. fn cmsgSpace(data_len: usize) usize { return cmsg_header_size + std.mem.alignForward(usize, data_len, @sizeOf(usize)); } test "session address unescaping" { const allocator = std.testing.allocator; const value = try unescapeAddress(allocator, "/run/user/1000/dbus%2Dbus"); defer allocator.free(value); try std.testing.expectEqualStrings("/run/user/1000/dbus-bus", value); try std.testing.expectError(error.InvalidAddress, unescapeAddress(allocator, "%2")); } test "replying to something that is not a method call is refused" { // Only a method call has a serial worth answering. Catching that here // rather than letting the bus reject the reply keeps a programming error // from looking like a protocol failure on the far side. const a = std.testing.allocator; var pair: [2]posix.fd_t = undefined; if (linux.errno(linux.socketpair(linux.AF.UNIX, linux.SOCK.STREAM, 0, &pair)) != .SUCCESS) return error.SocketPairFailed; defer _ = linux.close(pair[1]); var connection: Connection = .{ .allocator = a, .io = std.testing.io, .fd = pair[0] }; defer connection.deinit(); const bytes = try wire.encodeMessage(a, .{ .message_type = .signal, .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "Changed", }, 1, "", 0); defer a.free(bytes); var message = try wire.parseMessage( a, try a.dupe(u8, bytes), try a.alloc(posix.fd_t, 0), ); defer message.deinit(); try std.testing.expectError( error.ProtocolError, connection.sendReply(&message, "", &.{}, &.{}), ); try std.testing.expectError( error.ProtocolError, connection.sendError(&message, "dev.rockorager.Monstar.Error.Failed", "no"), ); } test "unknown message types are ignored, not fatal" { // The specification requires that a message of a type this version does // not know about be ignored. Ignoring it means the connection stays usable // and the next real message still arrives, which is what a socket pair can // demonstrate without a bus. const a = std.testing.allocator; var pair: [2]posix.fd_t = undefined; const rc = linux.socketpair(linux.AF.UNIX, linux.SOCK.STREAM, 0, &pair); if (linux.errno(rc) != .SUCCESS) return error.SocketPairFailed; defer _ = linux.close(pair[1]); var connection: Connection = .{ .allocator = a, .io = std.testing.io, .fd = pair[0] }; defer connection.deinit(); try connection.setNonblocking(); const signal_metadata: wire.Metadata = .{ .message_type = .signal, .path = "/dev/rockorager/Monstar", .interface = "dev.rockorager.Monstar", .member = "Changed", }; // A well-formed message that differs from the signal only in its type. const unknown = try wire.encodeMessage(a, signal_metadata, 1, "", 0); defer a.free(unknown); unknown[1] = 0x2d; const signal = try wire.encodeMessage(a, signal_metadata, 2, "", 0); defer a.free(signal); try writeBlocking(pair[1], unknown); try writeBlocking(pair[1], signal); var message = (try connection.nextMessage()).?; defer message.deinit(); try std.testing.expectEqual(MessageType.signal, message.messageType()); try std.testing.expectEqual(@as(u32, 2), message.header.serial); try std.testing.expect((try connection.nextMessage()) == null); }