// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The same handler, over HTTP/2. //! //! This is the claim the library is built around, so it gets a test that //! makes it rather than a paragraph that asserts it: the handler in //! `tests/e2e.zig` is *the same function*, and nothing in it knows that the //! opening handshake was RFC 8441's extended CONNECT rather than RFC 6455's //! `Upgrade`, that there was no `Sec-WebSocket-Key` to answer, or that the //! frames arrive inside DATA frames on one stream of a multiplexed //! connection. //! //! The client's half is written by hand below, in about a hundred lines, and //! imports nothing from this library: HTTP/2 frames, the four HPACK literals //! a CONNECT request needs, and WebSocket frames masked the way §5.3 says. //! //! The `Io` is real here and `Io.failing` in the other files, and the reason //! is structural rather than incidental: zig-http's HTTP/2 driver gives every //! stream a task of its own, because a handler reading its own request body //! waits for DATA frames that only the connection's reader task can deliver. //! An `Io` with no concurrency would refuse every stream. const std = @import("std"); const Io = std.Io; const testing = std.testing; const http = @import("http"); const Request = http.server.Request; const Response = http.server.Response; const Handler = http.server.Handler; const ws = @import("websocket"); const wss = @import("websocket_server"); const gpa = testing.allocator; /// The same echo handler `tests/e2e.zig` uses over HTTP/1.1, character for /// character. fn echo(req: *Request, res: *Response) anyerror!void { var buffer: [4096]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } fn chat(req: *Request, res: *Response) anyerror!void { var buffer: [4096]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer, .subprotocols = &.{ "chat.v2", "chat.v1" }, }) catch |err| return wss.refuse(res, err); while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } /// Runs one HTTP/2 connection and hands back what the server wrote. fn converse(client: []const u8, handler: Handler) ![]u8 { var c: http.transport.memory.Connection = try .init(gpa, client, .{}); defer c.deinit(); var conn = c.connection(); try http.http2.serve(testing.io, gpa, &conn, handler, .{ .send_date = false, .server_name = null, }); return gpa.dupe(u8, c.written()); } test "a WebSocket over HTTP/2, through RFC 8441's extended CONNECT" { var b: Client = .init(gpa); defer b.deinit(); try b.begin(); try b.connectRequest(1, "/echo", &.{}); // RFC 6455 §5.7's masked "Hello", carried in a DATA frame. try b.data(1, "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"); // And a Close, so the handler returns rather than waiting. try b.data(1, "\x88\x82\x37\xfa\x21\x3d\x34\x12"); const response = try converse(b.written(), .initStateless(echo)); defer gpa.free(response); var answer: Answer = try .parse(response); defer answer.deinit(); // §5.1 of RFC 8441: a 2xx, not a 101. There is nothing to switch — the // stream becomes the tunnel the moment the status goes out. try testing.expectEqualStrings("200", answer.status.?); // No `Sec-WebSocket-Accept`, because §5 says that exchange is superseded. try testing.expect(answer.field("sec-websocket-accept") == null); // And the octets in the DATA frames are a WebSocket conversation: the // unmasked echo of "Hello", then the echo of the Close. try testing.expectEqualSlices( u8, "\x81\x05Hello" ++ "\x88\x02\x03\xe8", answer.body.items, ); } test "a subprotocol is negotiated over HTTP/2 too" { var b: Client = .init(gpa); defer b.deinit(); try b.begin(); try b.connectRequest(1, "/chat", &.{ .{ .name = "sec-websocket-protocol", .value = "chat.v1" }, }); try b.data(1, "\x88\x80\x00\x00\x00\x00"); const response = try converse(b.written(), .initStateless(chat)); defer gpa.free(response); var answer: Answer = try .parse(response); defer answer.deinit(); try testing.expectEqualStrings("200", answer.status.?); try testing.expectEqualStrings("chat.v1", answer.field("sec-websocket-protocol").?); } test "a stream that does not offer websocket is refused, and the others carry on" { var b: Client = .init(gpa); defer b.deinit(); try b.begin(); // An ordinary GET to a WebSocket route: no `:protocol`, so no offer. try b.getRequest(1, "/echo"); // And beside it, on the same connection, a real one. try b.connectRequest(3, "/echo", &.{}); try b.data(3, "\x88\x80\x00\x00\x00\x00"); const response = try converse(b.written(), .initStateless(echo)); defer gpa.free(response); var first: Answer = try .parse(response); defer first.deinit(); // The refusal is `426 Upgrade Required`, the same answer `ws.refuse` // gives over HTTP/1.1. try testing.expectEqualStrings("426", first.statusOf(1).?); // The tunnel on the other stream was unaffected, which is the thing // HTTP/1.1 cannot do: there, one upgraded connection is the whole socket. try testing.expectEqualStrings("200", first.statusOf(3).?); } // -- the client's half, written by hand ------------------------------------- const Field = struct { name: []const u8, value: []const u8 }; /// Enough of an HTTP/2 client to ask for a tunnel, and no more. const Client = struct { gpa: std.mem.Allocator, bytes: std.ArrayList(u8) = .empty, fn init(allocator: std.mem.Allocator) Client { return .{ .gpa = allocator }; } fn deinit(c: *Client) void { c.bytes.deinit(c.gpa); } fn written(c: *const Client) []const u8 { return c.bytes.items; } /// RFC 9113 §3.4's connection preface, and the SETTINGS frame that must /// follow it. fn begin(c: *Client) !void { try c.bytes.appendSlice(c.gpa, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"); try c.frame(0x4, 0, 0, ""); } fn frame(c: *Client, kind: u8, flags: u8, stream_id: u32, payload: []const u8) !void { var head: [9]u8 = undefined; head[0] = @intCast((payload.len >> 16) & 0xff); head[1] = @intCast((payload.len >> 8) & 0xff); head[2] = @intCast(payload.len & 0xff); head[3] = kind; head[4] = flags; std.mem.writeInt(u32, head[5..9], stream_id, .big); try c.bytes.appendSlice(c.gpa, &head); try c.bytes.appendSlice(c.gpa, payload); } /// RFC 8441 §5.1's request: CONNECT with `:protocol`, and the `:scheme` /// and `:path` that §4 requires beside it. fn connectRequest(c: *Client, stream_id: u32, path: []const u8, extra: []const Field) !void { var fields: std.ArrayList(Field) = .empty; defer fields.deinit(c.gpa); try fields.appendSlice(c.gpa, &.{ .{ .name = ":method", .value = "CONNECT" }, .{ .name = ":protocol", .value = "websocket" }, .{ .name = ":scheme", .value = "http" }, .{ .name = ":authority", .value = "a.example" }, .{ .name = ":path", .value = path }, }); try fields.appendSlice(c.gpa, extra); const block = try encode(c.gpa, fields.items); defer c.gpa.free(block); // END_HEADERS, and deliberately not END_STREAM: the request body is // the tunnel. try c.frame(0x1, 0x4, stream_id, block); } fn getRequest(c: *Client, stream_id: u32, path: []const u8) !void { const block = try encode(c.gpa, &.{ .{ .name = ":method", .value = "GET" }, .{ .name = ":scheme", .value = "http" }, .{ .name = ":authority", .value = "a.example" }, .{ .name = ":path", .value = path }, }); defer c.gpa.free(block); try c.frame(0x1, 0x5, stream_id, block); // END_HEADERS | END_STREAM } fn data(c: *Client, stream_id: u32, payload: []const u8) !void { try c.frame(0x0, 0, stream_id, payload); } }; /// A field block in the one HPACK representation that needs no table: RFC /// 7541 §6.2.2's literal without indexing, with a new name and no Huffman /// coding. Fifteen lines, no state, and checkable by reading it. fn encode(allocator: std.mem.Allocator, fields: []const Field) ![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(allocator); for (fields) |f| { try out.append(allocator, 0x00); try out.append(allocator, @intCast(f.name.len)); try out.appendSlice(allocator, f.name); try out.append(allocator, @intCast(f.value.len)); try out.appendSlice(allocator, f.value); } return out.toOwnedSlice(allocator); } /// What the server wrote, as the response fields of each stream and the /// octets of the tunnel. /// /// The field sections are decoded with zig-http's own HPACK decoder, which is /// legitimate here for the reason its own test suite gives: by the time a /// response is decoded, that decoder has already correctly understood a /// request encoded by `encode` above, which shares no code with it. const Answer = struct { arena: std.heap.ArenaAllocator, /// The last response head, whichever stream it was on. status: ?[]const u8 = null, heads: std.ArrayList(Head) = .empty, /// Every DATA octet, in order. body: std.ArrayList(u8) = .empty, const Head = struct { stream_id: u31, fields: []const http.protocol.Field }; fn parse(bytes: []const u8) !Answer { var a: Answer = .{ .arena = .init(gpa) }; errdefer a.deinit(); const arena = a.arena.allocator(); const scratch = try gpa.alloc(u8, 16 * 1024); defer gpa.free(scratch); var decoder: http.http2.hpack.Decoder = .init(4096, scratch, .{}); defer decoder.deinit(gpa); var at: usize = 0; while (at + 9 <= bytes.len) { const length = (@as(usize, bytes[at]) << 16) | (@as(usize, bytes[at + 1]) << 8) | bytes[at + 2]; const kind = bytes[at + 3]; const stream_id: u31 = @truncate(std.mem.readInt(u32, bytes[at + 5 ..][0..4], .big)); at += 9; if (at + length > bytes.len) return error.TruncatedFrame; const payload = bytes[at..][0..length]; at += length; switch (kind) { 0x0 => try a.body.appendSlice(gpa, payload), 0x1 => { var fields: std.ArrayList(http.protocol.Field) = .empty; try decoder.decode(gpa, arena, payload, &fields); const owned = try fields.toOwnedSlice(arena); try a.heads.append(gpa, .{ .stream_id = stream_id, .fields = owned }); for (owned) |f| { if (std.mem.eql(u8, f.name, ":status")) a.status = f.value; } }, else => {}, } } return a; } fn deinit(a: *Answer) void { a.heads.deinit(gpa); a.body.deinit(gpa); a.arena.deinit(); } fn field(a: *const Answer, name: []const u8) ?[]const u8 { var i = a.heads.items.len; while (i > 0) { i -= 1; for (a.heads.items[i].fields) |f| { if (std.mem.eql(u8, f.name, name)) return f.value; } } return null; } fn statusOf(a: *const Answer, stream_id: u31) ?[]const u8 { for (a.heads.items) |head| { if (head.stream_id != stream_id) continue; for (head.fields) |f| { if (std.mem.eql(u8, f.name, ":status")) return f.value; } } return null; } };