// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The server over a real loopback socket. //! //! `e2e.zig` covers what the driver does with a given sequence of octets, and //! covers it far more thoroughly than this can, because it needs no scheduling //! and no ports. What it cannot cover is whether the pieces underneath are //! wired up: that `tcp.Listener` hands over a connection whose reader and //! writer point where they should, that the accept loop serves more than one //! client, that `shutdown` actually stops it, and that the buffers survive //! being handed between tasks. //! //! Each test runs the server in a task of its own, because the accept and the //! connect block on each other and neither can finish first. const std = @import("std"); const Io = std.Io; const net = Io.net; const testing = std.testing; const http = @import("http"); const http_io = @import("http_io"); const Request = http.server.Request; const Response = http.server.Response; const gpa = testing.allocator; fn echo(req: *Request, res: *Response) anyerror!void { try res.setHeader("Content-Type", "text/plain"); try res.sendPrint("{s} {s}", .{ req.method.name, req.target.path }); } /// A server on a loopback port, already accepting. /// /// Must not be moved once `start` has returned: the running task holds a /// pointer to the server, which holds one to the listener. const Fixture = struct { listener: http_io.tcp.Listener, server: http.server.Server, tasks: Io.Group, fn startWith(f: *Fixture, handler: http.server.Handler) !void { const io = testing.io; f.listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); errdefer f.listener.deinit(io); f.server = .init(io, gpa, f.listener.listener(), handler, .{ .http1 = .{ .send_date = false, .server_name = null }, }); f.tasks = .init; f.tasks.concurrent(io, run, .{&f.server}) catch return error.SkipZigTest; } fn start(f: *Fixture) !void { const io = testing.io; // Port zero: the kernel picks one, so the suite cannot collide with // whatever else is running on the machine. f.listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); errdefer f.listener.deinit(io); f.server = .init(io, gpa, f.listener.listener(), .initStateless(echo), .{ .http1 = .{ .send_date = false, .server_name = null }, }); f.tasks = .init; // Without a second task the accept and the connect deadlock. f.tasks.concurrent(io, run, .{&f.server}) catch return error.SkipZigTest; } fn run(server: *http.server.Server) void { server.serve() catch {}; } fn stop(f: *Fixture) void { const io = testing.io; f.server.shutdown(); f.tasks.await(io) catch {}; f.listener.deinit(io); } /// What the kernel bound, for connecting to -- a socket address, since /// that is what connecting takes. fn address(f: *const Fixture) net.IpAddress { return f.listener.localAddress(); } /// The same thing as the value the seam reports, for comparing against /// what a handler would be told. fn endpoint(f: *const Fixture) http.transport.Endpoint { return .fromStdAddress(f.listener.localAddress()); } }; /// Sends `bytes` and reads until the server closes. /// /// The write half is shut down after the request so that the server sees the /// end of the stream and stops waiting for another one; without that a /// kept-alive connection would leave both ends blocked on each other. fn roundTrip(address: net.IpAddress, bytes: []const u8) ![]u8 { const io = testing.io; const stream = try net.IpAddress.connect(&address, io, .{ .mode = .stream }); defer stream.close(io); var write_buffer: [1024]u8 = undefined; var writer = stream.writer(io, &write_buffer); try writer.interface.writeAll(bytes); try writer.interface.flush(); try stream.shutdown(io, .send); var read_buffer: [1024]u8 = undefined; var reader = stream.reader(io, &read_buffer); return reader.interface.allocRemaining(gpa, .limited(1 << 20)); } test "a request over a socket" { var f: Fixture = undefined; try f.start(); defer f.stop(); const response = try roundTrip(f.address(), "GET /hello HTTP/1.1\r\nHost: h\r\n\r\n"); defer gpa.free(response); try testing.expectEqualStrings( "HTTP/1.1 200 OK\r\n" ++ "Content-Length: 10\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "GET /hello", response, ); } test "two requests pipelined on one connection" { var f: Fixture = undefined; try f.start(); defer f.stop(); const response = try roundTrip( f.address(), "GET /a HTTP/1.1\r\nHost: h\r\n\r\nGET /bb HTTP/1.1\r\nHost: h\r\n\r\n", ); defer gpa.free(response); try testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nContent-Length: 6\r\nContent-Type: text/plain\r\n\r\nGET /a" ++ "HTTP/1.1 200 OK\r\nContent-Length: 7\r\nContent-Type: text/plain\r\n\r\nGET /bb", response, ); } test "the server keeps accepting after a connection ends" { var f: Fixture = undefined; try f.start(); defer f.stop(); for (0..3) |i| { const response = try roundTrip(f.address(), "GET /x HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n"); defer gpa.free(response); testing.expect(std.mem.endsWith(u8, response, "GET /x")) catch |err| { std.debug.print("connection {d} answered {s}\n", .{ i, response }); return err; }; } } test "the listener reports the port the kernel chose" { var f: Fixture = undefined; try f.start(); defer f.stop(); try testing.expect(f.address().getPort() != 0); try testing.expect(f.endpoint().eql(f.server.localAddress().?)); } test "this library's client against this library's server, over a real socket" { // The strongest check either half gets. Everything else in the client // suite is this library reading bytes it was handed, and everything in // the server suite is this library reading bytes it was handed -- both // could be wrong in the same way and agree. Here one half writes and the // other reads, over a socket, with nothing scripted in between. const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http1.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); const res = try c.send(.{ .host = "127.0.0.1", .target = "/hello", .method = .get }); const body = try c.readAll(res, 1 << 20); defer gpa.free(body); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqualStrings("GET /hello", body); try testing.expectEqualStrings("text/plain", res.header("content-type").?); // §9.3: neither end named `close`, so the connection survives for another. try testing.expect(c.canReuse()); } test "keep-alive across two exchanges, against a real server" { const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http1.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); for ([_][]const u8{ "/one", "/two", "/three" }) |target| { const res = try c.send(.{ .host = "127.0.0.1", .target = target }); const body = try c.readAll(res, 1 << 20); defer gpa.free(body); var expected: [64]u8 = undefined; try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "GET {s}", .{target}), body, ); try testing.expect(c.canReuse()); } } test "a POST with a body, read back by the server that received it" { const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http1.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); const res = try c.send(.{ .host = "127.0.0.1", .target = "/submit", .method = .post, .body = .{ .exact = 7 }, .content = "payload", }); const body = try c.readAll(res, 1 << 20); defer gpa.free(body); // The fixture echoes the method and path, which is enough to say the // server read the request line and did not choke on the body. try testing.expectEqualStrings("POST /submit", body); } test "the HTTP/2 client against this library's HTTP/2 server" { // Prior knowledge: §3.4's preface on a cleartext port, which is how // `curl --http2-prior-knowledge` and `nghttp` reach this server and the // only way to without TLS. const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/hello" }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqual(http.protocol.Version.http_2, res.version); try testing.expectEqualStrings("GET /hello", c.body(handle)); try testing.expectEqualStrings("text/plain", res.headers.get("content-type").?); c.finish(handle); } test "two HTTP/2 requests in flight at once, which is the point of the version" { // Both begun before either is awaited, so the server has two streams open // together and the responses may come back interleaved. Awaiting the // second first is deliberate: it makes the pump file the first one's // frames rather than deliver them. const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const first = try c.begin(.{ .host = "127.0.0.1", .target = "/one" }); const second = try c.begin(.{ .host = "127.0.0.1", .target = "/two" }); const res_second = try c.await(second); try testing.expectEqual(@as(u16, 200), res_second.status); try testing.expectEqualStrings("GET /two", c.body(second)); const res_first = try c.await(first); try testing.expectEqual(@as(u16, 200), res_first.status); try testing.expectEqualStrings("GET /one", c.body(first)); c.finish(first); c.finish(second); } test "an HTTP/2 POST, with the body in DATA frames" { const io = testing.io; var f: Fixture = undefined; try f.start(); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/submit", .method = .post, .body = .{ .exact = 7 }, .content = "payload", }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqualStrings("POST /submit", c.body(handle)); c.finish(handle); } /// Answers with what the request said its content length was, which is how a /// test asks whether a `Content-Length` crossed the wire: the server reads the /// field out of the field section and this is the only place it shows. fn declares(_: ?*anyopaque, req: *http.server.Request, res: *http.server.Response) anyerror!void { // Read before anything is consumed: what the message declared is a fact // about the field section, and reading the body is what makes the stream's // credit come back. const declared = req.body.length; const body = try req.body.readAlloc(gpa, 1 << 20); defer gpa.free(body); switch (declared) { .none => try res.send("none"), .exact => |n| try res.sendPrint("exact {d}", .{n}), .unknown => try res.send("unknown"), } } test "RFC 9110 8.6: an HTTP/2 request with a body declares how long it is" { // §8.1 of RFC 9113 delimits content with the stream, so this field is // optional -- and §8.6 of RFC 9110 asks a user agent to send it anyway // when it knows the length, recipients use it to check what arrived, and // Cloudflare's DNS-over-HTTP/3 endpoint answers 400 to a POST without one. // The server is what proves it went out: `req.length` is read from the // field section and from nowhere else. const io = testing.io; var f: Fixture = undefined; try f.startWith(.{ .context = null, .serveFn = declares }); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/submit", .method = .post, .body = .{ .exact = 7 }, .content = "payload", }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqualStrings("exact 7", c.body(handle)); c.finish(handle); } test "a GET declares nothing, because there is nothing to declare" { // Not `Content-Length: 0`: §8.6 of RFC 9110 has a user agent send the // field for content it is sending, and a request with no body is not a // request with an empty one. const io = testing.io; var f: Fixture = undefined; try f.startWith(.{ .context = null, .serveFn = declares }); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/hello" }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqualStrings("none", c.body(handle)); c.finish(handle); } /// Reads the whole request body and answers with how much of it arrived, /// which is what makes a flow-control test measure anything: a handler that /// never reads leaves the stream window shut, and correctly so. fn counts(_: ?*anyopaque, req: *http.server.Request, res: *http.server.Response) anyerror!void { const body = try req.body.readAlloc(gpa, 1 << 22); defer gpa.free(body); try res.sendPrint("{d}", .{body.len}); } test "a body larger than one frame and one window, which flow control must carry" { // Larger than the 16 KiB default frame size and larger than the 65535 // octet initial window, so the request cannot go out without the client // splitting it and waiting for the server's WINDOW_UPDATE. const io = testing.io; var f: Fixture = undefined; try f.startWith(.{ .context = null, .serveFn = counts }); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); const big = try gpa.alloc(u8, 200 * 1024); defer gpa.free(big); @memset(big, 'x'); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/big", .method = .post, .body = .{ .exact = big.len }, .content = big, }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); // The server counted every octet, so all 200 KiB crossed a 65535-octet // window and a 16 KiB frame limit -- which cannot happen without the // client splitting the body and waiting for WINDOW_UPDATE. try testing.expectEqualStrings("204800", c.body(handle)); c.finish(handle); } /// Answers with a body of the size the path asks for, so that a test can make /// a response cross a window. fn sized(_: ?*anyopaque, req: *http.server.Request, res: *http.server.Response) anyerror!void { const n = std.fmt.parseInt(usize, req.target.path[1..], 10) catch 0; const body = try gpa.alloc(u8, n); defer gpa.free(body); @memset(body, 'y'); try res.send(body); } test "RFC 9113 6.9.2: a response larger than the default connection window" { // The connection's flow-control window starts at 65535 and // SETTINGS_INITIAL_WINDOW_SIZE does not change it -- that setting is // about *stream* windows. Only a WINDOW_UPDATE on stream 0 raises it, and // a client that thought otherwise would keep accounting against a window // its peer never agreed to: the server stops at 65535 octets and waits // for credit, the client waits for the rest, and neither is at fault. // // Found against nginx, which is exactly what the interop guest is for. const io = testing.io; var f: Fixture = undefined; try f.startWith(.{ .context = null, .serveFn = sized }); defer f.stop(); const conn = try http_io.tcp.connect(io, gpa, f.address(), .{}); var c = try http.http2.client.Connection.init(io, gpa, conn, .{}); defer c.deinit(); try c.handshake(); const handle = try c.begin(.{ .host = "127.0.0.1", .target = "/200000" }); const res = try c.await(handle); try testing.expectEqual(@as(u16, 200), res.status); try testing.expectEqual(@as(usize, 200000), c.body(handle).len); c.finish(handle); }