Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mobile.AsyncTLSServer

Feature notes: TLS implementation notes (RFC map) · Async TLS socket server architecture

Classes, interfaces and records

classETLSAsyncServer

inherits from Exception

(no public members)

interfaceiAppTransportWork

Optional transport companion (Supports on the iAppTransport) for a session that must act without new input from the peer: resume paused work, or enforce a timeout of its own. RequestWork asks for one call of the session's iAppSessionWork.WorkQueued; requests made before it runs collapse into one. False: the connection is closed, or the reactor backend cannot run application work. SetWorkDeadline asks for the same call once the absolute time aDeadline, in stTlsUtils.GetTickCount64 milliseconds, has passed; it replaces the previous deadline, 0 clears it, and the connection's handshake and idle deadlines are not touched. The deadline is cleared before each WorkQueued, so set it again there while one is still needed. If a due deadline cannot be serviced, the connection is closed.

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

interfaceiAppTransportDeadlines

Optional transport companion for a session whose limits depend on where its conversation has got to. Call it from the session's own callbacks.

SetIdleLimit replaces IdleTimeout for this connection: the milliseconds without traffic in either direction before nrIdle is raised. 0 means no idle deadline. Setting a different value starts that period now.

SetSessionBudget raises nrRequestStalled once, after aMillis, whatever traffic there is meanwhile, and replaces any budget running. 0 cancels it. Answering nvKeepAlive does not set it again: call this again if one is still needed. Neither the handshake deadline nor the idle deadline is touched.

LoadPercent is how full the server is: the larger of its live sessions against MaxLiveSessions and its handshakes against MaxConcurrentHandshakes. ServerIdleMs is the server's IdleTimeout, for a session that will not run longer than the application asked.

ExpireIdleLimit ends the idle period now: nrIdle is raised at the next sweep of the deadlines, on the usual path, and nvKeepAlive starts the period again. For a session whose own sends keep the deadline moving although its peer has said nothing: a send completing before that sweep does not put it off, and input from the peer does.

procedure SetIdleLimit(aMillis: Cardinal); procedure SetSessionBudget(aMillis: Cardinal); function LoadPercent: Integer; function ServerIdleMs: Cardinal; procedure ExpireIdleLimit;

interfaceiAppTransportReceiveFlow

Optional transport companion that lets a session stop reading from the peer while it cannot take more input. Call it only from the session's own callbacks. ReceiveFlowAvailable is True once the handshake is complete, when TLS compression is off and the reactor backend supports application work; otherwise PauseReceive(True) raises ETLSAsyncServer, so test it first. PauseReceive(True) stops DataReceived and EarlyDataReceived calls and the reading of the socket; a receive the backend already started still completes and its data is held. To resume, call PauseReceive(False) and then iAppTransportWork.RequestWork: the held data is delivered after that WorkQueued, and reading restarts. While available, a session that implements iAppSessionWork gets its input in pieces of at most 16 KiB, so a pause takes effect before the next piece.

function ReceiveFlowAvailable: Boolean; procedure PauseReceive(aPaused: Boolean);

interfaceiAppSessionWork

Implement on the session to receive the calls iAppTransportWork asks for. WorkQueued runs on a reactor I/O thread, serialized with the session's other callbacks, like DataReceived.

procedure WorkQueued;

interfaceiAppTransport

function GetNegotiatedProtocol: OctetString; function GetNegotiatedVersion: TProtocolVersion; function GetRemoteAddress: string; procedure Send(aData: Pointer; aLen: Integer); procedure Close(aGraceful: Boolean); function Instance: tObject; function ExportKeyingMaterial(const aLabel : AnsiString; const aContext: tBytes; aLen : Integer): tBytes;
RFC 8446 sec.7.5 keying-material exporter for THIS connection - the "secure TLS connection identifier" surface. Full description »
property NegotiatedProtocol: OctetString read GetNegotiatedProtocol; property NegotiatedVersion: TProtocolVersion read GetNegotiatedVersion; property RemoteAddress: string read GetRemoteAddress;

interfaceiTLSConnectionInfo

WHAT THE HANDSHAKE DECIDED, for an application that needs to see it: the client certificate when mTLS was used, the name the client asked for, and the algorithms in force.

REACHED BY QueryInterface ON THE TRANSPORT, not by a method on iAppTransport:

var lTLS: iTLSConnectionInfo; if Supports(aTransport,iTLSConnectionInfo,lTLS) then if lTLS.PeerCertificatePresent then ...

Same reasoning as iAppSessionNudge below. iAppTransport is a shipped contract with implementors outside this repository, so widening it would break them; a transport that does not implement this one simply answers False to Supports, which is what makes the whole mechanism additive. Every transport this unit creates does implement it.

VALID ONLY WHILE THE CONNECTION IS. It reads through to the live TLS session, so hold it no longer than you hold the transport itself, and expect every member to answer its empty value once the connection has closed.

NOTHING HERE IS A SUBSTITUTE FOR THE HANDSHAKE'S OWN DECISIONS. The peer certificate has already been verified against the trust configuration by the time a session exists - if it had not passed, there would be no connection to ask. What this interface adds is WHO it turned out to be, so an application can authorize on top of an authentication that already happened.

function GetVersion: TProtocolVersion; function GetVersionName: string; function GetCipherSuite: TCipherSuite; function GetCipherSuiteName: string; function GetServerName: string; function GetKeyExchangeGroup: Word; function GetKeyExchangeGroupName: string; function GetIsResumed: Boolean; function GetPeerCertificate: iCertificate; function GetPeerCertificatePresent: Boolean; property Version: TProtocolVersion read GetVersion;
The negotiated record-layer version as the two-byte code point, e.g. cTLS12vmm / cTLS13vmm from StreamSec.Mobile.TlsConst. Compare against those constants rather than against literals.
property VersionName: string read GetVersionName;
The same thing as text - 'TLS 1.3', 'TLS 1.2' - for logging and for putting in a response header. A version this build does not know still answers something stable rather than ''.
property CipherSuite: TCipherSuite read GetCipherSuite;
The negotiated cipher suite as its two IANA octets.
property CipherSuiteName: string read GetCipherSuiteName;
The suite's registered name, e.g. 'TLS_AES_128_GCM_SHA256'. A suite outside the table answers '0xTTTT' - a number you can look up beats an empty string in a log.
property ServerName: string read GetServerName;
SERVER-SIDE SNI: the host name the client asked for (RFC 6066), '' when it sent none. IT IS ATTACKER-SUPPLIED AND UNAUTHENTICATED - the client picks the string, and nothing in the handshake ties it to the client's identity. Route on it; do not authenticate on it.
property KeyExchangeGroup: Word read GetKeyExchangeGroup;
The NamedGroup used for key exchange, as the IANA code point (the grp_* constants in StreamSec.Mobile.Tls13Handshake). TLS 1.3 ONLY: a TLS 1.2 session answers 0, because 1.2 carries its curve in the ServerKeyExchange rather than as a negotiated group and there is no honest single answer that spans both.
property KeyExchangeGroupName: string read GetKeyExchangeGroupName;
The group as text - 'x25519', 'secp256r1', 'X25519MLKEM768'. '' when there is none to report, which includes every TLS 1.2 session (see above).
property IsResumed: Boolean read GetIsResumed;
True when this session was resumed rather than fully negotiated. Worth testing before relying on the peer certificate: a resumed TLS 1.3 session authenticates by possession of the resumption secret, the server asks for no certificate on it and the ticket does not carry the original one, so PeerCertificate below is nil there.
property PeerCertificate: iCertificate read GetPeerCertificate;
The client's certificate when mTLS was used, nil otherwise. It has already been verified - a certificate that failed the trust configuration would have failed the handshake - so what is left for an application is authorization: read the subject through tbsCertificate.subject.AsRdnSequence and decide whether THIS peer may do what it is asking.
property PeerCertificatePresent: Boolean read GetPeerCertificatePresent;
True when the peer sent a certificate. Prefer it to testing PeerCertificate for nil: it says what it means, and it keeps the "is this an mTLS connection" question from reading like a defensive nil check.

interfaceiAppSession

The per-connection application session. When the handshake completes, ALPN (or the fallback policy) has picked an iAppProtocol; the connection asks it for CreateSession and from then on this is the object the reactor drives: Opened first, DataReceived for 1-RTT plaintext, EarlyDataReceived for what arrived as 0-RTT (see its contract below), Closed exactly once at the end. Callbacks run on reactor I/O threads with the connection's gate held: do the protocol work and return - never block there, and never join a thread from Closed. Instance exposes the implementing object to whoever holds the interface.

procedure Opened; procedure DataReceived(aData: Pointer; aLen: Integer); procedure EarlyDataReceived(aData: Pointer; aLen: Integer);
Leaving the method empty DISCARDS the data - which is safe only because the operator left 0-RTT off, or set edmRejectAndRetry so the client resends in 1-RTT. Full description »
procedure Closed(aGraceful: Boolean); function Instance: tObject;

interfaceiAppSessionNudge

OPTIONAL companion to iAppSession, reached by QueryInterface on the session a plugin returned from CreateSession - deliberately NOT a method ON iAppSession. That interface is a shipped contract with implementors outside this repository, so widening it would break them; a plugin that does not implement this one is simply not asked, which is what makes the whole mechanism additive. Nudged runs on an I/O thread with the connection's gate held, so it may read the session's own state directly and MUST NOT block. It answers for the protocol only - whether this connection is mid-message, mid-stream, or genuinely idle - and the application still gets the last word after it. aRearmMs is read only when the verdict is nvKeepAlive: it is how long to wait before asking again, and 0 there means "stop asking", i.e. hold this connection open until something else closes it - except after the peer's close (close_notify or FIN), where 0 is asked again every cPeerCloseGraceMs. That is the case a session waiting on an external event wants - a Snif callback that intends to answer when something finally happens keeps its transport alive by returning nvKeepAlive with aRearmMs = 0, and the connection stops being a deadline's business until the session arms one again. aRearmMs arrives holding the idle limit, except for nrRequestStalled: a session budget is not the idle deadline, so there it arrives holding what is left of the idle deadline already running (0 when none is), and nvKeepAlive with it untouched leaves that deadline where it was.

function Nudged(aReason: tNudgeReason; var aRearmMs: Cardinal): tNudgeVerdict;

interfaceiAppTransportFlow

HOW MUCH THE TRANSPORT WILL TAKE, for a session that sends more than a few octets at a time. OPTIONAL companion to iAppTransport, reached by QueryInterface on the transport - the same additive shape as iTLSConnectionInfo, and for the same reason: iAppTransport has implementors outside this repository. Every transport this unit creates over the reactor implements it; the plaintext redirect transport does not, and a session that finds it missing sends the way it always did.

WHY A SESSION NEEDS IT. Send never blocks and never refuses: it queues. The queue behind a send in flight is bounded by MaxSendQueueBytes, and a Send that does not fit CLOSES THE CONNECTION. Something is in flight far more often than a session can see - the server's own handshake and NewSessionTicket flight right after the handshake, the previous chunk of the same response, another HTTP/2 stream's frames - so a session that hands over a large buffer in one call, or one buffer per flow-control window, is one that gets its connection cut part-way. A session that keeps each Send within SendCredit, and sends the rest when iAppSessionDrain.Drained says there is room again, never does.

BOTH VALUES ARE A SNAPSHOT taken under the connection's gate. Inside a session callback (which already holds it) they stay true until the session itself sends; from any other thread they can be stale by the time they are read.

function GetSendCredit: Integer; function GetSendPending: Integer; property SendCredit: Integer read GetSendCredit;
Octets of APPLICATION data that Send can take now without the backlog ceiling being able to close the connection - already net of TLS record overhead, so it compares directly with what is passed to Send. Full description »
property SendPending: Integer read GetSendPending;
Octets handed to Send that the peer has not taken yet - the buffer in flight plus the queue behind it, as they go on the wire. 0 means everything sent so far has left.

interfaceiAppTransportAbort

Optional transport companion (Supports on the iAppTransport) that ends the connection now. 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 internal wake-queue lock, which is never held while a connection 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.

procedure Abort;

interfaceiAppSessionDrain

THE TRANSPORT HAS MADE ROOM. OPTIONAL companion to iAppSession, reached by QueryInterface on the session a plugin returned from CreateSession - like iAppSessionNudge, and for the same reason. A session that does not implement it is never called, which is what every session written before it expects.

Drained runs after EVERY completed send on an established connection that is not closing: the peer has taken a buffer, and aPending octets are still on their way (0 = everything sent so far has left). It is the other half of iAppTransportFlow: a session with more to send than SendCredit allowed sends the next part here, within the credit it reads now, and stops again when the credit runs out. Nothing else will wake it - a session that waits for credit without implementing this waits for ever.

CONTRACT: runs on an I/O thread with the connection's gate held, exactly like DataReceived. It MAY call Send and Close on its transport - that is the point - and must not block. On the POSIX reactors a completion can be reported from INSIDE a Send the session itself is making, so Drained can arrive while the session is still in the middle of sending: a session must either tolerate that or note it and carry on from its own loop. Raising from it closes the connection.

procedure Drained(aPending: Integer);

interfaceiAppSessionShutdown

HOW EACH DIRECTION ENDS, for a session that wants to know. OPTIONAL companion to iAppSession, reached by QueryInterface on the session once, when it is created - the same additive shape as iAppSessionDrain, so iAppSession and the sessions outside this repository are unchanged.

ReceiveClosed: nothing more will be delivered. After the peer's close_notify, or a TCP half-close (FIN) without one, it comes once every octet that came before it has been delivered to DataReceived. After a FIN, or the peer's close_notify on TLS 1.3, the session may still Send - to answer what it received - and ends the connection with Close(True), which sends this side's close_notify; if it does not, it is asked again (iAppSessionNudge, OnConnectionNudge) after IdleTimeout, or after 30 seconds when IdleTimeout is 0, and the connection closes gracefully unless that answer is nvKeepAlive. 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 sec.7.2.1). On a fatal alert, or when the connection is torn down, it comes together with SendClosed, and data still parked for a paused session is discarded undelivered. SendClosed: this side can send nothing more. This side's close_notify went out (also from inside the session's own Close), a fatal alert was sent or received, or the connection is being torn down. A Send after it is dropped. Each is called at most once, and both come before iAppSession.Closed, which is still the final call: the session detaches there. A session that does not implement this interface is told nothing new, and a FIN ends its connection at once, as before.

CONTRACT: runs on an I/O thread with the connection's gate held, like DataReceived. It may call Send and Close and must not block. Raising from it closes the connection.

procedure ReceiveClosed; procedure SendClosed;

interfaceiAppPlainTextRedirect

OPTIONAL companion to iAppProtocol, reached by QueryInterface on the protocol the registry resolved - the same additive shape as iAppSessionNudge above, and for the same reason: iAppProtocol has implementors outside this repository.

A PLAINTEXT REDIRECT IS NOT A SESSION, which is why this is one method and not a second iAppSession. The exchange is a single short request followed by a single short response and then a close: there is no handshake, no negotiated protocol, no keep-alive, nothing to nudge, and nothing that can outlive the answer. Giving it Opened/Closed/Nudged would be inventing a lifecycle for something that has none.

aData is the bytes read from the peer in one go, and is NOT guaranteed to be a complete request - the implementor decides what it has and answers, or answers with an error. It must not block: the caller is a short-lived thread holding one of a bounded number of slots.

WHO IS ASKED is not a new concept either. The connection carries no ALPN, so the server resolves it exactly as it resolves a TLS client that offered none: ResolveProtocol('') applies FallbackPolicy, with AlpnPriority ordering the candidates. A deployment that wants HTTP/1.1 to answer plaintext while HTTP/2 wins ALPN therefore sets AlpnPriority high on the h2 plugin and marks the HTTP/1.1 plugin IsFallbackProtocol - no separate selection knob.

procedure DataReceived(aData: Pointer; aLen: Integer);

interfaceiAppProtocol

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

interfaceiAppProtocolRegistry

function GetCount: Integer; function GetProtocol(aIndex: Integer): iAppProtocol; function GetFallbackProtocol: iAppProtocol; procedure SetFallbackProtocol(const Value: iAppProtocol); function GetFallbackPolicy: tFallbackPolicy; procedure SetFallbackPolicy(const Value: tFallbackPolicy); procedure AddProtocol(const aProtocol: iAppProtocol); function RemoveProtocol(const aProtocol: iAppProtocol): Boolean;
Unregisters the exact INSTANCE and answers whether it was present. BY INSTANCE, NOT BY TOKEN, deliberately: nothing forbids two registrations sharing a token, and a token lookup takes the first match - so a component asking to leave could evict a SIBLING's registration and leave its own behind, d... Full description »
function FindProtocol(const aToken: OctetString): iAppProtocol; function AdvertisedProtocols: TApplicationProtocols; function ResolveProtocol(const aNegotiated: OctetString): iAppProtocol; property Count: Integer read GetCount; property Protocols[aIndex: Integer]: iAppProtocol read GetProtocol; property FallbackProtocol: iAppProtocol read GetFallbackProtocol write SetFallbackProtocol; property FallbackPolicy: tFallbackPolicy read GetFallbackPolicy write SetFallbackPolicy;

interfaceiAppProtocolPriority

OPTIONAL companion to iAppProtocolRegistry, reached by QueryInterface on TsmAsyncTLSServer.Protocols - deliberately NOT a method on that interface, which is a shipped contract with implementors outside this repository. A registry that does not implement this one is simply not asked, and the caller falls back to the plain append.

procedure AddProtocolByPriority(const aProtocol: iAppProtocol; aPriority: Integer);
Insert aProtocol so the list stays in DESCENDING priority order. HIGHER IS PREFERRED: ALPN selection walks the SERVER's list outermost and takes the first token the client also offered (TCustomTLS_ContentLayer. Full description »
function ProtocolPriority(const aToken: OctetString): Integer;
The priority aToken was registered with, or cAlpnPriorityDefault if it is not registered.

classtTLSConnection

(no public members)

classTsmAsyncTLSServer — component reference

(no public members)

recordtProvisionItem

Kind: tProvisionKind; FileName: TFileName; Password: iSecretKey;

classtAppProtocolRegistry

THE REGISTRY IS READ FROM REACTOR THREADS AND WRITTEN FROM THE APPLICATION THREAD, so every public entry point takes fLock.

fList locks its own individual operations, but that is not enough: the list and fPriorities are TWO structures holding ONE fact, and the composite operations (scan, then Insert + PriorityInsert; IndexOf, then Delete + PriorityDelete) are what must be atomic. A reader walking the list while PriorityDelete shifts the array underneath it sees priorities belonging to the wrong protocols, or indexes past the end.

The public/Core split exists because the lock is NOT assumed re-entrant - TCriticalSection is recursive on Windows but that is not a promise this unit relies on, and the POSIX reactors compile the same code. AddProtocol delegates to AddProtocolByPriority and ResolveProtocol to FindProtocol, so each takes the lock once and calls the unlocked Core.

HELD ACROSS iAppProtocol.Token, which is a call OUT to the plugin: our own adapters read one field, but a foreign implementation must not call back into this registry from GetToken or it will deadlock against itself.

Count and Protocols[] are individually safe but not atomic AS A PAIR - a "for i := 0 to Count - 1" walk can still race a concurrent removal, which is why GetProtocol answers nil out of range instead of raising, and why AdvertisedProtocols (one locked snapshot) is what the handshake path actually uses.

constructor Create; destructor Destroy; override; procedure AddProtocol(const aProtocol: iAppProtocol); procedure AddProtocolByPriority(const aProtocol: iAppProtocol; aPriority: Integer); function ProtocolPriority(const aToken: OctetString): Integer; function RemoveProtocol(const aProtocol: iAppProtocol): Boolean; function FindProtocol(const aToken: OctetString): iAppProtocol; function AdvertisedProtocols: TApplicationProtocols; function ResolveProtocol(const aNegotiated: OctetString): iAppProtocol;

classtTLSAdmissionController

constructor Create(aMaxHandshakes, aMaxSessions: Integer); destructor Destroy; override; function Admit: tAdmissionVerdict; procedure HandshakeCompleted(aSuccess: Boolean); procedure SessionClosed; property MaxHandshakes: Integer read fMaxHandshakes write fMaxHandshakes; property MaxSessions: Integer read fMaxSessions write fMaxSessions; property ActiveHandshakes: Integer read fActiveHandshakes; property ActiveSessions: Integer read fActiveSessions;

classtTLSConnection

procedure SendCompleted(aByteLen: Integer); override;
Public to match tReactorConnection.SendCompleted; overriding it at a lower visibility would be an H2269 and would hide it from the reactor's callers.
function ReceiveEnded: Boolean; override; constructor Create(aServer: TsmAsyncTLSServer; aHandle: TSocketHandle; const aRemoteAddress: string; aEngineIndex: Integer); destructor Destroy; override; procedure ArmDeadline(aMillis: Cardinal);
Arms / disarms this connection's own deadline. Both are safe from ANY thread and take NO lock: the deadline is one interlocked field, so a re-arm on every byte received costs a single store, can never contend with the per-connection gate, and cannot invert a lock order against it. Full description »
procedure CancelDeadline; function CheckDeadline(aNow: UInt64): Boolean;
The reaper's whole interface to a connection. Returns True when a deadline had expired, in which case a nudge has been raised carrying the reason that matches this connection's PHASE - so the layers above are told whether they are being asked about a handshake that never finished or a session that has gone quiet. Takes no lock and never blocks.
function DeadlineExpired(aNow: UInt64): Boolean;
True when a deadline is armed and aNow (a stTlsUtils.GetTickCount64 value) has reached it. False whenever no deadline is armed.
function RequestNudgeFor(aReason: tNudgeReason): Boolean;
Asks the layers above whether this connection should still exist, and closes it if none of them objects. SAFE FROM ANY THREAD: the question is answered - and any resulting close performed - on the reactor's own I/O thread, under the per-connection gate, in a normal dispatch position. The caller neither takes the gate nor touches the content layer.
property Deadline: Int64 read ReadDeadline;
The armed deadline as a raw tick, or 0 when none is armed.
property Admitted: Boolean read fAdmitted write fAdmitted; property Engine: TsmSimpleTLSInternalServer read fEngine; property ContentLayer: TCustomTLS_ContentLayer read fContentLayer; property Session: iAppSession read fSession; property Protocol: iAppProtocol read fProtocol;

classtTLSConnectionReaper

inherits from TThread

THE CLOCK. One thread per active server, parked on an event with a timeout - the same shape tRenewalThread uses for ACME renewal, and deliberately NOT a tick hosted on the reactor's I/O threads: a plugin callback runs INLINE on the thread that delivered its bytes, so a blocking handler parks an I/O thread, and a timer living there would stop firing under exactly the load that makes reaping matter. Worse, any application handler that blocks is reachable by a normal request, which would hand a peer a way to switch the reaper off. It does no work of its own beyond comparing integers: for each connection it asks CheckDeadline, and a connection that has expired raises a NUDGE. The decision and the close then happen on that connection's own I/O thread, under its gate (see tTLSConnection.DoNudge), so this thread never takes a per-connection lock and never touches a content layer.

constructor Create(aServer: TsmAsyncTLSServer); destructor Destroy; override; procedure Poke;
Ends the current wait: a new connection arrived, or we are shutting down.

classtTLSListenerDaemon

inherits from TThread

The ONE accept-loop thread. It does not own the listening socket: the component binds and listens BEFORE this thread exists (so a bind failure raises synchronously out of 'Active := True' rather than dying silently on a background thread), and stops it from the outside to end the loop.

constructor Create(aServer: TsmAsyncTLSServer; aSocket: tTLSListenerSocket);

classTOCSPOptions

inherits from TPersistent

TOCSPOptions is the configuration TEMPLATE for the per-shard OCSP responders, the same way TTLSOptions is the template for the per-shard TLS options.

WHY A TEMPLATE AND NOT ONE SHARED TsmOcsp: a responder's TrustedCertificates binds to exactly ONE RootCerts store, so a single instance handed to N engines would end up bound to the last one and the other N-1 would validate against a store that is not theirs. Worse, each engine guards its responder with its OWN FOcspLock, so a shared instance would be raced by N unrelated locks - exactly the hazard that lock was added to remove. DoActivate therefore mints one TsmOcsp per shard from this template and binds each to its own RootCerts.

constructor Create(aOwner: TComponent); procedure AssignTo(Dest: TPersistent); override; procedure ApplyTo(aOcsp: TsmOcsp);
Stamps this configuration onto a freshly created responder.
property Enabled: Boolean read fEnabled write fEnabled default False;
Off by default: no responder is created and revocation falls back to CRLs.
property ResponderURL: string read fResponderURL write fResponderURL; property Timeout: Cardinal read fTimeout write fTimeout default 15000; property MaxClockSkew: Cardinal read fMaxClockSkew write fMaxClockSkew default 300; property RequireSignatureCheck: Boolean read fRequireSignatureCheck write fRequireSignatureCheck default True; property Nonce: Boolean read fNonce write fNonce default True; property RequireNonce: Boolean read fRequireNonce write fRequireNonce default False; property NonceLength: Integer read fNonceLength write fNonceLength default 16; property LightweightMode: Boolean read fLightweightMode write fLightweightMode default False;

classTsmAsyncTLSServer — component reference

inherits from TComponent

implements iAcmeAlpnTLS, iKeyAndCertStore

constructor Create(AOwner: TComponent); override; destructor Destroy; override; function PeerConnections(const aPeer: string): Integer;
The live connections counted against MaxConnectionsPerPeer for the source aPeer belongs to (PeerSourceKey): every address of one IPv6 /64 answers the same. 0 while MaxConnectionsPerPeer is 0, which counts nothing. » member page
function AddCertificate(const aCert: iCertificate; aExplicitTrust: Boolean; var aStatus: TCertStatusCode; aAllowExpired: Boolean = False; aAllowDuplicateKeyIdentifier: Boolean = False): Boolean;
Configuration belongs in OnConfigureEngine, which the component calls once per shard. These are the operations an application needs AFTER activation, when that handler has long returned - the only reason it would otherwise have to keep its own list of the engines. Full description »
function AddLocalCertificate(const aCert: iCertificate; var aStatus: TCertStatusCode; aAllowExpired: Boolean = False; aAllowDuplicateKeyIdentifier: Boolean = False): Boolean;
Files a chain CA with each shard's startup trust policy. » member page
function AddCRL(const aCRL: iCertificateList; var aStatus: TCertStatusCode): Boolean; procedure ClearExpiredSessionKeys(aConservative: Boolean = True); procedure ImportFromPFX(aFileName: TFileName; aPassword: iSecretKey);
Imports a PKCS#12 identity into every shard, parsing the file once.

Accepts BER as well as DER, which matters because most PKCS#12 files in circulation are BER.

Raises if the shards disagree about any item in the file - see the store methods for why a partial result is not offered. » member page
procedure LoadRootCertsFromFile(aFileName: TFileName);
Loads trust anchors into every shard. NO RESULT. A per-shard count would have to be either one shard's answer or a sum, and neither says anything a caller can use: the shards are required to hold the same anchors, so N times one number is noise, and one shard's number is a fact about that shard. Full description »
procedure ValidatePublicKeyPairs;
Re-pairs certificates with private keys on every shard. ImportFromPFX already does this per shard as the material lands, so an application rarely needs it. Full description »
function TryBeginAcmeChallenge: Boolean;
Every member fans out to ALL shards: the CA's validation connection is round-robined onto an arbitrary one, so a challenge present on a single shard would be found only ~1/N of the time, and a renewed certificate installed on a single shard would leave the rest serving the expired one. The gate is this component's own, covering the whole bank. » member page
procedure EndAcmeChallenge; procedure ProvisionAcmeChallenge(aKey: TComponent; const aIdentifier, aKeyAuthorization: string); procedure RemoveTLSAcmeALPN; procedure AddTLSAcmeALPN(const aPriv: iMPPrivateKey; const aHostName: string; const aAuthorization: tBytes);
The lower-level challenge install, for a host that drives ACME itself and manages the challenge key on its own (ProvisionAcmeChallenge registers the key in each shard's ring for you). Same mandatory fan-out. » member page
function AcmeAddCACertificate(const aCert: iCertificate; var aStatus: TCertStatusCode): Boolean;
Delegates to AddCertificate, forwarding aCert, True, aStatus, False and True, and returns its result. » member page
procedure ReplaceTLSServerCertificate(const aCert: iCertificate; const aPriv: iMPPrivateKey); overload; procedure ReplaceTLSServerCertificate(const aCert: iCertificate; const aPriv: iMPPrivateKey; const aRetired: array of iCertificate); overload;
As above; each shard's serving cache also drops every row that holds one of aRetired, the leaves this replacement supersedes, and each shard stops counting them as servable (see TsmStreamSecII.ReplaceTLSServerCertificate). » member page
procedure Deactivate(aKill: Boolean);
Stops the server. aKill = True tears every live connection down immediately. aKill = False closes the listener at once, then sends a TLS close_notify to each live connection and waits up to DeactivateTimeout milliseconds for them to finish; whatever is still connected when the timeout expires is killed. Active := False routes here - gracefully, unless DeactivateTimeout is 0. » member page
property Reactor: tAsyncReactor read fReactor; property Admission: tTLSAdmissionController read fAdmission; property Filter: iPeerFilter read fFilter write fFilter;
PEER SCREENING POLICY. Assign one before Active; nil means no policy and every peer is admitted, which is the shipped behaviour. Full description »
property OnPeerRefused: tAsyncTLSPeerRefusedEvent read fOnPeerRefused write fOnPeerRefused;
Fired when Filter turned a peer away at accept. See DoPeerRefused. » member page
procedure ReportPeerActivity(const aPeer: string; aUnits: Integer = 1);
Adds aUnits of work to aPeer's rate window. The server already reports one unit per ACCEPTED CONNECTION; a protocol whose unit of work is finer than a connection - anything multiplexed, HTTP/2 above all - should report its own, or a peer issuing thousands of requests down one connection registers as a single quiet client. No-op when no filter is assigned. » member page
property Protocols: iAppProtocolRegistry read fRegistry; property TicketStore: iTls13TicketStore read fTicketStore write fTicketStore;
A resumption-ticket store of your own, given to EVERY shard - the runtime counterpart of SharedTicketStore, and what it takes precedence over. Full description »
property DriveHighWater: Integer read fDriveHighWater;
Parallelism instrumentation: the maximum number of engine handshake drive calls observed running concurrently. Sharded -> up to EngineCount; a single engine pins it at 1. » member page
property DriveWidenMs: Integer read fDriveWidenMs write fDriveWidenMs;
Test-only: milliseconds to hold inside the drive region, to widen the observation window for the concurrency test. 0 in production. » member page
property BoundPort: Word read GetBoundPort;
The port the TLS listener is bound to while Active, 0 otherwise. With BindPort 0 the system assigns one; BindPort itself keeps the configured value, so a restart asks for a fresh port again. » member page
property BindIP: string read fBindIP write fBindIP; property BindPort: Word read fBindPort write fBindPort default 443; property PlainTextRedirectPort: Word read fPlainPort write SetPlainPort default 0;
OPTIONAL PLAINTEXT REDIRECT LISTENER. 0 (the default) means the server listens for TLS only, which is what it has always done. Full description »
property Active: Boolean read fActive write SetActive default False; property IOThreadCount: Integer read fIOThreadCount write fIOThreadCount default 0; property EngineCount: Integer read fEngineCount write fEngineCount default 0;
Number of TLS engine shards; 0 -> match the I/O thread count. » member page
property UseDirectLayer: Boolean read fUseDirectLayer write fUseDirectLayer default True;
PROTOTYPE: when True, each tTLSConnection creates its content layer once (TLSAddServerSession) and drives it directly (fContentLayer.Accept/DecodeData/ EncodeData/Close) under the reactor's per-conn gate - NO per-record FindTLSSession, NO per-engine shard lock. False = legacy engine-mediated path. See the header note on the shard lock being a per-connection concern. » member page
property SharedTicketStore: Boolean read fSharedTicketStore write fSharedTicketStore default False;
ONE TLS 1.3 resumption-ticket store for the whole shard bank, instead of one per engine. WHY IT MATTERS: a ticket is stored by the engine that ISSUED it, and shards are handed out round-robin, so with the default per-engine stores a resuming client only finds its ticket when it happens to land on... Full description »
property MaxConcurrentHandshakes: Integer read fMaxHandshakes write fMaxHandshakes default 256; property MaxLiveSessions: Integer read fMaxSessions write fMaxSessions default 8192; property MaxConnectionsPerPeer: Integer read fMaxConnectionsPerPeer write fMaxConnectionsPerPeer default 0;
Live connections from ONE source, from the accept on, so a connection that has not begun its handshake counts. Full description »
property FallbackPolicy: tFallbackPolicy read fFallbackPolicy write SetFallbackPolicy default fbpRefuse;
What to do when the client offers no ALPN we registered. Writes THROUGH to Protocols.FallbackPolicy, which is where resolution reads it, so the two cannot disagree - setting it on either is setting it on the registry. » member page
property DeactivateTimeout: Cardinal read fDeactivateTimeout write fDeactivateTimeout default 30000;
Milliseconds Active := False waits for live connections to close gracefully before killing the remainder. 0 means Active := False kills immediately - the pre-graceful-drain behaviour. » member page
property HandshakeTimeout: Cardinal read fHandshakeTimeout write fHandshakeTimeout default 15000;
TOTAL budget, in milliseconds, from ACCEPT to a completed TLS handshake. Deliberately an ABSOLUTE deadline: it is armed once, at accept, and is NEVER re-armed by traffic. Full description »
property IdleTimeout: Cardinal read fIdleTimeout write fIdleTimeout default 0;
Milliseconds an ESTABLISHED session may go without traffic in EITHER direction. Unlike HandshakeTimeout this one IS re-armed - by every inbound buffer and every outbound Send - because that is what idle means once a session exists; the absolute-budget argument above does not apply, since a peer t... Full description »
property MaxSendQueueBytes: Integer read fMaxSendQueueBytes write fMaxSendQueueBytes default cDefaultMaxSendQueue;
Per-connection ceiling on QUEUED outbound octets - what an application has handed to Send while an earlier send was still in flight, and the peer has not taken yet. Full description »
property OcspOptions: TOCSPOptions read fOcspOptions write SetOcspOptions;
Configuration for the per-shard OCSP responders. The component creates, owns and frees one TsmOcsp per engine from this - an application-created responder is one forgotten owner away from a silent leak, and only the component knows when a shard dies. Full description »
property OnConfigureEngine: tConfigureEngineEvent read fOnConfigureEngine write fOnConfigureEngine;
THE configuration hook. Write ONE handler; the component calls it once per engine shard, so every shard is configured identically with no extra work for the application and no configuration state duplicated in this component. Full description »
property OnTLSIncomingAlert: TTLSAlertEvent read fOnIncomingAlert write fOnIncomingAlert;
THE TLS ALERTS OF EVERY SHARD, on one handler. Same signature as the per-engine event of the same name, and the SENDER IS PASSED THROUGH UNCHANGED - it is the engine that raised the alert, which is what a handler wanting to know WHICH shard needs, and what makes a handler written for a single Tsm... Full description »
property OnTLSOutgoingAlert: TTLSAlertEvent read fOnOutgoingAlert write fOnOutgoingAlert; property OnHandshakeDone: tAsyncTLSConnectionEvent read fOnHandshakeDone write fOnHandshakeDone; property OnConnectionClosed: tAsyncTLSConnectionEvent read fOnConnectionClosed write fOnConnectionClosed; property OnProtocolSelect: tAsyncTLSProtocolSelectEvent read fOnProtocolSelect write fOnProtocolSelect; property OnConnectionNudge: tAsyncTLSNudgeEvent read fOnConnectionNudge write fOnConnectionNudge;
THE VETO. Fired after a connection has been nudged - by an application calling tTLSConnection.RequestNudgeFor today, by the deadline reaper when it lands - and BEFORE anything is closed. Full description »
property OnSendQueueOverflow: tAsyncTLSSendOverflowEvent read fOnSendQueueOverflow write fOnSendQueueOverflow;
THE BACKLOG CEILING CLOSED A CONNECTION. Fired once per connection when MaxSendQueueBytes refuses a buffer, just before the close it causes - the close is not vetoable and happens whatever the handler does. Full description »

Types (enumerations, sets, aliases)

enumtAdmissionVerdict

  tAdmissionVerdict = (avAdmit, avDeferHandshake, avRefuseBusy);

enumtFallbackPolicy

  tFallbackPolicy   = (fbpRefuse, fbpUseFallback, fbpFirstRegistered);

enumtNudgeReason

Why a connection is being asked whether it should still exist. Separate values rather than one "idle" because the layers that answer want to tell them apart: a handshake that never finished, a request that stopped arriving and a keep-alive connection between requests are not the same connection and do not deserve the same answer. nrRequestStalled is raised when the budget a session set with iAppTransportDeadlines.SetSessionBudget runs out.

  tNudgeReason  = (nrIdle,               // no traffic for the configured period
                   nrHandshakeStalled,   // handshake begun and never completed
                   nrRequestStalled,     // a session's own budget ran out
                   nrApplication,        // the application asked, for its own reasons
                   nrShutdown);          // the server is going down - wind up now

enumtNudgeVerdict

The answer. nvClose is the default at every layer: a deadline that expires by being ignored is not a deadline.

  tNudgeVerdict = (nvClose, nvKeepAlive);

proctAsyncTLSConnectionEvent

  tAsyncTLSConnectionEvent = procedure (Sender: TObject;
                                        aConnection: tTLSConnection) of object;

proctAsyncTLSPeerRefusedEvent

Fired when the peer screen turned a connection away at accept. Informational: the descriptor is already closed and nothing was sent.

  tAsyncTLSPeerRefusedEvent = procedure (Sender: TObject; const aPeer: string;
                                         aReason: tPeerRefusal) of object;

proctAsyncTLSProtocolSelectEvent

  tAsyncTLSProtocolSelectEvent = procedure (Sender: TObject;
                                            aConnection: tTLSConnection;
                                            const aALPN: OctetString;
                                            var aProtocol: iAppProtocol) of object;

proctAsyncTLSNudgeEvent

Fired before a nudged connection is closed - see OnConnectionNudge. aVerdict arrives carrying the protocol plugin's own answer (nvClose when the plugin did not implement iAppSessionNudge), so a handler that leaves it alone defers to the plugin.

  tAsyncTLSNudgeEvent = procedure (Sender: TObject; aConnection: tTLSConnection;
                                   aReason: tNudgeReason;
                                   var aVerdict: tNudgeVerdict;
                                   var aRearmMs: Cardinal) of object;

proctAsyncTLSSendOverflowEvent

Fired when MaxSendQueueBytes refused a buffer and the connection is being closed for it - see OnSendQueueOverflow. aQueued and aInFlight are the backlog it did not fit behind, aRefused the buffer that was dropped.

  tAsyncTLSSendOverflowEvent = procedure (Sender: TObject;
                                          aConnection: tTLSConnection;
                                          aQueued, aInFlight,
                                          aRefused: Integer) of object;

proctConfigureEngineEvent

Fired once per engine at activation (on the activating thread) so the app can load the identity + options into EACH sharded engine.

  tConfigureEngineEvent = procedure (Sender: TObject; aIndex: Integer;
                                     aEngine: TsmSimpleTLSInternalServer) of object;

enumtProvisionKind

ONE RECORDED PROVISIONING CALL, replayed when the engine bank exists. The engines are built inside activation, so a call that provisions the bank can only be performed once there is a bank. Recording it instead is what lets an application state its certificates in the ordinary place - beside the port and the routes, before Active := True - and have them applied at the first moment there is somewhere to put them. ONE QUEUE, NOT ONE PER OPERATION, because the ORDER is load-bearing: importing a leaf before its issuer is in the store leaves the chain incomplete, and an application says so by calling LoadRootCertsFromFile first. Replaying by category would discard exactly that.

  tProvisionKind = (pvkRootCerts, pvkPfx, pvkValidate);

Routines