Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.Transport

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)

Classes, interfaces and records

classeMailTransportError

inherits from Exception

(no public members)

interfaceiMailChannel

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;
True once the channel is encrypted. On this transport that is False until an in-band upgrade handshake has completed.
property VersionName: string read GetVersionName; property CipherSuiteName: string read GetCipherSuiteName; property PeerCertificate: iCertificate read GetPeerCertificate;
nil unless the peer presented one and it passed the handshake.
property PeerCertificatePresent: Boolean read GetPeerCertificatePresent;

interfaceiMailChannelAbort

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;

interfaceiMailConnectionHandler

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);
The channel is up and the peer is waiting for a greeting.
procedure DataReceived(aData: Pointer; aLen: Integer); function Pending: tMailHandlerPending;
Asked after every DataReceived and after Opened. mhpStartTLS makes the driver run the handshake and then call SecureChannelEstablished; mhpClose makes it stop reading and close.
procedure SecureChannelEstablished;
The upgrade succeeded and the channel is now encrypted.
procedure IdleTimeout(aWholeSession: Boolean);
A deadline expired. aWholeSession distinguishes the total-conversation budget from the between-commands one, because the two deserve different replies. The handler may write a farewell; the driver closes either way.
procedure Closed;

interfaceiMailConnectionFactory

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)

interfaceiMailSessionPhase

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;

classtMailChannel

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;
VIRTUAL, and it has to be: this is reached through tMailChannelClass. A constructor called through a class reference dispatches to the descendant only when it is virtual - with a static one the metaclass still supplies the descendant's instance SIZE and then runs THIS body, producing a tPop3Chann... Full description »
destructor Destroy; override; procedure Send(aData: Pointer; aLen: Integer); procedure Close(aGraceful: Boolean); function Receive(var aData: tBytes; aTimeoutMs: Cardinal; out aTimedOut: Boolean): Integer;
Plaintext octets, however the channel is currently framed. Returns the count, 0 when the connection has ended (an orderly close, a reset, or a socket a failed Send has closed), and -1 when nothing arrived (aTimedOut says whether a deadline or merely an empty round caused it - a TLS record that carried only handshake data yields no plaintext and is NOT a timeout).
function StartTLS(aDeadline: UInt64; out aError: string): Boolean;
The server side of the in-band upgrade. Call it AFTER the success reply has been written in cleartext - the 220 to STARTTLS, the +OK to STLS. Full description »
property State: tMailChannelState read fState;

classtMailServiceShutdown

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;
Registers runtime readiness without creating an idle OS thread.
procedure AddChannel(const aChannel: iMailChannel); procedure RemoveChannel(const aChannel: iMailChannel); procedure Request;
Bounded wait for channel closure and service stop, never joins.
procedure DrainChannels(const aFarewell: RawByteString; aReportMs: Cardinal; const aReport: tMailDrainReportEvent);
ORDINARY teardown of one component: has aFarewell sent on every registered session and the session closed, and waits until each has unregistered (the last thing the session's destructor does). Full description »
procedure SetScope(aScope: TObject); property Requested: Boolean read GetRequested;

classtMailListener

(no public members)

recordtMailPreambleClock

The two preamble limits of one session, from its own timestamps.

procedure Start(aIdleSeconds, aSessionSeconds: Integer; aNow: UInt64); procedure Restart(aNow: UInt64);
The session is back in its preamble: both limits run from aNow.
procedure Traffic(aNow: UInt64);
The peer said something, or the reply to it has just gone out.
property OpenedAt: UInt64 read fOpenedAt; property TrafficAt: UInt64 read fTrafficAt; function Reached(aNow: UInt64; out aWholeSession: Boolean): Boolean;
Has a limit been reached? aWholeSession says which one. The answer says nothing about whether the limit applies now: see PreamblePressurePercent.

classtMailConnectionThread

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;
VIRTUAL for the same reason tMailChannel.Create is - it is reached through tMailConnectionThreadClass. Full description »
destructor Destroy; override; property Peer: string read fPeer;

classtMailAcceptDaemon

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;

classtMailListenerOptions

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;
Set by tMailListener.Start and cleared by Stop.
property BoundPort: Word read fBoundPort;
The port the listener is bound to while InUse, 0 otherwise. With Port 0 this is the port the system assigned; Port itself is left as configured, so a stop and start binds a new system-assigned port and the setting streams out as it was set.
property Enabled: Boolean read fEnabled write fEnabled default False;
Off by default on every port, so adding this unit to an existing deployment changes nothing until somebody asks for it.
property BindIP: string read fBindIP write SetBindIP;
Empty binds every interface.
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;
NO `default` SPECIFIER ON THE SEVEN BELOW AT THIS LEVEL, and that is not an oversight. `default` tells the streaming system "do not write this value out", so it is only ever correct beside the constructor that actually produces it - and this class does not produce these four, its descendants do. Full description »
property MaxConnectionsPerPeer: Integer read fMaxConnectionsPerPeer write SetMaxConnectionsPerPeer;
Live connections from ONE peer address. Without it a single host can take every slot, which is the whole of the attack.
property IdleTimeoutSeconds: Integer read fIdleTimeoutSeconds write SetIdleTimeoutSeconds;
Seconds of silence between commands. 0 disables, which is not advisable against an untrusted peer.
property SessionTimeoutSeconds: Integer read fSessionTimeoutSeconds write SetSessionTimeoutSeconds;
Seconds for the WHOLE conversation, however busy. This is the one a dribbling peer cannot reset by sending something.
property PreambleIdleSeconds: Integer read fPreambleIdleSeconds write SetPreambleIdleSeconds;
THE PREAMBLE: a session that has neither authenticated nor opened a transaction (iMailSessionPhase). What it holds is a slot that somebody with something to do may need, and all it has shown is an address. These three say how long it may hold it. 0 in either of the first two turns that limit off, which leaves the two above in charge. Seconds of silence in the preamble.
property PreambleSessionSeconds: Integer read fPreambleSessionSeconds write SetPreambleSessionSeconds;
Seconds from the accept to the end of the preamble, however much is said, so a peer cannot keep its slot by saying NOOP. A session back in its preamble, as SMTP is after a message, has them again from that moment. It also bounds a TLS upgrade whatever the load: no read round runs while one is in progress.
property PreamblePressurePercent: Integer read fPreamblePressurePercent write SetPreamblePressurePercent;
When the two above apply: once this percentage of MaxConnections is in use. 0 means always. 100 means only when the port is full; above that normalises to 100, and a negative to 0. With MaxConnections 0 the port is never under pressure, so a value above 0 then never applies.

recordtMailImplicitClock

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);
aServerIdleMs is the async server's own IdleTimeout. Set and shorter than the listener's, it is the idle limit: an application that asked for it still gets it.
procedure Traffic(aNow: UInt64); procedure PreambleEntered(aNow: UInt64);
The session is back in its preamble, as SMTP is after a message: the preamble's limits run from aNow. The whole-session limit does not move.
function IdleLimitMs(aPastPreamble: Boolean): Cardinal;
The idle limit to run with, in this phase.
function IdleSpent(aNow: UInt64): Boolean;
The peer has said nothing for the whole idle limit. What this side sent meanwhile does not count, as on the listeners.
function BudgetMs(aPastPreamble: Boolean; aNow: UInt64): Cardinal;
The budget to run with from now, in this phase. 0 means none.
function Expired(aOnBudget, aPastPreamble: Boolean; aLoadPercent: Integer; aNow: UInt64; out aRearmMs, aBudgetMs: Cardinal): tMailImplicitVerdict;
A deadline ran out: aOnBudget says it was the budget. On mivKeep aRearmMs is when to ask again about the idle limit and aBudgetMs is the budget to run with; the session sets the one for the deadline that ran out.

classtMailListener

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;
Binds and starts accepting. A bind failure RAISES here, on the calling thread.
procedure RequestStop;
Stops accepting without joining any worker.
procedure Stop;
Stops accepting, wakes every live connection and waits for its thread.
property Active: Boolean read fActive; property ConnectionCount: Integer read GetConnectionCount; property OnPeerConnect: tMailPeerConnectEvent read fOnPeerConnect write fOnPeerConnect; property OnLog: tMailTransportLogEvent read fOnLog write fOnLog;

Types (enumerations, sets, aliases)

enumtMailTlsMode

  tMailTlsMode = (
    { No TLS on this port at all. The upgrade command is neither advertised nor
      honoured. }
    mtmDisabled,
    { Advertise the upgrade and honour it, but do not require it. }
    mtmOpportunistic,
    { Advertise the upgrade and refuse to go any further until it has been used.
      What "any further" means is the protocol's own answer - 530 at MAIL FROM
      for SMTP, a refused USER/PASS for POP3, LOGINDISABLED for IMAP. }
    mtmRequired);

enumtMailChannelState

  tMailChannelState = (mcsPlain, mcsSecure, mcsClosed);

enumtMailHandlerPending

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.

  tMailHandlerPending = (mhpNone, mhpStartTLS, mhpClose);

proctMailPeerConnectEvent

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.

  tMailPeerConnectEvent = procedure (Sender: TObject; const aPeer: string;
                                     var aAccept: Boolean) of object;

proctMailTransportLogEvent

  tMailTransportLogEvent = procedure (Sender: TObject; const aText: string;
                                      aFatal: Boolean) of object;

typetMailChannelClass

  tMailChannelClass = class of tMailChannel;

proctMailDrainReportEvent

DrainChannels progress: aWaitedMs since the drain began.

  tMailDrainReportEvent = procedure(aWaitedMs: UInt64) of object;

typetMailConnectionThreadClass

  tMailConnectionThreadClass = class of tMailConnectionThread;

typetMailAcceptDaemonClass

  tMailAcceptDaemonClass = class of tMailAcceptDaemon;

enumtMailImplicitVerdict

  tMailImplicitVerdict = (mivKeep, mivCloseIdle, mivCloseWhole);

Routines