// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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 @fromBackingInt(@intCast(0x0100 + @as(u64, tls_alert))); } test crypto { // A handshake that failed with TLS's handshake_failure, 40, closes // the connection with 0x0128. const code: Code = .crypto(40); try std.testing.expectEqual(@as(u64, 0x0128), @backingInt(code)); } /// The TLS alert inside a CRYPTO_ERROR, or null for any code outside /// §20.1's 0x0100-0x01ff -- which is how a caller holding a peer's /// CONNECTION_CLOSE tells "the certificate was bad" from every other /// reason a connection can end. pub fn alert(c: Code) ?u8 { const value = @backingInt(c); if (value < 0x0100 or value > 0x01ff) return null; return @intCast(value - 0x0100); } test alert { // 0x0133 is TLS's decrypt_error, 51, travelling as a CRYPTO_ERROR. const from_peer: Code = @fromBackingInt(0x0133); try std.testing.expectEqual(@as(?u8, 51), from_peer.alert()); // A transport error is not a TLS alert at all. try std.testing.expectEqual(@as(?u8, null), Code.flow_control_error.alert()); } }; /// §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, /// The reason phrase this end gave, or the one the peer did, cut to the /// first 64 octets. /// /// Borrowed from this `Closing`, and changed by the next `close` or /// `drain` that takes effect. Diagnostic text and nothing more: §19.19 /// says it "SHOULD be a UTF-8 encoded string", which is not the same as /// a peer having written one, so a caller that shows it to a person /// checks first. pub fn reason(c: *const Closing) []const u8 { return c.reason_buf[0..c.reason_len]; } test reason { var c: Closing = .{}; c.drain(.no_error, true, "server shutting down", 3_000_000_000); try std.testing.expectEqualStrings("server shutting down", c.reason()); } /// Enters the closing state, owing a CONNECTION_CLOSE at once. /// /// `deadline` is the instant the closing state ends -- by §10.2, now /// plus `close_timeout_multiplier` probe timeouts -- and `why` is copied, /// truncated to 64 octets. Only the first call does anything: a /// connection that is already closing or draining keeps the reason it /// ended for, because whatever went wrong afterwards went wrong with a /// connection that was already ending. /// /// This leaves `application` as it was, which for a fresh `Closing` is /// the transport variant (0x1c). A caller closing with an application /// error code sets `application` itself afterwards. 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; } test close { // A STREAM frame (type 0x08) broke a rule: close, and keep the frame // type for the CONNECTION_CLOSE that says so. var c: Closing = .{}; c.close(.stream_state_error, 0x08, "send on a receive-only stream", 3_000_000); try std.testing.expectEqual(State.closing, c.state); try std.testing.expectEqual(@as(?u64, 0x08), c.frame_type); // The frame is owed before any packet has asked for it. try std.testing.expect(c.owesClose()); } /// Enters the draining state, having heard the peer say it is over. /// /// `code`, `application` and `why` are what the peer's CONNECTION_CLOSE /// carried, and replace whatever this end had recorded; `why` is copied /// and truncated to 64 octets. `deadline` is used only when coming from /// `open`: from `closing`, the deadline already set stands. A connection /// already draining or closed is left alone. /// /// §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); } test drain { // The peer sent an application CONNECTION_CLOSE (0x1d) with code 0. var c: Closing = .{}; c.drain(.no_error, true, "bye", 3_000_000); try std.testing.expectEqual(State.draining, c.state); try std.testing.expect(c.application); // A draining endpoint never sends, however many packets arrive. c.onPacket(); try std.testing.expect(!c.owesClose()); } 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, which is /// what earns a closing endpoint the right to repeat itself. Harmless in /// any other state: only `owesClose` reads the count, and only while /// closing. pub fn onPacket(c: *Closing) void { c.since_sent +|= 1; } test onPacket { var c: Closing = .{}; c.close(.protocol_violation, null, "", 1000); c.onSent(); try std.testing.expect(!c.owesClose()); // The peer has evidently not heard: one more of its packets earns a // repeat. c.onPacket(); try std.testing.expect(c.owesClose()); } /// 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; } test owesClose { var c: Closing = .{}; try std.testing.expect(!c.owesClose()); // open: nothing to say c.close(.no_error, null, "done", 1000); try std.testing.expect(c.owesClose()); } /// Notes that a CONNECTION_CLOSE has gone out, and doubles the number of /// received packets the next one will cost. pub fn onSent(c: *Closing) void { c.since_sent = 0; c.next_answer = if (c.next_answer == 0) 1 else c.next_answer *| 2; } test onSent { var c: Closing = .{}; c.close(.no_error, null, "done", 1000); c.onSent(); // the first, owed at once c.onPacket(); c.onSent(); // the first repeat, for one packet // The next costs two. c.onPacket(); try std.testing.expect(!c.owesClose()); c.onPacket(); try std.testing.expect(c.owesClose()); } /// Whether the closing or draining period is over at `now`, so that the /// connection's state may be discarded. Always false while `open`. /// /// This only answers: it does not move the state to `closed`, which is /// the caller's to do once it has acted on the answer. pub fn expired(c: *const Closing, now: recovery.Instant) bool { return c.state != .open and now >= c.deadline; } test expired { var c: Closing = .{}; try std.testing.expect(!c.expired(std.math.maxInt(recovery.Instant))); c.close(.no_error, null, "done", 5000); try std.testing.expect(!c.expired(4999)); try std.testing.expect(c.expired(5000)); } }; 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), @backingInt(Code.crypto(0))); // 42 is TLS's bad_certificate. try testing.expectEqual(@as(u64, 0x012a), @backingInt(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, @fromBackingInt(@intCast(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); }