diff --git a/README.md b/README.md index 11b78cf..1a37b1b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ implemented rather than summarised here. ## Status -Early. The wire formats are exercised by 405 tests, eighteen property-based +Early. The wire formats are exercised by 411 tests, eighteen property-based fuzz targets and ten NixOS guests that point real implementations at it — `curl`, nginx, aioquic, Traefik, `h2load` and the h2spec conformance suite — and the framing rules are the ones RFC 9112 and RFC 9113 give. But it has not @@ -861,13 +861,28 @@ What it does not do is keep anything between calls. Every `fetch` dials, sends, reads and closes, so HTTP/2's multiplexing is not used across calls and a redirect to the same origin opens a second connection; a caller wanting many requests on one connection uses the drivers directly, which is what they are -for. There is no HTTP/3, because learning that a server speaks it means -`Alt-Svc` and remembering it; and a `Client` is not safe to share +for. A `Client` is not safe to share between tasks — it holds a random number generator and a lazily loaded certificate bundle, so one each is cheap. Over HTTP/2 the body is bounded by `http2_config.max_body_len`, because that driver gathers a body before handing it over; over HTTP/1.1 it streams into the writer. +**HTTP/3 is asked for, not negotiated.** Over TCP, ALPN chooses the version +inside the one handshake; QUIC is another transport on another protocol, so +trying it is a decision made before anything is sent. `http3 = .only` fetches +an `https` URL over HTTP/3 or fails with the handshake's error, and `.prefer` +tries QUIC first and falls back to TCP — before anything was sent, so a +request is never sent twice. Each address the name resolved to is tried in +turn, and a handshake is given `http3_handshake_timeout`, three seconds by +default: the usual reason for no answer is UDP blocked on the way, which is +silence rather than a refusal and costs the whole wait. A certificate refused +over QUIC is never retried at another address or over TCP, as over TLS. An +`http` URL is never fetched over HTTP/3, since RFC 9114 has no cleartext form, +and neither is anything going through a proxy, which would be RFC 9298's +CONNECT-UDP. Against the internet: Cloudflare, Google and this repository's +Forgejo answer over HTTP/3, and example.com, which has none, fails `.only` and +falls back under `.prefer`. + **A body too large to hold** goes in `payload_reader` rather than `payload`: a reader and a length. The length is declared as the `Content-Length`, and exactly that many octets are then read from the reader diff --git a/src/io/Client.zig b/src/io/Client.zig index 604ce58..50f70d0 100644 --- a/src/io/Client.zig +++ b/src/io/Client.zig @@ -58,11 +58,12 @@ //! requests on one connection uses the drivers directly, which is what they //! are for. //! -//! **No HTTP/3.** Finding out that a server speaks it means `Alt-Svc`, which -//! arrives on a response over some other version, and remembering it between -//! calls -- which this client does not do for anything. +//! **HTTP/3 only when asked.** `http3 = .only` or `.prefer` fetches an +//! `https` URL over QUIC, the second falling back to TCP when no handshake +//! completes. Nothing here yet learns from a server that it speaks HTTP/3 -- +//! that is `Alt-Svc`, which has to be remembered between calls. //! -//! **No proxy**, and no Unicode host names: `HostName` holds letters, digits +//! **No Unicode host names**: `HostName` holds letters, digits //! and hyphens, so an internationalised name has to arrive in its `xn--` //! form. zig-uri's `Uri.toUri` produces that when it is built with Unicode //! support. @@ -81,6 +82,7 @@ const uri = @import("uri"); const tcp = @import("tcp.zig"); const tls = @import("tls.zig"); const proxy = @import("proxy.zig"); +const http3_io = @import("http3.zig"); const protocol = http.protocol; const transport = http.transport; @@ -110,6 +112,26 @@ root_ca: ?tls.CertBundle = null, insecure_skip_verify: bool = false, /// Whether to offer `h2` over TLS. Off, only `http/1.1` is offered. http2: bool = true, +/// Whether an `https` URL is fetched over HTTP/3. +/// +/// TCP has ALPN to choose a version inside the one handshake; QUIC is a +/// different transport on a different protocol, so trying it is a decision +/// made before anything is sent, and this is where it is made. See `Http3`. +/// +/// Never for an `http` URL -- §3.1 of RFC 9114 gives HTTP/3 no cleartext +/// form -- and never through a proxy, since reaching one over HTTP/3 would be +/// RFC 9298's CONNECT-UDP, which is not implemented. Both of those are +/// fetched over TCP whatever this says. +http3: Http3 = .off, +/// How long a QUIC handshake to one address may take before it is given up +/// on: the next address is tried, and after the last, `.prefer` falls back to +/// TCP. Shorter than a TCP connect is allowed to take, because the usual +/// reason for no answer is UDP blocked somewhere on the way, which is silence +/// rather than a refusal and costs this whole wait. +http3_handshake_timeout: Io.Duration = .fromSeconds(3), +/// Passed to the HTTP/3 driver, apart from `accept_encodings`. Its +/// `max_body_len` bounds a response over HTTP/3, which is gathered whole. +http3_config: http.http3.client.Config = .{}, /// Whether an `http` URL is spoken to in HTTP/2 from the first octet. /// /// §3.3 of RFC 9113: a client that knows a server speaks HTTP/2 may start @@ -313,6 +335,19 @@ pub const FetchOptions = struct { }; }; +pub const Http3 = enum { + /// HTTP/1.1 and HTTP/2 over TCP, as ALPN decides. + off, + /// HTTP/3 or nothing: a server that does not complete a QUIC handshake is + /// the error that handshake failed with. + only, + /// HTTP/3 when the server answers over QUIC, and TCP when it does not. + /// The fallback happens only before anything was sent, so a request is + /// never sent twice; once a request has gone out over QUIC, a failure is + /// that failure. + prefer, +}; + pub const PayloadReader = struct { reader: *Io.Reader, /// Octets to send, which is also what `Content-Length` says. @@ -365,7 +400,17 @@ pub const FetchError = uri.parse.Error || Io.ConcurrentError || proxy.TunnelError || tls.ConnectOverError || + http.http3.client.Error || error{ + /// No QUIC handshake completed in `http3_handshake_timeout`, with + /// `http3 = .only`. + HandshakeTimeout, + /// The UDP socket would not send or receive, with `http3 = .only`. + NetworkFailed, + /// The server's certificate was refused during a QUIC handshake. Not + /// retried at another address or over TCP, for the reason + /// `tls.connectAny` gives. + BadCertificate, /// Neither `http` nor `https`. UnsupportedUriScheme, /// The URL names no host to connect to. @@ -682,6 +727,18 @@ fn exchange( .rng = try c.random(), .tcp = c.tcp_options, }; + // Resolved once for whichever transport ends up used, so that a fallback + // does not look the name up a second time. + var address_buffer: [16]net.IpAddress = undefined; + const addresses: []const net.IpAddress = if (via == null) try c.resolve(host, port, &address_buffer) else &.{}; + + if (via == null and c.http3 != .off) { + if (try c.overHttp3(host.text(), addresses, request, options.response_writer, follow)) |outcome| { + return outcome; + } + // `.prefer`, and no QUIC handshake completed: TCP, below. + } + var conn = if (via) |tunneller| tunnelled: { // The origin's name is the proxy's to resolve, which is the point of // asking it for the authority rather than for an address: the proxy @@ -692,11 +749,7 @@ fn exchange( const to_proxy = try c.dialProxy(tunneller); const through = try proxy.tunnel(c.io, c.gpa, to_proxy, authority, tunneller.authorization); break :tunnelled try tls.connectOver(c.io, c.gpa, through, tls_options); - } else direct: { - var address_buffer: [16]net.IpAddress = undefined; - const addresses = try c.resolve(host, port, &address_buffer); - break :direct try tls.connectAny(c.io, c.gpa, addresses, tls_options); - }; + } else try tls.connectAny(c.io, c.gpa, addresses, tls_options); const selected = conn.info.alpn orelse "http/1.1"; if (std.mem.eql(u8, selected, "h2") and c.http2) { return c.overHttp2(conn, request, options.response_writer, follow); @@ -708,6 +761,106 @@ fn exchange( return error.UnexpectedProtocol; } +/// An exchange over HTTP/3, or null when no QUIC handshake completed and +/// `http3 = .prefer` leaves TCP to try. +/// +/// Each address in turn, as `tcp.connectAny` does, since an address that +/// drops UDP is the ordinary case and not the exceptional one. +fn overHttp3( + c: *Client, + host: []const u8, + addresses: []const net.IpAddress, + request: Request, + response_writer: ?*Io.Writer, + follow: bool, +) FetchError!?Outcome { + var failure: FetchError = error.HandshakeTimeout; + for (addresses) |address| { + if (try c.attemptHttp3(host, address, request, response_writer, follow, &failure)) |outcome| { + return outcome; + } + } + return if (c.http3 == .prefer) null else failure; +} + +/// One address: a UDP socket, a QUIC handshake, and an exchange. Null, with +/// `failure` saying why, when the handshake did not complete and another +/// address or TCP may do better; an error for anything that happened after +/// the request began, which is not retried anywhere. +/// +/// The socket, the dialer and the task pumping it live in this frame and +/// nowhere else, which is why it is a function of its own: the dialer must +/// not move once connected, and all three end together when it returns. +fn attemptHttp3( + c: *Client, + host: []const u8, + address: net.IpAddress, + request: Request, + response_writer: ?*Io.Writer, + follow: bool, + failure: *FetchError, +) FetchError!?Outcome { + // The unspecified address of the family being dialled: a socket bound to + // one family cannot reach the other. + const local: net.IpAddress = switch (address) { + .ip4 => .{ .ip4 = .unspecified(0) }, + .ip6 => .{ .ip6 = .unspecified(0) }, + }; + var socket = local.bind(c.io, .{ .mode = .dgram }) catch { + failure.* = error.NetworkFailed; + return null; + }; + defer socket.close(c.io); + + var dialer: http3_io.Dialer = undefined; + dialer.connect(c.io, c.gpa, &socket, address, .{ + .host = host, + .root_ca = try c.trust(), + .insecure_skip_verify = c.insecure_skip_verify, + .rng = try c.random(), + .handshake_timeout_ns = @intCast(@max(0, c.http3_handshake_timeout.nanoseconds)), + }) catch |err| switch (err) { + error.OutOfMemory, error.Canceled => |e| return e, + // An answer about the name, not the address, and so not one to ask + // again elsewhere -- the same judgement `tls.connectAny` makes. + error.BadCertificate => return error.BadCertificate, + error.HandshakeTimeout, error.NetworkFailed, error.HandshakeFailed => |e| { + failure.* = e; + return null; + }, + }; + defer dialer.deinit(); + + // A stream read waits for a datagram and this is what makes one arrive, + // so it has to run beside the exchange rather than inside it. + var pump: Io.Group = .init; + defer pump.cancel(c.io); + try pump.concurrent(c.io, runDialer, .{&dialer}); + defer dialer.stop(); + + var config = c.http3_config; + config.accept_encodings = c.accept_encodings; + var h3: http.http3.client.Connection = .init(c.gpa, dialer.session(), config); + try h3.start(); + var answered = try h3.send(request); + defer answered.deinit(c.gpa); + const res = answered.response; + + if (follow and isRedirect(res.status)) { + if (res.header("location")) |location| return .{ + .status = res.status, + .version = res.version, + .location = try c.gpa.dupe(u8, location), + }; + } + if (response_writer) |w| w.writeAll(answered.body()) catch return error.WriteFailed; + return .{ .status = res.status, .version = res.version, .kept = try keep(c.gpa, res.headers) }; +} + +fn runDialer(dialer: *http3_io.Dialer) void { + dialer.run() catch {}; +} + /// A connection to a proxy, with buffers large enough for a TLS handshake to /// run inside whatever tunnel it is about to carry. fn dialProxy(c: *Client, p: proxy.Proxy) FetchError!transport.Connection { diff --git a/src/io/http3.zig b/src/io/http3.zig index e7e816e..8875e41 100644 --- a/src/io/http3.zig +++ b/src/io/http3.zig @@ -193,6 +193,10 @@ pub const Dialer = struct { rng: std.Random, sizes: quic.Connection.Sizes = .{}, max_send_window: ?usize = 64 << 10, + /// How long the handshake may take before `connect` gives up with + /// `error.HandshakeTimeout`, which is what a server that is not there + /// -- or UDP that is blocked on the way -- looks like. + handshake_timeout_ns: u64 = 10 * std.time.ns_per_s, }; pub fn connect( @@ -215,6 +219,7 @@ pub const Dialer = struct { .rng = options.rng, .sizes = options.sizes, .max_send_window = options.max_send_window, + .handshake_timeout_ns = options.handshake_timeout_ns, .local = .{ // What this end can hold is what it may promise, the same // arithmetic `Listener.advertised` does for the server. diff --git a/src/main.zig b/src/main.zig index b1a0300..6e8c26c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -46,6 +46,11 @@ const usage = \\ speaks whichever the server picks, redirects are \\ followed, and the certificate is checked against the \\ system's store unless --fetch-ca says otherwise. + \\ --fetch-http3 M + \\ only: fetch an https URL over HTTP/3 or fail. prefer: + \\ over HTTP/3 if the server answers over QUIC, and over + \\ TCP if it does not. Not through a proxy, and never + \\ for an http URL. \\ --fetch-timeout S \\ Give up on --fetch after S seconds, all of it counted: \\ the lookup, the connection, the handshake, redirects @@ -135,6 +140,7 @@ pub fn main(init: std.process.Init) !void { var fetch_gzip = false; var fetch_proxy: ?[]const u8 = null; var fetch_timeout: ?u32 = null; + var fetch_http3: http_io.Client.Http3 = .off; var key_path: ?[]const u8 = null; var args: std.process.Args.Iterator = .init(init.minimal.args); @@ -168,6 +174,10 @@ pub fn main(init: std.process.Init) !void { fetch_host = args.next() orelse return fail("--fetch-host wants a name"); } else if (std.mem.eql(u8, arg, "--fetch-gzip")) { fetch_gzip = true; + } else if (std.mem.eql(u8, arg, "--fetch-http3")) { + const text = args.next() orelse return fail("--fetch-http3 wants only or prefer"); + fetch_http3 = std.meta.stringToEnum(http_io.Client.Http3, text) orelse + return fail("--fetch-http3 wants only or prefer"); } else if (std.mem.eql(u8, arg, "--fetch-timeout")) { const text = args.next() orelse return fail("--fetch-timeout wants a number of seconds"); fetch_timeout = std.fmt.parseInt(u32, text, 10) catch @@ -200,7 +210,7 @@ pub fn main(init: std.process.Init) !void { if (fetch_url) |url| return fetch(io, gpa, url, fetch_version, fetch_ca, fetch_host, fetch_gzip, .{ .url = fetch_proxy, .environ_map = init.environ_map, - }, fetch_timeout); + }, fetch_timeout, fetch_http3); // One source of randomness for both listeners: the TLS handshake needs // it, and so does QUIC below. @@ -516,11 +526,13 @@ fn fetch( want_gzip: bool, proxies: ProxyChoice, timeout_seconds: ?u32, + use_http3: http_io.Client.Http3, ) !void { const version_text = version_choice orelse { if (host_override != null) return fail("--fetch-host needs --fetch-version"); - return fetchNegotiated(io, gpa, url, ca_path, want_gzip, proxies, timeout_seconds); + return fetchNegotiated(io, gpa, url, ca_path, want_gzip, proxies, timeout_seconds, use_http3); }; + if (use_http3 != .off) return fail("--fetch-http3 cannot be used with --fetch-version; that is --fetch-version 3"); if (timeout_seconds != null) return fail("--fetch-timeout cannot be used with --fetch-version"); // One driver pointed at one socket is exactly what a proxy is not. if (proxies.url != null) return fail("--fetch-proxy cannot be used with --fetch-version"); @@ -714,6 +726,7 @@ fn fetchNegotiated( want_gzip: bool, proxies: ProxyChoice, timeout_seconds: ?u32, + use_http3: http_io.Client.Http3, ) !void { var trust: ?http_io.tls.CertBundle = null; defer if (trust) |*bundle| bundle.deinit(gpa); @@ -727,6 +740,7 @@ fn fetchNegotiated( .gpa = gpa, .root_ca = trust, .accept_encodings = if (want_gzip) &.{.gzip} else &.{}, + .http3 = use_http3, .timeout = if (timeout_seconds) |seconds| .{ .duration = .{ .raw = .fromSeconds(seconds), .clock = .awake } } else diff --git a/tests/fetch.zig b/tests/fetch.zig index d8249b5..effcc91 100644 --- a/tests/fetch.zig +++ b/tests/fetch.zig @@ -187,6 +187,12 @@ const Fixture = struct { prng: std.Random.DefaultPrng = .init(0x7301), server: http.server.Server = undefined, tasks: Io.Group = .init, + /// HTTP/3, when `serveHttp3` has been called: a UDP socket on the same + /// port number as the TCP one, as a real server has it, so that one URL + /// reaches either. + udp: ?Io.net.Socket = null, + quic: http_io.http3.Listener = undefined, + quic_tasks: Io.Group = .init, fn startPlain(f: *Fixture) !void { const io = testing.io; @@ -225,8 +231,41 @@ const Fixture = struct { server.serve() catch {}; } + /// Answers HTTP/3 on the TCP listener's port number, with the same + /// certificate and the same routes. Only for a secure fixture: §3.1 of + /// RFC 9114 has no cleartext form. + fn serveHttp3(f: *Fixture) !void { + const io = testing.io; + std.debug.assert(f.is_secure); + const at: net.IpAddress = .{ .ip4 = .loopback(f.port()) }; + f.udp = try at.bind(io, .{ .mode = .dgram }); + errdefer { + f.udp.?.close(io); + f.udp = null; + } + try f.quic.init(io, gpa, &f.udp.?, .initStateless(routes), .{ + .auth = &f.auth, + .rng = f.prng.random(), + .reset_key = @splat(0x33), + .token_key = @splat(0x44), + .max_connections = 8, + }); + f.quic_tasks.concurrent(io, runQuic, .{&f.quic}) catch return error.SkipZigTest; + } + + fn runQuic(listener: *http_io.http3.Listener) void { + listener.run() catch {}; + } + fn stop(f: *Fixture) void { const io = testing.io; + if (f.udp) |*socket| { + f.quic.stop(); + f.quic_tasks.cancel(io); + f.quic.deinit(); + socket.close(io); + f.udp = null; + } f.server.shutdown(); f.tasks.await(io) catch {}; if (f.is_secure) { @@ -1309,6 +1348,223 @@ test "a deadline already past fails at once" { } else |err| try testing.expectEqual(error.Timeout, err); } +/// `localhost` as 127.0.0.1 and nothing else. The HTTP/3 fixture listens on +/// IPv4 alone, and a QUIC handshake to `::1` would be silence that costs a +/// whole handshake timeout before the address that works is tried -- a test +/// of patience rather than of anything here. +fn loopbackOnly( + host_name: net.HostName, + io: Io, + resolved: *Io.Queue(net.HostName.LookupResult), + options: net.HostName.LookupOptions, +) net.HostName.LookupError!void { + defer resolved.close(io); + if (!std.ascii.eqlIgnoreCase(host_name.bytes, "localhost")) return error.UnknownHostName; + resolved.putOne(io, .{ .address = .{ .ip4 = .loopback(options.port) } }) catch |err| switch (err) { + error.Canceled => |e| return e, + error.Closed => {}, + }; +} + +fn http3Client(trust: http_io.tls.CertBundle, mode: Client.Http3) Client { + return .{ + .io = testing.io, + .gpa = gpa, + .root_ca = trust, + .resolver = loopbackOnly, + .http3 = mode, + // Loopback answers in microseconds, and a server that is not there + // should not hold a test up for long. + .http3_handshake_timeout = .fromMilliseconds(500), + }; +} + +test "http3 = .only fetches over HTTP/3, certificate checked" { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + try f.serveHttp3(); + + var trust = try trustFixture(); + defer trust.deinit(gpa); + var client = http3Client(trust, .only); + defer client.deinit(); + + var buffer: [128]u8 = undefined; + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/hello?x=1") } }); + defer got.deinit(); + try testing.expectEqual(.ok, got.result.status); + try testing.expectEqual(http.protocol.Version.http_3, got.result.version); + try testing.expectEqualStrings("http_3 GET /hello x=1 ", got.body.written()); + // Lowercase on the wire, found without case here. + try expectEchoedFields(&got.result.headers); +} + +test "http3 = .only against a server with no HTTP/3 is the handshake's failure" { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + + var trust = try trustFixture(); + defer trust.deinit(gpa); + var client = http3Client(trust, .only); + defer client.deinit(); + + var buffer: [128]u8 = undefined; + const outcome = client.fetch(.{ .location = .{ .url = try f.url(&buffer, "localhost", "/") } }); + // Silence, or the ICMP port-unreachable loopback sends back: either way + // no QUIC, and no quiet retreat to TCP. + if (outcome) |result| { + var owned = result; + owned.deinit(); + return error.TestUnexpectedResult; + } else |err| switch (err) { + error.HandshakeTimeout, error.NetworkFailed => {}, + else => return err, + } +} + +test "http3 = .prefer uses HTTP/3 where there is one, and TCP where there is not" { + var trust = try trustFixture(); + defer trust.deinit(gpa); + var buffer: [128]u8 = undefined; + + { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + try f.serveHttp3(); + var client = http3Client(trust, .prefer); + defer client.deinit(); + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/") } }); + defer got.deinit(); + try testing.expectEqual(http.protocol.Version.http_3, got.result.version); + } + { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + var client = http3Client(trust, .prefer); + defer client.deinit(); + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/") } }); + defer got.deinit(); + // Fell back, and ALPN then chose as it always does. + try testing.expectEqual(http.protocol.Version.http_2, got.result.version); + try testing.expectEqualStrings("http_2 GET / - ", got.body.written()); + } +} + +test "over HTTP/3: a body, a streamed body, a redirect and gzip" { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + try f.serveHttp3(); + + var trust = try trustFixture(); + defer trust.deinit(gpa); + var client = http3Client(trust, .only); + defer client.deinit(); + var buffer: [128]u8 = undefined; + + { + var got = try fetch(&client, .{ + .location = .{ .url = try f.url(&buffer, "localhost", "/submit") }, + .payload = "hello", + }); + defer got.deinit(); + try testing.expectEqualStrings("http_3 POST /submit - hello", got.body.written()); + } + { + const size: u64 = 4 << 20; + var source_buffer: [8192]u8 = undefined; + var source: Pattern = .init(&source_buffer, size); + var got = try fetch(&client, .{ + .location = .{ .url = try f.url(&buffer, "localhost", "/verify") }, + .method = http.protocol.Method.put, + .payload_reader = .{ .reader = &source.interface, .length = size }, + }); + defer got.deinit(); + try testing.expectEqualStrings("http_3 PUT 4194304 octets", got.body.written()); + } + { + // Two QUIC connections, one per hop, since nothing is kept. + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/moved") } }); + defer got.deinit(); + try testing.expectEqualStrings("http_3 GET /landed from=moved ", got.body.written()); + } + { + var gzip_client = http3Client(trust, .only); + gzip_client.accept_encodings = &.{.gzip}; + defer gzip_client.deinit(); + const expected = try squishBody(gpa); + defer gpa.free(expected); + var got = try fetch(&gzip_client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/squish") } }); + defer got.deinit(); + try testing.expectEqualStrings("gzip", got.result.headers.get("content-encoding").?); + try testing.expectEqualSlices(u8, expected, got.body.written()); + } +} + +test "HTTP/3 is never used where it cannot be" { + var trust = try trustFixture(); + defer trust.deinit(gpa); + var buffer: [128]u8 = undefined; + + // An `http` URL: RFC 9114 has no cleartext form, so `.only` still means + // TCP here rather than an error. + { + var f: Fixture = undefined; + try f.startPlain(); + defer f.stop(); + var client = http3Client(trust, .only); + defer client.deinit(); + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/") } }); + defer got.deinit(); + try testing.expectEqual(http.protocol.Version.http_1_1, got.result.version); + } + + // Through a proxy: tunnelled over TCP, and HTTP/2 inside the tunnel, + // though the origin answers HTTP/3 as well. + { + var f: Fixture = undefined; + try f.startSecure(&.{ "h2", "http/1.1" }); + defer f.stop(); + try f.serveHttp3(); + var proxy: TestProxy = undefined; + try proxy.start(false, null); + defer proxy.stop(); + var client = http3Client(trust, .only); + client.https_proxy = .{ .host = "127.0.0.1", .port = proxy.port() }; + defer client.deinit(); + var got = try fetch(&client, .{ .location = .{ .url = try f.url(&buffer, "localhost", "/") } }); + defer got.deinit(); + try testing.expectEqual(http.protocol.Version.http_2, got.result.version); + try testing.expectEqual(@as(usize, 1), proxy.connects.load(.monotonic)); + } +} + +test "a timeout cuts a QUIC handshake short" { + // A server that never answers over UDP, a handshake allowed ten seconds, + // and a fetch allowed a fifth of one: cancellation has to reach into the + // QUIC handshake, or this takes the ten. + var silent: Io.net.Socket = try (Io.net.IpAddress{ .ip4 = .loopback(0) }).bind(testing.io, .{ .mode = .dgram }); + defer silent.close(testing.io); + + var trust = try trustFixture(); + defer trust.deinit(gpa); + var client = http3Client(trust, .only); + client.http3_handshake_timeout = .fromSeconds(10); + client.timeout = millis(200); + defer client.deinit(); + + var buffer: [128]u8 = undefined; + const url = try std.fmt.bufPrint(&buffer, "https://localhost:{d}/", .{silent.address.getPort()}); + const started = Io.Clock.awake.now(testing.io); + try testing.expectError(error.Timeout, client.fetch(.{ .location = .{ .url = url } })); + const took = started.durationTo(Io.Clock.awake.now(testing.io)); + try testing.expect(took.toMilliseconds() < 5_000); +} + test "what the client will not send" { var client: Client = .{ .io = testing.io, .gpa = gpa }; defer client.deinit();