Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

Mail subsystem notes (SMTP / POP3 / IMAP)

================================================================================
 MAIL SUBSYSTEM
 Analysis of the StreamSec.Mail units - SMTP, POP3, IMAP, and the stores
 (StreamSec Security Library for Embarcadero Delphi)
================================================================================

Generated: 2026-08-12

A complete mail host, as components. Mail arrives over SMTP, lands in a
maildir, and the same maildir is served back out over POP3 and IMAP; outbound
mail leaves through a queue that retries, expires and bounces. The client side
of all three protocols is here too, along with the message model they carry.

Companion to TLS.txt (every listener and every client here is a consumer of
that layer), to AsyncTLSServer.txt (which is how an implicit-TLS port is
served), and to PKIX.txt (S/MIME wrapping goes through the CMS components).
None is required reading first.


--------------------------------------------------------------------------------
0. SUMMARY
--------------------------------------------------------------------------------

Thirty units, about 47,600 lines. Twenty-nine are in the StrSecIV runtime
packages (170 through 370, i.e. XE3 through Delphi 13); the thirtieth is the
design-time registration unit in the DStrSecIV packages. Twelve palette
components, on the 'StreamSec Mobile' page beside the other Tsm
components, plus one on 'StreamSec Tools' beside the CMS components it extends.

THE SHAPE, because it is the same three times over. Each protocol is built in
four layers, and each layer knows nothing about the one above it:

  ENGINE      The protocol itself as a state machine over octets. No socket,
              no TLS, no threads - you can drive one from a memory buffer.
  TRANSPORT   A bound port, an accept loop, a thread per connection, and a
              channel that can upgrade itself to TLS in place.
  COMPONENT   The design-time face: properties, events, and the policy object
              that answers the engine's questions.
  STORE       Where messages and accounts actually live, shared by all three
              protocols rather than reimplemented per protocol.

WHAT IS DELIBERATELY NOT HERE. No mailing-list manager, no content filter (the
spam pipeline of section 5.2 scores the connection and the envelope, and a
check of the application's own may read the message), no virus scanning, no
webmail, no LMTP, no delivery-status-notification requests (RFC 3461 is refused
by name), no SRV-based autoconfiguration. The suite receives, stores, serves
and sends; policy above that is the application's.

SECURITY POSTURE IN ONE PARAGRAPH. Every password mechanism on every protocol
is refused on a cleartext channel, unconditionally and not configurably - SMTP
answers 538, POP3 and IMAP answer with the mechanism simply absent from the
capability list and the attempt refused. STARTTLS discards every claim made
before the upgrade rather than carrying it across. Implicit TLS is the
recommended posture (RFC 8314) and is what an async-server attachment provides;
the cleartext-then-upgrade ports exist because interoperability still needs
them. The relay gate is a policy, not an identity: the same component serves
port 25 and port 587, and what differs is whether that listener may carry mail
for a domain this host does not own, and whether a session must authenticate
before MAIL FROM.


--------------------------------------------------------------------------------
1. UNIT INVENTORY
--------------------------------------------------------------------------------

SMTP - receiving and sending

  StreamSec.Mail.SMTPEngine        2781  the RFC 5321 state machine over octets
  StreamSec.Mail.SMTPTransport      322  ports 25 / 587, the SMTP admission caps
  StreamSec.Mail.SMTPServer        3384  TsmSMTPServer: policy, relay gate,
                                         routing, and the three ways in
  StreamSec.Mail.SMTPSpool         2176  the on-disk queue behind a 250:
                                         retry, expiry, RFC 3464 bounces
  StreamSec.Mail.SMTPDelivery       640  local delivery into the maildir
  StreamSec.Mail.SMTPMx             676  MX resolution and the MTA-STS-aware
                                         delivery agent
  StreamSec.Mail.SMTPClient         928  TsmSMTPClient / TsmAdvancedSMTPClient

Retrieval - POP3 and IMAP

  StreamSec.Mail.POP3Engine        1871  the RFC 1939 state machine
  StreamSec.Mail.POP3Transport      219  port 110, the POP3 admission caps
  StreamSec.Mail.POP3Server        1377  TsmPOP3Server
  StreamSec.Mail.POP3Client         928  TsmPOP3Client / TsmAdvancedPOP3Client
  StreamSec.Mail.IMAPEngine        3984  the RFC 3501 state machine, IDLE,
                                         UIDPLUS and MOVE
  StreamSec.Mail.IMAPTransport      255  port 143, and why its timeouts differ
  StreamSec.Mail.IMAPServer        2037  TsmIMAPServer
  StreamSec.Mail.IMAPClient        1133  TsmIMAPClient / TsmAdvancedIMAPClient
  StreamSec.Mail.Retrieval          510  what the two retrieval servers share

Stores

  StreamSec.Mail.Maildir           6757  TsmMailStore: the mailbox tree, its
                                         index, its locks and its UIDs
  StreamSec.Mail.Users             1125  TsmMailUsers: Argon2id accounts

Message authentication and delivery policy

  StreamSec.Mail.Spf               1410  RFC 7208 evaluator
  StreamSec.Mail.Dkim              2171  RFC 6376 signer and verifier
  StreamSec.Mail.Dmarc              920  RFC 7489 alignment and policy
  StreamSec.Mail.MessageAuth        835  the inbound gate that runs all three
                                         and stamps Authentication-Results
  StreamSec.Mail.MTASTS             634  RFC 8461 policy fetch, parse and cache
  StreamSec.Mail.Dns               2098  the DNS-over-TCP resolver they need
  StreamSec.Mail.SpamFilter         895  the spam pipeline: score, verdict,
                                         stamp
  StreamSec.Mail.SpamChecks        1570  HELO, reverse DNS, DNSBL, rate and
                                         greylist checks

Messages

  StreamSec.Mail.Message           2672  TsmEmail: headers, addresses, the MIME
                                         tree, encodings
  StreamSec.Mail.SMIMEBroker        803  TstSMIMEBroker: S/MIME over TsmEmail

Shared and design-time

  StreamSec.Mail.Transport         2947  the protocol-neutral transport: listen,
                                         accept, thread, upgrade, shutdown
  StreamSec.Mail.Reg                129  design-time registration (design pkg)

THE ONE UNIT TO READ FIRST is StreamSec.Mail.Transport. It is where a
connection becomes a thread, where a cleartext channel becomes a TLS channel
without reconnecting, and where the admission limits are enforced; the three
protocol transports are thin subclasses of it that differ almost entirely in
their default timeouts and caps, and the reason those differ is in section 11.

Outside the family, stWorkerFatal holds the process's one fatal mechanism, which
the mail units share with the TLS layer: section 7.3.


--------------------------------------------------------------------------------
2. RFC MAP - WHICH RFC DEFINES WHAT, AND WHERE IT IS IMPLEMENTED
--------------------------------------------------------------------------------

Forty-nine specifications, of which four appear because they are deliberately
NOT implemented and one because only its reasoning is borrowed. Where a
document is only partly implemented the entry says which part.

MAIL TRANSFER

  RFC 5321  Simple Mail Transfer Protocol
            The server engine entire: the session state machine, path parsing,
            multiline replies, dot transparency, the Received trace field, and
            the size minima read as minima a server must ACCEPT rather than
            maxima it must enforce. VRFY and EXPN answer 252 rather than
            confirming or denying an address (sec.7.3), postmaster is resolved
            before the mailbox store so no unknown-user rule can hide it
            (sec.4.5.1), and a recipient repeated in one transaction is answered
            250 and dropped (section 14 on how that comparison treats case).
            SMTPEngine, SMTPServer, SMTPSpool, SMTPTransport, SMTPClient, SMTPMx

  RFC 6409  Message Submission for Mail
            Submission is a port ROLE, not a flag: the role enum has exactly
            two members and they differ in whether the listener may relay,
            whether it offers AUTH, and whether a session that has not
            authenticated is refused at MAIL FROM (sec.4.3; section 3.2).
            SMTPTransport, SMTPEngine, SMTPServer, SMTPClient

  RFC 1870  SMTP Service Extension for Message Size Declaration
            SIZE advertised on EHLO, with 0 spelling "no fixed maximum". The
            MAIL FROM SIZE= parameter is a courtesy pre-check; the real bound
            is enforced on the octets as they arrive.
            SMTPEngine

  RFC 2920  SMTP Service Extension for Command Pipelining
            PIPELINING advertised; a pipelined batch is answered from one read
            and the replies coalesce into a single write, so one TLS record.
            SMTPEngine

  RFC 6531  SMTP Extension for Internationalized Email
            SMTPUTF8 advertised and the MAIL parameter honoured only when
            OfferSmtpUtf8 is on; otherwise a non-ASCII path is 501 and the
            parameter itself 555.
            SMTPEngine, SMTPServer

  RFC 3848  ESMTP and LMTP Transmission Types Registration
            The Received "with" keyword distinguishes ESMTP / ESMTPA / ESMTPS /
            ESMTPSA, so a trace records HOW a message arrived - authenticated,
            encrypted, both or neither.
            SMTPServer, SMTPEngine

  RFC 3461  SMTP Service Extension for Delivery Status Notifications
            NOT IMPLEMENTED, and refused by name: RCPT parameters answer 555.
            SMTPEngine, SMTPClient

  RFC 3463  Enhanced Mail System Status Codes
            The enhanced codes carried in a bounce's Status: field and in live
            reply text.
            SMTPSpool, MessageAuth, SMTPServer

  RFC 3464  An Extensible Message Format for Delivery Status Notifications
            The bounce itself: multipart/report, report-type=delivery-status,
            Reporting-MTA and Arrival-Date, then Final-Recipient / Action /
            Status / Diagnostic-Code per recipient.
            SMTPSpool

TRANSPORT SECURITY

  RFC 8314  Cleartext Considered Obsolete: Use of TLS for Email Submission and
            Access
            The posture of the whole suite. Implicit TLS is the recommended
            deployment - SMTPS, IMAPS and POP3S as async-server attachments,
            encrypted from the first octet - and every password mechanism is
            refused on a cleartext channel on every protocol.
            SMTPTransport, SMTPEngine, SMTPServer, POP3Engine, POP3Server,
            POP3Client, IMAPEngine, IMAPServer, IMAPClient, SMTPClient,
            SMTPSpool, IMAPTransport, POP3Transport

  RFC 3207  SMTP Service Extension for Secure SMTP over TLS
            The 220 that promises the handshake is itself the last cleartext
            output. A failed upgrade closes the connection rather than
            reverting; STARTTLS is not offered twice; and on success the server
            discards the greeting name, the identity and any transaction rather
            than carrying a cleartext claim across the upgrade.
            SMTPEngine, Transport, SMTPClient, SMTPSpool, SMTPServer

  RFC 2595  Using TLS with IMAP, POP3 and ACAP
            The same rule for STLS and for IMAP STARTTLS: the affirmative reply
            is the last cleartext octet, the input buffer is wiped, and the line
            loop stops dead so nothing pipelined behind it is executed.
            POP3Engine, IMAPEngine, Transport, POP3Server, IMAPServer,
            POP3Client, IMAPClient, POP3Transport, IMAPTransport

  RFC 7301  TLS Application-Layer Protocol Negotiation
            How an implicit-TLS attachment is selected - and why each mail
            protocol needs its own async server, since no mail client offers
            ALPN and a fallback is singular.
            POP3Server, IMAPServer (with the TLS layer)

AUTHENTICATION

  RFC 4954  SMTP Service Extension for Authentication
            AUTH refused over cleartext with 538, unconditionally and not
            configurably; refused twice with 503; refused inside a transaction;
            '=' is the empty initial response; invalid base64 is 501.
            SMTPEngine, POP3Engine

  RFC 5034  POP3 SASL Authentication Mechanism
            AUTH PLAIN and AUTH LOGIN, the initial-response form routed through
            the same decoder and handler as the continuation form; '*' cancels.
            POP3Engine, POP3Server, POP3Client

  RFC 4959  IMAP Extension for SASL Initial Client Response
            AUTHENTICATE with an initial response, through the same path as the
            continuation form.
            IMAPEngine

  RFC 4616  The PLAIN SASL Mechanism
            authzid NUL authcid NUL passwd; the authorization identity is
            parsed past and ignored rather than honoured.
            SMTPEngine, POP3Engine, IMAPEngine

  RFC 9106  Argon2 Memory-Hard Function for Password Hashing
            The account password verifier: Argon2id, with the parameters
            published as properties so a deployment can raise them.
            Users, POP3Engine

RETRIEVAL

  RFC 1939  Post Office Protocol - Version 3
            Full server. Printable-ASCII commands enforced on the octets before
            any decode; the exclusive maildrop lock, with "unable to open"
            answered separately from a bad credential; DELE only MARKS and the
            marks commit exactly once, in UPDATE, reached only by QUIT.
            POP3Engine, POP3Server, POP3Transport, POP3Client, Maildir

  RFC 2449  POP3 Extension Mechanism
            CAPA answers TOP, UIDL, PIPELINING, RESP-CODES, then STLS only when
            it is fully wired, then the password mechanisms only on a secure
            channel - nothing that will be refused if used.
            POP3Engine, POP3Client

  RFC 3501  Internet Message Access Protocol - Version 4rev1
            Full server, IMAP4rev1 only. The four states plus STARTTLS and
            IDLE, the command grammar, SELECT/EXAMINE, FETCH including every
            BODY[section] form, partial fetches, ENVELOPE and BODYSTRUCTURE,
            STORE, SEARCH, COPY, EXPUNGE, and literals.
            IMAPEngine, IMAPServer, IMAPTransport, IMAPClient, Maildir

  RFC 2177  IMAP4 IDLE command
            IDLE parks the connection in a state whose grammar accepts exactly
            one input, DONE; anything else is a protocol error. On the STARTTLS
            port changes are pushed while it waits (section 6.3).
            IMAPEngine, IMAPServer, IMAPTransport

  RFC 4315  IMAP UIDPLUS extension
            Advertised. UID EXPUNGE removes only the named messages, and the
            APPENDUID / COPYUID response codes are emitted.
            IMAPEngine, IMAPServer, IMAPClient

  RFC 5788  IMAP4 keyword registry
            $Junk and $NotJunk, like any keyword, are stored per message in
            the Maildir and offered by PERMANENTFLAGS \* (6.3, 7.1).
            IMAPEngine, IMAPServer, Maildir

  RFC 6154  IMAP LIST extension for special-use mailboxes
            Advertised, with CREATE-SPECIAL-USE. LIST reports \Sent, \Drafts,
            \Trash, \Junk and \Archive by TsmIMAPServer.SpecialUse (6.3).
            IMAPEngine, IMAPServer

  RFC 6851  IMAP MOVE extension
            Advertised. MOVE and UID MOVE move each message by one rename of
            its file; COPYUID in an untagged OK, then the EXPUNGEs (6.3).
            IMAPEngine, IMAPServer, Maildir

  RFC 7888  IMAP4 Non-synchronizing Literals
            Server side: the {n+} form is REFUSED BY NAME rather than read as a
            plain count, because accepting the syntax without the semantics
            means the peer's next octets arrive unannounced.
            IMAPEngine, IMAPClient

MESSAGES

  RFC 5322  Internet Message Format
            Parse and compose: the header block, address fields, date fields,
            and the line-length rules.
            Message, SMTPEngine, SMTPSpool, Dkim, Dmarc, MessageAuth

  RFC 2045  MIME Part One: Format of Internet Message Bodies
            The MIME tree, Content-Type defaulting to text/plain when absent,
            quoted-printable and base64.
            Message

  RFC 2047  MIME Part Three: Message Header Extensions for Non-ASCII Text
            Decoded on demand (B and Q); encoded as UTF-8 B-encoded words
            within the 75-character limit.
            Message, IMAPEngine

  RFC 2049  MIME Part Five: Conformance Criteria
            Named as part of what the MIME engine implements; no separate
            conformance check exists as an identifier.
            Message

  RFC 2231  MIME Parameter Value and Encoded Word Extensions
            DELIBERATELY NOT decoded and NOT produced: an extended parameter is
            returned as its raw value.
            Message

  RFC 3798  Message Disposition Notification
            NOT IMPLEMENTED. No Disposition-Notification-To handling anywhere.
            (absent from Message)

  RFC 8551  S/MIME Version 4.0 Message Specification
            S/MIME wrapping and unwrapping over TsmEmail: multipart/signed and
            application/pkcs7-mime.
            SMIMEBroker

  RFC 8702  Use of the SHAKE One-Way Hash Functions in CMS
            The micalg names for the SHA-3 family.
            SMIMEBroker

MESSAGE AUTHENTICATION

  RFC 7208  Sender Policy Framework (SPF) Version 1
            Full evaluator, including the HELO identity checked on its own, the
            null reverse path falling back to the HELO name, and the lookup
            budgets - which are protocol, not tuning.
            Spf, Dns

  RFC 6376  DomainKeys Identified Mail (DKIM) Signatures
            Verifier and signer. Tag-list parsing where a REPEATED tag is a
            syntax error rather than first-or-last-wins; both canonicalisations
            on both halves.
            Dkim, Dns, MessageAuth

  RFC 8301  Cryptographic Algorithm and Key Usage Update to DKIM
            rsa-sha1 refused at BOTH ends, and an RSA key below 1024 bits
            refused as policy rather than as a parse failure.
            Dkim

  RFC 8463  A New Cryptographic Signature Method for DKIM (Ed25519-SHA256)
            p= is the BARE 32-octet key, not a SubjectPublicKeyInfo; PureEdDSA
            signs the 32-byte SHA-256 hash as the message.
            Dkim

  RFC 8032  Edwards-Curve Digital Signature Algorithm (EdDSA)
            The Ed25519 arm behind RFC 8463.
            Dkim

  RFC 7489  Domain-based Message Authentication, Reporting, and Conformance
            Relaxed alignment compares organizational domains, strict compares
            the whole FQDN; one aligned pass suffices, and a DKIM pass that is
            not aligned is not a DMARC pass.
            Dmarc, MessageAuth

  RFC 8601  Message Header Field for Indicating Message Authentication Status
            The Authentication-Results field the inbound gate stamps: an
            authserv-id, spf= with smtp.mailfrom, and one dkim= clause per
            signature. Sec.5: an incoming one naming this host, its
            authserv-id read as sec.2.2 defines it, is removed.
            MessageAuth, Dkim, SMTPServer

DELIVERY POLICY AND DNS

  RFC 8461  SMTP MTA Strict Transport Security (MTA-STS)
            The policy pointer TXT record, the HTTPS policy fetch, the parse
            with its exactly-one-label wildcard rule, the cache, and the
            anti-downgrade decision that is the whole point of the mechanism.
            MTASTS, SMTPMx

  RFC 7672  SMTP Security via Opportunistic DANE TLS
            Cited for its reasoning only, and that reasoning is load-bearing:
            the MX name came from unsigned DNS, so whoever forged the MX answer
            also chooses the name a certificate would have to match.
            MTASTS, SMTPMx

  RFC 7505  A "Null MX" Resource Record for Domains That Accept No Mail
            A single MX at the root label means the domain accepts no mail, and
            that is PERMANENT - bounce at once rather than retrying for days.
            Dns, SMTPMx

  RFC 6125  Service Identity in PKIX Certificates
            The MX-leg name check, which runs unconditionally because the
            delivery agent sets the name to check before the handshake.
            SMTPMx

  RFC 1035  Domain Names - Implementation and Specification
            Name and label caps enforced on parse AND on encode; compression
            pointers followed a bounded number of times so a self-referential
            pointer cannot hang the parser.
            Dns

  RFC 7766  DNS Transport over TCP
            The whole resolver: the wire message behind a two-octet length
            prefix. There is no UDP path.
            Dns

  RFC 3596  DNS Extensions to Support IP Version 6
            AAAA, and the ip6.arpa reverse name - one nibble per label, low
            nibble first.
            Dns

  RFC 4291  IP Version 6 Addressing Architecture
            The IPv6 literal parser, deliberately stricter than inet_pton.
            Dns

  RFC 6186  Use of SRV Records for Locating Email Submission/Access Services
            NOT IMPLEMENTED. There is no SRV record type and no autoconfigura-
            tion lookup.
            (absent from Dns)

OTHER

  RFC 8470  Using Early Data in HTTP
            Cited for what it does NOT give SMTP: every command that matters is
            a state transition, so a replayed early-data flight is a replayed
            message.
            SMTPServer

  RFC 822   Standard for ARPA Internet Text Messages
            The obsolete form still met in stored mail and in IMAP internal
            dates.
            Message, IMAPEngine, SMTPServer, SMTPSpool

TWO GAPS IN THE CITATIONS, both worth knowing because the behaviour is present
and only the reference is missing:

  8BITMIME is advertised on every EHLO and the BODY= parameter is parsed and
  enforced, but RFC 6152 is named nowhere. It is the only advertised ESMTP
  keyword in the engine without a citation.

  ENHANCEDSTATUSCODES (RFC 2034) is never advertised on EHLO, yet enhanced
  codes are emitted in live reply text by the inbound authentication gate. A
  client therefore receives enhanced codes it was never told to expect. This is
  a conformance wrinkle rather than a fault - the codes are well-formed and a
  client that ignores them reads an ordinary three-digit reply.


--------------------------------------------------------------------------------
3. THE SMTP SERVER
--------------------------------------------------------------------------------

3.1  THE ENGINE  (StreamSec.Mail.SMTPEngine)

The verb set is EHLO, HELO, MAIL, RCPT, DATA, RSET, NOOP, QUIT, AUTH, STARTTLS,
VRFY, EXPN and HELP. Anything else is 500 and a tick against the error budget.
VRFY and EXPN answer 252: both leak the address book, and 252 is the sanctioned
way to decline without claiming the address does not exist.

EHLO advertises, in wire order: the greeting, PIPELINING, SIZE, 8BITMIME,
STARTTLS, SMTPUTF8, AUTH and HELP - the last four each conditional. STARTTLS
appears only when the transport can actually perform it, so a half-wired server
answers 502 rather than promising a 220 it cannot honour; the advertisement and
the command share one condition and therefore cannot disagree. AUTH appears
only on an encrypted channel, whatever AuthMechanisms says.

END OF DATA, AND SMTP SMUGGLING. The line scanner recognises CRLF and nothing
else, so neither <LF>.<LF> nor <CR>.<CR> can terminate a message; the single
dot on its own CRLF-delimited line is the only exit from the data state. What
happens to a bare newline INSIDE the message is a separate decision -
BareNewlinePolicy is sbnReject by default, answering 521 and dropping the
connection, and sbnNormalize is the opt-in that rewrites to CRLF. The default
is refusal because this library does not silently rewrite the octets it was
given.

DOT TRANSPARENCY removes exactly one leading period, and the size bound is
enforced on the stored octets rather than on the SIZE= the client claimed - the
parameter is checked early as a courtesy, but a client that lies is caught by
the count.

WHEN A POLICY OR STORE CALL RAISES, the command's buffered reply is replaced by
451 "mailbox operation failed" and the session goes on. A RCPT that raises keeps
MAIL and the recipients already accepted; any other command resets the
transaction. Inside an unfinished DATA, or a DATA that raises after entering the
data state, the reply is 421 "temporary failure receiving message, closing",
because a body line must never become a command; an exception on the terminating
dot is 451 with the transaction reset. With the store unavailable it is 421
"mailbox service is shutting down". The exception itself goes to OnLog. The
process-state classes are section 7.3.

3.2  THE TWO PORT ROLES, AND THE RELAY GATE

The role is a TYPE, not a flag. It is fixed at construction, assignment does
not copy it, and the role-free constructor raises - so a forgotten role cannot
quietly become an inbound port. The role also picks the TLS default: inbound
gets port 25 and opportunistic TLS, because an MX that refuses cleartext
refuses mail; submission gets 587 and required TLS.

A SUBMISSION SESSION MUST AUTHENTICATE. MAIL FROM from a session in the
submission role that has not authenticated is refused with 530 "authentication
required", unless its address is in RelayNetworks (RFC 6409 sec.4.3,
paraphrased: an error by default unless authorization is otherwise
established). SMTP AUTH counts, and so does a client certificate bound to this
transaction's reverse path. The implicit-TLS attachment is in the submission
role and offers no STARTTLS. The inbound role is unaffected; RequireAuth
extends the refusal to every port.

AN AUTHENTICATED ACCOUNT SENDS AS ITSELF. After SMTP AUTH, MAIL FROM accepts
the identity the session authenticated as (the account name, or the
aAuthorizedAs an OnAuthenticate handler set), compared without regard to case;
the null path; an address a client certificate on the same connection asserts;
and any address OnCheckSenderIdentity allows for that account. Anything else
is refused with 550 5.7.1 and the session goes on (RFC 6409 sec.6.1). The rule
runs before the spam filter and OnCheckSender, so neither can widen it;
OnCheckSender can still narrow it. The AUTH= parameter of MAIL lends no
identity. A session without SMTP AUTH - an MX peer, a RelayNetworks peer, a
certificate alone - is not held to it; a certificate alone is already bound to
the address it asserts. The header From is not checked.

OnCheckSenderIdentity(Sender, aEnvelope, aAccount, aPath, var aAllow) is asked
only for a path outside the account's own, on a session with SMTP AUTH. It is
where an application lets an account send as an alias it owns. A handler that
raises allows nothing: the client gets 451 and may try again.

RELAYING IS A POLICY, NOT AN IDENTITY, and one function decides it for all
three ways in. The recipient check arrives pre-loaded with 550 "relay not
permitted" and opens only when the recipient is one of ours, or - and only when
the role permits relaying at all - when the sender authenticated or the peer
sits in RelayNetworks. OnCheckRelay has the last word and may veto even an
authenticated sender.

Port 25 has TWO INDEPENDENT BARRIERS. AllowRelayOnInbound is False by default;
and an inbound session's engine is given an empty mechanism set unconditionally,
so the authenticated branch is unreachable by construction rather than by
configuration. A listener that combines AllowRelayOnInbound with 0.0.0.0/0 in
RelayNetworks refuses to bind at all.

CLIENT-CERTIFICATE RELAY IS BOUND TO THE REVERSE PATH.
RelayForClientCertificate on its own authorizes nothing: the MAIL FROM address
must BE one of the certificate's identities - the emailAddress RDN or an
rfc822Name SAN - as an exact address, with no same-domain or wildcard rule, and
only after OnClientCertificate has approved the chain. CommonName is
deliberately not consulted: it is not an email identity, and treating a display
name as one would accept "Alice Smith" as an address. The binding belongs to
one transaction: RSET, or a MAIL that raises, withdraws it, and a RCPT that
raises keeps it.

3.3  STARTTLS, AND WHAT IT THROWS AWAY

The 220 that promises the handshake is flushed before the upgrade is requested,
so it is the last cleartext output. Everything the peer pipelined behind
STARTTLS is wiped unread and the state machine stops dead, which is what makes
the wipe stick. On success the server clears the greeting name, the
authenticated identity and any transaction in progress, and re-stamps the
transport facts - a claim made in cleartext does not survive the upgrade. A
failed upgrade closes the connection rather than reverting.

The in-band upgrade refuses 0-RTT by construction, and the implicit-TLS path
refuses it explicitly with 554 and a close. SMTP has no safe 0-RTT: every
command that matters is a state transition, so a replayed early-data flight is
a replayed message, and there is no exempt subset the way HTTP has safe methods.

3.4  AUTHENTICATION

PLAIN and LOGIN, and the cleartext refusal is unconditional and not
configurable - 538 whenever the channel is not encrypted. Credentials reach the
policy as iSecretKey and every buffer that held one is wiped. The SASL
authorization identity is parsed past and ignored, in both PLAIN's authzid and
the MAIL AUTH= parameter, because honouring it is how a mechanism becomes an
impersonation primitive.

The backend order is fixed: TsmMailUsers first, then OnAuthenticate, and with
neither assigned nothing authenticates. Deny by default.

3.5  LOCAL DELIVERY

Three modes. sldNone leaves local recipients to OnMessage. sldEvent routes
through OnResolveMailbox and OnLocalDeliver, which must RAISE to refuse.
sldMaildir uses the built-in store - and should be given an assigned
TsmMailStore rather than a directory whenever anything else serves the same
tree, so that SMTP, POP3 and IMAP share one object (the locks are shared
further than that: section 7.1).

ONE DEFINITION OF "LOCAL", used at RCPT and again at end-of-data so the two
decisions cannot drift. Delivery prepends exactly Return-Path and Delivered-To
and is byte-exact below that, but for a message that came with a field
forged in this host's name, whose local copy has its Subject marked, and
which is filed into JunkFolder - the one message that is - where the
mailbox has that folder (section 5).

A message with both local and relay recipients is delivered locally first and
the relay subset is then spooled under a suffixed id, so the two halves cannot
overwrite each other on disk. Local-first is deliberate: a failed second commit
answers 451 and risks a duplicate rather than a loss.

QUOTA. With a store whose mailboxes have a limit (TsmMailStore.Quota or
OnMailboxQuota, section 7.1), RCPT TO to a mailbox at or over its limit is
452 4.2.2, a transient refusal the sender retries (RFC 3463 sec.3.3, X.2.2
"Mailbox full"); a SIZE= declared at MAIL FROM that does not fit the room
left is 552 5.2.2 at that RCPT (RFC 1870 sec.6.4), and the other recipients
are still accepted. At the end of DATA, before anything is written, every
local mailbox the message is for is checked again and the message is
delivered to none if one refuses it: one reply covers the transaction. A
mailbox that has reached its limit since RCPT is 452 4.2.2, as at RCPT; a
message whose copies do not fit the room a mailbox has left is 552 5.2.2.
Each copy counts at the size it is stored: the Return-Path and Delivered-To
the store adds in front of it are included, and each copy carries its own
recipient. A recipient the application resolves to a mailbox, an alias,
counts against that mailbox, so an alias and its account are two copies, each
of its own size. A store given as an iSmtpMailboxStore takes part when it
also implements iSmtpMailboxQuota. When it adds anything to what it stores,
it should also implement iSmtpMailboxCopySize, which answers the size of a
copy as it will be stored; a store that does not is taken to store the
message as it is. sldEvent delivery has no quota.

3.6  THE QUEUE

THE 250 IS DURABLE BEFORE IT IS SENT. The body is written under its final name,
the envelope is written to a temporary and committed with ONE rename; the
envelope's presence is what makes a message queued. A crash therefore leaves an
orphan body - collected on the next start - and never a half-written
deliverable. With FlushToDisk on, both are flushed before the rename: Windows
FlushFileBuffers, POSIX fsync, Darwin F_FULLFSYNC, falling back to fsync where
the file system does not implement it (MailFlushHandle). A failed flush, like
any failed store, raises, and the reply becomes 451.

Retry advances a ladder and persists it; expiry is measured FROM ARRIVAL rather
than from the first attempt, so a message cannot outlive its deadline by being
retried slowly. The far end's own reply classifies the outcome: 5xx permanent,
anything else transient. Give-up bounces, unless the reverse path was null - a
message from <> must not generate another notification, and the bounce itself
is queued from <>.

STOPPING. Stop starts no new delivery and waits for those running; DrainTimeout
only decides when it logs that it is still waiting. A delivery in flight
finishes and its outcome is recorded, and an item claimed but not started is
released. Start raises while an earlier Stop has not finished. With a shared
TsmMailStore deactivated (sldMaildir) the workers attempt nothing, remote
recipients included, and look again every cSmtpSpoolStoreWaitMs (1000 ms); a
queue write raises "the spool has failed", and a delivery still in flight
records nothing. The spool keeps the store it was started with, so reactivating
the store is not enough: stop the SMTP server and start it again, and the
message is then attempted again. With sldMaildir a process-state fault freezes
the queue files (section 7.3).

OUTBOUND TLS IS ONE PROPERTY, not two flags, mapping implicit / required /
opportunistic onto the underlying pair in exactly one place. There is no
"never". Opportunistic protects against a passive observer only, and still
verifies the certificate when STARTTLS is in fact offered.

OUTBOUND TRUST IS A SECOND ENGINE, and this is the sharpest configuration trap
in the suite. An engine's root list is simultaneously its client-certificate
anchor set, so loading a public CA bundle onto the LISTENING engine would make
every certificate on the internet a relay credential. SmarthostTLSServer exists
so that outbound trust and inbound trust are different objects.

THE PUBLIC ROOT SET IS A COMPONENT, for the legs that need one.
TsmCCADBTrustAnchors (StreamSec.Mobile.CCADB, over the embedded list in
StreamSec.Mobile.CCADBRoots) carries the CCADB / Mozilla set filtered to the
websites trust bit: drop it beside an engine, point its Engine at that engine,
and the roots go in when loading finishes - before the application's own
TLSSetupClient and before anything has connected. AddCCADBRoots does the same
for an engine built at run time.

WHICH ENGINE IS THE WHOLE QUESTION, AND A SMARTHOST IS NOT ONE OF THEM. A
smarthost is one host, run by one operator, with one issuer, and that issuer is
knowable when the deployment is configured: put that ONE root on the engine
SmarthostTLSServer names, with LoadRootCertsFromFile, and the compiled-in set
is never needed on that leg at all. Public roots do not buy trust in the
smarthost - they let every authority in the set vouch for everything that
engine ever verifies. The legs that do need them are the ones whose peer
arrives with the message: the MX agent's own engine, and the separate engine
behind the MTA-STS policy fetch, which is a second trust domain again -
section 4. Never TLSServer, which is the trap above.

3.7  WHAT THE SMTP SERVER DOES NOT DO

No CHUNKING/BDAT, no ETRN, no TURN/ATRN, no XCLIENT and no PROXY protocol -
each falls through to 500. No DSN request parameters: any RCPT parameter draws
555, so a generated bounce carries Final-Recipient but no Original-Recipient.
No CRAM-MD5, SCRAM or XOAUTH2.

The queue resolves a message AS A WHOLE - delivered, deferred or bounced -
because the client API underneath reports one outcome per submission. That is
the honest limit of the layer below rather than an oversight, and the server
sidesteps it for mail it accepts itself by splitting the transaction before
queueing.

The shipped smarthost agent does not resolve MX; it is a submission relay and
the smarthost owns the rest of the journey. MX delivery is a separate agent -
section 4.

The greeting name is recorded and never verified: a forward lookup proves
nothing about the peer, so it is recorded, not judged.


--------------------------------------------------------------------------------
4. MX DELIVERY AND MTA-STS
--------------------------------------------------------------------------------

tSmtpMxAgent is an alternative delivery agent: install it where the smarthost
agent would go and the queue resolves each recipient domain itself. The
envelope is split per domain, and the outcome rules are asymmetric on purpose -
a domain is permanently failed only if EVERY host said so, and across domains
transient beats permanent, because requeueing a delivered domain is a duplicate
while bouncing a deferrable one is a loss.

Null MX and NXDOMAIN are PERMANENT and bounce at once. Retrying a domain that
has published "I accept no mail" for five days helps nobody.

MTA-STS IS WHAT MAKES "THE MX HAS NO TLS" DECIDABLE. Without it, a receiving
domain that fails to offer STARTTLS is indistinguishable from an attacker who
stripped it. The policy is discovered from a TXT record, fetched over HTTPS,
parsed - the wildcard form matches EXACTLY one label - and cached under the
policy id with the domain's own max_age as the expiry.

THE ANTI-DOWNGRADE RULE IS THE WHOLE POINT, and it is implemented on all three
failure paths: no usable TXT, no fetcher configured, and a fetch or parse that
failed. Each records why. Under enforce, an MX the policy does not name is
skipped before a connection is made, and the configured TLS posture is RAISED
by the policy and never lowered.

THE FETCH SEAM keeps the policy unit free of any HTTP dependency, so the whole
of discovery is testable from a string; the real fetcher lives beside the MX
agent, with certificate verification on, no redirects followed, and its own
bounded read.

THE POLICY FETCH AND THE MX LEG ARE WHY A PUBLIC ROOT SET EXISTS AT ALL.
Neither peer can be named before the message arrives: the policy host is
mta-sts. plus the recipient domain, and the MX host is whatever that domain's
DNS answers - and whenever TLS happens at all the certificate is checked
against that MX hostname, which is not something the TLS policy relaxes. No
anchor for either can be settled at compile time or at configuration time,
which is the one case TsmCCADBTrustAnchors is for (section 3.6).

THAT SET IS DATED, and the date is part of the answer. Established, Source and
RootCount report the day the embedded list was taken, the URL it came from and
how many roots it holds. A root program removes CAs as well as adding them, so
refreshing the set is a library release; an application that logs Established
at start gives an operator the one fact needed to judge whether the build's
trust has grown too old to be believed.

RFC 7672 IS CITED FOR ITS REASONING, NOT ITS MECHANISM. There is no DNSSEC here
and therefore no DANE. The reasoning that is borrowed is the one that matters:
the MX name came from unsigned DNS, so whoever forged the MX answer also
chooses the name a certificate would have to match - which is why opportunistic
TLS to an MX, with a name check against a name the attacker picked, is not the
protection it appears to be.

THE DNS RESOLVER underneath is TCP-only - there is no UDP path in the socket
abstraction - and is hardened for hostile input: bounds checks on every read,
the 255- and 63-octet caps enforced on parse AND on encode, and a bounded
number of compression-pointer hops so a self-referential pointer cannot hang
the parser. Address literals are parsed more strictly than inet_pton: no
leading zeros, no short forms, and a v4-mapped v6 literal yields sixteen octets
so it can never match a v4 network.

iDnsResolver is the substitution seam, and it is what makes every policy unit
testable without a network. It also distinguishes NODATA from NXDOMAIN, which
is the split that decides requeue versus bounce.

WHAT THIS AREA DOES NOT DO. No DNSSEC, no DANE/TLSA, no SMTP TLS Reporting
(RFC 8460), and no SRV-based autoconfiguration (RFC 6186). The DNS cache is
MX-only - TXT, address and name lookups go to the wire every time. There is no
switch to prefer a TLS-capable MX over a higher-priority one: requiring TLS is
what raises the posture, and TLSPolicy says that properly. The MTA-STS policy
cache is in-memory, per-instance and NOT thread-safe: a spool delivering on
several threads must give each its own or guard it externally.


--------------------------------------------------------------------------------
5. INBOUND MESSAGE AUTHENTICATION  (SPF, DKIM, DMARC)
--------------------------------------------------------------------------------

One gate runs all three and stamps the result. It is off by default, and when
on it judges ONLY unauthenticated mail arriving in the inbound role - a
submission client has already proved who it is, and its mail has not been
signed yet.

SPF is a full check_host(): every mechanism, all four qualifiers, redirect= and
exp=, and full macro expansion including %{p} with forward confirmation of the
PTR name. THE LOOKUP BUDGETS ARE PROTOCOL, NOT TUNING - ten querying terms, two
void answers, more than ten MX exchanges is a permerror - and the counters are
readable so a test can assert them. Attacker-supplied text (the exp= string,
the HELO name, the reverse path) is control-stripped before it can reach a
header or a log; a header-injection vector is one of the shipped self-test
assertions.

DKIM verifies every signature on the message, each with its own verdict, over
rsa-sha256 and ed25519-sha256 in both canonicalisations. THE BODY HASH IS
CHECKED BEFORE ANY DNS LOOKUP, so the commonest failure costs no query, and the
comparison is constant-time. Three verifier policies are load-bearing: From:
must be in h=, an l= signature is refused unless deliberately enabled, and
header selection is bottom-up so an ADDED duplicate header breaks the signature
rather than hiding under it.

The signer covers only headers actually present, always covers From: whether
listed or not, and OVERSIGNS by default - each name listed once more than it
occurs, so a later addition of that header invalidates rather than slips in. It
reuses the verifier's own header-input builder, so signer and verifier cannot
diverge. rsa-sha1 is refused at both ends, and an RSA key below 1024 bits is
refused as policy rather than as a parse failure.

DMARC discovers the policy with the organizational-domain fallback and sp=
selection, and aligns both the DKIM d= and the SPF-authenticated domain. A DKIM
PASS IS MEANINGLESS WITHOUT ALIGNMENT, and one aligned pass suffices. The
result and the DISPOSITION are separate values, so a fail under p=none is still
a delivery. The From-header parser refuses two From: fields, and refuses two
addresses in one field, rather than choosing between them.

THE DECISION TABLE has a documented precedence: an ambiguous From is 550;
a DKIM key that could not be retrieved, with no signature verified, is 451
4.7.5 when a broken-signature rule could still turn on it; a broken signature
is 550 5.7.20, whatever the DMARC record does, since no answer it could give
changes that; a DMARC record that could not be retrieved is 451 4.4.3, unless
a verified DKIM signature has d= equal to the From domain itself or SPF passed
for a domain equal to it; a DMARC reject or quarantine is 451 4.4.3 when
an answer that did not come could still turn it into a pass - an SPF temperror
for a domain aligned with From: under the record's aspf=, or a DKIM key that
could not be retrieved for a d= aligned under its adkim=; a DMARC reject is
550 5.7.1. Verification runs on the message EXACTLY as received and the
Authentication-Results field is prepended only afterwards - which is safe
precisely because DKIM selects headers bottom-up.

WHEN DNS DOES NOT ANSWER, the message waits at the sender - but ONLY IF THE
MISSING ANSWER COULD STILL CHANGE THE DMARC VERDICT; one already settled is
acted on. RFC 7489 sec.6.6.3 and RFC 7208 sec.8.6 leave the choice to the
receiver and name 4yx and 451; accepting would deliver a forged p=reject
sender whenever this server's DNS is down. A permanent answer that no record
exists is not a temporary failure: DMARC does not apply, as before. An SPF
temperror with no DMARC refusal at stake changes nothing, since no SPF result
alone refuses a message here: it is delivered and stamped spf=temperror. Nor
does one for a domain that is not aligned with From: under the record's own
aspf= - the same organizational domain under aspf=r, the same name under
aspf=s: no SPF answer for it could have satisfied DMARC, and the domain is the
sender's to choose, so the DMARC refusal stands.

A DKIM KEY THAT COULD NOT BE RETRIEVED, under a record that was retrieved and
asks for p=reject or p=quarantine, is the same doubt. When its signature's d=
- which the signature itself carries - is aligned with From: under the
record's adkim=, the key could still make the message pass, and it waits
with 451 4.4.3; when it is not, no key could, and the refusal stands. Another
aligned identifier that passed makes the message a pass with nothing to wait
for. Only the first MaxSignatures signatures are looked at, so one past them
is never fetched and defers nothing.

WITH NO SIGNATURE VERIFIED AT ALL the same rule holds. A key that could not
be retrieved defers the message when its d= is aligned under a record that
asks for p=reject or p=quarantine, as above, 451 4.4.3; or when
RejectBrokenSignature or RejectAnyBrokenSignature could turn on it - a key
that verifies keeps the message out of both, one that fails puts it in - 451
4.7.5, unless the message is refused whatever the key says: another
signature that failed under RejectAnyBrokenSignature, a DMARC p=reject with
nothing aligned still waiting, or RequirePublishedPolicy with no record.
Otherwise the signature is judged without: the message is delivered,
quarantined or refused on the rest, and carries the X-DNS-Warning for the
key. "Every signature failed" counts only the signatures whose key came. A
signature of the sender's own domain whose key it keeps from answering no
longer turns a p=reject refusal into a 451.

A DNS outage longer than the sender's retry time therefore bounces what it
would have delivered. Authenticator.FailClosedOnTempError := False, or
OnMailAuth, gives the old answer back.

AN EXACT MATCH NEEDS NO RECORD. When the DMARC record could not be retrieved
and a DKIM signature that verified has d= equal to the From domain, or SPF
passed for a domain equal to it - compared without regard to case and to a
trailing dot - the message is a DMARC pass and is delivered. RFC 7489
sec.6.6.2 step 5: "If one or more of the Authenticated Identifiers align with
the RFC5322.From domain, the message is considered to pass the DMARC mechanism
check." An identical name aligns under adkim=r and adkim=s, aspf=r and aspf=s
alike, so no record could have changed that. A d= or an SPF domain that is a
subdomain or the parent of the From domain still waits: whether it aligns is
the record's adkim= or aspf=, which is what could not be fetched. The
Authentication-Results field says dmarc=pass with the comment "exact
header.d match, policy record not retrieved", or "exact smtp.mailfrom match,
policy record not retrieved", in place of the p= it could not read.

WHAT DNS DID NOT ANSWER IS STAMPED ON THE MESSAGE. Every check that went on
without its DNS answer - a timeout, SERVFAIL, no reachable server, a
blocklist that refused the query, never a definite answer that no record
exists - adds one X-DNS-Warning field to the message the server delivers:

  X-DNS-Warning: mx.example.net;
    check=dmarc; dns=_dmarc.bank.example;
    relaxed="DMARC pass on a DKIM d= equal to From:, without the policy record"

check= is spf, dkim or dmarc, or the CheckName of a spam check (fcrdns, dnsbl,
dnswl); dns= is the name that was asked for; relaxed= is what the message was
judged without. One field per check, so each stays short and a filter rule
matches one check by matching one field; the inbound checks come first, then
the spam checks in the order they were added. It is stamped whatever made the
message go through - the decision table, FailClosedOnTempError False,
EnforceDmarc False, or OnMailAuth turning a deferral into an accept - and on
top of X-Spam-Status and Authentication-Results.

WHAT CLAIMS TO COME FROM HERE IS RENAMED, AND THE MESSAGE SAYS SO. An
Authentication-Results, X-DNS-Warning or X-Stripped-Fields field that arrives
with a message NAMING THIS HOST is kept under another name, on every message
the server takes in WHATEVER IS SWITCHED ON - VerifyInbound or not, a
SpamFilter or not, any port. RFC 8601 sec.5: an MTA "MUST delete any
discovered instance of this header field that claims, by virtue of its
authentication service identifier, to have been added within its trust
boundary but that did not come directly from another trusted MTA", and
"MUST delete or otherwise obscure any instance of this header field bearing
an authentication service identifier indicating that the header field was
added within example.com prior to adding its own header fields". A field
names this host when its first token is
ServerName, read as RFC 8601 sec.2.2 reads an authserv-id:

  authres-payload = [CFWS] authserv-id
           [ CFWS authres-version ]
           ( no-result / 1*resinfo ) [CFWS] CRLF

  authserv-id = value

value being RFC 2045's "value := token / quoted-string". So white space,
folding and comments before it are skipped, a quoted string is unquoted, the
token ends at white space or a tspecial - a version or a comment after it is
not part of it - and the name is compared without regard to case or a
trailing dot. The fields this host writes carry ServerName whole, up to the
253 characters of a DNS name, folded after the colon when it would not fit on
the first line. "mx.example.net 1;", "(c) mx.example.net;" and a quoted
"MX.Example.Net." all name mx.example.net; "mx.example.net.org" and
"(mx.example.net) relay" do not. Every other field is left exactly as and
where it arrived: another host's results may be all a reader has, and an
X-DNS-Warning is a diagnostic a sender gains nothing by planting.

THE NEW NAME IS cSmtpForgedFieldPrefix, "X-Forged-", in front of the name
the field arrived with, and the field is otherwise byte for byte as it came,
folding and all, in its place:

  X-Forged-Authentication-Results: mx.example.net; dkim=pass
    header.d=bank.example
  X-Forged-X-DNS-Warning: mx.example.net; check=spf; dns=planted.example

It is kept as evidence: a message whose forged fields are removed is never
delivered without a visible sign that it was tampered with. Under that name it
is no longer an Authentication-Results field - which is what the passage above
requires - nor an X-DNS-Warning: no filter or client reads it as one, a rule
written against the name finds nothing, and one prefix for all three kinds is
one rule that finds them all. An incoming field already named X-Forged- is not
this host's to police and stays as it came. Below this host's own fields the
message is byte for byte as it came but for the nine octets of each new name -
and for the Subject, below.

THE ONE OPT-OUT is Authenticator.StripInboundResults := False, the
application's explicit word that an Authentication-Results in this host's
name may be genuine - written by a filter of its own in front of this server,
the "trusted MTA" of the passage above. It is kept as that, and is read
whether or not VerifyInbound is on. It keeps only such a field: an
X-DNS-Warning or X-Stripped-Fields naming this host is still renamed, and
any field of the next paragraph still goes.

AND SO IS AN Authentication-Results THIS SERVER CANNOT READ. One bearing a
version this server does not support is removed WHOEVER IT NAMES, also with
StripInboundResults off. RFC 8601 sec.5: "An MTA SHOULD remove any instance
of this header field bearing a version (express or implied) that it does not
support. However, an MTA MUST remove such a header field if the SMTP
connection [SMTP] relaying the message is not from a trusted internal MTA."
This server has no trusted internal MTA. The version is the number after the
authserv-id, "authres-version = 1*DIGIT [CFWS]" in sec.2.2, which goes on:
"this specification is version "1", and the absence of a version implies
this version of the specification". So this server supports 1, written with
or without leading zeros, and no version at all; "relay.example 2;" goes,
"relay.example 1;" and "relay.example;" stay. Such a field is NOT SCORED: it
is no claim in this host's name, and a host that writes a newer version is
not a spammer for it.

A message that had any adds one field, above all of this host's others:

  X-Stripped-Fields: mx.example.net;
    authentication-results=2; x-dns-warning=1;
    renamed="X-Forged-"; reason="claimed to come from this host";
    authentication-results=1;
    reason="version not supported"

naming this host, then one group per reason: each field name taken away for
it, as it was before any renaming, with how many, in that order, a name
nothing was taken away of left out, and the reason that closes the group;
the group of the fields naming this host says, in renamed=, the prefix they
now carry. The groups come in that order, a reason with nothing taken away
is left out, and a field is counted once - one naming this host is a forgery
whatever its version - so a message that had only forgeries carries the
first three lines alone. NOTHING OF THOSE FIELDS IS COPIED INTO THE NOTE:
they are the sender's text, written to be believed. The name follows
X-DNS-Warning, X- and then what it is about, and is kept: the fields were
stripped of their standing as this host's, of their name or altogether. An
incoming X-Stripped-Fields naming this host is a forgery of this note and
is renamed and counted like the others; one naming another host stays. And
a field naming this host scores and files: see section 5.2. The server takes
them away once, after DKIM has read the message as it arrived and before the
spam stage, so the score sees the count; a host with its own pipeline has
SmtpStripForgedFields, SmtpStrippedFieldsNote, SmtpAuthResultsVersion,
SmtpStrippedForged, SmtpPrefixSubject and the StampMessage and
SmtpStampDnsWarnings overloads that take the count.

THE RECIPIENT SEES IT. A message delivered here to a LOCAL mailbox that came
with a field naming this host, a forgery and not a field removed for its
version, is marked and filed:

- ITS SUBJECT GETS TsmSMTPServer.ForgedSubjectPrefix IN FRONT, once:
  cSmtpForgedSubjectPrefix, "[Suspect] ", by default. A Subject that already
  begins with it, in any case - a message that came back through here - is
  left. A folded Subject, or one of RFC 2047 encoded words, gets it before the
  first word and separated from it by a space, never inside an encoded word:
  "Subject: =?UTF-8?Q?...?=" becomes "Subject: [Suspect] =?UTF-8?Q?...?=". A
  Subject whose value begins on a continuation line gets "[Suspect]", the fold
  separating it, and a message with none gets "Subject: [Suspect]". A prefix of
  its own that does not end in a space is given one. Empty, or nothing
  printable, turns it off - in a form, where an empty string is not stored, a
  single space. CHANGING THE SUBJECT BREAKS A DKIM SIGNATURE THAT COVERS IT for
  anyone verifying after this server, which has already verified it on the
  message as it arrived; so does renaming a field a signature covers, as
  removing it did.
- IT IS FILED into TsmSMTPServer.JunkFolder where the mailbox has that folder
  (section 5.2), with a SpamFilter or without one. It is the only message the
  server files.

WHAT GOES ONWARD IS NOT MARKED. The copy relayed or submitted outward - a
recipient that is not local, RouteRecipient's one definition (section 3.5),
from a RelayNetworks peer or an authenticated client - has the fields
renamed and the note, but keeps its Subject and is filed nowhere; the server
logs that a forgery was on it. A transaction with both kinds of recipient
delivers the marked copy locally and spools the unmarked one.

OUTBOUND SIGNING IS A DECORATOR around the delivery agent, so signing happens
on a spool worker at delivery time rather than on the thread that is still
holding a client's 250; disabled, it passes the bytes through untouched.

5.1  PROVISIONING A DKIM KEY, AND THE DNS RECORD THAT GOES WITH IT

Signing is useless until the public half is published, and the two ends have to
agree exactly. This is the whole of what a deployment has to do.

THE KEY IS A COMPONENT. TsmSMTPServer.DkimKey is a TComponent reference - a
TstRSAKey for rsa-sha256, a TstEdDSAKey for ed25519-sha256 - so the key is
dropped on the form beside the server and wired in the Object Inspector, the
same arrangement TsmAcmeClient uses for its AccountKey. The property is typed
TComponent so the mail unit stays free of any particular key class; the
drop-down is narrowed at design time to components that could actually sign a
DKIM signature, which is a shorter list than "private keys" - ECDSA, DSS and
ML-DSA components are excluded, because DKIM has no algorithm for them.

The key MATERIAL is not streamed. The component holds it and loads it from
wherever the deployment keeps it, so nothing secret lands in a DFM.

Underneath, tDkimSigner.Key takes the private half as an interface, and a bare
interface works there too - an Ed25519 signer is three lines, exactly as the
unit's own self-test builds one:

  lEdPriv := MustGetDSIED.NewPrivateKey(lCurve as iDiscreteLogField);
  (lEdPriv as iEdDSAPrivateKey).Seed := lSeed;
  lSigner.Key := lEdPriv;

RSA KEYS BELOW 1024 BITS ARE REFUSED, by the signer as well as the verifier, and
rsa-sha1 is refused outright. 2048 bits is the ordinary choice; anything larger
runs into the 255-octet limit on a single DNS character-string and has to be
published as a multi-string TXT record.

THE DNS RECORD. The owner name is

  <selector>._domainkey.<domain>          record type TXT

where <domain> is the signer's d= and <selector> its s=. Those two values are
the only thing that decides where a verifier looks, so the record has to be at
that exact name - not at the domain apex, and not under a different label.

THE VALUE is a DKIM tag list. The two forms this library verifies are

  v=DKIM1; k=rsa; p=<base64 of the SubjectPublicKeyInfo>
  v=DKIM1; k=ed25519; p=<base64 of the BARE 32-octet public key>

and the difference between them is the thing most easily got wrong. For RSA,
p= is the DER SubjectPublicKeyInfo - the same structure a .pem "PUBLIC KEY"
block wraps, base64 of the whole structure and not of the modulus. For
Ed25519, RFC 8463 sec.3 says p= is the raw key itself: 32 octets, NOT wrapped
in a SubjectPublicKeyInfo. A verifier that is handed the wrong one of these
sees a key it cannot parse and fails the signature.

THE COMPONENT BUILDS BOTH FOR YOU, from the key it will actually sign with:

  TsmSMTPServer.DkimDnsName    -> 'brisbane._domainkey.example.com'
  TsmSMTPServer.DkimDnsRecord  -> 'v=DKIM1; k=ed25519; p=11qYAYKxCr...'

Generating the record from the assigned key rather than from a separately typed
copy is the point: the published record and the signature cannot then disagree,
which is the failure this step usually produces. DkimDnsRecord raises if the
configuration could not produce a usable record - an empty DkimDomain or
DkimSelector, no DkimKey, an RSA key under the bit floor, or rsa-sha1 - and each
message names the property at fault rather than leaving it to surface later as
an unparseable key in somebody else's resolver.

The same pair is available without a server component, for a tool that only
publishes keys: DkimRecordName(selector, domain) and DkimPublicKeyRecord(key,
algorithm) in StreamSec.Mail.Dkim. Both read only the PUBLIC half, so a
component holding just a public key still produces the record.

WHAT THE VERIFIER AT THE FAR END WILL INSIST ON, and therefore what to check
after publishing: exactly ONE usable record at that name - more than one is
ambiguous and is refused rather than guessed at - and a non-empty p=, because
an empty p= is the RFC's way of spelling REVOKED and is treated as a hard fail.
A key record whose h= does not permit sha256 is also refused.

ROTATION IS BY SELECTOR, which is why the selector exists. Publish the new
record under a new selector, wait for the old one's TTL to pass out of caches,
then switch the signer to the new selector and leave the old record in place
long enough for mail already in flight to verify. Removing the old record too
early fails signatures on messages that are still in somebody's queue.

WHAT THIS AREA DOES NOT DO. No ARC (RFC 8617) - which is why refusing a broken
signature is the default rather than a forwarding-tolerant heuristic. No DMARC
reporting: rua=, ruf=, fo=, rf= and ri= are parsed past and no aggregate or
failure report is ever produced. pct< 100 is deliberately NOT sampled - below
100 the policy is not enforced at all and the verdict says so, because applying
a policy to a random subset makes delivery unpredictable without making it
safer. There is no Public Suffix List: relaxed alignment uses a small
compiled-in table of common multi-label suffixes plus a hook for a real PSL.
SPF records are read from TXT only, with no query for the historic type 99 RR.

5.2  SPAM SCORING

TsmSMTPServer.SpamFilter is a public, unpublished reference to a tSpamFilter
that the application builds and owns; left nil, nothing changes. Checks return
points, the TagScore and FileScore thresholds have no default, and no score can
refuse a message: only a check's own hard verdict defers or refuses it. An
authenticated session is not filtered unless FilterAuthenticated is set. An
enabled filter stamps every message it passes with X-Spam-Status. The server
acts on a deferral or a refusal; A VERDICT OF svFile IS THE STAMP ALONE -
FileScore reached, or a check asking for it, gives "X-Spam-Status: Yes" and the
message goes to the INBOX, as at TagScore. THE SERVER FILES ONLY A FORGERY,
because a field forged in this host's name is evidence of tampering the
recipient must be able to see, while a score is a measurement and only marks
the message: a message that came with such a field (section 5) goes into
TsmSMTPServer.JunkFolder - cSmtpJunkFolder, "Junk", the name the IMAP server's
default special-use mapping gives \Junk first - of each local mailbox THAT HAS
THAT FOLDER, with a SpamFilter or without one. That is the per-account
decision, because a POP3 user cannot see a folder: a mailbox read over IMAP has
a Junk folder, made by the client, the user or the application
(TsmMailStore.CreateFolder), and one collected over POP3 has none and gets the
message in its INBOX, marked. The server never creates the folder. The built-in
store files (sldMaildir, Store; iSmtpMailboxFiling in
StreamSec.Mail.SMTPDelivery); OnLocalDeliver gets every copy as before, its
stamp saying what it is. An empty JunkFolder files nothing.

ONE SCORE PER MESSAGE, AND THE THRESHOLDS ON IT. The filter runs at each stage
- connect, EHLO, MAIL, each RCPT, end of data - and the points add up: the
connection's own (connect and the latest EHLO) and this transaction's. A
message's score is that sum, and TagScore and FileScore are applied to the
sum - 15 at connect, 10 at RCPT and 15 at the end of data tag at a TagScore
of 40, though no stage reached it - together with the hardest verdict a check
asked for. The total starts again at every MAIL FROM, after every message and
at every EHLO, so a second message on one connection carries none of the
first one's points, nor of a transaction abandoned with RSET. What a stage's
own check asks for - defer, refuse - still answers that stage on the wire:
554 at connect, 4xx or 5xx at EHLO, MAIL or RCPT, at the end of data; a
refused recipient leaves the others. tSpamFilter.Conclude gives a host with
its own pipeline the same verdict from a Merge of its stages.

THE STAMP SAYS NO OR YES. X-Spam-Status goes on a message that was delivered
or spooled, so its verdict is "Yes" when the summed score reached TagScore or
FileScore, or a check asked to tag or file, and "No" otherwise. A deferral or
refusal a check asked for at RCPT for one recipient, or one the application
overrode in OnCheckConnection, OnCheckHelo, OnCheckSender or OnCheckRelay, is
not the stamp's verdict: the server logs it through OnLog where it is
answered - "<bob@example.net> from 192.0.2.1 refused by the spam filter at
RCPT: 550 ..." - and logs an override as "accepted by the application over
the spam filter's deferral at RCPT". The score and the list of findings are
stamped as before, a check that asked for more among them.
tSpamFilter.StampVerdict is that verdict; Conclude's is unchanged and still
says svDefer or svRefuse.

StreamSec.Mail.SpamChecks supplies HELO, reverse DNS, DNSBL, rate and greylist
checks. Every weight starts at zero and a check whose weights are all zero does
nothing; a check whose DNS question goes unanswered abstains, scores nothing
and reports the name in tSpamFinding.DnsName, which the server stamps as an
X-DNS-Warning field (section 5) - a resolver with no server configured
included, which reverse DNS used to score as a missing PTR. None of them reads
the message. iSpamCheck is the seam for one that does.

ONE WEIGHT HAS A DEFAULT: a message on which the server renamed a field
claiming to come from this host (section 5) scores
tSpamFilter.ForgedStampPoints, cSpamForgedStampPoints = 40 unless set, once
however many fields there were, as the finding forged-stamp in X-Spam-Status.
The filter scores it itself at sstData, from tSpamContext.ForgedStamps, so it
needs no check installed and counts in the message's score. 40: on a scale
whose file threshold is 80, it is one strong signal - alone it reaches a tag
threshold of 40. THE POINTS DO NOT FILE IT: the forgery itself is what files
the message where the mailbox has a Junk folder, whatever the points and the
thresholds, and the finding also asks for svFile, which the stamp shows as
"X-Spam-Status: Yes"; the points still count in X-Spam-Score. Nothing
legitimate plants a field in another host's name, but a message this host
stamped can come back, forwarded out and back in, with a genuine field of ours,
and it is treated the same; 0 keeps the finding, worth nothing, and the message
is still filed. A deployment whose thresholds use another scale sets the points
on that scale.


--------------------------------------------------------------------------------
6. THE RETRIEVAL SERVERS
--------------------------------------------------------------------------------

6.1  WHAT THEY SHARE

One base carries the store, the accounts, the TLS engine, the server name and
the events; one authentication gate serves both - TsmMailUsers first, then
OnAuthenticate, and with neither assigned nothing authenticates. Every log line
is scrubbed of control octets before it leaves, because an operator banner or a
localized OS error can carry octets that truncate a line.

Both refuse TLS 1.3 early data outright on the implicit-TLS port rather than
discarding it: under an accepting policy the TLS layer has already told the
client the octets were taken, so silently dropping them would be a lie.

Both listeners refuse to start rather than downgrade - a port whose TLS mode is
not disabled and which has no engine raises - and a failed bind unwinds so a
half-started listener is never left behind.

WHEN A COMMAND FAILS. A policy or store call that raises costs the client its
command, not its connection, and the client sees fixed text; the exception goes
to OnLog. IMAP discards the unfinished response, keeps the complete untagged
responses before it, and answers tagged NO "mailbox operation failed". A failed
IDLE or AUTHENTICATE leaves no IDLE or SASL state behind. A reply already
flushed (STARTTLS) cannot be replaced, so that session closes. POP3 replaces
the buffered reply with "-ERR mailbox operation failed", which keeps multi-line
framing intact; if the failure changed the session's state it answers "-ERR
mailbox operation failed, closing connection" and closes. With the store
unavailable the answer is "* BYE mailbox service is shutting down" or "-ERR
mailbox service is shutting down" and the close. The process-state classes are
section 7.3. Section 3.1 has the SMTP rules.

6.2  POP3

The command set is all of RFC 1939 this server answers: QUIT and CAPA in both
states, STLS, USER/PASS/AUTH in authorization, and STAT, LIST, UIDL, RETR, TOP,
DELE, RSET and NOOP in transaction. Commands are checked as printable ASCII on
the OCTETS before any decode.

DOT-STUFFING IS TREATED AS ONE GUARANTEE WITH THE TERMINATOR. A leading dot is
doubled after CRLF, after a bare LF and after a bare CR - deliberately
conservative, against lax clients - and a message not ending in CRLF is given
one before the terminating dot.

THE MAILDROP IS EXCLUSIVE, and that is RFC 1939's model rather than a
limitation: the lock is taken at successful authentication and released on
every exit path, including the idle timeout, the session budget, a dropped
socket and an exception. "Unable to open" is answered separately from a bad
credential, because they are different facts and conflating them tells a
guesser which one they got right. A refused maildrop charges the ERROR budget
but not the authentication budget - the password WAS right, and nothing else
would bound a peer that repeatedly signs in correctly against its own held lock
and buys a full Argon2id derivation each time.

THE LOCK IS AN OPEN HANDLE on ss-pop3.lock in the mailbox: a share-exclusive
open on Windows, a record lock on POSIX. The operating system releases it when
the holder dies, so nothing ages or breaks a lock, and the file stays on disk.
A second maildrop open in the SAME process is refused as well, on POSIX as on
Windows, by a process registry checked before any open - on POSIX closing any
descriptor of that file would drop the process's lock. The refusal is "the
mailbox is locked by another session". RENAME INBOX is refused while the
maildrop is held.

DELE ONLY MARKS. The marks commit exactly once, in UPDATE, which is reached
only by QUIT; RSET clears them; and the per-session mark array is not seeded
from any stored flag. A marked message goes whatever its \Deleted flag says by
then.

6.3  IMAP

IMAP4rev1 only. The command set covers CAPABILITY, NOOP, LOGOUT, STARTTLS,
AUTHENTICATE, LOGIN, SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE,
UNSUBSCRIBE, LIST, LSUB, STATUS, APPEND, CHECK, CLOSE, EXPUNGE, SEARCH, FETCH,
STORE, COPY, MOVE, UID, IDLE, GETQUOTA, GETQUOTAROOT and SETQUOTA.

LITERALS ARE THE WHOLE FRAMING STORY. There are two input modes and the
countdown never looks for a delimiter - a literal is a byte count and the
octets inside it are data, whatever they contain. Literal values are collected
and consumed positionally by the command handlers. The non-synchronising form
{n+} is REFUSED BY NAME rather than read as a plain count: accepting the syntax
without the semantics means the peer's next octets arrive unannounced.

NOTHING IS RESERVED WHEN A COUNT ARRIVES. The buffer grows with the octets
received, never beyond the count announced, and a regrown buffer wipes the old
block, which may hold a password. Limits.LiteralBytes bounds the literal octets
of one command IN ALL (default cImapMaxLiteral, 32 MiB; 0 = no limit), so it is
also the largest APPEND. Before authentication the bound is
cImapUnauthLiteralBytes, 4096, whatever LiteralBytes says, and any command
carries at most cImapMaxLiteralsPerCommand, 16, also with LiteralBytes 0;
zero-length literals count. Past either bound the answer is tagged, "<tag> BAD
literal too large" or "<tag> BAD too many literals", and charges the error
budget.

COMMAND LINES ARE UTF-8, STRICTLY. A line is decoded once its CRLF has ended
it, and a line that is not valid UTF-8 is "<tag> BAD the command line is not
valid UTF-8", charged to the error budget and never repaired. LOGIN takes its
user name and password as quoted UTF-8 (RFC 9051 sec.9, QUOTED-CHAR), the
password being the octets sent. Each LOGIN operand is the literal sent for it,
an empty one included, an atom or a quoted string, as RFC 3501's astring is;
an atom holding a control character, a parenthesis, "{", "%", "*", a quote
or a backslash is BAD, as is a parenthesised list or a literal marker joined
to an atom, and a TAB before a quote makes an atom. A literal's count may have
leading zeros. Anything after the password is BAD, before a literal it
announces is asked for. An empty user name is NO [AUTHENTICATIONFAILED]. A
character outside US-ASCII anywhere else -
in an atom user name or password, after the password, or in any other
command - is BAD, charged to the error budget, the command not run and a
literal it announces not asked for. No such character is read as a stand-in:
a mailbox name must be modified UTF-7 and one in raw 8-bit octets is BAD -
sent as a literal too, where the BAD comes after the literal is read - and
a STORE, UID STORE or APPEND flag list or a SEARCH KEYWORD cannot carry one.
A tag outside US-ASCII is not echoed; the answer is "* BAD", the untagged form
RFC 3501 sec.7.1.3 gives for "a protocol-level error for which the associated
command can not be determined". The AUTHENTICATE PLAIN and LOGIN user name is
strict UTF-8 by the same rule; the password is the octets sent. A LOGIN or
AUTHENTICATE user name holding a control or bidirectional character, and an
AUTHENTICATE user name that is not UTF-8, is refused with the answer every
authentication failure gets, NO [AUTHENTICATIONFAILED], without asking the
application; in AUTHENTICATE it is NO, not BAD, because the name came inside a
valid base64 SASL response.

ONE CAPABILITY LIST. The greeting's CAPABILITY response code, the CAPABILITY
command and the OK of LOGIN and AUTHENTICATE give the same list: AUTH=PLAIN and
AUTH=LOGIN on a secure channel before authentication (as AuthMechanisms says),
STARTTLS and LOGINDISABLED on a cleartext one, and no AUTH= once authenticated.
FETCH implements UID, FLAGS, INTERNALDATE, RFC822.SIZE, RFC822, RFC822.HEADER,
RFC822.TEXT, ENVELOPE, BODY, BODYSTRUCTURE, the ALL/FAST/FULL macros, and
BODY[<section>]<<partial>> and BODY.PEEK[...] by the grammar of RFC 3501
sec.6.4.5: part numbers, HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, TEXT and
MIME, with <origin.count>. An item it cannot parse is BAD before any untagged
line is sent. A part the message does not have is NIL and the command completes
OK. RFC822.TEXT is the body alone, and RFC822.HEADER the same octets as
BODY.PEEK[HEADER], including for a message stored with bare LF. RFC822.HEADER
and .PEEK leave \Seen alone; RFC822, RFC822.TEXT and BODY[...] set it on a
read-write selection.

ONE MIME BUDGET PER WALK. A section, BODY, BODYSTRUCTURE and ENVELOPE each
parse under one nesting depth (cMailMaxNestingDepth, 100) and one part total
(cMailMaxPartCount, 10000), shared across encapsulated message/rfc822 parts and
their siblings, and each level's storage is released before the next is parsed.
Over budget a section answers NIL, as does one naming more than 101 part
numbers. A structure item answers tagged NO "mailbox operation failed", with no
partial FETCH line and the complete responses before it kept.
Forward-as-attachment costs two levels per forward.

MESSAGE SETS. A sequence number above the message count, '*' in an empty
mailbox and a number with a leading zero are BAD. A UID that does not exist is
ignored and the command completes OK. Numbers run to 4294967295, and a range
may be written in either order.

SEARCH implements the flag keys, RECENT/OLD/NEW, LARGER/SMALLER, the date keys,
HEADER, the address and text keys, UID and a bare sequence set, combined by OR,
NOT and parenthesised lists. FROM, TO, CC, BCC and SUBJECT match the string,
without regard to case, in the unfolded value of that header field only, and
HEADER in the field it names (RFC 3501 sec.6.4.4); an empty string matches every
message that has the field. BODY is the body alone, TEXT header and body. The
command is parsed whole before a message is read: a malformed tree is BAD, an
unknown key anywhere in it NO, and nesting deeper than cImapMaxSearchDepth
(100) NO [LIMIT]. A string sent as a literal is refused with NO; send it quoted.
A sequence-set or UID key is held as the ranges it was written as, at most one
per element of the set, and is never expanded into a list of the messages it
selects: a message is tested by its number, or its UID, against those ranges.
So the memory a SEARCH needs, both what it holds and what it allocates on the
way, follows the length of its command line, not the size of the mailbox.

SHARED ACCESS IS THE POINT OF THE PROTOCOL. SELECT opens read-write and EXAMINE
read-only, never exclusive, so a second client selecting the same mailbox
succeeds; APPEND, COPY and STATUS each use their own transient view so the
session's snapshot is not disturbed. Untagged EXISTS and RECENT are re-derived
and emitted only when they have changed, and queued EXPUNGEs drain at a point
where the client is expecting them. A rescan runs at NOOP, CHECK, IDLE, DONE
and RENAME INBOX, before the removal in EXPUNGE and UID EXPUNGE, and in the idle
round below, never inside FETCH, STORE or SEARCH; what another session did
reaches the client then, as EXPUNGE, EXISTS and RECENT. CLOSE also rescans
before its removal, and reports nothing.

SELECT and EXAMINE close any prior selection first, and a failure leaves none
selected (RFC 3501 sec.6.3.1).

KEYWORDS. STORE, APPEND, COPY and MOVE take keywords as well as the system
flags: $Junk and $NotJunk, which a client sets when its user marks a message as
junk or not junk (RFC 5788 registry), and any other atom of 1 to
cMailMaxKeywordLength (64) characters. They are stored in the Maildir (7.1), so
another session and a restart see them. SELECT lists the folder's keywords in
FLAGS and in PERMANENTFLAGS, with \* while the folder can take a new one; a
STORE that defines one answers an untagged FLAGS and PERMANENTFLAGS. A keyword
matches without regard to case and keeps the spelling it was first stored
under. A folder holds at most cMailMaxKeywords (26) keywords: past that a STORE
needing a new one is NO [LIMIT] and stores nothing, and an APPEND, COPY or MOVE
needing one is NO. STORE FLAGS replaces the keywords with the ones it names.
SEARCH KEYWORD and UNKEYWORD test them.

QUOTA (RFC 9208, advertised as QUOTA and QUOTA=RES-STORAGE). An account has
one quota root, "", over INBOX and every folder (7.1). GETQUOTAROOT of a
folder that exists names it, and GETQUOTA "" gives its STORAGE in units of
1024 octets, the usage rounded up and the limit down; with no limit the
resource list is empty. STATUS takes DELETED-STORAGE, the messages with
\Deleted set, in the same unit. An APPEND or COPY whose messages do not fit
the room left is NO [OVERQUOTA] and stores nothing. MOVE is not refused: it
adds nothing to the one root, so a user at the limit can still move mail to
Trash. SETQUOTA is NO and QUOTASET is not advertised; the limits are the
store's.

SPECIAL-USE (RFC 6154, advertised as SPECIAL-USE and CREATE-SPECIAL-USE).
LIST gives a folder the attributes \Sent, \Drafts, \Trash, \Junk or \Archive
by TsmIMAPServer.SpecialUse, a list of '<attribute>=<folder>' lines that names
folders by their full IMAP name and compares them as the store compares folder
names. The default, cImapDefaultSpecialUse, maps Sent, Sent Items and Sent
Messages to \Sent; Drafts to \Drafts; Trash, Deleted Items and Deleted
Messages to \Trash; Junk, Spam, Junk E-mail and Junk Email to \Junk; and
Archive to \Archive. A child such as Archive.2026 is not mapped by its parent's
line. A line with another attribute or no folder maps nothing, so '\Sent='
alone is a list that maps nothing. LSUB reports no attributes.
CREATE <name> (USE (<attributes>)) creates the folder only when the mapping
already gives that name every use asked for; otherwise it is NO [USEATTR] and
nothing is created (RFC 6154 sec.3). \All and \Flagged name virtual mailboxes
a Maildir does not have, and are always NO [USEATTR]. Any other parameter after
the name is BAD.

MOVE AND UID MOVE (RFC 6851, advertised as MOVE). Each message moves by ONE
RENAME of its file into the target's cur/, under a fresh base name and with its
flags, so at every instant, a crash included, it is in exactly one of the two
mailboxes. Its UID in the target is reserved in the target's index before the
first rename; one that is not used is never handed out. The \Deleted flag is
never set on the way, and messages the set does not name stay whatever flags
they carry. The answer is an untagged OK [COPYUID <uidvalidity> <source UIDs>
<target UIDs>], then an untagged EXPUNGE for each moved message, highest number
first, then the tagged OK (RFC 6851 sec.3.3 and 4.3). A message that could not
move stays where it was; the command then answers NO, after the COPYUID and the
EXPUNGEs of those that did. A store fault part way through, such as a keyword
table or index of the target that cannot be written, stops the move at that
message and is answered the same way, with the fault in the server log. A
missing target is NO [TRYCREATE], an EXAMINE selection NO, and in both nothing
moves. A set naming no message is OK. As with COPY, the moved message is not
\Recent in the target, and its INTERNALDATE, kept for the session that moved
it, is the time of the move when the mailbox is next opened.

EXPUNGE, CLOSE and UID EXPUNGE rescan first and take \Deleted from the stored
flags, so a message another session marked is removed. One another session
un-deleted in between is kept and the command answers OK: NO means a message is
still there and still \Deleted. STORE reports only flags that were stored,
along with any flags it finds another session set; a write that fails is NO
"store error: can't store that data".

A MAILBOX THAT GOES AWAY. When another connection renames, deletes or replaces
the selected mailbox the session ends with "* BYE selected mailbox was renamed
or deleted, have to disconnect" rather than a false success or a NIL. Another
mailbox going away is only a NO, and the session stays: "the mailbox was
renamed or deleted" for STATUS and APPEND, "the destination mailbox was renamed
or deleted" for COPY, and "mailbox operation failed" for MOVE. A failed open
says "no such mailbox" when it is missing and otherwise "cannot open that
mailbox", for SELECT, EXAMINE, STATUS, APPEND, COPY and MOVE; OS text and paths
go to OnLog. APPEND, COPY and MOVE add [TRYCREATE] only for a destination that
does not exist; APPEND and COPY take back what they published when they fail.

RENAME. An ordinary RENAME takes the '.Name.*' children along and is rolled
back if a move fails. It keeps UIDVALIDITY and UIDs unless the target name's
history is unknown, or the same value belongs to another or an unproven
lifetime; then that mailbox alone gets a fresh value, its UIDs and contents
kept. RENAME INBOX moves INBOX's messages, with their flags, to a new mailbox
under a fresh UIDVALIDITY; INBOX keeps its UIDVALIDITY and UIDNEXT and its
children stay. An existing target is NO. RENAME "" x is NO "RENAME needs a
nonempty source mailbox", never INBOX.

IDLE parks the connection in a state whose grammar accepts exactly one input:
DONE. The mailbox is rescanned on entry and at DONE.

IDLE PUSHES, ON BOTH PORTS. A round runs about once a second
(cMailConnectionReadRoundMs, 1000 ms): on the STARTTLS port on the connection
thread, on the implicit-TLS port on a reactor thread, by the transport's work
deadline, set only while the session is in IDLE and with no thread per session.
Either rescans when the selected mailbox's generation has moved or
cImapIdleRescanSeconds (30 s) have passed. A delivery, APPEND, EXPUNGE or COPY
through the same store instance is pushed at the next round; through another
store instance or process, within those 30 s.
Delivery to other mailboxes causes no rescan, except that a mailbox sharing one
of the cMailGenerationSlots (256) hash slots costs a needless one. Pushes are
EXISTS, EXPUNGE and RECENT. A flag-only change is never pushed, from anywhere;
the client reads it when it next fetches FLAGS. A failed round follows the
rules of section 6.1, and a BYE from a round is followed by the close. What a
round sends does not count as the client's traffic: a client that reads its
pushes and says nothing still ends at the idle limit, and on the implicit-TLS
port OnConnectionNudge is asked first, as for any idle limit.

6.4  WHAT THE RETRIEVAL SERVERS DO NOT DO

APOP IS NOT MERELY UNIMPLEMENTED, IT IS IMPOSSIBLE against this account store,
and the same is true of CRAM-MD5 and DIGEST-MD5: each needs the server to hold
something the password can be recomputed from, and what is stored is an Argon2id
tag. That is a deliberate trade - the store is safe to steal, and the price is
that challenge-response mechanisms cannot exist.

IMAP declines rather than half-answers: CONDSTORE/QRESYNC, BINARY, COMPRESS,
MULTIAPPEND, LITERAL+, SORT and THREAD are not advertised and not accepted.
SEARCH takes no literal strings and no SENT* keys, and matches encoded words as
they are stored. LIST reports no attribute but the
special-use ones, LSUB none, and LIST-EXTENDED (RFC 5258), with its RETURN
(SPECIAL-USE), is not offered.

IDLE is accepted only in the selected state, where RFC 2177 also permits it in
the authenticated state. A reactor backend that runs no application work
(tAsyncReactor.SupportsApplicationWork False; the shipped ones all do) has no
round, and its sessions hear of changes at DONE or their next command.

POP3 advertises RESP-CODES but never emits an extended response code; there is
no [IN-USE] or [AUTH]. LOGIN-DELAY, EXPIRE and IMPLEMENTATION are not offered,
and the obsolete LAST is absent. POP3 has no quotas, and neither protocol has
ACLs.


--------------------------------------------------------------------------------
7. THE STORES
--------------------------------------------------------------------------------

7.1  THE MAILBOX TREE  (TsmMailStore)

One directory per mailbox under the root, with Maildir++ tmp/new/cur inside
each. No RFC defines maildir; the layout is D. J. Bernstein's convention plus
the Maildir++ extension, and folder directories are SIBLINGS carrying the
parent's name with a leading dot.

THE COMMIT RULE IS ONE RENAME, applied identically everywhere: write into tmp/,
flush if FlushToDisk is on (it is by default), then a single rename into place.
A crash therefore leaves a stray file in tmp/ and never a half-written message
where a reader can see it.

Names are '<unix seconds>.<pid>_<serial>.<host>' with an interlocked serial, so
two threads in one process cannot collide. ARRIVAL TIME COMES FROM THE NAME,
not from the filesystem, so a copy or a restore does not reorder a mailbox.
Flags live in the info suffix, whose separator is ';' on Windows and ':'
elsewhere - because ':' in a Windows filename opens an alternate data stream,
which is a silent way to lose a message.

KEYWORDS are lower-case letters of the same suffix, 'a' to 'z', as Maildir++
spells them, named by the folder's keyword table, ss-keywords, beside its
ss-uidlist: one '<n> <keyword>' line per letter, n = 0 for 'a', the format of
Dovecot's dovecot-keywords. The table only grows; a keyword is added under the
index lock before any message carries its letter, and the file is replaced by a
rename. A letter the table does not name is not reported.
COPY, MOVE and RENAME INBOX carry keywords by name into the target's table.

QUOTA is the storage limit of every mailbox in octets, 0 (the default) for
none; OnMailboxQuota changes it for one mailbox, named by its directory, so an
alias the SMTP server resolves to a mailbox counts against that mailbox.
tMaildir.MailboxQuota answers a mailbox's usage and limit, the usage being the
octets of the files in new/ and cur/ of INBOX and of every folder. IT IS
COUNTED ONCE AND THEN KEPT, not walked per command: a delivery, APPEND and
COPY add to it, EXPUNGE takes from it, and DELETE of a folder or the rollback
of a refused COPY has it counted again. It lives in memory only, per store
root and process, so a crash leaves nothing on disk that can disagree with the
files; after a restart each mailbox is counted when first asked about. Files
another program adds or removes are seen at the next count, at most
cMailQuotaRecountSeconds (300) after the last, or at once after RecountUsage.
A delivery or removal while a mailbox is being counted can be counted twice or
not at all until the next count. The store measures and answers; the SMTP and
IMAP servers refuse (3.5, 6.3). tMaildir.Deliver itself refuses nothing.

ONE ALLOWLIST guards every name that becomes a new path: letters, digits, dot,
underscore and hyphen, no leading or trailing dot, at most cMailMaxSegment (64)
characters a segment, and the twenty-two reserved Windows device names, with or
without an extension (aux.team is refused). A mapped folder, '.A.B', is at most
255 characters. AutoCreate - off by default - is the only mode in which
something a peer chose becomes a directory name, and even then only through
that allowlist.

FOLDER NAMES ARE STORED AS IMAP SPELLS THEM. A folder segment may also be the
modified UTF-7 of RFC 3501 sec.5.1.3 (MailSafeFolderSegment): direct letters,
digits, underscore, hyphen, an interior space and '&-', and '&' runs of
modified BASE64. 'Sent Items' is the directory '.Sent Items', and a folder a
client names '&AMQ-rende' is the directory '.&AMQ-rende', as Dovecot and Courier
name theirs. The name must be the one canonical spelling of what it decodes to
(no padding bits, no null shift, no run holding printable US-ASCII, so an
encoded dot, slash or backslash is refused), and the decoded text may hold no
control character, lone surrogate, U+FFFE, U+FFFF or bidirectional control.
Account directories and local parts keep the first allowlist.
MailEncodeFolderName and MailDecodeFolderName convert between a name and its
text. Modified UTF-7 stretches a non-ASCII character to about three, so the
64-character bound admits roughly 20 of them in one segment.

SPACES AROUND A FOLDER NAME AND AROUND EACH OF ITS SEGMENTS ARE TRIMMED, as
more likely a keyboard error than a chosen name: CREATE " Work . Sent " makes
'Work.Sent', and SELECT "Work.Sent " opens it. Interior spaces are kept. The
IMAP server trims the mailbox names of every command (not the patterns of
LIST and LSUB), and the store trims every name it is given
(MailTrimFolderName, used by MailFolderToDir and so by CreateFolder,
OpenFolder, RenameFolder and DeleteFolder, and by the subscription list), so a
library caller gets the answer a client does. Only the space U+0020 is
trimmed: a tab or another control is refused as before. A segment left empty
is refused, as in 'Sent..2026'. A name of spaces alone is the empty name to
the IMAP server, and the store refuses it rather than take it for INBOX. A
trimmed spelling is the name it trims to: CREATE "Work " where 'Work' exists
answers as CREATE "Work" does, and RENAME "Work " "Work" is a rename onto
itself and refused.

CREATE OF A MAILBOX THAT EXISTS IS NO [ALREADYEXISTS] (RFC 3501 sec.6.3.3,
RFC 5530 sec.3): INBOX in any case, a name that compares equal to an existing
one, a trimmed spelling, a name with a trailing delimiter and a CREATE with a
USE list alike. The existing mailbox is left as it was. The store's
CreateNewFolder decides it under the folder-name lock, in the step that
creates, so of two sessions - or two store objects over one root - creating
one name at once exactly one gets OK. CreateFolder keeps its meaning for a
library caller: True when the folder exists afterwards. A folder is made only
when its tmp, new and cur are all directories afterwards. Where something
else stands in the place of one of them, CreateNewFolder and CreateFolder
answer False, CREATE answers NO "cannot create that mailbox", and the CREATE
that follows once it is gone completes the folder. A child does not
create its parent: Maildir++ keeps 'A.B' as a directory of its own, so after
CREATE "A.B" a CREATE "A" answers OK.

AN EMPTY NAME NAMES NO MAILBOX. SELECT, EXAMINE, STATUS, APPEND, CREATE,
DELETE, RENAME (either name), COPY, UID COPY, MOVE, UID MOVE, SUBSCRIBE,
UNSUBSCRIBE and GETQUOTAROOT answer a mailbox name that is empty, or empty
once trimmed, with NO "a mailbox name cannot be empty" and do nothing else;
CREATE "." is that name too, the trailing delimiter dropped. RENAME "" x keeps
its own text, below. A refused SELECT or EXAMINE still deselects, as every
failed one does. The NO carries no response code: RFC 3501 has none for it,
and RFC 5530's NONEXISTENT is for deleting what does not exist. LIST and LSUB
are not affected: an empty reference or pattern is legal there, and LIST ""
"" answers the delimiter and the root (RFC 3501 sec.6.3.8). The store's
functions keep '' as INBOX for a library caller.

NAMES FOUND ON DISK ARE COMPARED UNDER A SEPARATE RULE, so a directory another
program made ('.Aux', '.Con.Sub', a Dovecot-style name) does not break the
account's other folder operations, though a client still cannot CREATE or open
it. A comparable name is at most 254 units (UTF-16 on Windows, UTF-8 octets on
Linux and Android, Unicode characters on Darwin) and holds no NUL or '/'; on
Windows also no control character, none of < > : " \ | ? *, and no trailing dot
or space. An invalid pair raises eMailStoreError before any handler is asked.

TsmMailStore.OnCompareFolderName decides what is the same folder. aSame arrives
holding the default answer, which ignores ASCII case, on POSIX too, with no
Unicode folding - except inside a modified UTF-7 run, where case is part of the
BASE64: '&AOQ-' and '&AoQ-' are two folders. On Windows, where they would be
one directory, CREATE of the second is refused. INBOX is always matched
without regard to ASCII case and cannot alias another name. The handler must
define a consistent equivalence, or behaviour is undefined; an exception from
it cancels the operation and reaches the caller's log. Two directories that
compare equal make every operation on that name fail, with "ambiguous mailbox
folder name" in the log, until they are merged or a handler tells them apart.

DELETE removes a directory link itself, never what it points to.

THE INDEX is one file per folder, ss-uidlist, recording UIDVALIDITY, UIDNEXT
and a UID per message. A rescan lists new/ and cur/, and looks once more by
base name for any message the view or the index knows and the listing did not
show, because a flag rename can carry a file past a running enumeration. New
UIDs are assigned in the order messages arrived, the view is ordered by UID,
and the index is saved BEFORE a message leaves new/, so a failed save spends no
\Recent and publishes no unrecorded UID. A row both looks missed stays as a
tombstone, and is pruned only when the next rescan of that mailbox, by any view
of this store, misses it again; one missed scan does not cost a message its
UID. A message never shown to this session and numbered below what it has shown
stays out of the view until a new SELECT. A view holding an older UIDVALIDITY
fails before it touches a file.

A MISSING OR CORRUPT INDEX is treated as LOST rather than partially trusted,
because recovering half an index is how two messages come to share a UID. A
fresh open mints a new UIDVALIDITY; a session that already has the mailbox
selected gets a failure rather than a renumbering.

UIDVALIDITY IS A COUNTER. A new value is the greater of the current Unix second
and the last value issued plus one, written to .ss-uidvalidity-counter at the
store root before any index can use it; .ss-uidnames-history there records what
each mailbox name has been. Both are flushed, and on POSIX so is their
directory. A value in an existing index may be an older one taken from the
clock alone, which is why it is trusted only with proof: the duplicate check
reads the indexes of ONE ACCOUNT, INBOX and its folders, one directory level,
and the first mint in each process and any counter recovery read every
ss-uidlist under the root. Keep both files with the store in every backup. A
restore of the counter alone needs every process using the store stopped and
restarted.

READ-ONLY OPENS (EXAMINE, STATUS) change no message: no flag, no expunge,
nothing leaves new/, so \Recent is not spent. The UID index is still written,
because a UID that is not recorded is not stable. A read-only open creates
tmp/, new/ and cur/ only for an INBOX with neither new/ nor cur/, as first
delivery would, and an INBOX with exactly one of them is not repaired: the open
answers NO. A read-write or POP3 open of INBOX creates them whenever missing.

LOCKING. One recursive operation lock per process guards mailbox lists, index
work and flag renames, whichever store asks, so a handler that consults another
store cannot invert a lock order. Each canonical root has a commit gate, held
for one file-system step, such as a rename, an unlink, a directory create, a
metadata write or the write of a message into tmp/. An SMTP spool with
sldMaildir local delivery holds it for one whole queue write, flushes included.
Two files at the store root exclude other processes: .ss-index.lock (rescan,
APPEND, EXPUNGE, and CREATE, DELETE and RENAME once they hold .ss-rename.lock),
where contention fails at once with "the mailbox index is busy" and the client
may retry, and .ss-rename.lock (RENAME, CREATE, DELETE and their cleanup), which
waits. ss-pop3.lock is section 6.2.

READS TAKE NO LOCK and STORE only the operation lock and the commit gate, never
.ss-index.lock, so neither fails while another process scans. A read checks the
mailbox's identity before and after, and retries up to cMailStoreFlagAttempts
(3) when a flag rename moved the file; past that it raises "the message keeps
moving". On Windows a message is opened sharing read, write and delete, so a
FETCH or RETR cannot make another session's STORE or EXPUNGE fail; EXPUNGE
renames a file to <name>.tmp, which no lookup resolves, before deleting it, and
a failed delete renames it back.

THE DELIVERY PATH NEVER TAKES A MAILBOX LOCK - it reads no index, takes no
index, rename or maildrop lock and waits for no lock held for a client session,
which is what lets SMTP deliver into a mailbox an IMAP client has open. What it
does take is the store's publication lock, which it shares only with APPEND,
and the commit gate.

EXPUNGE RETURNS REMOVED MESSAGE NUMBERS DESCENDING, so a client can apply them
one at a time without renumbering underneath itself.

THE SHARED COMPONENT is the reason this is one object rather than three: the
mailbox list is swapped atomically after being built and validated outside the
lock, because clear-then-re-add lets a reader see an empty list.

7.2  THE ACCOUNTS  (TsmMailUsers)

What is stored is a per-account random salt and an Argon2id tag, with THAT
ACCOUNT'S cost parameters recorded beside it. Verification runs with the
account's own parameters, so raising the component's cost does not lock anyone
out; after a successful sign-in whose stored cost is weaker, the verifier is
re-derived at the current cost. A fresh salt is minted on every SetPassword,
including a password change - reusing it would let anyone holding the previous
file tell whether the password actually changed.

NO TIMING ORACLE. Verification never returns early: an unknown, disabled or
locked-out account still runs a full derivation against a stable decoy salt and
discards the result. The comparison is constant-time, and the derivation runs
OUTSIDE the lock - snapshot under it, ~100 ms of Argon2id outside it, then
re-find under it, because the account may have been changed meanwhile.

LOCKOUT is a failure count plus a window, defaulting to ten failures and
fifteen minutes, and the count belongs to an account AND a source address.
An attempt in flight counts against it until it is over: while the failures
and the attempts still deriving reach MaxFailures, another attempt from that
source is refused as locked out, so connections in parallel get no more
guesses than one connection, and after a lockout runs out the source has one
attempt at a time. A right password in flight counts too, so more than
MaxFailures sign-ins to one account from one source at the same moment see
the excess refused, and retry. Ten
wrong passwords from one address refuse that address the account, the right
password included, on IMAP, POP3 and SMTP, on every port; they do nothing to a
client somewhere else. VerifyEx, Verify and IsLocked take the source; the
servers pass the connection's remote address. One source is one IPv4 address, or
one /64 of IPv6 (cMailUserSourcePrefixBits), because one host may hold every
address of its /64 (MailUserSourceKey); an IPv4-mapped IPv6 address is its IPv4
address. A right password clears that source's count alone. Unlock
and a password change clear every source of the account, and IsLocked with no
source says whether any source is locked out.

THE FAILURE TABLE is bounded by MaxFailureEntries, default 16,384, about 3 MiB.
An entry is made only for an account that exists, so invented names take no
room. When it is full the oldest entry not locked out goes first, and the oldest
locked out only when every entry is; what goes is that source's count, so a full
table gives an address its guesses back sooner and never refuses a sign-in. It
is memory only, and a restart forgets it.

WHAT THIS LEAVES is guessing spread over many addresses: each may make
MaxFailures guesses at an account, and then one per LockoutSeconds, for as long
as its entry stays in the table. Past MaxFailureEntries entries all locked
out, the oldest lockout goes to make room and its source has MaxFailures
guesses again; to reach that an attacker needs more than MaxFailureEntries
sources failing against existing accounts within LockoutSeconds. Nothing
counts across addresses, by design, because a limit across addresses is what
let a stranger lock an account out. What bounds it is the number of
addresses, the Argon2id cost per guess, the limits per address on each port,
and the password.

THE FILE is a UTF-8 INI with one section per account, the mailbox name
percent-escaped so any address round-trips. Loading is fail-closed: a duplicate
or empty name, or a zero-length salt or verifier, is refused rather than
skipped. A missing file is simply an empty store, because a server starting for
the first time has no users.

THERE IS NO DESIGN-TIME USER COLLECTION, deliberately: a published collection
would put password verifiers in a DFM, where they get copied into version
control.

7.3  STORE LIFETIME AND PROCESS-STATE FAULTS

DEACTIVATING OR FREEING A TsmMailStore invalidates every view and access
reference it handed out: they raise eMailStoreUnavailable, and live sessions
get BYE or -ERR and close.

THE PROCESS-STATE CLASSES are EAccessViolation, EPrivilege, EStackOverflow,
EExternalException and EInvalidPointer. After one of them the process's memory
can no longer be trusted, and the scope is the PROCESS, not the store. It
applies to the store; to session code and its callbacks, also on a reactor
thread serving an implicit-TLS session; and at the top of a mail thread
(accept, connection, spool worker, shutdown and channel-close workers). In this
order:

  1  One process-wide latch, shared with the TLS layer's worker boundaries
     (stWorkerFatal). If another owner already holds it, the stores only stop
     committing, and reporting and exit stay with that owner.
  2  Every attached mail component logs "fatal mailbox store: ..." through
     OnLog.
  3  Every activated TsmMailStore becomes Failed, permanently, and nothing more
     is committed. With sldMaildir local delivery the spool's queue files
     freeze.
  4  Listeners are told to stop. Then each component's sessions get "* BYE
     mailbox store failed", "-ERR mailbox store failed" or "421 mailbox store
     failed", from a pool of cMailChannelCloseWorkers (16) threads, with a
     shared closure wait of cMailChannelCloseTimeoutMs (650 ms). Then an
     attached TsmAsyncTLSServer's Active goes False on the mail shutdown
     worker; the store's fatal path waits for that worker at most
     cMailShutdownRequestTimeoutMs (750 ms).
  5  Every store's OnFatalError runs on a worker. E is valid only during the
     call. Stop what the application owns, its Windows service included; do not
     free library components or join request threads. A raising handler is
     logged and ignored, and nothing a handler does can permit continuation.
  6  The process exits with cWorkerFatalExitCode, 70.

Each phase is bounded by cWorkerFatalPhaseTimeout (1000 ms), and a watchdog
(cWorkerFatalWatchdogTimeout, 5000 ms) ends the process if dispatch itself
sticks. These values are chosen, not measured. Ending the process is the only
action; no setting turns it off, on POSIX as on Windows. A fatal shutdown does
not join request workers; ordinary component destruction does.

An ordinary exception from the work of an accept, connection or spool thread
goes to the owning component's OnLog; at a shutdown or channel-close worker it
is dropped. None goes to stderr. An exception out of an OnLog handler is
contained, whatever its class, on any thread that is not a mail worker - the
application's main thread at Active := True, say. An engine driven with no
store callback re-raises a process-state exception to its owner. The async
server's reactor, listener and reaper threads are not mail threads: only mail
code running on them is covered. The TLS layer's own boundaries are described
in TLS.txt.

7.4  WHAT THE STORES DO NOT DO

No maildirsize: the quota usage is the store's own (7.1), and a Courier or
Dovecot quota file in the same tree is neither read nor written. No
'maildirfolder' marker file, which some Courier and Dovecot configurations
expect. No message parsing beyond the header/body split. No encrypted or
authenticated user file: the INI is plaintext on disk and protection is
filesystem permissions.

An info letter this store does not know survives a flag update, but not the move
from new/ to cur/, where only the known flags are carried across.


--------------------------------------------------------------------------------
8. THE CLIENTS
--------------------------------------------------------------------------------

TWO TIERS PER PROTOCOL, AND THE DIFFERENCE IS ENGINE OWNERSHIP, not protocol
features. TsmSMTPClient, TsmPOP3Client and TsmIMAPClient each create and own a
TLS engine, and their TLSServer setter refuses a foreign instance; the Advanced
tier takes an engine you supply, which is what lets several clients share one
trust domain. Nothing about the protocol differs between the two.

Implicit TLS is the default. The in-band upgrade is confined to one window in
the base class, and outside that window cleartext I/O raises.

AFTER THE HANDSHAKE THE CAPABILITY LIST IS RE-READ - a second EHLO, a second
CAPA, a second CAPABILITY - because a capability list obtained in cleartext is
an attacker's list. POP3 and IMAP additionally DISCARD every octet buffered
before the upgrade, which is the client half of the same rule the servers
apply.

AUTHENTICATION IS REFUSED WITHOUT TLS in all three, unconditionally and more
strictly than RequireTLS, because every mechanism these clients speak carries
the password. Credentials live in iSecretKey and travel in wiped byte buffers,
never through an immutable string: the command, its base64 and the CRLF are
assembled in one buffer that is wiped afterwards.

POP3 READS MULTI-LINE RESPONSES ON RAW OCTETS rather than through the base's
line reader, for two stated reasons - the line reader accepts a bare LF, and a
message body is not text.

IMAP HAS TWO READ MODES and the second is a pure byte countdown that never
looks for a delimiter, so a literal ends where its count says and nowhere else.
IMAP ADDRESSES EVERY MESSAGE BY UID, never by sequence number, because any
EXPUNGE renumbers and an API built on sequence numbers is a race by
construction.


--------------------------------------------------------------------------------
9. THE MESSAGE MODEL AND S/MIME
--------------------------------------------------------------------------------

TsmEmail is headers plus a MIME tree. Headers are ordered, duplicates are
legal, and values are stored unfolded and otherwise raw. Entities are headers
plus either a leaf body or child parts.

TOLERANT IN, STRICT OUT. The parser accepts bare-LF line ends, a missing colon,
unknown transfer encodings and an absent closing multipart delimiter; what it
WRITES is always CRLF, always with a closing delimiter, and always with a
transfer encoding it can name. Quoted-printable decoding tolerates lowercase
hex and stray '='; base64 output wraps at 76. Header words are decoded on
demand in both B and Q forms and encoded as UTF-8 B-words within the
75-character limit.

Address parsing walks quoted strings, nested comments, groups (flattened) and
angle addresses. For submission, the reverse path comes from Sender falling
back to From, and the forward paths from To, Cc and Bcc deduplicated
case-insensitively.

RFC 2231 EXTENDED PARAMETERS ARE DELIBERATELY NOT DECODED and not produced: an
extended parameter is returned as its raw value.

S/MIME CONNECTS TO CMS BY INHERITANCE, not delegation - the broker descends
from the CMS broker, so the SignedData and EnvelopedData workers are the same
components the rest of the library uses. Layering is innermost-first, the CMS
convention, so signed-then-enveloped means sign first.

WHAT S/MIME PROTECTS IS THE CONTENT ENTITY - the Content-* headers and the body
- and not the address headers, which the envelope has already carried in the
clear. multipart/signed is produced and verified with the signature DETACHED
over the canonical entity octets, and the signed part is added as bytes so
those octets stay pristine. Decoding peels every layer however deeply nested,
alternating multipart/signed and opaque forms, and reports the layers
innermost-first. Everything stays in secure memory and decrypted payloads are
wiped.

Not implemented: RFC 3798 message disposition notifications, and RFC 2231.


--------------------------------------------------------------------------------
10. DELPHI DECLARATIONS
--------------------------------------------------------------------------------

Thirteen registered components. Twelve Tsm* on the 'StreamSec Mobile' palette
page beside the other Tsm components; TstSMIMEBroker on 'StreamSec Tools',
beside the CMS workers it wires to.

  TsmEmail                 the message: headers, MIME tree, encodings
  TsmSMTPClient            owns its TLS engine
  TsmAdvancedSMTPClient    takes one
  TsmPOP3Client            owns its TLS engine
  TsmAdvancedPOP3Client    takes one
  TsmIMAPClient            owns its TLS engine
  TsmAdvancedIMAPClient    takes one
  TsmSMTPServer            inbound MX and submission, the relay gate, the queue
  TsmPOP3Server            one maildrop at a time
  TsmIMAPServer            shared access, IDLE, UIDPLUS, MOVE
  TsmMailStore             the mailbox tree - ONE object for all three servers
  TsmMailUsers             Argon2id accounts - ONE object for all three
  TstSMIMEBroker           S/MIME over TsmEmail

EVERY MAIL CLIENT inherits nine published properties and two events from the
TLS client base: Host, Port, ServerName, ImplicitTLS, RequireTLS,
ConnectTimeout, IOTimeout, ALPNProtocols, and the certificate events.

OBJECT REFERENCES THAT MUST BE WIRED for a working server:

  TsmSMTPServer.TLSServer     or any listener with TLS refuses to start
  TsmSMTPServer.Store         (preferred) or MailboxRoot, for sldMaildir
  TsmSMTPServer.Users         or nothing can authenticate
  TsmPOP3Server.Store/.Users/.TLSServer
  TsmIMAPServer.Store/.Users/.TLSServer
  TsmMailStore.Users          the accounts ARE the mailbox list

SUB-OBJECTS STREAMED INLINE rather than as component references: Inbound and
Submission on the SMTP server, Plain on each retrieval server, and Limits on
all three. Each is a TPersistent whose own properties stream as
Inbound.Port = 2525 and so on.

ONE PROPERTY EDITOR IS REGISTERED, on TsmSMTPServer.DkimKey. The property is a
plain TComponent reference so the runtime unit needs no key class; the editor
lists only components whose CLASS implements an RSA or EdDSA private-key
interface, which excludes the public-key-only counterparts, the ECDSA / DSS /
ML-DSA keys DKIM cannot use, and every non-key component. The test is on the
class, so it works before a key has been generated.

DENY BY DEFAULT IS STRUCTURAL IN THE PUBLISHED SURFACE. Every listener's
Enabled is False, every server's Active is False, AllowRelayOnInbound is False,
RelayForClientCertificate is False, AutoCreate is False, and VerifyInbound is
off.

GUARD RAILS LIVE IN THE SETTERS AND IN Start, not merely in the documentation.
Port, BindIP, Backlog and TLSMode refuse to change on a listener that is in
use, because a live change would either do nothing or silently relax a
submission port. A listener that could not work refuses to start rather than
starting degraded.

Active AT DESIGN TIME ONLY KEEPS THE VALUE, on all three servers. It streams,
and Loaded starts the server at run time; setting it in the Object Inspector
binds nothing in the IDE.

A PORT OF 0 ASKS THE SYSTEM. tMailListenerOptions.BoundPort (Inbound,
Submission, Plain) is the port bound while InUse and 0 otherwise. Port keeps
the configured value, so a stop and start binds a new system port and the
setting streams out as it was set. The listening log lines show the bound port.

IMPLICIT TLS NEEDS AN ASYNC SERVER PER PROTOCOL. The Server property attaches a
mail component to a TsmAsyncTLSServer; because no mail client offers ALPN, the
component must be that server's FALLBACK, which means setting IsFallback here
AND FallbackPolicy there. A fallback is singular, so one async server cannot be
the implicit-TLS port for SMTP and POP3 and IMAP at once - it is one async
server each for 465, 993 and 995.

THOSE PORTS ARE THE ASYNC SERVER'S. A mail component's own listeners speak
cleartext with an optional STARTTLS and cannot do implicit TLS. 465, 993 and
995 are conventions, set as BindPort on each TsmAsyncTLSServer, whose BoundPort
reports what it got.

THE TIMEOUTS ON THE LISTENER OPTIONS REACH AN ATTACHED SESSION, the idle,
session and preamble ones (section 11): 465 goes by Submission, 995 and 993 by
Plain.
The session sets them on its own connection and asks the server's
OnConnectionNudge as any session does. A server IdleTimeout that is set and
shorter than the listener's is the idle limit. With room on the port, a session
that has not left its preamble is held to the idle limit, as on the listener:
the re-check of its preamble limits every cMailPreambleRecheckMs does not put
the idle limit off.

THE CAPS DO NOT. A connection is admitted before there is a session, so they are
the async server's, and off or large by default because that server is not only
for mail. HandshakeTimeout bounds a peer that has not finished its handshake,
which is also a peer that has not had its banner. To give an implicit-TLS port
its protocol's caps, before Active:

  Imaps.MaxConnectionsPerPeer := IMAP.Plain.MaxConnectionsPerPeer;
  Imaps.MaxLiveSessions       := IMAP.Plain.MaxConnections;

An address the cap refuses is reported to OnPeerRefused. The async server
counts an IPv6 peer by its /64 and an IPv4-mapped IPv6 peer as its IPv4
address (section 11). AsyncTLSServer.txt section 5 has the rest.

FREEING A MAIL COMPONENT NEVER CHANGES A SHARED ASYNC SERVER'S Active: whatever
else it serves goes on. The destructor stops admitting, unregisters its
protocol, joins its own listeners' connection threads, and then closes only its
own sessions. Farewells ("* BYE server shutting down", "-ERR server shutting
down", "421 service closing transmission channel") and graceful closes run on
worker threads, unless no worker thread can be started at all. The calling
thread otherwise only waits; on the main thread it runs CheckSynchronize every
cMailDrainPollMs (10 ms), so a session callback that
synchronizes with the main thread can finish. After cMailDrainAbortMs (10000
ms) the sessions still open are aborted (iMailChannelAbort, over
iAppTransportAbort in AsyncTLSServer.txt section 8.1), so a peer that stopped
reading cannot hold it; a slow but live client past that sees a reset. The wait
has NO BOUND for a session callback that never returns, because freeing under
it would be a use-after-free: every cMailDestroyDrainMs (5000 ms) OnLog hears
"<n> ms passed and a session on the shared TLS server still holds this
component". These values are chosen, not measured.

Active := False on the mail component stops its own listeners and does not
close sessions on an attached async server. Only the fatal path of section 7.3
takes that server down.


--------------------------------------------------------------------------------
11. LIMITS - EVERY CAP IN ONE TABLE
--------------------------------------------------------------------------------

Every bound is a named constant except the mapped-folder limit below, and on
the tSmtpLimits / tPop3Limits / tImapLimits objects 0 means UNBOUNDED and a
negative normalises to 0 on the way in - save that the IMAP bounds before
authentication and on literals per command apply whatever LiteralBytes says.

A connection holds its slot from the accept until its thread ends, or on an
implicit-TLS port until it closes. One that
ends by a FIN, by a reset, or by a send or a read that fails gives the slot back
as soon as the next read finds that out, and no later than one read round
(cMailConnectionReadRoundMs). The idle and session limits below are for
connections that stay up.

THE PREAMBLE is the state of a session that has neither authenticated nor, on
SMTP, had a RCPT accepted with the transaction not yet over: MAIL alone, the
null path included, costs nothing and leaves a session in it. The end of a
message and RSET bring an SMTP session back, and its preamble limits then run
from that moment, not from the accept. The three preamble
rows below hold it to far less than the idle and session rows, when they apply:
while the share of MaxConnections in use is at least the percentage, 0 meaning
at any load. They are properties of the same names on the listener options, in
seconds, and 0 turns either limit off. All three are chosen, not measured. Too
short: a slow client is dropped and has to retry, or on IMAP a client that
connects before asking the user for a password. Too long: a silent peer keeps
its slot that long, and a full port stays full that long. Too low a percentage:
the RFC minimum gives way while the port still has room.

The percentages come from the RFCs. RFC 9051 sec.5.4 has its minimum for a timer
"that applies to sessions after authentication" and leaves one before it
unrestricted, so IMAP is 0. RFC 5321 sec.4.5.3.2.7 ("at least 5 minutes while it
is awaiting the next command") and RFC 1939 sec.3 ("at least 10 minutes'
duration") name no state, so on SMTP and POP3 the limits are load shedding, at
50. RFC 5321 sec.3.8 and sec.7.8 leave room for that; RFC 1939 has no such text.

SMTP

  command line                     512      RFC 5321 minimum, incl. CRLF
  SASL line                     12,288      bounded separately from the command
  DATA text line                65,536      far above the RFC's 1000
  forward/reverse path             256      RFC 5321, counted on octets
  message                       25 MiB
  recipients                       100      over it: 452, not 550
  messages per connection          100      over it: 421 and close
  protocol errors                   20      then 421
  auth failures                      3      deliberately far below the errors
  idle                             300 s    RFC 5321 sec.4.5.3.2 floor
  whole session                  1,800 s    not resettable by traffic
  preamble: idle / whole          30 / 120 s  cSmtpDefaultPreamble*
  preamble: past this share           50 %
  connections / per peer        256 / 8     sized for an MX
  ports                    25 / 587 / 465   465 on the async server: section 10

POP3

  command line                     512      matched to the response bound
  SASL line                     12,288
  UIDL                              70      RFC 1939 sec.7, by substitution
  protocol errors / auth        20 / 3
  idle                             600 s    RFC 1939 sec.3 ten-minute floor
  whole session                  1,800 s
  preamble: idle / whole          30 / 120 s  cPop3TransportPreamble*
  preamble: past this share           50 %
  connections / per peer         64 / 3     three, because the store refuses a
                                            second concurrent maildrop anyway
  ports                      110 / 995      995 on the async server: section 10

IMAP

  command line                   8,192      a literal never travels in it
  SASL line                     12,288
  literal octets per command    32 MiB      so also the largest APPEND
  the same, before authentication  4,096    cImapUnauthLiteralBytes
  literals per command              16      cImapMaxLiteralsPerCommand
  SEARCH nesting depth             100      cImapMaxSearchDepth; one more is
                                            NO [LIMIT]
  keywords per folder               26      cMailMaxKeywords: the letters a-z
                                            of Maildir++; one more is NO
                                            [LIMIT]
  keyword length                    64      cMailMaxKeywordLength; longer is
                                            NO
  protocol errors / auth        20 / 3
  idle                           1,800 s    RFC 9051 sec.5.4 thirty-minute floor
  whole session                 86,400 s    a day - IDLE is why
  preamble: idle / whole          60 / 180 s  cImapTransportPreamble*
  preamble: past this share            0 %  at any load
  connections / per peer        128 / 8     eight, because a real client opens
                                            one per open mailbox
  IDLE round                     1,000 ms   cMailConnectionReadRoundMs, both
                                            ports
  IDLE rescan                       30 s    cImapIdleRescanSeconds
  ports                      143 / 993      993 on the async server: section 10

IMPLICIT-TLS PORTS (TsmAsyncTLSServer)

  connections per address            0      MaxConnectionsPerPeer; set the
                                            listener's: section 10
  IPv6 source of that count        /64      cPeerSourceIPv6PrefixBits, chosen:
                                            everybody behind one /64 shares one
                                            limit, as behind one IPv4 NAT; and
                                            ::ffff:a.b.c.d counts as a.b.c.d
  live sessions                  8,192      MaxLiveSessions; likewise
  handshakes in flight             256      MaxConcurrentHandshakes
  accept to finished handshake  15,000 ms   HandshakeTimeout, absolute
  preamble limits: ask again     5,000 ms   cMailPreambleRecheckMs, once reached
                                            with the port not under pressure

TRANSPORT (shared)

  handshake budget              30,000 ms   and 64 rounds
  blocked send                  30,000 ms   named separately on purpose
  wire buffer                   17,408
  listen backlog                    64
  fatal: closure wait              650 ms   cMailChannelCloseTimeoutMs
  fatal: stop request              750 ms   cMailShutdownRequestTimeoutMs
  fatal: join a stopping worker  1,000 ms   cMailShutdownJoinTimeoutMs
  fatal: close workers              16      cMailChannelCloseWorkers
  destroy: abort after          10,000 ms   cMailDrainAbortMs
  destroy: log every             5,000 ms   cMailDestroyDrainMs
  destroy: poll                     10 ms   cMailDrainPollMs

QUEUE

  retry ladder      60,300,900,1800,3600,7200,14400 s, last repeats
  give-up                     5 days       measured FROM ARRIVAL; 0 = never
  delivery threads                 1
  bounce quotes                8,192 bytes
  store-down wait              1,000 ms    cSmtpSpoolStoreWaitMs

MESSAGES

  MIME nesting depth               100      cMailMaxNestingDepth
  MIME parts                    10,000      cMailMaxPartCount
  both shared across encapsulated messages in an IMAP walk

STORES

  path segment                      64      letters/digits/._- only; a folder
                                            segment also an interior space and
                                            modified UTF-7
  mapped folder                    255      a literal, MailFolderToDir
  folder name compared             254 units
  mailbox generation slots         256      cMailGenerationSlots
  mailbox quota                      0      TsmMailStore.Quota, octets; 0 = no
                                            limit
  quota usage recounted after      300 s    cMailQuotaRecountSeconds; at once
                                            after RecountUsage
  read/STORE/EXPUNGE attempts        3      cMailStoreFlagAttempts
  fatal phase / watchdog    1,000 / 5,000 ms
  fatal exit code                   70      cWorkerFatalExitCode
  Argon2id                  64 MiB, t=3, p=4, 16-octet salt, 32-octet tag
  lockout                     10 failures / 900 s, per account and source;
                                            attempts in flight count
  IPv6 source of the lockout       /64      cMailUserSourcePrefixBits, chosen:
                                            everybody behind one /64 shares one
                                            count per account; ::ffff:a.b.c.d
                                            counts as a.b.c.d
  failure table             16,384 entries  cMailUserFailureEntries

POLICY

  SPF lookups / void            10 / 2      protocol, not tuning
  SPF mx exchanges / ptr        10 / 10     over: permerror / ignore the rest
  DKIM RSA floor             1,024 bits     refused as policy
  DKIM clock skew                  300 s
  DKIM signatures / message          8      each costs a lookup and a verify
  DMARC pct                out of range clamps UP to 100
  X-DNS-Warning dns= / text  253 / 120   cSmtpDnsWarningMaxName / MaxText;
                                            one field per check
  X-Stripped-Fields host           253   cSmtpDnsWarningMaxName; one field per
                                            message, nothing of the fields
                                            copied
  Name: host; first line            78   cAuthFoldWidth; a longer one is
                                            folded after the colon, the host
                                            name kept whole
  Authentication-Results value      80   cAuthResultsMaxValue; a domain, d=
                                            or s= the sender chose, shortened
  forged field prefix      "X-Forged-"   cSmtpForgedFieldPrefix; the field
                                            otherwise as it came, section 5
  forged Subject prefix   "[Suspect] "   cSmtpForgedSubjectPrefix, the
                                            default ForgedSubjectPrefix,
                                            section 5
  Junk folder                   "Junk"   cSmtpJunkFolder, the default
                                            JunkFolder; section 5.2
  forged-stamp points               40   cSpamForgedStampPoints, once per
                                            message; the forgery files the
                                            copy whatever the score; the
                                            stamp says Yes, section 5.2
  MTA-STS max_age            1 year cap; policy 64 KiB; 128 mx patterns
  MTA-STS fetch              64 KiB, 15,000 ms, ZERO redirects
  DNS name / label            255 / 63      on parse AND on encode
  DNS pointer hops                  16
  DNS cache                  512 entries, TTL clamped to 60..86,400 s

The IDLE, attempt, slot, fatal, destroy and store-down values, the MIME pair,
the two literal counts, the ask-again period, the failure table and the IPv6
lockout prefix are chosen, not measured. The ask-again period: too long and a
port that fills up keeps silent sessions that much longer, too short and it
wakes for nothing on a port with room. The failure table: too small and, under
guessing from more addresses than it holds, an address's count is dropped
early; too large costs only memory. Change it with
TsmMailUsers.MaxFailureEntries. The IPv6 lockout prefix: longer
and a host that rotates through its /64 is a new source at each address;
shorter and more unrelated clients share one count, as behind one IPv4 NAT.


--------------------------------------------------------------------------------
12. IMPLEMENTED vs NOT - FEATURE MATRIX
--------------------------------------------------------------------------------

SMTP SERVER                                          yes   no   note
  EHLO/HELO, MAIL, RCPT, DATA, RSET, NOOP, QUIT       *
  PIPELINING, SIZE, 8BITMIME, SMTPUTF8                *
  STARTTLS                                            *
  implicit TLS (SMTPS)                                *      via async server
  AUTH PLAIN / LOGIN                                  *          TLS only
  AUTH CRAM-MD5 / SCRAM / XOAUTH2                          *
  inbound MX role + submission role                   *
  relay gate, RelayNetworks, client-cert relay        *
  local delivery to maildir                           *
  forgery filed into a Junk folder the mailbox has    *
  forged fields kept renamed, Subject marked          *          local copy
  outbound queue, retry, expiry, bounces              *
  DSN request parameters (NOTIFY, ORCPT)                   *     555 by name
  CHUNKING/BDAT, ETRN, TURN/ATRN, XCLIENT, PROXY           *     500
  VRFY / EXPN                                              *     252 by choice
  ENHANCEDSTATUSCODES advertised                           *     codes emitted

RETRIEVAL
  POP3 full RFC 1939 + CAPA + STLS                    *
  POP3 APOP                                                *     impossible
  IMAP4rev1 core, IDLE, UIDPLUS                       *
  IMAP MOVE (RFC 6851)                                *
  IMAP keywords, $Junk and $NotJunk                   *
  IMAP ENVELOPE / BODYSTRUCTURE                       *
  IMAP partial + sectioned FETCH                      *
  IMAP IDLE push on the STARTTLS port                 *
  IMAP IDLE push on the implicit-TLS port             *
  IMAP SEARCH boolean structure (NOT/OR/groups)       *
  IMAP CONDSTORE, QRESYNC, BINARY, COMPRESS,               *     declined, not
    MULTIAPPEND, LITERAL+, SORT, THREAD                           half-answered
  modified UTF-7 mailbox names                        *
  special-use attributes in LIST, CREATE with USE     *
  other mailbox attributes, LIST-EXTENDED                  *
  IMAP QUOTA (STORAGE), OVERQUOTA                     *
  ACLs                                                     *

STORES
  maildir with Maildir++ folders                      *
  shared by all three servers                         *
  UID index, UIDVALIDITY, UIDNEXT                     *
  Argon2id accounts, lockout, cost upgrade            *
  quota accounting                                    *
  encrypted account file                                   *

POLICY
  SPF, DKIM (verify + sign), DMARC                    *
  Authentication-Results                              *
  MTA-STS with anti-downgrade                         *
  MX delivery                                         *
  MX preference ordering on the delivery path         *
  DNSSEC / DANE                                            *
  ARC                                                      *
  DMARC reporting (rua/ruf)                                *
  SMTP TLS Reporting (RFC 8460)                            *
  SRV autoconfiguration (RFC 6186)                         *

MESSAGES
  RFC 5322 + MIME parse and compose                   *
  quoted-printable, base64, RFC 2047 words            *
  S/MIME sign, verify, encrypt, decrypt               *
  RFC 2231 extended parameters                             *
  message disposition notifications                        *


--------------------------------------------------------------------------------
13. SELF-TESTS AND THE DEMO
--------------------------------------------------------------------------------

The mail units are tested on Win32 and Win64 before release, with tests that
do not ship.

EIGHTEEN SELF-TEST FUNCTIONS SHIP INSIDE THE LIBRARY UNITS - MaildirSelfTest,
ImapEngineSelfTest, SmtpServerSelfTest, SmtpRelaySelfTest, SmtpSpoolSelfTest,
SmtpDeliverySelfTest, SpfSelfTest, DkimSelfTest and the rest - and each is
declared in its unit's interface, so you can call it. Where one takes an
out-parameter, a False names the failing vector, by number or by name.

NONE OF THEM NEEDS A NETWORK. DNS, SPF, DKIM, DMARC, MTA-STS, maildir, users
and the engines run against scripted resolvers, stub fetchers and canned
packets.

THE STORE IS THE DECIDER: delete the account and the same password stops
working.

WHAT THE SELF-TESTS DO NOT SHOW. DkimSelfTest verifies the signatures in
RFC 6376 Appendix A and RFC 8463 Appendix A, produced by the RFC authors rather
than by this library. The rest check the library against itself and against RFC
vectors. None of them talks to another mail implementation.

THE DEMO - Demos\<your IDE>\MailServer - is a complete small mail host: SMTP
in, maildir, POP3 and IMAP back out, all three sharing one store, one account
component and one TLS engine. Its thesis is that THE ARRANGEMENT IS THE
DATAMODULE: nothing constructs a component or assigns an object reference in
code. Exactly three things remain code, each with its reason - the certificate,
because a password is not a design-time property; the mailbox root, because it
defaults beside the executable; and the ORDER, which is why Active is
deliberately not streamed True.

The demo is also the worked example of the threading contract: OnLog and the
session events arrive on connection threads, so the datamodule queues lines
under a lock and a timer drains them, handing the form finished text on the
main thread.

Its ports are 2525, 2587, 2110 and 2143 on 127.0.0.1, because binding below
1024 needs privilege and a demo that must run as administrator teaches the
wrong lesson.


--------------------------------------------------------------------------------
14. KNOWN GAPS
--------------------------------------------------------------------------------

Collected from the sections above, in the order a deployment is likely to meet
them.

  1  No implicit-TLS listener without an async server, and one async server per
     protocol because a fallback is singular. This is the deployment shape
     RFC 8314 recommends, so it is the first thing to build.

  2  The MTA-STS policy cache is per-instance and not thread-safe. A spool
     delivering on several threads must give each its own or guard it.

  3  The queue resolves a message as a whole. A multi-domain envelope that
     partly succeeds is requeued whole, so the domain that took it receives a
     duplicate on retry.

  4  No ARC, so a forwarded message that broke its DKIM signature is refused by
     default. That default is deliberate; the alternative is a heuristic.

  5  No DMARC or TLS reporting, and no DNSSEC and therefore no DANE.

  6  IMAP: LIST reports the special-use attributes only; no \HasChildren,
     \HasNoChildren or \Noinferiors, and no LIST-EXTENDED.

  7  IMAP IDLE on the implicit-TLS port rescans on a reactor thread, as every
     command on that port runs. A rescan of a large mailbox holds that thread
     for as long as it takes, and other connections on it wait.

  8  Quotas count storage only: no MESSAGE or MAILBOX resource, one root per
     account, no soft limit or warning, and none on POP3.

  9  An unknown maildir flag letter does not survive the move from new/ to cur/.

 10  IMAP SEARCH matches the stored octets: an RFC 2047 encoded word is not
     decoded and an octet outside US-ASCII matches only '?', so a search for
     non-ASCII text finds little.

 11  IMAP: a literal in an argument position leaves no placeholder in the
     command line, so a handler expecting one can take the next argument in its
     place. An empty literal, {0}, does not reach the handler, and a count with
     leading zeros leaves a stray '{' in the line. SEARCH refuses any literal.

 12  IMAP: the over-long-line rule drops only what is buffered. The rest of
     that line, arriving later, runs as a command, and a line that arrives
     whole with its CRLF is accepted at any length.

 13  IMAP DELETE or RENAME by a session of its own selected mailbox (not INBOX)
     leaves the session selected, and it reports "* 0 EXISTS".

 14  IMAP APPEND and COPY open their destination through a transient read-write
     view, which moves pending arrivals out of new/ and so spends their \Recent.
     The appended or copied message itself is never \Recent.

 15  IMAP's refusal of 0-RTT on the implicit-TLS port, "* BYE early data is not
     accepted by this service", is sent without its final LF.

 16  SMTP: a local recipient resolved to an empty mailbox, with no
     OnLocalDeliver assigned, is answered 250 and dropped. Postmaster is the
     exception (RFC 5321 sec.4.5.1).

 17  SMTP: the check for a recipient repeated in one transaction folds case, so
     a second recipient differing only in case is answered 250 and dropped from
     the envelope, although RFC 5321 sec.2.4 leaves local-part case to the
     destination.

 18  Two citation gaps: 8BITMIME is implemented but RFC 6152 is named nowhere,
     and enhanced status codes are emitted without ENHANCEDSTATUSCODES ever
     being advertised.