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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One HTTP/3 connection, on one QUIC connection.//!//! Smaller than the HTTP/2 driver rather than larger, and the difference is//! all the things that are no longer here. There is no connection preface to//! read, because QUIC's handshake is one. No flow control, no WINDOW_UPDATE,//! no stream table and no MAX_CONCURRENT_STREAMS, because a QUIC connection//! already has all of that and §4.6 of RFC 9114 says so outright. No//! RST_STREAM, because QUIC has one. No writer lock, because a QUIC stream is//! independent of every other and there is no single byte stream to serialise//! onto -- which was the largest single piece of the HTTP/2 driver.//!//! What is left is three unidirectional streams that carry the connection's//! own business, and a task per request.//!//! ## The streams//!//! §6.2: each unidirectional stream begins with a varint saying what it is.//! Both ends open a control stream (0x00) and the two QPACK streams (0x02 and//! 0x03); §4.2 of RFC 9204 requires the QPACK pair to exist even when, as//! here, they will never carry anything. A stream of an unknown type is//! abandoned rather than refused (§6.2), which is the same "ignore what you//! do not know" rule the frame layer has and exists so that extensions can be//! deployed without a flag day.//!//! §6.2.1 is the sharp edge: the control stream "MUST NOT be closed", and//! either end closing one is H3_CLOSED_CRITICAL_STREAM. A second control//! stream is H3_STREAM_CREATION_ERROR. Neither can happen by accident, which//! is exactly why they are worth checking -- a peer doing either is either//! broken or probing.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;
const quic = @import("quic");
const protocol = @import("../protocol.zig");const transport = @import("../transport.zig");const Handler = @import("../server/Handler.zig");const Request = @import("../server/Request.zig");const Response = @import("../server/Response.zig");const compression = @import("../server/compression.zig");const Headers = protocol.Headers;const Status = protocol.Status;
const frame = @import("frame.zig");const qpack = @import("qpack.zig");const request_builder = @import("../field/request.zig");
const log = std.log.scoped(.http3);
const Connection = @This();
pub const Config = struct { /// §7.2.4.1: the largest field section this server will decode, before /// compression. A section over it is one request's problem and gets a /// 431, not a connection error -- §4.2.2 of RFC 9114 says so, and the /// reasoning is the same as HTTP/2's: RST_STREAM would tell the client /// "nothing happened, try again", which it would, for ever. max_field_section_size: u32 = 16 * 1024, /// How much of a request body to hold. A QUIC stream has its own flow /// control underneath this; what this bounds is the arena above it. max_body_len: usize = 1 << 20, /// How many field lines one request may carry. max_fields: usize = 64, /// RFC 9220: whether to advertise `SETTINGS_ENABLE_CONNECT_PROTOCOL`, /// which is what lets a client send an extended CONNECT and so what lets /// a WebSocket run over HTTP/3. /// /// RFC 9220 is three pages and most of them are about what it does *not* /// change: the setting has the same identifier as RFC 8441's, the request /// has the same shape, and the answer is the same `2xx`. What differs is /// that there is no stream to be careful about -- see `upgrade`. enable_connect_protocol: bool = true, /// Whether to code a response body, and how. Null is a server that does /// not compress; the same `server.compression.Config` the other two /// drivers take, because a content coding is the representation's and not /// the version's. compression: ?compression.Config = null, /// Whether to undo a content coding on a request body before the handler /// sees it. The same option the other two drivers take. request_decoding: ?compression.RequestDecoding = null,};
io: Io,gpa: Allocator,session: transport.Session,handler: Handler,config: Config,/// §6.2.1: one control stream in each direction, and they may not close.control_out: ?transport.Stream = null,control_in_seen: bool = false,/// §7.2.4: SETTINGS must be the first frame on the control stream, and this/// is how "must" is checked.peer_settings_seen: bool = false,/// §5.2: the stream identifier this endpoint named in the GOAWAY it sent, or/// null while it has sent none.////// "The identifier in a GOAWAY frame... indicates the highest-numbered/// request... that might have been processed", and a request at or above it/// was not -- which is what makes a graceful shutdown safe to retry against.sent_goaway: ?u64 = null,/// §2.1 of RFC 9000: the next client-initiated bidirectional stream this/// endpoint has not seen, which is what a GOAWAY names.next_request_stream: u64 = 0,/// §7.2.6: the identifier in the last GOAWAY the peer sent. A second one may/// only name something lower.peer_goaway: ?u64 = null,/// §7.2.7: the last MAX_PUSH_ID the peer sent, which a later one may not go/// below. Nothing else is done with it, because this server does not push;/// it is kept because the rule about the sequence is a rule whether or not/// the permission is ever used.peer_max_push_id: ?u64 = null,tasks: Io.Group = .init,mutex: Io.Mutex = .init,
/// Serves one connection until the peer goes away.pub fn init( io: Io, gpa: Allocator, session: transport.Session, handler: Handler, config: Config,) Connection { return .{ .io = io, .gpa = gpa, .session = session, .handler = handler, .config = config, };}
/// Serves one connection until the peer goes away.////// Separate from `init` so that whoever is serving can hold a pointer to the/// connection while it runs -- which is what `Listener.shutdown` needs, since/// a GOAWAY has to reach a connection that is in the middle of its work.pub fn run(c: *Connection) void { const io = c.io; const session = c.session; // Every stream task has returned before this frame goes away, which // matters because they point into it. defer c.tasks.cancel(io);
// §6.2: the control streams cannot be opened until the peer has said how // many streams this endpoint may open, and it says so in its transport // parameters -- which arrive with the handshake. Opening them any earlier // is a STREAM_LIMIT_ERROR against a limit that is zero because nothing // has been negotiated yet. if (!session.waitEstablished()) return;
c.openControlStreams() catch |err| { log.debug("could not open the control streams: {s}", .{@errorName(err)}); return; };
while (session.accept()) |stream| { // §5.2: a request that arrives at or above the identifier this // endpoint named in its GOAWAY was not processed, and saying so is // the whole value of a graceful shutdown -- a client that is told // H3_REQUEST_REJECTED knows it may send the request again somewhere // else, where a connection that simply closed leaves it guessing // whether the request happened. if (c.refuses(stream.id)) { c.reject(stream); continue; }
// §6.1: a bidirectional stream from a client is a request. A // unidirectional one says what it is in its first varint, and // reading that is itself blocking, so it happens on a task rather // than in this loop -- a peer that opened a stream and sent nothing // would otherwise stop every request behind it. c.tasks.concurrent(io, runStream, .{ c, stream }) catch { // §4.1: "the server MAY abort the stream", and REQUEST_REJECTED // is the code that means nothing happened and another connection // would do. c.reject(stream); }; }
c.tasks.await(io) catch {};}
fn runStream(c: *Connection, stream: transport.Stream) void { if (stream.id.directionality() == .bidirectional) { c.mutex.lockUncancelable(c.io); c.next_request_stream = @max(c.next_request_stream, stream.id.value + 4); c.mutex.unlock(c.io); } if (stream.id.directionality() == .unidirectional) { c.serveUnidirectional(stream); } else { c.serveRequest(stream); }}
/// §5.2: whether a request on this stream is one this endpoint has already/// said it would not process.fn refuses(c: *Connection, id: quic.stream.Id) bool { const last = c.sent_goaway orelse return false; if (id.directionality() != .bidirectional) return false; return id.value >= last;}
fn reject(c: *Connection, stream: transport.Stream) void { // §4.1.2: "the server MAY abort the stream", and H3_REQUEST_REJECTED is // the code that means nothing happened here and another connection would // do. It is the one answer a client can act on without having to know // whether the request took effect. c.abort(stream, .request_rejected);}
/// Ends one request stream without answering it, which is what §4.1.2 calls a/// stream error: the connection and every other request on it are unaffected.////// Both halves, because a QUIC stream has two and resetting one says nothing/// about the other. Without the STOP_SENDING a client that is still uploading/// a request body has been told its answer will never come and not told to/// stop asking, so it goes on paying for octets this server has already/// decided to discard -- which §4.1 puts as "a server can abort reading the/// request stream".fn abort(c: *Connection, stream: transport.Stream, code: frame.Error) void { c.session.resetStream(stream.id, @intFromEnum(code)); c.session.stopSending(stream.id, @intFromEnum(code));}
/// §5.2: begins a graceful shutdown.////// The identifier named is the next request stream this endpoint has not yet/// seen, so everything already in flight is finished and everything after it/// is refused with a code the client can retry on. §2.1 of RFC 9000 numbers/// client-initiated bidirectional streams 0, 4, 8..., which is why the step/// is four rather than one.////// §5.2 describes doing this twice -- an initial GOAWAY naming the largest/// possible identifier, to stop new requests while leaving time for those in/// flight, then a second naming the real cut-off. This sends the cut-off/// directly, which is the same guarantee in one frame: what is in flight/// finishes, and nothing new is taken.pub fn shutdown(c: *Connection) void { c.mutex.lockUncancelable(c.io); defer c.mutex.unlock(c.io);
const control = c.control_out orelse return; const last = c.next_request_stream; // §7.2.6: "an endpoint MAY send multiple GOAWAY frames indicating // different identifiers, but the identifier in each frame MUST NOT be // greater than the identifier in any previous frame." if (c.sent_goaway) |already| { if (last >= already) return; } c.sent_goaway = last;
var buffer: [32]u8 = undefined; var w = control.writer(&buffer); var body: [8]u8 = undefined; var bw: Io.Writer = .fixed(&body); writeVarint(&bw, last) catch return;
var header: [16]u8 = undefined; const n = frame.write(&header, .goaway, bw.buffered().len) catch return; w.interface.writeAll(header[0..n]) catch return; w.interface.writeAll(bw.buffered()) catch return; w.interface.flush() catch return;}
/// §4.1: a request stream carries a HEADERS frame, then the body, then/// nothing.////// This is where the four-layer claim gets its third test, and the first/// against a transport that is not a byte stream. What goes in is a QUIC/// stream and a QPACK field section; what comes out is the same `Request`/// and `Response` a handler has been written against since HTTP/1.0, built/// by the same `field.request` the HTTP/2 driver uses.fn serveRequest(c: *Connection, stream: transport.Stream) void { var arena_state: std.heap.ArenaAllocator = .init(c.gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
var read_buffer: [4096]u8 = undefined; var r = stream.reader(&read_buffer);
// §4.1: "an HTTP message (request or response) consists of... the header // field section... followed by zero or more DATA frames". So the first // frame decides whether this is a request at all. const header = c.readFrameHeader(&r.interface) catch return; if (header.kind != .headers) { // §4.1: a request stream that opens with anything else. DATA before // HEADERS is the case worth naming, because it is what a client that // has lost track of its own framing produces. c.close(.frame_unexpected, "a request stream did not open with HEADERS"); return; } if (header.length > c.config.max_field_section_size) { // §4.2.2: one request's problem, and the answer is a status rather // than a reset -- a reset says "nothing happened, try again", which // the client would, for ever. c.respondStatus(stream, .request_header_fields_too_large); return; }
const section = arena.alloc(u8, @intCast(header.length)) catch return; // All of it, not whatever has arrived. A QUIC stream delivers what it // has, and a field section large enough to span two datagrams would // otherwise be read short and abandoned without a word -- which is a // failure that depends on timing, so it is absent on a loopback socket // and present on a network. r.interface.readSliceAll(section) catch return;
var fields: [64]qpack.Field = undefined; var scratch: [8192]u8 = undefined; const n = qpack.decode(section, fields[0..@min(fields.len, c.config.max_fields)], &scratch) catch |err| { // §6 of RFC 9204 gives every one of these the same code, because a // field section that cannot be decoded leaves the connection unable // to decode any later one either -- there is no per-stream recovery // from a compression failure, which is the price of a shared table // even when, as here, the table is empty. log.debug("could not decode the field section: {s}", .{@errorName(err)}); c.close(.qpack_decompression_failed, "the field section did not decode"); return; };
// Into the shape `field.request` reads, which is the same list the HTTP/2 // driver hands it. var list: std.ArrayList(protocol.Field) = .empty; for (fields[0..n]) |f| { const name = arena.dupe(u8, f.name) catch return; const value = arena.dupe(u8, f.value) catch return; list.append(arena, .{ .name = name, .value = value }) catch return; }
// §4.1: the body is whatever DATA frames follow, so the handler cannot be // handed the stream itself -- it would read the next frame's type and // length as the first two octets of the message. var body_reader: BodyReader = .init(c, &r.interface); var req = request_builder.build( c.io, arena, &list, .{ .secure = true, .alpn = "h3" }, body: { const plain: Request.Body = .{ .reader = &body_reader.interface, .length = .unknown, }; const decoding = c.config.request_decoding orelse break :body plain; // §8.4: undone before the handler when asked, and the failure is // answered rather than hidden -- coded octets reaching a handler // that was promised decoded ones is a wrong answer, not an error. const decoded = compression.decodeRequest( arena, decoding, protocol.Headers.initBorrowed(list.items).get("content-encoding"), plain.reader, plain.length, ) catch { // The same answer `build`'s own `OutOfMemory` gets three // lines below: give the stream up rather than hand a handler // coded octets it was told would be decoded. c.abort(stream, .internal_error); return; }; break :body .{ .reader = decoded.reader, .length = decoded.length }; }, .{ .version = .http_3, .extended_connect = c.config.enable_connect_protocol, }, ) catch |err| switch (err) { // §4.1.2: a malformed request "MUST be treated as a stream error of // type H3_MESSAGE_ERROR", which is one request rather than the // connection -- the thing HTTP/1.1 cannot do. // // A `400` would be friendlier and is what this used to send, but it // is not what the rule says, and the difference is not cosmetic: a // status code is a claim that the request was understood well enough // to be answered, and a field name this server has rejected as // unreadable is by definition one it did not understand. HTTP/2 has // always reset here, for the same reason. error.Malformed => { c.abort(stream, .message_error); return; }, error.NotImplemented => { c.respondStatus(stream, .not_implemented); return; }, error.OutOfMemory => return, };
var out_buffer: [4096]u8 = undefined; var state: ResponseState = .{ .connection = c, .stream = stream, .writer = stream.writer(&out_buffer), }; state.connect_protocol = req.connect_protocol; state.reader = &body_reader.interface;
var res: Response = .{ .headers = .empty, .arena = arena, .version = .http_3, .context = &state, .vtable = &response_vtable, .accept_encoding = req.headers.get("accept-encoding"), .compress = c.config.compression, };
c.handler.serve(&req, &res) catch |err| { log.debug("handler failed for {s} {s}: {s}", .{ req.method.name, req.target.raw, @errorName(err), }); if (res.state == .head) c.respondStatus(stream, .internal_server_error); return; };
switch (res.state) { .head => res.send("") catch {}, .body => res.end() catch {}, .ended => {}, // §5 of RFC 8441, which RFC 9220 inherits: "orderly TCP-level // closures are represented as END_STREAM flags". The handler has // stopped speaking whatever it was speaking, so the tunnel closes the // way a socket would -- which here means ending the QUIC stream, // because that is what says where a stream stops. .upgraded => state.writer.finish() catch {}, }}
/// §4.1: the request body, which is the payloads of the DATA frames that/// follow the HEADERS frame and nothing else.////// The frame headers between them are why a handler cannot simply be handed/// the stream: it would read a type and a length as the first two octets of/// the message, and every DATA frame after the first would splice two more/// into the middle of it. HTTP/2's driver has the same job and does not look/// like this, because there the frames arrive on a connection shared with/// every other stream and are taken apart before they reach a stream at all.const BodyReader = struct { interface: Io.Reader, source: *Io.Reader, /// The connection, so that a frame which has no business on a request /// stream can end it. §7.2 makes those connection errors rather than /// stream errors, which is a judgement about what they mean: a peer /// sending SETTINGS down a request stream has lost track of which stream /// is which, and nothing else it says can be trusted either. connection: *Connection, /// What is left of the DATA frame being read. remaining: u64 = 0, /// Whether the stream has ended or something on it was not a DATA frame. finished: bool = false,
fn init(connection: *Connection, source: *Io.Reader) BodyReader { return .{ .interface = .{ .vtable = &.{ .stream = streamImpl }, .buffer = &.{}, .seek = 0, .end = 0, }, .source = source, .connection = connection, }; }
fn streamImpl(io_reader: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const b: *BodyReader = @alignCast(@fieldParentPtr("interface", io_reader)); if (b.finished) return error.EndOfStream;
while (b.remaining == 0) { const kind = readVarint(b.source) catch { b.finished = true; return error.EndOfStream; }; const length = readVarint(b.source) catch { b.finished = true; return error.EndOfStream; }; const f: frame.Kind = @enumFromInt(kind); switch (f) { .data => b.remaining = length, // §4.1: trailers, which are read and discarded the way // HTTP/1.1's chunked trailers are -- a handler has no way to // ask for them, so delivering them would be inventing an // interface rather than implementing one. .headers => { b.source.discardAll64(length) catch {}; b.finished = true; return error.EndOfStream; }, else => { // §7.2: SETTINGS, GOAWAY, MAX_PUSH_ID and CANCEL_PUSH // belong to the control stream, and §7.2.5 says a server // "MUST treat the receipt of a PUSH_PROMISE frame as a // connection error of type H3_FRAME_UNEXPECTED". An // unknown type is a different thing entirely and is // stepped over, per §7.2.8. if (!f.allowedOnRequestStream()) { b.connection.close( .frame_unexpected, "a control frame on a request stream", ); b.finished = true; return error.EndOfStream; } b.source.discardAll64(length) catch { b.finished = true; return error.EndOfStream; }; }, } }
const take = @min(b.remaining, limit.toInt() orelse b.remaining); const n = b.source.stream(w, .limited64(take)) catch |err| switch (err) { error.EndOfStream => { b.finished = true; return error.EndOfStream; }, else => |e| return e, }; b.remaining -= n; return n; }};
/// What a response needs to know: which stream it is going out on, and the/// writer it is going out through.const ResponseState = struct { connection: *Connection, stream: transport.Stream, writer: transport.Stream.Writer, body: BodyWriter = undefined, /// RFC 9220: the `:protocol` the client asked for, if it sent one. connect_protocol: ?[]const u8 = null, /// The reader the handler gets when the stream becomes a tunnel. reader: ?*Io.Reader = null, /// What the body writer buffers into, so that a handler writing a line at /// a time does not spend a datagram on each line. body_buffer: [4096]u8 = undefined, /// Whether `body` has been initialised, which decides whether there is /// anything for `end` to flush. A response with no body never touches it, /// and flushing an undefined writer is a crash rather than a no-op. body_begun: bool = false,};
/// §7.2.1: the body, as DATA frames.////// One frame per drain rather than one per write, and nothing reaches the/// socket until the buffer fills or the handler flushes. The first version of/// this did the opposite -- no buffer, a frame per write, and a flush at the/// end of every one -- on the argument that a handler writing a line at a/// time is doing so on purpose and a driver should not decide otherwise for/// it. The argument is wrong twice over.////// It is wrong about this library, whose HTTP/1.1 driver buffers a body the/// same way and whose own demonstration server calls `flush` explicitly when/// it wants a line to leave -- so a handler already says when it means it,/// and the ones that do not were being charged for a decision they never/// made. And it is wrong about the cost, which is not the three octets of/// frame header it counted: every write became its own datagram. A megabyte/// written in sixty-six octet lines left as fifteen thousand packets of a/// hundred and seventeen octets, against the nine hundred a full-sized/// datagram needs, and the connection spent its time on packet headers,/// authentication tags and acknowledgements. It ran at two megabytes a/// second where the same handler over HTTP/1.1 ran at six hundred.////// A handler that means each line to leave on its own still gets exactly/// that, because `flush` is implemented here rather than inherited: it/// empties this buffer *and* the stream's, so an explicit flush reaches the/// wire. That is a stronger promise than the HTTP/1.1 driver makes.const BodyWriter = struct { interface: Io.Writer, state: *ResponseState, /// Whether a drain sends what it wrote instead of leaving it for the next /// one. A response batches; a tunnel does not, because a tunnel carries a /// conversation and an octet held back waiting for company is a peer /// waiting for an answer that has been written and not sent. when: When,
const When = enum { batched, at_once };
fn init(state: *ResponseState, buffer: []u8, when: When) BodyWriter { return .{ .interface = .{ .vtable = &.{ .drain = drain, .flush = flushAll }, .buffer = buffer, }, .state = state, .when = when, }; }
/// Writes what is buffered here and whatever `data` adds, as one DATA /// frame, and leaves it in the stream writer rather than sending it. fn drain(io_writer: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize { const b: *BodyWriter = @alignCast(@fieldParentPtr("interface", io_writer));
const buffered = io_writer.buffered(); const from_data = Io.Writer.countSplat(data, splat); if (buffered.len + from_data == 0) return 0;
try b.write(buffered, data, splat, buffered.len + from_data); io_writer.end = 0; if (b.when == .at_once) try b.state.writer.interface.flush(); return from_data; }
/// Empties this writer and the stream's, which is what makes an explicit /// `flush` in a handler mean "send this now" rather than "move it to /// another buffer". fn flushAll(io_writer: *Io.Writer) Io.Writer.Error!void { const b: *BodyWriter = @alignCast(@fieldParentPtr("interface", io_writer));
const buffered = io_writer.buffered(); if (buffered.len != 0) { try b.write(buffered, &.{}, 0, buffered.len); io_writer.end = 0; } try b.state.writer.interface.flush(); }
/// One frame header, then the octets it counted. fn write( b: *BodyWriter, buffered: []const u8, data: []const []const u8, splat: usize, total: usize, ) Io.Writer.Error!void { const out = &b.state.writer.interface;
var header: [16]u8 = undefined; const n = frame.write(&header, .data, total) catch return error.WriteFailed; try out.writeAll(header[0..n]);
if (buffered.len != 0) try out.writeAll(buffered); if (data.len == 0) return; for (data[0 .. data.len - 1]) |bytes| try out.writeAll(bytes); const pattern = data[data.len - 1]; for (0..splat) |_| try out.writeAll(pattern); }};
const response_vtable: Response.VTable = .{ .beginBody = beginBody, .end = endBody, .sendInterim = sendInterim, .upgrade = upgrade,};
/// RFC 9220: hands the stream over, once the client has asked for a protocol/// this handler is willing to speak.////// The same exchange as RFC 8441's over HTTP/2 -- a `:protocol` in the/// request, a `2xx` rather than a `101`, and the stream becomes the tunnel --/// and simpler than either of the versions before it, for a reason worth/// stating.////// Over HTTP/1.1 an upgrade has to refuse when the request body has not been/// read, because those octets sit in the byte stream *in front of* the new/// protocol's first octet and handing the stream over would corrupt it. Over/// HTTP/2 that check is unnecessary because DATA frames are framed/// separately. Here it is unnecessary for a stronger reason: the request body/// and the tunnel are the same QUIC stream, delivered in order by the/// transport, so there is nothing to be in front of anything and nothing for/// this function to check.fn upgrade(res: *Response, protocol_name: []const u8) Response.UpgradeError!Response.Upgrade { const state: *ResponseState = @ptrCast(@alignCast(res.context.?)); const c = state.connection;
if (!c.config.enable_connect_protocol) return error.UpgradeUnavailable;
// RFC 9110 §7.8's rule with RFC 8441's spelling, which RFC 9220 inherits // unchanged: a server may not switch to a protocol the client did not ask // for, and here the asking is `:protocol` rather than an `Upgrade` field. const offered = state.connect_protocol orelse return error.NotOffered; if (!protocol.token.eqlIgnoreCase(offered, protocol_name)) return error.NotOffered;
// §5.1 of RFC 8441: `200`, not `101`. There is nothing to switch -- the // stream becomes the tunnel the moment a 2xx goes out -- and the driver // picks the status rather than the handler, the same way the HTTP/1.1 // side picks `101`. writeFieldSection(state, .ok, &res.headers, null) catch return error.WriteFailed;
// A body of no particular length, which is what a tunnel is, and one // that sends what it is given rather than waiting for more of it. state.body = .init(state, &.{}, .at_once); state.body_begun = true; return .{ .input = state.reader orelse return error.WriteFailed, .output = &state.body.interface, };}
fn beginBody(res: *Response, length: protocol.Length) Response.Error!*Io.Writer { const state: *ResponseState = @ptrCast(@alignCast(res.context.?)); try writeHead(state, res, length); // §4.1: the body goes out as DATA frames, so what the handler gets is a // writer that puts a frame header in front of what it is given rather // than the stream itself. state.body = .init(state, &state.body_buffer, .batched); state.body_begun = true; return &state.body.interface;}
fn endBody(res: *Response) Response.Error!void { const state: *ResponseState = @ptrCast(@alignCast(res.context.?)); // Whatever the handler wrote last and did not flush. Before the trailers, // because §4.1 puts the second field section after the content and a // trailer that overtook the end of the body would describe something the // recipient had not been given yet. if (state.body_begun) state.body.interface.flush() catch return error.WriteFailed; try sendTrailers(state, res); state.writer.finish() catch return error.WriteFailed;}
/// RFC 9114 §4.1: the trailer section, which is a second HEADERS frame after/// the DATA frames.////// Simpler again than HTTP/2's, which needs END_STREAM on the frame: here the/// end of the trailer section is the end of the QUIC stream, and the stream/// ends because the writer finishes it. One framing layer fewer, which is the/// pattern the whole driver has.fn sendTrailers(state: *ResponseState, res: *Response) Response.Error!void { if (res.trailers.fields.items.len == 0) return;
var fields: [64]qpack.Field = undefined; var count: usize = 0; for (res.trailers.fields.items) |f| { if (count == fields.len) break; // §6.5.1 of RFC 9110, and §4.1's own rule that a trailer section has // no pseudo-headers in it. if (Response.isForbiddenTrailer(f.name)) continue; if (f.name.len > 0 and f.name[0] == ':') continue; fields[count] = .{ .name = f.name, .value = f.value }; count += 1; } if (count == 0) return;
var section: [4096]u8 = undefined; var sw: Io.Writer = .fixed(§ion); qpack.encode(&sw, fields[0..count]) catch return error.WriteFailed; const body = sw.buffered();
var header: [16]u8 = undefined; const n = frame.write(&header, .headers, body.len) catch return error.WriteFailed; state.writer.interface.writeAll(header[0..n]) catch return error.WriteFailed; state.writer.interface.writeAll(body) catch return error.WriteFailed; state.writer.interface.flush() catch return error.WriteFailed;}
fn sendInterim(res: *Response, status: protocol.Status, headers: *const Headers) Response.Error!void { const state: *ResponseState = @ptrCast(@alignCast(res.context.?)); // §4.1: an informational response is a HEADERS frame like any other, and // more of them may follow. Which is what makes `103 Early Hints` work // here and over HTTP/2, where HTTP/1.0 silently drops it. try writeFieldSection(state, status, headers, null);}
/// §4.1: the status and the fields, as one HEADERS frame.fn writeHead(state: *ResponseState, res: *Response, length: protocol.Length) Response.Error!void { const declared: ?u64 = switch (length) { .exact => |n| n, .none => 0, .unknown => null, }; try writeFieldSection(state, res.status, &res.headers, declared);}
fn writeFieldSection( state: *ResponseState, status: protocol.Status, headers: *const Headers, content_length: ?u64,) Response.Error!void { var fields: [64]qpack.Field = undefined; var count: usize = 0;
var status_text: [3]u8 = undefined; _ = std.fmt.bufPrint(&status_text, "{d}", .{@intFromEnum(status)}) catch return error.WriteFailed; fields[count] = .{ .name = ":status", .value = &status_text }; count += 1;
var length_text: [20]u8 = undefined; if (content_length) |n| { const text = std.fmt.bufPrint(&length_text, "{d}", .{n}) catch return error.WriteFailed; fields[count] = .{ .name = "content-length", .value = text }; count += 1; }
for (headers.fields.items) |field| { if (count == fields.len) break; // §4.2: "an endpoint MUST NOT generate an HTTP/3 field section // containing connection-specific fields", and the driver owns the // rest of these -- a handler that set `content-length` would be // setting it twice, and one that set `connection` would be describing // a hop that does not exist. if (isDriverField(field.name)) continue; if (field.name.len > 0 and field.name[0] == ':') continue; fields[count] = .{ .name = field.name, .value = field.value }; count += 1; }
var section: [8192]u8 = undefined; var sw: Io.Writer = .fixed(§ion); qpack.encode(&sw, fields[0..count]) catch return error.WriteFailed; const body = sw.buffered();
var header: [16]u8 = undefined; const n = frame.write(&header, .headers, body.len) catch return error.WriteFailed; state.writer.interface.writeAll(header[0..n]) catch return error.WriteFailed; state.writer.interface.writeAll(body) catch return error.WriteFailed; state.writer.interface.flush() catch return error.WriteFailed;}
/// The fields this driver writes itself, which a handler may not.////// The same list as the HTTP/2 driver's, and for a sharper reason here:/// §4.2 of RFC 9114 makes a connection-specific field a malformed message/// rather than merely useless, because HTTP/3 has no hop for one to describe.fn isDriverField(name: []const u8) bool { const managed = [_][]const u8{ "content-length", "transfer-encoding", "connection", "keep-alive", "upgrade", "proxy-connection", }; for (managed) |m| { if (std.ascii.eqlIgnoreCase(name, m)) return true; } return false;}
fn respondStatus(c: *Connection, stream: transport.Stream, status: protocol.Status) void { var out_buffer: [1024]u8 = undefined; var state: ResponseState = .{ .connection = c, .stream = stream, .writer = stream.writer(&out_buffer), }; const empty: Headers = .empty; writeFieldSection(&state, status, &empty, 0) catch return; state.writer.finish() catch {};}
fn readFrameHeader(c: *Connection, r: *Io.Reader) !frame.Header { _ = c; const kind = try readVarint(r); const length = try readVarint(r); return .{ .kind = @enumFromInt(kind), .length = length, .header_len = 0 };}
/// §6.2: opens this endpoint's control stream and the two QPACK streams.fn openControlStreams(c: *Connection) !void { const control = try c.session.openUnidirectional(); c.control_out = control;
var buffer: [64]u8 = undefined; var w = control.writer(&buffer);
// §6.2: the stream type, then §7.2.4's SETTINGS, which "MUST be sent as // the first frame" on it. try writeVarint(&w.interface, @intFromEnum(frame.StreamType.control)); try writeSettings(&w.interface, c.config); try w.interface.flush();
// §4.2 of RFC 9204: both QPACK streams have to exist, even though this // encoder never inserts and so never sends anything on either. A peer // that waited for them before encoding would wait for ever. inline for (.{ frame.StreamType.qpack_encoder, frame.StreamType.qpack_decoder }) |kind| { const s = try c.session.openUnidirectional(); var b: [8]u8 = undefined; var sw = s.writer(&b); try writeVarint(&sw.interface, @intFromEnum(kind)); try sw.interface.flush(); }}
fn writeSettings(w: *Io.Writer, config: Config) !void { // Two settings and a body built first, because §7.2.4's frame carries its // length in front of it and the length is not known until the pairs are. var body: [32]u8 = undefined; var bw: Io.Writer = .fixed(&body); // §7.2.4.1. try writeVarint(&bw, 0x06); // SETTINGS_MAX_FIELD_SECTION_SIZE try writeVarint(&bw, config.max_field_section_size); // RFC 9204 §5: zero, which is this decoder saying it will keep no dynamic // table and so no peer may insert into one. try writeVarint(&bw, 0x01); // SETTINGS_QPACK_MAX_TABLE_CAPACITY try writeVarint(&bw, 0); try writeVarint(&bw, 0x07); // SETTINGS_QPACK_BLOCKED_STREAMS try writeVarint(&bw, 0); // RFC 9220 §3: the same identifier RFC 8441 gave it for HTTP/2, which is // the whole of what that document had to say about the wire. if (config.enable_connect_protocol) { try writeVarint(&bw, 0x08); // SETTINGS_ENABLE_CONNECT_PROTOCOL try writeVarint(&bw, 1); }
const payload = bw.buffered(); var header: [16]u8 = undefined; const n = try frame.write(&header, .settings, payload.len); try w.writeAll(header[0..n]); try w.writeAll(payload);}
fn writeVarint(w: *Io.Writer, value: u64) !void { var buf: [8]u8 = undefined; const written = quic.varint.write(&buf, value); try w.writeAll(written);}
/// §6.2: a unidirectional stream says what it is in its first varint.fn serveUnidirectional(c: *Connection, stream: transport.Stream) void { var buffer: [1024]u8 = undefined; var r = stream.reader(&buffer);
const kind = readVarint(&r.interface) catch return; switch (@as(frame.StreamType, @enumFromInt(kind))) { .control => { // §6.2.1: "only one control stream per peer", and a second is // H3_STREAM_CREATION_ERROR. if (c.control_in_seen) { c.close(.stream_creation_error, "a second control stream"); return; } c.control_in_seen = true; c.readControl(&r.interface); }, // RFC 9204 §4.2: they exist and carry nothing, because this decoder // advertised no table for the peer to describe. Anything at all on // the encoder stream is an insertion into a table that was refused. // // Both are as critical as the control stream, and for the same // reason: "closing either unidirectional stream type MUST be treated // as a connection error of type H3_CLOSED_CRITICAL_STREAM". A peer // that ends one has ended the compression context the connection is // still using, whatever it may have meant by it. .qpack_encoder => { if (r.interface.takeByte()) |_| { c.close(.qpack_encoder_stream_error, "an insertion into a table of zero capacity"); } else |err| switch (err) { error.EndOfStream => c.close( .closed_critical_stream, "the peer closed its QPACK encoder stream", ), else => {}, } }, // Nothing this encoder sends can be acknowledged, since nothing it // sends uses a dynamic table, so the instructions here are read only // to notice the stream ending. .qpack_decoder => { _ = r.interface.discardRemaining() catch return; c.close(.closed_critical_stream, "the peer closed its QPACK decoder stream"); }, // §4.6: "a server MUST treat receipt of a push stream as a connection // error of type H3_STREAM_CREATION_ERROR", since a client has no // business pushing to a server. .push => c.close(.stream_creation_error, "a client push stream"), // §6.2: "recipients of unknown stream types MUST either abort reading // of the stream or discard incoming data without further processing" // -- the same tolerance the frame layer has, and for the same reason. _ => {}, }}
/// §7.2.4: reads the peer's SETTINGS, then whatever else the control stream/// carries.fn readControl(c: *Connection, r: *Io.Reader) void { while (true) { // A read that fails is not the same as a stream that ended, and the // difference decides whether the peer has broken a rule or the // connection has simply gone. Reporting the second as the first sends // whoever reads the log looking for a protocol violation that never // happened, which is a worse bug than it looks: the line is the only // thing they have. const kind = readVarint(r) catch |err| switch (err) { error.EndOfStream => break, else => return, }; const length = readVarint(r) catch |err| switch (err) { error.EndOfStream => break, else => return, };
const f: frame.Kind = @enumFromInt(kind); if (!f.allowedOnControlStream()) { c.close(.frame_unexpected, "a request frame on the control stream"); return; } // §7.2.4: "if the first frame of the control stream is any other // frame type, this MUST be treated as a connection error of type // H3_MISSING_SETTINGS." if (!c.peer_settings_seen) { if (f != .settings) { c.close(.missing_settings, "the control stream did not open with SETTINGS"); return; } c.peer_settings_seen = true; } else if (f == .settings) { // §7.2.4: "SETTINGS frames MUST NOT be sent subsequently." c.close(.frame_unexpected, "a second SETTINGS frame"); return; }
// §7.2.6: a GOAWAY, which is the one control frame a server has to // check rather than step over. if (f == .goaway) { if (!c.onGoaway(r, length)) return; continue; }
// §7.2.3: "if a server receives a CANCEL_PUSH frame for a push ID // that has not yet been mentioned by a PUSH_PROMISE frame, this MUST // be treated as a connection error of type H3_ID_ERROR". This server // has never mentioned one and never will, so there is no push ID a // client can legitimately cancel and no value to read before saying // so. if (f == .cancel_push) { c.close(.id_error, "a CANCEL_PUSH for a push that was never promised"); return; }
// §7.2.7: "a MAX_PUSH_ID frame cannot reduce the maximum push ID". if (f == .max_push_id) { if (!c.onMaxPushId(r, length)) return; continue; }
// Nothing here acts on a setting yet: what a peer will accept // changes what an encoder may send, and this encoder sends the least // it can in every case. The frame is still read to the end, because // a stream is a stream and the next frame begins where this one // stops. r.discardAll64(length) catch return; }
// §6.2.1: "the sender MUST NOT close the control stream, and the receiver // MUST NOT request that the sender close it. If either control stream is // closed at any point, this MUST be treated as a connection error of type // H3_CLOSED_CRITICAL_STREAM." c.close(.closed_critical_stream, "the peer closed its control stream");}
/// §16 of RFC 9000's variable-length integer, read from a stream.////// The first two bits say how many octets there are, which is what makes this/// readable without a lookahead -- and `readSliceAll` for the rest, because a/// varint can straddle whatever boundary the stream happened to deliver on./// §7.2.6: a GOAWAY from the client.////// False when the connection has been closed over it, so the caller stops/// reading. Two things are checked, and both are H3_ID_ERROR:////// The identifier a *client* sends is a push ID, not a stream ID -- "a client/// MUST send a push ID that is... the GOAWAY frame from a server contains a/// stream ID". This server promises no pushes, so the only push ID it can/// honestly have processed is none at all, and any value is acceptable to/// note and act on by not pushing, which it was not going to do.////// And a second GOAWAY may only name something lower: "the identifier in each/// frame MUST NOT be greater than the identifier in any previous frame". An/// increasing one would be a peer taking back a promise it had already made/// about what it would not accept, which is the one thing the frame exists to/// make reliable.fn onGoaway(c: *Connection, r: *Io.Reader, length: u64) bool { if (length == 0 or length > 8) { c.close(.frame_error, "a GOAWAY that is not one identifier"); return false; } const id = readVarint(r) catch { c.close(.frame_error, "a truncated GOAWAY"); return false; }; if (c.peer_goaway) |already| { if (id > already) { c.close(.id_error, "a GOAWAY naming a higher identifier than the last"); return false; } } c.peer_goaway = id;
// §5.2: the client is shutting down, so this endpoint stops taking new // requests from it as well. Not required of a server -- the frame is about // what the *client* will accept -- but a client that has said it is going // away is not one to start new work with, and answering the requests // already in flight is what both ends want. c.mutex.lockUncancelable(c.io); const last = c.next_request_stream; c.mutex.unlock(c.io); if (c.sent_goaway == null) { c.sent_goaway = last; } return true;}
fn readVarint(r: *Io.Reader) !u64 { return (try readVarintSized(r)).value;}
/// The same, and how many octets it took.////// §16 of RFC 9000 lets an encoder choose any width that holds the value, so/// the width cannot be worked back from the value -- and a frame whose body/// is one identifier is only well formed if that identifier fills it, which/// is a comparison nothing can make without this.fn readVarintSized(r: *Io.Reader) !struct { value: u64, len: usize } { const first = try r.takeByte(); const extra: usize = @as(usize, 1) << @as(u2, @intCast(first >> 6)); var buf: [8]u8 = undefined; buf[0] = first; if (extra > 1) try r.readSliceAll(buf[1..extra]); const parsed = try quic.varint.parse(buf[0..extra]); return .{ .value = parsed.value, .len = extra };}
/// §7.2.7: a client raising the number of pushes it would accept, which this/// server answers by continuing not to push.////// The frame is still checked, because the rule is about the sequence rather/// than about pushing: a value below the last one is H3_ID_ERROR whether or/// not either end ever intended to use the permission.fn onMaxPushId(c: *Connection, r: *Io.Reader, length: u64) bool { const got = readVarintSized(r) catch { c.close(.frame_error, "a truncated MAX_PUSH_ID"); return false; }; // §7.1: a frame body with anything in it beyond the fields the type // defines is H3_FRAME_ERROR. if (got.len != length) { c.close(.frame_error, "a MAX_PUSH_ID that is not one identifier"); return false; } if (c.peer_max_push_id) |already| { if (got.value < already) { c.close(.id_error, "a MAX_PUSH_ID smaller than the last"); return false; } } c.peer_max_push_id = got.value; return true;}
fn close(c: *Connection, code: frame.Error, why: []const u8) void { log.debug("connection error {s}: {s}", .{ @tagName(code), why }); c.session.close(@intFromEnum(code), why);}
test { std.testing.refAllDecls(@This());}