Something went wrong. Try again.
A small D-Bus client transport for Zig: session bus, method calls, signals, replies and file descriptor passing.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665// SPDX-FileCopyrightText: © 2026 Tim Culverhouse <tim@timculverhouse.com>// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Reading D-Bus messages: framing bytes off a stream, parsing a message's//! header, and the bounds-checked `Decoder` over its body.//!//! `wire.zig` holds the encoding half, 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 Depth = wire.Depth;const basicType = wire.basicType;const Error = wire.Error;const MessageType = wire.MessageType;const max_message_size = wire.max_message_size;const signatureOne = wire.signatureOne;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;
/// The header fields of a parsed message. The string fields alias the owning/// `Message.data` and are only valid until that message is deinitialized.pub const Header = struct { message_type: MessageType, flags: u8, serial: u32, 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, /// Who sent the message, as their unique name. The bus fills this in, so a /// message that came from one always has it; it is what a reply has to be /// addressed to. sender: ?[]const u8 = null, signature: []const u8 = "", unix_fd_count: u32 = 0,};
/// One parsed message and the resources it owns: its buffer and any received/// file descriptors. Call `deinit` on every message you are handed.pub const Message = struct { allocator: std.mem.Allocator, data: []u8, fds: []std.posix.fd_t, header: Header, body_offset: usize, endian: std.builtin.Endian, /// Close the received descriptors and free the message buffer. pub fn deinit(self: *Message) void { for (self.fds) |fd| _ = std.os.linux.close(fd); self.allocator.free(self.fds); self.allocator.free(self.data); self.* = undefined; } /// The argument bytes following the header. pub fn body(self: *const Message) []const u8 { return self.data[self.body_offset..]; } /// The signature describing the body, empty when there are no arguments. pub fn bodySignature(self: *const Message) []const u8 { return self.header.signature; } /// Whether this is a method call, return, error, or signal. pub fn messageType(self: *const Message) MessageType { return self.header.message_type; } /// Whether the caller set NO_REPLY_EXPECTED, in which case answering this /// call is allowed but wasted: nothing is waiting for the answer. pub fn noReplyExpected(self: *const Message) bool { return self.header.flags & 0x1 != 0; } /// A decoder positioned at the start of the body. pub fn bodyDecoder(self: *const Message) Decoder { return .{ .data = self.body(), .endian = self.endian, .base_offset = 0 }; }};
/// Return the total length of the message beginning at `prefix`, or null if/// `prefix` does not yet hold enough bytes to determine or complete it. This/// lets a caller feed a growing receive buffer in without over-reading.pub fn messageLength(prefix: []const u8) !?usize { if (prefix.len < 16) return null; const endian: std.builtin.Endian = switch (prefix[0]) { 'l' => .little, 'B' => .big, else => return error.InvalidMessage, }; // Type zero is reserved and never valid, but a type this version does not // know about must be ignored rather than refused, so that a peer speaking a // later revision of the protocol does not break framing. if (prefix[3] != 1 or prefix[1] == 0) return error.InvalidMessage; const body_len = readInt(u32, prefix[4..8], endian); const fields_len = readInt(u32, prefix[12..16], endian); const fields_end = std.math.add(usize, 16, fields_len) catch return error.Overflow; const body_start = alignForward(fields_end, 8) catch return error.Overflow; const total = std.math.add(usize, body_start, body_len) catch return error.Overflow; if (total > max_message_size) return error.MessageTooLarge; if (prefix.len < total) return null; return total;}
/// Parse exactly one message, taking ownership of `data` and `fds`; both are/// released by `Message.deinit`, including on error paths inside the returned/// message's lifetime. The header fields, the padding before the body, and/// the body's conformance to its signature are all validated up front, so a/// message that parses can be decoded without further structural checks./// A message of an unknown type parses if it is well formed; required header/// fields are only enforced for the types this version defines.pub fn parseMessage(allocator: std.mem.Allocator, data: []u8, fds: []std.posix.fd_t) !Message { const n = try messageLength(data) orelse return error.EndOfMessage; if (n != data.len) return error.TrailingData; const endian: std.builtin.Endian = if (data[0] == 'l') .little else .big; const fields_len: usize = readInt(u32, data[12..16], endian); const body_offset = try alignForward(16 + fields_len, 8); for (data[16 + fields_len .. body_offset]) |v| if (v != 0) return error.InvalidMessage; var d: Decoder = .{ .data = data[16 .. 16 + fields_len], .endian = endian, .base_offset = 16 }; var h: Header = .{ .message_type = @enumFromInt(data[1]), .flags = data[2], .serial = readInt(u32, data[8..12], endian) }; if (h.serial == 0) return error.InvalidMessage; var seen: u16 = 0; while (!d.finished()) { try d.structAlignment(); const code = try d.byte(); // Unvalidated: a known field's signature is compared against the one // it must have, and an unknown field's is enforced by the walk that // skips its value, so a walk here would repeat one or the other. const sig = try d.signatureData(); if (code <= 9 and code != 7) { const bit: u16 = @as(u16, 1) << @intCast(code); if (seen & bit != 0) return error.DuplicateHeaderField; seen |= bit; } switch (code) { 1 => { try requireHeaderSig(sig, "o"); h.path = try d.objectPath(); }, 2 => { try requireHeaderSig(sig, "s"); h.interface = try headerName(&d, validInterfaceName); }, 3 => { try requireHeaderSig(sig, "s"); h.member = try headerName(&d, validMemberName); }, 4 => { try requireHeaderSig(sig, "s"); h.error_name = try headerName(&d, validInterfaceName); }, 5 => { try requireHeaderSig(sig, "u"); h.reply_serial = try d.uint32(); }, 6 => { try requireHeaderSig(sig, "s"); h.destination = try headerName(&d, validBusName); }, 7 => { try requireHeaderSig(sig, "s"); h.sender = try headerName(&d, validBusName); }, 8 => { try requireHeaderSig(sig, "g"); h.signature = try d.signature(); }, 9 => { try requireHeaderSig(sig, "u"); h.unix_fd_count = try d.uint32(); }, // On failure the signature is checked after all, so a malformed // one is reported as that and not as whatever the walk tripped // over first; a message that parses never takes the extra walk. else => d.skipSignatureValue(sig) catch |err| { return if (!validSignature(sig, false)) error.InvalidSignature else err; }, } } switch (h.message_type) { .method_call => if (h.path == null or h.member == null) return error.MissingHeaderField, .method_return => if (h.reply_serial == null) return error.MissingHeaderField, .error_reply => if (h.error_name == null or h.reply_serial == null) return error.MissingHeaderField, .signal => if (h.path == null or h.interface == null or h.member == null) return error.MissingHeaderField, // An unknown message type has no fields this version can require of it. // It is still validated like any other message, so a caller that // discards it knows it discarded something well-formed. _ => {}, } if ((data.len - body_offset == 0) != (h.signature.len == 0)) return error.InvalidMessage; if (h.unix_fd_count != fds.len) return error.InvalidMessage; var body_decoder: Decoder = .{ .data = data[body_offset..], .endian = endian }; var signature_index: usize = 0; while (signature_index < h.signature.len) try body_decoder.skipOne(h.signature, &signature_index, .{}); try body_decoder.end(); return .{ .allocator = allocator, .data = data, .fds = fds, .header = h, .body_offset = body_offset, .endian = endian };}
/// A cursor over an argument list that bounds-checks every read. `base_offset`/// is the position of `data` within the whole message, which alignment padding/// is computed against; it is zero for a body and 16 for a header field array.pub const Decoder = struct { data: []const u8, position: usize = 0, endian: std.builtin.Endian, base_offset: usize = 0, /// Whether every byte has been consumed. pub fn finished(self: *const Decoder) bool { return self.position == self.data.len; } /// Assert that the argument list was consumed exactly. pub fn end(self: *const Decoder) !void { if (!self.finished()) return error.TrailingData; } fn alignment(self: *Decoder, a: usize) !void { const global = std.math.add(usize, self.base_offset, self.position) catch return error.Overflow; // Alignments are 1, 2, 4, or 8, so the round-up is a mask rather than // a division, which matters when `a` only becomes known at runtime, // as it does for every array element. std.debug.assert(std.math.isPowerOfTwo(a)); const padding = (0 -% global) & (a - 1); if (padding > self.data.len -| self.position) return error.EndOfMessage; for (self.data[self.position .. self.position + padding]) |v| if (v != 0) return error.InvalidMessage; self.position += padding; } fn take(self: *Decoder, n: usize) ![]const u8 { if (n > self.data.len -| self.position) return error.EndOfMessage; const out = self.data[self.position .. self.position + n]; self.position += n; return out; } /// Read a `y` byte. pub fn byte(self: *Decoder) !u8 { return (try self.take(1))[0]; } /// Read the content of a `y`-element array in one step: everything from /// the current position to `end_pos`, which is what `beginArray` /// returned. The result aliases the decoded buffer rather than being /// copied, and `endArray` passes trivially afterwards. pub fn byteSlice(self: *Decoder, end_pos: usize) ![]const u8 { if (end_pos < self.position) return error.InvalidMessage; if (end_pos > self.data.len) return error.EndOfMessage; const out = self.data[self.position..end_pos]; self.position = end_pos; return out; } /// Read a `q` unsigned 16-bit integer. pub fn uint16(self: *Decoder) !u16 { try self.alignment(@sizeOf(u16)); return readInt(u16, try self.take(@sizeOf(u16)), self.endian); } /// Read a `u` unsigned 32-bit integer. pub fn uint32(self: *Decoder) !u32 { try self.alignment(@sizeOf(u32)); return readInt(u32, try self.take(@sizeOf(u32)), self.endian); } /// Read a `t` unsigned 64-bit integer. pub fn uint64(self: *Decoder) !u64 { try self.alignment(@sizeOf(u64)); return readInt(u64, try self.take(@sizeOf(u64)), self.endian); } /// Read an `n` signed 16-bit integer. pub fn int16(self: *Decoder) !i16 { try self.alignment(@sizeOf(i16)); return readInt(i16, try self.take(@sizeOf(i16)), self.endian); } /// Read the content of an `i`-element array in one step: everything from /// the current position to `end_pos`, which is what `beginArray` /// returned, decoded into `dest`. The filled prefix of `dest` is /// returned, and `endArray` passes trivially afterwards. The values are /// copied rather than aliased, because the message buffer guarantees /// neither their alignment nor their byte order; when the message's /// byte order is the host's, the copy is a single one. A `dest` too /// small for the array is `error.InvalidValue`. pub fn int32Slice(self: *Decoder, end_pos: usize, dest: []i32) Error![]i32 { if (end_pos < self.position) return error.InvalidMessage; if (end_pos > self.data.len) return error.EndOfMessage; const content = self.data[self.position..end_pos]; if (content.len % @sizeOf(i32) != 0) return error.InvalidMessage; const count = content.len / @sizeOf(i32); if (count > dest.len) return error.InvalidValue; if (self.endian == comptime builtin.cpu.arch.endian()) { @memcpy(std.mem.sliceAsBytes(dest[0..count]), content); } else { for (dest[0..count], 0..) |*value, index| { value.* = std.mem.readInt(i32, content[index * @sizeOf(i32) ..][0..@sizeOf(i32)], self.endian); } } self.position = end_pos; return dest[0..count]; } /// Read an `i` signed 32-bit integer. pub fn int32(self: *Decoder) !i32 { try self.alignment(@sizeOf(i32)); return readInt(i32, try self.take(@sizeOf(i32)), self.endian); } /// Read an `x` signed 64-bit integer. pub fn int64(self: *Decoder) !i64 { try self.alignment(@sizeOf(i64)); return readInt(i64, try self.take(@sizeOf(i64)), self.endian); } /// Read a `b` boolean, rejecting values other than 0 and 1. pub fn boolean(self: *Decoder) !bool { const v = try self.uint32(); if (v > 1) return error.InvalidValue; return v == 1; } /// Read an `h` file descriptor, which travels as an index into the /// descriptors received with the message rather than as the descriptor. /// The caller resolves it against `Message.fds`. pub fn unixFd(self: *Decoder) !u32 { return self.uint32(); } /// Read a `d` double. pub fn double(self: *Decoder) !f64 { try self.alignment(@sizeOf(u64)); return @bitCast(readInt(u64, try self.take(@sizeOf(u64)), self.endian)); } /// 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: *Decoder) ![]const u8 { const n = try self.uint32(); const value = try self.take(n); if ((try self.byte()) != 0) return error.InvalidString; return value; } /// Read an `s` string, validating its UTF-8 and terminator. The result aliases /// the decoded buffer rather than being copied. pub fn string(self: *Decoder) ![]const u8 { const value = try self.stringData(); if (!validText(value)) return error.InvalidString; return value; } /// Read an `o` object path, validating its syntax. A valid path is ASCII /// with no NUL in it, so the syntax check subsumes the text check an `s` /// gets and the content is walked once, not twice. pub fn objectPath(self: *Decoder) ![]const u8 { const value = try self.stringData(); if (!validObjectPath(value)) return error.InvalidObjectPath; return value; } /// A signature's framing: the length byte, the content, the terminator. /// What the content must look like is the caller's check. fn signatureData(self: *Decoder) ![]const u8 { const n = try self.byte(); const value = try self.take(n); if ((try self.byte()) != 0) return error.InvalidSignature; return value; } /// Read a `g` signature, which may be empty or hold several complete types. pub fn signature(self: *Decoder) ![]const u8 { const value = try self.signatureData(); if (!validSignature(value, true)) return error.InvalidSignature; return value; } /// Read the signature that opens a `v` variant, requiring one complete /// type. That requirement subsumes the ordinary signature check, so the /// value is walked once, not once per check. pub fn variantSignature(self: *Decoder) ![]const u8 { const value = try self.signatureData(); if (!validSignature(value, false)) return error.InvalidSignature; return value; } /// Skip the padding that precedes a struct or dict entry, rejecting nonzero /// padding bytes. pub fn structAlignment(self: *Decoder) !void { try self.alignment(8); } /// Enter 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. Returns the position at which the array /// ends: pass it to `arrayFinished` to drive the element loop and to /// `endArray` when done — or, for a `y` or `i` array, to `byteSlice` or /// `int32Slice` to take the whole content in one step. pub fn beginArray(self: *Decoder, element: u8) !usize { const element_alignment = typeAlignment(element) orelse return error.InvalidSignature; return self.beginArrayAligned(element_alignment); } /// The rest of `beginArray`, for the signature walk, whose element type /// is already validated and its alignment already in hand. fn beginArrayAligned(self: *Decoder, element_alignment: usize) !usize { const n = try self.uint32(); // The protocol caps an array independently of the message around it, // which matters once a build raises `max_message_size` past 64 MiB. if (n > spec_max_array_size) return error.MessageTooLarge; try self.alignment(element_alignment); const end_pos = std.math.add(usize, self.position, n) catch return error.Overflow; if (end_pos > self.data.len) return error.EndOfMessage; return end_pos; } /// Whether the array ending at `end_pos` has been fully read, erroring if /// decoding has already run past it. pub fn arrayFinished(self: *const Decoder, end_pos: usize) !bool { if (self.position > end_pos) return error.InvalidMessage; return self.position == end_pos; } /// Assert that the array ending at `end_pos` was consumed exactly. pub fn endArray(self: *const Decoder, end_pos: usize) !void { if (self.position != end_pos) return error.InvalidMessage; } /// Skip one value described by `signature_value`, which must be a single /// complete type. Used to step over header fields and variants this code does /// not interpret, and to validate a body against its signature. pub fn skipSignatureValue(self: *Decoder, signature_value: []const u8) Error!void { return self.skipSignatureValueAtDepth(signature_value, .{}); } /// The rest of `skipSignatureValue`, carrying the depth a variant's /// value inherits so nested variants cannot recurse without bound. fn skipSignatureValueAtDepth(self: *Decoder, signature_value: []const u8, depth: Depth) Error!void { var index: usize = 0; try self.skipOne(signature_value, &index, depth); if (index != signature_value.len) return error.InvalidSignature; } /// One open container of the walk below: an array looping its elements, /// a struct before and after its first completed field, or a dict entry /// stepping from key to value to `}`. An array frame is the one that /// carries state: where its element's signature starts, so completing /// an element can loop the signature back, and where its content ends. const Frame = struct { kind: u8, elem_start: usize = 0, end_pos: usize = 0, }; /// Walk the data of one complete type. One loop over the signature with /// an explicit stack of open containers rather than recursive descent, /// so a value costs a switch and not a call; only a variant recurses, /// because its value carries a signature of its own, and the variant /// depth bound is what keeps that recursion finite. The walk enforces /// the signature grammar as strictly as `signatureOne` does, which is /// what lets a variant's signature go unwalked ahead of its value. fn skipOne(self: *Decoder, sig: []const u8, index: *usize, depth: Depth) Error!void { var stack: [3 * Depth.max_container_depth]Frame = undefined; var sp: usize = 0; var array_depth = depth.array; var struct_depth = depth.structure; var dict_depth = depth.dict_entry; outer: while (true) { if (index.* >= sig.len) return error.InvalidSignature; const c = sig[index.*]; index.* += 1; switch (c) { 'y' => _ = try self.byte(), // The specification allows a boolean no value but 0 and 1, // so unlike every other fixed-size type its values are // inspected here rather than left to a later read. 'b' => if (try self.uint32() > 1) return error.InvalidMessage, 'u', 'i', 'h' => _ = try self.uint32(), 'n', 'q' => { try self.alignment(2); _ = try self.take(2); }, 'x', 't', 'd' => { try self.alignment(8); _ = try self.take(8); }, 's' => _ = try self.string(), 'o' => _ = try self.objectPath(), 'g' => _ = try self.signature(), 'v' => { // On failure the signature is checked after all, so a // malformed one is reported as that and not as whatever // the walk tripped over first. const inner = try self.signatureData(); const inner_depth = try depth.enterVariant(array_depth + struct_depth + dict_depth); self.skipSignatureValueAtDepth(inner, inner_depth) catch |err| { return if (!validSignature(inner, false)) error.InvalidSignature else err; }; }, 'a' => { array_depth += 1; if (array_depth > Depth.max_container_depth) return error.InvalidSignature; if (depth.variant + array_depth + struct_depth + dict_depth > Depth.max_message_depth) return error.InvalidMessage; if (index.* >= sig.len) return error.InvalidSignature; const alignment_value = typeAlignment(sig[index.*]) orelse return error.InvalidSignature; const end_pos = try self.beginArrayAligned(alignment_value); switch (sig[index.*]) { // A fixed-size element is as large as its alignment, // so the elements sit back to back with no padding // and the whole array is skipped in one step, // provided the length divides evenly. Walking it // element by element proves nothing more and costs a // bounds check per element, which for `ay` is one // per byte. 'y', 'n', 'q', 'i', 'u', 'x', 't', 'd', 'h' => { if ((end_pos - self.position) % alignment_value != 0) return error.InvalidMessage; self.position = end_pos; index.* += 1; array_depth -= 1; }, // Booleans are the one fixed-size type whose values // the walk must inspect, so their arrays loop. 'b' => { index.* += 1; while (self.position < end_pos) { if (try self.uint32() > 1) return error.InvalidMessage; } if (self.position != end_pos) return error.InvalidMessage; array_depth -= 1; }, // The string-like elements are single characters // too, so their arrays loop right here with no frame // to keep; these are the common `as`, `ao`, and `ag` // shapes. Running past the end is a length that lied // about where its elements stop. 's' => { index.* += 1; while (self.position < end_pos) _ = try self.string(); if (self.position != end_pos) return error.InvalidMessage; array_depth -= 1; }, 'o' => { index.* += 1; while (self.position < end_pos) _ = try self.objectPath(); if (self.position != end_pos) return error.InvalidMessage; array_depth -= 1; }, 'g' => { index.* += 1; while (self.position < end_pos) _ = try self.signature(); if (self.position != end_pos) return error.InvalidMessage; array_depth -= 1; }, else => if (self.position == end_pos) { // Empty, so the element type exists only in the // signature and is stepped over there. try signatureOne(sig, index, .{ .array = array_depth, .structure = struct_depth, .dict_entry = dict_depth, }, true); array_depth -= 1; } else { stack[sp] = .{ .kind = 'a', .elem_start = index.*, .end_pos = end_pos }; sp += 1; continue :outer; }, } }, '(' => { struct_depth += 1; if (struct_depth > Depth.max_container_depth) return error.InvalidSignature; if (depth.variant + array_depth + struct_depth + dict_depth > Depth.max_message_depth) return error.InvalidMessage; try self.structAlignment(); stack[sp] = .{ .kind = '(' }; sp += 1; continue :outer; }, ')' => { // Only a struct with at least one completed field // closes, which keeps this walk as strict as // `signatureOne` for a signature nothing has validated, // such as a variant's. if (sp == 0 or stack[sp - 1].kind != 'P') return error.InvalidSignature; sp -= 1; struct_depth -= 1; }, '{' => { // A dict entry is only an array's element, and its key // must be a basic type; the key's value is what the // next pass of this loop consumes. if (sp == 0 or stack[sp - 1].kind != 'a') return error.InvalidSignature; dict_depth += 1; if (dict_depth > Depth.max_container_depth) return error.InvalidSignature; if (depth.variant + array_depth + struct_depth + dict_depth > Depth.max_message_depth) return error.InvalidMessage; try self.structAlignment(); if (index.* >= sig.len or !basicType(sig[index.*])) return error.InvalidSignature; stack[sp] = .{ .kind = 'K' }; sp += 1; continue :outer; }, else => return error.InvalidSignature, } // A complete value has been consumed; close everything it // completes in turn. while (sp > 0) { const top = &stack[sp - 1]; switch (top.kind) { 'a' => { if (self.position > top.end_pos) return error.InvalidMessage; if (self.position < top.end_pos) { index.* = top.elem_start; continue :outer; } sp -= 1; array_depth -= 1; }, '(' => { top.kind = 'P'; continue :outer; }, 'P' => continue :outer, 'K' => { top.kind = 'D'; continue :outer; }, 'D' => { if (index.* >= sig.len or sig[index.*] != '}') return error.InvalidSignature; index.* += 1; sp -= 1; dict_depth -= 1; }, else => unreachable, } } return; } }};
/// Read one fixed-size integer from `data`, in the byte order the message/// declared in its header.////// `T` names the wire type being read, and what makes a type acceptable is/// checked here rather than trusted at each call: the protocol stores a byte/// order only for its 16-, 32-, and 64-bit integers, signed and unsigned/// alike.fn readInt(comptime T: type, data: []const u8, endian: std.builtin.Endian) T { comptime { const info = @typeInfo(T); if (info != .int) @compileError( "readInt reads an integer, not " ++ @typeName(T), ); if (info.int.bits != 16 and info.int.bits != 32 and info.int.bits != 64) @compileError(std.fmt.comptimePrint( "readInt reads 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 read by `byte`", .{info.int.bits}, )); } // Callers pass a slice they have already bounds-checked, either a fixed // slice of the header or what `Decoder.take` returned, so a length that // does not match is a bug here and not a malformed message. std.debug.assert(data.len == @sizeOf(T)); return std.mem.readInt(T, data[0..@sizeOf(T)], endian);}fn alignForward(value: usize, a: usize) !usize { return std.math.add(usize, value, (a - value % a) % a);}/// Read a header field that must be a well-formed name. Every name grammar/// is ASCII with no NUL, so the name check subsumes the text check an/// ordinary string gets and the value is walked once, the way an object/// path is.fn headerName(d: *Decoder, comptime valid: fn ([]const u8) bool) Error![]const u8 { const value = try d.stringData(); if (!valid(value)) return error.InvalidName; return value;}
fn requireHeaderSig(got: []const u8, wanted: []const u8) Error!void { if (std.mem.eql(u8, got, wanted)) return; // The field's signature was read without a walk, so the distinction the // two errors draw is settled here, on the mismatch path only: a wrong // field type is only that if the signature is well formed at all. if (!validSignature(got, false)) return error.InvalidSignature; return error.WrongHeaderFieldType;}