Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mobile.AsyncTLSReactor

re-arm, close

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

Classes, interfaces and records

classEReactorInvariant

inherits from Exception

(no public members)

classtAsyncReactor

(no public members)

recordTSendItem

Data: PByte; Len: Integer;

classtReactorConnection

inherits from TInterfacedObject

Abstract per-connection object the reactor drives. Reference-counted (tInterfacedObject) so an in-flight overlapped op can pin it alive through an IInterface anchor held in its I/O context. The reactor does NOT own the connection's lifetime: the caller (server connection table / test) must keep a reference for as long as the connection is attached.

procedure HandleReceived(aData: Pointer; aLen: Integer); virtual; abstract;
Feed received plaintext/ciphertext to the next layer IN ORDER. Must fully consume aLen bytes (or buffer them internally) before returning; the reactor re-arms the next recv only after this returns. Descendant-implemented, invoked by the reactor.
function ReceiveEnded: Boolean; virtual;
The peer half-closed the TCP connection (recv returned 0). Called by the backend with the gate held. True keeps the connection open for SENDING: the backend posts no further receive and does not close it, and the descendant ends it later (RequestClose, or a deadline). False (the base) closes it at once, as a FIN always did.
constructor Create(aReactor: tAsyncReactor; aHandle: TSocketHandle); destructor Destroy; override; procedure Enter;
take the per-conn gate
procedure Leave;
release the per-conn gate
procedure EnqueueSend(aData: Pointer; aLen: Integer);
Ordered raw send of bytes already framed for the wire. MUST be called with the per-conn gate held (both the reactor path - KeyUpdate/alert/close_notify - and app-pool responses serialize through the same lock + FIFO). Copies aLen bytes; posts immediately if no send is in flight, else enqueues.
procedure SendCompleted(aByteLen: Integer); virtual;
Called by the reactor when a send completes (gate held); advances the FIFO. VIRTUAL so a descendant can learn that bytes actually reached the wire. Full description »
procedure RequestClose;
Cooperative close: the content layer asks the reactor to stop re-arming and tear down after the current completion (no exception needed).
procedure CloseFromReactor;
Idempotent teardown from the reactor path.
function RequestNudge: Boolean;
Asks the reactor to run DoNudge for this connection on one of its own I/O threads. SAFE FROM ANY THREAD, and the point of the whole mechanism: a deadline reaper, a management call or an application timer can reach a connection WITHOUT taking its gate, without touching the content layer and withou... Full description »
function RequestWork: Boolean; procedure SetReceivePaused(aPaused: Boolean);
Owner-gate only. Already posted receives remain owned by the backend; pausing prevents the next drain/rearm. Resume exactly once when idle.
procedure ResumeReceive; property ReceivePaused: Boolean read fReceivePaused; procedure DeliverNudge;
Runs the nudge: gate, Closed re-test, DoNudge, then the close DoNudge asked for. Called by a backend when it delivers a nudge it accepted; also callable directly as the fallback for a backend that cannot. Never raises out.
procedure DeliverQueuedWake;
Backend packet delivery. Empty/duplicate packets are harmless; explicit direct DeliverNudge retains its historical application-nudge meaning.
property CloseRequested: Boolean read GetCloseRequested; property NudgePending: Boolean read GetNudgePending;
True between RequestNudge and its delivery. A readiness backend reads this to tell a nudge event from an ordinary one; a completion backend does not need it (it carries the nudge in the packet).
procedure NoteRecvPosted;
Reactor-internal recv accounting (keeps the single-outstanding-recv invariant observable). NoteRecvPosted is called by PostReceive, NoteRecvCompleted by the recv completion, before any re-arm.
procedure NoteRecvCompleted; property Handle: TSocketHandle read fHandle; property Reactor: tAsyncReactor read fReactor; property RecvInFlight: Integer read fRecvInFlight; property RecvHighWater: Integer read fRecvHighWater; property Closed: Integer read fClosed; function SendCredit: Integer;
How many octets EnqueueSend can take NOW and still leave the backlog ceiling a quarter of its size to spare. Full description »
property SendQueueBytes: Integer read fSendQueueBytes;
Outbound backlog. SendQueueBytes counts what is QUEUED, i.e. excluding the buffer currently in flight; HighWater is the most ever queued and is the number to watch when sizing the cap. SendInFlightBytes is the length of the buffer the reactor is sending right now (0 when none), and SendPendingBytes is the two together: everything handed to EnqueueSend that the peer has not taken yet.
property SendInFlightBytes: Integer read fSendInFlightBytes; property SendPendingBytes: Integer read GetSendPendingBytes; property SendInFlight: Boolean read fSendInFlight;
True while a send is outstanding OR another is queued behind it. A close requested during that window MUST NOT tear the socket down - the queued octets would go with it. See the close guards in both reactor backends.
property SendQueueHighWater: Integer read fSendQueueHighWater; property MaxSendQueueBytes: Integer read fMaxSendQueueBytes write fMaxSendQueueBytes;
Hard ceiling on the queued backlog, in octets. 0 = unbounded, which is what this class used to be unconditionally and is a memory-exhaustion hole: a peer that issues requests and then stops reading its socket makes every response accumulate here, heap-copied, with nothing to stop it. NOT vetoable - by the time it trips, the memory is already committed.

classtReactorDatagramEndpoint

inherits from TInterfacedObject

A bound UDP socket the reactor drives (stSocket.OpenDatagramHandle makes one). Reference-counted for the same reason as tReactorConnection, and, like it, kept alive by its owner while attached.

RECEIVING. The reactor reads each datagram whole into its own buffer and calls HandleDatagram with it and its sender. HandleDatagram runs on an I/O thread with NO lock of this class held, and must neither keep aData nor take long: the next receive is posted after it returns.
- ReceiveDepth = 1 (the default): calls are SERIALIZED, one at a time, in the order the system delivered the datagrams.
- ReceiveDepth > 1: that many receives are kept posted, so on a completion backend (IOCP) calls may run CONCURRENTLY on several I/O threads and in any order - for a server whose handler dispatches to per-peer state with its own locks. A readiness backend (epoll, kqueue) still serializes; a handler written for > 1 is correct there. A receive that fails - an ICMP report about an earlier send, a datagram larger than the buffer, which cannot happen with the reactor's 64 KiB buffer - is counted in ReceiveErrors and the endpoint goes on receiving. An exception raised by HandleDatagram is counted in HandlerFaults and swallowed: one bad datagram from one peer must not take the socket down for the others.

SENDING. SendTo is safe from any thread, HandleDatagram included, and never waits. The datagram is handed to the system at once, or dropped and counted in SendsDropped: a full send buffer, a datagram too large for the path, an unreachable network. There is no queue - a datagram protocol recovers from loss itself, and a queue here would only be a second, unbounded, buffer behind the system's.

CLOSING. Close is safe from any thread, HandleDatagram included. The socket is closed once no system call is using it - a send or receive in progress on another thread finishes first - and DoClose runs once. A HandleDatagram already running on another thread may still be running when Close returns. An endpoint freed without Close (one never attached) closes its handle without running DoClose.

ECN. SetEcnReception(True), before AttachDatagram, has the backend read the ECN field of every datagram it receives; it then calls HandleDatagramEcn with the marking (deUnknown where the system supplied none), whose default passes the datagram on to HandleDatagram. SendToEcn and SendSegmentsToEcn send with the ECN bits set. The backends in this repository do both on Windows, Linux, Android, macOS and iOS, where the system allows it.

constructor Create(aReactor: tAsyncReactor; aHandle: TSocketHandle); destructor Destroy; override; procedure HandleDatagram(aData: Pointer; aLen: Integer; const aFrom: tSocketAddress); virtual; abstract;
One datagram: aLen octets at aData (0 is a real, empty datagram), sent by aFrom. See the class comment for threads and order.
procedure HandleDatagramEcn(aData: Pointer; aLen: Integer; const aFrom: tSocketAddress; aEcn: tDatagramEcn); virtual;
The same datagram with its ECN marking: what the backends call. Same threads and order as HandleDatagram. Override it to read the marking; the default calls HandleDatagram.
function SendTo(aData: Pointer; aLen: Integer; const aTo: tSocketAddress): Boolean;
True once the datagram is handed to the system; False when it was dropped (LastError says why, unless the endpoint is closed).
function SendSegmentsTo(aData: Pointer; aLen, aSegmentSize: Integer; const aTo: tSocketAddress; out aError: Integer): Integer;
aLen octets at aData as consecutive datagrams of aSegmentSize, the last possibly shorter (valid sizes only): the number handed to the system, always the first ones; aError describes the first one that was not (0 for a full send buffer).
function SendToEcn(aData: Pointer; aLen: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; out aError: Integer): Boolean;
SendTo with the ECN bits set to aEcn: deNotEct, deEct0 or deEct1. False with aError = cDatagramUnsupported: nothing was sent and nothing is counted - deCe, deUnknown, or a marking the backend or the system cannot set; send the datagram again with SendTo. Otherwise as SendTo, with the reason for a drop in aError (0 for a full send buffer).
function SendSegmentsToEcn(aData: Pointer; aLen, aSegmentSize: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; out aError: Integer): Integer;
SendSegmentsTo with every datagram marked aEcn, as SendToEcn marks one. A result of 0 with aError = cDatagramUnsupported means that nothing was sent and nothing is counted: send the datagrams again with SendSegmentsTo.
function SetEcnReception(aEnabled: Boolean; out aError: Integer): Boolean;
Turns reading the ECN field of received datagrams on or off, as stSocket.SetDatagramEcnReception does for a handle. Call it before AttachDatagram, and from one thread at a time: a change afterwards applies to the receives posted after it. False: aError is cDatagramUnsupported (the backend or the system cannot), cDatagramClosed or a system error, and EcnReception is as it was.
procedure Close; function AcquireHandle(out aHandle: TSocketHandle): Boolean;
For the backends. AcquireHandle takes the handle lock and answers the handle, or answers False - with the lock NOT held - once the endpoint is closed. Every True is paired with one ReleaseHandle.
procedure ReleaseHandle; procedure NoteReceived; procedure NoteReceiveError(aError: Integer); procedure NoteHandlerFault; property Reactor: tAsyncReactor read fReactor; property Handle: TSocketHandle read fHandle;
The handle as attached, also after Close (for a backend's bookkeeping; never for a system call - see AcquireHandle).
property Closed: Integer read fClosed; property EcnReception: Boolean read fEcnReception;
True after SetEcnReception(True) succeeded (and no later SetEcnReception(False)); the backends read it to decide how to receive.
property ReceiveDepth: Integer read fReceiveDepth write SetReceiveDepth;
Receives kept posted; set before the endpoint is attached. At least 1.
property DatagramsReceived: Int64 read GetDatagramsReceived; property DatagramsSent: Int64 read GetDatagramsSent; property SendsDropped: Int64 read GetSendsDropped; property ReceiveErrors: Int64 read GetReceiveErrors; property HandlerFaults: Int64 read GetHandlerFaults; property LastError: Integer read fLastError;
The last system error a send or receive reported, or a stSocket datagram code (cDatagramTruncated); 0 when there has been none.

classtAsyncReactor

Abstract reactor. Concrete backends implement the platform I/O multiplexer.

constructor Create(aThreadCount: Integer); virtual; procedure Start; virtual; abstract; procedure Stop; virtual; abstract; procedure CloseSocketHandle(aHandle: TSocketHandle); virtual; abstract;
Closes an OS socket handle. Abstract because it is the one teardown step that is genuinely platform-specific; tReactorConnection.CloseFromReactor routes through here so the connection class needs no socket API of its own.
procedure Attach(aConnection: tReactorConnection); virtual; abstract; procedure Detach(aConnection: tReactorConnection); virtual; abstract; function PostReceive(aConnection: tReactorConnection): Boolean; virtual; abstract;
Post the (single) next receive for aConnection. Returns False if it could not be posted (shutting down / socket error) - the caller must then close.
function PostSend(aConnection: tReactorConnection; aData: Pointer; aLen: Integer): Boolean; virtual; abstract;
Copy aLen bytes and post one overlapped send. Returns False on failure.
function Nudge(aConnection: tReactorConnection): Boolean; virtual;
Deliver an out-of-band wake for aConnection on one of this reactor's own I/O threads, which then calls aConnection.DeliverNudge. Full description »
function SupportsApplicationWork: Boolean; virtual;
Old external backends remain supported for complete-body protocols.
function ConnectionCount: Integer; virtual; abstract;
Live attached connections. A graceful shutdown polls this while draining.
function SnapshotConnections(out aConns: TArray<tReactorConnection>; out aHold: TArray<IInterface>): Integer; virtual; abstract;
Snapshot of the attached connections, each pinned by an interface reference parked in aHold so the raw references stay valid for as long as the caller keeps aHold alive. Returns the count. Every backend needs this for the drain, so it lives on the abstraction rather than on one implementation.
function SupportsDatagrams: Boolean; virtual;
VIRTUAL, NOT ABSTRACT, for the reason Nudge gives: a backend outside this repository that predates the path keeps compiling, and answers that it does not have it.
procedure AttachDatagram(aEndpoint: tReactorDatagramEndpoint); virtual;
Takes aEndpoint in and posts its ReceiveDepth receives. Raises EReactorUnavailable on a backend without the path, and EReactorInvariant (with the endpoint closed) when not one receive could be posted.
procedure DetachDatagram(aEndpoint: tReactorDatagramEndpoint); virtual;
Drops aEndpoint; called by tReactorDatagramEndpoint.Close before the socket is closed.
function SendDatagram(aEndpoint: tReactorDatagramEndpoint; aData: Pointer; aLen: Integer; const aTo: tSocketAddress; out aError: Integer): Boolean; virtual;
Sends one datagram now (see tReactorDatagramEndpoint.SendTo). aError is a system error, a stSocket datagram code, or 0 for a full send buffer.
function SendDatagramSegments(aEndpoint: tReactorDatagramEndpoint; aData: Pointer; aLen, aSegmentSize: Integer; const aTo: tSocketAddress; out aError: Integer): Integer; virtual;
Several datagrams of aSegmentSize from one buffer (see tReactorDatagramEndpoint.SendSegmentsTo). The default sends them one by one through SendDatagram, so a backend without the override keeps working; a backend with segmentation offload sends them in one call.
function SetDatagramEcnReception(aEndpoint: tReactorDatagramEndpoint; aEnabled: Boolean; out aError: Integer): Boolean; virtual;
ECN on the datagram path (see tReactorDatagramEndpoint.SetEcnReception, SendToEcn and SendSegmentsToEcn). Virtual, not abstract, for the reason Nudge gives: the base answers cDatagramUnsupported for reception and for a marking, sends deNotEct through SendDatagram and SendDatagramSegments, and sends a marked batch one SendDatagramEcn at a time.
function SendDatagramEcn(aEndpoint: tReactorDatagramEndpoint; aData: Pointer; aLen: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; out aError: Integer): Boolean; virtual; function SendDatagramSegmentsEcn(aEndpoint: tReactorDatagramEndpoint; aData: Pointer; aLen, aSegmentSize: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; out aError: Integer): Integer; virtual; function DatagramEndpointCount: Integer; virtual;
Always returns 0.
property Kind: tReactorKind read GetKind; property ThreadCount: Integer read fThreadCount; property EnforceSingleRecv: Boolean read fEnforceSingleRecv write fEnforceSingleRecv;
When True (default), PostReceive raises EReactorInvariant if a second recv would be posted for a connection. Test harnesses flip it off to install the negative control (deliberately post two concurrent recvs).

classEReactorUnavailable

inherits from Exception

(no public members)

Types (enumerations, sets, aliases)

typeTSocketHandle

  TSocketHandle = NativeUInt;

typeTSocketHandle

  TSocketHandle = Integer;

enumtReactorKind

  tReactorKind = (rkIOCP, rkEpoll, rkKQueue, rkSelect);

typePSendItem

One queued outbound buffer awaiting its turn in a connection's send FIFO.

  PSendItem = ^TSendItem;

proctReactorFactory

Constructs one backend instance. Registration rather than a hard-coded case statement, because this unit must NOT reference the backends - they reference it. Each backend registers itself from its initialization section, so simply having the unit in the program makes that backend available.

  tReactorFactory = function (aThreadCount: Integer): tAsyncReactor;

Routines