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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! RFC 9114 §7: HTTP/3's frames, which are much less than HTTP/2's.//!//! A frame is a variable-length type, a variable-length length, and that many//! octets. There is no stream identifier, because a frame arrives on a QUIC//! stream and the stream is the identifier; no flags, because the two that//! HTTP/2 needed are now either QUIC's job or a frame of their own; and no//! fixed nine-octet header, because a varint says what it needs to and stops.//!//! Most of what HTTP/2's frame layer did has moved *down* rather than away.//! Flow control, stream creation, resets, priority and even the connection//! preface all belong to QUIC now, which is why the list of types here is//! short and why four of the entries in HTTP/2's table have no counterpart at//! all.//!//! §7.2.8 is the rule that makes this future-proof and is easy to get//! backwards, because it is the opposite of QUIC's: "frames of unknown types//! MUST be ignored" — an HTTP/3 frame carries its own length, so a reader//! that does not understand one can step over it, where a QUIC frame's length//! is implied by its type and an unknown type means the rest of the packet//! cannot be located at all. The two protocols travel together and disagree//! about this on purpose.
const std = @import("std");const quic = @import("quic");
/// §7.2's frame types, and the reserved ones that are not.pub const Kind = enum(u64) { /// §7.2.1: a message body, or part of one. data = 0x00, /// §7.2.2: a field section, compressed with QPACK. headers = 0x01, /// §7.2.3: give up on a promised push. Parsed and refused, since this /// server promises none. cancel_push = 0x03, /// §7.2.4: the connection's parameters, exactly once, first on the /// control stream. settings = 0x04, /// §7.2.5: a server push. Refused for the same reason HTTP/2's is. push_promise = 0x05, /// §7.2.6: the last request this endpoint will answer. goaway = 0x07, /// §7.2.7: how many pushes the client will allow. max_push_id = 0x0d, _,
/// §11.2.1 reserves the frame types of the form `0x1f * N + 0x21` "to /// exercise the requirement that unknown types be ignored", which is the /// same trick QUIC's transport parameters use and exists for the same /// reason: a rule nothing tests is a rule implementations quietly break. /// /// Nothing here treats them specially -- that is the point. They are /// unknown types and are ignored like any other, and this function exists /// so that a *test* can name one. pub fn isReserved(k: Kind) bool { const v = @backingInt(k); if (v < 0x21) return false; return (v - 0x21) % 0x1f == 0; }
test isReserved { // 0x21, then every 0x1f after it. try std.testing.expect(Kind.isReserved(@fromBackingInt(0x21))); try std.testing.expect(Kind.isReserved(@fromBackingInt(0x21 + 0x1f))); try std.testing.expect(!Kind.isReserved(@fromBackingInt(0x22))); try std.testing.expect(!Kind.headers.isReserved()); }
/// §7.2.8: whether this is one of the frame types HTTP/2 defined and /// HTTP/3 has no counterpart for -- PRIORITY, PING, WINDOW_UPDATE and /// CONTINUATION. Their numbers are reserved so that an implementation /// carried over from HTTP/2 is caught sending one: "their receipt MUST be /// treated as a connection error of type H3_FRAME_UNEXPECTED", on any /// stream. Unlike `isReserved`'s types, these are not merely unknown. pub fn isHttp2Only(k: Kind) bool { return switch (@backingInt(k)) { 0x02, 0x06, 0x08, 0x09 => true, else => false, }; }
test isHttp2Only { // HTTP/2's PING. try std.testing.expect(@as(Kind, @fromBackingInt(0x06)).isHttp2Only()); // A type both define is not one of them, and neither is grease. try std.testing.expect(!Kind.headers.isHttp2Only()); try std.testing.expect(!@as(Kind, @fromBackingInt(0x21)).isHttp2Only()); }
/// §7.2: whether a frame of this type may appear on a request stream. /// /// The table in §7.2 is per stream type rather than per connection, and /// getting it wrong is a connection error either way: a SETTINGS on a /// request stream and a DATA on the control stream are both /// H3_FRAME_UNEXPECTED. pub fn allowedOnRequestStream(k: Kind) bool { return switch (k) { .data, .headers => true, // §7.2.5: "a client MUST NOT send a PUSH_PROMISE frame. A server // MUST treat the receipt of a PUSH_PROMISE frame as a connection // error of type H3_FRAME_UNEXPECTED." This is the server's // question -- it is asked of what a client sent -- so the // direction that may carry one is the direction it never reads. .push_promise => false, .cancel_push, .settings, .goaway, .max_push_id => false, // §9: an unknown type is ignored, which means allowed -- all but // the ones §7.2.8 reserves for having been HTTP/2's. _ => !k.isHttp2Only(), }; }
test allowedOnRequestStream { try std.testing.expect(Kind.headers.allowedOnRequestStream()); try std.testing.expect(Kind.data.allowedOnRequestStream()); try std.testing.expect(!Kind.settings.allowedOnRequestStream()); // §9: a type nobody has defined is stepped over, not refused. try std.testing.expect(@as(Kind, @fromBackingInt(0x21)).allowedOnRequestStream()); // §7.2.8: but one HTTP/2 defined and HTTP/3 dropped is refused. try std.testing.expect(!@as(Kind, @fromBackingInt(0x08)).allowedOnRequestStream()); }
/// §7.2: whether a frame of this type may appear on the control stream. pub fn allowedOnControlStream(k: Kind) bool { return switch (k) { .cancel_push, .settings, .goaway, .max_push_id => true, .data, .headers, .push_promise => false, _ => !k.isHttp2Only(), }; }
test allowedOnControlStream { try std.testing.expect(Kind.settings.allowedOnControlStream()); try std.testing.expect(Kind.goaway.allowedOnControlStream()); try std.testing.expect(!Kind.data.allowedOnControlStream()); try std.testing.expect(@as(Kind, @fromBackingInt(0x21)).allowedOnControlStream()); }};
/// §8.1's error codes, which are QUIC application error codes rather than/// anything HTTP/3 invented a space for.pub const Error = enum(u64) { no_error = 0x0100, general_protocol_error = 0x0101, internal_error = 0x0102, stream_creation_error = 0x0103, closed_critical_stream = 0x0104, frame_unexpected = 0x0105, frame_error = 0x0106, excessive_load = 0x0107, id_error = 0x0108, settings_error = 0x0109, missing_settings = 0x010a, request_rejected = 0x010b, request_cancelled = 0x010c, request_incomplete = 0x010d, message_error = 0x010e, connect_error = 0x010f, version_fallback = 0x0110, /// RFC 9204 §6: QPACK's three, which live in the same space. qpack_decompression_failed = 0x0200, qpack_encoder_stream_error = 0x0201, qpack_decoder_stream_error = 0x0202, _,};
/// §6.2's unidirectional stream types, which are the first varint on any/// unidirectional stream.pub const StreamType = enum(u64) { /// §6.2.1: one per direction, per connection, and it may not close. control = 0x00, /// §4.6: a server push, which this server never opens. push = 0x01, /// RFC 9204 §4.2: where an encoder's table updates travel. qpack_encoder = 0x02, /// RFC 9204 §4.2: where a decoder's acknowledgements travel. qpack_decoder = 0x03, _,};
pub const ParseError = error{ /// The frame header is longer than what has arrived; try again with more. /// A length too large to hold is not an error here, since the header that /// declares one parses: `Header.end` is where it shows, as null. Incomplete,};
pub const Header = struct { kind: Kind, length: u64, /// How many octets the type and length took, which is where the payload /// begins. header_len: usize,
/// One past the last octet of this frame, counted from the start of its /// header: how many octets have to have arrived before the payload is all /// there. Null when a peer declared a length that cannot be held in a /// `usize` at all, which no amount of waiting will satisfy. pub fn end(h: Header) ?usize { const total = std.math.add(u64, h.header_len, h.length) catch return null; return std.math.cast(usize, total); }
test end { // A DATA frame of five octets: a one-octet type and a one-octet length, // so the frame ends seven octets in. const h = try parse(&.{ 0x00, 0x05, 'h', 'e', 'l', 'l', 'o' }); try std.testing.expectEqual(@as(?usize, 7), h.end());
const huge: Header = .{ .kind = .data, .length = std.math.maxInt(u64), .header_len = 9 }; try std.testing.expectEqual(@as(?usize, null), huge.end()); }};
/// Reads a frame header from the front of `bytes`.////// `Incomplete` rather than an error for a partial header, because a frame/// arrives on a stream and a stream delivers what it has: the caller's answer/// is to wait for more, not to close the connection.pub fn parse(bytes: []const u8) ParseError!Header { const kind = quic.varint.parse(bytes) catch return error.Incomplete; const rest = bytes[kind.len..]; const length = quic.varint.parse(rest) catch return error.Incomplete; return .{ .kind = @fromBackingInt(@intCast(kind.value)), .length = length.value, .header_len = kind.len + length.len, };}
test parse { // A HEADERS frame of three octets, of which only the header need have // arrived: the payload is the caller's to wait for. const h = try parse(&.{ 0x01, 0x03 }); try std.testing.expectEqual(Kind.headers, h.kind); try std.testing.expectEqual(@as(u64, 3), h.length); try std.testing.expectEqual(@as(usize, 2), h.header_len);
try std.testing.expectError(error.Incomplete, parse(&.{0x01}));}
/// Writes a frame header to the front of `out`, returning how many octets it/// took. The payload is the caller's to write after it. `NoSpace` when `out`/// cannot hold the header, in which case nothing has been written.pub fn write(out: []u8, kind: Kind, length: u64) error{NoSpace}!usize { const type_len = quic.varint.encodedLen(@backingInt(kind)); const length_len = quic.varint.encodedLen(length); if (out.len < type_len + length_len) return error.NoSpace; var at: usize = 0; at += quic.varint.write(out[at..], @backingInt(kind)).len; at += quic.varint.write(out[at..], length).len; return at;}
test write { var out: [16]u8 = undefined; const n = try write(&out, .data, 5); try std.testing.expectEqualSlices(u8, &.{ 0x00, 0x05 }, out[0..n]);
// A length of 1000 needs a two-octet varint. var small: [2]u8 = undefined; try std.testing.expectError(error.NoSpace, write(&small, .data, 1000));}
pub const SettingsError = error{ /// The payload does not divide into identifier-value pairs: H3_FRAME_ERROR /// by §7.1. Malformed, /// An identifier HTTP/2 defined and HTTP/3 reserved: H3_SETTINGS_ERROR by /// §7.2.4.1. ReservedSetting, /// The stream could not be read. ReadFailed,};
/// What a peer's SETTINGS said that changes what this end may send.pub const Settings = struct { /// §7.2.4.1: SETTINGS_MAX_FIELD_SECTION_SIZE, the largest field section /// the peer will accept, by §4.2.2's arithmetic. Null when the peer did /// not say, which §7.2.4.1 makes unlimited. max_field_section_size: ?u64 = null,};
/// Reads a SETTINGS payload of `length` octets off `r`, checks it, and/// returns what of it constrains this end.////// The encoders here insert into no QPACK table and ask for no extension, so/// the one setting that changes what they send is the peer's limit on a field/// section. The rest of the payload is still a payload, and two of the ways it/// can be wrong are connection errors §7.2.4 names. A stream that ends inside/// the payload is a truncated frame, so `Malformed`.pub fn readSettings(r: *std.Io.Reader, length: u64) SettingsError!Settings { var settings: Settings = .{}; var left = length; var id: u64 = 0; while (left > 0) { inline for (.{ true, false }) |is_id| { if (left == 0) return error.Malformed; const first = r.takeByte() catch |err| return switch (err) { error.EndOfStream => error.Malformed, error.ReadFailed => error.ReadFailed, }; const len = @as(usize, 1) << @intCast(first >> 6); if (len > left) return error.Malformed; var buf: [8]u8 = undefined; buf[0] = first; if (len > 1) r.readSliceAll(buf[1..len]) catch |err| return switch (err) { error.EndOfStream => error.Malformed, error.ReadFailed => error.ReadFailed, }; left -= len; const value = (quic.varint.parse(buf[0..len]) catch return error.Malformed).value; if (is_id) { if (isHttp2Setting(value)) return error.ReservedSetting; id = value; } else if (id == 0x06) { settings.max_field_section_size = value; } } } return settings;}
/// §7.2.4.1: "Setting identifiers that were defined in [HTTP/2] where there is/// no corresponding HTTP/3 setting have also been reserved... Their receipt/// MUST be treated as a connection error of type H3_SETTINGS_ERROR." Those are/// 0x00 and 0x02 through 0x05; 0x01 and 0x06 have HTTP/3 meanings.fn isHttp2Setting(id: u64) bool { return id == 0x00 or (id >= 0x02 and id <= 0x05);}
test readSettings { // SETTINGS_MAX_FIELD_SECTION_SIZE of 16384 (a four-octet varint) and a // grease identifier, which is to be ignored. var ok: std.Io.Reader = .fixed(&.{ 0x06, 0x80, 0x00, 0x40, 0x00, 0x21, 0x00 }); try std.testing.expectEqual(@as(?u64, 16384), (try readSettings(&ok, 7)).max_field_section_size); // No limit said, which is no limit. var silent: std.Io.Reader = .fixed(&.{ 0x01, 0x00 }); try std.testing.expectEqual(@as(?u64, null), (try readSettings(&silent, 2)).max_field_section_size);
// HTTP/2's SETTINGS_ENABLE_PUSH. var reserved: std.Io.Reader = .fixed(&.{ 0x02, 0x00 }); try std.testing.expectError(error.ReservedSetting, readSettings(&reserved, 2));
// An identifier with no value, and a value running past the frame. var odd: std.Io.Reader = .fixed(&.{ 0x06, 0x00, 0x07 }); try std.testing.expectError(error.Malformed, readSettings(&odd, 3)); var over: std.Io.Reader = .fixed(&.{ 0x06, 0x40, 0x10 }); try std.testing.expectError(error.Malformed, readSettings(&over, 2)); // A stream that ends inside the payload. var short: std.Io.Reader = .fixed(&.{0x06}); try std.testing.expectError(error.Malformed, readSettings(&short, 2));}
/// The octets a frame header for this type and length occupies, for a caller/// that has to know before it has somewhere to put it.pub fn headerLen(kind: Kind, length: u64) usize { return quic.varint.encodedLen(@backingInt(kind)) + quic.varint.encodedLen(length);}
test headerLen { try std.testing.expectEqual(@as(usize, 2), headerLen(.data, 60)); try std.testing.expectEqual(@as(usize, 3), headerLen(.data, 1000));
var out: [16]u8 = undefined; try std.testing.expectEqual(headerLen(.settings, 100_000), try write(&out, .settings, 100_000));}
const testing = std.testing;
test "RFC 9114 7.1: a frame is a type, a length, and that many octets" { // "HTTP/3 frames are formatted with a type and a length" -- and nothing // else. No stream identifier, because the stream it arrives on is the // identifier; no flags, because HTTP/2's two are now QUIC's business or a // frame of their own. var out: [16]u8 = undefined; const n = try write(&out, .headers, 1234); const header = try parse(out[0..n]); try testing.expectEqual(Kind.headers, header.kind); try testing.expectEqual(@as(u64, 1234), header.length); try testing.expectEqual(n, header.header_len);}
test "RFC 9114 7.1: the type and the length are both variable length" { // Which is the saving over HTTP/2's fixed nine octets: a DATA frame of // sixty octets costs two here and nine there, and the difference is paid // on every frame of every response. var out: [16]u8 = undefined; try testing.expectEqual(@as(usize, 2), try write(&out, .data, 60)); try testing.expectEqual(@as(usize, 3), try write(&out, .data, 1000)); try testing.expectEqual(@as(usize, 5), try write(&out, .data, 100_000));
// A type is a varint too. The first reserved type, 0x21, is 33 and fits // in one octet like every other type here; the reserved series runs on // past 63, and those cost more -- which is the case worth having, since a // reader that assumed one octet would find the frame where the length is. try testing.expectEqual(@as(usize, 2), headerLen(@fromBackingInt(@intCast(0x21)), 0)); try testing.expect(Kind.isReserved(@fromBackingInt(@intCast(0x1f * 100 + 0x21)))); try testing.expectEqual(@as(usize, 3), headerLen(@fromBackingInt(@intCast(0x1f * 100 + 0x21)), 0));}
test "RFC 9114 7.2.8: an unknown frame type is ignored, not refused" { // The opposite of QUIC's rule, and on purpose. §7.2.8: "frames of unknown // types MUST be ignored" -- an HTTP/3 frame carries its own length, so a // reader that does not understand one can step over it. A QUIC frame's // length is implied by its type, so an unknown type there means the rest // of the packet cannot be located at all and §12.4 makes it a connection // error. The two protocols travel together and disagree about this. var out: [16]u8 = undefined; const n = try write(&out, @fromBackingInt(@intCast(0x21)), 3); const header = try parse(out[0..n]); try testing.expectEqual(@as(u64, 0x21), @backingInt(header.kind)); try testing.expectEqual(@as(usize, 3), header.end().? - header.header_len); try testing.expect(header.kind.allowedOnRequestStream()); try testing.expect(header.kind.allowedOnControlStream());}
test "RFC 9114 11.2.1: the reserved types are the ones that exercise the rule" { // "Frame types of the format 0x1f * N + 0x21 are reserved to exercise the // requirement that unknown types be ignored." Nothing treats them // specially, which is the point -- this is only so a test can name one. try testing.expect(Kind.isReserved(@fromBackingInt(@intCast(0x21)))); try testing.expect(Kind.isReserved(@fromBackingInt(@intCast(0x40)))); try testing.expect(Kind.isReserved(@fromBackingInt(@intCast(0x5f)))); try testing.expect(!Kind.isReserved(.data)); try testing.expect(!Kind.isReserved(.headers)); try testing.expect(!Kind.isReserved(@fromBackingInt(@intCast(0x22))));}
test "RFC 9114 7.2: which frames belong on which stream" { // The table is per stream type, and both halves of getting it wrong are // H3_FRAME_UNEXPECTED: a DATA on the control stream and a SETTINGS on a // request stream are the same kind of error. try testing.expect(Kind.data.allowedOnRequestStream()); try testing.expect(Kind.headers.allowedOnRequestStream()); try testing.expect(!Kind.settings.allowedOnRequestStream()); try testing.expect(!Kind.goaway.allowedOnRequestStream());
try testing.expect(Kind.settings.allowedOnControlStream()); try testing.expect(Kind.goaway.allowedOnControlStream()); try testing.expect(!Kind.data.allowedOnControlStream()); try testing.expect(!Kind.headers.allowedOnControlStream());}
test "a header that has not all arrived is incomplete rather than wrong" { // A frame arrives on a stream and a stream delivers what it has, so the // answer to half a length is to wait rather than to close the connection. var out: [16]u8 = undefined; const n = try write(&out, .data, 100_000); try testing.expectError(error.Incomplete, parse(out[0 .. n - 1])); try testing.expectError(error.Incomplete, parse(out[0..1])); try testing.expectError(error.Incomplete, parse(&.{}));}