// SPDX-FileCopyrightText: © 2026 Tim Culverhouse // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Building D-Bus messages: the argument `Encoder` and the header //! serialization around it. //! //! `wire.zig` holds the decoding half along with the message size limits and //! the signature validation that both halves share, and it re-exports //! everything here, so nothing needs to import this file by name. const builtin = @import("builtin"); const std = @import("std"); const wire = @import("../wire.zig"); const MessageType = wire.MessageType; const max_message_size = wire.max_message_size; const spec_max_array_size = wire.spec_max_array_size; const typeAlignment = wire.typeAlignment; const validBusName = wire.validBusName; const validInterfaceName = wire.validInterfaceName; const validMemberName = wire.validMemberName; const validObjectPath = wire.validObjectPath; const validSignature = wire.validSignature; const validText = wire.validText; /// Offsets recorded by `Encoder.beginArray` and consumed by `Encoder.endArray`, /// which patches the array's length once its elements have been written. pub const ArrayBookmark = struct { length_offset: usize, content_offset: usize }; /// Builds a D-Bus argument list, inserting the padding each type's alignment /// requires. The encoder does not track a signature: the caller states the /// signature separately and is responsible for writing values that match it. pub const Encoder = struct { allocator: std.mem.Allocator, buffer: std.ArrayList(u8) = .empty, base_offset: usize, /// An encoder for a message body, which starts at an eight-byte boundary. pub fn init(allocator: std.mem.Allocator) Encoder { return .{ .allocator = allocator, .base_offset = 0 }; } /// An encoder for content that will land at `base_offset` within the final /// message, so that alignment is computed against the message as a whole. pub fn initWithBase(allocator: std.mem.Allocator, base_offset: usize) Encoder { return .{ .allocator = allocator, .base_offset = base_offset }; } /// Release the encoder's buffer. pub fn deinit(self: *Encoder) void { self.buffer.deinit(self.allocator); } /// The encoded bytes so far, valid until the next write or `deinit`. pub fn bytes(self: *const Encoder) []const u8 { return self.buffer.items; } fn reserve(self: *Encoder, count: usize) !void { const n = std.math.add(usize, self.buffer.items.len, count) catch return error.Overflow; if (n > max_message_size) return error.MessageTooLarge; try self.buffer.ensureTotalCapacity(self.allocator, n); } /// Pad to `alignment_value` and reserve room for `count` more bytes, in /// one capacity check, so a value's padding and the value itself cost one /// `reserve` rather than two. The caller appends its `count` bytes with /// the AssumeCapacity variants. fn prepare(self: *Encoder, alignment_value: usize, count: usize) !void { const global = std.math.add(usize, self.base_offset, self.buffer.items.len) catch return error.Overflow; // Alignments are 1, 2, 4, or 8, so the round-up is a mask rather // than a division, as in the decoder. std.debug.assert(std.math.isPowerOfTwo(alignment_value)); const padding = (0 -% global) & (alignment_value - 1); try self.reserve(std.math.add(usize, padding, count) catch return error.Overflow); self.buffer.appendNTimesAssumeCapacity(0, padding); } fn alignment(self: *Encoder, alignment_value: usize) !void { try self.prepare(alignment_value, 0); } fn raw(self: *Encoder, value: []const u8) !void { try self.reserve(value.len); self.buffer.appendSliceAssumeCapacity(value); } /// Append a `y` byte. pub fn byte(self: *Encoder, value: u8) !void { try self.reserve(1); self.buffer.appendAssumeCapacity(value); } /// Append the content of a `y`-element array in one step, between /// `beginArray` and `endArray`, rather than paying a `byte` call and its /// capacity check per element. pub fn byteSlice(self: *Encoder, value: []const u8) !void { try self.raw(value); } /// Append a `b` boolean, encoded as a 32-bit 0 or 1. pub fn boolean(self: *Encoder, value: bool) !void { try self.uint32(@intFromBool(value)); } /// Append an `n` signed 16-bit integer. pub fn int16(self: *Encoder, value: i16) !void { try self.writeInt(i16, value); } /// Append a `q` unsigned 16-bit integer. pub fn uint16(self: *Encoder, value: u16) !void { try self.writeInt(u16, value); } /// Append an `i` signed 32-bit integer. pub fn int32(self: *Encoder, value: i32) !void { try self.writeInt(i32, value); } /// Append the content of an `i`-element array in one step, between /// `beginArray` and `endArray`, rather than paying an `int32` call and /// its capacity check per element. On a little-endian host the values /// already have the wire's byte order and move as one copy. pub fn int32Slice(self: *Encoder, values: []const i32) !void { try self.prepare(@sizeOf(i32), values.len * @sizeOf(i32)); if (comptime builtin.cpu.arch.endian() == .little) { self.buffer.appendSliceAssumeCapacity(std.mem.sliceAsBytes(values)); } else { for (values) |value| { std.mem.writeInt(i32, self.buffer.addManyAsArrayAssumeCapacity(@sizeOf(i32)), value, .little); } } } /// Append a `u` unsigned 32-bit integer. pub fn uint32(self: *Encoder, value: u32) !void { try self.writeInt(u32, value); } /// Append an `x` signed 64-bit integer. pub fn int64(self: *Encoder, value: i64) !void { try self.writeInt(i64, value); } /// Append a `t` unsigned 64-bit integer. pub fn uint64(self: *Encoder, value: u64) !void { try self.writeInt(u64, value); } /// Append an `h` file descriptor, which travels as an index into the /// descriptor array sent with the message rather than as the descriptor. pub fn unixFd(self: *Encoder, index: u32) !void { try self.uint32(index); } /// Append a `d` double. pub fn double(self: *Encoder, value: f64) !void { try self.writeInt(u64, @bitCast(value)); } /// Append one fixed-size integer, little-endian, after the padding its /// width requires. /// /// `T` names the wire type being written and is checked here for the same /// reason, and on the same terms, as `Decoder.readInt` checks its own: the /// protocol stores a byte order only for its 16-, 32-, and 64-bit /// integers, signed and unsigned alike. fn writeInt(self: *Encoder, comptime T: type, value: T) !void { comptime { const info = @typeInfo(T); if (info != .int) @compileError( "writeInt writes an integer, not " ++ @typeName(T), ); if (info.int.bits != 16 and info.int.bits != 32 and info.int.bits != 64) @compileError(std.fmt.comptimePrint( "writeInt writes the types the protocol stores with a byte order, which are " ++ "16, 32, and 64 bits, not {d}; a byte has no byte order and is written by `byte`", .{info.int.bits}, )); } try self.prepare(@sizeOf(T), @sizeOf(T)); std.mem.writeInt(T, self.buffer.addManyAsArrayAssumeCapacity(@sizeOf(T)), value, .little); } /// The framing an `s` and an `o` share: the length, the content, the /// terminator. What the content must look like is the caller's check. fn stringData(self: *Encoder, value: []const u8) !void { if (value.len > std.math.maxInt(u32)) return error.Overflow; // The length, the value, and its terminator in one reservation. try self.prepare(4, value.len + 5); std.mem.writeInt(u32, self.buffer.addManyAsArrayAssumeCapacity(4), @intCast(value.len), .little); self.buffer.appendSliceAssumeCapacity(value); self.buffer.appendAssumeCapacity(0); } /// Append an `s` string. The value must be valid UTF-8 without an interior /// NUL; the terminating NUL is added here. pub fn string(self: *Encoder, value: []const u8) !void { if (!validText(value)) return error.InvalidString; try self.stringData(value); } /// Append an `o` object path, rejecting anything that is not a valid /// path. A valid path is ASCII with no NUL in it, so the syntax check /// subsumes the text check an `s` gets and the value is walked once. pub fn objectPath(self: *Encoder, value: []const u8) !void { if (!validObjectPath(value)) return error.InvalidObjectPath; try self.stringData(value); } /// A signature's framing: the length byte, the content, the terminator, /// in one reservation. The caller has already checked the content, which /// is what bounds the length to the byte. fn signatureData(self: *Encoder, value: []const u8) !void { std.debug.assert(value.len <= 255); try self.reserve(value.len + 2); self.buffer.appendAssumeCapacity(@intCast(value.len)); self.buffer.appendSliceAssumeCapacity(value); self.buffer.appendAssumeCapacity(0); } /// Append a `g` signature, which may be empty or hold several complete types. pub fn signature(self: *Encoder, value: []const u8) !void { if (!validSignature(value, true)) return error.InvalidSignature; try self.signatureData(value); } /// Append the signature that opens a `v` variant. Unlike `signature`, /// this requires exactly one complete type, as a variant holds a single /// value; that requirement subsumes the ordinary check, so the value is /// walked once, not once per check. pub fn variantSignature(self: *Encoder, value: []const u8) !void { if (!validSignature(value, false)) return error.InvalidSignature; try self.signatureData(value); } /// Pad to the eight-byte boundary that precedes a struct's fields. pub fn structAlignment(self: *Encoder) !void { try self.alignment(8); } /// Pad to the eight-byte boundary that precedes a dict entry. pub fn dictEntryAlignment(self: *Encoder) !void { try self.alignment(8); } /// Start an array of the type whose signature begins with `element` — /// `'i'` for `ai`, `'('` for `a(us)`, `'{'` for `a{sv}` — from which the /// element alignment follows. The length is written once `endArray` is /// called with the returned bookmark; every `beginArray` must be paired /// with one. The content of a `y` or `i` array is appended in one step /// with `byteSlice` or `int32Slice` rather than a call per element. pub fn beginArray(self: *Encoder, element: u8) !ArrayBookmark { const element_alignment = typeAlignment(element) orelse return error.InvalidSignature; try self.alignment(4); const length_offset = self.buffer.items.len; try self.raw(&.{ 0, 0, 0, 0 }); try self.alignment(element_alignment); return .{ .length_offset = length_offset, .content_offset = self.buffer.items.len }; } /// Close the array opened by `bookmark`, patching in its byte length. pub fn endArray(self: *Encoder, bookmark: ArrayBookmark) !void { if (bookmark.content_offset > self.buffer.items.len or bookmark.length_offset + 4 > bookmark.content_offset) return error.InvalidValue; const length = self.buffer.items.len - bookmark.content_offset; if (length > spec_max_array_size) return error.MessageTooLarge; std.mem.writeInt(u32, self.buffer.items[bookmark.length_offset..][0..4], @intCast(length), .little); } }; /// The header fields of a message to encode. Which fields are required /// depends on the message type, and `encodeMessage` rejects incomplete /// combinations. pub const Metadata = struct { message_type: MessageType, flags: u8 = 0, path: ?[]const u8 = null, interface: ?[]const u8 = null, member: ?[]const u8 = null, error_name: ?[]const u8 = null, reply_serial: ?u32 = null, destination: ?[]const u8 = null, signature: []const u8 = "", }; /// Validate `metadata` and encode its header field array, positioned as it /// will land in the message: at offset 12, where the fixed header's own u32 /// array length begins. The shared front half of `encodeHeader` and /// `encodeMessage`. fn headerFields(allocator: std.mem.Allocator, metadata: Metadata, serial: u32, body_len: usize, unix_fd_count: u32) !Encoder { if (serial == 0 or body_len > std.math.maxInt(u32) or !validSignature(metadata.signature, true)) return error.InvalidMessage; switch (metadata.message_type) { .method_call => if (metadata.path == null or metadata.member == null) return error.MissingHeaderField, .method_return => if (metadata.reply_serial == null) return error.MissingHeaderField, .error_reply => if (metadata.error_name == null or metadata.reply_serial == null) return error.MissingHeaderField, .signal => if (metadata.path == null or metadata.interface == null or metadata.member == null) return error.MissingHeaderField, else => return error.InvalidMessage, } // The specification reserves these for messages a peer synthesizes about // its own connection; they must never cross the wire, and the reference // bus disconnects a sender that tries. Refusing here is the sending half // of that rule. if (metadata.path) |v| { if (std.mem.eql(u8, v, "/org/freedesktop/DBus/Local")) return error.ReservedName; } if (metadata.interface) |v| { if (std.mem.eql(u8, v, "org.freedesktop.DBus.Local")) return error.ReservedName; } // The names the specification gives a grammar are refused when they // break it; the path gets the same treatment where it is written. if (metadata.interface) |v| if (!validInterfaceName(v)) return error.InvalidName; if (metadata.member) |v| if (!validMemberName(v)) return error.InvalidName; if (metadata.error_name) |v| if (!validInterfaceName(v)) return error.InvalidName; if (metadata.destination) |v| if (!validBusName(v)) return error.InvalidName; var e = Encoder.initWithBase(allocator, 12); errdefer e.deinit(); const fields = try e.beginArray('('); if (metadata.path) |v| try headerString(&e, 1, "o", v); if (metadata.interface) |v| try headerString(&e, 2, "s", v); if (metadata.member) |v| try headerString(&e, 3, "s", v); if (metadata.error_name) |v| try headerString(&e, 4, "s", v); if (metadata.reply_serial) |v| { try e.structAlignment(); try e.byte(5); try e.variantSignature("u"); try e.uint32(v); } if (metadata.destination) |v| try headerString(&e, 6, "s", v); if (metadata.signature.len != 0) { try e.structAlignment(); try e.byte(8); try e.variantSignature("g"); try e.signature(metadata.signature); } if (unix_fd_count != 0) { try e.structAlignment(); try e.byte(9); try e.variantSignature("u"); try e.uint32(unix_fd_count); } try e.endArray(fields); try e.alignment(8); const total = std.math.add(usize, 12 + e.bytes().len, body_len) catch return error.Overflow; if (total > max_message_size) return error.MessageTooLarge; return e; } /// Write the fixed twelve-byte prefix and the encoded field array into `out`, /// which must hold exactly the header. fn fillHeader(out: []u8, metadata: Metadata, serial: u32, body_len: usize, fields: *const Encoder) void { out[0] = 'l'; out[1] = @backingInt(metadata.message_type); out[2] = metadata.flags; out[3] = 1; std.mem.writeInt(u32, out[4..8], @intCast(body_len), .little); std.mem.writeInt(u32, out[8..12], serial, .little); @memcpy(out[12..], fields.bytes()); } /// Serialize the header of a little-endian message whose body is `body_len` /// bytes: everything up to where the body starts, padding included. A caller /// that scatter-gathers its writes sends the body right after this without /// the body ever being copied, which is how `Connection` sends. The caller /// owns the returned slice. pub fn encodeHeader(allocator: std.mem.Allocator, metadata: Metadata, serial: u32, body_len: usize, unix_fd_count: u32) ![]u8 { var fields = try headerFields(allocator, metadata, serial, body_len, unix_fd_count); defer fields.deinit(); const out = try allocator.alloc(u8, 12 + fields.bytes().len); fillHeader(out, metadata, serial, body_len, &fields); return out; } /// Serialize a complete little-endian message. `serial` must be nonzero, and /// `unix_fd_count` is the number of descriptors sent alongside the message, /// which the body refers to by index. The caller owns the returned slice. pub fn encodeMessage(allocator: std.mem.Allocator, metadata: Metadata, serial: u32, body: []const u8, unix_fd_count: u32) ![]u8 { var fields = try headerFields(allocator, metadata, serial, body.len, unix_fd_count); defer fields.deinit(); const header_len = 12 + fields.bytes().len; const out = try allocator.alloc(u8, header_len + body.len); fillHeader(out[0..header_len], metadata, serial, body.len, &fields); @memcpy(out[header_len..], body); return out; } fn headerString(e: *Encoder, code: u8, sig: []const u8, value: []const u8) !void { try e.structAlignment(); try e.byte(code); try e.variantSignature(sig); // An `s` header field's value has already passed its name grammar, // which is ASCII with no NUL, so the text check would walk it again to // learn nothing. if (sig[0] == 'o') try e.objectPath(value) else try e.stringData(value); }