Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! HTTP/2 frames: RFC 9113 §4 and §6.//!//! Pure over slices. Nothing here touches a connection except `Header.read`//! and the handful of writers at the bottom, which is what lets the whole//! frame layer be fuzzed on a string.//!//! The centre of the file is `checkHeader`: every rule RFC 9113 states about//! a frame that depends on nothing but its nine header octets and the agreed//! maximum frame size, in one table-shaped function. What is left over for//! the driver is exactly the stateful rules — a CONTINUATION that does not//! follow a header block, a DATA on a half-closed stream — and the line//! between the two is "does deciding need more than those nine octets".
const std = @import("std");const Io = std.Io;
const Writer = Io.Writer;
/// RFC 9113 §4.1. Nine octets, and every possible nine octets is a valid/// one — there is no bit pattern here that is an error, which is why `parse`/// cannot fail. Everything that can be wrong about a frame is wrong about its/// length, its type and its stream identifier *together*, and that is/// `checkHeader`.pub const header_len = 9;
pub const Header = struct { length: u24, /// Non-exhaustive: §4.1 requires a frame of an unknown type to be /// discarded rather than refused, so an unknown type has to be a value /// this can hold. type: Type, /// Raw. The named bits are read through the per-type views below, which /// is how §4.1's "flags that have no defined semantics ... MUST be /// ignored" becomes the default rather than a rule to remember. flags: u8, /// The reserved bit above this is masked off and deliberately not /// checked: §4.1 says it "MUST be ignored when receiving", and an /// implementation that refused a frame carrying it would be refusing a /// frame the RFC says to accept. stream_id: u31,
/// Decodes nine octets already in hand. It cannot fail: an unknown type /// is a value `Type` can hold, and the reserved bit is dropped. pub fn parse(bytes: *const [header_len]u8) Header { return .{ .length = std.mem.readInt(u24, bytes[0..3], .big), .type = @fromBackingInt(@intCast(bytes[3])), .flags = bytes[4], .stream_id = @truncate(std.mem.readInt(u32, bytes[5..9], .big)), }; }
test parse { // A PING header on stream zero, eight octets of payload to follow. const h: Header = .parse(&.{ 0x00, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 }); try testing.expectEqual(@as(u24, 8), h.length); try testing.expectEqual(Type.ping, h.type); try testing.expectEqual(@as(u31, 0), h.stream_id); }
/// Encodes the header into nine octets the caller owns, with the reserved /// bit clear, as §4.1 requires of a sender. pub fn write(h: Header, bytes: *[header_len]u8) void { std.mem.writeInt(u24, bytes[0..3], h.length, .big); bytes[3] = @backingInt(h.type); bytes[4] = h.flags; std.mem.writeInt(u32, bytes[5..9], h.stream_id, .big); }
test write { const h: Header = .{ .length = 4, .type = .window_update, .flags = 0, .stream_id = 3 }; var bytes: [header_len]u8 = undefined; h.write(&bytes); try testing.expectEqualSlices(u8, &.{ 0x00, 0x00, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03 }, &bytes); }
/// Reads one off a connection, however few octets at a time it delivers. /// /// `error.EndOfStream` here is a peer that closed at a frame boundary, /// which is not by itself an error — it is what a connection ending looks /// like. pub fn read(in: *Io.Reader) Io.Reader.Error!Header { return .parse(try in.takeArray(header_len)); }
test read { var in: Io.Reader = .fixed(&.{ 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00 }); const h = try Header.read(&in); try testing.expectEqual(Type.settings, h.type); try testing.expect(AckFlags.from(h.flags).ack); // Nothing more: the next read is the connection ending cleanly. try testing.expectError(error.EndOfStream, Header.read(&in)); }
/// `write`, onto a connection's writer. Only the header: the payload is /// the caller's to write after it. Nothing is flushed. pub fn writeTo(h: Header, out: *Writer) Writer.Error!void { var bytes: [header_len]u8 = undefined; h.write(&bytes); try out.writeAll(&bytes); }
test writeTo { var buffer: [header_len]u8 = undefined; var out: Writer = .fixed(&buffer); try (Header{ .length = 0, .type = .settings, .flags = 0x01, .stream_id = 0 }).writeTo(&out); try testing.expectEqualSlices(u8, &.{ 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00 }, out.buffered()); }};
pub const Type = enum(u8) { data = 0x00, headers = 0x01, priority = 0x02, rst_stream = 0x03, settings = 0x04, push_promise = 0x05, ping = 0x06, goaway = 0x07, window_update = 0x08, continuation = 0x09, _,
/// The name for a log, or null for a type from the registry this does not /// implement — which is not an error, only something to discard. pub fn name(t: Type) ?[]const u8 { return switch (t) { .data => "DATA", .headers => "HEADERS", .priority => "PRIORITY", .rst_stream => "RST_STREAM", .settings => "SETTINGS", .push_promise => "PUSH_PROMISE", .ping => "PING", .goaway => "GOAWAY", .window_update => "WINDOW_UPDATE", .continuation => "CONTINUATION", _ => null, }; }
test name { try testing.expectEqualStrings("WINDOW_UPDATE", Type.window_update.name().?); // 0x0c is ORIGIN in the registry, which this does not implement. try testing.expect(@as(Type, @fromBackingInt(0x0c)).name() == null); }
/// Whether a frame of this type carries a field block fragment. pub fn carriesFieldBlock(t: Type) bool { return t == .headers or t == .continuation or t == .push_promise; }
test carriesFieldBlock { try testing.expect(Type.headers.carriesFieldBlock()); try testing.expect(Type.continuation.carriesFieldBlock()); try testing.expect(!Type.data.carriesFieldBlock()); }};
/// DATA's flags (§6.1). The unnamed fields are the bits §4.1 requires a/// receiver to ignore, and making them padding rather than named fields is/// what makes ignoring them the only thing this type can do.pub const DataFlags = packed struct(u8) { end_stream: bool = false, // 0x01 _unused_1: u2 = 0, padded: bool = false, // 0x08 _unused_2: u4 = 0,
/// Views a header's raw flags octet. Bits this type does not name are /// carried but never read. pub fn from(raw: u8) DataFlags { return @bitCast(raw); }
test from { const f: DataFlags = .from(0x01); try testing.expect(f.end_stream); try testing.expect(!f.padded); }
/// The raw octet for a header's `flags`. Built from named fields, it /// carries only the bits this type defines. pub fn toInt(f: DataFlags) u8 { return @bitCast(f); }
test toInt { try testing.expectEqual(@as(u8, 0x09), (DataFlags{ .end_stream = true, .padded = true }).toInt()); }};
pub const HeadersFlags = packed struct(u8) { end_stream: bool = false, // 0x01 _unused_1: u1 = 0, end_headers: bool = false, // 0x04 padded: bool = false, // 0x08 _unused_2: u1 = 0, priority: bool = false, // 0x20 _unused_3: u2 = 0,
/// Views a header's raw flags octet. Bits this type does not name are /// carried but never read. pub fn from(raw: u8) HeadersFlags { return @bitCast(raw); }
test from { const f: HeadersFlags = .from(0x05); try testing.expect(f.end_stream); try testing.expect(f.end_headers); try testing.expect(!f.priority); }
/// The raw octet for a header's `flags`. Built from named fields, it /// carries only the bits this type defines. pub fn toInt(f: HeadersFlags) u8 { return @bitCast(f); }
test toInt { try testing.expectEqual(@as(u8, 0x04), (HeadersFlags{ .end_headers = true }).toInt()); }};
/// SETTINGS and PING share a shape: one ACK bit and nothing else.pub const AckFlags = packed struct(u8) { ack: bool = false, // 0x01 _unused: u7 = 0,
/// Views a header's raw flags octet. Bits this type does not name are /// carried but never read. pub fn from(raw: u8) AckFlags { return @bitCast(raw); }
test from { const f: AckFlags = .from(0x01); try testing.expect(f.ack); }
/// The raw octet for a header's `flags`. Built from named fields, it /// carries only the bits this type defines. pub fn toInt(f: AckFlags) u8 { return @bitCast(f); }
test toInt { try testing.expectEqual(@as(u8, 0x01), (AckFlags{ .ack = true }).toInt()); }};
pub const ContinuationFlags = packed struct(u8) { _unused_1: u2 = 0, end_headers: bool = false, // 0x04 _unused_2: u5 = 0,
/// Views a header's raw flags octet. Bits this type does not name are /// carried but never read. pub fn from(raw: u8) ContinuationFlags { return @bitCast(raw); }
test from { const f: ContinuationFlags = .from(0xfb); // Every bit but END_HEADERS set, and none of them is END_HEADERS. try testing.expect(!f.end_headers); }
/// The raw octet for a header's `flags`. Built from named fields, it /// carries only the bits this type defines. pub fn toInt(f: ContinuationFlags) u8 { return @bitCast(f); }
test toInt { try testing.expectEqual(@as(u8, 0x04), (ContinuationFlags{ .end_headers = true }).toInt()); }};
/// RFC 9113 §7. Non-exhaustive because §7 says "Unknown or unsupported error/// codes MUST NOT trigger any special behavior", so one has to be/// representable rather than rejected.pub const ErrorCode = enum(u32) { no_error = 0x00, protocol_error = 0x01, internal_error = 0x02, flow_control_error = 0x03, settings_timeout = 0x04, stream_closed = 0x05, frame_size_error = 0x06, refused_stream = 0x07, cancel = 0x08, compression_error = 0x09, connect_error = 0x0a, enhance_your_calm = 0x0b, inadequate_security = 0x0c, http_1_1_required = 0x0d, _,
/// The name §7 gives the code, or null for one this does not know -- /// which a peer may send, and which must not be treated specially. pub fn name(c: ErrorCode) ?[]const u8 { return switch (c) { .no_error => "NO_ERROR", .protocol_error => "PROTOCOL_ERROR", .internal_error => "INTERNAL_ERROR", .flow_control_error => "FLOW_CONTROL_ERROR", .settings_timeout => "SETTINGS_TIMEOUT", .stream_closed => "STREAM_CLOSED", .frame_size_error => "FRAME_SIZE_ERROR", .refused_stream => "REFUSED_STREAM", .cancel => "CANCEL", .compression_error => "COMPRESSION_ERROR", .connect_error => "CONNECT_ERROR", .enhance_your_calm => "ENHANCE_YOUR_CALM", .inadequate_security => "INADEQUATE_SECURITY", .http_1_1_required => "HTTP_1_1_REQUIRED", _ => null, }; }
test name { try testing.expectEqualStrings("ENHANCE_YOUR_CALM", ErrorCode.enhance_your_calm.name().?); try testing.expect(@as(ErrorCode, @fromBackingInt(0x99)).name() == null); }
/// For `{f}`: the §7 name, or the number when there is no name to give. pub fn format(c: ErrorCode, w: *Writer) Writer.Error!void { if (c.name()) |n| return w.writeAll(n); try w.print("unknown error code 0x{x}", .{@backingInt(c)}); }
test format { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); try w.print("{f}; {f}", .{ ErrorCode.refused_stream, @as(ErrorCode, @fromBackingInt(0x99)) }); try testing.expectEqualStrings("REFUSED_STREAM; unknown error code 0x99", w.buffered()); }};
/// What a peer has to be told, and how much goes down with it.pub const Fault = struct { code: ErrorCode, /// RFC 9113 §5.4. A connection error ends everything with a GOAWAY; a /// stream error ends one stream with a RST_STREAM. The distinction is not /// cosmetic — escalating a stream error kills requests that were fine, /// and demoting a connection error leaves the connection in a state /// neither end agrees about. scope: enum { connection, stream },
/// A connection error: answered with GOAWAY. pub fn conn(code: ErrorCode) Fault { return .{ .code = code, .scope = .connection }; }
test conn { const f: Fault = .conn(.protocol_error); try testing.expectEqual(ErrorCode.protocol_error, f.code); try testing.expect(f.scope == .connection); }
/// A stream error: answered with RST_STREAM on the one stream. pub fn strm(code: ErrorCode) Fault { return .{ .code = code, .scope = .stream }; }
test strm { const f: Fault = .strm(.frame_size_error); try testing.expectEqual(ErrorCode.frame_size_error, f.code); try testing.expect(f.scope == .stream); }};
/// Every rule RFC 9113 states about a frame that needs nothing but its header/// and the agreed maximum size. Null when the header is acceptable on its own/// terms.////// `max_frame_size` is the `SETTINGS_MAX_FRAME_SIZE` this end advertised,/// since that is the limit a peer's frames are held to. Both ends use it: a/// PUSH_PROMISE is refused here because a server never receives one (§6.6)/// and this library's client always sends `SETTINGS_ENABLE_PUSH` 0 (§8.4).pub fn checkHeader(h: Header, max_frame_size: u24) ?Fault { // §4.2. Always a connection error here even where the RFC would permit a // stream error, because a frame longer than the agreed maximum has left // the reader unable to say where the next one starts. if (h.length > max_frame_size) return .conn(.frame_size_error);
return switch (h.type) { // §6.1, §6.2: a DATA or HEADERS frame on stream zero is a connection // error of type PROTOCOL_ERROR. .data, .headers => if (h.stream_id == 0) Fault.conn(.protocol_error) else null,
// §6.3. The length rule is one of the few places the RFC *requires* a // stream error rather than merely permitting one, so it may not be // escalated. PRIORITY itself is deprecated: parsed, checked, thrown // away. .priority => if (h.stream_id == 0) Fault.conn(.protocol_error) else if (h.length != 5) Fault.strm(.frame_size_error) else null,
// §6.4. .rst_stream => if (h.stream_id == 0) Fault.conn(.protocol_error) else if (h.length != 4) Fault.conn(.frame_size_error) else null,
// §6.5. The multiple-of-six rule is why a SETTINGS payload never // needs buffering: it is read six octets at a time. .settings => if (h.stream_id != 0) Fault.conn(.protocol_error) else if (AckFlags.from(h.flags).ack and h.length != 0) Fault.conn(.frame_size_error) else if (h.length % 6 != 0) Fault.conn(.frame_size_error) else null,
// §6.6: "A client cannot push, thus servers MUST treat receipt of a // PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR." // A client that sent SETTINGS_ENABLE_PUSH 0, as this library's always // does, has the same rule from §8.4. This is the whole of this // library's support for server push. .push_promise => Fault.conn(.protocol_error),
// §6.7. .ping => if (h.stream_id != 0) Fault.conn(.protocol_error) else if (h.length != 8) Fault.conn(.frame_size_error) else null,
// §6.8. .goaway => if (h.stream_id != 0) Fault.conn(.protocol_error) else if (h.length < 8) Fault.conn(.frame_size_error) else null,
// §6.9. The zero-increment rule is a payload rule and lives in // `parseWindowUpdate`, where the scope depends on the stream too. .window_update => if (h.length != 4) Fault.conn(.frame_size_error) else null,
// §6.10. .continuation => if (h.stream_id == 0) Fault.conn(.protocol_error) else null,
// §4.1: "Implementations MUST discard frames that have unknown or // unsupported types." Not an error — and the length is already // bounded by the check above, so the payload can simply be discarded. _ => null, };}
test checkHeader { const max = 16384; // An ordinary DATA frame passes. try testing.expect(checkHeader(.{ .length = 100, .type = .data, .flags = 0, .stream_id = 1 }, max) == null); // A PING on a stream is refused, and the whole connection goes with it. const fault = checkHeader(.{ .length = 8, .type = .ping, .flags = 0, .stream_id = 1 }, max).?; try testing.expectEqual(ErrorCode.protocol_error, fault.code); try testing.expect(fault.scope == .connection);}
/// How a padded payload divides up (§6.1, §6.2).////// One function with its own tests rather than three lines repeated twice,/// because this arithmetic is historically where padding handling goes wrong.pub const Padding = struct { /// The application data between the Pad Length octet and the padding. data_len: u24, /// The octets of padding after it, which must be discarded and must not /// be counted as data — though they *are* counted against flow control. pad_len: u8,
/// `payload_len` is the whole frame payload, Pad Length octet included. /// /// §6.1: "If the length of the padding is the length of the frame payload /// or greater, the frame MUST be treated as a connection error of type /// PROTOCOL_ERROR." A payload of zero octets with PADDED set has no Pad /// Length octet to read at all, and falls out of the same comparison. pub fn parse(payload_len: u24, pad_len: u8) ParseError!Padding { if (payload_len == 0) return error.Padding; if (pad_len >= payload_len) return error.Padding; return .{ .data_len = @intCast(payload_len - 1 - pad_len), .pad_len = pad_len }; }
test parse { // Ten octets: the Pad Length octet, five of data, four of padding. const p = try Padding.parse(10, 4); try testing.expectEqual(@as(u24, 5), p.data_len); try testing.expectEqual(@as(u8, 4), p.pad_len); try testing.expectError(error.Padding, Padding.parse(10, 10)); }};
pub const ParseError = error{ /// The payload is not the length this frame type requires. `checkHeader` /// catches nearly all of these first; these exist so that a parser handed /// a bad slice directly still refuses it rather than reading past the end. BadLength, /// A field in the payload has a value the RFC forbids: a WINDOW_UPDATE /// increment of zero, a PRIORITY depending on its own stream. Protocol, /// Padding as long as the payload or longer. Padding,};
/// Exhaustive, so a new member of `ParseError` cannot be added without/// somebody deciding what the peer is told about it.pub fn errorCode(err: ParseError) ErrorCode { return switch (err) { error.BadLength => .frame_size_error, error.Protocol, error.Padding => .protocol_error, };}
test errorCode { try testing.expectEqual(ErrorCode.frame_size_error, errorCode(error.BadLength)); try testing.expectEqual(ErrorCode.protocol_error, errorCode(error.Padding));}
/// A RST_STREAM payload (§6.4): the error code, which may be one this does/// not know.pub fn parseRstStream(payload: []const u8) ParseError!ErrorCode { if (payload.len != 4) return error.BadLength; return @fromBackingInt(@intCast(std.mem.readInt(u32, payload[0..4], .big)));}
test parseRstStream { try testing.expectEqual(ErrorCode.cancel, try parseRstStream(&.{ 0, 0, 0, 0x08 })); try testing.expectError(error.BadLength, parseRstStream(&.{ 0, 0, 0x08 }));}
/// A WINDOW_UPDATE payload (§6.9): the increment, with the reserved bit/// dropped. An increment of zero is `error.Protocol`; whether that is a/// stream or a connection error depends on the frame's stream, which only the/// caller has.pub fn parseWindowUpdate(payload: []const u8) ParseError!u31 { if (payload.len != 4) return error.BadLength; const increment: u31 = @truncate(std.mem.readInt(u32, payload[0..4], .big)); // §6.9: "A receiver MUST treat the receipt of a WINDOW_UPDATE frame with // an flow-control window increment of 0 as a stream error"; on stream // zero it is a connection error. The caller knows which. if (increment == 0) return error.Protocol; return increment;}
test parseWindowUpdate { try testing.expectEqual(@as(u31, 65535), try parseWindowUpdate(&.{ 0, 0, 0xff, 0xff })); try testing.expectError(error.Protocol, parseWindowUpdate(&.{ 0, 0, 0, 0 }));}
pub const Priority = struct { exclusive: bool, dependency: u31, weight: u8,};
/// A PRIORITY payload (§6.3), parsed so that it can be checked and thrown/// away: §5.3.2 deprecates the scheme it belongs to. Only the length is/// checked here; a stream depending on itself is the caller's to refuse,/// since only the caller knows which stream the frame arrived on.pub fn parsePriority(payload: []const u8) ParseError!Priority { if (payload.len != 5) return error.BadLength; const word = std.mem.readInt(u32, payload[0..4], .big); return .{ .exclusive = word & 0x8000_0000 != 0, // The reserved bit is masked off and not checked, same rule as a // stream identifier's. .dependency = @truncate(word), .weight = payload[4], };}
test parsePriority { const p = try parsePriority(&.{ 0x80, 0, 0, 0x03, 15 }); try testing.expect(p.exclusive); try testing.expectEqual(@as(u31, 3), p.dependency); try testing.expectEqual(@as(u8, 15), p.weight);}
pub const Goaway = struct { last_stream_id: u31, code: ErrorCode, /// Whatever the peer wanted to say. Never stored, and never trusted. debug: []const u8,};
/// A GOAWAY payload (§6.8). `debug` is a slice of `payload` and lives only/// as long as it does.pub fn parseGoaway(payload: []const u8) ParseError!Goaway { if (payload.len < 8) return error.BadLength; return .{ .last_stream_id = @truncate(std.mem.readInt(u32, payload[0..4], .big)), .code = @fromBackingInt(@intCast(std.mem.readInt(u32, payload[4..8], .big))), .debug = payload[8..], };}
test parseGoaway { const g = try parseGoaway(&.{ 0, 0, 0, 0x05, 0, 0, 0, 0x00 }); try testing.expectEqual(@as(u31, 5), g.last_stream_id); try testing.expectEqual(ErrorCode.no_error, g.code); try testing.expectEqual(@as(usize, 0), g.debug.len);}
// -- writers ----------------------------------------------------------------//// DATA and HEADERS are deliberately not here: writing either means flow// control and fragmenting across CONTINUATION, which is the driver's. It gets// `Header.writeTo` and writes its own payload.
/// A whole RST_STREAM frame, header and payload. Nothing is flushed.pub fn writeRstStream(out: *Writer, stream_id: u31, code: ErrorCode) Writer.Error!void { try (Header{ .length = 4, .type = .rst_stream, .flags = 0, .stream_id = stream_id }).writeTo(out); var payload: [4]u8 = undefined; std.mem.writeInt(u32, &payload, @backingInt(code), .big); try out.writeAll(&payload);}
test writeRstStream { var buffer: [16]u8 = undefined; var out: Writer = .fixed(&buffer); try writeRstStream(&out, 1, .cancel); try testing.expectEqualSlices(u8, &.{ 0, 0, 4, 0x03, 0, 0, 0, 0, 1, // header 0, 0, 0, 0x08, // CANCEL }, out.buffered());}
/// A whole GOAWAY frame on stream zero. `debug` goes out as the additional/// debug data, and has to fit in the peer's maximum frame size less the eight/// octets ahead of it, which is the caller's to ensure. Nothing is flushed.pub fn writeGoaway(out: *Writer, last_stream_id: u31, code: ErrorCode, debug: []const u8) Writer.Error!void { try (Header{ .length = @intCast(8 + debug.len), .type = .goaway, .flags = 0, .stream_id = 0, }).writeTo(out); var payload: [8]u8 = undefined; std.mem.writeInt(u32, payload[0..4], last_stream_id, .big); std.mem.writeInt(u32, payload[4..8], @backingInt(code), .big); try out.writeAll(&payload); try out.writeAll(debug);}
test writeGoaway { var buffer: [32]u8 = undefined; var out: Writer = .fixed(&buffer); try writeGoaway(&out, 7, .no_error, "bye"); try testing.expectEqualSlices(u8, &[_]u8{ 0, 0, 11, 0x07, 0, 0, 0, 0, 0, // header: eight octets and "bye" 0, 0, 0, 7, // last stream 0, 0, 0, 0, // NO_ERROR } ++ "bye", out.buffered());}
/// A PING with ACK set, echoing the eight octets the peer sent (§6.7)./// Nothing is flushed.pub fn writePingAck(out: *Writer, opaque_data: *const [8]u8) Writer.Error!void { try (Header{ .length = 8, .type = .ping, .flags = (AckFlags{ .ack = true }).toInt(), .stream_id = 0, }).writeTo(out); try out.writeAll(opaque_data);}
test writePingAck { var buffer: [32]u8 = undefined; var out: Writer = .fixed(&buffer); try writePingAck(&out, "abcdefgh"); try testing.expectEqualSlices(u8, &.{ 0, 0, 8, 0x06, 0x01, 0, 0, 0, 0 }, out.buffered()[0..header_len]); try testing.expectEqualStrings("abcdefgh", out.buffered()[header_len..]);}
/// A whole WINDOW_UPDATE frame; stream zero is the connection's own window./// An increment of zero is an error for the peer to report (§6.9), so it is/// the caller's to avoid. Nothing is flushed.pub fn writeWindowUpdate(out: *Writer, stream_id: u31, increment: u31) Writer.Error!void { try (Header{ .length = 4, .type = .window_update, .flags = 0, .stream_id = stream_id }).writeTo(out); var payload: [4]u8 = undefined; std.mem.writeInt(u32, &payload, increment, .big); try out.writeAll(&payload);}
test writeWindowUpdate { var buffer: [16]u8 = undefined; var out: Writer = .fixed(&buffer); try writeWindowUpdate(&out, 0, 1024); try testing.expectEqualSlices(u8, &.{ 0, 0, 4, 0x08, 0, 0, 0, 0, 0, // header, on the connection 0, 0, 0x04, 0x00, // 1024 }, out.buffered());}
/// The empty SETTINGS frame with ACK set that §6.5.3 requires in answer to/// each SETTINGS a peer sends. Nothing is flushed.pub fn writeSettingsAck(out: *Writer) Writer.Error!void { try (Header{ .length = 0, .type = .settings, .flags = (AckFlags{ .ack = true }).toInt(), .stream_id = 0, }).writeTo(out);}
test writeSettingsAck { var buffer: [16]u8 = undefined; var out: Writer = .fixed(&buffer); try writeSettingsAck(&out); try testing.expectEqualSlices(u8, &.{ 0, 0, 0, 0x04, 0x01, 0, 0, 0, 0 }, out.buffered());}
const testing = std.testing;
test "a header is nine octets and every nine octets is a header" { const bytes = [_]u8{ 0x00, 0x00, 0x08, 0x06, 0x01, 0x80, 0x00, 0x00, 0x01 }; const h = Header.parse(&bytes); try testing.expectEqual(@as(u24, 8), h.length); try testing.expectEqual(Type.ping, h.type); try testing.expectEqual(@as(u8, 0x01), h.flags); // The reserved bit is masked off rather than refused, and the identifier // survives it. try testing.expectEqual(@as(u31, 1), h.stream_id);
// And it round trips, reserved bit excepted — which is the only thing // `write` cannot put back, because `parse` deliberately dropped it. var out: [header_len]u8 = undefined; h.write(&out); try testing.expectEqualSlices(u8, &.{ 0x00, 0x00, 0x08, 0x06, 0x01, 0x00, 0x00, 0x00, 0x01 }, &out);}
test "flags are read through a view that ignores what it must" { // Every undefined bit set. The named fields are unaffected by them, which // is the whole of what §4.1's "MUST be ignored" asks for -- the unnamed // fields do carry those bits, and nothing ever reads them. const d = DataFlags.from(0xff); try testing.expect(d.end_stream); try testing.expect(d.padded); // And a frame *written* from named fields carries only the defined bits, // because the unnamed ones default to zero. try testing.expectEqual(@as(u8, 0x09), (DataFlags{ .end_stream = true, .padded = true }).toInt()); try testing.expectEqual(@as(u8, 0x00), (DataFlags{}).toInt()); // A frame with none of the defined bits is not mistaken for one that has // them. const none = DataFlags.from(0xf6); try testing.expect(!none.end_stream); try testing.expect(!none.padded);
const h = HeadersFlags.from(0x2d); try testing.expect(h.end_stream); try testing.expect(h.end_headers); try testing.expect(h.padded); try testing.expect(h.priority);
try testing.expect(AckFlags.from(0x01).ack); try testing.expect(ContinuationFlags.from(0x04).end_headers);}
fn header(t: Type, length: u24, flags: u8, stream_id: u31) Header { return .{ .length = length, .type = t, .flags = flags, .stream_id = stream_id };}
test "checkHeader, one RFC rule at a time" { const max = 16384;
// §4.2: longer than the agreed maximum. try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.data, max + 1, 0, 1), max).?.code);
// §6.1, §6.2: DATA and HEADERS need a stream. try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.data, 0, 0, 0), max).?.code); try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.headers, 0, 0, 0), max).?.code); try testing.expect(checkHeader(header(.data, 5, 0, 1), max) == null);
// §6.3: PRIORITY is five octets, and a wrong length is a *stream* error. try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.priority, 5, 0, 0), max).?.code); const priority_len = checkHeader(header(.priority, 4, 0, 1), max).?; try testing.expectEqual(ErrorCode.frame_size_error, priority_len.code); try testing.expectEqual(@as(@TypeOf(priority_len.scope), .stream), priority_len.scope);
// §6.4: RST_STREAM is four octets, and its length error is a connection // error. try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.rst_stream, 4, 0, 0), max).?.code); const rst_len = checkHeader(header(.rst_stream, 5, 0, 1), max).?; try testing.expectEqual(ErrorCode.frame_size_error, rst_len.code); try testing.expectEqual(@as(@TypeOf(rst_len.scope), .connection), rst_len.scope);
// §6.5: SETTINGS lives on stream zero, is a multiple of six, and an ACK // carries nothing. try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.settings, 0, 0, 1), max).?.code); try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.settings, 7, 0, 0), max).?.code); try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.settings, 6, 0x01, 0), max).?.code); try testing.expect(checkHeader(header(.settings, 12, 0, 0), max) == null); try testing.expect(checkHeader(header(.settings, 0, 0x01, 0), max) == null);
// §6.6: a server never receives one. try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.push_promise, 4, 0, 1), max).?.code);
// §6.7, §6.8. try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.ping, 7, 0, 0), max).?.code); try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.ping, 8, 0, 1), max).?.code); try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.goaway, 7, 0, 0), max).?.code); try testing.expect(checkHeader(header(.goaway, 8, 0, 0), max) == null);
// §6.9, §6.10. try testing.expectEqual(ErrorCode.frame_size_error, checkHeader(header(.window_update, 5, 0, 0), max).?.code); try testing.expectEqual(ErrorCode.protocol_error, checkHeader(header(.continuation, 0, 0, 0), max).?.code);
// §4.1: an unknown type is discarded, not refused. try testing.expect(checkHeader(header(@fromBackingInt(@intCast(0x63)), 10, 0xff, 0), max) == null); try testing.expect(checkHeader(header(@fromBackingInt(@intCast(0x63)), 10, 0xff, 7), max) == null);}
test "padding arithmetic, at its boundaries" { // One octet of payload is the Pad Length octet and no data. try testing.expectEqual(@as(u24, 0), (try Padding.parse(1, 0)).data_len); // Padding as long as the payload leaves nowhere for the Pad Length octet. try testing.expectError(error.Padding, Padding.parse(1, 1)); // A payload of nothing has no Pad Length octet to read. try testing.expectError(error.Padding, Padding.parse(0, 0)); // The largest padding that still fits. const p = try Padding.parse(256, 255); try testing.expectEqual(@as(u24, 0), p.data_len); try testing.expectEqual(@as(u8, 255), p.pad_len); // And an ordinary one. const q = try Padding.parse(10, 4); try testing.expectEqual(@as(u24, 5), q.data_len);}
test "payload parsers refuse what they must" { try testing.expectEqual(ErrorCode.cancel, try parseRstStream(&.{ 0, 0, 0, 8 })); try testing.expectError(error.BadLength, parseRstStream(&.{ 0, 0, 8 }));
try testing.expectEqual(@as(u31, 1), try parseWindowUpdate(&.{ 0, 0, 0, 1 })); // The reserved bit is ignored here too. try testing.expectEqual(@as(u31, 1), try parseWindowUpdate(&.{ 0x80, 0, 0, 1 })); try testing.expectError(error.Protocol, parseWindowUpdate(&.{ 0, 0, 0, 0 })); try testing.expectError(error.BadLength, parseWindowUpdate(&.{ 0, 0, 0 }));
const p = try parsePriority(&.{ 0x80, 0, 0, 3, 16 }); try testing.expect(p.exclusive); try testing.expectEqual(@as(u31, 3), p.dependency); try testing.expectEqual(@as(u8, 16), p.weight); try testing.expectError(error.BadLength, parsePriority(&.{ 0, 0, 0, 3 }));
const g = try parseGoaway(&.{ 0, 0, 0, 5, 0, 0, 0, 1, 'w', 'h', 'y' }); try testing.expectEqual(@as(u31, 5), g.last_stream_id); try testing.expectEqual(ErrorCode.protocol_error, g.code); try testing.expectEqualStrings("why", g.debug); try testing.expectError(error.BadLength, parseGoaway(&.{ 0, 0, 0, 5 }));}
test "what the writers write is what the readers read" { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer);
try writeGoaway(&w, 7, .enhance_your_calm, "slow down"); var in: Io.Reader = .fixed(buffer[0..w.end]); const h = try Header.read(&in); try testing.expectEqual(Type.goaway, h.type); try testing.expectEqual(@as(u31, 0), h.stream_id); const g = try parseGoaway(try in.take(h.length)); try testing.expectEqual(@as(u31, 7), g.last_stream_id); try testing.expectEqual(ErrorCode.enhance_your_calm, g.code); try testing.expectEqualStrings("slow down", g.debug);
w = .fixed(&buffer); try writeRstStream(&w, 3, .refused_stream); in = .fixed(buffer[0..w.end]); const rst = try Header.read(&in); try testing.expectEqual(@as(u31, 3), rst.stream_id); try testing.expectEqual(ErrorCode.refused_stream, try parseRstStream(try in.take(rst.length)));
w = .fixed(&buffer); try writePingAck(&w, "12345678"); in = .fixed(buffer[0..w.end]); const ping = try Header.read(&in); try testing.expect(AckFlags.from(ping.flags).ack); try testing.expectEqualStrings("12345678", try in.take(ping.length));
w = .fixed(&buffer); try writeSettingsAck(&w); try testing.expectEqualSlices(u8, &.{ 0, 0, 0, 0x04, 0x01, 0, 0, 0, 0 }, buffer[0..w.end]);}
test "a header read one octet at a time is the same header" { const memory = @import("../transport/memory.zig"); var c: memory.Connection = try .init(testing.allocator, &.{ 0x00, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, }, .{ .chunk = 1 }); defer c.deinit(); const conn = c.connection();
const h = try Header.read(conn.input); try testing.expectEqual(Type.ping, h.type); try testing.expectEqual(@as(u24, 8), h.length);}