// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! OpenPGP packet framing and multiprecision integers, RFC 9580 sections 3.2 //! and 4.2. //! //! Only what reading a transferable secret key and writing a signature need: //! both header formats on the way in, and the current (new-format) header on //! the way out. Partial body lengths are refused, since they appear only in //! streamed data packets and never in keys. const std = @import("std"); const testing = std.testing; pub const Error = error{ /// The bytes end before a header, length or body says they should. Truncated, /// A header that is not a packet header, or a partial body length. MalformedPacket, }; /// Packet tags this program cares about. pub const Tag = enum(u8) { signature = 2, secret_key = 5, public_key = 6, secret_subkey = 7, user_id = 13, public_subkey = 14, _, }; pub const Packet = struct { tag: Tag, body: []const u8, }; /// Walks the packets in a byte string without copying them. pub const Iterator = struct { bytes: []const u8, index: usize = 0, pub fn next(it: *Iterator) Error!?Packet { if (it.index >= it.bytes.len) return null; const rest = it.bytes[it.index..]; const header = rest[0]; if (header & 0x80 == 0) return error.MalformedPacket; var tag: u8 = undefined; var len: usize = undefined; var header_len: usize = undefined; if (header & 0x40 != 0) { tag = header & 0x3f; if (rest.len < 2) return error.Truncated; const o1 = rest[1]; if (o1 < 192) { len = o1; header_len = 2; } else if (o1 < 224) { if (rest.len < 3) return error.Truncated; len = ((@as(usize, o1) - 192) << 8) + rest[2] + 192; header_len = 3; } else if (o1 == 255) { if (rest.len < 6) return error.Truncated; len = std.mem.readInt(u32, rest[2..6], .big); header_len = 6; } else { return error.MalformedPacket; } } else { tag = (header >> 2) & 0x0f; switch (header & 0x03) { 0 => { if (rest.len < 2) return error.Truncated; len = rest[1]; header_len = 2; }, 1 => { if (rest.len < 3) return error.Truncated; len = std.mem.readInt(u16, rest[1..3], .big); header_len = 3; }, 2 => { if (rest.len < 5) return error.Truncated; len = std.mem.readInt(u32, rest[1..5], .big); header_len = 5; }, // Indeterminate: the packet runs to the end of the data. 3 => { len = rest.len - 1; header_len = 1; }, else => unreachable, } } if (rest.len - header_len < len) return error.Truncated; it.index += header_len + len; return .{ .tag = @fromBackingInt(@intCast(tag)), .body = rest[header_len..][0..len] }; } }; /// Reads fields out of a packet body in order. pub const Reader = struct { bytes: []const u8, index: usize = 0, pub fn remaining(r: Reader) []const u8 { return r.bytes[r.index..]; } pub fn atEnd(r: Reader) bool { return r.index >= r.bytes.len; } pub fn take(r: *Reader, n: usize) Error![]const u8 { if (r.bytes.len - r.index < n) return error.Truncated; defer r.index += n; return r.bytes[r.index..][0..n]; } pub fn takeByte(r: *Reader) Error!u8 { return (try r.take(1))[0]; } pub fn takeInt(r: *Reader, comptime T: type) Error!T { return std.mem.readInt(T, (try r.take(@sizeOf(T)))[0..@sizeOf(T)], .big); } /// An MPI: a two-octet bit count and then the big-endian value in /// `ceil(bits / 8)` octets. Returns the value's octets. pub fn takeMpi(r: *Reader) Error![]const u8 { const bits = try r.takeInt(u16); return r.take((@as(usize, bits) + 7) / 8); } }; /// Writes a new-format packet header for a body of `len` octets. pub fn writeHeader(w: *std.Io.Writer, tag: Tag, len: usize) std.Io.Writer.Error!void { try w.writeByte(0xc0 | @backingInt(tag)); if (len < 192) { try w.writeByte(@intCast(len)); } else if (len < 8384) { const v = len - 192; try w.writeByte(@intCast((v >> 8) + 192)); try w.writeByte(@truncate(v)); } else { try w.writeByte(255); try w.writeInt(u32, @intCast(len), .big); } } /// Writes `value` (big-endian, leading zeros allowed) as an MPI, with the /// leading zeros removed and the bit count of what remains. pub fn writeMpi(w: *std.Io.Writer, value: []const u8) std.Io.Writer.Error!void { const v = std.mem.trimStart(u8, value, &.{0}); const bits: u16 = if (v.len == 0) 0 else @intCast((v.len - 1) * 8 + (8 - @clz(v[0]))); try w.writeInt(u16, bits, .big); try w.writeAll(v); } /// The length `writeMpi` will write for `value`. pub fn mpiLength(value: []const u8) usize { return 2 + std.mem.trimStart(u8, value, &.{0}).len; } test "both header formats and every length encoding" { // Old format, one-octet length; new format, one-, two- and five-octet // lengths. var buf: [20000]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try w.writeAll(&.{ 0x99, 0x00, 0x02, 0xaa, 0xbb }); // old format, tag 6, two-octet length try writeHeader(&w, .user_id, 3); try w.writeAll("abc"); try writeHeader(&w, .signature, 300); try w.splatByteAll(1, 300); try writeHeader(&w, .secret_key, 10000); try w.splatByteAll(2, 10000); var it: Iterator = .{ .bytes = w.buffered() }; const p1 = (try it.next()).?; try testing.expectEqual(Tag.public_key, p1.tag); try testing.expectEqualSlices(u8, &.{ 0xaa, 0xbb }, p1.body); const p2 = (try it.next()).?; try testing.expectEqual(Tag.user_id, p2.tag); try testing.expectEqualStrings("abc", p2.body); const p3 = (try it.next()).?; try testing.expectEqual(@as(usize, 300), p3.body.len); const p4 = (try it.next()).?; try testing.expectEqual(@as(usize, 10000), p4.body.len); try testing.expectEqual(@as(?Packet, null), try it.next()); } test "a truncated body or a partial length is refused" { var it: Iterator = .{ .bytes = &.{ 0xc2, 0x05, 0x00 } }; try testing.expectError(error.Truncated, it.next()); var it2: Iterator = .{ .bytes = &.{ 0xcb, 0xe0, 0x00 } }; try testing.expectError(error.MalformedPacket, it2.next()); } test "MPIs count bits from the first set one" { var buf: [16]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeMpi(&w, &.{ 0x00, 0x01, 0xff }); try testing.expectEqualSlices(u8, &.{ 0x00, 0x09, 0x01, 0xff }, w.buffered()); try testing.expectEqual(@as(usize, 4), mpiLength(&.{ 0x00, 0x01, 0xff })); var r: Reader = .{ .bytes = w.buffered() }; try testing.expectEqualSlices(u8, &.{ 0x01, 0xff }, try r.takeMpi()); try testing.expect(r.atEnd()); }