Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.Maildir

WHERE MAIL FOR THIS HOST LIVES, AND THE ONLY THING THAT READS IT BACK.
  StreamSec.Mail.SMTPDelivery puts a message in a mailbox; this unit is the
  other half - enumerate, read, flag, delete, and the per-message identity POP3
  and IMAP have to be able to promise is stable.

  MAILDIR++, because the commit protocol is the one this codebase already
  trusts (write into tmp, flush, rename into new) and because the layout is what
  Dovecot and Courier read. That second reason is the deciding one: an operator
  can point another server at the same tree, or migrate off this one, without a
  converter. Flags live in the file name, folders are sibling '.Name'
  directories, and the hierarchy delimiter is '.'.

  THE ONE INVARIANT EVERYTHING ELSE RESTS ON:

      THE DELIVERY PATH NEVER TAKES A MAILBOX LOCK.

  Deliver writes tmp -> flush -> rename into new/. It reads no index and takes
  no cross-process maildrop lock. A short publication lock serializes fatal
  failure with writes. It waits for no lock held for a client session.
  A POP3 session held open for twenty minutes cannot delay or fail an inbound
  delivery through its long-lived maildrop lock. The index is only ever
  written by a reader that already holds the store lock.

  UIDVALIDITY IS MINTED ONCE AND NEVER REUSED. If the index is lost or will not
  parse, a NEW UIDVALIDITY is minted rather than the old one recovered. RFC 3501
  sec.2.3.1.1 makes a changed UIDVALIDITY mean "discard your cache", which costs
  a client one resync; reusing a UID for a different message means the client
  shows the wrong mail and never finds out. On any doubt, bump it.

  ONE ALLOWLIST FOR CLIENT PATH SEGMENTS. A mailbox is looked up by address
  and named by configuration, and an IMAP folder name is checked segment by
  segment against MailSafeFolderSegment before a directory is built from it.
  MailSafeSegment is the canonical client path allowlist; SMTPDelivery
  delegates to it, and MailSafeFolderSegment widens it only by an interior
  space and canonical modified UTF-7 (RFC 3501 sec.5.1.3), the spelling the
  folder directory then carries, as Dovecot and Courier name theirs.
  Comparisons accept filesystem folder names independently of the allowlist
  used to CREATE them.

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

Classes, interfaces and records

interfaceiMailFatalLease

function Enter(aShutdown: Boolean): Boolean; procedure Leave(aShutdown: Boolean); procedure Cancel;

recordtMailFatalHandler

Log, Shutdown: tMailFatalErrorEvent; Lease: iMailFatalLease;

classeMailStoreError

inherits from Exception

(no public members)

classeMailKeywordLimit

inherits from eMailStoreError

A new keyword for a folder whose keyword table is full (cMailMaxKeywords).

(no public members)

classeMailStoreUnavailable

inherits from eMailStoreError

Retained views and access references are invalid after shutdown.

(no public members)

classeMailSelectionUnavailable

inherits from eMailStoreUnavailable

(no public members)

classeMailRenameError

inherits from eMailStoreError

Every failed rollback pair is reported as current -> original path.

(no public members)

classeMailExpungeError

inherits from eMailStoreError

Physical removals remain true even if saving their index failed.

constructor Create(const aMessage: string; const aRemoved: TArray<Integer>); property Removed: TArray<Integer> read fRemoved;

recordtMailItem

ONE MESSAGE, as a view reports it. The body is NOT here - a mailbox of ten thousand messages costs ten thousand of these rather than the mail itself.

Uid: Cardinal;
Assigned in arrival order, never reused, monotonic within one UIDVALIDITY.
Name: string;
The maildir base name, WITHOUT the info suffix. Stable for the life of the message and unique across processes and restarts, which is what makes it the natural POP3 UIDL.
Octets: Int64; Flags: tMailFlags; Arrived: TDateTime;
When the message was delivered, from the name rather than the filesystem - a copy or a restore changes the mtime and must not change this.
Recent: Boolean;
It was in new/ when this view opened: IMAP's \Recent, and the thing that makes "first session to see it" answerable at all.
Keywords: TArray<string>;
Its IMAP keywords, as the folder's keyword table first spelled them. Filled by iMailboxView.Items; a letter the table does not name is left out.

interfaceiMailboxView

(no public members)

interfaceiMailboxAccess

WHAT EVERY RETRIEVAL PROTOCOL NEEDS OF A MAILBOX TREE.

function Available: Boolean;
A retained access object is usable only while its own store is live.
function SameFolderName(const aFolder1, aFolder2: string): Boolean;
The application's folder-name decision, with fixed INBOX semantics.
function MailboxExists(const aAddress: string): Boolean;
THE IDENTITY IS THE ADDRESS. No path component of any kind comes off the wire; the address is a lookup key and the directory is configuration.
function OpenFolder(const aAddress, aFolder: string; aMode: tMailboxOpenMode; out aView: iMailboxView; out aWhy: string; out aMissing: Boolean): Boolean;
aFolder is '' or 'INBOX' for the maildir root, or a delimited path such as 'Sent.2026'. False with aWhy set when it does not exist, cannot be named safely, or is locked by another session. aMissing is True only for a nonexistent folder, rather than an index or access failure.
function ListFolders(const aAddress, aPattern: string): TArray<string>;
Folder names under aAddress, INBOX first. aPattern accepts '*' and '%' with the IMAP meanings; '' lists everything.
function CreateFolder(const aAddress, aFolder: string): Boolean;
True when the folder exists afterwards, whether this call made it or it was there already. False for '' and INBOX, which are never created, for a name the store refuses, and when its tmp, new and cur cannot all be made directories - a file in the place of one, say.
function CreateNewFolder(const aAddress, aFolder: string; out aExisted: Boolean): Boolean;
IMAP CREATE: True only when THIS CALL made the folder. False with aExisted True when a folder of that name already exists - by SameFolderName, after trimming, and INBOX or '' included - and False with aExisted False when the name is refused or the folder cannot be made. Full description »
function DeleteFolder(const aAddress, aFolder: string): Boolean; function RenameFolder(const aAddress, aFrom, aTo: string): Boolean;
IMAP RENAME. It is NOT one directory rename: a maildir++ child is a sibling directory whose name carries the parent's, so '.Sent' moving to '.Archive' has to take every '.Sent.*' with it or the children are orphaned under a parent that no longer exists. Full description »
function ReadSubscriptions(const aAddress: string): TArray<string>;
The IMAP subscription list, which is per ACCOUNT and has nothing to do with which folders exist - RFC 3501 sec.6.3.6 is explicit that a client may subscribe to a mailbox that does not exist yet. Stored one name per line in 'subscriptions' at the mailbox root.
function WriteSubscriptions(const aAddress: string; const aNames: TArray<string>): Boolean;

interfaceiMailboxView

ONE OPEN FOLDER, for the length of a session.

IT IS A SNAPSHOT. Message numbers are fixed when it opens and only Refresh may change them - POP3 forbids renumbering inside a session outright, and IMAP forbids it anywhere an untagged EXISTS would not be legal.

function GetCount: Integer; function GetTotalOctets: Int64; function GetUidValidity: Cardinal; function GetUidNext: Cardinal; function GetItem(aIndex: Integer): tMailItem; property Count: Integer read GetCount;
1-based, as both protocols number.
property TotalOctets: Int64 read GetTotalOctets; property UidValidity: Cardinal read GetUidValidity; property UidNext: Cardinal read GetUidNext; property Items[aIndex: Integer]: tMailItem read GetItem; function ReadMessage(aIndex: Integer; out aData: tBytes): Boolean;
The stored octets, exactly. Nothing here rewrites what was delivered.
function ReadHead(aIndex, aBodyLines: Integer; out aData: tBytes): Boolean;
The header block, plus at most aBodyLines lines of body - POP3 TOP, and what an IMAP header search needs so it does not read whole messages. aBodyLines < 0 means headers only.
function SetFlags(aIndex: Integer; aFlags: tMailFlags; aMode: tMailFlagMode; aExternalChanged: PBoolean = nil): tMailFlagResult;
Every disk flag observation synchronizes the snapshot, even if the requested change fails. aExternalChanged reports disk flags different from this view before STORE and survives persistence errors. Missing files are not errors; other failures raise eMailStoreError.
procedure MarkDeleted(aIndex: Integer; aDeleted: Boolean);
Marks only. Nothing leaves the mailbox until Expunge.
function Expunge: TArray<Integer>;
Commits every message marked \Deleted and answers the message numbers removed, DESCENDING - which is the order a client can apply without renumbering underneath itself.
function Refresh(out aAdded: Integer): Boolean;
Picks up arrivals in new/. IMAP only; a POP3 view must never call it.
function Append(const aData: tBytes; aFlags: tMailFlags; const aArrived: TDateTime; out aUid: Cardinal): Boolean; function RemoveAppended(const aNames: TArray<string>): Boolean;
Roll back only files successfully appended through this view. Names are stable Maildir basenames, independent of UIDs and flag suffixes. Folder renames are followed within the same account. A changed or missing index does not prevent their removal.
function MoveTo(const aIndices: TArray<Integer>; const aTarget: iMailboxView; out aSrcUids, aDstUids: TArray<Cardinal>; out aRemoved: TArray<Integer>): Boolean;
IMAP MOVE (RFC 6851). Each message named by aIndices (ascending message numbers in this view) leaves this folder and enters aTarget, another read-write view of the same store, by ONE RENAME of its file: at every instant, a crash included, the message is in exactly one of the two folders. Full description »
function Keywords: TArray<string>;
IMAP KEYWORDS. The keywords this folder's table defines, in table order, read from disk.
function SetFlagsKeywords(aIndex: Integer; aFlags: tMailFlags; const aKeywords: TArray<string>; aMode: tMailFlagMode; aExternalChanged: PBoolean = nil): tMailFlagResult;
SetFlags, and the keywords with the flags in the same rename: aMode applies to both, so mfmReplace with aKeywords nil clears them. A keyword not yet in the table is added to it for mfmAdd and mfmReplace (eMailKeywordLimit when the table is full); one being removed that the table does not hold changes nothing. A keyword that MailKeywordIsValid refuses raises eMailStoreError.
function AppendKeywords(const aData: tBytes; aFlags: tMailFlags; const aKeywords: TArray<string>; const aArrived: TDateTime; out aUid: Cardinal): Boolean;
Append, with keywords, defined in the table as SetFlagsKeywords does.
procedure Close;

classtMaildir

(no public members)

classtMaildirView

inherits from TInterfacedObject

implements iMailboxView

ONE OPEN FOLDER. Created only by tMaildir.

constructor Create(aOwner: tMaildir; const aBase: string; aMode: tMailboxOpenMode; aLock: TFileStream); destructor Destroy; override; function ReadMessage(aIndex: Integer; out aData: tBytes): Boolean; function ReadHead(aIndex, aBodyLines: Integer; out aData: tBytes): Boolean; function SetFlags(aIndex: Integer; aFlags: tMailFlags; aMode: tMailFlagMode; aExternalChanged: PBoolean = nil): tMailFlagResult;
Delegates to DoSetFlags, passing 6 argument(s), and returns its result.
procedure MarkDeleted(aIndex: Integer; aDeleted: Boolean); function Expunge: TArray<Integer>; function Refresh(out aAdded: Integer): Boolean; function Append(const aData: tBytes; aFlags: tMailFlags; const aArrived: TDateTime; out aUid: Cardinal): Boolean;
Delegates to AppendKeywords, forwarding aData, aFlags, nil, aArrived and aUid, and returns its result.
function RemoveAppended(const aNames: TArray<string>): Boolean;
Roll back only files successfully appended through this view. Names are stable Maildir basenames, independent of UIDs and flag suffixes. Folder renames are followed within the same account. A changed or missing index does not prevent their removal.
function MoveTo(const aIndices: TArray<Integer>; const aTarget: iMailboxView; out aSrcUids, aDstUids: TArray<Cardinal>; out aRemoved: TArray<Integer>): Boolean; function Keywords: TArray<string>; function SetFlagsKeywords(aIndex: Integer; aFlags: tMailFlags; const aKeywords: TArray<string>; aMode: tMailFlagMode; aExternalChanged: PBoolean = nil): tMailFlagResult;
Delegates to DoSetFlags, passing 6 argument(s), and returns its result.
function AppendKeywords(const aData: tBytes; aFlags: tMailFlags; const aKeywords: TArray<string>; const aArrived: TDateTime; out aUid: Cardinal): Boolean; procedure Close;

classtMaildir

inherits from TInterfacedObject

implements iMailboxAccess

THE TREE. One directory per mailbox under a root, Maildir++ inside each.

constructor Create(const aRoot: string); destructor Destroy; override; procedure AddMailbox(const aAddress, aDirectory: string);
'alice@example.com' -> 'alice'. The address is matched case-insensitively; the directory is taken literally and must pass MailSafeSegment.
procedure ClearMailboxes; procedure ReplaceMailboxes(aList: TStrings);
THE WHOLE LIST, IN ONE LOCKED STEP. Clear-then-re-add is not equivalent: the lock is per operation, so a reader between the two sees an EMPTY mailbox list and an address that exists resolves to nothing. Full description »
procedure EnsureMailbox(const aAddress: string);
Creates the three subdirectories if they are missing.
function ResolveMailbox(const aAddress: string; out aMailbox: string): Boolean;
Resolves an address to its directory NAME (not a path).
procedure Deliver(const aMailbox: string; const aData: tBytes);
THE DELIVERY PATH. tmp -> flush -> rename into new/, no maildrop lock, no index. The publication lock serializes writes with fatal failure. Raises on failure: a normal return is what a 250 is built on.
function DeliverToFolder(const aMailbox, aFolder: string; const aData: tBytes): Boolean;
THE SAME, INTO A FOLDER THAT EXISTS: aFolder of the mailbox aMailbox (a directory NAME, as Deliver takes), named as OpenFolder names one and found by SameFolderName. Full description »
procedure BeginCommit;
Retain this store through Access while an external writer uses the same fatal-publication gate as Maildir persistence.
procedure EndCommit; function Available: Boolean; function SameFolderName(const aFolder1, aFolder2: string): Boolean; function MailboxExists(const aAddress: string): Boolean; function OpenFolder(const aAddress, aFolder: string; aMode: tMailboxOpenMode; out aView: iMailboxView; out aWhy: string; out aMissing: Boolean): Boolean; function ListFolders(const aAddress, aPattern: string): TArray<string>; function CreateFolder(const aAddress, aFolder: string): Boolean; function CreateNewFolder(const aAddress, aFolder: string; out aExisted: Boolean): Boolean; function DeleteFolder(const aAddress, aFolder: string): Boolean; function RenameFolder(const aAddress, aFrom, aTo: string): Boolean; function ReadSubscriptions(const aAddress: string): TArray<string>; function WriteSubscriptions(const aAddress: string; const aNames: TArray<string>): Boolean; function Generation: Integer;
A COUNTER THAT MOVES WHENEVER A MAILBOX'S CONTENTS MAY HAVE CHANGED THROUGH THIS OBJECT - a delivery, an APPEND, an EXPUNGE, in any mailbox of the tree. Full description »
function GenerationSlot(const aAddress, aFolder: string): Integer;
GENERATION, SCOPED TO ONE MAILBOX. GenerationSlot resolves aFolder of aAddress once (-1: not resolvable); MailboxGeneration moves whenever Generation does for that mailbox - and, because slots are shared by hash, sometimes for another one, which costs a needless rescan and nothing else. Full description »
function MailboxGeneration(aSlot: Integer): Int64; function MailboxQuota(const aMailbox: string; out aUsed, aLimit: Int64): Boolean;
THE QUOTA OF ONE MAILBOX. aMailbox is its directory name, as ResolveMailbox gives it, so an alias that resolves to a mailbox is counted against that mailbox. Full description »
function AccountQuota(const aAddress: string; out aUsed, aLimit: Int64): Boolean;
MailboxQuota of the mailbox aAddress resolves to; False, with both 0, when it resolves to none.
procedure RecountUsage(const aMailbox: string);
The next MailboxQuota of aMailbox counts its files again. For an application that has changed the files itself.
property Quota: Int64 read GetQuota write SetQuota;
The limit of every mailbox, in octets; 0 is no limit.
property OnMailboxQuota: tMailQuotaEvent read fOnMailboxQuota write fOnMailboxQuota;
Called by MailboxQuota on the asking thread; an exception propagates to that caller.
property Root: string read fRoot; property HostName: string read fHostName write fHostName;
Used in the generated file name, per the maildir convention.
property AutoCreate: Boolean read fAutoCreate write fAutoCreate;
Accept a recipient with no configured mailbox, deriving the directory from the local part. OFF BY DEFAULT: it is the one mode in which something a peer chose influences a path, and it turns a host into a catch-all that creates a directory per spam target.
property FlushToDiskProperty: Boolean read fFlushToDisk write fFlushToDisk;
Flush each message to the platter before the rename that commits it. On by default: the sender has been told the message is accepted.

classTsmMailStore — component reference

inherits from TComponent

THE MAILBOX TREE AS ONE COMPONENT, so the SMTP server that writes it and the POP3 and IMAP servers that read it are pointed at THE SAME OBJECT rather than three configured with the same directory.

One shared configuration keeps mailbox lists and AutoCreate policy from disagreeing. Separate stores share the process operation lock, index and maildrop exclusion, and the fatal latch for the same canonical root.

ONE LIST, NOT TWO. With Users assigned the accepted addresses are the ACCOUNTS: an account is a mailbox is a maildir, which is the 1:1:1 model StreamSec.Mail.Users already claims, made structural. Without it, fill in Mailboxes by hand. Configuring both is legitimate - the explicit list wins for an address the account store does not know - but it is the arrangement in which the two can drift.

constructor Create(AOwner: TComponent); override; procedure BeforeDestruction; override; procedure ReportFatalError(E: Exception);
Fatal exceptions from protocol and application callbacks use the same terminal coordinator as folder-comparison failures. » member page
destructor Destroy; override; property Store: tMaildir read fStore;
The store itself, once Active. nil before that. » member page
property Access: iMailboxAccess read fStoreRef;
What a retrieval protocol holds. » member page
property Failed: Boolean read GetFailed;
Permanent for this component instance, including after deactivation. » member page
property FailurePending: Boolean read GetFailurePending; procedure AddFatalErrorHandler(const aLog, aShutdown: tMailFatalErrorEvent);
Independent service observers; all log before any service is stopped. » member page
procedure RemoveFatalErrorHandler(const aLog, aShutdown: tMailFatalErrorEvent); procedure Refresh;
Re-reads Mailboxes and Users into the store. Called for you when either changes and when Active is set; exposed because an application that provisions accounts from somewhere else needs to say so. » member page
property Root: string read fRoot write SetRoot;
Where the tree lives, one subdirectory per mailbox. » member page
property Mailboxes: TStringList read fMailboxes write SetMailboxes;
'alice@example.com=alice' - the address this host accepts, and the directory its mail goes in. The address is matched case-insensitively; the directory must be a plain, safe name, which is checked. » member page
property Users: TsmMailUsers read fUsers write SetUsers;
The password accounts. When assigned, every account name is an accepted address and its directory is derived from the local part through the allowlist - see the class comment. » member page
property HostName: string read GetHostName write SetHostName;
Used in the generated file name, per the maildir convention. Set it to this host's FQDN. » member page
property AutoCreate: Boolean read GetAutoCreate write SetAutoCreate default False;
Accept an address with no configured mailbox and no account, deriving the directory from the local part. OFF BY DEFAULT - it is the one mode in which something a peer chose influences a path. » member page
property FlushToDisk: Boolean read GetFlushToDisk write SetFlushToDisk default True;
Flush each message to the platter before the rename that commits it. On by default: the sender has been told the message is accepted. » member page
property Quota: Int64 read GetQuota write SetQuota default 0;
The storage limit of every mailbox, in octets; 0, the default, is no limit. The library only measures and answers it: the IMAP and SMTP servers over this store refuse what would pass it, see tMaildir.MailboxQuota for how the usage is kept. » member page
property OnMailboxQuota: tMailQuotaEvent read fOnMailboxQuota write fOnMailboxQuota;
One mailbox's limit instead of Quota: aMailbox is its directory name, aLimit arrives as Quota. Called on the thread that asks, an SMTP session at RCPT and end of DATA, an IMAP session at APPEND, COPY and GETQUOTA. » member page
property Active: Boolean read fActive write SetActive default False;
Builds the store. Nothing reads or writes a mailbox until it is True, and Root cannot change while it is. » member page
property OnFatalError: tMailFatalErrorEvent read fOnFatalError write fOnFatalError;
Runs on a worker after bounded service shutdown. E is valid only during this callback. Stop what the application owns, including its Windows service. Do not free library components or join request threads here. The process WILL end after this handler returns, or after its one-second deadline, with exit code 70. This event cannot permit continuation. A raising handler is logged and ignored. » member page
property OnCompareFolderName: tMailCompareFolderNameEvent read fOnCompareFolderName write SetOnCompareFolderName;
Default: invariant ASCII lower-case equality over full names valid on the file system, except inside a modified UTF-7 run ('&' to '-'), whose case is significant. Full description »

Types (enumerations, sets, aliases)

proctMailCompareFolderNameEvent

aSame starts with the store's case-insensitive default answer.

  tMailCompareFolderNameEvent = procedure(Sender: TObject;
    const aFolder1, aFolder2: string; var aSame: Boolean) of object;

proctMailFatalErrorEvent

  tMailFatalErrorEvent = procedure(Sender: TObject; E: Exception) of object;

proctMailQuotaEvent

aMailbox is the mailbox's directory name. aLimit starts with the store's Quota: octets, 0 for no limit.

  tMailQuotaEvent = procedure(Sender: TObject; const aMailbox: string;
    var aLimit: Int64) of object;

enumtMailFlag

The Maildir++ flag set. The letters are the on-disk spelling and the order of this enumeration IS their ASCII order, which is what the convention requires of the info suffix.

  tMailFlag = (
    mfDraft,      // D
    mfFlagged,    // F
    mfPassed,     // P - resent/forwarded
    mfAnswered,   // R - "replied"
    mfSeen,       // S
    mfDeleted);   // T - "trashed"

settMailFlags

  tMailFlags = set of tMailFlag;

enumtMailFlagMode

  tMailFlagMode = (mfmReplace, mfmAdd, mfmRemove);

enumtMailFlagResult

  tMailFlagResult = (mfrUnchanged, mfrChanged, mfrMissing, mfrFailed);

enumtMailboxOpenMode

  tMailboxOpenMode = (
    { Read, flag and expunge. }
    mbmReadWrite,
    { IMAP EXAMINE and STATUS: no message changes, not even \Seen, and nothing
      leaves new/ - which is what \Recent is made of. The UID index is still
      written: a UID is the store's, and one that is not recorded is not
      stable. }
    mbmReadOnly,
    { POP3: read-write AND the cross-process maildrop lock. }
    mbmExclusive);

arraytMailItems

  tMailItems = array of tMailItem;

proctMailFatalExitHook

  tMailFatalExitHook = procedure(aExitCode: Cardinal);

proctMailThreadTestHook

  tMailThreadTestHook = procedure(const aThread: string);

Routines