Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Ending a connection: RFC 9000 §10 and §20.//!//! Three ways a QUIC connection ends, and they are not variations on one//! theme. It can be **closed immediately** (§10.2), which means saying so in a//! CONNECTION_CLOSE frame; it can **time out** (§10.1), which means both ends//! forget about it without a word; or it can be **stateless reset** (§10.3),//! which is what an endpoint that has lost its state says to a peer that has//! not. This implements the first two.//!//! ## Why there are two states after the end//!//! Because packets are still arriving. §10.2 puts it as "the closing and//! draining connection states exist to ensure that connections close cleanly//! and that delayed or reordered packets are properly discarded" — an//! endpoint that freed everything the instant it sent a CONNECTION_CLOSE//! would then meet the packets already in flight with no idea what they were.//!//! **Closing** is what an endpoint enters after sending the frame: it answers//! any packet it can attribute to the connection by repeating the frame, in//! case the first one was lost, and it does nothing else. **Draining** is what//! it enters after *receiving* one: the peer has already said everything it//! is going to, so this state sends nothing at all. Both last about three//! probe timeouts, and §10.2 is explicit that the point of the wait is late//! packets rather than anything either end still has to say.//!//! The asymmetry matters: §10.2.2 warns that an endpoint which answered a//! CONNECTION_CLOSE with another one could produce "a constant exchange of//! CONNECTION_CLOSE frames until one of the endpoints exits the closing//! state". Draining is the state that cannot do that.
const std = @import("std");
const recovery = @import("recovery.zig");
/// §20.1's transport error codes.////// These travel in a CONNECTION_CLOSE frame of type 0x1c and describe the/// transport itself. The application variant, 0x1d, carries codes that belong/// to whatever is running over QUIC — DNS over QUIC's own, for instance — and/// this enumeration says nothing about those.pub const Code = enum(u64) { no_error = 0x00, internal_error = 0x01, connection_refused = 0x02, flow_control_error = 0x03, stream_limit_error = 0x04, stream_state_error = 0x05, final_size_error = 0x06, frame_encoding_error = 0x07, transport_parameter_error = 0x08, connection_id_limit_error = 0x09, protocol_violation = 0x0a, invalid_token = 0x0b, application_error = 0x0c, crypto_buffer_exceeded = 0x0d, key_update_error = 0x0e, aead_limit_reached = 0x0f, no_viable_path = 0x10, /// RFC 9368 §10.2: the two ends' Version Information does not agree /// with the version the connection is using. version_negotiation_error = 0x11, _,
/// §20.1: "CRYPTO_ERROR (0x0100-0x01ff): The cryptographic handshake /// failed. A range of 256 values is reserved for carrying error codes /// specific to the cryptographic handshake that is used." /// /// The 256 values are TLS's own alert codes, carried through unchanged, /// which is how a QUIC endpoint reports "the certificate was bad" without /// QUIC having to know what a certificate is. pub fn crypto(tls_alert: u8) Code { return @enumFromInt(0x0100 + @as(u64, tls_alert)); }
/// The TLS alert inside a CRYPTO_ERROR, if this is one. pub fn alert(c: Code) ?u8 { const value = @intFromEnum(c); if (value < 0x0100 or value > 0x01ff) return null; return @intCast(value - 0x0100); }};
/// §10.2's two states, plus the one before them.pub const State = enum { /// Nothing has ended. open, /// A CONNECTION_CLOSE has been sent. §10.2.1: answer any packet /// attributable to this connection by repeating it, in case it was lost, /// and do nothing else. closing, /// A CONNECTION_CLOSE has been received. §10.2.2: "an endpoint in the /// draining state MUST NOT send any packets." draining, /// The wait is over and the state may be discarded. closed,};
/// §10.2: "These states SHOULD persist for at least three times the current/// PTO interval."pub const close_timeout_multiplier: u64 = 3;
/// What an endpoint remembers about a connection that has ended.pub const Closing = struct { state: State = .open, /// The code to send, or the one the peer sent. code: Code = .no_error, /// §19.19: "the type of frame that triggered the error", or null when no /// frame did — a value of zero, which the frame encodes explicitly. frame_type: ?u64 = null, /// Whether this is the application variant (0x1d) rather than the /// transport one (0x1c). application: bool = false, /// A reason phrase, copied because the frame that carried it points into /// a datagram buffer the caller will reuse. reason_buf: [64]u8 = undefined, reason_len: usize = 0, /// When the closing or draining state ends. deadline: recovery.Instant = 0, /// How many packets have arrived since the last CONNECTION_CLOSE was /// sent, which §10.2.1 wants a limit built on: "An endpoint SHOULD limit /// the rate at which it generates packets in the closing state. For /// instance, an endpoint could wait for a progressively increasing number /// of received packets or amount of time before responding." since_sent: u32 = 0, /// The next count of received packets that will earn an answer. It /// doubles each time, so a peer that keeps sending gets a reply that /// costs progressively less — and a connection cannot be turned into a /// packet amplifier by a peer that ignores the close. next_answer: u32 = 1,
pub fn reason(c: *const Closing) []const u8 { return c.reason_buf[0..c.reason_len]; }
/// Enters the closing state, ready to send. pub fn close(c: *Closing, code: Code, frame_type: ?u64, why: []const u8, deadline: recovery.Instant) void { if (c.state != .open) return; c.state = .closing; c.code = code; c.frame_type = frame_type; c.deadline = deadline; c.setReason(why); // The first packet is owed immediately, without waiting to be asked. c.since_sent = 0; c.next_answer = 0; }
/// Enters the draining state, having heard the peer say it is over. /// /// §10.2.2 permits one last CONNECTION_CLOSE before this, and this does /// not send one: an endpoint that answers every close with a close is how /// §10.2.2's "constant exchange" happens, and the peer already knows. pub fn drain(c: *Closing, code: Code, application: bool, why: []const u8, deadline: recovery.Instant) void { if (c.state == .draining or c.state == .closed) return; // §10.2.2: "An endpoint MAY enter the draining state from the closing // state... In this case, the draining state ends when the closing // state would have ended" — the deadline already set stands. if (c.state == .open) c.deadline = deadline; c.state = .draining; c.code = code; c.application = application; c.setReason(why); }
fn setReason(c: *Closing, why: []const u8) void { // §19.19's Reason Phrase is "additional diagnostic information", // written by the peer and shown to a human. It is truncated rather // than refused: a peer that sends a long one is being verbose, not // hostile, and there is nothing to be gained by ending the connection // twice. const len = @min(why.len, c.reason_buf.len); @memcpy(c.reason_buf[0..len], why[0..len]); c.reason_len = len; }
/// Notes that a packet arrived while the connection was ending. pub fn onPacket(c: *Closing) void { c.since_sent +|= 1; }
/// Whether a CONNECTION_CLOSE should go out now. /// /// §10.2.1's rate limit, as the progressively increasing number of /// received packets it suggests. §10.2.2 is the other half: a draining /// endpoint sends nothing, ever. pub fn owesClose(c: *const Closing) bool { if (c.state != .closing) return false; return c.since_sent >= c.next_answer; }
/// Notes that one has gone out. pub fn onSent(c: *Closing) void { c.since_sent = 0; c.next_answer = if (c.next_answer == 0) 1 else c.next_answer *| 2; }
/// Whether the wait is over. pub fn expired(c: *const Closing, now: recovery.Instant) bool { return c.state != .open and now >= c.deadline; }};
const testing = std.testing;
test "RFC 9000 20.1: a TLS alert travels as a CRYPTO_ERROR" { // "A range of 256 values is reserved for carrying error codes specific to // the cryptographic handshake that is used", which is how QUIC reports a // bad certificate without knowing what a certificate is. try testing.expectEqual(@as(u64, 0x0100), @intFromEnum(Code.crypto(0))); // 42 is TLS's bad_certificate. try testing.expectEqual(@as(u64, 0x012a), @intFromEnum(Code.crypto(42))); try testing.expectEqual(@as(?u8, 42), Code.crypto(42).alert());
// And an ordinary transport code is not one. try testing.expectEqual(@as(?u8, null), Code.protocol_violation.alert()); // Including one from the far end of the range, which a peer may send and // which this enumeration has no name for. try testing.expectEqual(@as(?u8, null), (@as(Code, @enumFromInt(0x0200))).alert());}
test "RFC 9000 10.2.1: the first close goes at once and the rest slow down" { // "An endpoint SHOULD limit the rate at which it generates packets in the // closing state. For instance, an endpoint could wait for a progressively // increasing number of received packets... before responding." var c: Closing = .{}; c.close(.protocol_violation, 0x08, "bad frame", 1000); try testing.expectEqual(State.closing, c.state);
// Owed immediately: the peer has not heard yet. try testing.expect(c.owesClose()); c.onSent(); try testing.expect(!c.owesClose());
// One more packet earns one more answer. c.onPacket(); try testing.expect(c.owesClose()); c.onSent();
// The next costs two, then four: a peer that ignores the close gets an // answer that costs progressively less, which is what stops a closed // connection being a packet amplifier. c.onPacket(); try testing.expect(!c.owesClose()); c.onPacket(); try testing.expect(c.owesClose()); c.onSent();
for (0..3) |_| c.onPacket(); try testing.expect(!c.owesClose()); c.onPacket(); try testing.expect(c.owesClose());}
test "RFC 9000 10.2.2: a draining endpoint sends nothing" { // "An endpoint that receives a CONNECTION_CLOSE frame MAY send a single // packet containing a CONNECTION_CLOSE frame before entering the draining // state... An endpoint MUST NOT send further packets. Doing so could // result in a constant exchange of CONNECTION_CLOSE frames until one of // the endpoints exits the closing state." var c: Closing = .{}; c.drain(.no_error, false, "goodbye", 1000); try testing.expectEqual(State.draining, c.state); try testing.expectEqualStrings("goodbye", c.reason());
for (0..100) |_| { c.onPacket(); try testing.expect(!c.owesClose()); }}
test "RFC 9000 10.2.2: draining from closing keeps the deadline it had" { // "An endpoint MAY enter the draining state from the closing state if it // receives a CONNECTION_CLOSE frame... In this case, the draining state // ends when the closing state would have ended." var c: Closing = .{}; c.close(.protocol_violation, null, "mine", 1000); c.drain(.no_error, false, "theirs", 9999);
try testing.expectEqual(State.draining, c.state); try testing.expectEqual(@as(recovery.Instant, 1000), c.deadline); // And it stops talking, which is the whole reason to move. c.onPacket(); try testing.expect(!c.owesClose());
try testing.expect(!c.expired(999)); try testing.expect(c.expired(1000));}
test "a reason phrase written by a peer is truncated, not refused" { // §19.19's Reason Phrase is diagnostic text the peer chose. A long one is // verbosity rather than an attack, and there is nothing to be gained by // ending a connection that is already ending. var c: Closing = .{}; var long: [500]u8 = @splat('x'); c.drain(.internal_error, false, &long, 10); try testing.expectEqual(@as(usize, 64), c.reason().len);}
test "an endpoint that has already closed does not close again" { // The first reason is the true one: whatever happened afterwards happened // to a connection that was already ending. var c: Closing = .{}; c.close(.flow_control_error, null, "first", 500); c.close(.internal_error, null, "second", 900); try testing.expectEqual(Code.flow_control_error, c.code); try testing.expectEqualStrings("first", c.reason()); try testing.expectEqual(@as(recovery.Instant, 500), c.deadline);}