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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! RFC 9460 end to end: a DNS server publishing HTTPS records, zig-http//! serving over TCP and QUIC, and `http_io.Client` finding HTTP/3 from DNS on//! the very first request -- with zig-dns-client doing the resolver's half,//! through `https_records`' glue.//!//! Everything is on loopback. The DNS server is a few dozen lines built with//! zig-dns, answering a zone that exists only in this file; the names are//! `.test` (RFC 6761), which resolve nowhere else and which zig-dns-client//! does not answer by itself the way it answers `localhost`. The certificate//! in `testdata/` is self-signed for the three of them.
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 dns_client = @import("dns_client");const dns = @import("dns");const https_records = @import("https_records");
const Client = http_io.Client;const gpa = testing.allocator;
const cert_pem = @embedFile("testdata/names.cert.pem");const key_pem = @embedFile("testdata/names.key.pem");
/// Which version carried the request, and what it asked for.fn echo(req: *http.server.Request, res: *http.server.Response) anyerror!void { try res.sendPrint("{t} {s}", .{ req.version, req.target.path });}
/// The zone, which depends on where the servers ended up listening:////// ```/// origin.test. A 127.0.0.1/// alias.test. A 127.0.0.1/// plain.test. A 127.0.0.1/// _<P>._https.origin.test. HTTPS 1 . alpn=h3 no-default-alpn port=<Q>/// _<P>._https.alias.test. HTTPS 0 origin.test./// origin.test. HTTPS 1 . alpn=h3 no-default-alpn port=<Q>/// ```////// where P is the origin's TCP port and Q its QUIC port. The origin is not on/// 443, so §9.1 has the client ask `_<P>._https.` names; an alias's target is/// asked without the prefix (§3), which is why `origin.test` itself carries/// the record as well. `plain.test` has addresses and no records: NODATA.const Zone = struct { io: Io, socket: net.Socket, origin_port: u16, quic_port: u16, params_buf: [32]u8 = undefined, queries: usize = 0,
fn run(z: *Zone) void { z.serve() catch {}; }
fn serve(z: *Zone) !void { while (true) { var incoming: [4096]u8 = undefined; const datagram = try z.socket.receive(z.io, &incoming); const query = dns.Message.parse(datagram.data) catch continue; const question = (query.question() catch continue) orelse continue; var outgoing: [4096]u8 = undefined; const reply = try z.answer(&outgoing, query.header.id, question); z.queries += 1; try z.socket.send(z.io, &datagram.from, reply); } }
fn params(z: *Zone) @FieldType(dns.rdata.Svcb, "params") { // alpn=h3, no-default-alpn, port -- in ascending key order, which // §2.2 requires. const fixed = "\x00\x01\x00\x03\x02h3" ++ "\x00\x02\x00\x00" ++ "\x00\x03\x00\x02"; @memcpy(z.params_buf[0..fixed.len], fixed); std.mem.writeInt(u16, z.params_buf[fixed.len..][0..2], z.quic_port, .big); return .{ .bytes = z.params_buf[0 .. fixed.len + 2] }; }
fn answer(z: *Zone, buffer: []u8, id: u16, question: dns.Question) ![]u8 { var name_buf: [300]u8 = undefined; const printed = try std.fmt.bufPrint(&name_buf, "{f}", .{question.name}); const name = std.mem.trimEnd(u8, printed, ".");
var prefixed: [3][64]u8 = undefined; const origin_https = try std.fmt.bufPrint(&prefixed[0], "_{d}._https.origin.test", .{z.origin_port}); const alias_https = try std.fmt.bufPrint(&prefixed[1], "_{d}._https.alias.test", .{z.origin_port}); const plain_https = try std.fmt.bufPrint(&prefixed[2], "_{d}._https.plain.test", .{z.origin_port});
const known_host = eql(name, "origin.test") or eql(name, "alias.test") or eql(name, "plain.test"); const known = known_host or eql(name, origin_https) or eql(name, alias_https) or eql(name, plain_https);
var builder = try dns.Builder.init(buffer, .{ .id = id, .response = true, .recursion_desired = true, .recursion_available = true, .rcode = if (known) .noerror else .nxdomain, }, .{}); try builder.question(question); const at = question.name; switch (question.type) { .a => if (known_host) try builder.record(.answer, .{ .name = at, .ttl = 60, .data = .{ .a = .{ .octets = .{ 127, 0, 0, 1 } } }, }), .https => if (eql(name, origin_https) or eql(name, "origin.test")) { try builder.record(.answer, .{ .name = at, .ttl = 60, .data = .{ .https = .{ .priority = 1, .target = dns.Name.literal("."), .params = z.params(), } } }); } else if (eql(name, alias_https)) { try builder.record(.answer, .{ .name = at, .ttl = 60, .data = .{ .https = .{ .priority = 0, .target = dns.Name.literal("origin.test"), } } }); }, // AAAA, and HTTPS for `plain.test`: the name exists, and has // nothing of that type. else => {}, } return builder.finish(); }
fn eql(a: []const u8, b: []const u8) bool { return std.ascii.eqlIgnoreCase(a, b); }};
// What the two hooks ask, pointed at the zone above. Container-level because// the hooks have `HostName.lookup`'s signature, which has nowhere else to keep// anything; the test sets them before the first fetch.var servers: [1]dns_client.Server = undefined;var host_lookup: dns_client.HostLookup = undefined;var service_lookup: dns_client.ServiceLookup = undefined;
fn testHosts( host_name: net.HostName, io: Io, resolved: *Io.Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions,) net.HostName.LookupError!void { return host_lookup.resolve(host_name, io, resolved, options);}
fn resolveServices( host_name: net.HostName, io: Io, resolved: *Io.Queue(dns_client.ServiceLookup.Service), options: dns_client.ServiceLookup.LookupOptions,) dns_client.ServiceLookup.Error!void { return service_lookup.resolve(host_name, io, resolved, options);}
fn testServices( host_name: net.HostName, io: Io, resolved: *Io.Queue(Client.Service), options: Client.ServiceLookupOptions,) Client.ServiceLookupError!void { return https_records.bridge(resolveServices, host_name, io, resolved, options);}
fn runServer(server: *http.server.Server) void { server.serve() catch {};}
fn runQuic(listener: *http_io.http3.Listener) void { listener.run() catch {};}
test "RFC 9460 end to end: HTTPS records take the first request to HTTP/3" { const io = testing.io;
var auth: http_io.tls.CertKeyPair = try .fromSlice(gpa, io, cert_pem, key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(0x9460);
// The origin over TCP, where HTTP/2 is the best it will do. var tcp: http_io.tls.Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random(), }); defer tcp.deinit(io); var server: http.server.Server = .init(io, gpa, tcp.listener(), .initStateless(echo), .{}); var server_tasks: Io.Group = .init; server_tasks.concurrent(io, runServer, .{&server}) catch return error.SkipZigTest; defer { server.shutdown(); server_tasks.await(io) catch {}; }
// And over QUIC, on a port nothing says except the HTTPS record. var udp = try (net.IpAddress{ .ip4 = .loopback(0) }).bind(io, .{ .mode = .dgram }); defer udp.close(io); var quic: http_io.http3.Listener = undefined; try quic.init(io, gpa, &udp, .initStateless(echo), .{ .auth = &auth, .rng = prng.random(), .reset_key = @splat(0x94), .token_key = @splat(0x60), .max_connections = 8, }); var quic_tasks: Io.Group = .init; quic_tasks.concurrent(io, runQuic, .{&quic}) catch return error.SkipZigTest; defer { quic.stop(); quic_tasks.cancel(io); quic.deinit(); }
// The zone. const dns_socket = try (net.IpAddress{ .ip4 = .loopback(0) }).bind(io, .{ .mode = .dgram }); var zone: Zone = .{ .io = io, .socket = dns_socket, .origin_port = tcp.localAddress().getPort(), .quic_port = udp.address.getPort(), }; defer zone.socket.close(io); var zone_tasks: Io.Group = .init; zone_tasks.concurrent(io, Zone.run, .{&zone}) catch return error.SkipZigTest; defer zone_tasks.cancel(io);
servers = .{.{ .endpoint = .fromStdAddress(zone.socket.address), .protocol = .udp }}; const resolver: dns_client.Resolver = .{ .servers = &servers, .options = .{ .timeout = .fromSeconds(2), .attempts = 1 }, }; host_lookup = .{ .resolver = resolver }; service_lookup = .{ .resolver = resolver };
// The certificate's own bundle, as the only thing trusted. const trusted: http_io.tls.CertKeyPair = try .fromSlice(gpa, io, cert_pem, key_pem); var trust = trusted.bundle; defer trust.deinit(gpa); var client: Client = .{ .io = io, .gpa = gpa, .root_ca = trust, .http3 = .advertised, .resolver = testHosts, .services = testServices, .http3_handshake_timeout = .fromSeconds(2), }; defer client.deinit();
const port = zone.origin_port; var buffer: [128]u8 = undefined;
const Case = struct { url_fmt: []const u8, expected: []const u8 }; const cases = comptime [_]Case{ // The very first request to the origin, over QUIC, to a port only DNS // named -- nothing has been fetched, so no `Alt-Svc` could have said so. .{ .url_fmt = "https://origin.test:{d}/first", .expected = "http_3 /first" }, // Through an alias to the record behind it, with the alias's name in // SNI and the certificate check. .{ .url_fmt = "https://alias.test:{d}/aliased", .expected = "http_3 /aliased" }, // An `http` URL, which the record upgrades (§9.5) -- to a port that // speaks only TLS, so it could not have worked as written. .{ .url_fmt = "http://origin.test:{d}/upgraded", .expected = "http_3 /upgraded" }, // No record: TCP, and ALPN's choice. .{ .url_fmt = "https://plain.test:{d}/plain", .expected = "http_2 /plain" }, }; inline for (cases) |case| { const url = try std.fmt.bufPrint(&buffer, case.url_fmt, .{port}); var body: Io.Writer.Allocating = .init(gpa); defer body.deinit(); var result = client.fetch(.{ .location = .{ .url = url }, .response_writer = &body.writer, }) catch |err| { std.debug.print("{s}: {t}\n", .{ url, err }); return err; }; defer result.deinit(); try testing.expectEqualStrings(case.expected, body.written()); } // And it was DNS that said all of this: the zone was asked. try testing.expect(zone.queries > 0);}