Feature notes
Async TLS socket server architecture
================================================================================
ASYNC TLS SOCKET SERVER - ARCHITECTURE
An async, implicit-TLS socket server whose application layer is a plugin
selected by TLS ALPN, over a sharded bank of TsmSimpleTLSInternalServer engines
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Updated: 2026-10-09 (LARGE RESPONSES. A Send that queues behind something in
flight and does not fit under MaxSendQueueBytes closes
the connection, and right after a TLS 1.3 handshake the
NewSessionTicket flight IS in flight - so a single
large response is not safe from it, as section 5.05
used to say. Section 5.05 now says how a plugin paces
itself: iAppTransportFlow on the transport, and
iAppSessionDrain on the session (section 8.1). The
close is reported by OnSendQueueOverflow.)
Regenerated: 2026-08-08 (PROVISIONING ORDER REVERSED - this supersedes earlier
guidance and the old pattern is now REFUSED, so any
application written against it must change.
ImportFromPFX, LoadRootCertsFromFile and
ValidatePublicKeyPairs are now called BEFORE
Active := True. On a dormant component they touch no
engine - there is none yet - they RECORD the request,
and the recorded sequence is applied to the whole
shard bank as it is built, so the application
provisions once and the component decides when and how
often the material reaches an engine.
DO NOT call them from OnConfigureEngine. By the time
the first handler runs the bank already exists and all
three refuse rather than pretend, because a late call
could reach some shards and not others. The earlier
text told you to call them from the handler guarded to
shard 0 (if aIndex = 0); that no longer works.
OnConfigureEngine is now for PER-SHARD SETTINGS ONLY -
what the component cannot fan out, such as
TLSOptions.Assign and IncludeRootInTLSChain - and a
handler needing to know what was provisioned reads it
off the aEngine it was handed. Section on certificate
and anchor provisioning updated.)
Generated: 2026-07-24 (Core thesis: the TLS session pool is the FIRST resource
to saturate under load - it bounds the client count
BEFORE sockets, threads or buffers can. A platform I/O
reactor front-ends a two-tier TLS admission gate; an
ALPN->plugin registry selects the application layer at
the content-layer seam.)
--------------------------------------------------------------------------------
0. SUMMARY - TLS AS THE GOVERNOR
--------------------------------------------------------------------------------
The design goal is a specific inversion of the classic thread-per-connection
server (which is what tTCPDaemon and the SSH SocketServer do
today): a TCP connection must own NO expensive resource until it has passed the
TLS gate. Accepted-but-not-yet-handshaking connections cost only a socket handle
plus one receive buffer; the session state, and whatever the application protocol
allocates for itself, come LATE - after the handshake has produced a live session
and ALPN has chosen a protocol. On top of that, an explicit two-tier semaphore sizes the TLS
work directly. The consequence is the requirement asked for: SSL/TLS saturates
first. When the box is full it is full of TLS sessions, never of idle threads or
un-drained buffers.
Three moving parts deliver this:
1. A platform I/O REACTOR (IOCP on Windows, epoll on Linux, kqueue on the BSD/
macOS targets) with a small fixed I/O-thread pool - NOT one thread per
connection. This keeps a pre-handshake connection cheap and uniform.
2. A two-tier TLS ADMISSION CONTROLLER: at most H concurrent in-flight
handshakes (CPU-bound asymmetric crypto) and at most S live established
sessions (memory-bound). S is the advertised max-clients number, and it is
a TLS quantity.
3. An ALPN -> PLUGIN REGISTRY. Implicit TLS is negotiated first; the ALPN token
the handshake settles on selects an iAppProtocol plugin (or a configured
fallback), which mints the per-connection iAppSession that becomes the
application layer. The seam is each shard engine's OnTLSAddContentLayer.
Implicit TLS (no plaintext preamble, no STARTTLS) is intrinsic: every accepted
socket is wrapped in a TLS content layer from byte 0, so the ALPN plugin
selection and the DoS gate both sit behind the TLS handshake by construction.
THE COMPONENT IS TsmAsyncTLSServer. Drop it on a form, configure the TLS
identity and policy once in OnConfigureEngine, give it one or more application
protocols, and set Active. The application protocols that ship with the library
are components too, so the whole server is assembled in the Object Inspector:
TsmHTTPSv1dot1 HTTPS over HTTP/1.1 ALPN 'http/1.1'
TsmHTTPSv2 HTTPS over HTTP/2 ALPN 'h2'
TsnipTLSServer Snif/Snip class remoting over TLS
Each publishes a Server property; assigning it registers that protocol's ALPN
token with this server, and the token the handshake settles on is what selects
the protocol per connection. A protocol that is not a component - anything
implementing iAppProtocol - is registered from code instead (section 4). Nothing
stops one server carrying all three at once on a single port, which is the point
of selecting by ALPN rather than by port number. When it does, each also
publishes AlpnPriority to say which of them wins a client that offers more than
one; section 4.1 explains why that needs stating at design time.
The platform I/O backend and the listening socket are chosen automatically for
the target being compiled - IOCP and Winsock on Windows, epoll or kqueue and the
POSIX socket API elsewhere - so a consumer configures nothing for it and the
same code serves on both.
--------------------------------------------------------------------------------
1. DESIGN INVARIANT - WHY TLS BOUNDS CONCURRENCY BEFORE TCP / THREADS / BUFFERS
================================================================================
Model each resource as an admission GATE with a capacity, ordered by how
expensive it is to hold. A connection climbs the ladder; it can only reach a gate
after clearing every cheaper one below it:
GATE CAPACITY COST TO HOLD ONE WHERE IT LIVES
---- -------- ---------------- --------------
3 TLS SESSION S key schedule, per-conn RNG, tTLSAdmissionController
(live) record buffers, cert chain <== BINDING GATE
-------------------------------------------------- taken at accept, today
2 TLS handshake H transient handshake state + tTLSAdmissionController
(in flight) one asymmetric-crypto op
--------------------------------------------------
1 reactor CCB N_conn one socket handle + the receive tAsyncReactor +
(accepted) slab the reactor posts tTLSConnection
--------------------------------------------------
0 accept L_backlog a kernel accept-queue entry the listen backlog
There is no application-worker pool above these: plugins run inline on the
reactor thread that delivered the bytes, so an application buffer is whatever
the plugin allocates for itself and it is bounded by S like everything else
above gate 1. Section 6 says what that costs; section 10 lists a bounded pool
as open work, because a blocking plugin is exactly the case such a pool is for.
Choose the capacities so each gate strictly dominates the next expensive one:
L_backlog > N_conn >> S and H <= cores * k
The invariant that makes TLS the binding constraint:
- A connection CANNOT reach a TLS session, and therefore cannot reach a plugin
or any buffer a plugin allocates, without a session token (gate 3).
- Therefore the number of connections consuming expensive resources is
bounded by S, the live-session cap - a TLS quantity.
- Because N_conn >> S, the reactor still has cheap CCB capacity to spare when
the session pool is already full, so a flood is absorbed as "server full"
on a cheap descriptor rather than as thread/FD/OOM exhaustion. TCP never
runs out first.
WHERE THE CODE AS BUILT IS WEAKER THAN THIS INVARIANT, stated plainly because it
is the one place the design and the build genuinely diverge (section 5 has the
mechanics, section 10 tracks it):
- Admission is decided at ACCEPT, not on the ClientHello. A connection that
never sends a byte still consumes a session token, so gate 1's large cheap
capacity is not actually in front of gate 3 today.
- avDeferHandshake is not a wait. Both non-admit verdicts close the descriptor
immediately, so H currently behaves as a second refusal threshold rather
than as a queue.
- HandshakeTimeout bounds accept-to-handshake-complete and IdleTimeout
bounds an established session's quiet time; both are enforced by a reaper
thread the component owns. Without the handshake budget,
MaxConcurrentHandshakes silent TCP sockets could deny service to everyone
else indefinitely, at no cost to the attacker - no TLS, no crypto, not one
byte sent. See section 5.
The invariant above is still what the structure is FOR - it is why the reactor,
the admission controller and the plugin seam are separate objects with separate
capacities - and closing the two gaps that remain is a change to when Admit is
called, not to the shape of the thing.
--------------------------------------------------------------------------------
2. UNIT INVENTORY & WHAT EACH TYPE IS
================================================================================
EIGHT RUNTIME UNITS, all in the 'contains' of every StrSecIV170-370 package
(XE3 .. Florence), so the whole set compiles on every supported Delphi - which
is what keeps a version-gated construct in them a build failure rather than a
latent hazard:
StreamSec.Mobile.AsyncTLSServer the component and everything that is
one-per-connection: TsmAsyncTLSServer,
tTLSConnection, tTLSListenerDaemon,
tTLSAdmissionController,
tAppProtocolRegistry, TOCSPOptions,
and the iApp* plugin contract.
StreamSec.Mobile.AsyncTLSReactor the abstraction: tAsyncReactor,
tReactorConnection, tReactorKind,
NewReactor / RegisterReactor /
ReactorAvailable / DefaultReactorKind.
StreamSec.Mobile.AsyncTLSReactor.IOCP tIOCPReactor (Windows)
StreamSec.Mobile.AsyncTLSReactor.Poll tPollReactor (shared readiness
base for the two below)
StreamSec.Mobile.AsyncTLSReactor.Epoll tEpollReactor (Linux / Android)
StreamSec.Mobile.AsyncTLSReactor.KQueue tKQueueReactor (macOS / iOS / BSD)
StreamSec.Mobile.AsyncTLSListener.Winsock tTLSListenerSocket (Windows)
StreamSec.Mobile.AsyncTLSListener.Posix tTLSListenerSocket (POSIX)
one class, two implementations,
exactly one linked.
StreamSec.Mobile.AsyncTLSServerReg DESIGN-TIME only, in every
DStrSecIV170-370 and in no runtime
package: it is what puts the three
components on the palette.
WHAT EACH TYPE IS. Legend: A -> B means "A hands work to / is built on B".
TsmAsyncTLSServer -> the published component. NOT a TsmStreamSecII
descendant: it is a TComponent that OWNS a bank of N
TsmSimpleTLSInternalServer engines (the shards), the
listener, the reactor, the admission controller and the
ALPN registry. TLS policy is therefore configured per
shard through OnConfigureEngine rather than through
inherited TLSOptions - one handler, called once per
shard, is where every setting goes (section 9). The
component also implements iKeyAndCertStore, which is
what lets a single ImportFromPFX provision the whole
bank from one parse of the file (sections 6 and 9).
tTLSListenerSocket -> the accept-side socket API, one class with a Windows
and a POSIX implementation, picked by the target. It
binds and listens on the ACTIVATING thread, so a bind
failure comes back out of 'Active := True'.
tTLSListenerDaemon -> the ONE accept-loop thread. Its Execute is a loop of
Accept -> StartPeerTransport(handle, peer address); it
does NOT spawn a thread per accept and owns no socket
API of its own.
tAsyncReactor -> abstract platform I/O demultiplexer; concrete backends
wrap IOCP / epoll / kqueue and register themselves with
NewReactor from their initialization sections, so naming
the unit in a uses clause IS the selection. A small
fixed I/O-thread pool services every live connection.
tReactorConnection -> the reactor's half of a connection: the descriptor, the
per-connection gate (Enter/Leave), the send queue, and
the recv-in-flight accounting that EnforceSingleRecv
checks.
tTLSConnection -> descends from tReactorConnection and adds the TLS half:
the content layer, the resolved plugin and its session,
the shard index. It IS the iAppTransport handed to the
plugin.
tTLSAdmissionController -> the two-tier H/S counter (section 5).
iAppProtocolRegistry -> ALPN token -> iAppProtocol map with a configurable
fallback; produces the advertised ALPN list and resolves
the negotiated token after the handshake (section 4).
iAppProtocol / iAppSession / iAppTransport -> the plugin contract (section 8).
Existing units used as-is:
StreamSec.Mobile.TlsInternalServer TsmSimpleTLSInternalServer (the shard
engine), iAcmeAlpnTLS.
StreamSec.Mobile.StreamSecII TLSSetupServer (once per shard at
activation), TLSAddServerSession (once per
connection), OnTLSAddContentLayer /
TTLSChangeCipherSpec, OnTLSEarlyData /
OnTLSCheckEarlyDataReplay. The record path
itself goes to the connection's own layer,
not back through the engine (section 3).
StreamSec.Mobile.TlsClass / TlsLayer TCustomTLS_ContentLayer,
TApplicationProtocols, TProtocolVersion.
stTlsUtils GetTickCount64, cross-version and
cross-platform (the deactivate deadline).
NOT used: stSocket. It cannot serve as the listener here, for two reasons that
both fail silently rather than at compile time: its sockets are not overlapped,
and it discards the peer address the plugin contract requires.
PLATFORM SURFACE. StreamSec.Mobile.AsyncTLSServer itself contains no platform
API and no $IFDEF in its body: Sleep comes from System.SysUtils, the monotonic
clock from stTlsUtils, the socket API from whichever listener unit the
conditional uses clause pulled in, and closing an accepted descriptor from
tAsyncReactor.CloseSocketHandle. The $IFDEF is in the uses clause and nowhere
else, which is what makes the component identical on both platforms.
--------------------------------------------------------------------------------
3. IMPLICIT TLS - FROM BYTE 0
================================================================================
There is no STARTTLS and no explicit-upgrade path. Every accepted descriptor is
wrapped in a TLS content layer immediately and its first bytes go straight into
the handshake, so the ALPN plugin choice and the admission gate are unavoidably
behind the handshake. The first record on the wire is a TLS record.
TWO DRIVE PATHS EXIST, and which one runs is the published UseDirectLayer
property. It defaults to True.
DIRECT (default). At accept the connection creates its content layer ONCE
(TLSAddServerSession keyed on the connection instance) and thereafter drives
that layer object directly - Accept / DecodeData / EncodeData / Close - under
the reactor's per-connection gate. No per-record FindTLSSession lookup, and no
shard lock on the record path, because a content layer belongs to exactly one
connection and the gate already serializes it.
ENGINE-MEDIATED (UseDirectLayer := False). Every call goes through the
owning shard engine, which re-resolves the layer from the connection instance
by a binary search over its session table and takes the shard's lock to do it.
An A/B validation mode - correctness and speed - not for production use.
The two paths differ only in HOW the layer is reached. Either way the ciphertext
the layer produces is queued to the reactor for async send, and the plaintext it
yields is routed to the plugin session - 1-RTT to DataReceived, accepted 0-RTT to
EarlyDataReceived (sections 7, 9).
The engine-mediated path is the one place in the subsystem that reaches the
layer through the ENGINE's session-keyed entry points rather than through the
layer object the connection already holds. The indirection buys nothing here -
a content layer belongs to exactly one connection - which is why the mode is
A/B scaffolding rather than a supported alternative: see section 10, which
tracks deleting it.
Reading the negotiated version off the layer, not off the wire: the 1.3 record
version stays 0x0303, so use the content layer's Version: TProtocolVersion,
which returns the true negotiated minor once supported_versions has been parsed
(cTLS13vmm for 1.3). Per-connection secret buffers are wiped with ProtectClear
on release, never FillChar - the library-wide zeroization rule.
ExportKeyingMaterial (RFC 8446 s7.5) is exposed on iAppTransport for plugins
that carry their own authentication inside the tunnel and must bind it to this
channel - the Snif KAPA is the library's own consumer. On the direct path it
reads the held layer; on the engine-mediated path it re-resolves under the
shard lock first. It returns empty unless a TLS 1.3 handshake completed, and a consumer
MUST fail closed on empty rather than proceed unbound.
--------------------------------------------------------------------------------
4. ALPN -> APPLICATION-LAYER PLUGIN DISPATCH
================================================================================
The application layer is chosen by the ALPN protocol the handshake settles on,
with a configurable fallback when the client offers nothing usable. ALPN is
negotiated INSIDE the handshake (a ServerHello extension for 1.2, the encrypted
EncryptedExtensions for 1.3), so the registry is consulted at TWO points.
4.1 During the handshake (the offer list)
TsmAsyncTLSServer.ConfigureContentLayer is assigned to every shard engine's
OnTLSAddContentLayer (type TTLSChangeCipherSpec = procedure(Sender: TObject;
Client: TCustomTLS_ContentLayer) of object), which fires once per session after
the engine has seeded the layer and before the handshake. It does exactly two
things:
- sets Client.OfferTLS13 := True;
- MERGES iAppProtocolRegistry.AdvertisedProtocols into the list the engine
already seeded, engine entries keeping priority, registry protocols
appended only when not already present.
The merge is not a detail. The engine stocks each new session from its own
FALPN, and that is where AddTLSAcmeALPN puts 'acme-tls/1'. Overwriting the
list instead would mean an ACME tls-alpn-01 challenge could be installed on
every shard and still never be negotiable, so validation could not succeed on
this server at all.
Certificate selection then keys on the negotiated ALPN: it is passed as the
const ALPN: OctetString of TGetCertificateEvent, so an 'acme-tls/1' handshake
selects the challenge certificate while 'h2' / 'http/1.1' select the real one on
the same port. OCSP stapling and the certificate hooks are NOT set here; they
come from the shard engine, configured once per shard in OnConfigureEngine
(section 9).
ORDER WITHIN THE REGISTRY SEGMENT IS PREFERENCE. Selection walks OUR list
outermost and takes the first token the client also offered (RFC 7301 s3.2,
TCustomTLS_ContentLayer.PickProtocol), so the client's own ordering is ignored
beyond membership. Registering from code states that order plainly - adjacent
AddProtocol calls read top to bottom - but a COMPONENT registers itself from
Loaded, and that is DFM declaration order: invisible, changed by accident, and
wrong in a way nothing reports, because every ordering is a valid negotiation.
Each of the plugin components therefore publishes AlpnPriority - TsmHTTPSv1dot1,
TsmHTTPSv2 and TsnipTLSServer alike. HIGHER IS PREFERRED, insertion is sorted,
and a component lands in its right slot whenever it happens to load, so the
reverse declaration order yields the same advertised list. Equal priorities
keep insertion order, so components left at cAlpnPriorityDefault (0) are
advertised in registration order. The priority surface is the separate
iAppProtocolPriority.AddProtocolByPriority, reached with Supports; a protocol
registered from code through iAppProtocolRegistry.AddProtocol needs no
priority awareness.
It orders the REGISTRY SEGMENT ONLY. Engine-seeded tokens such as 'acme-tls/1'
are merged ahead of all of them by the rule above and cannot be demoted here,
which is correct: a challenge that cannot be negotiated is a challenge that
fails. HTTP.txt section 16 has the worked h2-against-http/1.1 example.
THE REGISTRY IS LOCKED. It is read from reactor threads on every handshake
(AdvertisedProtocols here, ResolveProtocol in 4.2) and written from the
application thread whenever a plugin binds, unbinds or is freed, so every
public entry point takes one critical section. The list and its parallel
priority array are two structures holding one fact, and it is the COMPOSITE
operations that have to be atomic - a reader walking the list while a removal
shifts the priorities under it would otherwise read priorities belonging to
the wrong protocols. AdvertisedProtocols returns a single locked snapshot for
that reason. Two consequences worth knowing:
- the lock is held across iAppProtocol.Token, which is a call out to the
plugin, so an implementation must not call back into the registry from
GetToken;
- Count and Protocols[] are each safe but not atomic AS A PAIR, so a
"for i := 0 to Count - 1" walk can still race a concurrent removal.
Protocols[] answers nil out of range rather than raising, and the
handshake path uses the snapshot instead.
The plugin COMPONENTS additionally refuse to re-order a live server at all:
AlpnPriority raises while Active (section 8.3).
4.2 After the handshake (resolve + instantiate)
The settled token is the layer's SelectedProtocol, which is empty unless
something was genuinely agreed.
ALPN LEAVES THE LAYER IN ONE OF TWO STATES, and both version paths now produce
them identically. When the peer's offer matches, PickProtocol narrows
ApplicationProtocols to the single agreed token and records it in
SelectedProtocol. When the peer offers NO ALPN at all, the server TRUNCATES the
list to empty - so an empty list means "nothing negotiated" and a one-entry
list means "this was agreed". TLS 1.2 always did this (HandleClientHello); the
1.3 server did not, and leaving our own offer standing made the list read back
as an agreement, because after a handshake nothing distinguishes the offer from
the outcome. Two things break on that:
- with the offer left standing, this server would read
ApplicationProtocols[0] and get its own first advertisement - the
registry would always resolve something, the fallback below would be
unreachable, and a client sending no ALPN would be quietly served by
whatever sorted first, a position AlpnPriority sets for unrelated reasons;
- certificate selection keys off ApplicationProtocols[0] directly
(TlsLayer.InternalGetMyServerCertificate), so a no-ALPN client was answered
with the leaf chosen for our first advertised token. With a tls-alpn-01
challenge installed the engine seeds 'acme-tls/1' ahead of the registry,
which means an ordinary client was served the CHALLENGE certificate.
The connection asks the server to resolve it (ResolveProtocolFor), which
consults the registry and applies tFallbackPolicy on a miss:
fbpRefuse no plugin, the connection is closed. THE DEFAULT: a
client offering no ALPN is refused unless you choose
otherwise. Set one of the two below to serve such
clients. Separately, the engine will already have sent
a fatal no_application_protocol (120) when the offered
set intersected nothing, which is an earlier and
different refusal.
fbpUseFallback use the registry's FallbackProtocol.
fbpFirstRegistered use the FIRST ENTRY IN THE LIST. That is the
highest-priority registration, not the earliest one -
the list is kept in descending priority order. This is
the setting that serves a no-ALPN client the way a web
server usually should.
THE CONTENT LAYER HAS ITS OWN, SEPARATE DEFAULT. TCustomTLS_ContentLayer
exposes ServedProtocol and AlpnFallbackPolicy, defaulting to afpFirstOffered -
"serve the first thing we offered" - because that is what every consumer
reading ApplicationProtocols[0] has always received, and the layer is shared
with the Indy, Synapse and blocking-component stacks. This server does not use
it: it reads SelectedProtocol and states the no-ALPN rule once, in
FallbackPolicy, because two knobs for one decision is how they come to
disagree.
THE ONE CLEARTEXT PORT: PlainTextRedirectPort.
A server that answers only TLS still has to say something to the browser that
typed the bare host name. Set PlainTextRedirectPort (0, off, by default) and the
component binds that port too - conventionally 80 - purely to answer ONE request
per connection with a redirect and close.
IT IS NOT AN HTTP SERVER AND WILL NOT BECOME ONE. Nothing is routed, no body is
read, no keep-alive is honoured: one buffer in, one response out, socket closed.
A request larger than 8 KiB, or one that does not arrive within five seconds, is
dropped without a reply, and at most 64 of these exchanges run at once. Those
bounds are deliberately small - the port exists to redirect people to the port
that does the work.
IT IS NOT PART OF THE REACTOR. Redirects are handled on short-lived threads of
their own and never touch an I/O thread, so a slow or hostile peer on the
cleartext port cannot occupy capacity that belongs to TLS connections. The
listener binds AFTER the TLS port and is torn down BEFORE it, so the server never
advertises a redirect to a port it is not yet serving, or outlives it.
WHICH PLUGIN ANSWERS. A cleartext connection negotiated nothing - there is no
ALPN without TLS - so it is resolved exactly like a TLS connection that offered
no ALPN: through FallbackPolicy, above. The plugin it lands on must implement
iAppPlainTextRedirect:
iAppPlainTextRedirect = interface
procedure DataReceived(aData: Pointer; aLen: Integer);
end;
One method, because there is one exchange. A plugin that does not implement it
simply does not serve this port, and the connection is closed. StreamSec's own
HTTP/1.1 plugin implements it - see HTTP.txt for the event it surfaces and for
the open-redirect trap that event exists to close.
SO IT TAKES TWO SETTINGS, NOT ONE, and setting only the port is the common
mistake: with FallbackPolicy left at its fbpRefuse default, every cleartext
connection is refused and the port appears dead. Pair PlainTextRedirectPort with
fbpUseFallback and mark the answering plugin (HTTP/1.1's IsFallback), or with
fbpFirstRegistered if the highest-priority plugin is the right answer.
OnProtocolSelect gives the application the last word per connection. The
resolved iAppProtocol.CreateSession(transport) mints the per-connection
iAppSession, and iAppSession.Opened fires. There is no worker-pool slot to take
at this point - the session runs on the reactor thread that delivered the bytes
(section 6).
4.3 Why the contract has the shape it has
Three interfaces, all 'i'-prefixed with a GUID, declared in section 8:
iAppProtocol a protocol descriptor advertising an ALPN Token, and the
factory for sessions. Registered with AddProtocol - not
'Register', which is IDE-hostile. The Token is what the
HANDSHAKE matches (FindProtocol / ResolveProtocol); the
REGISTRATION is keyed by the instance, so RemoveProtocol takes
an iAppProtocol and returns whether it was there. Nothing
forbids two registrations sharing a token, and a token-keyed
removal would take the first match - which need not belong to
the caller. Registering an instance twice re-seats it rather
than duplicating it, so a second entry can never survive the
registrant and dangle.
CreateSession MAY ANSWER nil, and a component plugin does
exactly that once it has been freed: its adapter is refcounted
and can outlive it in a registry the component never knew
about, so the destructor detaches the back-pointer instead of
leaving it dangling. nil means "I decline this connection" and
the connection is closed the same way an unresolved ALPN is.
iAppSession one per admitted connection. Verb-named callbacks (Opened,
DataReceived, EarlyDataReceived, Closed) - no 'On' prefix, which
is reserved for component event properties.
iAppTransport the back-channel the session writes through (Send, Close) and
inspects (NegotiatedProtocol, NegotiatedVersion, RemoteAddress,
ExportKeyingMaterial). tTLSConnection implements it, so a plugin
never touches the socket or the TLS engine directly.
The registry's names avoid the reserved-ish ones for the same reason:
AddProtocol / FallbackProtocol / FallbackPolicy rather than Register / Default,
and the plugin key is Token rather than Name, which would collide with
TComponent.Name.
--------------------------------------------------------------------------------
5. ADMISSION CONTROL - THE TWO TIERS, AND WHAT IS ENFORCED TODAY
================================================================================
Two SEPARATE bounds, because they stress different resources:
H = MaxConcurrentHandshakes caps concurrent in-flight handshakes; sized to CPU
(asymmetric crypto). Default 256.
S = MaxLiveSessions caps live established sessions; sized to memory
(key schedule + per-connection RNG + record buffers + chain). Default 8192.
THIS is the advertised concurrent-client ceiling.
tTLSAdmissionController is four calls and two counters:
Admit: tAdmissionVerdict avRefuseBusy when S is reached, avDeferHandshake
when H is reached, otherwise avAdmit - and avAdmit
reserves a handshake slot.
HandshakeCompleted(aSuccess) releases the handshake slot and, on success, takes
a session slot.
SessionClosed releases the session slot.
ActiveHandshakes / read-only observability.
ActiveSessions
MaxConnectionsPerPeer (default 0, no limit) caps the live connections from one
peer address, from the accept on. A connection over it is closed there, before
Admit takes a token, and OnPeerRefused hears prTooManyConnections, so one
address cannot take the handshake slots of everybody else. Whether one address
is one client is the application's knowledge, which is why it is off by
default.
What counts as one address is PeerSourceKey's answer (it calls
stSocketAddress.SourceAddressKey), not the text the listener reports: an IPv4
address is itself, an IPv4-mapped IPv6 address (::ffff:a.b.c.d) is that IPv4
address, and any other IPv6 address counts by its first
cPeerSourceIPv6PrefixBits bits, 64. A port, brackets, a zone and the case of
the hexadecimal make no difference. 64 is chosen, not measured: RFC 4291
sec.2.5.4 gives a global unicast address a 64-bit interface identifier, so one
host may hold every address of its /64, and counting those one by one counts
nothing. What it trades: everybody behind one IPv6 /64 - a household, an
office, a carrier that gives one /64 to many customers - shares one limit, as
everybody behind one IPv4 NAT does. PeerConnections(aPeer) reads the count of
the source aPeer belongs to. A connection gives its slot back by the key it
took it with, whichever way it ends.
The same iPeerFilter instance can be assigned to TsmAsyncTLSServer.Filter and
TsmAsyncQUICServer.Filter. This shares address/token rules and activity/rate
state across TCP and UDP. QUIC screens before Retry or connection allocation,
counts only address-proven connections, and re-screens validated IP rebinding.
Its OnPeerRefused may be called per spoofed Initial datagram; handlers must be
cheap and applications must throttle their logging. See QUICServer.txt,
PEER FILTER, for the admission, token and rebinding rules.
WHAT ACTUALLY HAPPENS TODAY, which is less than the two-tier design above
promises:
* Admit is called from StartPeerTransport - that is, at ACCEPT, before a single
byte has been read. The handshake token is therefore not tied to a
ClientHello having arrived.
* BOTH non-admit verdicts do the same thing: the descriptor is closed
immediately. avDeferHandshake exists in the enum and is returned by the
controller, but nothing parks a connection and retries, so H is in practice a
second refusal threshold rather than a queue.
* There is no OnAdmission event. An application cannot override the verdict per
connection; the only knobs are the two capacities, both of which raise
ETLSAsyncServer if changed while Active.
* Stalled connections ARE reaped. Two published timeouts, both in
milliseconds, both 0 to disable:
HandshakeTimeout 15000 ACCEPT to a completed handshake. An ABSOLUTE
budget: armed once when the connection is
accepted and never re-armed by traffic.
IdleTimeout 0 an ESTABLISHED session's quiet time. An IDLE
deadline: re-armed by traffic in EITHER
direction. OFF by default - see below.
The difference is deliberate and is the whole defence. A last-activity timer
is defeated by a peer that dribbles one octet just inside every window, and
the handshake is where that costs an attacker least and the server most - so
the handshake budget is absolute and cannot be reset by sending anything. Once
a session exists, "idle" genuinely means idle and the re-arming form is right.
IdleTimeout IS OFF BY DEFAULT, deliberately. A protocol where a connection is
SUPPOSED to sit quiet for a long time - a callback or notification channel
that exists precisely so the server can speak later - is a normal thing to
build on this component, and defaulting the timeout on would reap exactly
those connections. Turn it on once the sessions that must survive it either
implement iAppSessionNudge or are covered by an OnConnectionNudge handler.
IT COUNTS BOTH DIRECTIONS, AND IT COUNTS PROGRESS RATHER THAN INTENT. Arming
only on receive would have made IdleTimeout mean "the peer has not spoken",
which is backwards for a server-push protocol: a callback connection busy
delivering notifications, all outbound, whose client need not answer, would
age out while actively in use. The outbound arm is on send COMPLETION, not on
Send: Send only means the application handed us bytes, and if the peer has
stopped reading those bytes sit in the FIFO while Send keeps being called - so
arming there would make a stalled connection look permanently busy and defeat
the timer that should catch it. A completion means the peer took the bytes.
That is also what makes IdleTimeout half of the answer to a slow-read peer:
MaxSendQueueBytes below bounds how MUCH such a peer can pin, and IdleTimeout
bounds how LONG it can pin it.
Expiry does not close anything by itself. It raises a NUDGE, which asks the
protocol plugin and then the application whether the connection should live -
see section 5.1. Only if neither objects does the connection close, and the
close is performed by the reactor's own I/O thread.
So saturation surfaces as "server full" and it is still the TLS session pool that
binds - the honest failure mode the design asked for. The graceful middle band,
where a well-behaved client rides out a short spike instead of being refused, is
still not there: that means calling Admit on the first ClientHello instead of at
accept, and giving avDeferHandshake a bounded wait. Section 10 keeps both.
--------------------------------------------------------------------------------
5.05 THE OUTBOUND BACKLOG - MaxSendQueueBytes, AND PACING WITHIN IT
================================================================================
Every gate in section 1 bounds what a peer can make the server ACCEPT. None of
them bounds what it can make the server HOLD ON ITS BEHALF - that is the job
of the cap below, on tReactorConnection's send FIFO:
Without it, a peer that issues requests and then stops reading its socket - a
zero TCP window, a normal state that needs no malice - would make every
response accumulate there as a heap copy, with nothing anywhere in the stack
paying attention. TLS provides no backpressure, HTTP/1.1 has none, and HTTP/2
flow control does not cover header frames. On the HTTP/1.1 path the body is
already its third copy by the time it is queued.
MaxSendQueueBytes (default 1 MiB) is a per-connection ceiling on QUEUED octets:
what was handed to Send while an earlier send was still in flight. The buffer in
flight itself is not counted against it.
A SINGLE LARGE Send IS NOT SAFE FROM IT, because something is in flight far more
often than a plugin can see:
* Right after a TLS 1.3 handshake the server's NewSessionTicket flight is. A
client that sends its request directly behind its Finished - OpenSSL and
Node do - has the whole of the first response queued behind that flight.
* On HTTP/2 the earlier frames of the same connection are, and a browser's
WINDOW_UPDATE lets a whole flow-control window be produced at once
(Chromium opens 6 MiB per stream and 15 MiB for the connection).
A plugin that hands over more than the ceiling in one call while anything is in
flight has its connection closed - a large download stops part-way, or a fresh
connection receives nothing at all.
PACING. A plugin that sends more than a few kilobytes at a time therefore paces
itself, with two optional companions (section 8.1):
iAppTransportFlow on the transport. SendCredit is how many octets of
application data Send can take now: net of TLS record
overhead, counting the buffer in flight as well as the
queue, and holding a quarter of the ceiling back for what
the stack sends on its own (alerts, close_notify, a
protocol's control frames). SendPending is what has been
handed over and not yet taken by the peer.
iAppSessionDrain on the session. Drained(aPending) runs after every
completed send: the peer took a buffer, so there may be
room for the next part.
A plugin that keeps each Send within SendCredit and sends the rest from Drained
is never the one the ceiling closes. The HTTP/1.1 and HTTP/2 plugins in
StreamSec.Mobile.HTTPS work this way: they keep at most about 1 MiB of a
response with the transport, whatever the ceiling, and a body sent from a file
is read from the file as it goes rather than copied into memory first
(HTTP.txt).
Drained runs on an I/O thread with the connection's gate held, like
DataReceived, and may Send. On the POSIX reactors a write can complete inside
the Send that made it, so Drained can arrive while the session is still sending;
the HTTP sessions note that and carry on from their own loop.
* Breaching it closes the connection, and is NOT vetoable. By the time it trips
the memory is committed; asking a handler what to do would hold it longer.
This is the one bound in the subsystem with no nudge in front of it.
* IT IS REPORTED. OnSendQueueOverflow fires once per connection, just before
the close, with the queue, the buffer in flight and the refused buffer's
size. Without a handler the close is silent - which is how a download that
stops part-way leaves nothing in a server log - so a server should log it.
* It bounds SIZE. IdleTimeout bounds DURATION, because the idle deadline is
re-armed on send COMPLETION - so a peer that has stopped reading stops
re-arming and is reaped. The two are meant to be used together; with
IdleTimeout off, this cap is doing all the work. A paced download re-arms
the deadline with every piece the peer takes, so IdleTimeout does not have
to outlast a whole download.
* Size it from evidence: tTLSConnection.SendQueueHighWater reports the most any
connection ever queued, SendInFlightBytes the buffer being sent and
SendPendingBytes the two together. AGGREGATE EXPOSURE IS THIS TIMES
MaxLiveSessions - 1 MiB x 8192 is an 8 GB worst case - so an operator should
lower one, the other, or both. A server-wide budget is section 10 open work.
* 0 disables the cap entirely (unbounded queue) and is not advisable against
untrusted peers. SendCredit then answers MaxInt, and the HTTP plugins still
keep to their own 1 MiB.
HOW EACH DIRECTION ENDS. A session that implements iAppSessionShutdown (found
with Supports, once, when the session is created) hears of each direction:
ReceiveClosed nothing more will be delivered. After the peer's
close_notify, or a half-close (FIN) without one, every
octet that came before it has reached DataReceived first.
After a FIN, or a TLS 1.3 close_notify, the session may
still Send, and ends the connection with Close(True), which
sends this side's close_notify. After a TLS 1.2
close_notify the server answers and closes as soon as
ReceiveClosed returns, and a Send from ReceiveClosed is
dropped (RFC 5246 section 7.2.1). On a fatal alert or
teardown it comes with SendClosed, and data still parked
for a paused session is discarded.
SendClosed this side can send nothing more: its close_notify went out
(also from inside the session's own Close), a fatal alert
was sent or received, or the connection is going away.
Each is called at most once, both before iAppSession.Closed, which stays the
last call and the place to detach. They run like DataReceived: on an I/O
thread, gate held, may Send and Close, must not block; raising closes.
For such a session a FIN does not end the connection at once: the server stops
reading and keeps the write side open, so the reply to a request the peer sent
before half-closing still goes out. After the peer's close_notify on TLS 1.2 the
server answers at once (RFC 5246 section 7.2.1); on TLS 1.3 the session may
reply first. If the session does not close, the server closes gracefully after
IdleTimeout, or after cPeerCloseGraceMs (30 seconds, chosen, not measured) when
IdleTimeout is 0: it then asks the session and the application again (section
5.1) and closes only if they do not answer nvKeepAlive. A completed send does
not cancel that bound, and after the peer's close a keep-alive with aRearmMs 0
is asked again every cPeerCloseGraceMs instead of leaving deadline scope. A
session without the interface is told nothing new, and a FIN ends its connection
at once, as it always did. The HTTP/1.1 plugin implements it: once the peer has
finished, it closes after the last response it can answer, or at once when no
response is leaving - a partial request still buffered can never complete.
--------------------------------------------------------------------------------
5.1 THE NUDGE - ASKING BEFORE CLOSING
================================================================================
A timeout that simply kills the connection is wrong for any protocol where being
quiet is legitimate: a session parked waiting on an external event looks exactly
like a stalled peer from the transport. So an expiry is a QUESTION, asked in this
order, and the answer decides:
1. THE PROTOCOL PLUGIN, if it implements iAppSessionNudge. This is OPTIONAL and
is reached by QueryInterface on the session object a plugin returned from
CreateSession - it is deliberately NOT a method on iAppSession, so every
existing plugin keeps working untouched and is simply not asked.
iAppSessionNudge = interface
function Nudged(aReason: tNudgeReason;
var aRearmMs: Cardinal): tNudgeVerdict;
end;
2. THE APPLICATION, through OnConnectionNudge on the component. It receives the
plugin's answer in aVerdict and has the last word:
procedure (Sender: TObject; aConnection: tTLSConnection;
aReason: tNudgeReason;
var aVerdict: tNudgeVerdict; var aRearmMs: Cardinal)
tNudgeReason nrIdle an established session went quiet
nrHandshakeStalled a handshake never completed
nrRequestStalled a budget the session set ran out (8.1)
nrApplication the application raised the nudge itself
nrShutdown the server is going down - wind up now
tNudgeVerdict nvClose let it go (THE DEFAULT AT EVERY LAYER)
nvKeepAlive hold it open
nrShutdown IS THE GRACEFUL-CLOSE NOTIFICATION, and it is why the nudge is a
question rather than a kill. Deactivate raises it on every live connection
BEFORE any close_notify is sent, so a session is asked to wind up while its
transport still works. Without it, the only shutdown signal a session would
get is iAppSession.Closed - which arrives at teardown, runs with the
per-connection gate held and therefore must not block: a notification that
the connection is already gone rather than a chance to finish. A session
answering nvClose (the default) is closed immediately; one answering nvKeepAlive
survives into the close_notify sweep and the drain, which DeactivateTimeout
bounds - so it can ask for more time and cannot hold shutdown open.
aRearmMs is read only when the verdict is nvKeepAlive: it is how long until
the question is asked again. It ARRIVES PRE-LOADED with the period that would
apply anyway, so a layer that answers nvKeepAlive without touching it keeps
being asked. For nrRequestStalled that is what is left of the idle deadline
already running (0 when none is): a session budget is not the idle deadline,
and nvKeepAlive with aRearmMs left alone leaves that deadline where it was.
Setting it to 0 means "stop asking" and takes the connection out of deadline
scope entirely (except after the peer's close - close_notify or FIN - where 0
is asked again every cPeerCloseGraceMs) - an explicit opt-in on purpose,
because a connection with no deadline is one whose peer can vanish without a
FIN and never be noticed. Prefer an application-level heartbeat over an
indefinite veto.
A session waiting on an external event stays alive like this:
procedure TForm1.ServerConnectionNudge(Sender: TObject;
aConnection: tTLSConnection; aReason: tNudgeReason;
var aVerdict: tNudgeVerdict; var aRearmMs: Cardinal);
begin
if (aReason = nrIdle) and MySessionIsWaitingForSomething(aConnection) then
aVerdict := nvKeepAlive; // aRearmMs left alone: keep asking me
end;
THE IN-LIBRARY EXAMPLE IS tSnipTLSSession (StreamSec.Snip.TLSServer), which
implements iAppSessionNudge because a snip connection is supposed to sit quiet -
it exists so the server can speak later, so without answering the idle question
it would be indistinguishable from a stalled peer. It answers nrIdle with
nvKeepAlive while it is still being served, leaving aRearmMs alone so the
application still gets a say every period, and answers nrShutdown by signalling
its serve loop to unwind and then nvClose.
SILENCE IS CONSENT. With no plugin interface and no handler, the verdict stays
nvClose and the connection is reaped - a deadline that can be ignored by saying
nothing is not a deadline.
CONTRACT for both callbacks: they run on an I/O thread with that connection's
gate held. They must not block, must not close the connection themselves, and
must not call back into the server. The close, if any, happens when they return.
A NOTE ON HOLDING CONNECTIONS OPEN. nvKeepAlive with aRearmMs = 0 takes the
connection out of every deadline the server has. That is a real capability and
also a real way to exhaust MaxLiveSessions with connections nothing will ever
reap, so an application that uses it owns the lifetime it just took over.
tTLSConnection.RequestNudgeFor(aReason) raises the same question from
application code, from any thread, and ArmDeadline / CancelDeadline set that
connection's deadline directly.
--------------------------------------------------------------------------------
6. THREADING, SHARDING & BUFFERS
================================================================================
THREADS.
- ONE listener daemon thread: Accept -> StartPeerTransport, nothing else.
- A fixed I/O-thread pool inside the reactor (IOThreadCount, 0 = core count),
servicing completion or readiness for every live connection. Connection
lifetime is decoupled from thread lifetime, which is what stops threads
binding before TLS.
- No application-worker pool. A plugin's DataReceived runs INLINE on the
reactor thread that delivered the bytes, so a blocking plugin blocks an I/O
thread and, through the per-connection gate, its own connection. Plugins are
expected to be non-blocking; the pool that would fix this is open work
(section 10).
PER-CONNECTION SERIALIZATION IS THE LOAD-BEARING GUARANTEE. The TLS record and
handshake state machine is not re-entrant, so each connection carries a gate
(tReactorConnection.Enter/Leave) and the reactor keeps a SINGLE outstanding
recv per connection. Opened / DataReceived / Closed for one connection are
therefore strictly serialized and never re-entered concurrently, and Send /
Close are mutually exclusive with them - safe to call from inside DataReceived.
This is why a plugin engine needs no locking of its own, and it is the direct
mitigation for the class of problem the SSH thread-safety notes record.
EnforceSingleRecv is the debug switch that asserts the invariant rather than
trusting it; the POSIX backends carry a duplicate-event discard specifically to
keep it true.
Threads are NOT affinitized to connections. Per-connection TLS state is
thread-agnostic - ephemeral keys, peer points and all key material live in the
GLOBAL DSI pool or in RTL TBytes, never in a thread-local pool - so any worker
may drive any connection across successive callbacks, and the reactor keeps one
shared completion port with free migration.
SHARDING, AND WHY IT IS A THROUGHPUT KNOB. Each connection is round-robined
onto one of EngineCount TsmSimpleTLSInternalServer engines for life (0 = match
the I/O thread count). One engine is already self-consistent: its session table
and its TLS 1.3 ticket store sit behind its own internal lock. But then every
connection contends on that one lock for the per-record table lookup and the
O(n log n) sorted insert on each accept. N engines spread that onto N locks, so
handshakes run ~N-way parallel - DriveHighWater reports the maximum concurrency
actually observed, which is N when sharded and 1 with EngineCount = 1.
TRADEOFF: the ticket store shards with the engine, so TLS 1.3 resumption and
0-RTT only hit when a reconnect lands on the issuing shard (~1/N). A shared or
stateless/encrypted ticket store is the fix; it is open work.
AND IT IS PAID AT EVERY ACTIVATION. Each engine carries its OWN certificate
store, so OnConfigureEngine runs per shard and each shard's TLSSetupServer
follows it. That is real work - of the order of half a second per shard for an
ordinary web-server configuration - and it happens on the thread that set
Active, before the listener binds.
THE DEFAULT SCALES WITH THE MACHINE, which is the part that surprises: 0 means
one engine per I/O thread, and one I/O thread per core. On a 32-core server that
is 32 certificate stores to build, so Active := True takes some twenty seconds
and the server appears to hang with nothing bound and nothing logged. The same
configuration on four cores binds in under three.
So choose EngineCount for the handshake rate the deployment actually sees rather
than leaving it to the core count. A handful of shards is plenty for most
servers, keeps activation about a second, and costs nothing once running - the
sharding is about handshake concurrency, not about steady-state throughput on
established connections.
PROVISION THE IDENTITY ONCE, NOT PER SHARD. Building the stores is per shard
and irreducible, but READING the PKCS#12 file need not be. The component's own
ImportFromPFX parses and decrypts the file once and hands the result to every
shard; LoadRootCertsFromFile and ValidatePublicKeyPairs cover the whole bank
the same way.
CALL THEM BEFORE Active := True. On a dormant component they touch no engine -
there is none yet - they RECORD the request, and the recorded sequence is
applied to the whole bank as it is built. That deferral is the point: the
application provisions once, in the order it chooses, and the component
decides when and how often the material reaches an engine.
Server.LoadRootCertsFromFile(cAnchors);
Server.ImportFromPFX(cIdentity, tDualSecretKey.CreateForPFX(cPassword));
Server.OnConfigureEngine := ConfigureEngine;
Server.Active := True;
procedure TForm1.ConfigureEngine(Sender: TObject; aIndex: Integer;
aEngine: TsmSimpleTLSInternalServer);
begin
{ PER-SHARD SETTINGS ONLY - what the component cannot fan out. }
aEngine.TLSOptions.Assign(...);
aEngine.IncludeRootInTLSChain := False;
end;
DO NOT CALL THE PROVISIONING METHODS FROM OnConfigureEngine. By the time the
first handler runs the bank already exists, and all three refuse at that point
rather than pretend - the recorded material has been applied and a late call
could reach some shards and not others. A handler that needs to know what was
provisioned reads it off the aEngine it was handed.
ANCHORS BEFORE IDENTITY, and that order is a requirement rather than a habit.
Importing a leaf pairs it with its issuer, and the issuer is looked for in the
stores as they stand at that moment - so anchors loaded afterwards are too
late and the chain is left incomplete. Where the automatic AIA caIssuers chase
is enabled (OnFetchCAIssuer assigned), the same miss turns into a network
fetch on the thread that set Active, before anything is bound. Load the
anchors first and the issuer resolves locally, which is why the two calls
appear in that order above.
A RECORDED IMPORT IS REPLAYED BEFORE OnConfigureEngine, on shards no handler
has seen yet, so a trust setting made in the handler does not apply to it. A
CA in the file whose issuer is not in the store at that moment is filed only
with LocalExplicitTrustByDefault on, which a new shard does not have: the CA
is refused and the shard holds the leaf without it. Turning the setting on in
the handler does not bring the CA back, and a client that verifies cannot
build the chain from what the shard then sends. Two orders do file it: the
anchor recorded first, as above; or, in the handler, the trust setting and
then aEngine.ImportFromPFX on that shard, at the cost of one parse per shard.
HOW MUCH THIS MATTERS DEPENDS ON HOW THE PFX WAS WRITTEN, and the range is
wide. A PKCS#12 file is opened with a password-derived key, and the iteration
count is the writer's choice: the compatibility encoding this library writes
by default uses 2000, while PBES2 - what ExportToPFX produces unless told
otherwise - uses 131072. One import costs roughly 50 ms in the first case and
750 ms in the second, so importing per shard on a bank of eight costs about
0.4 s or about 6 s. Doing it once puts the second case back under 1 s.
DO NOT CALL TLSSetupServer FROM OnConfigureEngine. The component calls it on each
engine as soon as the handler returns, so a handler that calls it too does the
whole store setup twice. Configure in the handler; let the component commit.
NOTE that the per-engine lock is coarser than the concern it guards: record
crypto is per-connection (cipher, sequence number and IV live on the
connection's own content layer), so it needs only per-CONNECTION serialization,
which the gate already provides. That is exactly what UseDirectLayer exploits
(section 3).
BUFFERS. There is no server-level slab allocator. The reactor posts a receive
buffer per connection and the IOCP backend copies each send payload into a
per-operation slab, so buffer memory tracks live connections and queued sends
rather than peak accepted descriptors. Handshake key material is ProtectClear'd
on release. Because there is no worker pool, application buffers are whatever
the plugin allocates for itself, bounded by S like everything else behind gate
3.
--------------------------------------------------------------------------------
7. CONNECTION LIFECYCLE
================================================================================
There is no tConnectionState enum: each transition below is already implied by
which object exists and which callback is running. The phases, in order:
ACCEPTED The listener returns a handle and a peer address.
StartPeerTransport asks the admission controller for a verdict
(section 5) and, on avAdmit, round-robins the connection onto a
shard, constructs the tTLSConnection, attaches it to the reactor
and posts the first receive. A non-admit verdict closes the
handle here and nothing else is built.
HANDSHAKING Reactor bytes are pumped into the connection's content layer
and the ciphertext it produces goes back out through the
reactor's send path (section 3). The connection holds a
handshake token for this whole phase. None of this is reachable
from outside the component.
0-RTT Optional, TLS 1.3 only. When early data is accepted, decrypted
0-RTT plaintext is delivered to iAppSession.EarlyDataReceived.
Supplying or omitting the EarlyData stream is the accept/refuse
switch, and omitting it is the safe default; replay is gated by
OnTLSCheckEarlyDataReplay and MaxEarlyDataSize on the engine.
A plugin that cannot make a request idempotent should ignore
this callback, which is what both HTTP sessions do.
ESTABLISHED The handshake completes: HandshakeCompleted(True) trades the
handshake token for a session token, the ALPN token is resolved
to a plugin (section 4), CreateSession mints the iAppSession and
Opened fires, then OnHandshakeDone. Steady state is
decrypt -> DataReceived, and the session writing through
iAppTransport.Send -> encrypt -> reactor send.
CLOSING Either side closes, or a fatal alert ends it.
iAppSession.Closed(aGraceful) fires, the session token is
released, the content layer is torn down (ProtectClear on key
material) and the connection detaches from the reactor. Then
OnConnectionClosed.
ONE RULE FOR PLUGIN AUTHORS: iAppSession.Closed runs with the per-connection
gate HELD. Never join a thread, wait on a lock that another thread takes under
the gate, or re-enter the transport from inside it - that is a deadlock, and it
is the one lifecycle mistake this contract makes easy to write.
DEACTIVATION mirrors it. Active := False stops accepting at once, then sends
close_notify to every live connection and waits up to DeactivateTimeout
milliseconds (default 30000) for them to finish; whatever is still connected
when the deadline passes is killed. DeactivateTimeout = 0 kills immediately.
Deactivate(aKill) is the explicit form. The teardown order matters and is
fixed: terminate the accept thread, stop the listener, join it, and only then
tear down connections, because the POSIX listener cannot be woken any other
way.
--------------------------------------------------------------------------------
8. THE PLUGIN CONTRACT & THE COMPONENT SURFACE
================================================================================
This is the part of the unit a third party must implement or call, copied from
the declared interface rather than proposed. Everything else - the reactor
internals, the connection control block, the admission counters - is reachable
but is not a contract, and the unit is the reference for it.
{ ---------------------------- the plugin contract --------------------------- }
iAppTransport = interface
['{5E2A7C10-8B4F-42D9-B3E6-1A9C0D7F4B28}']
function GetNegotiatedProtocol: OctetString;
function GetNegotiatedVersion: TProtocolVersion;
function GetRemoteAddress: string;
procedure Send(aData: Pointer; aLen: Integer);
procedure Close(aGraceful: Boolean);
function Instance: tObject;
{ RFC 8446 s7.5 exporter for THIS connection. Empty unless a TLS 1.3
handshake completed - consumers MUST fail closed. }
function ExportKeyingMaterial(const aLabel : AnsiString;
const aContext: tBytes;
aLen : Integer): tBytes;
property NegotiatedProtocol: OctetString read GetNegotiatedProtocol;
property NegotiatedVersion: TProtocolVersion read GetNegotiatedVersion;
property RemoteAddress: string read GetRemoteAddress;
end;
iAppSession = interface
['{B1D9F4A0-3C82-4E57-9A6B-0F2D8C1E5A73}']
procedure Opened;
procedure DataReceived(aData: Pointer; aLen: Integer);
procedure EarlyDataReceived(aData: Pointer; aLen: Integer);
procedure Closed(aGraceful: Boolean);
function Instance: tObject;
end;
iAppProtocol = interface
['{7C4E1A82-9F3D-4B16-A0C5-2E8D6F0B1A34}']
function GetToken: OctetString;
function GetDescription: string;
function CreateSession(const aTransport: iAppTransport): iAppSession;
property Token: OctetString read GetToken;
property Description: string read GetDescription;
end;
iAppProtocolRegistry = interface
['{9A0F3D6C-1E74-4B85-8C2A-6D5F0B39E1C7}']
procedure AddProtocol(const aProtocol: iAppProtocol);
function RemoveProtocol(const aProtocol: iAppProtocol): Boolean;
{ FindProtocol/ResolveProtocol answer the FIRST entry whose Token matches.
Since the list is kept in descending priority order that is the
highest-priority entry answering to it, which is the server's own stated
preference - and what PickProtocol would have chosen anyway. }
function FindProtocol(const aToken: OctetString): iAppProtocol;
function AdvertisedProtocols: TApplicationProtocols;
function ResolveProtocol(const aNegotiated: OctetString): iAppProtocol;
property Count: Integer ...;
property Protocols[aIndex: Integer]: iAppProtocol ...;
property FallbackProtocol: iAppProtocol ...;
property FallbackPolicy: tFallbackPolicy ...;
end;
tAdmissionVerdict = (avAdmit, avDeferHandshake, avRefuseBusy);
tFallbackPolicy = (fbpRefuse, fbpUseFallback, fbpFirstRegistered);
ETLSAsyncServer = class(Exception);
function NewAppProtocolRegistry: iAppProtocolRegistry;
Note what is NOT there: iAppTransport has no ContentLayer - a plugin cannot
reach the TLS layer object. ExportKeyingMaterial is the sanctioned way to bind
to the channel, and what a session may READ about the handshake is section 8.2,
which hands over facts rather than the layer. A completed send is not on
iAppSession either: a session that needs it implements iAppSessionDrain
(section 8.1 and section 5.05).
--------------------------------------------------------------------------------
8.1 THE OPTIONAL COMPANIONS, AND WHY THEY ARE SEPARATE INTERFACES
================================================================================
iAppTransport, iAppSession, iAppProtocol and iAppProtocolRegistry are PUBLIC
CONTRACTS implemented outside the library. Widening one breaks them, so
anything added later is a SEPARATE interface reached by QueryInterface, and a
party that does not implement it is simply not asked. That is what makes the
mechanism additive rather than a version break, and it is the pattern to follow
for anything added next.
iAppSessionNudge on the SESSION, asked before a deadline closes it
(section 6)
iAppSessionDrain on the SESSION, told after every completed send that
the peer took a buffer (section 5.05)
iTLSConnectionInfo on the TRANSPORT, what the handshake decided (below)
iAppTransportDeadlines on the TRANSPORT, for a session whose limits depend on
where its conversation has got to. SetIdleLimit replaces
IdleTimeout for this connection, 0 meaning no idle
deadline; a different value starts that period now.
SetSessionBudget raises nrRequestStalled once after that
many milliseconds, whatever traffic there is meanwhile,
0 cancelling it; nvKeepAlive does not set it again
and leaves the idle deadline where it was.
LoadPercent is the fuller of live sessions against
MaxLiveSessions and handshakes against
MaxConcurrentHandshakes. ServerIdleMs reads IdleTimeout,
for a session that will not run longer than the
application asked. ExpireIdleLimit ends the idle period
now, for a session whose own sends keep the deadline
moving: nrIdle comes at the next sweep, and nvKeepAlive
starts the period again. Call them from the session's
own callbacks. The mail sessions are the in-library
users (MAIL.txt section 10).
iAppTransportFlow on the TRANSPORT, how much Send can take now without
the backlog ceiling closing the connection, and how
much is still on its way (section 5.05)
iAppTransportAbort on the TRANSPORT, ends the connection now where Close
only asks (below)
iAppTransportFlow = interface
['{1955F943-8067-485A-B632-5C79F1328BE7}']
property SendCredit: Integer ...; { application octets; MaxInt: no cap }
property SendPending: Integer ...; { wire octets in flight + queued }
end;
iAppSessionDrain = interface
['{43F08F4E-5A6F-4C66-8DAC-65D4050D4E18}']
procedure Drained(aPending: Integer);
end;
iAppTransportAbort = interface
['{A7D3E915-2C64-4B8F-9E07-5B1C8F4A6D23}']
procedure Abort;
end;
Close, graceful or not, only asks for the close: the connection goes once what
is queued has been sent, so a peer that has stopped reading keeps it open until
a deadline reaps it, and with IdleTimeout 0 there is none. Abort discards what
is queued and has the reactor tear the connection down on one of its own
threads, without asking the session or OnConnectionNudge. It never takes the
connection's gate and never waits for a session callback: it takes only the
reactor's short wake-queue lock, which is never held while a gate is waited for.
So it is safe from any thread, including one a session callback is waiting for;
a callback running on the connection finishes first. On a reactor backend
without an out-of-band wake the close stays requested and happens at the
connection's next completion. tTLSConnection implements it; reach it with
Supports on the iAppTransport.
--------------------------------------------------------------------------------
8.2 iTLSConnectionInfo - WHAT THE HANDSHAKE DECIDED
================================================================================
var lTLS: iTLSConnectionInfo;
if Supports(aTransport,iTLSConnectionInfo,lTLS) then
if lTLS.PeerCertificatePresent then ...
iTLSConnectionInfo = interface
['{7C4E1B95-2D68-4A3F-8E01-6B5C93A0D742}']
property Version: TProtocolVersion ...; { cTLS12vmm / cTLS13vmm }
property VersionName: string ...; { 'TLS 1.3' }
property CipherSuite: TCipherSuite ...; { the two IANA octets }
property CipherSuiteName: string ...; { 'TLS_AES_128_GCM_SHA256' }
property ServerName: string ...; { SNI; CLIENT-SUPPLIED }
property KeyExchangeGroup: Word ...; { grp_*; 0 on TLS 1.2 }
property KeyExchangeGroupName: string ...; { 'x25519' }
property IsResumed: Boolean ...;
property PeerCertificate: iCertificate ...; { nil without mTLS }
property PeerCertificatePresent: Boolean ...;
end;
function TlsVersionName(const aVersion: TProtocolVersion): string;
function TlsCipherSuiteName(const aSuite: TCipherSuite): string;
Every transport this unit creates implements it. It reads through to the live TLS
session, so hold it no longer than the transport and expect every member to
answer its empty value once the connection has closed - the accessors take the
same locks ExportKeyingMaterial takes and answer empty rather than faulting.
FOUR THINGS TO KNOW BEFORE USING IT:
* ServerName IS ATTACKER-SUPPLIED AND UNAUTHENTICATED. The client chooses the
string; nothing in the handshake ties it to the client's identity, and a name
matching no certificate would not have stopped the handshake. Route on it,
never authenticate on it.
* KeyExchangeGroup IS TLS 1.3 ONLY and answers 0 on a 1.2 session, which
carries its curve inside the ServerKeyExchange rather than as a negotiated
group. There is no honest single answer spanning both, so it does not invent
one. After a HelloRetryRequest it holds the group finally used.
* THE PEER CERTIFICATE HAS ALREADY BEEN VERIFIED against the trust
configuration - one that failed would have failed the handshake. What this
adds is WHO it turned out to be, so an application can authorize on top of an
authentication that already happened.
* ON A RESUMED SESSION nothing was presented again. On TLS 1.3 there is no
certificate at all: the server asks for none on a PSK resumption and the
ticket does not carry the original one, so PeerCertificate is nil
(TLS.txt section 4.5). Test IsResumed if that distinction matters.
This does NOT contradict "the peer certificate is the engine's business": the
engine still decides whether to accept it, and this interface reports the
decision. A plugin cannot influence verification through it, only read the
outcome. StreamSec.Mobile.HTTPS wraps it as the string-valued
iHttpConnectionInfo that a request handler sees (HTTP.txt section 2.1); the
wrapper exists so the transport-agnostic HTTP core needs neither the TLS nor the
PKIX units.
A SNIF METHOD served by TsnipTLSServer reaches the same interface for the
connection its call arrived on:
lCert := TsnipTLSServer.CurrentPeerCertificate; // nil: no client certificate
lTLS := TsnipTLSServer.CurrentTransportInfo; // the whole iTLSConnectionInfo
Both read TsnifClassServer.CurrentContext, which belongs to the calling thread for
the duration of one call, and answer nil outside a call or on a connection that
is not snip over TLS. The same is available as IsnipTLSTransportInfo, by Supports
on CurrentContext.Connection - the way a method reaches IsnifChannelBinding - and
as TransportInfo / PeerCertificate on TsnipServerTLSOctetConnection. The
connection takes the interface once, when the snip channel is set up, and keeps
it while it lives; its members answer their empty values once the TLS session has
closed. On a resumed TLS 1.3 session there is no client certificate (TLS.txt
section 4.5), so a listener that authorizes on it runs with
Options.SessionResumption := False.
The two fields behind ServerName and KeyExchangeGroup are new on
TCustomTLS_ContentLayer - PeerServerName, recorded from the one point every
server-side ClientHello passes through, and NegotiatedGroup, recorded on both
sides once the group is settled. Both are written by the handshake and never by a
consumer.
{ --------------------- what the component publishes ------------------------- }
BindIP, BindPort (443), Active
PlainTextRedirectPort (0 = off)
IOThreadCount (0 = cores), EngineCount (0 = IOThreadCount)
UseDirectLayer (True), MaxConcurrentHandshakes (256), MaxLiveSessions (8192)
FallbackPolicy (fbpRefuse), DeactivateTimeout (30000)
HandshakeTimeout (15000), IdleTimeout (0 = off)
MaxSendQueueBytes (1 MiB)
OcspOptions: TOCSPOptions
OnConfigureEngine, OnHandshakeDone, OnConnectionClosed, OnProtocolSelect,
OnConnectionNudge, OnSendQueueOverflow, OnTLSIncomingAlert, OnTLSOutgoingAlert
EIGHT events: there is no OnAdmission, no OnConnectionAccepted and no
OnServerError. OnSendQueueOverflow is the one close the server makes on its
own initiative that would otherwise leave no trace - see section 5.05.
{ ------------------------- the TLS alerts of every shard -------------------- }
property OnTLSIncomingAlert: TTLSAlertEvent;
property OnTLSOutgoingAlert: TTLSAlertEvent;
Same signature as the per-engine events of the same name, and the SENDER IS THE
ENGINE that raised the alert rather than this component - so a handler can tell
the shards apart, and a handler written for a single TsmSimpleTLSInternalServer
works here unmodified. Every shard is routed to these two, so one handler answers
for all of them; an engine whose alert event was assigned from OnConfigureEngine
keeps what it was given.
ASSIGN AT LEAST ONE OF THEM IN A SERVER - and read this even if you do not want
the reporting. An engine with NO alert handler RAISES: EIncomingTLSAlert or
EOutgoingTLSAlert, for every alert except close_notify. That is the right default
for a client, where an alert means the one connection you cared about has failed
and an exception is how you want to hear it. On a server it is not: a
handshake_failure or protocol_version from a probing client is a routine event,
and it must not travel as an exception on a reactor thread. Assigning either
property routes every shard through this component, whose own handlers are silent
when nothing is assigned.
Fatal is the layer's own verdict and is a var parameter it acts on. Read it - it
is the natural split between a fatal log and a warning log, which is the pair most
servers want. Change it only if you mean to change how the connection ends.
Called on a reactor thread, inside the drive path, so treat it like any other
per-connection callback: do not block, and marshal anything that touches a UI.
Public but unpublished: Reactor, Admission, Protocols, BoundPort,
DriveHighWater and the test-only DriveWidenMs. On tTLSConnection itself:
RequestNudgeFor, ArmDeadline, CancelDeadline, DeadlineExpired, CheckDeadline,
and the backlog figures SendQueueBytes, SendQueueHighWater, SendInFlightBytes
and SendPendingBytes (section 5.05).
BoundPort is the port the TLS listener is bound to while Active, and 0
otherwise. With BindPort 0 the system assigns one; BindPort keeps the configured
value, so a restart asks for a fresh port again.
Unlike the capacities, the two timeouts may be changed while Active - they are
read when a deadline is armed, so a change takes effect on the next connection
(HandshakeTimeout) or the next inbound buffer (IdleTimeout).
Everything that defines the security parameters of a long-running connection
raises ETLSAsyncServer if written while Active - changing them under live
traffic would leave existing sessions on the old policy with no way to tell
them apart.
{ ---------------------- runtime operations after Active --------------------- }
AddCertificate / AddLocalCertificate / AddCRL / ClearExpiredSessionKeys
{ the iAcmeAlpnTLS surface }
TryBeginAcmeChallenge / EndAcmeChallenge / ProvisionAcmeChallenge /
AddTLSAcmeALPN / RemoveTLSAcmeALPN / AcmeAddCACertificate /
ReplaceTLSServerCertificate { component hot swap }
Deactivate(aKill)
Every one of these fans out to ALL shards, and that is mandatory rather than
tidy: the CA's validation connection is round-robined onto an arbitrary shard,
so a challenge present on one would be found ~1/N of the time, and a renewed
certificate installed on one would leave the rest serving the expired one.
Serving-certificate replacement visits shards one at a time, each under its
own TLSLock. The bank lock spans them, only to keep the shards alive: it is
held while activation builds them and Deactivate frees them, and while
ReplaceTLSServerCertificate or a certificate reload walks them, so Deactivate
on another thread waits for a walk to finish. It is taken before any shard
lock and never on a reactor thread; do not call ReplaceTLSServerCertificate
from a session callback, which Deactivate waits for. Within one engine
preparation completes
before any serving slot is published. A later shard's failure does not roll
back shards that already switched; retry the failed operation. Use one writer
per target, or serialize all application, ACME and reloader writes externally.
Concurrent writers can interleave shard by shard and leave a lasting mixture
of identities after both calls succeed. The reloader does not detect another
writer's later changes from its accepted digest. Chain and revocation checks
retain each engine's normal policy and fetch behavior.
Ordinary OCSP warming errors after publication are reported through the engine
OnWorkerError callback with the engine component as Sender and do not report
the committed swap as a failure. OnWorkerError also observes the fatal LOG
phase before OnWorkerFatal notification and exit 70. One worker serializes
queued warm-up passes and then exits. Publication does not join an earlier
fetch. Warm-up uses the assigned responder with its descendant state,
TrustedCertificates, linked stores and hooks. Changing or detaching Ocsp, or
receiving its destruction notification, waits for the in-flight fetch. Timeout
bounds each responder read, not the total exchange; slow-drip peers and custom
descendants can extend the wait without a finite total bound. Shutdown joins
the worker before destroying its stores. Custom descendants must detach Ocsp
before their destructor frees state used by CheckCertificate.
For externally published PFX files, use tCertificateReloader as described in
CertificateReload.txt. It stores the private key on every shard before filing
the leaf, so key lookup places the leaf in MyCerts. It also files the PFX's CA
bags with startup import semantics, then calls the component's
ReplaceTLSServerCertificate. The reloader uses the protected key-store surface
internally; applications use the supported provisioning and reloader APIs.
Reload certificate and CRL filing uses protected StoreReloadCertificate and
StoreReloadCRL fan-outs. Each engine holds its setup lock and TLSLock while
applying the startup store policy. Protected EngineGeneration changes when
activation creates a new bank, so CheckOnce can reapply the watched identity.
PFX CRL bags are decoded and filed with the startup CRL rules (MyCerts, then
RootCerts, then CollectedCertificates), after every certificate bag of the
file. A CRL bag that does not hold a DER CertificateList makes the import or
reload attempt raise. A reload whose own CRL bag, signed by an issuer in the
same PFX, revokes the leaf or a certificate in its chain is refused, as such
a file is unusable at startup.
ImportFromPFX is startup provisioning and raises while Active. Replacement
preserves the component name/algorithm rules. The array form of
ReplaceTLSServerCertificate also retires leaves on every shard, as
CertificateReload.txt describes; a new bank starts with none retired. EC
signing leaves with keyAgreement as well as digitalSignature, and leaves
without keyUsage, occupy the same ECDHE/TLS 1.3 slots as initial setup.
Selected sessions keep their certificate/key references; later full handshakes
use the new caches.
--------------------------------------------------------------------------------
9. WHAT THE COMPONENT DOES FOR YOU, AND THE ONE THING IT CANNOT
================================================================================
THE TLS-TO-SOCKET PLUMBING IS ENTIRELY INTERNAL. A consumer of this component
never calls a TLS API and never touches a content layer: not to set the server
up, not to feed it bytes, not to get plaintext back, not to close it. The
component owns the accept loop, the reactor, the shard engines, the per-connection
TLS state and the encrypt/decrypt path in both directions, and there is no
supported way to reach into any of it from outside. What a consumer works with is
exactly two things:
- CONFIGURATION, through OnConfigureEngine (called once per shard with that
shard's TsmSimpleTLSInternalServer) and the published properties. Load the
identity, the trust anchors, TLSOptions - cipher suites, supported groups,
key-agreement preferences, RequireClientCertificate, EarlyData /
MaxEarlyDataSize, VerifyServerName - and the certificate events there. Write
ONE handler; every shard is configured identically, and no configuration
state is duplicated in the component.
SETTINGS ARE PER SHARD; PROVISIONING THE KEY MATERIAL NEED NOT BE. Three
operations are offered on the component itself and cover the whole bank:
ImportFromPFX one parse of the file, into every shard
LoadRootCertsFromFile the anchors, into every shard at activation
ValidatePublicKeyPairs re-pairs certificates with keys on every shard
Call them before Active := True, as section 6 shows. The component records
the provisioning sequence until its shard bank exists. Provision the trust
anchors before recording the identity import. OnConfigureEngine supplies
per-shard settings; it cannot call these provisioning methods, and the
recorded sequence has already been applied when it runs, so a trust setting
made there does not reach a recorded import (section 6).
That is the whole of the component-level surface, and WHAT PUTS SOMETHING
ON IT IS COST AND ORDERING, not that it sounds like an operation.
ImportFromPFX qualifies on both counts. It runs in NON-CONSTANT TIME - it
parses the file and derives a key from a password, so what it costs is a
property of the file rather than of the call, and doing it per shard
multiplies whatever that turns out to be (section 6). And it is not
free-standing: the trust anchors have to be in place BEFORE it runs, so
LoadRootCertsFromFile or AddCertificate has to come first. A call with a
prerequisite and an unbounded cost is exactly the kind the component should
own, because the alternative is every application getting the order and the
repetition right by itself.
ASSIGNING A PROPERTY IS THE OPPOSITE CASE: constant time, no prerequisite,
and identical on every shard. The handler does it with no help, so the
component gains nothing by carrying it and the published surface stays
small - which is the point. Do NOT add delegate or shim getters here to
"expose" engine SETTINGS; they belong on the engine the handler was already
given, and mirroring them is what the TLSOptions grouping rule forbids.
- AN APPLICATION PROTOCOL, through the plugin contract of section 8. Bytes
arrive already decrypted at iAppSession.DataReceived and leave through
iAppTransport.Send, which encrypts them.
Everything else is a consequence of those two. OCSP stapling comes from
OcspOptions (one responder per shard, created and owned by the component); mTLS
is RequireClientCertificate on the engine, with the peer identity captured in the
engine's certificate events, because a plugin deliberately cannot reach the
content layer; ACME works because the component implements iAcmeAlpnTLS, so
TsmAcmeRenewalManager drives a tls-alpn-01 challenge against the whole shard bank
directly. The ALPN offer list is assembled from the registry merged with what the
engine seeded (section 4.1) - which is what lets an 'acme-tls/1' challenge and
the real protocols share one port.
0-RTT EARLY DATA - THE ONE PLACE A PLUGIN MUST COOPERATE
GENERAL ADVICE FIRST: LEAVE 0-RTT OFF. It is off by default (EarlyData =
edmDisabled) and that default is the right one for almost every deployment. What
it buys is one round trip on a resumed connection; what it costs is a class of
request that can be replayed, a second code path through your application, and a
configuration that is wrong in a way nothing will warn you about. Turn it on when
you have measured that the round trip matters AND the protocol on top of it is
written for replay - not because it is available.
WHAT THE TLS LAYER GUARANTEES BEFORE IT HANDS YOU ANY OF IT
A plugin never has to second-guess the layer. iAppSession.EarlyDataReceived is
called ONLY when every one of the following is already true, and there is no
configuration or failure mode in which it fires in breach of them:
- TLS 1.3 was negotiated, the session was RESUMED from a ticket THIS server
issued, and the client proved possession of its PSK (the binder verified).
- That ticket was claimed ATOMICALLY and is now gone. Of any number of
concurrent handshakes offering it, exactly one got through; a replayed 0-RTT
flight finds no ticket and cannot be accepted a second time. This is what
makes single-use the anti-replay mechanism rather than housekeeping.
- The store backing that claim promised tscAtomicConsume. One that cannot make
the claim atomic refuses 0-RTT outright.
- The PSK was the client's FIRST offered identity - the only one early data can
be keyed to; the ticket's cipher suite equals the negotiated suite EXACTLY;
the ticket's server name and key-exchange group match this connection.
- The ticket advertised a non-zero max_early_data_size, the engine policy is
edmAccept, and your OnTLSCheckEarlyDataReplay hook approved this exact
(ticket, ClientHello) pair.
- The records decrypted and authenticated under the client early-traffic key.
These are not unauthenticated octets.
So a session does not ask whether 0-RTT was really permitted, whether the ticket
was fresh, or whether the peer is who it claims. All of it has happened already.
WHAT THE TLS LAYER CANNOT CHECK, BECAUSE ONLY YOU CAN
Exactly one thing, and everything that follows from it: THE LAYER DOES NOT KNOW
WHERE YOUR MESSAGES BEGIN AND END. It moves an octet stream. It cannot tell
whether a flight holds one complete request, half a request, or five, because
finding out means parsing the very bytes whose trustworthiness is the question.
Only the application protocol knows its own framing, so only the application
protocol can decide what a unit of work is here. Three consequences:
- WHICH OPERATIONS ARE SAFE is a property of the request, not of the octets. A
GET is idempotent; a POST that moves money is not; at this layer they are the
same bytes.
- IDEMPOTENT AT THE PROTOCOL IS NOT IDEMPOTENT AT THE APPLICATION. A GET that
increments a counter is a replay hazard whatever the method says.
- A MESSAGE CAN STRADDLE THE BOUNDARY. If one of yours does, only you can know.
And the conservative reading is not "treat it as early" but REFUSE IT: a
straddled message is only half replayable, having been seen partly under one
security context and partly under another. The HTTP plugins answer 425 to
such a request whatever their policy says (HTTP.txt section 2.1).
That division is the whole of the cooperation this section is named for. The
layer answers "is this peer entitled to send early data, and is this flight
genuine?"; you answer "given that it is, what am I willing to DO before the
handshake finishes?".
AND IF YOU WANT NONE OF IT: leaving EarlyDataReceived empty DISCARDS the data,
which is safe only while 0-RTT is off or set to edmRejectAndRetry (where the
client resends in 1-RTT). Under edmAccept the server has ALREADY told the client
the data was taken, so it will not resend and the request is simply lost. The
HTTP plugins answer this with RFC 8470 - see HTTP.txt.
What the current interfaces give a session is a two-callback split, and that split
IS the signal in both directions:
iAppSession.EarlyDataReceived every byte delivered here is 0-RTT and therefore
replayable.
iAppSession.DataReceived every byte delivered here is 1-RTT. The FIRST
call to DataReceived on a connection that had
early data is the EndOfEarlyData boundary: the
client has finished its handshake and everything
from here on is replay-protected.
(the engine side) TCustomTLS_ContentLayer.EarlyDataStatus reports
the same phase as edsNone / edsReceiving /
edsRejected / edsEnded, and TsmStreamSecII fires
OnTLSEndOfEarlyData once at the boundary.
So a session must track the framing of its own protocol across those two
callbacks and know, for every message it assembles, which side of the boundary
each byte came from. Three rules follow, and they are what "signal the start and
end of each message" means with today's interfaces:
1. A message that ARRIVES WHOLE in EarlyDataReceived may be acted on only if
replaying it is harmless - a cacheable GET, a read-only query. Anything that
changes state, spends money or consumes a nonce must wait.
2. A message that STRADDLES the boundary - starts in EarlyDataReceived and
completes in DataReceived - must not be treated as 1-RTT because it finished
there. Its early half is still replayable. Either buffer it and re-validate
the whole message after the boundary, or refuse it.
3. A session that cannot make that distinction cheaply should not implement
EarlyDataReceived at all. Both of the plugins take exactly this route: the
HTTP sessions and the Snif/Snip session discard early data, because HTTP
request framing and an authenticated remoting handshake both straddle the
boundary too easily to be worth the risk.
There is NO per-message call a plugin makes back into the TLS layer today - no
BeginMessage / EndMessage on iAppSession or iAppTransport, and no way for a
session to tell the layer that a message is complete. The boundary information
flows one way, from the layer to the plugin, and the plugin's obligation is to
respect it. If per-message signalling is wanted - so the layer could, for
instance, hold a reply until the client's Finished lands, or feed a replay cache
keyed per message - it is an interface addition, and section 10 tracks it.
--------------------------------------------------------------------------------
10. OPEN ITEMS / FUTURE WORK
================================================================================
ADMISSION - the gaps section 5 names:
- Call Admit on the first ClientHello instead of at accept, so a connection
that never speaks cannot hold a session token. This is the one that restores
the invariant in section 1. The timers (HandshakeTimeout / IdleTimeout /
the nudge, section 5.1) bound the exposure but do not remove it: a silent
peer is evicted after HandshakeTimeout, but still holds a token for that
long.
- Give avDeferHandshake a bounded wait so H queues instead of refusing.
- Then a handshake-RATE token bucket on top of H, for renegotiation and
ClientHello floods. The reaper thread is the natural place to refill it - it
already ticks and already owns no per-connection lock.
- An OnAdmission event, so an allow-list peer can bypass a wait and an
IP-reputation check can refuse early.
THE ENGINE-MEDIATED DRIVE PATH (section 3). UseDirectLayer = False routes every
record through the engine's session-keyed entry points, which is the pattern
this subsystem is meant not to use: the connection already holds its layer, so
re-resolving it per call buys nothing and takes a shard lock to do it. Once the
A/B validation has run its course, deleting the branch removes the only
engine-mediated call sites from the component and makes UseDirectLayer a
property with one value, i.e. removable too.
AN EARLY-DATA MESSAGE BOUNDARY on the plugin contract (section 9). Today the
0-RTT boundary reaches a session only as the switch from EarlyDataReceived to
DataReceived, and a session cannot tell the layer anything back - not "this
message is complete", not "hold this reply until the client's Finished lands".
Any per-message replay policy therefore lives entirely inside the plugin. If that
is not good enough, it is an interface addition rather than a fix.
CONCURRENCY AND MEMORY:
- A SERVER-WIDE OUTBOUND budget. The INBOUND half is bounded: the HTTPS
plugins carry Limits.TotalBodyBytes, a ceiling on bodies held across every
connection (HTTP.txt section 20). Nothing equivalent bounds the sum of the
send FIFOs - MaxSendQueueBytes (section 5.05) bounds one connection's backlog
and the aggregate is still that times MaxLiveSessions. Same shape of gap, same
root: section 1's gates count CONNECTIONS, not the memory each may hold, so
every per-connection cap has to be multiplied out by hand to get the real
number. A budget the admission controller could consult would let gate 3 mean
what section 1 claims it means.
- A bounded application-worker pool, so a blocking plugin stops occupying an
I/O thread (section 6). This would add a gate above the ladder in section 1.
- A shared or stateless/encrypted TLS 1.3 ticket store, so resumption and 0-RTT
stop being a ~1/N lottery across shards (section 6).
- A slab allocator with ProtectClear-on-release for handshake-key buffers.
REACTOR:
- A select() fallback for POSIX targets that have neither epoll nor kqueue
(rkSelect is in tReactorKind and nothing registers it).
OBSERVABILITY, the honest gap: DriveHighWater and the admission counters are
the whole of it. There is no per-connection error surface (no OnServerError),
so a handshake that fails is simply a connection that closes, and diagnosing
why means attaching to the engine's own events. Anything built here should be
an event on the component rather than logging inside it.
--------------------------------------------------------------------------------
11. SNIF / SNIP OVER QUIC
================================================================================
TsnipQUICServer is the QUIC counterpart of TsnipTLSServer. It is an application
protocol plugin for TsmAsyncQUICServer, not a listener. The QUIC host owns the
UDP socket, certificate, trust policy and TLS configuration. The plugin owns
its TsnifClassServer and dispatches each accepted connection on a serving thread.
TsnifClassServer.RegisterServerClass(TMyRemotedThing);
quic := TsmAsyncQUICServer.Create(Self);
quic.OnConfigureEngine := ConfigureEngine;
quic.BindIP := '127.0.0.1';
quic.BindPort := 4443;
snip := TsnipQUICServer.Create(Self);
snip.Server := quic;
quic.Active := True;
Assign Server in the Object Inspector or in code. Loaded and the host's
pre-activation hook handle streamed component order. AlpnToken freezes once
AppProtocol is handed out. AlpnPriority orders the registry, higher first and
equal priorities in insertion order; change the association or priority only
while the host is inactive. Manual additional registrations must be removed by
the application. A retained adapter refuses new sessions after plugin disposal.
TsnipQUICClient owns its TLS configuration engine. TsnipAdvancedQUICClient
borrows a TLSServer and uses GlobalServer when none is assigned. Both descend
from TsnicClassClient and provide the TLS client's Host, Port, ServerName,
HandshakeTimeout, padding, layer events and Snif login/account recovery surface.
Start connects UDP/QUIC, opens the snip channel and authenticates the Snif user.
The default port is UDP 4443, reusing cSnipDefaultPort. This can coexist with
TCP 4443. Configure the TLS engine's trust anchors and server identity just as
for the TLS client; QUIC always negotiates TLS 1.3.
The default ALPN is the shared private-use token 'snip', also used by TLS.
Both ends must agree if AlpnToken / SnipAlpnToken are changed. The single default token is
declared in StreamSec.Snip.TLSOctetConnection and reused by both transports.
TsnipServerQUICOctetConnection.RemoteAddress reports the current validated
path's address only, without a port or IPv6 brackets. It follows validated
rebinding; copy it when an operation needs a stable peer identity.
Exactly one client-initiated bidirectional QUIC stream (stream zero) carries
snip. Its framing is byte-identical to TLS, including padding and the connect /
accept exchange. Further streams are stopped/reset with an application error;
they do not create additional class servers or serving threads. This plugin
does not opt in to QUIC 0-RTT: authentication and remoted operations must not be
replayed. KAPA binds to this connection's RFC 9266 tls-exporter value
(EXPORTER-Channel-Binding, empty context, 32 bytes); absent exporters fail closed.
The octet connection copies ordered input to its framing buffer and grants
Consume credit for those bytes. Granting credit only after a complete message
would deadlock messages larger than the initial stream window. Output respects
SendCapacity; blocked server sends wait on the serving thread for Writable.
The reactor thread never waits for application progress.
MaxFrameSize bounds one inbound frame BODY, in octets, with the same 16 MiB
default on every snip transport. It is published on TsnipTLSServer,
TsnipQUICServer, TsnipCustomTLSClient and TsnipCustomQUICClient (including their
plain and advanced descendants), TsnipSSHClient and TsnipSSHServer. TsnipClient
and TsnipServer forward it to their owned SSH snip components. Values below 1
raise EsnipProtocol at assignment and leave the setting unchanged.
The component copies the value into each framer it creates, before its first
read. Changing it while active configures future connections; existing framers
keep their own limits. A program using an octet connection directly sets its
MaxFrameSize before the first read instead.
A message is ONE frame, not a series of frames. Choose the limit for the
largest legitimate encoded message, including its fields and any padding. For
example, an upload carrying a 38 MB package as one snif argument needs more
than 38 MB of frame body on the receiving server:
snip.MaxFrameSize := 64 * 1024 * 1024;
This is an application choice, not a larger default: a peer can make this end
buffer about one such frame PER CONNECTION. Limit the value to what the
application needs, and account for the number of concurrent connections.
A frame header that declares more fails the connection with a Snip protocol
error. MaxFrameSize also bounds TLS/QUIC buffered plaintext: beyond one frame
plus its header and 64 KiB of reader headroom the buffer refuses further data.
Over TLS the connection fails; over QUIC transport credit for the overflow is
withheld. SSH uses the same declared-body limit with pull-driven buffering.
A client driver thread serializes all tQuicClient calls, receives packets and
drives ACKs, loss recovery and output while the application waits for messages.
It sends PINGs before the negotiated idle timeout, including quiet periods
between calls and user interaction during recovery. RecoveryHeartbeatInterval
may tighten that cadence; disabling recovery heartbeats does not disable the
QUIC liveness traffic. Other QUIC clients must keep an idle snip channel alive
in the same way. The host's IdleTimeoutMS remains useful for vanished peers.
There is no TLS-style idle-nudge veto on a QUIC session.
ConnectTimeout is on by default (15000 ms): it starts at authenticated Opened,
including when the peer never opens a stream or sends the snip connect frame.
ReadTimeout defaults to zero (off), so ordinary quiet channels are allowed.
Waits distinguish data, timeout and closed exactly as the TLS connection does.
Call snip.Stop on the application's thread. It refuses new sessions, signals
blocked reads and sends, and waits up to DrainTimeout (default 10000 ms).
iQuicAppSessionDrain also handles host shutdown without joining on the reactor.
A timed-out handler retains the dispatch state until it unwinds. For normal
teardown, free clients, stop the plugin, deactivate the QUIC host, then free
plugin and host. No plugin may activate or destroy its host in a QUIC callback.