Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.IMAPEngine

The server side of RFC 3501, with no socket, no TLS and no threads in it:
  octets go in through Receive, reply octets come out through OnOutput, and
  every decision the protocol does not make itself is asked of an
  iImapServerPolicy. Same shape as StreamSec.Mail.SMTPEngine and
  StreamSec.Mail.POP3Engine, and for the same reason - the framing is the
  security-critical half of an IMAP server and it is testable only if nothing
  else is in the way.

  THE LITERAL IS THE WHOLE FRAMING PROBLEM. IMAP is the only protocol in this
  family whose command length is announced by the peer mid-command: a braced octet count says
  "the next n octets are data, whatever they contain", and those octets may hold
  CRLF, a tag, or a complete second command. So an implementation that keeps
  scanning for CRLF while a literal is outstanding can be made to execute octets
  the client sent as DATA. This engine therefore has exactly two input modes -
  reading a line, or counting down a literal - and the countdown is over BYTES
  ONLY. Nothing in the literal path looks for a delimiter, and the line scanner
  is never entered while fLitRemaining > 0.

  Synchronising literals are collected before command grammar validation,
  only after the '+ ' continuation that RFC 3501 sec.4.3 requires. Literal
  count and aggregate octets are bounded, including before authentication.
  Non-synchronising literals (the braced count suffixed '+', RFC 7888) are NOT advertised and NOT
  accepted: they would let a peer put an unbounded body into the same round trip
  as the command that describes it, which is the one thing the continuation
  exists to prevent.

  UNTAGGED RESPONSES AND WHEN THEY MAY BE SENT. RFC 3501 sec.5.5 forbids
  reporting an EXPUNGE while a FETCH, STORE or SEARCH is in progress, because
  the client is holding message numbers that the report would renumber
  underneath it. The rule is enforced structurally here: the expunge queue is
  drained only from Flush, which no command handler calls, and command handlers
  set fNoExpunge for their duration.

  WHAT IS IMPLEMENTED. IMAP4rev1 (RFC 3501) with IDLE (RFC 2177), UIDPLUS
  (RFC 4315: APPENDUID, COPYUID, UID EXPUNGE), MOVE (RFC 6851: MOVE and
  UID MOVE) and SPECIAL-USE (RFC 6154: the use attributes in LIST, and
  CREATE with USE) and QUOTA (RFC 9208: GETQUOTA, GETQUOTAROOT, the STORAGE
  resource, STATUS DELETED-STORAGE and NO [OVERQUOTA]; SETQUOTA is refused);
  keywords, $Junk and $NotJunk among them, are stored
  (PERMANENTFLAGS \*). CAPABILITY reports exactly what this engine answers and
  nothing aspirational.
  WHAT IS NOT, and is refused rather than half-answered: CONDSTORE/QRESYNC,
  BINARY, COMPRESS, MULTIAPPEND, LITERAL+, SORT/THREAD, and the SEARCH keys
  outside the documented set below.

Feature notes: Mail subsystem notes (SMTP / POP3 / IMAP)

Classes, interfaces and records

classeImapServerError

inherits from Exception

(no public members)

recordtImapStatusCounts

Messages: Integer; Recent: Integer; UidNext: Cardinal; UidValidity: Cardinal; Unseen: Integer; DeletedStorage: Int64;
Octets of the messages with \Deleted set: RFC 9208 sec.4.1.4's DELETED-STORAGE, which STATUS gives in units of 1024 octets.

recordtImapQuotaResource

One resource of a quota root (RFC 9208 sec.4.2.1): its name, as STORAGE, and its usage and limit in the resource's own units - 1024 octets for STORAGE (sec.5.1).

Name: string; Usage: Int64; Limit: Int64;

classtImapSession

(no public members)

interfaceiImapServerPolicy

EVERY DECISION THE ENGINE DOES NOT MAKE ITSELF. The engine owns framing, sequencing, the sequence-number/UID mapping, the untagged-response rules and the deletion marks; who may sign in and what the mailboxes hold belong to the application.

CALLED ON WHATEVER THREAD DROVE Receive, so blocking is permitted.

INDICES ARE 1-BASED MESSAGE SEQUENCE NUMBERS in the currently selected mailbox, exactly as the store's iMailboxView numbers them. The engine never hands a UID to this interface without saying so in the name.

function Greeting(const aSession: tImapSession): string;
Greeting text, without the '* OK ' prefix. '' takes the default.
function Authenticate(const aSession: tImapSession; const aUser: string; const aPassword: iSecretKey; var aWhy: string): Boolean;
The credential, in wiped storage. RUN ONLY OVER A SECURE CHANNEL - the engine refuses every password mechanism outright otherwise, so an implementation never sees one that crossed cleartext. ONE FAILURE ANSWER FOR EVERY REASON: aWhy goes to the log and the engine sends a single fixed NO, or LOGIN becomes an account enumerator.
function SelectFolder(const aSession: tImapSession; const aFolder: string; aReadOnly: Boolean; var aWhy: string): Boolean;
aReadOnly is EXAMINE. The engine closes any prior selection before calling SelectFolder. A failure or exception leaves none selected, as RFC 3501 sec.6.3.1 requires.
procedure CloseFolder(const aSession: tImapSession; aExpunge: Boolean); function CreateFolder(const aSession: tImapSession; const aFolder: string; var aWhy: string): Boolean;
True only when this call made the mailbox (RFC 3501 sec.6.3.3). For one that exists, False with aWhy starting '[ALREADYEXISTS] ' (RFC 5530 sec.3); aWhy is the text of the tagged NO. The engine has refused an empty name and INBOX before asking.
function DeleteFolder(const aSession: tImapSession; const aFolder: string; var aWhy: string): Boolean; function RenameFolder(const aSession: tImapSession; const aFrom, aTo: string; var aWhy: string): Boolean; function Subscribe(const aSession: tImapSession; const aFolder: string; aSubscribe: Boolean; var aWhy: string): Boolean; function ListFolders(const aSession: tImapSession; const aReference, aPattern: string; aSubscribedOnly: Boolean): TArray<string>;
Names matching aPattern under aReference, with the IMAP wildcards already applied. aSubscribedOnly is LSUB. INBOX must come back as 'INBOX'.
function SpecialUse(const aSession: tImapSession; const aFolder: string): string;
The special-use attributes of aFolder (RFC 6154 sec.2), space separated, each with its backslash: '\Sent', '\Junk'; '' for none. LIST reports them, and CREATE with USE succeeds only for a name whose answer here holds every use asked for.
function FolderStatus(const aSession: tImapSession; const aFolder: string; out aCounts: tImapStatusCounts; var aWhy: string): Boolean; function QuotaRoots(const aSession: tImapSession; const aFolder: string; out aRoots: TArray<string>; var aWhy: string): Boolean;
The quota roots of aFolder (GETQUOTAROOT, sec.4.1.2), none for a folder no quota covers; False with aWhy when the folder does not exist or cannot be named.
function QuotaResources(const aSession: tImapSession; const aRoot: string; out aResources: tImapQuotaResources; var aWhy: string): Boolean;
The resources of the quota root aRoot (GETQUOTA, sec.4.1.1), each with its usage and limit; none for a root with no limit (sec.4.2.1). False with aWhy for a root that is not one of this session's. A refusal of APPEND, COPY or MOVE for want of room is the policy's own aWhy, beginning '[OVERQUOTA] ' (sec.4.3.1). SETQUOTA is refused by the engine and QUOTASET is not advertised.
function MessageCount(const aSession: tImapSession): Integer; function RecentCount(const aSession: tImapSession): Integer; function UidValidity(const aSession: tImapSession): Cardinal; function UidNext(const aSession: tImapSession): Cardinal; function FirstUnseen(const aSession: tImapSession): Integer;
1-based sequence number of the first \Unseen message, or 0.
function ItemAt(const aSession: tImapSession; aIndex: Integer): tMailItem; function ReadMessage(const aSession: tImapSession; aIndex: Integer; out aData: tBytes): Boolean; function ReadHead(const aSession: tImapSession; aIndex, aBodyLines: Integer; out aData: tBytes): Boolean;
Header block plus at most aBodyLines lines of body; aBodyLines < 0 is headers only.
function SetFlags(const aSession: tImapSession; aIndex: Integer; aFlags: tMailFlags; const aKeywords: TArray<string>; aMode: tMailFlagMode; aExternalChanged: PBoolean = nil): tMailFlagResult;
Persistence outcomes are per message; failures are logged by policy. ItemAt retains observed disk flags even when the requested write fails. aExternalChanged reports disk flags differing from the prior view. aKeywords go with aFlags under the same aMode, so mfmReplace with no keywords clears them (RFC 3501 sec.6.4.6).
function MailboxKeywords(const aSession: tImapSession; out aRoom: Integer): TArray<string>;
The keywords the selected mailbox defines, and in aRoom how many new ones it can still take: 0 for none, and for a read-only selection.
function Expunge(const aSession: tImapSession; const aRestrict: TArray<Integer>; out aRemoved: TArray<Integer>; var aWhy: string): Boolean;
Commits every message marked \Deleted whose sequence number is in aRestrict (empty = all of them, i.e. plain EXPUNGE; a non-empty set is UID EXPUNGE, RFC 4315 sec.2.1). Answers the numbers removed, DESCENDING, which is the order a client can apply without renumbering underneath itself.
function AppendMessage(const aSession: tImapSession; const aFolder: string; const aData: tBytes; aFlags: tMailFlags; const aKeywords: TArray<string>; const aArrived: TDateTime; out aUidValidity: Cardinal; out aUid: Cardinal; var aWhy: string; out aTryCreate: Boolean): Boolean;
APPEND. aUidValidity and aUid feed the UIDPLUS APPENDUID. aTryCreate is true only when the destination does not exist.
function CopyMessages(const aSession: tImapSession; const aIndices: TArray<Integer>; const aFolder: string; out aUidValidity: Cardinal; out aSrcUids, aDstUids: TArray<Cardinal>; var aWhy: string; out aTryCreate: Boolean): Boolean;
COPY. aIndices are ascending sequence numbers in the selected mailbox; aSrcUids/aDstUids feed the UIDPLUS COPYUID and must correspond element-for-element. aTryCreate is true only for a missing target.
function MoveMessages(const aSession: tImapSession; const aIndices: TArray<Integer>; const aFolder: string; out aUidValidity: Cardinal; out aSrcUids, aDstUids: TArray<Cardinal>; out aRemoved: TArray<Integer>; var aWhy: string; out aTryCreate: Boolean): Boolean;
MOVE and UID MOVE (RFC 6851). As CopyMessages, and each message that reached aFolder leaves the selected mailbox, without \Deleted ever being set on it and whatever \Deleted the others carry. Full description »
function Refresh(const aSession: tImapSession; out aAdded: Integer): Boolean;
Picks up arrivals. Answers the number added, which the engine turns into an untagged EXISTS/RECENT at a moment when that is legal.
procedure SessionClosed(const aSession: tImapSession);

classtImapLimits

inherits from TPersistent

The engine's configurable bounds. A TPersistent so a component can publish it as a sub-object. Zero removes this configurable cap; negative normalises to zero. Mandatory command-literal bounds still apply.

constructor Create(aOwner: TComponent); virtual; procedure AssignTo(Dest: TPersistent); override; property CommandLineBytes: Integer read fCommandLineBytes write SetCommandLineBytes default cImapMaxCommandLine; property AuthLineBytes: Integer read fAuthLineBytes write SetAuthLineBytes default cImapMaxAuthLine; property LiteralBytes: Integer read fLiteralBytes write SetLiteralBytes default cImapMaxLiteral;
The literal octets one command may carry, summed over its literals - so also the largest APPEND this server will take. 0 = no limit. Before authentication cImapUnauthLiteralBytes applies instead.
property Errors: Integer read fErrors write SetErrors default cImapDefaultMaxErrors; property AuthFailures: Integer read fAuthFailures write SetAuthFailures default cImapDefaultMaxAuthFailures;

classtImapSession

ONE CONNECTION'S IMAP CONVERSATION.

Drive it with Start (which queues the greeting) and then Receive for every octet the peer sends. Replies leave through OnOutput, COALESCED: everything one Receive produced is emitted in a single call.

NOT THREAD-SAFE, and does not need to be: it belongs to one connection. The one exception is Nudge, which a transport may call from its own thread to deliver an IDLE update; it only sets a flag that Receive/Flush act on.

constructor Create(const aPolicy: iImapServerPolicy; aLimits: tImapLimits = nil); destructor Destroy; override; procedure Start;
Queues the greeting. Call once, before the first Receive.
procedure Receive(aData: Pointer; aLen: Integer);
Every octet the peer sent, in order. Replies leave through OnOutput before this returns.
procedure Flush;
Emits whatever is queued, including any untagged report that became legal while no command was running. A transport calls this after Nudge.
function IdleFailed(aException: Exception): Boolean;
Reports a transport-side idle poll failure under the same exception and store-liveness rules as a command, then flushes the response.
procedure Nudge;
THE TRANSPORT SAYS THE MAILBOX MAY HAVE CHANGED. Safe from another thread: it sets a flag and nothing else.
procedure SecureChannelEstablished;
The handshake the engine asked for has completed.
property State: tImapState read fState; property ServerName: string read fServerName write fServerName; property AuthenticatedUser: string read fAuthUser; property SecureChannel: Boolean read fSecureChannel write fSecureChannel; property RemoteAddress: string read fRemoteAddress write fRemoteAddress; property SelectedFolder: string read fFolder; property SelectedReadOnly: Boolean read fReadOnly; property AuthMechanisms: tImapServerAuths read fAuthMechanisms write fAuthMechanisms; property OfferStartTLS: Boolean read fOfferStartTLS write fOfferStartTLS; property Limits: tImapLimits read fLimits; property OnOutput: tImapOutputEvent read fOnOutput write fOnOutput; property OnException: tImapExceptionEvent read fOnException write fOnException; property OnStoreUnavailable: tImapStoreUnavailableEvent read fOnStoreUnavailable write fOnStoreUnavailable;
Queries this session's store; exception classes do not identify it.
property OnCloseRequested: TNotifyEvent read fOnCloseRequested write fOnCloseRequested; property OnStartTLSRequested: TNotifyEvent read fOnStartTLSRequested write fOnStartTLSRequested;

Types (enumerations, sets, aliases)

enumtImapState

RFC 3501 sec.3 states four. issStartTLS is this engine's, and it exists to STOP THE LINE LOOP DEAD: everything the peer pipelined behind STARTTLS has already been discarded by then, and no further command may be read from a buffer that is about to stop being cleartext. issIdle is the IDLE window, in which the only input accepted is the line 'DONE'.

  tImapState = (issNotAuthenticated, issAuthenticated, issSelected, issLogout,
                issStartTLS, issIdle);

enumtImapServerAuth

The SASL mechanisms this engine can run. Named isa* because StreamSec.Mail.POP3Engine and StreamSec.Mail.SMTPEngine already use psa* and ssa*, and a component that uses two of the three would otherwise resolve a duplicate to whichever unit came last in the uses clause, silently.
isaLoginCmd is the LOGIN COMMAND, not the LOGIN mechanism: it is a member rather than the absence of the others, so "SASL off, LOGIN on" is expressible and [] still means nothing authenticates.

  tImapServerAuth  = (isaLoginCmd, isaPlain, isaLogin);

settImapServerAuths

  tImapServerAuths = set of tImapServerAuth;

enumtImapStatusItem

What STATUS may be asked for (RFC 3501 sec.6.3.10).

  tImapStatusItem  = (isiMessages, isiRecent, isiUidNext, isiUidValidity,
                      isiUnseen, isiDeletedStorage);

settImapStatusItems

  tImapStatusItems = set of tImapStatusItem;

typetImapQuotaResources

  tImapQuotaResources = TArray<tImapQuotaResource>;

proctImapOutputEvent

Reply octets. No Sender: this is an engine, not a component - the same shape as tSmtpOutputEvent and tPop3OutputEvent.

  tImapOutputEvent = procedure (aData: Pointer; aLen: Integer) of object;

proctImapExceptionEvent

  tImapExceptionEvent = procedure(aException: Exception) of object;

proctImapStoreUnavailableEvent

  tImapStoreUnavailableEvent = function: Boolean of object;

Routines