Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Quic.AppProtocol

Feature notes: Asynchronous QUIC server and HTTP/3 component

Classes, interfaces and records

classeQuicAppProtocol

inherits from Exception

(no public members)

interfaceiQuicAppTransport

One QUIC connection, as handed to CreateSession and OnHandshakeDone. Calls are serialized per connection. Sending: SendCapacity(aStreamID) is how many bytes Send takes on that stream now (0 once its FIN or reset is queued). Send at most that much and send the rest from a later Writable. Receiving: after processing n bytes from StreamData or StreamDataEarly, call Consume(aStreamID, n) to give the peer n bytes of credit back; until you do, it cannot send beyond the stream and connection receive windows. Keeping or dropping the received array does not affect credit. Consume raises if n exceeds the bytes delivered and not yet consumed. OpenStream opens a stream of your own; False, with aStreamID 0, means the peer's stream limit is reached - try again later, for example from Writable. ResetSend abandons your sending side of a stream, StopReceive asks the peer to stop sending on it, and Close ends the connection at once with an application error code, discarding queued data; Closed follows. ConnectionInfo can be queried for iTLSConnectionInfo. Inside and after Closed the transport is inert: queries return empty values, Consume and Close do nothing, and OpenStream, Send, ResetSend and StopReceive raise.

function GetNegotiatedProtocol: OctetString; function GetRemoteAddress: string; function GetConnectionInfo: IInterface; function OpenStream(aUnidirectional: Boolean; out aStreamID: UInt64): Boolean; function SendCapacity(aStreamID: UInt64): Integer; procedure Send(aStreamID: UInt64; const aData: TBytes; aOffset, aCount: Integer; aFin: Boolean);
Queues aCount bytes of aData from aOffset on aStreamID, then the stream's FIN if aFin is True. Success means QUIC accepted them into its bounded send queue, not that they were sent or acknowledged. Full description »
procedure Consume(aStreamID, aCount: UInt64); procedure ResetSend(aStreamID, aErrorCode: UInt64); procedure StopReceive(aStreamID, aErrorCode: UInt64); procedure Close(aErrorCode: UInt64; const aReason: string); function ExportKeyingMaterial(const aLabel: AnsiString; const aContext: TBytes; aLength: Integer): TBytes; function Instance: TObject; property NegotiatedProtocol: OctetString read GetNegotiatedProtocol; property RemoteAddress: string read GetRemoteAddress;
Address only of the current validated path: no port or IPv6 brackets. IPv4-mapped IPv6 retains its ::ffff: prefix. Read anew for each request when a connection may rebind.
property ConnectionInfo: IInterface read GetConnectionInfo;

interfaceiQuicAppTransportBufferPolicy

Optional. Call PrepareReceiveReserve from Opened, before sending stream data, if you need the guarantee TryGetReceiveLimits reports as GuaranteedReceiveReserve: queued output never takes buffer space needed for receive credit the peer was already granted. It caps the buffer memory this connection uses for output at aSendWindow bytes; the credit itself does not change. The host prepares max(256,W div 256) pending STREAM intervals including FINs; tiny holes beyond that cap fail only this connection. CRYPTO/control budgets remain independent. W/RTT is the throughput ceiling: 64 KiB at 50 ms gives 1.31 MB/s, 256 KiB gives 5.24 MB/s. A peer can force W one-byte ranges: steady send storage is W + W*SizeOf(tSendRange) plus max(256,W div 256)*32 output bytes. Send ranges measure 32/40 bytes on Win32/Win64; output stream intervals 32 on both (CRYPTO intervals 16). Copy-on-change can double descriptor storage and costs quadratic CPU. Multiply by listener MaxConnections, plus receive/HTTP/TLS storage. HTTP/3 defaults deliberately to 65536: visible low speed is preferable to letting each peer pin large allocations. Raise it with a lower connection cap and explicit memory budget. False, with nothing changed, if aSendWindow is not positive or too large for the connection's buffers, if any STREAM data or FIN was queued, if a different window was prepared, or after Closed.

function PrepareReceiveReserve(aSendWindow: Integer): Boolean;

interfaceiQuicAppTransportEarlyData

Optional queries for a protocol that acts on a message before all of it has arrived. StreamHasEarlyData is True while aStreamID still has 0-RTT bytes or a 0-RTT FIN not yet delivered, including ones waiting behind missing data. EarlyDataWindowOpen is True while the connection can still accept 0-RTT packets, so any stream may yet receive early input; it does not say whether a particular message is early. Both are False after Closed.

function EarlyDataWindowOpen: Boolean; function StreamHasEarlyData(aStreamID: UInt64): Boolean;

recordtQuicAppReceiveLimits

StreamAllowance, ConnectionAllowance, PeerUniAllowance: UInt64; GuaranteedReceiveReserve, ReceiveTerminal: Boolean;

interfaceiQuicAppTransportReceiveLimits

Optional flow-control figures for aStreamID, to size input buffering. StreamAllowance and ConnectionAllowance are the receive windows: the most bytes the peer may have sent that you have not yet consumed, on the stream and on the connection (window sizes, not stream offsets). PeerUniAllowance is the window each peer-opened unidirectional stream starts with. ReceiveTerminal is True once the stream's FIN has been delivered or the peer has reset it; a known final size with data still missing does not count. GuaranteedReceiveReserve is True when PrepareReceiveReserve succeeded and the buffers can hold the whole ConnectionAllowance. False, with every field zero, for an unknown or send-only stream and after Closed; asking never creates a stream.

function TryGetReceiveLimits(aStreamID: UInt64; out aLimits: tQuicAppReceiveLimits): Boolean;

interfaceiQuicAppTransportWork

Optional: run your own work on the connection's worker, serialized with the session's callbacks. RequestWork, from any thread, asks for one iQuicAppSessionWork.WorkQueued call; requests made before it runs give one call, and it never runs inside RequestWork. False means the connection is gone. SetWorkDeadline sets the session's single timer to aTickMS, an absolute stTlsUtils.GetTickCount64 time in milliseconds, replacing any earlier value; 0 clears it. When it falls due, WorkQueued runs and the timer is cleared.

function RequestWork: Boolean; procedure SetWorkDeadline(aTickMS: UInt64);

interfaceiQuicAppTransportIngress

Datagrams for this connection that its bounded ingress queue refused for capacity. Reading takes no connection lock, so it is safe while one of the connection's callbacks runs. A detached transport returns zero.

function IngressDropCount: Int64;

interfaceiQuicAppTransportStreamBudget

Optional cumulative client-bidirectional credit, under the entry lock. Skipped IDs count as opened. Metadata includes live records, bounded sparse retired ranges and reservations for unused/skipped allowed peer IDs; the ceiling never grows. Increasing to an absolute larger limit queues/retransmits MAX_STREAMS and wakes output; reserve room for every additional allowed stream. Values cannot exceed 2^60. RequestDrain starts this connection's ACK-aware graceful shutdown, bounded by the listener's ShutdownTimeoutMS. It never stops the listener.

function GetStreamBudget(out aOpened, aGrant: UInt64; out aMetadata, aCeiling: Integer): Boolean; function IncreaseStreamBudget(aGrant: UInt64): Boolean; procedure RequestDrain;

interfaceiQuicAppSessionRetirement

Optional application release after transport completion, outside session callbacks. Return True only after relinquishing all application, QPACK and streaming references to that stream. False keeps its bounded record.

function ReleaseStream(aStreamID: UInt64): Boolean;

interfaceiQuicAppSessionDrainClose

Optional protocol-specific successful drain close. Without it the host uses transport NO_ERROR, as for Snip. HTTP/3 supplies application 0x100.

procedure DrainClose(out aErrorCode: UInt64; out aApplication: Boolean);

interfaceiQuicAppSession

Your state for one connection, created by iQuicAppProtocol.CreateSession. Opened runs once, right after CreateSession, when the TLS 1.3 handshake has completed with your protocol's ALPN token. Each connection turn then runs WorkQueued if due, the stream events, and finally Writable:
StreamData the peer's bytes on a stream, in order (Consume them when processed). aFin True marks the end of the peer's data; aData may then be empty. aData is shared: you may keep it, but never modify it.
StreamReset the peer abandoned the stream (RESET_STREAM). No more data follows; the host returns its credit itself. StreamStopped the peer stopped reading what you send (STOP_SENDING). The host has reset your side; send nothing more on it.
Writable a chance to send more (check SendCapacity). It is not an acknowledgement and runs whether or not room grew. Closed runs exactly once, last, with the QUIC or application error code (0 for no error); the transport is unusable from then on. Callbacks run on connection workers, one at a time per connection (at final shutdown Closed can run on the deactivating thread). Keep them short: a blocked callback holds a worker. They may use the transport, but cannot activate, destroy or reconfigure the hosting components. An exception raised by Opened, WorkQueued, a stream callback or Writable closes the connection with a QUIC internal error; one raised by Closed is ignored. Optional companions: iQuicAppSessionWork, iQuicAppSessionReceiveStarted, iQuicAppSessionEarlyData and iQuicAppSessionDrain.

procedure Opened; procedure StreamData(aStreamID: UInt64; const aData: TBytes; aFin: Boolean); procedure StreamReset(aStreamID, aErrorCode: UInt64); procedure StreamStopped(aStreamID, aErrorCode: UInt64); procedure Writable; procedure Closed(aErrorCode: UInt64); function Instance: TObject;

interfaceiQuicAppSessionEarlyData

Implement this on every session of a protocol that opts in to 0-RTT with iQuicAppProtocolEarlyData; without it, accepted early input closes the connection. StreamDataEarly works like StreamData, after Opened, but delivers bytes the client sent as 0-RTT early data before its handshake completed. Such input can be a replay: act on it only where repeating it is harmless. StreamData then carries 1-RTT bytes only.

Before the first call, TLS and QUIC have already established that this connection may send early data: TLS 1.3 resumption with a single-use ticket this server issued (verified binder, atomic ticket store, same cipher suite, server name and key-exchange group, same ALPN, QUIC version and application context, compatible transport parameters), engine policy edmAccept, approval by OnTLSCheckEarlyDataReplay, and packets authenticated under the client's early-traffic key. Do not repeat these checks; AsyncTLSServer.txt section 9 explains them for TLS over TCP.

What only your protocol can check is its own message framing. Every chunk, and every FIN, is either wholly early or wholly 1-RTT; an empty chunk with aFin True counts as input of its kind, an empty chunk without FIN says nothing. Unlike TLS over TCP, QUIC has no single point where early data ends: streams interleave, so 1-RTT data on one stream does not mean early input on another is over (iQuicAppTransportEarlyData tells whether more can come). For each message on each stream, record whether any byte or its FIN came early and whether any came 1-RTT, and refuse a message that has both - do not merely treat it as early. The HTTP plugins answer such a request with 425 before any handler runs, whatever EarlyDataPolicy says. An idempotent method does not make the application's side effects replay-safe, and the single-use ticket only stops a second acceptance by this server's ticket store.

A protocol that cannot frame early input this way must not opt in: dropping input the server accepted as 0-RTT loses it, because the client will not send it again.

procedure StreamDataEarly(aStreamID: UInt64; const aData: TBytes; aFin: Boolean);

interfaceiQuicAppSessionReceiveStarted

Optional. StreamReceiveStarted tells you the peer has started sending on aStreamID, before that stream's first StreamData, StreamDataEarly or StreamReset, even when its first bytes are still missing because later ones arrived first. aStartedMS is when the host first saw the stream, in stTlsUtils.GetTickCount64 milliseconds; time input deadlines from it. It is called once per stream. A stream ID the peer skips gets no call until the peer sends on it.

procedure StreamReceiveStarted(aStreamID, aStartedMS: UInt64);

interfaceiQuicAppSessionWork

WorkQueued runs on the connection's worker, serialized with the other callbacks, after iQuicAppTransportWork.RequestWork or when the work deadline has passed; it does not say which. A deadline that fired is cleared, so if you still have timers, call SetWorkDeadline again with the earliest one.

procedure WorkQueued;

interfaceiQuicAppSessionDrain

Optional, for graceful shutdown. When the server is deactivated, the host calls BeginDrain on a connection worker: stop taking new work (TsmHTTPSv3 sends GOAWAY) and finish what is in progress. Make Drained True once all your remaining output has been passed to Send; the host then waits for the peer to acknowledge the queued data and FINs before closing, at most ShutdownTimeoutMS. A session without this is closed at once, and output still queued is discarded.

procedure BeginDrain; function GetDrained: Boolean; property Drained: Boolean read GetDrained;

interfaceiQuicAppProtocol

A QUIC application protocol. Register it with TsmAsyncQUICServer.Protocols.AddProtocol while the server is inactive. Token is the ALPN token clients must offer, exact bytes such as 'h3'; there is no fallback, and it must not change while registered. Description is a readable name. CreateSession runs on a connection worker for each connection that negotiated Token, after the handshake, under the same rules as session callbacks. Return a new session for that one connection; nil closes the connection. Whatever a session uses from your plugin must stay valid until its Closed: a plugin component should deactivate its server before it is freed, as TsmHTTPSv3 does.

function GetToken: OctetString; function GetDescription: string; function CreateSession(const aTransport: iQuicAppTransport): iQuicAppSession; property Token: OctetString read GetToken; property Description: string read GetDescription;

interfaceiQuicAppProtocolEarlyData

Optional: implement it on your iQuicAppProtocol to let the endpoint accept 0-RTT. The host calls CaptureEarlyDataContext once per activation, before accepting connections. Return a nonempty description of every local setting your early-input handling depends on; it goes into the tickets the server issues, and 0-RTT on a later connection is accepted only if the current activation produces the same bytes, so make it change whenever a setting changes incompatibly with early input sent under older tickets. Return empty to refuse 0-RTT. If any registered protocol lacks this interface or returns empty, or all tokens and contexts together exceed cQuicAppMaxEarlyDataContext bytes, the whole endpoint refuses 0-RTT; ordinary connections and resumption still work. Describe configuration only: create no sessions and cause no side effects here. Sessions of an opted-in protocol must implement iQuicAppSessionEarlyData.

function CaptureEarlyDataContext: TBytes;

interfaceiQuicServerAvailability

TsmAsyncQUICServer.Availability, for a component that advertises this endpoint (TsmHTTPSv3 uses it for Alt-Svc). TryGetPort returns True and the bound UDP port from a successful activation until deactivation or endpoint closure, and only for an aProtocol registered for that activation (the same reference); otherwise False with aPort 0. It reports local readiness, not reachability from the Internet. Safe from any thread; a kept reference stays valid after the server is freed and then returns False.

function TryGetPort(const aProtocol: iQuicAppProtocol; out aPort: Word): Boolean;

interfaceiQuicServerAvailabilityControl

Host-only: TsmAsyncQUICServer updates Availability through this; a plugin never calls it. BeginActivation starts a new generation and clears the old answer, Publish sets the port and protocols for that generation (port 0 or no protocols clears it), and Withdraw clears it until the next BeginActivation. Calls with an older generation are ignored.

function BeginActivation: UInt64; procedure Publish(aGeneration: UInt64; aPort: Word; const aProtocols: tQuicAppProtocols); procedure Withdraw(aGeneration: UInt64);

interfaceiQuicAppProtocolRegistry

TsmAsyncQUICServer.Protocols, the protocols the server offers by ALPN. Change it only while the server is inactive; while it is active, AddProtocol and RemoveProtocol raise eQuicAppProtocol. AddProtocol also raises for nil, for a Token outside 1..255 octets, for a Token another protocol has registered, and when 64 are registered; adding the same protocol again does nothing. FindProtocol matches the token exactly. The server cannot be activated with no protocol registered.

procedure AddProtocol(const aProtocol: iQuicAppProtocol); procedure RemoveProtocol(const aProtocol: iQuicAppProtocol); function FindProtocol(const aToken: OctetString): iQuicAppProtocol; function GetTokens: tQuicProtocolTokens; function GetCount: Integer; property Tokens: tQuicProtocolTokens read GetTokens; property Count: Integer read GetCount;

interfaceiQuicAppProtocolPriority

Optional on a registry: AddProtocolByPriority registers a protocol at a place in the ALPN preference list. Higher priorities come first; equal priorities keep the order they were added in, and AddProtocol adds at priority 0. Like AddProtocol it raises while the server is active, because the registry is frozen then. TsnipQUICServer uses it for AlpnPriority.

procedure AddProtocolByPriority(const aProtocol: iQuicAppProtocol; aPriority: Integer);

interfaceiQuicAppProtocolComponent

Implement this on a plugin component, as TsmHTTPSv3 does. On every activation, before the registry is frozen, the server calls BindToServer(itself) on each component owned by its Owner; if aServer is the server your component is assigned to, register with aServer.Protocols there. A streamed form then works whichever component loads first. Adding an already registered protocol does nothing, so repeating the registration is harmless.

procedure BindToServer(aServer: TComponent);

interfaceiQuicAppRegistryControl

Host-only: TsmAsyncQUICServer freezes Protocols on activation and thaws it after deactivation; a plugin never calls this. While frozen, AddProtocol and RemoveProtocol raise, also through a registry reference kept elsewhere.

procedure Freeze; procedure Thaw;

Types (enumerations, sets, aliases)

arraytQuicProtocolTokens

  tQuicProtocolTokens = array of OctetString;

arraytQuicAppProtocols

  tQuicAppProtocols = array of iQuicAppProtocol;

Routines