// SPDX-FileCopyrightText: © 2026 Tim Culverhouse // SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Bounds-checked D-Bus wire encoding and decoding. const std = @import("std"); const build_options = @import("build_options"); /// The largest message the protocol allows, header and body together. pub const spec_max_message_size: usize = 1 << 27; /// The largest array the protocol allows, in bytes of content. pub const spec_max_array_size: usize = 1 << 26; /// Largest message this build will encode or accept. The protocol permits /// `spec_max_message_size`, but the limit is what keeps a hostile peer from /// forcing large allocations, so the default is well under the ceiling and a /// build sets `-Dmax_message_size=` only as high as it actually needs. pub const max_message_size: usize = build_options.max_message_size; comptime { if (max_message_size > spec_max_message_size) @compileError( "max_message_size exceeds the protocol maximum of 128 MiB", ); // Below the fixed header no message can be framed at all, so a smaller // limit would reject everything rather than merely being strict. if (max_message_size < 16) @compileError( "max_message_size is smaller than a message's fixed header", ); } /// How deep a signature walk has gone. Arrays, structs, and dict entries are /// counted apart because the specification bounds them apart: 32 arrays /// wrapped around 32 structs is legal even though it nests 64 deep. The /// reference implementation's signature validator keeps the same three /// separate counters, dict entries included -- its braces do not spend the /// parenthesis budget -- so this bucketing is reference-faithful, not a /// leniency. pub const Depth = struct { /// The specification bounds array nesting and open-parenthesis nesting /// separately, at this many each, rather than bounding the combined /// depth. pub const max_container_depth = 32; /// The specification also bounds what a signature alone cannot: "the /// maximum total depth of recursion is 64", counting containers and /// variants together across a whole message. A variant's value opens a /// signature of its own, so without this bound a message could nest /// variants three body bytes per level and recurse the walk that skips /// them beyond any native stack. The reference implementation's body /// walk enforces the same 64 on the same terms, counting every array, /// struct, dict entry, and variant toward one total. pub const max_message_depth = 64; array: usize = 0, structure: usize = 0, dict_entry: usize = 0, /// Message depth already spent by enclosing variants and the containers /// open around them when each was entered. Not part of the signature /// grammar -- each variant carries its own signature, with its own /// budgets above -- but what carries the total across variant /// boundaries, and what bounds the walk's recursion. variant: usize = 0, /// Enter the signature a variant's value carries, with `containers` /// open around the variant in the current signature: the grammar /// budgets reset, because the signature is its own, and the total /// message depth carries across, checked against what the /// specification allows. The error is about the message rather than /// any signature, which is what the error value says. pub fn enterVariant(self: Depth, containers: usize) !Depth { const total = self.variant + containers + 1; if (total > max_message_depth) return error.InvalidMessage; return .{ .variant = total }; } pub fn enterArray(self: Depth) !Depth { var next = self; next.array += 1; if (next.array > max_container_depth) return error.InvalidSignature; return next; } pub fn enterStruct(self: Depth) !Depth { var next = self; next.structure += 1; if (next.structure > max_container_depth) return error.InvalidSignature; return next; } pub fn enterDictEntry(self: Depth) !Depth { var next = self; next.dict_entry += 1; if (next.dict_entry > max_container_depth) return error.InvalidSignature; return next; } }; /// Every error the encoder, decoder, and message parser can return. pub const Error = error{ InvalidValue, InvalidName, ReservedName, InvalidString, InvalidObjectPath, InvalidSignature, InvalidMessage, MissingHeaderField, DuplicateHeaderField, WrongHeaderFieldType, MessageTooLarge, Overflow, EndOfMessage, TrailingData, }; /// The four D-Bus message types. The enum is non-exhaustive because a peer may /// send a type this version does not know about, which the specification /// requires be ignored rather than treated as an error. pub const MessageType = enum(u8) { method_call = 1, method_return = 2, error_reply = 3, signal = 4, _, }; /// Building a message is a large enough job to keep in its own file. The names /// are re-exported here so that a caller only ever imports `wire`, and so that /// the split stays an arrangement of this file rather than part of the API. const encode = @import("wire/encode.zig"); pub const ArrayBookmark = encode.ArrayBookmark; pub const Encoder = encode.Encoder; pub const Metadata = encode.Metadata; pub const encodeHeader = encode.encodeHeader; pub const encodeMessage = encode.encodeMessage; /// Reading a message is likewise its own file, re-exported here for the same /// reason as the encoding half above. const decode = @import("wire/decode.zig"); pub const Decoder = decode.Decoder; pub const Header = decode.Header; pub const Message = decode.Message; pub const messageLength = decode.messageLength; pub const parseMessage = decode.parseMessage; /// The vector width the text validation below runs at, zero where the target /// has no vectors and everything falls back to the scalar loop. const text_chunk_len = std.simd.suggestVectorLength(u8) orelse 0; const TextChunk = @Vector(text_chunk_len, u8); /// `chunk` shifted right by `n` lanes, with the vacated lanes filled from the /// end of `prev`: lane `i` holds the byte `n` positions before `chunk[i]` in /// the input. This is how a check relates a byte to the lead that precedes /// it when the sequence straddles a chunk boundary. fn textPrev(comptime n: comptime_int, prev: TextChunk, chunk: TextChunk) TextChunk { const mask = comptime blk: { var m: [text_chunk_len]i32 = undefined; for (&m, 0..) |*e, i| { e.* = if (i < n) ~@as(i32, @intCast(text_chunk_len - n + i)) else @intCast(i - n); } break :blk m; }; return @shuffle(u8, chunk, prev, mask); } /// Whether `chunk` continues valid NUL-free UTF-8, given the chunk before it /// for the sequences that straddle the boundary. This is the compare-based /// variant of Keiser and Lemire's "Validating UTF-8 In Less Than One /// Instruction Per Byte": positions that must be continuation bytes are /// exactly those one lane after a `C0`-and-up byte, two after `E0`-and-up, /// or three after `F0`-and-up, and everything else the specification /// excludes -- overlong encodings, surrogate halves, codepoints past /// U+10FFFF, and byte values no UTF-8 text contains -- is a compare of a /// byte against the lead one lane back. fn validTextChunk(prev: TextChunk, chunk: TextChunk) bool { const prev1 = textPrev(1, prev, chunk); const expects_continuation = (prev1 >= @as(TextChunk, @splat(0xC0))) | (textPrev(2, prev, chunk) >= @as(TextChunk, @splat(0xE0))) | (textPrev(3, prev, chunk) >= @as(TextChunk, @splat(0xF0))); const is_continuation = (chunk & @as(TextChunk, @splat(0xC0))) == @as(TextChunk, @splat(0x80)); // A NUL, a byte no text contains (C0 and C1 encode only overlongs, F5 // and up only codepoints past U+10FFFF), or an E0, ED, F0, or F4 lead // whose follower is outside the range that keeps its codepoint legal: // below A0 after E0 or below 90 after F0 is overlong, A0 and up after ED // is a surrogate half, 90 and up after F4 is past U+10FFFF. const bad_value = (chunk == @as(TextChunk, @splat(0))) | (chunk -% @as(TextChunk, @splat(0xC0)) < @as(TextChunk, @splat(2))) | (chunk >= @as(TextChunk, @splat(0xF5))) | ((prev1 == @as(TextChunk, @splat(0xE0))) & (chunk -% @as(TextChunk, @splat(0x80)) < @as(TextChunk, @splat(0x20)))) | ((prev1 == @as(TextChunk, @splat(0xED))) & (chunk -% @as(TextChunk, @splat(0xA0)) < @as(TextChunk, @splat(0x20)))) | ((prev1 == @as(TextChunk, @splat(0xF0))) & (chunk -% @as(TextChunk, @splat(0x80)) < @as(TextChunk, @splat(0x10)))) | ((prev1 == @as(TextChunk, @splat(0xF4))) & (chunk -% @as(TextChunk, @splat(0x90)) < @as(TextChunk, @splat(0x30)))); return !@reduce(.Or, (expects_continuation != is_continuation) | bad_value); } /// The scalar half of `validText`, and the whole of it on a target with no /// vectors: check each lead byte for NUL before decoding its sequence, which /// covers every position because a continuation byte is never zero. fn validTextScalar(value: []const u8) bool { var i: usize = 0; while (i < value.len) { const lead = value[i]; if (lead == 0) return false; if (lead < 0x80) { i += 1; continue; } const sequence_length = std.unicode.utf8ByteSequenceLength(lead) catch return false; if (value.len - i < sequence_length) return false; _ = std.unicode.utf8Decode(value[i..][0..sequence_length]) catch return false; i += sequence_length; } return true; } /// Whether `value` may be encoded as a `s` string: valid UTF-8, with no /// interior NUL to be confused with the terminator. /// /// One pass checks both, where a NUL scan and `utf8ValidateSlice` would walk /// the string twice, and the pass stays in vector code through non-ASCII /// content. A chunk that is ASCII and NUL-free costs one compare; any other /// chunk goes through `validTextChunk`, as does the chunk after it, whose /// boundary-straddling checks close the sequences it opened. The tail — or /// the whole value, when it is shorter than a chunk, which nearly every /// string on a real bus is — is padded with a harmless ASCII byte into one /// more chunk rather than walked scalar, and the padding is also what /// catches a sequence truncated by the end of the value: its lead expects a /// continuation and meets an `a`. pub fn validText(value: []const u8) bool { if (comptime text_chunk_len == 0) return validTextScalar(value); var i: usize = 0; var prev: TextChunk = @splat(0); var prev_suspect = false; while (value.len - i >= text_chunk_len) : (i += text_chunk_len) { const chunk: TextChunk = value[i..][0..text_chunk_len].*; // A byte needs a closer look if it is NUL or non-ASCII, which // wrapping subtraction turns into one compare: 0 wraps to 255. const suspect = @reduce(.Or, chunk -% @as(TextChunk, @splat(1)) >= @as(TextChunk, @splat(0x7f))); if (suspect or prev_suspect) { if (!validTextChunk(prev, chunk)) return false; } prev = chunk; prev_suspect = suspect; } const tail = value[i..]; if (!prev_suspect) { // Nothing straddles into the tail, so a short one is cheaper walked // scalar than padded: below the crossover, the loop's few // iterations beat the padded chunk's fixed cost. if (tail.len == 0) return true; if (tail.len < min_padded_len) return validTextScalar(tail); } var padded: [text_chunk_len]u8 = @splat('a'); padCopy(&padded, tail); const chunk: TextChunk = padded; // The padded chunk gets the same one-compare fast path a full chunk // does, which is the whole cost of a short ASCII string. const suspect = @reduce(.Or, chunk -% @as(TextChunk, @splat(1)) >= @as(TextChunk, @splat(0x7f))); if (!suspect and !prev_suspect) return true; return validTextChunk(prev, chunk); } /// Below this many bytes, a scalar walk of a clean-boundary tail beats /// padding it into a chunk. const min_padded_len = 8; /// Copy `src`, shorter than a chunk, to the front of `dest` as a pair of /// overlapping fixed-size copies rather than a generic memcpy call, whose /// setup dwarfs a copy this small. fn padCopy(dest: *[text_chunk_len]u8, src: []const u8) void { const n = src.len; std.debug.assert(n <= text_chunk_len); inline for ([_]usize{ 32, 16, 8, 4 }) |width| { if (comptime width < text_chunk_len) { if (n >= width) { dest[0..width].* = src[0..width].*; dest[n - width ..][0..width].* = src[n - width ..][0..width].*; return; } } } for (dest[0..n], src) |*d, s| d.* = s; } /// Whether `chunk` continues a well-formed object path: every byte drawn /// from `[A-Za-z0-9_/]`, and no slash directly after the slash before it, /// which is the whole empty-component rule once the ends are checked. The /// chunk before it supplies the byte an adjacency straddling the boundary /// compares against. fn validPathChunk(prev: TextChunk, chunk: TextChunk) bool { const slash = chunk == @as(TextChunk, @splat('/')); const digit = chunk -% @as(TextChunk, @splat('0')) < @as(TextChunk, @splat(10)); // Setting the case bit folds both alphabets into one range. const letter = (chunk | @as(TextChunk, @splat(0x20))) -% @as(TextChunk, @splat('a')) < @as(TextChunk, @splat(26)); const word = digit | letter | (chunk == @as(TextChunk, @splat('_'))) | slash; const doubled = slash & (textPrev(1, prev, chunk) == @as(TextChunk, @splat('/'))); return @reduce(.And, word) and !@reduce(.Or, doubled); } /// Whether `value` is a well-formed `o` object path: an absolute path of /// nonempty components drawn from `[A-Za-z0-9_]`, or the root `/` alone. /// The ends are checked directly, which leaves "every byte in the alphabet, /// no two slashes adjacent" for the middle -- a vector predicate, checked a /// chunk at a time the way `validText` is. pub fn validObjectPath(value: []const u8) bool { if (value.len == 0 or value[0] != '/') return false; if (value.len == 1) return true; if (value[value.len - 1] == '/') return false; if (comptime text_chunk_len != 0) { // An underscore is in the alphabet and is not a slash, so it seeds // the adjacency check for the first position and pads the tail — // or the whole path, when it is shorter than a chunk. var i: usize = 0; var prev: TextChunk = @splat('_'); while (value.len - i >= text_chunk_len) : (i += text_chunk_len) { const chunk: TextChunk = value[i..][0..text_chunk_len].*; if (!validPathChunk(prev, chunk)) return false; prev = chunk; } const tail = value[i..]; if (tail.len == 0) return true; if (tail.len >= min_padded_len) { var padded: [text_chunk_len]u8 = @splat('_'); padCopy(&padded, tail); return validPathChunk(prev, padded); } // A short tail is cheaper walked scalar than padded; the byte // before it seeds the adjacency check, with the leading slash // standing in when the tail is the whole path. return validPathTail(value, @max(i, 1)); } return validPathTail(value, 1); } /// The scalar walk over `value[start..]`, with `value[start - 1]` seeding /// the slash-adjacency check; `start` is at least 1, the leading slash. fn validPathTail(value: []const u8, start: usize) bool { var previous_char = value[start - 1]; for (value[start..]) |c| { if (c == '/') { if (previous_char == '/') return false; } else if (!std.ascii.isAlphanumeric(c) and c != '_') return false; previous_char = c; } return true; } /// What one pass over a name's characters learns: whether every character /// belongs and no element rule is broken, and whether a separator appeared /// at all, which the wrappers below need because most of them require one. const NameBody = struct { valid: bool, has_dot: bool }; /// Whether `chunk` continues a well-formed name: every character from /// `[A-Za-z0-9_.]` (plus `-` where `hyphen` allows it), no dot directly /// after the dot before it — the nonempty-element rule, once the wrappers /// check the ends — and, where `no_digit_start` applies, no digit opening /// an element. The chunk before it supplies the byte the adjacency rules /// compare against. fn validNameChunk(comptime hyphen: bool, comptime no_digit_start: bool, prev: TextChunk, chunk: TextChunk) NameBody { const dot = chunk == @as(TextChunk, @splat('.')); const digit = chunk -% @as(TextChunk, @splat('0')) < @as(TextChunk, @splat(10)); // Setting the case bit folds both alphabets into one range. const letter = (chunk | @as(TextChunk, @splat(0x20))) -% @as(TextChunk, @splat('a')) < @as(TextChunk, @splat(26)); var word = digit | letter | (chunk == @as(TextChunk, @splat('_'))) | dot; if (hyphen) word = word | (chunk == @as(TextChunk, @splat('-'))); const prev_dot = textPrev(1, prev, chunk) == @as(TextChunk, @splat('.')); var bad = dot & prev_dot; if (no_digit_start) bad = bad | (digit & prev_dot); return .{ .valid = @reduce(.And, word) and !@reduce(.Or, bad), .has_dot = @reduce(.Or, dot), }; } /// The character and element rules over the whole of `value`, a chunk at a /// time the way `validObjectPath` walks; the wrappers check the ends. An /// underscore seeds and pads, since it is in every alphabet and neither a /// dot nor a digit. fn validNameBody(comptime hyphen: bool, comptime no_digit_start: bool, value: []const u8) NameBody { if (comptime text_chunk_len == 0) { var previous_char: u8 = '_'; var has_dot = false; for (value) |c| { const word = std.ascii.isAlphanumeric(c) or c == '_' or c == '.' or (hyphen and c == '-'); if (!word) return .{ .valid = false, .has_dot = has_dot }; if (c == '.') { if (previous_char == '.') return .{ .valid = false, .has_dot = true }; has_dot = true; } else if (no_digit_start and previous_char == '.' and std.ascii.isDigit(c)) { return .{ .valid = false, .has_dot = has_dot }; } previous_char = c; } return .{ .valid = true, .has_dot = has_dot }; } var i: usize = 0; var prev: TextChunk = @splat('_'); var has_dot = false; while (value.len - i >= text_chunk_len) : (i += text_chunk_len) { const chunk: TextChunk = value[i..][0..text_chunk_len].*; const body = validNameChunk(hyphen, no_digit_start, prev, chunk); has_dot = has_dot or body.has_dot; if (!body.valid) return .{ .valid = false, .has_dot = has_dot }; prev = chunk; } const tail = value[i..]; if (tail.len == 0) return .{ .valid = true, .has_dot = has_dot }; var padded: [text_chunk_len]u8 = @splat('_'); padCopy(&padded, tail); const body = validNameChunk(hyphen, no_digit_start, prev, padded); return .{ .valid = body.valid, .has_dot = has_dot or body.has_dot }; } /// Whether `value` is a well-formed member name: 1 to 255 characters of /// `[A-Za-z0-9_]`, not beginning with a digit. pub fn validMemberName(value: []const u8) bool { if (value.len == 0 or value.len > 255) return false; if (std.ascii.isDigit(value[0])) return false; const body = validNameBody(false, false, value); return body.valid and !body.has_dot; } /// Whether `value` is a well-formed interface name, which is also the rule /// for error names: at most 255 characters, two or more nonempty elements /// separated by dots, each of `[A-Za-z0-9_]` and not beginning with a digit. pub fn validInterfaceName(value: []const u8) bool { if (value.len == 0 or value.len > 255) return false; if (value[0] == '.' or std.ascii.isDigit(value[0]) or value[value.len - 1] == '.') return false; const body = validNameBody(false, true, value); return body.valid and body.has_dot; } /// Whether `value` is a well-formed bus name. A well-known name follows the /// interface rules with `-` added to the alphabet; a unique name is a colon /// followed by the same, except that its elements may begin with digits. pub fn validBusName(value: []const u8) bool { if (value.len == 0 or value.len > 255) return false; if (value[0] == ':') { const rest = value[1..]; if (rest.len == 0 or rest[0] == '.' or rest[rest.len - 1] == '.') return false; const body = validNameBody(true, false, rest); return body.valid and body.has_dot; } if (value[0] == '.' or std.ascii.isDigit(value[0]) or value[value.len - 1] == '.') return false; const body = validNameBody(true, true, value); return body.valid and body.has_dot; } /// Whether `c` is a basic type code: a fixed-size type or one of the three /// string-like ones, which is everything but the containers and `v`. The /// specification allows only these as a dict entry's key. pub fn basicType(c: u8) bool { return switch (c) { 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 'h', 's', 'o', 'g' => true, else => false, }; } /// Whether `value` is a well-formed `g` signature. `allow_empty` distinguishes /// the two uses: a signature may list any number of complete types, while a /// variant's must name exactly one. pub fn validSignature(value: []const u8, allow_empty: bool) bool { // Nearly every signature on a real bus is a single type code, answered // here without the grammar walk. Either `allow_empty` is satisfied by // one complete type. if (value.len == 1) return basicType(value[0]) or value[0] == 'v'; if (value.len > 255 or (!allow_empty and value.len == 0)) return false; var i: usize = 0; var count: usize = 0; while (i < value.len) : (count += 1) signatureOne(value, &i, .{}, false) catch return false; return allow_empty or count == 1; } /// Advance `i` past one single complete type. `element_of_array` says whether /// the type being read is an array's element type, which is the only place the /// specification allows a dict entry. /// /// One loop over the characters with an explicit stack of open containers, /// rather than recursive descent, so a character costs a switch and not a /// call with its `Depth` copy. The stack holds what a completed type /// continues: `a` is an array awaiting its element, `(` a struct none of /// whose fields have completed yet, `P` one with at least one field, and `D` /// a dict entry whose key is consumed and whose value type is being read. /// Each marker's count is bounded by its nesting budget before it is pushed, /// which is what bounds the stack. pub fn signatureOne(sig: []const u8, i: *usize, depth: Depth, element_of_array: bool) Error!void { var stack: [3 * Depth.max_container_depth]u8 = undefined; var sp: usize = 0; var array_depth = depth.array; var struct_depth = depth.structure; var dict_depth = depth.dict_entry; const start = i.*; outer: while (true) { if (i.* >= sig.len) return error.InvalidSignature; const c = sig[i.*]; i.* += 1; switch (c) { 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'o', 'g', 'h', 'v' => {}, 'a' => { array_depth += 1; if (array_depth > Depth.max_container_depth) return error.InvalidSignature; stack[sp] = 'a'; sp += 1; continue :outer; }, '(' => { struct_depth += 1; if (struct_depth > Depth.max_container_depth) return error.InvalidSignature; stack[sp] = '('; sp += 1; continue :outer; }, '{' => { // A dict entry is only an array's element: the type after a // pending `a`, or the whole of an element type being read. const as_element = if (sp > 0) stack[sp - 1] == 'a' else element_of_array and i.* == start + 1; if (!as_element) return error.InvalidSignature; dict_depth += 1; if (dict_depth > Depth.max_container_depth) return error.InvalidSignature; if (i.* >= sig.len or !basicType(sig[i.*])) return error.InvalidSignature; i.* += 1; stack[sp] = 'D'; sp += 1; continue :outer; }, ')' => { // Only a struct with at least one completed field closes. if (sp == 0 or stack[sp - 1] != 'P') return error.InvalidSignature; sp -= 1; struct_depth -= 1; }, else => return error.InvalidSignature, } // A complete type just ended; close everything it completes in turn. while (sp > 0) { switch (stack[sp - 1]) { 'a' => { sp -= 1; array_depth -= 1; }, '(' => { stack[sp - 1] = 'P'; continue :outer; }, 'P' => continue :outer, 'D' => { if (i.* >= sig.len or sig[i.*] != '}') return error.InvalidSignature; i.* += 1; sp -= 1; dict_depth -= 1; }, else => unreachable, } } return; } } /// The boundary a value of the type `c` starts on, or null when `c` opens no /// type at all. Only the first character of a complete type decides this, so /// a container's own code is enough. pub fn typeAlignment(c: u8) ?usize { return switch (c) { 'y', 'g', 'v' => 1, 'n', 'q' => 2, 'b', 'i', 'u', 'h', 's', 'o', 'a' => 4, 'x', 't', 'd', '(', '{' => 8, else => null, }; } test "method call round trip and fragmented prefix" { const a = std.testing.allocator; var body = Encoder.init(a); defer body.deinit(); try body.string("hello"); const bytes = try encodeMessage(a, .{ .message_type = .method_call, .path = "/org/test", .interface = "org.test", .member = "Hello", .destination = "org.test", .signature = "s" }, 7, body.bytes(), 0); try std.testing.expect((try messageLength(bytes[0..15])) == null); const owned = try a.dupe(u8, bytes); a.free(bytes); var message = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); defer message.deinit(); var d = message.bodyDecoder(); try std.testing.expectEqualStrings("hello", try d.string()); try d.end(); } test "nested dictionary variant alignment and unix fds" { const a = std.testing.allocator; var body = Encoder.init(a); defer body.deinit(); const array = try body.beginArray('{'); try body.dictEntryAlignment(); try body.string("answer"); try body.variantSignature("u"); try body.uint32(42); try body.endArray(array); const bytes = try encodeMessage(a, .{ .message_type = .method_call, .path = "/x", .member = "M", .signature = "a{sv}" }, 1, body.bytes(), 2); defer a.free(bytes); // Parse with harmless negative descriptors; Linux close rejects them. const owned = try a.dupe(u8, bytes); const fds = try a.dupe(std.posix.fd_t, &.{ -1, -1 }); var m = try parseMessage(a, owned, fds); defer m.deinit(); try std.testing.expectEqual(@as(u32, 2), m.header.unix_fd_count); var d = m.bodyDecoder(); const end_pos = try d.beginArray('{'); try d.structAlignment(); try std.testing.expectEqualStrings("answer", try d.string()); try std.testing.expectEqualStrings("u", try d.variantSignature()); try std.testing.expectEqual(@as(u32, 42), try d.uint32()); try d.endArray(end_pos); } test "big endian incoming and malformed variant" { var data = [_]u8{ 'B', 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0 }; // Header field: reply serial, variant u, value 1. data[16] = 5; data[17] = 1; data[18] = 'u'; data[19] = 0; data[23] = 1; const a = std.testing.allocator; var m = try parseMessage(a, try a.dupe(u8, &data), try a.alloc(std.posix.fd_t, 0)); defer m.deinit(); try std.testing.expectEqual(@as(u32, 1), m.header.reply_serial.?); var bad = data; bad[19] = 1; const bad_owned = try a.dupe(u8, &bad); defer a.free(bad_owned); const bad_fds = try a.alloc(std.posix.fd_t, 0); defer a.free(bad_fds); try std.testing.expectError(error.InvalidSignature, parseMessage(a, bad_owned, bad_fds)); } test "signed integers decode in either byte order" { // A signed value used to be read as unsigned and bit cast; it is read as // the signed type directly now, so the sign has to survive the byte swap // of a big-endian message as well as the pass through of a little-endian // one. Minus two is every byte set but the least significant, and the // minimum is the sign bit alone, where a sign-extension mistake shows up // as a magnitude one. const n_little = [_]u8{ 0xfe, 0xff }; const n_big = [_]u8{ 0xff, 0xfe }; const i_little = [_]u8{ 0xfe, 0xff, 0xff, 0xff }; const i_big = [_]u8{ 0xff, 0xff, 0xff, 0xfe }; const x_little = [_]u8{ 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; const x_big = [_]u8{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe }; var d: Decoder = .{ .data = &n_little, .endian = .little }; try std.testing.expectEqual(@as(i16, -2), try d.int16()); d = .{ .data = &n_big, .endian = .big }; try std.testing.expectEqual(@as(i16, -2), try d.int16()); d = .{ .data = &i_little, .endian = .little }; try std.testing.expectEqual(@as(i32, -2), try d.int32()); d = .{ .data = &i_big, .endian = .big }; try std.testing.expectEqual(@as(i32, -2), try d.int32()); d = .{ .data = &x_little, .endian = .little }; try std.testing.expectEqual(@as(i64, -2), try d.int64()); d = .{ .data = &x_big, .endian = .big }; try std.testing.expectEqual(@as(i64, -2), try d.int64()); const n_min_little = [_]u8{ 0x00, 0x80 }; const n_min_big = [_]u8{ 0x80, 0x00 }; const x_min_little = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0x80 }; const x_min_big = [_]u8{ 0x80, 0, 0, 0, 0, 0, 0, 0 }; d = .{ .data = &n_min_little, .endian = .little }; try std.testing.expectEqual(std.math.minInt(i16), try d.int16()); d = .{ .data = &n_min_big, .endian = .big }; try std.testing.expectEqual(std.math.minInt(i16), try d.int16()); d = .{ .data = &x_min_little, .endian = .little }; try std.testing.expectEqual(std.math.minInt(i64), try d.int64()); d = .{ .data = &x_min_big, .endian = .big }; try std.testing.expectEqual(std.math.minInt(i64), try d.int64()); } /// `s` repeated `n` times, for building long test inputs. The `**` operator /// that once did this is gone from the language as of Zig 0.17. fn repeat(comptime s: []const u8, comptime n: usize) *const [s.len * n]u8 { return comptime blk: { var out: [s.len * n]u8 = undefined; for (0..n) |i| @memcpy(out[i * s.len ..][0..s.len], s); const result = out; break :blk &result; }; } test "text validation rejects NULs and invalid UTF-8 in its single pass" { // Text that belongs in an `s`, including runs long enough to spend time // in the vector loop and multibyte content that lands in the scalar one. for ([_][]const u8{ "", "hello", "h\u{e9}llo w\u{f6}rld", "\u{65e5}\u{672c}\u{8a9e}", repeat("a", 100), repeat("a", 100) ++ "\u{e9}" ++ repeat("b", 100), }) |valid| { if (!validText(valid)) { std.debug.print("rejected valid text \"{s}\"\n", .{valid}); return error.TestUnexpectedResult; } } for ([_][]const u8{ // A NUL anywhere would be confused with the terminator: alone, in an // ASCII run long enough for the vector loop, and after non-ASCII, // where only the scalar loop can see it. "\x00", "a\x00b", repeat("a", 100) ++ "\x00" ++ repeat("b", 100), "\u{e9}\x00", // Invalid UTF-8: a bare continuation byte, an overlong NUL, a // surrogate half, a codepoint past U+10FFFF, and a truncated // sequence. "\x80", "\xc0\x80", "\xed\xa0\x80", "\xf4\x90\x80\x80", "\xe2\x82", repeat("a", 100) ++ "\xe2\x82", }, 0..) |invalid, index| { if (validText(invalid)) { std.debug.print("accepted invalid text, case {d}\n", .{index}); return error.TestUnexpectedResult; } } } test "text validation agrees with the standard library across random inputs" { // The vector validator and a NUL scan plus `utf8ValidateSlice` must be // the same predicate. Random bytes probe the rejection paths, random // codepoint sequences the acceptance paths, and single-byte corruptions // of those sequences the boundaries between them; a fixed seed keeps a // failure reproducible. var prng = std.Random.DefaultPrng.init(0x6d64627573); const random = prng.random(); var buffer: [512]u8 = undefined; var encoded: [4]u8 = undefined; for (0..20_000) |round| { var len: usize = 0; if (round % 2 == 0) { len = random.intRangeAtMost(usize, 0, buffer.len); random.bytes(buffer[0..len]); } else { while (len + 4 <= buffer.len) { const codepoint = switch (random.intRangeAtMost(u8, 0, 3)) { 0 => random.intRangeAtMost(u21, 0, 0x7F), 1 => random.intRangeAtMost(u21, 0x80, 0x7FF), 2 => random.intRangeAtMost(u21, 0x800, 0xFFFF), else => random.intRangeAtMost(u21, 0x10000, 0x10FFFF), }; const n = std.unicode.utf8Encode(codepoint, &encoded) catch continue; @memcpy(buffer[len..][0..n], encoded[0..n]); len += n; if (random.intRangeAtMost(u8, 0, 15) == 0) break; } // A corruption lands anywhere, including mid-sequence and at // chunk boundaries. if (len > 0 and random.boolean()) { buffer[random.intRangeAtMost(usize, 0, len - 1)] = random.int(u8); } } const value = buffer[0..len]; const reference = std.mem.findScalar(u8, value, 0) == null and std.unicode.utf8ValidateSlice(value); if (validText(value) != reference) { std.debug.print("disagreement on round {d}, len {d}\n", .{ round, len }); return error.TestUnexpectedResult; } } } test "object path validation agrees with its one-byte-at-a-time definition" { // The specification's rule, written the obvious way, is the reference // the vector version must match. Random strings over a small alphabet // that is mostly slashes and word characters probe the adjacency and // end rules; a sprinkling of arbitrary bytes probes the alphabet rule. // A fixed seed keeps a failure reproducible. const reference = struct { fn valid(value: []const u8) bool { if (value.len == 0 or value[0] != '/' or (value.len > 1 and value[value.len - 1] == '/')) return false; if (value.len == 1) return true; var component = false; for (value[1..]) |c| { if (c == '/') { if (!component) return false; component = false; } else { if (!std.ascii.isAlphanumeric(c) and c != '_') return false; component = true; } } return component; } }.valid; var prng = std.Random.DefaultPrng.init(0x6f626a70617468); const random = prng.random(); const alphabet = "///abcXYZ019__.-\x00\xff"; var buffer: [200]u8 = undefined; for (0..20_000) |round| { const len = random.intRangeAtMost(usize, 0, buffer.len); for (buffer[0..len]) |*c| c.* = alphabet[random.intRangeAtMost(usize, 0, alphabet.len - 1)]; // Most rounds get the leading slash so the middle rules are what is // being probed, not the first byte. if (len > 0 and round % 8 != 0) buffer[0] = '/'; const value = buffer[0..len]; if (validObjectPath(value) != reference(value)) { std.debug.print("disagreement on round {d}: \"{s}\"\n", .{ round, value }); return error.TestUnexpectedResult; } } } test "signature validation agrees with its recursive definition" { // The grammar written the obvious way -- recursive descent -- is the // reference the iterative walk must match, for both uses of // `allow_empty`. Random strings over the signature alphabet probe the // container rules; a sprinkling of arbitrary bytes probes the rest. A // fixed seed keeps a failure reproducible. const reference = struct { fn one(sig: []const u8, i: *usize, depth: Depth, element_of_array: bool) Error!void { if (i.* >= sig.len) return error.InvalidSignature; const c = sig[i.*]; i.* += 1; switch (c) { 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'o', 'g', 'h', 'v' => {}, 'a' => { const inner = try depth.enterArray(); if (i.* >= sig.len) return error.InvalidSignature; try one(sig, i, inner, true); }, '(' => { const inner = try depth.enterStruct(); const fields_start = i.*; while (i.* < sig.len and sig[i.*] != ')') try one(sig, i, inner, false); if (i.* == fields_start or i.* >= sig.len) return error.InvalidSignature; i.* += 1; }, '{' => { if (!element_of_array) return error.InvalidSignature; const inner = try depth.enterDictEntry(); if (i.* >= sig.len or !basicType(sig[i.*])) return error.InvalidSignature; i.* += 1; try one(sig, i, inner, false); if (i.* >= sig.len or sig[i.*] != '}') return error.InvalidSignature; i.* += 1; }, else => return error.InvalidSignature, } } fn valid(value: []const u8, allow_empty: bool) bool { if (value.len > 255 or (!allow_empty and value.len == 0)) return false; var i: usize = 0; var count: usize = 0; while (i < value.len) : (count += 1) one(value, &i, .{}, false) catch return false; return allow_empty or count == 1; } }; var prng = std.Random.DefaultPrng.init(0x7369676e6f6e65); const random = prng.random(); const alphabet = "yiustdvgas((({{{)))}}}a\x00.z"; var buffer: [48]u8 = undefined; for (0..30_000) |round| { const len = random.intRangeAtMost(usize, 0, buffer.len); for (buffer[0..len]) |*c| c.* = alphabet[random.intRangeAtMost(usize, 0, alphabet.len - 1)]; const value = buffer[0..len]; const allow_empty = round % 2 == 0; if (validSignature(value, allow_empty) != reference.valid(value, allow_empty)) { std.debug.print("disagreement on round {d}: \"{s}\"\n", .{ round, value }); return error.TestUnexpectedResult; } } } test "variant nesting is bounded at the specification's message depth" { // "The maximum total message depth, including variants, is 64." A // variant chain costs three body bytes per level, so without the bound a // peer could nest one deep enough that skipping it recurses beyond any // native stack. Sixty-four is a message; sixty-five is not. const a = std.testing.allocator; for ([_]struct { variants: usize, expected: ?Error }{ .{ .variants = 64, .expected = null }, .{ .variants = 65, .expected = error.InvalidMessage }, }) |case| { var body: Encoder = .init(a); defer body.deinit(); for (0..case.variants - 1) |_| try body.variantSignature("v"); try body.variantSignature("y"); try body.byte(7); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.x", .member = "M", .signature = "v", }, 1, body.bytes(), 0); const owned = try a.dupe(u8, bytes); a.free(bytes); if (case.expected) |expected| { defer a.free(owned); const no_fds = try a.alloc(std.posix.fd_t, 0); defer a.free(no_fds); try std.testing.expectError(expected, parseMessage(a, owned, no_fds)); } else { var m = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); m.deinit(); } } } test "name grammars match the specification" { const long = "x." ++ repeat("a", 254); for ([_][]const u8{ "Foo", "_foo", "FooBar2", repeat("a", 255) }) |valid| { try std.testing.expect(validMemberName(valid)); } for ([_][]const u8{ "", "1Foo", "foo.bar", "foo-bar", "fo\u{e9}", repeat("a", 256) }) |invalid| { try std.testing.expect(!validMemberName(invalid)); } for ([_][]const u8{ "org.freedesktop.DBus", "a.b", "a._1.b", "_.__" }) |valid| { try std.testing.expect(validInterfaceName(valid)); } for ([_][]const u8{ "", "org", ".a.b", "a.b.", "a..b", "a.1b", "1a.b", "a-b.cd", "a.b\u{e9}", long, }) |invalid| { try std.testing.expect(!validInterfaceName(invalid)); } for ([_][]const u8{ "org.freedesktop.DBus", "com.example-thing.Foo", ":1.42", ":1.0.a", ":a.b" }) |valid| { try std.testing.expect(validBusName(valid)); } for ([_][]const u8{ "", "org", ":", ":1", ":.a", ":a.", "a.1b", "1a.b", ":x\u{e9}.y", long }) |invalid| { try std.testing.expect(!validBusName(invalid)); } } test "a header field carrying a malformed name is refused" { // The encoder refuses to write one, so the wire bytes are patched: the // interface's first character becomes a digit after encoding. const a = std.testing.allocator; const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.Xample.Iface", .member = "M", }, 1, "", 0); const owned = try a.dupe(u8, bytes); a.free(bytes); defer a.free(owned); const at = std.mem.find(u8, owned, "Xample").?; owned[at] = '1'; const no_fds = try a.alloc(std.posix.fd_t, 0); defer a.free(no_fds); try std.testing.expectError(error.InvalidName, parseMessage(a, owned, no_fds)); try std.testing.expectError(error.InvalidName, encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.1ample.Iface", .member = "M", }, 1, "", 0)); try std.testing.expectError(error.InvalidName, encodeMessage(a, .{ .message_type = .method_call, .path = "/x", .member = "not.a.member", .destination = "org.x.y", }, 1, "", 0)); try std.testing.expectError(error.InvalidName, encodeMessage(a, .{ .message_type = .method_call, .path = "/x", .member = "M", .destination = "nodots", }, 1, "", 0)); } test "the reserved local path and interface never cross the wire" { // The specification reserves both for messages a peer synthesizes about // its own connection, and the reference bus disconnects a sender that // uses them; refusing to encode them is the sending half of that rule. const a = std.testing.allocator; try std.testing.expectError(error.ReservedName, encodeMessage(a, .{ .message_type = .method_call, .path = "/org/freedesktop/DBus/Local", .member = "M", }, 1, "", 0)); try std.testing.expectError(error.ReservedName, encodeMessage(a, .{ .message_type = .method_call, .path = "/x", .interface = "org.freedesktop.DBus.Local", .member = "M", }, 1, "", 0)); // The names remain ordinary prefixes: only the exact reserved values // are refused. const bytes = try encodeMessage(a, .{ .message_type = .method_call, .path = "/org/freedesktop/DBus/LocalNot", .interface = "org.freedesktop.DBus.LocalNot", .member = "M", }, 1, "", 0); a.free(bytes); } test "message depth counts containers and variants together" { // The 64 the specification allows is a total: an array at the bottom of // sixty-three variants is the sixty-fourth level and fine, while the // same array under one more variant is not. const a = std.testing.allocator; for ([_]struct { variants: usize, expected: ?Error }{ .{ .variants = 63, .expected = null }, .{ .variants = 64, .expected = error.InvalidMessage }, }) |case| { var body: Encoder = .init(a); defer body.deinit(); for (0..case.variants - 1) |_| try body.variantSignature("v"); try body.variantSignature("ay"); const array = try body.beginArray('y'); try body.endArray(array); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.x", .member = "M", .signature = "v", }, 1, body.bytes(), 0); const owned = try a.dupe(u8, bytes); a.free(bytes); if (case.expected) |expected| { defer a.free(owned); const no_fds = try a.alloc(std.posix.fd_t, 0); defer a.free(no_fds); try std.testing.expectError(expected, parseMessage(a, owned, no_fds)); } else { var m = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); m.deinit(); } } } test "boolean values are inspected wherever the walk meets them" { // The specification allows a boolean no value but 0 and 1, in an array // as much as anywhere else. const a = std.testing.allocator; for ([_]struct { second: u32, expected: ?Error }{ .{ .second = 1, .expected = null }, .{ .second = 2, .expected = error.InvalidMessage }, }) |case| { var body: Encoder = .init(a); defer body.deinit(); const array = try body.beginArray('b'); try body.uint32(0); try body.uint32(case.second); try body.endArray(array); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.x", .member = "M", .signature = "ab", }, 1, body.bytes(), 0); const owned = try a.dupe(u8, bytes); a.free(bytes); if (case.expected) |expected| { defer a.free(owned); const no_fds = try a.alloc(std.posix.fd_t, 0); defer a.free(no_fds); try std.testing.expectError(expected, parseMessage(a, owned, no_fds)); } else { var m = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); m.deinit(); } } } test "bulk ai content round trips in either byte order and is bounds checked" { const a = std.testing.allocator; var body: Encoder = .init(a); defer body.deinit(); const values = [_]i32{ 1, -2, 3, std.math.minInt(i32), std.math.maxInt(i32) }; const array = try body.beginArray('i'); try body.int32Slice(&values); try body.endArray(array); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.x", .member = "M", .signature = "ai", }, 1, body.bytes(), 0); const owned = try a.dupe(u8, bytes); a.free(bytes); var m = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); defer m.deinit(); var d = m.bodyDecoder(); var dest: [8]i32 = undefined; const end_pos = try d.beginArray('i'); try std.testing.expectEqualSlices(i32, &values, try d.int32Slice(end_pos, &dest)); try d.endArray(end_pos); try d.end(); // A big-endian message is decoded with its own byte order, which is the // path a same-endian copy cannot cover. const big = [_]u8{ 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x02 }; var swapped: Decoder = .{ .data = &big, .endian = .big }; try std.testing.expectEqualSlices(i32, &.{ -2, 2 }, try swapped.int32Slice(big.len, &dest)); // A length that is not whole elements, an end past the buffer, and a // destination too small for the array are each their own refusal. var ragged: Decoder = .{ .data = big[0..6], .endian = .little }; try std.testing.expectError(error.InvalidMessage, ragged.int32Slice(6, &dest)); var beyond: Decoder = .{ .data = &big, .endian = .little }; try std.testing.expectError(error.EndOfMessage, beyond.int32Slice(big.len + 4, &dest)); var cramped: Decoder = .{ .data = &big, .endian = .little }; try std.testing.expectError(error.InvalidValue, cramped.int32Slice(big.len, dest[0..1])); } test "bulk ay content round trips and is bounds checked" { const a = std.testing.allocator; var body: Encoder = .init(a); defer body.deinit(); const array = try body.beginArray('y'); try body.byteSlice(&.{ 1, 2, 3, 4, 5 }); try body.endArray(array); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/x", .interface = "org.x", .member = "M", .signature = "ay", }, 1, body.bytes(), 0); const owned = try a.dupe(u8, bytes); a.free(bytes); var m = try parseMessage(a, owned, try a.alloc(std.posix.fd_t, 0)); defer m.deinit(); var d = m.bodyDecoder(); const end_pos = try d.beginArray('y'); try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5 }, try d.byteSlice(end_pos)); try d.endArray(end_pos); try d.end(); // An end past the buffer is a truncation, and one behind the current // position means the caller already read past it. const data = [_]u8{ 1, 2 }; var bounds: Decoder = .{ .data = &data, .endian = .little }; try std.testing.expectError(error.EndOfMessage, bounds.byteSlice(3)); _ = try bounds.byteSlice(2); try std.testing.expectError(error.InvalidMessage, bounds.byteSlice(1)); } test "invalid values and oversized prefix" { const a = std.testing.allocator; var e = Encoder.init(a); defer e.deinit(); try std.testing.expectError(error.InvalidObjectPath, e.objectPath("bad")); try std.testing.expectError(error.InvalidSignature, e.signature("a")); var h = [_]u8{ 'l', 1, 0, 1 } ++ @as([12]u8, @splat(0)); std.mem.writeInt(u32, h[4..8], @intCast(max_message_size), .little); try std.testing.expectError(error.MessageTooLarge, messageLength(&h)); } test "every type in the specification round trips" { // One body holding every type code the specification allows on the wire, // in the order the type table lists them, followed by each container. // `parseMessage` walks the whole body against this signature, so a // disagreement between the encoder and the skipper fails here too. const signature_value = "ybnqiuxtdhsogvai(is)a{sv}"; const a = std.testing.allocator; var body: Encoder = .init(a); defer body.deinit(); try body.byte(0xab); try body.boolean(true); try body.int16(std.math.minInt(i16)); try body.uint16(std.math.maxInt(u16)); try body.int32(std.math.minInt(i32)); try body.uint32(std.math.maxInt(u32)); try body.int64(std.math.minInt(i64)); try body.uint64(std.math.maxInt(u64)); try body.double(-0.5); try body.unixFd(0); try body.string("string"); try body.objectPath("/org/example/Path"); try body.signature("a{sv}"); try body.variantSignature("d"); try body.double(2.5); const numbers = try body.beginArray('i'); for ([_]i32{ 1, -2, 3 }) |value| try body.int32(value); try body.endArray(numbers); try body.structAlignment(); try body.int32(7); try body.string("in a struct"); const dictionary = try body.beginArray('{'); try body.dictEntryAlignment(); try body.string("key"); try body.variantSignature("t"); try body.uint64(99); try body.endArray(dictionary); const bytes = try encodeMessage(a, .{ .message_type = .signal, .path = "/org/example/Path", .interface = "org.example.Types", .member = "Every", .signature = signature_value, }, 1, body.bytes(), 1); const owned = try a.dupe(u8, bytes); a.free(bytes); // A harmless placeholder descriptor; Linux close rejects a negative one. const fds = try a.dupe(std.posix.fd_t, &.{-1}); var message = try parseMessage(a, owned, fds); defer message.deinit(); try std.testing.expectEqualStrings(signature_value, message.bodySignature()); var d = message.bodyDecoder(); try std.testing.expectEqual(@as(u8, 0xab), try d.byte()); try std.testing.expectEqual(true, try d.boolean()); try std.testing.expectEqual(std.math.minInt(i16), try d.int16()); try std.testing.expectEqual(std.math.maxInt(u16), try d.uint16()); try std.testing.expectEqual(std.math.minInt(i32), try d.int32()); try std.testing.expectEqual(std.math.maxInt(u32), try d.uint32()); try std.testing.expectEqual(std.math.minInt(i64), try d.int64()); try std.testing.expectEqual(std.math.maxInt(u64), try d.uint64()); try std.testing.expectEqual(@as(f64, -0.5), try d.double()); try std.testing.expectEqual(@as(u32, 0), try d.unixFd()); try std.testing.expectEqualStrings("string", try d.string()); try std.testing.expectEqualStrings("/org/example/Path", try d.objectPath()); try std.testing.expectEqualStrings("a{sv}", try d.signature()); try std.testing.expectEqualStrings("d", try d.variantSignature()); try std.testing.expectEqual(@as(f64, 2.5), try d.double()); const numbers_end = try d.beginArray('i'); for ([_]i32{ 1, -2, 3 }) |value| try std.testing.expectEqual(value, try d.int32()); try d.endArray(numbers_end); try d.structAlignment(); try std.testing.expectEqual(@as(i32, 7), try d.int32()); try std.testing.expectEqualStrings("in a struct", try d.string()); const dictionary_end = try d.beginArray('{'); try d.structAlignment(); try std.testing.expectEqualStrings("key", try d.string()); try std.testing.expectEqualStrings("t", try d.variantSignature()); try std.testing.expectEqual(@as(u64, 99), try d.uint64()); try d.endArray(dictionary_end); try d.end(); } test "signature validation matches the specification's type codes" { // Every code the specification defines as a type, and every code it // reserves. A reserved code reaching the wire is a protocol error, so the // struct and dict-entry codes `r` and `e` are rejected alongside `m`, // `*`, `?`, `@`, `&`, and `^`; signatures spell those out with brackets. for ([_][]const u8{ "y", "b", "n", "q", "i", "u", "x", "t", "d", "h", "s", "o", "g", "v", "ai", "aay", "as", "a{sv}", "a(i)", "(is)", "((i))", "(ybnqiuxtd)", "ybnqiuxtdhsogv", }) |valid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); body.signature(valid) catch |err| { std.debug.print("rejected valid signature \"{s}\"\n", .{valid}); return err; }; } for ([_][]const u8{ // The reserved codes, including the `r` and `e` that name a struct and // a dict entry outside of a signature, where brackets spell them out. "r", "e", "m", "*", "?", "@", "&", "^", // Brackets that do not balance, and an array with no element type. "(", ")", "{", "}", "a", "ai(", "(i", "i)", "(is", "a{sv", // A struct with no fields, a dict entry with the wrong number of // types, one outside an array, and one keyed by a container. "()", "a{s}", "a{iss}", "{is}", "a{vs}", }) |invalid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try std.testing.expectError(error.InvalidSignature, body.signature(invalid)); } } test "a dict entry is only valid as an array element" { // The specification allows DICT_ENTRY to "occur only as an array element // type", so being nested inside some container is not enough on its own. for ([_][]const u8{ "a{is}", "a{sv}", "(a{is})", "aa{is}", "a{sa{sv}}" }) |valid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); body.signature(valid) catch |err| { std.debug.print("rejected a dict entry in an array: {s}\n", .{valid}); return err; }; } for ([_][]const u8{ "{is}", "({is})", "(i{is})", "((({is})))", "a({is})" }) |invalid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try std.testing.expectError(error.InvalidSignature, body.signature(invalid)); } } test "size limits agree with the protocol" { // The build option is bounded at compile time, so this pins the protocol's // own constants and records the relationship for a reader. try std.testing.expectEqual(@as(usize, 134217728), spec_max_message_size); try std.testing.expectEqual(@as(usize, 67108864), spec_max_array_size); try std.testing.expect(max_message_size <= spec_max_message_size); // An array is capped separately from the message around it, which starts // to matter once a build raises `max_message_size` past 64 MiB. The length // is refused before any content is read, so checking it needs no more than // the four bytes that carry the length. var data: [8]u8 = @splat(0); std.mem.writeInt(u32, data[0..4], @intCast(spec_max_array_size + 1), .little); var over: Decoder = .{ .data = &data, .endian = .little }; try std.testing.expectError(error.MessageTooLarge, over.beginArray('u')); // Exactly at the cap is allowed through and fails on the buffer instead, // which is what makes the check exclusive rather than off by one. std.mem.writeInt(u32, data[0..4], @intCast(spec_max_array_size), .little); var at_limit: Decoder = .{ .data = &data, .endian = .little }; try std.testing.expectError(error.EndOfMessage, at_limit.beginArray('u')); } test "container nesting is bounded per kind, as the specification bounds it" { // "The maximum depth of container type nesting is 32 array type codes and // 32 open parentheses", which is two budgets rather than one: a signature // nesting 32 arrays around 32 structs spends both and is still legal. const arrays = repeat("a", Depth.max_container_depth) ++ "i"; const structs = repeat("(", Depth.max_container_depth) ++ "i" ++ repeat(")", Depth.max_container_depth); const both = repeat("a", Depth.max_container_depth) ++ structs; const dict_entries = repeat("a{sa{s", 3) ++ "i" ++ repeat("}}", 3); for ([_][]const u8{ arrays, structs, both, dict_entries }) |valid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); body.signature(valid) catch |err| { std.debug.print("rejected a signature within both budgets: {s}\n", .{valid}); return err; }; } // One past either budget is refused, and overspending one does not become // permissible by having spent little of the other. const too_many_arrays = repeat("a", Depth.max_container_depth + 1) ++ "i"; const too_many_structs = repeat("(", Depth.max_container_depth + 1) ++ "i" ++ repeat(")", Depth.max_container_depth + 1); for ([_][]const u8{ too_many_arrays, too_many_structs }) |invalid| { var body: Encoder = .init(std.testing.allocator); defer body.deinit(); try std.testing.expectError(error.InvalidSignature, body.signature(invalid)); } } test { // Neither half has tests of its own yet; the round trips above cover both. // Referencing them here means any tests they grow will run. _ = encode; _ = decode; }