// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One QUIC connection, with a lock around it and somewhere to send. //! //! The `quic.Connection` inside is a state machine that is not safe to touch //! from two tasks at once, and in a server it is touched by at least two: the //! endpoint's pump, which feeds it datagrams and fires its timers, and //! whatever task is serving the connection, which reads and writes streams. //! Everything here that reaches the connection does so under `mutex`, and //! everything that might have given it something to say calls `flush` before //! it returns. //! //! `arrived` is the other half. A task waiting to read is waiting for a //! datagram that will be delivered by a different task entirely, so it waits //! on a condition rather than spinning, and the pump broadcasts after every //! datagram and every timer. Broadcast rather than signal, deliberately: the //! waiters have different predicates — one wants a stream to exist, another //! wants octets on a particular stream, a third wants the handshake to //! finish — so waking one of them can wake the wrong one and stall the rest. const std = @import("std"); const Io = std.Io; const net = Io.net; const assert = std.debug.assert; const quic = @import("quic"); const ecn = @import("ecn.zig"); const Stream = @import("Stream.zig"); const Session = @This(); /// How many peer addresses one session tracks, which is what §9 migration /// needs and is bounded by what the library will hold. const max_paths = quic.path.capacity; io: Io, socket: *net.Socket, /// Nanoseconds since the endpoint's origin. The library measures durations /// and never dates (§10.1 of RFC 9000 and the whole of RFC 9002), so what it /// is given is a monotonic count from an origin it never sees. origin: Io.Timestamp, /// Undefined until `provisioned`, like `tls` below and for the same reason: a /// slot that has never carried a connection has nothing to say about one. connection: *quic.Connection, /// The buffers behind that connection, which the endpoint allocated and will /// free. Held here rather than inside the connection because the connection /// does not allocate and so cannot be the thing that frees. memory: quic.Connection.Memory, /// The `bufferBound` count this session's send window was last grown at, so /// that one refusal is acted on once rather than at every tick that follows /// it. See `Endpoint.retune`. tuned_at: u64 = 0, /// Whether the two above exist yet. /// /// A connection's buffers are the bulk of what an endpoint spends, and how /// much of it is the caller's choice -- so allocating every slot's worth /// before a single packet arrives makes the memory an endpoint holds a /// function of the connections it is *willing* to serve rather than the ones /// it is serving. A megabyte-per-stream window on a hundred permitted /// connections is gigabytes committed to answer one request. /// /// So a slot is furnished when it is first claimed, and keeps what it was /// given afterwards: the footprint follows the peak number of connections /// alive at once, and a slot that is never claimed costs nothing. Keeping /// rather than freeing on release is deliberate -- a busy endpoint would /// otherwise return a connection's buffers to the allocator and ask for them /// again microseconds later, for ever. provisioned: bool = false, /// Whether the application's task for this connection is still running. /// /// A slot has two lifetimes and is only free when both have ended: the /// connection's, which runs on past a CONNECTION_CLOSE for §10.2's closing /// period, and the task's. Freeing it when the task returned let a handler /// that gave up on a failed handshake take the closing period with it, so /// the peer's next packet found no connection and was answered with a /// stateless reset instead of the close. Freeing it when the connection /// closed let a slot be claimed again while the old task was still on its /// way out. Written by that task as it returns and read by the pump, hence /// atomic. serving: std.atomic.Value(bool) = .init(false), tls: Tls, /// This session's encoded transport parameters, which the TLS handshake reads /// while building its EncryptedExtensions -- so they have to outlive the call /// that starts it, which means living here rather than on a stack frame. parameter_bytes: [256]u8 = undefined, parameter_len: usize = 0, /// The connection ID this endpoint told the peer to use, which is what routes /// a datagram back to this session once the peer has heard it. local_id: [8]u8 = undefined, local_id_len: usize = 0, /// The connection ID the *client* invented and addressed its first packet to, /// which routes a datagram here until the client has learnt the one above. /// /// §7.2 of RFC 9000: a client "MUST change the Destination Connection ID it /// uses to the value selected by the server" -- but only once it has seen /// that value, and the first thing it sends is addressed to a value it chose /// itself. Everything a client sends before the server's first packet reaches /// it therefore carries the client's own identifier, and a server that routed /// only by what it issued would not recognise any of it. /// /// Which matters more than it sounds, because a ClientHello does not always /// fit in one packet. A client whose first flight spans two datagrams sends /// both to the identifier it chose, and an endpoint that failed to route the /// second would hand each half of the ClientHello to a *different* /// connection -- and then neither could complete a handshake, with nothing /// anywhere reporting an error. original_id: [20]u8 = undefined, original_id_len: usize = 0, /// The addresses this session has heard from, indexed by the path number the /// connection was given. §8.2 of RFC 9000 defines a path as "the 2-tuple of /// IP address and port"; this is where that 2-tuple lives, because the /// library deals in small integers and has never seen an address. peers: [max_paths]?net.IpAddress = @splat(null), /// The local socket each path leaves from, where it is not `socket`. /// /// draft-ietf-quic-multipath-21: a client's second path is a second 4-tuple, /// and the half of it that is the client's own is a second socket -- bound /// to another interface, or only another port. The peer's address is the /// same for both, so it is the socket that tells the paths apart. path_sockets: [max_paths]?*net.Socket = @splat(null), /// Taken with `lockUncancelable` everywhere, on purpose. Nothing is held /// across a blocking call -- the only I/O under it is a UDP `sendTo`, which /// does not wait for anybody -- so a cancellation point here would buy /// nothing and would leave every caller with an error to handle that can only /// mean "we were cancelled while not waiting". The cancellation point is /// `arrived.wait`, which is where a task actually stops. mutex: Io.Mutex = .init, /// Broadcast after anything that might make a waiter's question have a new /// answer: a datagram, a timer, or the connection ending. arrived: Io.Condition = .init, in_use: bool = false, /// Whether the pump has finished with this session. A reader waiting for /// octets that will now never come has to be told, or it waits for the idle /// timeout and then for ever. done: bool = false, /// The datagram being built, used only under `mutex`. outgoing: [2048]u8 = undefined, /// Nanoseconds since the endpoint's origin. pub fn now(s: *Session) u64 { const at = Io.Timestamp.now(s.io, .awake); return @intCast(@max(at.nanoseconds - s.origin.nanoseconds, 0)); } /// Sends whatever the connection has to say, until it has nothing. /// /// Called by the pump after every datagram and every timer, and by any task /// that has just given the connection something to send. The lock is taken /// here rather than by the caller because that is the rule this type exists /// to enforce: there is no path to the socket that does not go through this /// function, and no call to this function that is not under the lock. pub fn flush(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.flushLocked(); } /// A send that failed, which ends a flush: whatever is left goes with the /// next one, or is lost and found missing by loss recovery. /// /// Except that `error.Canceled` is not the socket failing but the task being /// asked to stop, and reporting it is what uses the request up. Swallowed /// here, a cancel landing on a send was lost, and a handshake it was meant /// to end waited out its whole timeout; re-armed, the next cancelation point /// -- the wait for a datagram -- reports it instead. pub fn sendFailed(io: Io, err: anyerror) void { if (err == error.Canceled) io.recancel(); } /// `flush`, for a caller that already holds the lock. pub fn flushLocked(s: *Session) void { while (true) { const at = s.now(); const datagram = s.connection.send(&s.outgoing, at) catch break orelse break; const socket = s.path_sockets[datagram.path] orelse s.socket; // n0's NAT traversal: a probe goes to a candidate address rather than // to the path's peer. const to = if (datagram.to) |address| forSocket(socket, address) else s.peers[datagram.path] orelse break; // §13.4: the connection says what the IP header's ECN field should // hold and the socket is what can set it, which is this seam. An // unmarked datagram asks for no control message at all, so the // ordinary path costs nothing. var control: ecn.Control = .{}; const ancillary = control.forSend(&to, datagram.ecn); if (ancillary.len == 0) { socket.send(s.io, &to, datagram.bytes) catch |err| return sendFailed(s.io, err); } else { var messages = [_]net.OutgoingMessage{.{ .address = &to, .data_ptr = datagram.bytes.ptr, .data_len = datagram.bytes.len, .control = ancillary, }}; socket.sendMany(s.io, &messages, .{}) catch |err| return sendFailed(s.io, err); } } } /// Writes to a stream, waiting when there is no room rather than failing. /// /// `Connection.write` is all or nothing against a fixed per-stream buffer, so /// a body larger than that buffer cannot be handed over in one call -- and /// failing would be the wrong answer, because the room is not gone but /// pending: it comes back as the peer acknowledges what has been sent and /// extends more credit (§4.1 of RFC 9000). So this is where a writer waits, /// and it is the reason the writer blocks at all. /// /// Flushing before each wait is not an optimisation. The room this is waiting /// for only appears when the octets already written reach the peer, and /// nothing else in this design will send them -- a writer that slept without /// flushing would be waiting for a consequence of an action it had not taken. pub fn writeStream(s: *Session, id: quic.stream.Id, bytes: []const u8) error{WriteFailed}!void { return s.writeStreamMaybeFinished(id, bytes, false); } /// Writes the last of a stream and ends this endpoint's half of it, in one /// packet. /// /// `writeStream` followed by `finishStream` would do the same thing and takes /// a packet more to do it: the write is flushed on its way out, so the FIN has /// nothing left to travel with and goes in a STREAM frame of its own carrying /// no data. §19.8 allows that -- a zero-length frame with the FIN bit at the /// final offset is a valid frame -- and it is still the wrong thing to send. /// /// Every other implementation puts the FIN on the frame carrying the last /// octet, and a peer that has only ever been spoken to by those is a peer that /// has never had to handle the other shape. Quad9's DNS-over-QUIC server /// answers a query whose FIN arrives with it and silently ignores one whose FIN /// arrives behind it -- no close, no reset, an acknowledgement for both packets /// and no answer -- and its DNS-over-HTTP/3 server does the same to a request. /// Both were reached by `zig-dns-client` and neither could be explained from /// this side of the wire. Sending what everybody else sends is also a packet /// cheaper, so there is nothing to weigh. pub fn writeStreamFinished(s: *Session, id: quic.stream.Id, bytes: []const u8) error{WriteFailed}!void { return s.writeStreamMaybeFinished(id, bytes, true); } /// Waits on `arrived`, with the lock held, for the callers whose answer has /// no room for `error.Canceled`: a stream's reader and writer, which can only /// say that they failed, and `accept`, `readDatagram` and `waitEstablished`, /// which can only say null or false. False when the wait was canceled. /// /// The cancelation is re-armed before that false is returned, and that is the /// point of having one function for it. A cancelation is delivered to one /// cancelation point and no more, and this is where every one of those /// callers stops -- so a wait that turned it into "failed" and nothing else /// would be the end of it, and the task that was asked to stop would go on /// with whatever it did after a failure: the next server, the next attempt. /// Re-armed, it is the caller's next cancelation point that reports it. pub fn waitArrived(s: *Session) bool { s.arrived.wait(s.io, &s.mutex) catch |err| switch (err) { error.Canceled => { s.io.recancel(); return false; }, }; return true; } fn writeStreamMaybeFinished( s: *Session, id: quic.stream.Id, bytes: []const u8, fin: bool, ) error{WriteFailed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); var at: usize = 0; while (at < bytes.len) { const chunk = @min(bytes.len - at, max_write_chunk); if (s.connection.write(id, bytes[at..][0..chunk])) { at += chunk; continue; } else |err| switch (err) { error.NoRoom => {}, else => return error.WriteFailed, } s.flushLocked(); if (s.done or s.connection.closeState() != null) return error.WriteFailed; if (!s.waitArrived()) return error.WriteFailed; } // Before the flush rather than after it, which is the whole point: the // packet builder reads the stream's send state, so a FIN set now leaves on // the frame carrying the octets above and a FIN set afterwards cannot. if (fin) s.connection.finishStream(id) catch return error.WriteFailed; s.flushLocked(); } /// How much is offered to `Connection.write` at a time. /// /// Smaller than the per-stream buffer on purpose: the call is all or nothing, /// so offering the whole buffer's worth would fail whenever anything at all /// was still outstanding, and the writer would wait for the stream to empty /// completely before making any progress at all. const max_write_chunk = 1024; /// Hands the connection a datagram that arrived from `from`. /// /// The path number is looked up or assigned here, which is the whole of what /// this type adds to `Connection.receive`: the library speaks in path /// numbers and the socket speaks in addresses, and something has to hold the /// table between them. pub fn receive(s: *Session, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const path = s.pathOf(from) orelse return; s.receiveLocked(path, datagram, from, codepoint); } /// `receive`, for a datagram that arrived on the socket of path `path` -- /// which, with the peer at one address for every path, is the only thing /// that says which path it came by. pub fn receiveOn(s: *Session, path: quic.path.Id, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.receiveLocked(path, datagram, from, codepoint); } fn receiveLocked(s: *Session, path: quic.path.Id, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { // draft-ietf-quic-address-discovery-01: the one thing the connection // cannot know for itself, and what it reports when the peer asks. s.connection.setPeerAddress(path, frameAddress(from)) catch {}; s.connection.receiveEcn(datagram, path, s.now(), codepoint) catch {}; s.flushLocked(); s.arrived.broadcast(s.io); } /// draft-ietf-quic-multipath-21 §3.1: opens a path to `peer` from `socket`, /// returning the caller's path number for it -- which datagrams arriving on /// `socket` are to be handed to `receiveOn` with -- and the multipath path /// ID the connection chose. pub fn openPath(s: *Session, socket: *net.Socket, peer: net.IpAddress) error{ NotAllowed, NoPathAvailable, TooManyPaths }!struct { route: quic.path.Id, id: u32 } { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const route: quic.path.Id = for (s.peers[1..], 1..) |seen, i| { if (seen == null) break @intCast(i); } else return error.TooManyPaths; const id = try s.connection.openPath(route, s.now()); s.peers[route] = peer; s.path_sockets[route] = socket; s.flushLocked(); return .{ .route = route, .id = id }; } /// Whether the caller's path `route` -- as `openPath` returned it -- has /// been validated (§8.2 of RFC 9000), after which it can carry data. pub fn pathValidated(s: *Session, route: quic.path.Id) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const seen = s.connection.paths.find(route) orelse return false; return seen.validated; } /// `Connection.useSendPath`, under the lock. pub fn useSendPath(s: *Session, id: u32) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.useSendPath(id); s.flushLocked(); } /// `Connection.setScheduler`, under the lock. pub fn setScheduler(s: *Session, scheduler: quic.Connection.Scheduler) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.connection.setScheduler(scheduler); } /// `Connection.abandonPath`, under the lock. pub fn abandonPath(s: *Session, id: u32) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.abandonPath(id); s.flushLocked(); } /// draft-ietf-quic-ack-frequency-14: asks the peer to acknowledge less /// often. See `Connection.requestAckFrequency`. pub fn requestAckFrequency(s: *Session, threshold: u64, max_ack_delay: u64, reordering: u64) error{ NotSupported, InvalidDelay }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.requestAckFrequency(threshold, max_ack_delay, reordering); s.flushLocked(); } /// draft-ietf-quic-ack-frequency-14: asks the peer to acknowledge now. pub fn requestImmediateAck(s: *Session) error{NotSupported}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.requestImmediateAck(); s.flushLocked(); } /// n0's NAT traversal: offers one of this endpoint's addresses to the peer. /// See `Connection.addNatAddress`. pub fn addNatAddress(s: *Session, address: net.IpAddress) error{ NotNegotiated, TooManyAddresses }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.addNatAddress(frameAddress(address)); s.flushLocked(); } /// Withdraws one. pub fn removeNatAddress(s: *Session, address: net.IpAddress) error{NotNegotiated}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.removeNatAddress(frameAddress(address)); s.flushLocked(); } /// A client starts a round of hole punching. See `Connection.startNatRound`. pub fn startNatRound(s: *Session) error{ NotNegotiated, NotClient, NoLocalAddresses }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.startNatRound(s.now()); s.flushLocked(); } /// Whether both ends asked for n0's NAT traversal, with multipath in use. pub fn natNegotiated(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.natNegotiated(); } /// `Connection.setPathStatus`, under the lock. pub fn setPathStatus(s: *Session, id: u32, status: quic.frame.PathStatus.Status) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.setPathStatus(id, status); s.flushLocked(); } /// Fires the connection's timers, but only those that are due. /// /// The distinction is the whole of this function. `Connection.onTimeout` does /// not ask whether a timer expired -- it *is* the expiry: §6.2 of RFC 9002's /// probe timeout puts the entire outstanding flight back on the wire and /// doubles the backoff, because the only reason to call it is that nothing /// has been heard. Calling it on a connection whose timer is not due /// retransmits a flight that is still perfectly in flight and doubles a /// backoff that was never triggered, which is invisible on a small exchange /// and takes a large one apart. pub fn tick(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const at = s.now(); const due = s.connection.timeout() orelse return; if (due > at) return; s.connection.onTimeout(at); s.flushLocked(); s.arrived.broadcast(s.io); } /// When this connection next wants waking, or null if it is waiting on /// nothing. pub fn timeout(s: *Session) ?u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.timeout(); } /// Says that nothing further will arrive, and wakes everything waiting. pub fn finish(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.done = true; s.arrived.broadcast(s.io); } /// The path number for an address, assigning one if this is the first time it /// has been heard from. /// /// Null when the table is full, which means a peer has been seen at more /// addresses than §9 migration needs -- the datagram is dropped rather than /// evicting a path the connection is still using. fn pathOf(s: *Session, from: net.IpAddress) ?quic.path.Id { for (&s.peers, 0..) |maybe, i| { const seen = maybe orelse continue; if (seen.eql(&from)) return @intCast(i); } for (&s.peers, 0..) |*slot, i| { if (slot.* != null) continue; slot.* = from; return @intCast(i); } // Full. A route the connection has finished with -- a candidate NAT // traversal probed that went nowhere, say -- is given to the new // address; one it is still using never is. for (s.peers[1..], 1..) |*slot, i| { const route: quic.path.Id = @intCast(i); if (s.connection.routeInUse(route)) continue; s.connection.forgetRoute(route); slot.* = from; s.path_sockets[route] = null; return route; } return null; } /// `address` as `socket` can send to it: an IPv4 address in its IPv4-mapped /// IPv6 form for an IPv6 socket, which is dual-stack and says so for every /// IPv4 peer it hears from. fn forSocket(socket: *const net.Socket, address: quic.frame.Address) net.IpAddress { if (socket.address == .ip6) switch (address.ip) { .v4 => |v4| { var mapped: [16]u8 = @splat(0); mapped[10] = 0xff; mapped[11] = 0xff; @memcpy(mapped[12..16], &v4); return .{ .ip6 = .{ .bytes = mapped, .port = address.port } }; }, .v6 => {}, }; return ipAddress(address); } // -- what the application sees --------------------------------------------- /// The next stream the peer opened that has not been handed over yet. /// /// Blocks until there is one or until the connection is finished with, so a /// caller's loop is `while (session.accept()) |stream|` and null is the end /// of it. /// /// There is no deadline, and it does not need one. §10.1 of RFC 9000 gives /// every connection an idle timeout, so a connection that has gone quiet is /// one the pump will close on its own -- at which point `done` is set and /// this returns. The same fact was a trap when writing the drivers, where /// "run until there is nothing left to do" ran until the connection timed /// out; here it is the guarantee that makes an unbounded wait safe, because /// the thing being waited for always eventually arrives or stops existing. pub fn accept(s: *Session) ?Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); while (true) { if (s.connection.accept()) |id| { return .{ .session = s, .id = id }; } if (s.done or s.connection.closeState() != null) return null; if (!s.waitArrived()) return null; } } /// RFC 9221: the next unreliable datagram, copied into `buffer`. /// /// Blocks like `accept`, and ends the same way -- null when the connection is /// finished with. A datagram is not a stream, so it does not arrive through /// `accept`, and an application that wants both runs a task for each. That is /// not a workaround: the two are genuinely independent, and an application /// that folded them into one loop would be deciding for its caller that a /// datagram may wait behind a request. pub fn readDatagram(s: *Session, buffer: []u8) ?[]u8 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); while (true) { if (s.connection.readDatagram()) |payload| { const n = @min(payload.len, buffer.len); @memcpy(buffer[0..n], payload[0..n]); s.connection.takeDatagram(); return buffer[0..n]; } if (s.done or s.connection.closeState() != null) return null; if (!s.waitArrived()) return null; } } /// RFC 9221: queues an unreliable datagram and sends it. pub fn sendDatagram(s: *Session, bytes: []const u8) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.sendDatagram(bytes); s.flushLocked(); } /// Waits for the handshake to finish. /// /// What it is for is the moment before a connection can be used at all. An /// application protocol that opens streams of its own -- HTTP/3 opens three /// before it will answer anything -- cannot open them until the peer's /// transport parameters have arrived, because those parameters are what say /// how many streams it may open (§4.6 of RFC 9000). Before the handshake /// those limits are zero and every open is a STREAM_LIMIT_ERROR, which looks /// like a bug in the application and is a bug in its timing. /// /// False when the connection ended first, which is the other thing that can /// happen to a handshake. pub fn waitEstablished(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); while (!s.connection.isEstablished()) { if (s.done or s.connection.closeState() != null) return false; if (!s.waitArrived()) return false; } return true; } /// Whether the handshake has finished. pub fn isEstablished(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.isEstablished(); } /// draft-ietf-quic-address-discovery-01: the address the peer says this /// endpoint's datagrams arrive from, or null if it has said nothing -- which /// it does only if this endpoint asked, in `address_discovery`. pub fn observedAddress(s: *Session) ?net.IpAddress { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const observed = s.connection.observedAddress() orelse return null; return ipAddress(observed); } /// A socket address as the library carries one, and back. pub fn frameAddress(a: net.IpAddress) quic.frame.Address { return switch (a) { .ip4 => |v4| .{ .ip = .{ .v4 = v4.bytes }, .port = v4.port }, .ip6 => |v6| .{ .ip = .{ .v6 = v6.bytes }, .port = v6.port }, }; } pub fn ipAddress(a: quic.frame.Address) net.IpAddress { return switch (a.ip) { .v4 => |bytes| .{ .ip4 = .{ .bytes = bytes, .port = a.port } }, .v6 => |bytes| .{ .ip6 = .{ .bytes = bytes, .port = a.port } }, }; } /// RFC 9368: the Version Information the peer sent, if it sent any. pub fn peerVersionInformation(s: *Session) ?quic.parameters.VersionInformation { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const peer = s.connection.peer orelse return null; return peer.version_information; } /// RFC 9287: how many packets from the peer arrived with the QUIC Bit clear. pub fn greasedPackets(s: *Session) u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.greasedPackets(); } /// draft-ietf-quic-multipath-21: how many paths past path 0 have been /// opened on this connection, whether or not they are still open -- and /// whether or not their slots have since been given to new path IDs. pub fn pathsOpened(s: *Session) u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.paths_opened; } /// RFC 7250: the raw public key the peer proved it holds, or null for a /// certificate handshake or one that has not finished. On an endpoint that /// admits any key, this is who the session is with. pub fn peerPublicKey(s: *Session) ?quic.tls.PublicKey { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.peerPublicKey(); } /// §3.5 of RFC 9000: abandons one stream, without touching the connection. /// /// The thing HTTP/1.1 cannot do, and the reason an application protocol over /// QUIC can refuse one request without dropping the others: the error code is /// the application's own -- RFC 9114's H3_REQUEST_REJECTED, for instance, /// which tells a client that nothing happened and the request may be sent /// again elsewhere. pub fn resetStream(s: *Session, id: quic.stream.Id, code: u64) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.resetStream(id, code); s.flushLocked(); } /// §3.5: asks the peer to stop sending on a stream. pub fn stopSending(s: *Session, id: quic.stream.Id, code: u64) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.stopSending(id, code); s.flushLocked(); } /// §19.19: ends the connection with an error code belonging to whatever is /// running over QUIC rather than to QUIC. /// /// The 0x1d variant of CONNECTION_CLOSE, which is the one an application /// protocol gets: HTTP/3's H3_FRAME_UNEXPECTED and the rest are codes in that /// space, and sending one as a transport error would tell the peer that QUIC /// itself had been broken. pub fn closeApplication(s: *Session, code: u64, why: []const u8) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.connection.closeApplication(code, why, s.now()); s.flushLocked(); s.arrived.broadcast(s.io); } /// §10: how this connection ended, if it has. pub fn closeState(s: *Session) ?quic.close.State { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.closeState(); } /// Opens a stream this endpoint will send on. pub fn openUnidirectional(s: *Session) !Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const id = try s.connection.openUnidirectional(); return .{ .session = s, .id = id }; } pub fn openBidirectional(s: *Session) !Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const id = try s.connection.openBidirectional(); return .{ .session = s, .id = id }; } /// The TLS state the connection's handshake points into. /// /// Owned by the session because the connection does not allocate and the /// handshake must outlive it, and a union because the two ends of a QUIC /// connection run different halves of the same handshake. Nothing else about /// a session differs between them: a stream is a stream whoever opened the /// connection, which is what makes one `Session` serve both. pub const Tls = union(enum) { server: quic.tls_handshake.Server, client: quic.tls_handshake.Client, pub fn handshake(t: *Tls) quic.tls.Handshake { return switch (t.*) { .server => |*v| v.handshake(), .client => |*v| v.handshake(), }; } };