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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What must be true of everything the server writes, whatever it was sent.//!//! The HTTP/1.1 oracle in `tests/fuzz.zig` has to carve out exceptions —//! HTTP/1.1 framing is not self-describing, so a reader has to be told what a//! body means before it can find the end of it. HTTP/2's is: every octet on//! the connection belongs to a frame whose length is written on the front of//! it. So this walker is strictly stronger, and it can say the thing that//! matters most://!//! **Every field block is contiguous and complete.** HPACK state is shared by//! every stream on the connection, so a header block that is interrupted by//! another frame, or that simply stops, leaves the peer's decoder permanently//! out of step — and every *subsequent* block on that connection then decodes//! to something the server never sent. That is HTTP/2's request smuggling,//! and it is a property of the octets alone, which is why it belongs here and//! not in a test.//!//! Imports nothing from `http`, so that a frame reader bug cannot cancel out//! a frame writer bug.
const std = @import("std");const Allocator = std.mem.Allocator;
const frames = @import("frames.zig");const Type = frames.Type;const Flags = frames.Flags;
pub const Frame = struct { kind: u8, flags: u8, stream_id: u31, payload: []const u8,
pub fn has(f: Frame, flag: u8) bool { return f.flags & flag != 0; }};
pub const ParseError = error{ /// The connection ended inside a frame header or a frame payload. A /// server that closes here has written something no client can read. Truncated,} || Allocator.Error;
/// Every frame in what the server wrote, in order.pub fn parse(gpa: Allocator, bytes: []const u8) ParseError![]Frame { var out: std.ArrayList(Frame) = .empty; errdefer out.deinit(gpa);
var at: usize = 0; while (at < bytes.len) { if (bytes.len - at < 9) return error.Truncated; const length = (@as(usize, bytes[at]) << 16) | (@as(usize, bytes[at + 1]) << 8) | @as(usize, bytes[at + 2]); const kind = bytes[at + 3]; const flags = bytes[at + 4]; // The high bit of the identifier is reserved and §4.1 says a reader // must ignore it, so it is masked off rather than checked. const stream_id: u31 = @truncate(std.mem.readInt(u32, bytes[at + 5 ..][0..4], .big)); at += 9; if (bytes.len - at < length) return error.Truncated; try out.append(gpa, .{ .kind = kind, .flags = flags, .stream_id = stream_id, .payload = bytes[at..][0..length], }); at += length; } return out.toOwnedSlice(gpa);}
pub const Limits = struct { /// What the client told the server with `SETTINGS_MAX_FRAME_SIZE`, or the /// §6.5.2 default when it said nothing. max_frame_size: usize = 16384,};
pub const Violation = error{ FirstFrameIsNotSettings, FrameTooLarge, /// A frame that must be on the connection arrived on a stream, or the /// other way round (§6). WrongStream, /// The server opened a stream, which it may only do by pushing — and push /// is switched off in every configuration this library ships. ServerInitiatedStream, /// A field block interrupted by another frame, or one that never ended. /// The dangerous one; see the note at the top of the file. InterruptedFieldBlock, UnterminatedFieldBlock, /// A CONTINUATION that continues nothing. OrphanContinuation, /// Something sent on a stream the server had already finished. FrameAfterEndStream, /// Two RST_STREAM frames for one stream, which says the server lost track /// of it. DoubleReset, /// A payload whose length the frame type fixes (§6.4, §6.7, §6.8, §6.9). BadPayloadLength,};
/// Walks the frames and returns the first rule broken, or null.////// Returning the rule rather than asserting is what lets the fuzz driver/// print the whole conversation beside the name of what was wrong with it.pub fn check(list: []const Frame, limits: Limits) ?Violation { if (list.len == 0) return null; if (list[0].kind != Type.settings or list[0].stream_id != 0 or list[0].has(Flags.ack)) { // §3.4: the server's connection preface is a SETTINGS frame, and it // is the first thing it sends. return error.FirstFrameIsNotSettings; }
// A field block in progress: the stream it belongs to, or null. var block_on: ?u31 = null; // Streams the server has finished with, and streams it has reset. var ended: Seen = .{}; var reset: Seen = .{};
for (list) |f| { if (f.payload.len > limits.max_frame_size) return error.FrameTooLarge;
// §6.10: nothing may come between a HEADERS and the CONTINUATION // frames that finish it, not even a frame for another stream. if (block_on) |id| { if (f.kind != Type.continuation or f.stream_id != id) { return error.InterruptedFieldBlock; } if (f.has(Flags.end_headers)) block_on = null; continue; } if (f.kind == Type.continuation) return error.OrphanContinuation;
switch (f.kind) { Type.settings, Type.ping, Type.goaway => { if (f.stream_id != 0) return error.WrongStream; }, Type.data, Type.headers, Type.rst_stream => { if (f.stream_id == 0) return error.WrongStream; // Every identifier a client opens is odd (§5.1.1), so an even // one here is a stream the server opened itself. if (f.stream_id % 2 == 0) return error.ServerInitiatedStream; if (ended.has(f.stream_id) and f.kind != Type.rst_stream) { return error.FrameAfterEndStream; } }, Type.window_update => {}, else => {}, }
switch (f.kind) { Type.rst_stream, Type.window_update => { if (f.payload.len != 4) return error.BadPayloadLength; }, Type.ping => if (f.payload.len != 8) return error.BadPayloadLength, Type.goaway => if (f.payload.len < 8) return error.BadPayloadLength, Type.priority => if (f.payload.len != 5) return error.BadPayloadLength, Type.settings => if (f.payload.len % 6 != 0) return error.BadPayloadLength, else => {}, }
if (f.kind == Type.headers and !f.has(Flags.end_headers)) block_on = f.stream_id;
if (f.kind == Type.rst_stream) { if (reset.has(f.stream_id)) return error.DoubleReset; reset.add(f.stream_id); } if ((f.kind == Type.headers or f.kind == Type.data) and f.has(Flags.end_stream)) { ended.add(f.stream_id); } }
if (block_on != null) return error.UnterminatedFieldBlock; return null;}
/// The handful of stream identifiers a conversation in a test touches./// Linear and fixed, because `check` takes no allocator and a hash map here/// would be harder to read than the rules it exists to serve.const Seen = struct { ids: [256]u31 = undefined, len: usize = 0,
fn has(s: *const Seen, id: u31) bool { return std.mem.findScalar(u31, s.ids[0..s.len], id) != null; }
fn add(s: *Seen, id: u31) void { if (s.len == s.ids.len) return; s.ids[s.len] = id; s.len += 1; }};
/// The conversation as something a person can read, one line per frame.////// Header blocks print as their compressed octets here, because decompressing/// them needs the connection's HPACK state and this file has none. What holds/// the decoded view is `Conversation.dump` in `tests/h2.zig`, which has a/// decoder; this is what the fuzz driver has when a conversation has gone/// wrong enough that there may be no decoding it.pub fn dump(list: []const Frame, w: *std.Io.Writer) !void { for (list, 0..) |f, i| { try w.print("{d:>3} {s:<14} stream {d:<3} flags 0x{x:0>2}{s} len {d}", .{ i, typeName(f.kind), f.stream_id, f.flags, flagNames(f.kind, f.flags), f.payload.len, }); switch (f.kind) { Type.rst_stream => if (f.payload.len == 4) try w.print(" {s}", .{ errorName(std.mem.readInt(u32, f.payload[0..4], .big)), }), Type.goaway => if (f.payload.len >= 8) try w.print(" last {d} {s} {s}", .{ std.mem.readInt(u32, f.payload[0..4], .big), errorName(std.mem.readInt(u32, f.payload[4..8], .big)), f.payload[8..], }), Type.window_update => if (f.payload.len == 4) try w.print(" +{d}", .{ std.mem.readInt(u32, f.payload[0..4], .big), }), Type.settings => { var at: usize = 0; while (at + 6 <= f.payload.len) : (at += 6) { try w.print(" {s}={d}", .{ settingName(std.mem.readInt(u16, f.payload[at..][0..2], .big)), std.mem.readInt(u32, f.payload[at + 2 ..][0..4], .big), }); } }, Type.data => try w.print(" {f}", .{Preview{ .bytes = f.payload }}), else => {}, } try w.writeByte('\n'); }}
/// At most forty octets of a payload, printable ones as themselves.const Preview = struct { bytes: []const u8,
pub fn format(p: Preview, w: *std.Io.Writer) !void { const shown = @min(p.bytes.len, 40); try w.writeByte('"'); for (p.bytes[0..shown]) |c| { if (std.ascii.isPrint(c)) try w.writeByte(c) else try w.print("\\x{x:0>2}", .{c}); } try w.writeByte('"'); if (shown < p.bytes.len) try w.print("...+{d}", .{p.bytes.len - shown}); }};
pub fn typeName(kind: u8) []const u8 { return switch (kind) { Type.data => "DATA", Type.headers => "HEADERS", Type.priority => "PRIORITY", Type.rst_stream => "RST_STREAM", Type.settings => "SETTINGS", Type.push_promise => "PUSH_PROMISE", Type.ping => "PING", Type.goaway => "GOAWAY", Type.window_update => "WINDOW_UPDATE", Type.continuation => "CONTINUATION", else => "unknown", };}
fn flagNames(kind: u8, flags: u8) []const u8 { // Only the combinations a server actually sends, because this is a // debugging aid and a table of all 256 would not help anybody. if (kind == Type.settings or kind == Type.ping) { return if (flags & Flags.ack != 0) " ACK" else ""; } if (kind == Type.headers) { return switch (flags & (Flags.end_stream | Flags.end_headers)) { Flags.end_stream | Flags.end_headers => " END_STREAM|END_HEADERS", Flags.end_headers => " END_HEADERS", Flags.end_stream => " END_STREAM", else => "", }; } if (kind == Type.continuation) { return if (flags & Flags.end_headers != 0) " END_HEADERS" else ""; } if (kind == Type.data) { return if (flags & Flags.end_stream != 0) " END_STREAM" else ""; } return "";}
pub fn errorName(code: u32) []const u8 { return switch (code) { 0x0 => "NO_ERROR", 0x1 => "PROTOCOL_ERROR", 0x2 => "INTERNAL_ERROR", 0x3 => "FLOW_CONTROL_ERROR", 0x4 => "SETTINGS_TIMEOUT", 0x5 => "STREAM_CLOSED", 0x6 => "FRAME_SIZE_ERROR", 0x7 => "REFUSED_STREAM", 0x8 => "CANCEL", 0x9 => "COMPRESSION_ERROR", 0xa => "CONNECT_ERROR", 0xb => "ENHANCE_YOUR_CALM", 0xc => "INADEQUATE_SECURITY", 0xd => "HTTP_1_1_REQUIRED", else => "unknown", };}
fn settingName(id: u16) []const u8 { return switch (id) { 0x1 => "HEADER_TABLE_SIZE", 0x2 => "ENABLE_PUSH", 0x3 => "MAX_CONCURRENT_STREAMS", 0x4 => "INITIAL_WINDOW_SIZE", 0x5 => "MAX_FRAME_SIZE", 0x6 => "MAX_HEADER_LIST_SIZE", else => "unknown", };}
const testing = std.testing;
test "a truncated frame is not a frame" { const gpa = testing.allocator; try testing.expectError(error.Truncated, parse(gpa, &.{ 0, 0, 4, 0x8, 0, 0, 0, 0, 0, 1, 2 })); try testing.expectError(error.Truncated, parse(gpa, &.{ 0, 0 }));}
test "the walker finds an interrupted field block" { const gpa = testing.allocator; var b: frames.Builder = .init(gpa); defer b.deinit(); try b.settings(&.{}); // END_HEADERS clear, and then something that is not a CONTINUATION. try b.headersRaw(1, 0, ""); try b.data(1, 0, "x");
const list = try parse(gpa, b.written()); defer gpa.free(list); try testing.expectEqual(@as(?Violation, error.InterruptedFieldBlock), check(list, .{}));}
test "the walker finds a field block that never ends" { const gpa = testing.allocator; var b: frames.Builder = .init(gpa); defer b.deinit(); try b.settings(&.{}); try b.headersRaw(1, 0, "");
const list = try parse(gpa, b.written()); defer gpa.free(list); try testing.expectEqual(@as(?Violation, error.UnterminatedFieldBlock), check(list, .{}));}
test "a well formed conversation breaks no rule" { const gpa = testing.allocator; var b: frames.Builder = .init(gpa); defer b.deinit(); try b.settings(&.{}); try b.headers(1, 0, &frames.get("/")); try b.data(1, frames.Flags.end_stream, "hello"); try b.goaway(1, frames.ErrorCode.no_error, "");
const list = try parse(gpa, b.written()); defer gpa.free(list); try testing.expectEqual(@as(?Violation, null), check(list, .{}));}