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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! HTTPS, both ways round: a TCP listener with a TLS handshake in front of//! every connection it accepts, and a dialler with one in front of every//! connection it opens.//!//! The two halves are the same file because they are the same job seen from//! either end, and they meet in `Connection.wrap`: everything after the//! handshake is identical, and what differs is only whether this end was//! proving who it is or deciding whom to believe.//!//! Nothing above this knows. `transport.Connection` already says whether a//! channel is confidential and what was negotiated over it, so a driver reads//! and writes exactly as it does over a plain socket, and `server.Server`//! chooses HTTP/2 or HTTP/1.1 from `Info.alpn` without a line of it being//! about TLS. That is why this file is short: the seam it fits was designed//! for it long before it existed, and `Info.secure` and `Info.alpn` have been//! sitting there with nothing to fill them in.//!//! ## ALPN is the whole of how HTTP/2 gets selected//!//! §3.1 of RFC 9113 gives HTTP/2 over TLS the identifier `h2`, and there is//! no other way in: the `PRI ` preface only works on a cleartext port, and//! §3.2's `Upgrade` was removed. So a server that does not offer `h2` in its//! ALPN list is a server no browser will speak HTTP/2 to, whatever else it//! supports.
const std = @import("std");const Io = std.Io;const net = Io.net;const Allocator = std.mem.Allocator;
const tls = @import("tls");const http = @import("http");const transport = http.transport;const tcp = @import("tcp.zig");
/// The certificate and key a listener answers with. Re-exported so that a/// caller does not have to name the TLS library to configure one.pub const CertKeyPair = tls.config.CertKeyPair;
/// The trust a client checks a server's chain against, re-exported for the/// same reason. It is `std.crypto.Certificate.Bundle`, which has `rescan` for/// the system store; `certBundleFromFilePath` is the one-file case.pub const CertBundle = tls.config.cert.Bundle;
/// Reads a bundle of trusted certificates out of one PEM file.pub const certBundleFromFilePath = tls.config.cert.fromFilePath;
pub const Options = struct { /// The certificate chain and its private key. auth: *CertKeyPair, /// What to offer in ALPN, in preference order. /// /// The default offers HTTP/2 ahead of HTTP/1.1, which is what a browser /// expects and what this library can serve. A caller that does not want /// HTTP/2 removes it here rather than turning the driver off, because /// what is advertised and what is served disagreeing is a client that /// selects `h2` and is answered in HTTP/1.1. alpn_protocols: []const []const u8 = &.{ "h2", "http/1.1" }, /// Where randomness for the handshake comes from. rng: std.Random, /// Options for the socket underneath. tcp: tcp.Listener.Options = .{},};
pub const Listener = struct { inner: tcp.Listener, options: Options,
pub const ListenError = tcp.Listener.ListenError;
/// Starts listening, as `tcp.Listener.listen` does; the handshake happens /// on each accept, not here. /// /// `options` is kept, and what it points at -- the certificate and key, /// the ALPN list, the random number generator -- is borrowed, so it has /// to outlive the listener. pub fn listen(io: Io, address: net.IpAddress, options: Options) ListenError!Listener { return .{ .inner = try tcp.Listener.listen(io, address, options.tcp), .options = options, }; }
test listen { const io = testing.io; var auth: CertKeyPair = try .fromSlice(testing.allocator, io, test_cert_pem, test_key_pem); defer auth.deinit(testing.allocator); var prng: std.Random.DefaultPrng = .init(1);
var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random(), }); defer l.deinit(io); try testing.expect(l.localAddress().getPort() != 0); }
/// Closes the listening socket. Connections already accepted are their /// own, and are not closed by this. pub fn deinit(l: *Listener, io: Io) void { l.inner.deinit(io); l.* = undefined; }
test deinit { const io = testing.io; var auth: CertKeyPair = try .fromSlice(testing.allocator, io, test_cert_pem, test_key_pem); defer auth.deinit(testing.allocator); var prng: std.Random.DefaultPrng = .init(1);
var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); l.deinit(io); }
/// Where this listener is, with the port the kernel chose when the one /// asked for was zero. pub fn localAddress(l: *const Listener) net.IpAddress { return l.inner.localAddress(); }
test localAddress { const io = testing.io; const gpa = testing.allocator; var auth: CertKeyPair = try .fromSlice(gpa, io, test_cert_pem, test_key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(1); var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io);
var group: Io.Group = .init; defer group.cancel(io); group.concurrent(io, greetOne, .{&l}) catch return error.SkipZigTest;
// Which is the address a client dials to reach it. var client_prng: std.Random.DefaultPrng = .init(2); var conn = try connect(io, gpa, l.localAddress(), .{ .host = "localhost", .root_ca = auth.bundle, .rng = client_prng.random(), }); defer conn.close(io, gpa); try testing.expectEqual(l.localAddress().getPort(), conn.info.peer.?.port()); }
/// Makes an accept in progress return `error.ListenerClosed`, and every /// accept after it; see `tcp.Listener.shutdown`. pub fn shutdown(l: *Listener, io: Io) void { l.inner.shutdown(io); }
test shutdown { const io = testing.io; var auth: CertKeyPair = try .fromSlice(testing.allocator, io, test_cert_pem, test_key_pem); defer auth.deinit(testing.allocator); var prng: std.Random.DefaultPrng = .init(1); var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io);
l.shutdown(io); try testing.expectError(error.ListenerClosed, l.listener().accept(io, testing.allocator, .{})); }
/// The transport-level view of this listener, which is what /// `server.Server` takes. Each accept runs the server's half of a TLS /// handshake, and one that fails is `error.ConnectionAborted` -- that /// client's problem, and not a reason to stop accepting. It borrows `l`, /// which must not move while it is in use. pub fn listener(l: *Listener) transport.Listener { return .{ .context = l, .vtable = &vtable }; }
test listener { const io = testing.io; const gpa = testing.allocator; var auth: CertKeyPair = try .fromSlice(gpa, io, test_cert_pem, test_key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(1); var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io);
// The client's half of the handshake, which has to run at the same // time as the accept below. const Dial = struct { fn run(address: net.IpAddress, trust: CertBundle, rng: std.Random) void { var conn = connect(testing.io, testing.allocator, address, .{ .host = "localhost", .root_ca = trust, .rng = rng, }) catch return; defer conn.close(testing.io, testing.allocator); conn.output.writeAll("hello") catch return; conn.output.flush() catch return; } }; var client_prng: std.Random.DefaultPrng = .init(2); var group: Io.Group = .init; defer group.cancel(io); group.concurrent(io, Dial.run, .{ l.localAddress(), auth.bundle, client_prng.random() }) catch return error.SkipZigTest;
var accepted = try l.listener().accept(io, gpa, .{}); defer accepted.close(io, gpa); // Confidential, and HTTP/1.1 by ALPN, since that is all the client // offered. try testing.expect(accepted.info.secure); try testing.expectEqualStrings("http/1.1", accepted.info.alpn.?); try testing.expectEqualStrings("hello", try accepted.input.take(5)); }
const vtable: transport.Listener.VTable = .{ .accept = acceptImpl, .shutdown = shutdownImpl, .localAddress = localAddressImpl, .establish = establishImpl, };
fn acceptImpl( context: ?*anyopaque, io: Io, gpa: Allocator, options: transport.Listener.Options, ) transport.Listener.AcceptError!transport.Connection { const l: *Listener = @ptrCast(@alignCast(context.?)); // Through the seam rather than around it: the plain listener's own // accept is what knows how to turn a socket into a connection. The // handshake is `establishImpl`'s, in the connection's own task, so // that a client which connects and never sends a ClientHello holds // up nobody but itself. return l.inner.listener().accept(io, gpa, options); }
fn establishImpl( context: ?*anyopaque, io: Io, gpa: Allocator, plain: transport.Connection, ) transport.Listener.AcceptError!transport.Connection { const l: *Listener = @ptrCast(@alignCast(context.?)); var owned = plain; errdefer owned.close(io, gpa); return Connection.open(gpa, io, plain, l.options) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A handshake that does not complete is this connection's // problem and nobody else's: a client offering nothing this // server accepts, a scan, or a plaintext request to a TLS port. // §6.2 of RFC 8446 has the alert already sent by the time this // returns, so what is left is to forget the connection. error.HandshakeFailed => return error.ConnectionAborted, error.Canceled => return error.Canceled, }; }
fn shutdownImpl(context: ?*anyopaque, io: Io) void { const l: *Listener = @ptrCast(@alignCast(context.?)); l.shutdown(io); }
fn localAddressImpl(context: ?*anyopaque) ?transport.Endpoint { const l: *Listener = @ptrCast(@alignCast(context.?)); return .fromStdAddress(l.inner.localAddress()); }};
/// What a client has to settle before it will believe an answer.////// The mirror of `Options` and deliberately not the same struct: a server/// proves who it is and a client decides whom to believe, so beyond the socket/// underneath the two have almost nothing in common.pub const ClientOptions = struct { /// The name to ask for, which is also the name the certificate has to /// carry. It travels as SNI, and it is not simply the address because one /// address serves many names — which is the whole reason SNI exists, and /// the reason a caller that dialled an address still has to say what it /// expects to find there. /// /// A bare address here almost certainly fails the check, and that is /// worth knowing before it costs an afternoon: verification goes through /// `std.crypto.Certificate.Parsed.verifyHostName`, which compares this /// against the certificate's dNSName entries and its common name. It does /// not read iPAddress entries at all, so a certificate issued for /// `IP:127.0.0.1` — which is what `openssl req -addext` writes, and what /// curl accepts — is not matched by `127.0.0.1` here. Give the name the /// certificate was issued for, and dial whatever address you like. host: []const u8, /// Where the trust for that check comes from. /// /// Empty by default, which fails every connection closed until a caller /// says what it trusts: `std.crypto.Certificate.Bundle` has `rescan` for /// the system store and `addCertsFromFilePath` for one file. Empty and /// trusting nothing is the right default for a library — a client that /// silently trusted whatever the machine happened to hold would be making /// that decision on the caller's behalf. The type is the one zig-quic's /// client takes, so a bundle loaded once serves an HTTP/3 connection and /// this one both. root_ca: tls.config.cert.Bundle = .{ .bytes = .empty, .map = .empty }, /// For a test, and named so that it cannot be set by accident. insecure_skip_verify: bool = false, /// What to offer in ALPN, in preference order. /// /// HTTP/1.1 alone, because that is the driver this dials for. Offering /// `h2` would be asking for a protocol the caller may have no driver /// ready to speak, and what is advertised disagreeing with what is spoken /// is the same fault at this end as at the server's. An empty list sends /// no ALPN extension at all, which is what to pass when talking to /// something that does not expect one. alpn_protocols: []const []const u8 = &.{"http/1.1"}, /// Where randomness for the handshake comes from. rng: std.Random, /// Options for the socket underneath. Its buffers are raised to what a /// handshake needs — see `connect`. tcp: transport.Listener.Options = .{},};
pub const ConnectError = net.IpAddress.ConnectError || Allocator.Error || Io.Cancelable || error{HandshakeFailed};
/// The smallest read buffer a connection may have for a TLS handshake to be/// run over it: one whole record, which `tls.client` asserts rather than/// checks.pub const min_read_buffer_len = tls.input_buffer_len;/// And the smallest write buffer, which is the ClientHello: 1572 octets plus/// the host name, rounded up to what the library asserts.pub const min_write_buffer_len = 2048;
pub const ConnectOverError = error{ OutOfMemory, HandshakeFailed, /// The connection's buffers are smaller than `min_read_buffer_len` and /// `min_write_buffer_len`. Checked here because the TLS library asserts /// it, and an assertion is a crash rather than an answer. BufferTooSmall,} || Io.Cancelable;
/// Puts a TLS handshake on a connection that is already open -- a tunnel/// through a proxy, which is the case this is for, or anything else a/// `transport.Connection` can be.////// Takes ownership of `plain`: it is closed on failure, and closing the/// connection returned closes it as well. `options.tcp` is not used, since/// there is no socket to make -- so the buffers `plain` already has are the/// ones the handshake runs through, and they have to be at least/// `min_read_buffer_len` and `min_write_buffer_len` (more for a host name/// longer than about 450 octets), or this is `error.BufferTooSmall`.pub fn connectOver( io: Io, gpa: Allocator, plain: transport.Connection, options: ClientOptions,) ConnectOverError!transport.Connection { var owned = plain; errdefer owned.close(io, gpa); if (plain.input.buffer.len < min_read_buffer_len or plain.output.buffer.len < @max(min_write_buffer_len, 1600 + options.host.len)) { return error.BufferTooSmall; } return Connection.dial(gpa, io, plain, options);}
test connectOver { const io = testing.io; const gpa = testing.allocator; var auth: CertKeyPair = try .fromSlice(gpa, io, test_cert_pem, test_key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(1); var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io); var group: Io.Group = .init; defer group.cancel(io); group.concurrent(io, greetOne, .{&l}) catch return error.SkipZigTest;
// A plain connection first -- a tunnel through a proxy, in real use -- // with buffers a handshake fits in. const plain = try tcp.connect(io, gpa, l.localAddress(), .{ .read_buffer_len = min_read_buffer_len, .write_buffer_len = min_write_buffer_len, }); var client_prng: std.Random.DefaultPrng = .init(2); var conn = try connectOver(io, gpa, plain, .{ .host = "localhost", .root_ca = auth.bundle, .rng = client_prng.random(), }); defer conn.close(io, gpa); try testing.expect(conn.info.secure); try testing.expectEqualStrings("hello", try conn.input.take(5));}
/// Dials a server and puts a TLS handshake in front of the connection.////// The client half of accepting through `Listener.listener`, and deliberately/// the same return type: what a driver is handed does not depend on which end/// opened it, or on whether there is TLS underneath at all. `http1.client`/// reads and writes this exactly as it reads and writes a plain socket, and/// can learn that the channel is confidential only by asking `Info.secure` —/// which is the same division that lets one driver serve a terminated/// connection and a direct one without knowing the difference.////// The socket's buffers are raised to `min_read_buffer_len` and/// `min_write_buffer_len` where `options.tcp` asks for less, since the/// handshake runs through them.pub fn connect( io: Io, gpa: Allocator, address: net.IpAddress, options: ClientOptions,) ConnectError!transport.Connection { // The handshake runs through the socket's own buffers, and `tls.client` // *asserts* their sizes rather than reporting an error: a record is up to // `tls.input_buffer_len` octets, and a ClientHello is 1572 plus the host // name. The socket's default read buffer here is 8 KB, so a caller who // changed nothing would panic inside the TLS library rather than be told // anything. Raised rather than refused, because the number belongs to the // protocol and there is nothing useful a caller could say about it. return connectAny(io, gpa, &.{address}, options);}
test connect { const io = testing.io; const gpa = testing.allocator; var auth: CertKeyPair = try .fromSlice(gpa, io, test_cert_pem, test_key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(1); var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io); var group: Io.Group = .init; defer group.cancel(io); group.concurrent(io, greetOne, .{&l}) catch return error.SkipZigTest;
var client_prng: std.Random.DefaultPrng = .init(2); var conn = try connect(io, gpa, l.localAddress(), .{ // The name the certificate was issued for, whatever was dialled. .host = "localhost", // The only certificate trusted is the server's own. .root_ca = auth.bundle, .alpn_protocols = &.{ "h2", "http/1.1" }, .rng = client_prng.random(), }); defer conn.close(io, gpa); try testing.expect(conn.info.secure); // The server prefers `h2`, and it was offered. try testing.expectEqualStrings("h2", conn.info.alpn.?); try testing.expectEqualStrings("hello", try conn.input.take(5));}
/// `connect` for a name that resolved to several addresses: the first that/// accepts a TCP connection gets the handshake, as `tcp.connectAny` explains.////// A failed *handshake* is not retried against the next address. Every/// address a name resolves to is meant to be the same server, so a/// certificate that did not verify at one is an answer about the name rather/// than about that address -- and trying the others until one says something/// different is the shape of an attack, not of a fallback.pub fn connectAny( io: Io, gpa: Allocator, addresses: []const net.IpAddress, options: ClientOptions,) ConnectError!transport.Connection { var plain_options = options.tcp; plain_options.read_buffer_len = @max(plain_options.read_buffer_len, min_read_buffer_len); plain_options.write_buffer_len = @max(plain_options.write_buffer_len, min_write_buffer_len, 1600 + options.host.len);
var plain = try tcp.connectAny(io, gpa, addresses, plain_options); errdefer plain.close(io, gpa); return Connection.dial(gpa, io, plain, options);}
test connectAny { const io = testing.io; const gpa = testing.allocator; var auth: CertKeyPair = try .fromSlice(gpa, io, test_cert_pem, test_key_pem); defer auth.deinit(gpa); var prng: std.Random.DefaultPrng = .init(1);
// A port nothing is listening on: one a listener had, and gave back. var gone: tcp.Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); const refused = gone.localAddress(); gone.deinit(io);
var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{ .auth = &auth, .rng = prng.random() }); defer l.deinit(io); var group: Io.Group = .init; defer group.cancel(io); group.concurrent(io, greetOne, .{&l}) catch return error.SkipZigTest;
// The first address refuses the connection, so the second gets the // handshake. var client_prng: std.Random.DefaultPrng = .init(2); var conn = try connectAny(io, gpa, &.{ refused, l.localAddress() }, .{ .host = "localhost", .root_ca = auth.bundle, .rng = client_prng.random(), }); defer conn.close(io, gpa); try testing.expectEqual(l.localAddress().getPort(), conn.info.peer.?.port()); try testing.expectEqualStrings("hello", try conn.input.take(5));}
/// One TLS session over one socket, accepted or dialled.////// Boxed for the same reason the plain one is: the reader and writer hand out/// the addresses of interfaces inside this struct, so it must not move.pub const Connection = struct { /// The socket underneath, still owning its own buffers. plain: transport.Connection, session: tls.Connection, reader: tls.Connection.Reader, writer: tls.Connection.Writer, read_buffer: []u8, write_buffer: []u8, /// The negotiated protocol, copied because the handshake's own copy does /// not outlive it. alpn_buf: [32]u8 = undefined, alpn_len: usize = 0,
const OpenError = error{ OutOfMemory, HandshakeFailed, Canceled };
/// A handshake that failed, as the error to report: the task's cancel /// when that is what stopped it, since the handshake library turns every /// failed read into one of its own errors and the cancel would otherwise /// be lost -- and a client's deadline with it, leaving it to try the next /// address uncanceled. fn handshakeFailed(plain: transport.Connection) OpenError { return if (plain.canceled()) error.Canceled else error.HandshakeFailed; }
/// A server's end: a handshake that proves who this is. fn open( gpa: Allocator, io: Io, plain: transport.Connection, options: Options, ) OpenError!transport.Connection { // The handshake reads and writes the socket directly; the TLS // connection it produces is what everything after it goes through. const session = tls.server(plain.input, plain.output, .{ .auth = options.auth, .alpn_protocols = options.alpn_protocols, .rng = options.rng, .now = Io.Timestamp.now(io, .real), }) catch return handshakeFailed(plain); return wrap(gpa, plain, session); }
/// A client's end: a handshake that decides whether to believe the peer. fn dial( gpa: Allocator, io: Io, plain: transport.Connection, options: ClientOptions, ) OpenError!transport.Connection { const session = tls.client(plain.input, plain.output, .{ .host = options.host, .root_ca = options.root_ca, .insecure_skip_verify = options.insecure_skip_verify, .alpn_protocols = options.alpn_protocols, .rng = options.rng, .now = Io.Timestamp.now(io, .real), }) catch return handshakeFailed(plain); return wrap(gpa, plain, session); }
/// Everything after the handshake, which is the same whichever end did /// it: the session gets buffers of its own, and what comes back is a /// `transport.Connection` that says it is confidential and says what was /// negotiated over it. fn wrap( gpa: Allocator, plain: transport.Connection, session: tls.Connection, ) error{OutOfMemory}!transport.Connection { const c = gpa.create(Connection) catch return error.OutOfMemory; errdefer gpa.destroy(c);
// A whole record rather than a round 16 KiB, so that a second TLS // session can be run over this one -- an `https` URL through an // `https://` proxy -- without `connectOver` refusing the buffers. const read_buffer = gpa.alloc(u8, min_read_buffer_len) catch return error.OutOfMemory; errdefer gpa.free(read_buffer); const write_buffer = gpa.alloc(u8, 16 * 1024) catch return error.OutOfMemory; errdefer gpa.free(write_buffer);
c.* = .{ .plain = plain, .session = session, .reader = undefined, .writer = undefined, .read_buffer = read_buffer, .write_buffer = write_buffer, }; c.reader = c.session.reader(read_buffer); c.writer = c.session.writer(write_buffer);
if (session.alpn_protocol) |selected| { const n = @min(selected.len, c.alpn_buf.len); @memcpy(c.alpn_buf[0..n], selected[0..n]); c.alpn_len = n; }
return .{ .input = &c.reader.interface, .output = &c.writer.interface, .info = .{ .peer = plain.info.peer, .local = plain.info.local, .secure = true, .alpn = if (c.alpn_len > 0) c.alpn_buf[0..c.alpn_len] else null, }, .context = c, .vtable = &vtable, }; }
const vtable: transport.Connection.VTable = .{ .close = closeImpl, .shutdownWrite = shutdownWriteImpl, };
fn closeImpl(context: ?*anyopaque, io: Io, gpa: Allocator) void { const c: *Connection = @ptrCast(@alignCast(context.?)); // §6.1 of RFC 8446: `close_notify` says the end of the data was // meant, which is what stops a truncation from looking like one. c.session.close() catch {}; c.plain.close(io, gpa); gpa.free(c.read_buffer); gpa.free(c.write_buffer); gpa.destroy(c); }
fn shutdownWriteImpl(context: ?*anyopaque, io: Io) void { const c: *Connection = @ptrCast(@alignCast(context.?)); c.session.close() catch {}; c.plain.shutdownWrite(io); }};
test { std.testing.refAllDecls(@This());}
test "every vtable entry is compiled" { // Not a tautology, and here because it caught a real one. Zig analyzes a // function when something reaches it, and nothing reaches a vtable entry // until the vtable itself is reached -- so this file compiled, and the // whole suite passed, while `acceptImpl` called a function that did not // exist. `refAllDecls` above does not go deep enough to find it. // // Naming the tables is enough: their initializers hold the function // pointers, so analyzing them analyzes everything they point at. _ = Listener.vtable; _ = Connection.vtable;}
const testing = std.testing;
// The same pair as `tests/testdata/localhost.*.pem`: a self-signed P-256// certificate for `localhost`, good until 2126. Written out because a module// cannot embed a file from outside its own directory, and these are tests.const test_cert_pem = \\-----BEGIN CERTIFICATE----- \\MIIBljCCATugAwIBAgIUT9Cd/23KfriE8ttZNvsC7w1y9lQwCgYIKoZIzj0EAwIw \\FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MDkyNjE4MzI1OFoYDzIxMjYwOTAy \\MTgzMjU4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO \\PQMBBwNCAASvCuhUluNElHncZr24RngfDOfmayijCbPucvE1r2V745mnSIGHnakn \\s2eWgX5zuQVhbRNUycRH8hF4QQbVi3l9o2kwZzAdBgNVHQ4EFgQUATz3WW1g75zq \\PDOozbeqNmicSeMwHwYDVR0jBBgwFoAUATz3WW1g75zqPDOozbeqNmicSeMwDwYD \\VR0TAQH/BAUwAwEB/zAUBgNVHREEDTALgglsb2NhbGhvc3QwCgYIKoZIzj0EAwID \\SQAwRgIhAJSicVwe31Yq4soylh995pZBp2FziR6vP0Ff+eRXYxXdAiEA7R1Nm+PV \\BZWHzWTxa2niZ9CeBTHNyqrP169Y1XxBIEQ= \\-----END CERTIFICATE----- \\;const test_key_pem = \\-----BEGIN PRIVATE KEY----- \\MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgDWJoXM+DF25m61Er \\GOUfHutn11pB8biDvFRvYv01vyWhRANCAASvCuhUluNElHncZr24RngfDOfmayij \\CbPucvE1r2V745mnSIGHnakns2eWgX5zuQVhbRNUycRH8hF4QQbVi3l9 \\-----END PRIVATE KEY----- \\;
/// Accepts one connection and says `hello` on it, for the examples above: a/// handshake needs both ends at once, so the server's half runs as a task.fn greetOne(l: *Listener) void { var conn = l.listener().accept(testing.io, testing.allocator, .{}) catch return; defer conn.close(testing.io, testing.allocator); conn.output.writeAll("hello") catch return; conn.output.flush() catch return;}