THE CLEARTEXT HALF, FOR EVERY MAIL PROTOCOL IN THIS FAMILY. TsmAsyncTLSServer
is implicit TLS from byte 0, which is exactly right for 465, 995 and 993 and
exactly wrong for the port beside each of them: a peer connects to 25, 110 or
143 in CLEARTEXT, reads the greeting, and only then may ask for TLS -
STARTTLS in SMTP (RFC 3207) and IMAP (RFC 2595), STLS in POP3 (RFC 2595).
This unit is that transport - a bound port, a blocking accept loop, one thread
per connection, and a byte channel that can upgrade itself to TLS in place.
IT SPEAKS NO PROTOCOL AT ALL, AND IT NAMES NONE. It moves octets and performs
the handshake; the conversation belongs to an iMailConnectionHandler,
implemented by StreamSec.Mail.SMTPServer and StreamSec.Mail.POP3Server over
their respective transport-free engines.
NOTHING HERE IS INSTANTIATED DIRECTLY. Every class in this unit is a base with
a per-protocol descendant - tSmtpListener, tSmtpChannel and
tSmtpListenerOptions in StreamSec.Mail.SMTPTransport, with the POP3 and IMAP
counterparts to follow. That is not ceremony: A LISTENER IS ITS PORT, and 25,
110 and 143 are three different answers to every question a port is asked -
which TLS posture is correct, how long silence may last, how many connections
one peer may hold, and what the upgrade command is called in a log line. The
listener is also the only object here that knows which protocol its port
speaks, which is why it - and nothing else - names the concrete channel and
thread classes (see ChannelClass).
WHY THREAD-PER-CONNECTION AND NOT THE REACTOR.
- The upgrade is trivial when the thread owns the socket: stop reading
cleartext, run the handshake in place, carry on. On the async server the
same thing would break its stated invariant that a connection cannot reach
a plugin without a TLS session token (AsyncTLSServer.txt section 1).
- Mail does synchronous durable I/O on the connection thread - a spool write
that fsyncs, a mailbox write that fsyncs, an Argon2id derivation per
authentication - and the reactor runs plugin callbacks INLINE on an I/O
thread.
- An MX or a mailbox server sees tens of concurrent connections, not tens of
thousands. The caps here are sized for that and are enforced before a
thread is created.
THE FUTURE IS NOT FORECLOSED. iMailConnectionHandler is transport-shaped
(Opened / DataReceived / Pending / SecureChannelEstablished / IdleTimeout /
Closed), so a reactor-based driver can be written later and the handler is
unchanged.
DEPENDENCIES ARE DELIBERATE: stSocket for the socket, TlsClass for the content
layer, TlsInternalServer for the engine. It does NOT use
StreamSec.Mobile.AsyncTLSServer, which would drag in the reactor and both
listener backends for nothing.Feature notes: Mail subsystem notes (SMTP / POP3 / IMAP)
inherits from Exception
(no public members)
WHAT THE CONVERSATION SEES OF ITS TRANSPORT. Deliberately the union of what iAppTransport and iTLSConnectionInfo already provide on the async side, so the same session code can be driven over either with a thin adapter and no conditionals.
A PROTOCOL'S OWN CHANNEL INTERFACE DESCENDS FROM THIS ONE and carries its own GUID. That is what keeps the descendants apart at run time: Delphi's QueryInterface does NOT walk interface ancestry, so a class that lists only iSmtpChannel does not answer to iMailChannel and vice versa. Anything that must be reachable as both has to list both - see tSmtpAsyncChannel in StreamSec.Mail.SMTPServer, which has no ancestor to inherit the entry from.
function GetRemoteAddress: string;
function GetSecure: Boolean;
function GetVersionName: string;
function GetCipherSuiteName: string;
function GetPeerCertificate: iCertificate;
function GetPeerCertificatePresent: Boolean;
procedure Send(aData: Pointer; aLen: Integer);
procedure Close(aGraceful: Boolean);
property RemoteAddress: string read GetRemoteAddress;
property Secure: Boolean read GetSecure;
property VersionName: string read GetVersionName;
property CipherSuiteName: string read GetCipherSuiteName;
property PeerCertificate: iCertificate read GetPeerCertificate;
property PeerCertificatePresent: Boolean read GetPeerCertificatePresent;
Optional companion of iMailChannel (Supports on the channel): ends the connection now, without waiting for queued output to reach the peer, and without blocking behind a session callback that is running on it. A channel without it is closed with Close(False) instead.
procedure Abort;
ONE CONNECTION'S CONVERSATION, from the driver's side. Every method runs on that connection's own thread, so blocking is permitted and expected - which is the whole reason this transport exists.
procedure Opened(const aChannel: iMailChannel);
procedure DataReceived(aData: Pointer; aLen: Integer);
function Pending: tMailHandlerPending;
procedure SecureChannelEstablished;
procedure IdleTimeout(aWholeSession: Boolean);
procedure Closed;
THE HANDLE A LISTENER HOLDS ON WHOEVER MINTS ITS HANDLERS. IT DECLARES NO METHOD, and that is the point rather than an omission: the only thing a NEUTRAL listener does with a factory is hold it, count its reference and refuse to start without one.
MINTING A HANDLER NEEDS THE CHANNEL AND THE OPTIONS OF A PARTICULAR PROTOCOL, both of which are per-protocol classes here, so NewHandler is declared on the per-protocol descendant where both parameters can be typed. A neutral NewHandler(iMailChannel, tMailListenerOptions) would put two casts on the accept path instead: an interface cast is a QueryInterface that can fail at run time, on the very line that reads aChannel.Secure to set the engine's AUTH gate; and tSmtpListenerOptions(aOptions) is an UNCHECKED class cast onto an object whose first descendant field is the port's role. Neither failure has a compile error and one of them is an open relay.
(no public members)
WHERE A SESSION HAS GOT TO, for the driver's limits on a session that has not yet got anywhere. Optional: a handler that does not implement it is never in the preamble. Found with Supports, once, when the handler is minted, so iMailConnectionHandler itself is unchanged.
PastPreamble is True once the peer has authenticated or, on SMTP, has a transaction with a recipient accepted: what a server owes a client from then on is the protocol's whole idle limit, whatever the load. When it goes back to False the preamble starts again, and so do its limits. Called on the thread that runs the conversation, between the handler's other calls.
function PastPreamble: Boolean;
inherits from TInterfacedObject
implements iMailChannel
ONE CONNECTION'S OCTETS. fLayer = nil IS THE CLEARTEXT SENTINEL: before the upgrade Send writes straight to the socket and Receive returns socket bytes; after it, the identical calls route through EncodeData/DecodeData and nothing above this class changes.
EVERYTHING IS PROTECTED RATHER THAN PRIVATE. private in Delphi is unit scope, so a tPop3Channel declared in another unit could see none of it, and the split would be decorative. Widening is source-compatible in both directions, which makes it free now and impossible once packaged.
constructor Create(aSocket: tAbstractSocket; aEngine: TsmSimpleTLSInternalServer; const aRemoteAddress: string); virtual;
destructor Destroy; override;
procedure Send(aData: Pointer; aLen: Integer);
procedure Close(aGraceful: Boolean);
function Receive(var aData: tBytes; aTimeoutMs: Cardinal; out aTimedOut: Boolean): Integer;
function StartTLS(aDeadline: UInt64; out aError: string): Boolean;
property State: tMailChannelState read fState;
Pins channels independently of mailbox state. A control thread stops services without joining the worker reporting a fatal exception.
constructor Create(const aFarewell: RawByteString; aStop: TThreadMethod);
destructor Destroy; override;
procedure Start;
procedure AddChannel(const aChannel: iMailChannel);
procedure RemoveChannel(const aChannel: iMailChannel);
procedure Request;
procedure DrainChannels(const aFarewell: RawByteString; aReportMs: Cardinal; const aReport: tMailDrainReportEvent);
procedure SetScope(aScope: TObject);
property Requested: Boolean read GetRequested;
(no public members)
The two preamble limits of one session, from its own timestamps.
procedure Start(aIdleSeconds, aSessionSeconds: Integer; aNow: UInt64);
procedure Restart(aNow: UInt64);
procedure Traffic(aNow: UInt64);
property OpenedAt: UInt64 read fOpenedAt;
property TrafficAt: UInt64 read fTrafficAt;
function Reached(aNow: UInt64; out aWholeSession: Boolean): Boolean;
inherits from TThread
The driver: read, hand to the handler, honour what it asks for.
constructor Create(aListener: tMailListener; var aSocket: tAbstractSocket; const aPeer: string); virtual;
destructor Destroy; override;
property Peer: string read fPeer;
inherits from TThread
The accept loop. Binds in the CONSTRUCTOR so a bind failure - port 25 without privilege on POSIX is the common one - comes back out of the caller's activation instead of dying inside a thread where nobody sees it.
constructor Create(aListener: tMailListener); virtual;
destructor Destroy; override;
procedure Stop;
inherits from TPersistent
THE PUBLISHED CONFIGURATION OF ONE BOUND PORT, less everything a protocol answers for itself.
DESCEND FROM IT PER PROTOCOL - tSmtpListenerOptions today, the POP3 and IMAP counterparts to follow - because five of these settings are not the transport's to choose: the port number, the TLS posture, the two deadlines whose RFC floors are five minutes for SMTP (RFC 5321 sec.4.5.3.2), ten for POP3 (RFC 1939 sec.3) and thirty for IMAP (RFC 9051 sec.5.4), and the two admission caps, which bound transient transactions on an MX but a steady-state population of signed-in users on IMAP. A descendant sets them in its constructor and REDECLARES each published property with its own `default`.
What stays here is what a bound socket owns whatever is spoken over it: the address and the backlog.
constructor Create(aOwner: TPersistent); virtual;
procedure AssignTo(Dest: TPersistent); override;
property InUse: Boolean read fInUse;
property BoundPort: Word read fBoundPort;
property Enabled: Boolean read fEnabled write fEnabled default False;
property BindIP: string read fBindIP write SetBindIP;
property Port: Word read fPort write SetPort;
property TLSMode: tMailTlsMode read fTLSMode write SetTLSMode;
property Backlog: Integer read fBacklog write SetBacklog default cMailDefaultBacklog;
property MaxConnections: Integer read fMaxConnections write SetMaxConnections;
property MaxConnectionsPerPeer: Integer read fMaxConnectionsPerPeer write SetMaxConnectionsPerPeer;
property IdleTimeoutSeconds: Integer read fIdleTimeoutSeconds write SetIdleTimeoutSeconds;
property SessionTimeoutSeconds: Integer read fSessionTimeoutSeconds write SetSessionTimeoutSeconds;
property PreambleIdleSeconds: Integer read fPreambleIdleSeconds write SetPreambleIdleSeconds;
property PreambleSessionSeconds: Integer read fPreambleSessionSeconds write SetPreambleSessionSeconds;
property PreamblePressurePercent: Integer read fPreamblePressurePercent write SetPreamblePressurePercent;
A SESSION ON AN IMPLICIT-TLS PORT GOES BY THE SAME OPTIONS as one on its protocol's listener, but nothing polls it: the reactor's reaper raises a nudge when a deadline runs out, and the session decides here. No thread and no dependency on the async server: the session passes in what the transport told it.
procedure Start(aOptions: tMailListenerOptions; aServerIdleMs: Cardinal; aNow: UInt64);
procedure Traffic(aNow: UInt64);
procedure PreambleEntered(aNow: UInt64);
function IdleLimitMs(aPastPreamble: Boolean): Cardinal;
function IdleSpent(aNow: UInt64): Boolean;
function BudgetMs(aPastPreamble: Boolean; aNow: UInt64): Cardinal;
function Expired(aOnBudget, aPastPreamble: Boolean; aLoadPercent: Integer; aNow: UInt64; out aRearmMs, aBudgetMs: Cardinal): tMailImplicitVerdict;
ONE BOUND PORT: the accept daemon, the live connections, the caps.
constructor Create(aOptions: tMailListenerOptions; const aFactory: iMailConnectionFactory; aEngine: TsmSimpleTLSInternalServer);
destructor Destroy; override;
procedure Start;
procedure RequestStop;
procedure Stop;
property Active: Boolean read fActive;
property ConnectionCount: Integer read GetConnectionCount;
property OnPeerConnect: tMailPeerConnectEvent read fOnPeerConnect write fOnPeerConnect;
property OnLog: tMailTransportLogEvent read fOnLog write fOnLog;
What the handler wants done once its DataReceived returns. Polled rather than called back, because the driver owns the socket and the handler must not touch it: a handler that closed or upgraded the channel from inside a read callback would be reaching into the loop that is calling it.
A peer has connected and nothing has been said yet. Set aAccept False to drop it before a thread is created or a greeting is written - the natural home for a blocklist or a DNSBL lookup, and the counterpart of the async server's peer filter. Runs on the ACCEPT thread, so it must be quick: everything behind it is waiting.
DrainChannels progress: aWaitedMs since the drain began.