From e2189caf93d8a3f8929e66b30257ebf30e57288b Mon Sep 17 00:00:00 2001 From: Andris Reinman Date: Mon, 30 Nov 2026 14:28:51 +0200 Subject: [PATCH 1/2] fix: keep message sources once in memory The server copied the storage option with structuredClone, which also copies strings, so every message source was kept twice (the copy for control.reset() and the live one). The copy now shares strings, and Buffer sources are turned into binary strings once, so the copies share them too. The MIME parser joined the body lines of every part into a new string, and nested message/rfc822 parts copied their content again. Bodies and epilogues are now slices of the source, which V8 shares with it. A 710 MB corpus of 11,637 messages now takes 714 MB of heap once parsed, down from 2036 MB. A message given in storage as a bare Uint8Array was stored empty, it now keeps its source. Co-Authored-By: Claude Opus 5.5 --- src/mimeparser.ts | 54 +++++++++++++++++--------- src/server.ts | 92 ++++++++++++++++++++++++++++++++++++++------ test/control.test.ts | 38 ++++++++++++++++++ 3 files changed, 155 insertions(+), 29 deletions(-) diff --git a/src/mimeparser.ts b/src/mimeparser.ts index 822bc2e..f631423 100644 --- a/src/mimeparser.ts +++ b/src/mimeparser.ts @@ -80,11 +80,19 @@ export interface MimeNode { globalMessage?: MimeNode; } -/** A node while it is parsed: lines are collected in lists, finalizeTree() turns it into a MimeNode */ +/** + * A node while it is parsed: body and epilogue are ranges of the source, finalizeTree() turns it into a MimeNode + * whose body and epilogue are slices of the source. V8 keeps a slice as a reference into the source string, so + * the tree does not copy the message (also not for the nested messages of message/rfc822 parts) + */ interface ParseNode extends Omit { state?: 'header' | 'body' | 'epilogue'; - body: string[]; - epilogue?: string[]; + /** body lines read so far */ + bodyLines?: number; + bodyStart?: number; + bodyEnd?: number; + epilogueStart?: number; + epilogueEnd?: number; childNodes: ParseNode[]; /** the root of the tree has none */ parentNode?: ParseNode; @@ -254,6 +262,7 @@ class MIMEParser { // keep parsing until the last linebreak is not a string (no linebreaks anymore) while (typeof this._br === 'string') { + const lineStart = this._pos; line = this.readLine(); const delimiter = this.matchDelimiter(line); @@ -271,9 +280,14 @@ class MIMEParser { break; case 'body': - // push the line with previous linebreak value, joined together the lines - // give the original body - this._node.body.push((this._node.body.length ? prevBr : '') + line); + // the body runs from the first body line up to the end of the last one, the line + // breaks between the lines included + if (!this._node.bodyLines) { + this._node.bodyLines = 0; + this._node.bodyStart = lineStart; + } + this._node.bodyLines++; + this._node.bodyEnd = lineStart + line.length; break; case 'epilogue': @@ -281,10 +295,10 @@ class MIMEParser { // of the enclosing multipart (or the end of the message) is the epilogue. Every // epilogue line keeps the line break that precedes it, the first one being the // line break that ends the close delimiter line - if (!this._node.epilogue) { - this._node.epilogue = []; + if (this._node.epilogueStart === undefined) { + this._node.epilogueStart = lineStart - (prevBr || '').length; } - this._node.epilogue.push(prevBr + line); + this._node.epilogueEnd = lineStart + line.length; break; default: @@ -403,10 +417,10 @@ class MIMEParser { open.bare = true; } } - } else if (node.body.length) { + } else if (node.bodyLines) { // the preamble ends here. The line break between the preamble and the delimiter belongs to // the delimiter, but the preamble lines end with their own - node.body[node.body.length - 1] += prevBr; + node.bodyEnd! += (prevBr || '').length; } if (!delimiter.close) { @@ -462,26 +476,26 @@ class MIMEParser { const parsing: Partial = stack.pop()!; // the same object, from here on with its lines joined const node = parsing as unknown as MimeNode; - const lines = parsing.body!; + const lines = parsing.bodyLines || 0; // a body section holds lines, parts, or at least a close delimiter. A blank line followed by // the end of the input leaves the trailing empty line in the body, one followed directly by // a delimiter leaves nothing const closed = node.boundary && !node.unterminated; - if (!(lines.length || parsing.childNodes!.length || closed)) { + if (!(lines || parsing.childNodes!.length || closed)) { node.hasBody = false; } // RFC 3501 7.4.2 body-fld-lines, counted like Dovecot does: the line breaks in the body - node.lineCount = lines.length ? lines.length - 1 : 0; - node.body = lines.join(''); + node.lineCount = lines ? lines - 1 : 0; + node.body = lines ? this.rfc822.slice(parsing.bodyStart, parsing.bodyEnd) : ''; node.size = node.body.length; // a message/rfc822 entity carries its parsed message this.parseEmbeddedMessage(node); - if (parsing.epilogue) { - node.epilogue = parsing.epilogue.join(''); + if (parsing.epilogueStart !== undefined) { + node.epilogue = this.rfc822.slice(parsing.epilogueStart, parsing.epilogueEnd); } parsing.childNodes!.forEach(child => stack.push(child)); @@ -489,6 +503,11 @@ class MIMEParser { // remove unneeded properties delete parsing.parentNode; delete parsing.state; + delete parsing.bodyLines; + delete parsing.bodyStart; + delete parsing.bodyEnd; + delete parsing.epilogueStart; + delete parsing.epilogueEnd; if (!node.childNodes!.length) { delete node.childNodes; } @@ -504,7 +523,6 @@ class MIMEParser { childNodes: [], header: [], parsedHeader: Object.create(null), - body: [], multipart: false, boundary: false, parentNode diff --git a/src/server.ts b/src/server.ts index 541541a..85eaa30 100644 --- a/src/server.ts +++ b/src/server.ts @@ -361,6 +361,10 @@ class IMAPServer extends Stream { if (this.options.storage) { // a typo in a fixture fails here with the path of the problem validateStorage(this.options.storage); + // the copy that control.reset() restores, with message sources as binary strings, which every later + // copy shares, instead of the Buffers of the caller next to the strings made from them + this.options.storage = copyStorage(this.options.storage); + Object.values(this.options.storage).forEach(prepareSources); } this.systemFlags = ([] as string[]).concat(this.options.systemFlags || ['\\Answered', '\\Flagged', '\\Draft', '\\Deleted', '\\Seen']); this.loadStorage(); @@ -406,7 +410,7 @@ class IMAPServer extends Stream { // indexFolders() below turns the storage option into namespaces and mailboxes in place this.storage = ( this.options.storage - ? structuredClone(this.options.storage) + ? copyStorage(this.options.storage) : { INBOX: {}, '': {} @@ -1448,16 +1452,7 @@ class IMAPServer extends Stream { mailbox.uidnext = message.uid + 1; } - // message source is kept as a binary string (one character per octet) - if (message.raw instanceof Uint8Array) { - message.raw = Buffer.from(message.raw).toString('binary'); - } else if (typeof message.raw !== 'string') { - message.raw = message.raw ? String(message.raw) : ''; - } - if (/[\u0100-\uffff]/.test(message.raw)) { - // characters outside Latin-1 can only come from a unicode string, so encode it as UTF-8 - message.raw = Buffer.from(message.raw, 'utf-8').toString('binary'); - } + message.raw = binarySource(message.raw); // Allow plugins to process messages const processed = message as Message; @@ -4041,6 +4036,81 @@ function resetSocket(socket: net.Socket, tcpSocket?: net.Socket | null): void { socket.destroy(); } +/** + * A message source as the server keeps it, a binary string (one character per octet) + * + * @param {*} raw Source from storage: a binary string, a unicode string, a Buffer or a Uint8Array + * @return {String} Binary string + */ +function binarySource(raw: unknown): string { + if (raw instanceof Uint8Array) { + return Buffer.from(raw).toString('binary'); + } + const source = typeof raw === 'string' ? raw : raw ? String(raw) : ''; + // characters outside Latin-1 can only come from a unicode string, so encode it as UTF-8 + return /[\u0100-\uffff]/.test(source) ? Buffer.from(source, 'utf-8').toString('binary') : source; +} + +/** + * Turns the message sources of a mailbox from storage and of its folders into binary strings, in place. A + * message given as a string or a Uint8Array becomes a string, one given as an object keeps its other keys + * + * @param {Object} mailbox Mailbox or namespace from storage + */ +function prepareSources(mailbox: StorageMailbox): void { + if (!mailbox || typeof mailbox !== 'object') { + return; + } + if (Array.isArray(mailbox.messages)) { + mailbox.messages = mailbox.messages.map(message => + typeof message === 'string' || message instanceof Uint8Array + ? binarySource(message) + : message && typeof message === 'object' + ? Object.assign(message, { raw: binarySource(message.raw) }) + : message + ); + } + Object.values(mailbox.folders || {}).forEach(prepareSources); +} + +/** + * Copies the storage option for loadStorage(), which changes it in place. Like structuredClone, except that + * strings are shared: they are immutable, and copying them would keep every message source twice, as the + * option stays for control.reset(). Arrays and plain objects are copied, anything else (Dates, Buffers, Maps) + * goes through structuredClone. An object that appears twice is copied once + * + * @param {*} value Storage or a part of it + * @param {Map} [copies] Copies made so far + * @return {*} Copy + */ +function copyStorage(value: T, copies = new Map()): T { + if (!value || typeof value !== 'object') { + return value; + } + if (copies.has(value)) { + return copies.get(value) as T; + } + const proto = Object.getPrototypeOf(value); + let copy: unknown; + if (Array.isArray(value)) { + const list: unknown[] = []; + copies.set(value, list); + value.forEach(item => list.push(copyStorage(item, copies))); + copy = list; + } else if (proto === Object.prototype || proto === null) { + const object: Record = {}; + copies.set(value, object); + for (const key of Object.keys(value)) { + object[key] = copyStorage((value as Record)[key], copies); + } + copy = object; + } else { + copy = structuredClone(value); + copies.set(value, copy); + } + return copy as T; +} + /** * Copies a response tree for the `mutate` action of a script rule: arrays and plain objects are copied, * other values (Buffers) are shared diff --git a/test/control.test.ts b/test/control.test.ts index 19db5ba..49330bc 100644 --- a/test/control.test.ts +++ b/test/control.test.ts @@ -461,6 +461,44 @@ describe('control API reset', () => { }); }); +describe('storage option copy', () => { + it('leaves the storage option unchanged and restores it on reset()', () => { + const date = new Date('2020-01-02T03:04:05Z'); + const shared = { note: 'same object twice' }; + const makeStorage = () => ({ + INBOX: { + messages: [ + { raw: Buffer.from('Subject: buffer\r\n\r\n\xe4\r\n', 'binary'), internaldate: date, flags: ['\\Seen'], extra: shared }, + { raw: 'Subject: string\r\n\r\nB\r\n', extra: shared }, + // a message can also be only its source + new Uint8Array(Buffer.from('Subject: bare\r\n\r\nC\r\n')) + ] + }, + '': { separator: '/', folders: { Archive: Object.assign(Object.create(null), { messages: [] }) } } + }); + const storage = makeStorage(); + const before = makeStorage(); + const server = imapkit({ storage }); + const messages = server.storage.INBOX.messages; + assert.strictEqual(messages[0]?.raw, 'Subject: buffer\r\n\r\n\xe4\r\n'); + assert.strictEqual(messages[2]?.raw, 'Subject: bare\r\n\r\nC\r\n'); + assert.notStrictEqual(messages[0]?.internaldate, date); + // an object that appears twice is copied once, like structuredClone does + assert.strictEqual(messages[0]?.extra, messages[1]?.extra); + assert.notStrictEqual(messages[0]?.extra, shared); + + server.control.addMessage('INBOX', { raw: 'Subject: new\r\n\r\nC\r\n' }); + server.control.setFlags('INBOX', [1], ['\\Flagged'], 'add'); + server.control.deleteMailbox('Archive'); + assert.deepStrictEqual(storage, before); + + const initial = imapkit({ storage: before }).control.snapshot(); + server.control.reset(); + assert.deepStrictEqual(server.control.snapshot(), initial); + assert.deepStrictEqual(storage, before); + }); +}); + describe('control API users and sessions', () => { const ctx = setupServer(() => ({})); const open = useSessions(ctx); From 5274250e10699591057070cc0995f0e9130c5078 Mon Sep 17 00:00:00 2001 From: Andris Reinman Date: Mon, 30 Nov 2026 14:28:53 +0200 Subject: [PATCH 2/2] feat: --maildir loads the mailboxes from a Maildir++ directory or .eml files imapkit --maildir= (IMAPKIT_MAILDIR) builds the storage from a Maildir++ directory (cur and new, flags from the file names, .Name folders) or from a directory of *.eml files, whose subdirectories with mail become mailboxes. The file modification time is the internal date, line breaks are converted to CRLF, and the files are only read. imapkit/lib/maildir exports loadMaildir() for use from code. A large corpus can not go through --storage, as Node.js can not read a JSON file over about 512 MB into one string. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 2 +- bin/help.txt | 18 +- bin/imapkit.js | 12 ++ docs/docs/getting-started/command-line.md | 20 ++- src/maildir.ts | 200 ++++++++++++++++++++++ test/cli.test.ts | 61 ++++++- test/maildir.test.ts | 153 +++++++++++++++++ 8 files changed, 453 insertions(+), 15 deletions(-) create mode 100644 src/maildir.ts create mode 100644 test/maildir.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 97828de..3f41832 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,7 @@ Plugins must stay self-contained: if a plugin is not loaded, no trace of it shou Per connection hooks for plugins that change the wire format: `connection.parserOptions` and `connection.compilerOptions` are passed to the `imap-handler` parser and compiler, `connection.importMailboxName(name)` converts every mailbox name argument (the `mailboxArguments` positions) to the modified UTF-7 storage name and throws a BAD error for an invalid name, and `connection.exportMailboxName(path)` converts a storage name for output. Every response that carries a mailbox name must convert it: either call `exportMailboxName` (LIST, LSUB, NAMESPACE), or put `{ type: 'MAILBOX', value: storageName }` in the attributes (also inside lists, like the MAILBOX correlator of ESEARCH), which `send` converts for the receiving session and sends as an atom or a string (STATUS, QUOTAROOT, METADATA, needed for notifications that go to several sessions). `matchFolders` takes the export function as its third argument. A command whose mailbox argument has no fixed position calls `importMailboxName` itself (GETMETADATA, ESEARCH). `connection.searchCharset` fixes the SEARCH charset of a session: a CHARSET argument is then BAD, and SORT/THREAD accept only that charset; `connection.defaultSearchCharset` only changes the charset assumed without CHARSET (IMAP4rev2: UTF-8). UTF8=ACCEPT and IMAP4rev2 set these through `src/utf8-session.ts`, which computes the UTF-8 state of a session from `connection.enabled`, so both plugins work in any load order. `connection.disabledSearchKeys` and `connection.disabledStatusItems` (Sets, or null) remove SEARCH keys and STATUS items from a session (BAD), `connection.addedStatusItems` allows STATUS items for one session only, `connection.number64` makes the `number64` SEARCH argument type (LARGER, SMALLER) take 63-bit values, and `connection.parserOptions.number64` (imap-handler) literal sizes and partial ranges (IMAP4rev2 sets both), `connection.messageGlobal` makes message/global parts encapsulate a message in BODYSTRUCTURE and section numbers (`resolveNode(tree, path, global)`, `embeddedMessage()` in `mimeparser.ts`), and `connection.getFlags(message)` can be replaced per connection (IMAP4rev2 leaves out `\Recent`). A plugin that needs another one lists its name in `plugin.requires` (UTF8=ACCEPT requires ENABLE), `src/load-plugins.ts` loads it first. -Other modules: `mimeparser.ts`, `bodystructure.ts`, `envelope.ts`, `addressparser.ts` produce BODYSTRUCTURE/ENVELOPE data from raw messages; `encoded-words.ts` decodes RFC 2047 encoded words for SEARCH header keys, SORT and THREAD; `sorting.ts` (collation, base subject, sent date, address and Message-ID values, and the search step) and `threading.ts` (THREAD command, ORDEREDSUBJECT and REFERENCES) back the SORT, SORT=DISPLAY and THREAD=* plugins; `smtp-listener.ts` is the optional SMTP listener (built on the optional `smtp-server` peer dependency) that appends incoming mail to INBOX; `cert/` holds the self-signed localhost cert used for STARTTLS and `secureConnection` (embedded through the generated `src/cert.ts`). +Other modules: `mimeparser.ts`, `bodystructure.ts`, `envelope.ts`, `addressparser.ts` produce BODYSTRUCTURE/ENVELOPE data from raw messages; `encoded-words.ts` decodes RFC 2047 encoded words for SEARCH header keys, SORT and THREAD; `sorting.ts` (collation, base subject, sent date, address and Message-ID values, and the search step) and `threading.ts` (THREAD command, ORDEREDSUBJECT and REFERENCES) back the SORT, SORT=DISPLAY and THREAD=* plugins; `maildir.ts` (`loadMaildir(dir)`, not in the package root or the browser bundle because it reads files) builds a storage object from a Maildir++ directory or a directory of `.eml` files for `imapkit --maildir`; `smtp-listener.ts` is the optional SMTP listener (built on the optional `smtp-server` peer dependency) that appends incoming mail to INBOX; `cert/` holds the self-signed localhost cert used for STARTTLS and `secureConnection` (embedded through the generated `src/cert.ts`). ## Tests diff --git a/README.md b/README.md index 7285567..ae203c7 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Point your IMAP client to `localhost:1143` and log in with user name `testuser` `imapkit -p 1143 --tls-port=1993` also listens for implicit TLS (IMAPS) connections on port 1993, both ports serve the same mailboxes. `imapkit --smtpPort=1025` also starts an SMTP server that appends every message it receives to INBOX. SMTP needs the optional [smtp-server](https://www.npmjs.com/package/smtp-server) package, which is not installed with ImapKit: `npm install -g smtp-server` (or `npm install smtp-server` next to a local install). -Run `imapkit --help` to see all command line options, the environment variables (`IMAPKIT_PORT`, `IMAPKIT_PLUGINS`, ...) and sample configuration data. For example, `imapkit -p 1143 --plugin=IDLE,MOVE,CONDSTORE --storage=storage.json` loads three plugins and the mailboxes of `storage.json`. +Run `imapkit --help` to see all command line options, the environment variables (`IMAPKIT_PORT`, `IMAPKIT_PLUGINS`, ...) and sample configuration data. For example, `imapkit -p 1143 --plugin=IDLE,MOVE,CONDSTORE --storage=storage.json` loads three plugins and the mailboxes of `storage.json`. `--maildir=` loads the mailboxes from a Maildir++ directory or a directory of `.eml` files instead. ### Include as a Node.js module diff --git a/bin/help.txt b/bin/help.txt index 8e55654..d73ba4f 100644 --- a/bin/help.txt +++ b/bin/help.txt @@ -16,6 +16,12 @@ Usage: imapkit [OPTS] -s, --secure=true Starts a secure server, defaults port to 993 -d, --debug=true Writes IMAP traffic to console --storage= Path to JSON file with the directory tree + --maildir= Loads the mailboxes from a Maildir++ directory + (cur/new, flags from the file names, .Sub + folders) or from a directory of *.eml files + (subdirectories with *.eml files become + mailboxes). The files are read once at start + and never changed --config= Path to config JSON file --script= Path to a JSON file with script rules that make the server misbehave on purpose (see @@ -48,12 +54,12 @@ Usage: imapkit [OPTS] run can be repeated The options can also be set with environment variables: IMAPKIT_PORT, -IMAPKIT_SECURE, IMAPKIT_DEBUG, IMAPKIT_STORAGE, IMAPKIT_CONFIG, -IMAPKIT_SCRIPT, IMAPKIT_PLUGINS (comma separated), IMAPKIT_TLS_PORT, -IMAPKIT_SMTPPORT, IMAPKIT_REST_PORT, IMAPKIT_REST_HOST, IMAPKIT_REST_TOKEN, -IMAPKIT_OAUTH_PORT, IMAPKIT_OAUTH_HOST, IMAPKIT_OAUTH_CONSENT, -IMAPKIT_OAUTH_SECURE, IMAPKIT_OAUTH_ISSUER, IMAPKIT_QUIRKS and -IMAPKIT_SCRIPT_SEED. +IMAPKIT_SECURE, IMAPKIT_DEBUG, IMAPKIT_STORAGE, IMAPKIT_MAILDIR, +IMAPKIT_CONFIG, IMAPKIT_SCRIPT, IMAPKIT_PLUGINS (comma separated), +IMAPKIT_TLS_PORT, IMAPKIT_SMTPPORT, IMAPKIT_REST_PORT, +IMAPKIT_REST_HOST, IMAPKIT_REST_TOKEN, IMAPKIT_OAUTH_PORT, +IMAPKIT_OAUTH_HOST, IMAPKIT_OAUTH_CONSENT, IMAPKIT_OAUTH_SECURE, +IMAPKIT_OAUTH_ISSUER, IMAPKIT_QUIRKS and IMAPKIT_SCRIPT_SEED. NB! If port or smtpPort values are below 1024 you most probably need to use sudo or run the command with administrator rights. diff --git a/bin/imapkit.js b/bin/imapkit.js index 7789c33..441faa1 100755 --- a/bin/imapkit.js +++ b/bin/imapkit.js @@ -5,6 +5,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import imapkit from '../dist/esm/index.js'; +import { loadMaildir } from '../dist/esm/maildir.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const packageData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8')); @@ -19,6 +20,7 @@ const { values: argv } = parseArgs({ help: { type: 'boolean', short: 'h' }, config: { type: 'string' }, storage: { type: 'string' }, + maildir: { type: 'string' }, script: { type: 'string' }, plugin: { type: 'string', multiple: true }, smtpPort: { type: 'string' }, @@ -52,6 +54,7 @@ const listOption = value => const configLocation = argv.config || process.env.IMAPKIT_CONFIG; const storageLocation = argv.storage || process.env.IMAPKIT_STORAGE; +const maildirLocation = argv.maildir || process.env.IMAPKIT_MAILDIR; const scriptLocation = argv.script || process.env.IMAPKIT_SCRIPT; const smtpPort = argv.smtpPort || argv['smtp-port'] || process.env.IMAPKIT_SMTPPORT; const tlsPort = argv['tls-port'] || process.env.IMAPKIT_TLS_PORT; @@ -75,6 +78,11 @@ if (configLocation) { config = JSON.parse(fs.readFileSync(configLocation, 'utf-8')); } +if (storageLocation && maildirLocation) { + console.error('Failed to start ImapKit: --storage and --maildir can not be used together'); + process.exit(1); +} + if (storageLocation) { config.storage = JSON.parse(fs.readFileSync(storageLocation, 'utf-8')); } @@ -151,6 +159,10 @@ if (argv.help) { } let server; try { + if (maildirLocation) { + // read here, not with the other files above, so that --help does not read a large directory + config.storage = loadMaildir(maildirLocation); + } server = imapkit(config); } catch (err) { // an unknown plugin or quirk name, invalid storage ... diff --git a/docs/docs/getting-started/command-line.md b/docs/docs/getting-started/command-line.md index cbc2d34..d991937 100644 --- a/docs/docs/getting-started/command-line.md +++ b/docs/docs/getting-started/command-line.md @@ -29,6 +29,7 @@ Install the command with `npm install -g imapkit`, or run it from a project that | `-s`, `--secure` | `IMAPKIT_SECURE=true` | Implicit TLS on the IMAP port, with the bundled self-signed certificate for `localhost`. | | `-d`, `--debug` | `IMAPKIT_DEBUG=true` | Writes the IMAP traffic to the console. | | `--storage=` | `IMAPKIT_STORAGE` | JSON file with the mailbox tree, the `storage` option. See [Storage](../guides/storage.md). | +| `--maildir=` | `IMAPKIT_MAILDIR` | Loads the mailbox tree from a Maildir++ directory or a directory of `.eml` files instead of a storage file, see [Mail files on disk](#mail-files-on-disk). | | `--config=` | `IMAPKIT_CONFIG` | JSON file with [server options](../reference/server-options.md), see [Configuration file](#configuration-file). | | `--script=` | `IMAPKIT_SCRIPT` | JSON file with [script rules](../faults/scripted-faults.md), a rule or a list of rules. | | `--plugin=` | `IMAPKIT_PLUGINS` | Plugins to load. Comma separated (`--plugin=IDLE,MOVE`) or repeated (`--plugin=IDLE --plugin=MOVE`). Names are case-insensitive and capability spellings like `LITERAL+` work too. | @@ -46,7 +47,7 @@ Install the command with `npm install -g imapkit`, or run it from a project that | `--smtpPort=`, `--smtp-port=` | `IMAPKIT_SMTPPORT` | Starts an SMTP server on this port that appends every message it receives to INBOX. Needs the optional `smtp-server` package, see [Installation](installation.md#optional-the-smtp-listener). | | `-h`, `--help` | | Prints the options, every plugin with a short description, and sample config and storage files. | -A command line option wins over its environment variable, and both win over the config file. `--plugin` replaces the `plugins` list of the config file, `--storage` its `storage`, and `--script` its `script`. +A command line option wins over its environment variable, and both win over the config file. `--plugin` replaces the `plugins` list of the config file, `--storage` and `--maildir` its `storage`, and `--script` its `script`. `--storage` and `--maildir` can not be used together. Ports below 1024 (143 and 993 included) usually need administrator rights. Pick a port such as 1143 for local use. @@ -115,6 +116,23 @@ imapkit -p 1143 --plugin=SPECIAL-USE --storage=storage.json Without a storage file the server has an empty INBOX. The file is read once at startup and never written. See [Storage](../guides/storage.md) for every key (UIDs, UIDVALIDITY, internal dates, special-use attributes, ACLs and more). +## Mail files on disk + +`--maildir` builds the mailbox tree from files instead of a storage file, which is handy for a large test corpus or a copy of a real mailbox: + +```bash +imapkit -p 1143 --maildir=./corpus +``` + +Two layouts are recognized: + +- **Maildir++**, a directory with `cur` and `new` (or with `.Name` maildir folders, as Dovecot and Courier keep them). The messages of `new` and `cur` go to INBOX, a `.Work` folder becomes the mailbox `Work` and `.Work.Projects` becomes `Work/Projects`, a missing parent is a `\Noselect` name. Flags come from the `:2,` info of the file names (`D`, `F`, `R`, `S`, `T`, keyword letters are skipped), messages in `new` are `\Recent`, and `tmp` is ignored. +- **A directory of `.eml` files**. They go to INBOX, and every subdirectory that holds `.eml` files somewhere below it becomes a mailbox of the same name. Other files and hidden entries are skipped. + +Messages get UIDs in file name order (numbers sorted as numbers), the modification time of a file is the internal date, and LF line breaks are converted to CRLF. Other mailboxes go into the `""` namespace with `/` as separator. Like a storage file, the files are read once at startup and never written: every change a client makes stays in memory. From code, `imapkit/lib/maildir` returns the same storage object, `imapkit({ storage: loadMaildir(dir) })`. + +All messages are kept in memory. The parsed MIME structure of the messages a client has fetched adds about a third to their size (a 710 MB corpus takes about 1 GB), so a large corpus may need a bigger heap than the default (`node --max-old-space-size=4096`). A JSON storage file can not hold that much: Node.js reads it into one string, which can not be larger than about 512 MB. + ## Script file `--script` loads [script rules](../faults/scripted-faults.md) that make the server misbehave on purpose. JSON rules use strings for `match` and `send`: diff --git a/src/maildir.ts b/src/maildir.ts new file mode 100644 index 0000000..d87711e --- /dev/null +++ b/src/maildir.ts @@ -0,0 +1,200 @@ +/** + * Builds a storage object from mail files on disk, for `imapkit --maildir=` and `imapkit/lib/maildir`. + * + * Two layouts are recognized: + * + * - Maildir++ (a directory with `cur` or `new`, or with `.Name` maildir folders): the messages of `new` and `cur` + * go to INBOX, every `.Name` / `.Name.Sub` subdirectory that is itself a maildir becomes the mailbox + * `Name` / `Name/Sub`. + * Flags come from the `:2,` info of the file name, messages in `new` are `\Recent`. + * - A plain directory: its `*.eml` files go to INBOX, every subdirectory with `*.eml` files somewhere below it + * becomes a mailbox of the same name (recursively). + * + * The internal date of a message is the modification time of its file (as Dovecot does for maildir), and line + * breaks are converted to CRLF. Files are read once, the server never writes to the directory. The module uses node:fs, so it is not part of the + * package root and the browser bundle. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { encodeMailboxName } from './mailbox-name.js'; +import { normalizeLineBreaks } from './mimeparser.js'; + +interface MaildirMessage { + raw: string; + flags: string[]; + internaldate: Date; +} + +interface MaildirFolder { + flags?: string[]; + messages?: MaildirMessage[]; + folders?: Record; + /** set on the namespace */ + separator?: string; +} + +/** the storage option: INBOX and, with folders, the "" namespace */ +export interface MaildirStorage { + [namespace: string]: MaildirFolder; + INBOX: MaildirFolder; +} + +/** maildir info flags (https://cr.yp.to/proto/maildir.html), lowercase letters are keywords and are skipped */ +const INFO_FLAGS: Record = { + D: '\\Draft', + F: '\\Flagged', + R: '\\Answered', + S: '\\Seen', + T: '\\Deleted' +}; + +// numbers in file names sort as numbers (`a9` before `a10`). One collator: localeCompare() with options sets up +// a new one for every comparison +const collator = new Intl.Collator('en', { numeric: true }); + +/** entries of a directory sorted by name, the hidden ones (`.Name`) only when asked for */ +function entries(dir: string, hidden = false): fs.Dirent[] { + return fs + .readdirSync(dir, { withFileTypes: true }) + .filter(entry => hidden || !entry.name.startsWith('.')) + .sort((a, b) => collator.compare(a.name, b.name)); +} + +function isDirectory(dir: string): boolean { + try { + return fs.statSync(dir).isDirectory(); + } catch { + return false; + } +} + +function isMaildir(dir: string): boolean { + return isDirectory(path.join(dir, 'cur')) || isDirectory(path.join(dir, 'new')); +} + +/** + * Reads a message as a binary string (one character per octet), the form the server keeps it in. Maildir files + * usually have LF line breaks, the server serves CRLF, so they are converted here once: otherwise the parsed + * form of every message would be kept next to the source + */ +function readMessage(file: string, flags: string[]): MaildirMessage { + const fd = fs.openSync(file, 'r'); + try { + return { raw: normalizeLineBreaks(fs.readFileSync(fd, 'latin1')), flags, internaldate: fs.fstatSync(fd).mtime }; + } finally { + fs.closeSync(fd); + } +} + +/** flags of a maildir file name, `:2,` */ +export function parseInfoFlags(name: string): string[] { + const info = /:2,([^:]*)$/.exec(name); + if (!info) { + return []; + } + return [...new Set(info[1])].filter(letter => INFO_FLAGS[letter]).map(letter => INFO_FLAGS[letter] as string); +} + +function readMaildirMessages(dir: string): MaildirMessage[] { + const messages: MaildirMessage[] = []; + for (const sub of ['cur', 'new']) { + const subdir = path.join(dir, sub); + if (!isDirectory(subdir)) { + continue; + } + for (const entry of entries(subdir)) { + if (entry.isFile()) { + const flags = parseInfoFlags(entry.name); + messages.push(readMessage(path.join(subdir, entry.name), sub === 'new' ? flags.concat('\\Recent') : flags)); + } + } + } + return messages; +} + +/** adds a folder at `names` below `folders`, missing parents become \Noselect names */ +function addFolder(folders: Record, names: string[], folder: MaildirFolder): void { + let level = folders; + names.slice(0, -1).forEach(name => { + level[name] = level[name] || { flags: ['\\Noselect'] }; + const parent = level[name]; + parent.folders = parent.folders || {}; + level = parent.folders; + }); + const name = names[names.length - 1] as string; + // a parent added before as \Noselect keeps the children it already has + folder.folders = Object.assign(level[name]?.folders || {}, folder.folders); + level[name] = folder; +} + +/** the `.Name` subdirectories of a Maildir++ root that are maildirs */ +function maildirFolders(dir: string): string[] { + return entries(dir, true) + .filter(entry => entry.isDirectory() && /^\.[^.]/.test(entry.name) && isMaildir(path.join(dir, entry.name))) + .map(entry => entry.name); +} + +function loadMaildirPlusPlus(dir: string, subfolders: string[]): MaildirStorage { + const storage: MaildirStorage = { INBOX: { messages: readMaildirMessages(dir) } }; + const folders: Record = {}; + subfolders.forEach(name => { + const names = name.slice(1).split('.'); + if (names.some(part => !part)) { + throw new Error('Invalid maildir folder name ' + name); + } + addFolder(folders, names, { messages: readMaildirMessages(path.join(dir, name)) }); + }); + if (subfolders.length) { + storage[''] = { separator: '/', folders }; + } + return storage; +} + +/** the *.eml files of a directory and its subdirectories as folders, subdirectories without any are left out */ +function loadEmlDirectory(dir: string): { messages: MaildirMessage[]; folders?: Record } { + const messages: MaildirMessage[] = []; + let folders: Record | undefined; + for (const entry of entries(dir)) { + const file = path.join(dir, entry.name); + if (entry.isDirectory()) { + const child = loadEmlDirectory(file); + if (child.messages.length || child.folders) { + folders = folders || {}; + // storage keeps modified UTF-7 names (RFC 3501 section 5.1.3) + folders[encodeMailboxName(entry.name)] = child; + } + } else if (entry.isFile() && /\.eml$/i.test(entry.name)) { + messages.push(readMessage(file, [])); + } + } + return folders ? { messages, folders } : { messages }; +} + +/** + * Builds the storage object of a Maildir++ directory or of a directory of .eml files + * + * @param dir Directory to read + * @returns Storage with INBOX and, for subfolders, the "" namespace with "/" as separator + */ +export function loadMaildir(dir: string): MaildirStorage { + if (!isDirectory(dir)) { + throw new Error('Not a directory: ' + dir); + } + // a Maildir++ root has cur and new, or at least maildir folders (an INBOX that was never delivered to) + const subfolders = maildirFolders(dir); + if (isMaildir(dir) || subfolders.length) { + return loadMaildirPlusPlus(dir, subfolders); + } + const { messages, folders } = loadEmlDirectory(dir); + const storage: MaildirStorage = { INBOX: { messages } }; + if (folders) { + if (Object.keys(folders).some(name => name.toUpperCase() === 'INBOX')) { + throw new Error('A subdirectory named INBOX conflicts with the INBOX of ' + dir); + } + storage[''] = { separator: '/', folders }; + } + return storage; +} + +export default loadMaildir; diff --git a/test/cli.test.ts b/test/cli.test.ts index e38a13e..9123daf 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -46,25 +46,37 @@ describe('imapkit command', { skip: !built && 'run npm run build first' }, () => }); } - /** sends A1 CAPABILITY after the greeting and resolves with everything received until the tagged response */ - function capability(port: number): Promise { + /** + * Sends tagged commands one at a time after the greeting, each once the previous one is answered, and resolves + * with everything received until the tagged response of the last one + */ + function commands(port: number, lines: string[]): Promise { return new Promise((resolve, reject) => { const socket = net.connect(port, 'localhost'); let received = ''; + let sent = 0; + const tagOf = (line: string) => line.split(' ')[0]; socket.on('data', chunk => { received += chunk.toString('binary'); - if (/^\* (OK|PREAUTH)/.test(received) && !received.includes('A1 ')) { - socket.write('A1 CAPABILITY\r\n'); + const answered = sent ? new RegExp('^' + tagOf(lines[sent - 1] as string) + ' ', 'm').test(received) : /^\* (OK|PREAUTH)/.test(received); + if (!answered) { + return; } - if (/^A1 /m.test(received)) { + if (sent === lines.length) { socket.end(); - resolve(received); + return resolve(received); } + socket.write(lines[sent++] + '\r\n'); }); socket.on('error', reject); }); } + /** sends A1 CAPABILITY after the greeting and resolves with everything received until the tagged response */ + function capability(port: number): Promise { + return commands(port, ['A1 CAPABILITY']); + } + it('starts a server that answers IMAP', async () => { const port = await freePort(); const child = spawn(process.execPath, [bin, '-p', String(port), '--plugin=IDLE,MOVE'], { stdio: ['ignore', 'pipe', 'inherit'] }); @@ -122,6 +134,43 @@ describe('imapkit command', { skip: !built && 'run npm run build first' }, () => } }); + it('loads the mailboxes of a directory with --maildir', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'imapkit-maildir-')); + fs.mkdirSync(path.join(dir, 'Work')); + fs.writeFileSync(path.join(dir, 'a.eml'), 'Subject: a\r\n\r\nA\r\n'); + fs.writeFileSync(path.join(dir, 'b.eml'), 'Subject: b\r\n\r\nB\r\n'); + fs.writeFileSync(path.join(dir, 'Work', 'c.eml'), 'Subject: c\r\n\r\nC\r\n'); + const port = await freePort(); + const child = spawn(process.execPath, [bin, '-p', String(port), '--maildir=' + dir], { stdio: ['ignore', 'pipe', 'inherit'] }); + try { + await listening(child); + const transcript = await commands(port, ['A1 LOGIN testuser testpass', 'A2 STATUS INBOX (MESSAGES)', 'A3 STATUS Work (MESSAGES)']); + assert.match(transcript, /^\* STATUS "?INBOX"? \(MESSAGES 2\)\r$/m); + assert.match(transcript, /^\* STATUS "?Work"? \(MESSAGES 1\)\r$/m); + } finally { + child.kill(); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + it('refuses --storage together with --maildir', () => { + assert.throws( + () => execFileSync(process.execPath, [bin, '-p', '0', '--storage=x.json', '--maildir=x'], { encoding: 'utf-8', stdio: 'pipe' }), + (err: { stderr: string }) => /--storage and --maildir can not be used together/.test(err.stderr) + ); + }); + + it('refuses a --maildir that is not a directory', () => { + assert.throws( + () => + execFileSync(process.execPath, [bin, '-p', '0', '--maildir=' + path.join(os.tmpdir(), 'imapkit-no-such-dir')], { + encoding: 'utf-8', + stdio: 'pipe' + }), + (err: { stderr: string }) => /Failed to start ImapKit: Not a directory/.test(err.stderr) + ); + }); + it('leaves plugins out with --quirk', async () => { const port = await freePort(); const child = spawn(process.execPath, [bin, '-p', String(port), '--plugin=IDLE,MOVE', '--quirk=no-move'], { stdio: ['ignore', 'pipe', 'inherit'] }); diff --git a/test/maildir.test.ts b/test/maildir.test.ts new file mode 100644 index 0000000..9768635 --- /dev/null +++ b/test/maildir.test.ts @@ -0,0 +1,153 @@ +// Loading storage from a Maildir++ directory or a directory of .eml files (src/maildir.ts, imapkit --maildir) + +import { describe, it, after } from 'node:test'; +import assert from 'node:assert'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { loadMaildir, parseInfoFlags } from '../src/maildir.js'; +import { setupServer } from './helpers/index.js'; + +/** writes files given as { 'relative/path': content } below a new temporary directory */ +function fixture(files: Record): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'imapkit-maildir-')); + for (const [name, content] of Object.entries(files)) { + const file = path.join(dir, name); + fs.mkdirSync(path.dirname(file), { recursive: true }); + if (name.endsWith('/')) { + continue; + } + fs.writeFileSync(file, content, 'latin1'); + } + return dir; +} + +const message = (subject: string): string => 'Subject: ' + subject + '\r\n\r\nHello\r\n'; + +describe('loadMaildir', () => { + const dirs: string[] = []; + const make = (files: Record): string => { + const dir = fixture(files); + dirs.push(dir); + return dir; + }; + after(() => dirs.forEach(dir => fs.rmSync(dir, { recursive: true, force: true }))); + + it('reads the flags of maildir file names', () => { + assert.deepEqual(parseInfoFlags('1700000000.M1P1.host:2,FRS'), ['\\Flagged', '\\Answered', '\\Seen']); + assert.deepEqual(parseInfoFlags('1700000000.M1P1.host:2,DTab'), ['\\Draft', '\\Deleted']); + assert.deepEqual(parseInfoFlags('1700000000.M1P1.host:2,'), []); + assert.deepEqual(parseInfoFlags('1700000000.M1P1.host'), []); + assert.deepEqual(parseInfoFlags('1700000000.M1P1.host:2,SS'), ['\\Seen']); + }); + + it('loads a Maildir++ directory with flags, new messages and folders', () => { + const dir = make({ + 'cur/1.host:2,S': message('one'), + 'cur/2.host:2,FR': message('two'), + 'new/3.host': message('three'), + 'tmp/4.host': message('in delivery'), + '.Sent/cur/1.host:2,S': message('sent'), + '.Work.Projects/new/1.host': message('project'), + '.Archive/cur/.hidden': message('hidden'), + '.NotAMaildir/': '' + }); + const mtime = new Date('2020-01-02T03:04:05Z'); + fs.utimesSync(path.join(dir, 'cur', '1.host:2,S'), mtime, mtime); + + const storage = loadMaildir(dir); + const inbox = storage.INBOX.messages || []; + assert.deepEqual( + inbox.map(m => [m.raw.split('\r\n')[0], m.flags]), + [ + ['Subject: one', ['\\Seen']], + ['Subject: two', ['\\Flagged', '\\Answered']], + ['Subject: three', ['\\Recent']] + ] + ); + assert.equal(inbox[0]?.internaldate.getTime(), mtime.getTime()); + + const folders = storage['']?.folders || {}; + assert.equal(storage['']?.separator, '/'); + assert.deepEqual(Object.keys(folders).sort(), ['Archive', 'Sent', 'Work']); + assert.deepEqual(folders.Archive?.messages, []); + assert.equal(folders.Sent?.messages?.length, 1); + // a parent that is not a maildir itself is a \Noselect name + assert.deepEqual(folders.Work?.flags, ['\\Noselect']); + assert.equal(folders.Work?.folders?.Projects?.messages?.[0]?.raw, message('project')); + }); + + it('loads a folder whose parent is a maildir too', () => { + const dir = make({ '.A.B/cur/1.host:2,': message('b'), '.A/cur/1.host:2,': message('a') }); + const folders = loadMaildir(dir)['']?.folders || {}; + assert.equal(folders.A?.flags, undefined); + assert.equal(folders.A?.messages?.length, 1); + assert.equal(folders.A?.folders?.B?.messages?.length, 1); + }); + + it('loads a directory of .eml files, subdirectories as mailboxes', () => { + const dir = make({ + 'b.eml': message('b'), + 'a10.eml': message('a10'), + 'a9.EML': message('a9'), + 'README.md': 'not a message', + 'assets/images/x.png': 'not a message', + 'Empty/': '', + '.hidden.eml': message('hidden'), + 'Work/x.eml': message('work'), + 'Work/Old/y.eml': message('old'), + 'Café & Co/z.eml': message('unicode') + }); + const storage = loadMaildir(dir); + assert.deepEqual( + storage.INBOX.messages?.map(m => m.raw.split('\r\n')[0]), + ['Subject: a9', 'Subject: a10', 'Subject: b'] + ); + const folders = storage['']?.folders || {}; + // storage names are modified UTF-7 (RFC 3501 section 5.1.3) + assert.deepEqual(Object.keys(folders).sort(), ['Caf&AOk- &- Co', 'Work']); + assert.equal(folders.Work?.folders?.Old?.messages?.length, 1); + }); + + it('keeps 8-bit octets as they are', () => { + const raw = 'Subject: =?utf-8?q?x?=\r\n\r\n\xe4\xf6\xfc\x00\xff\r\n'; + const dir = make({ 'a.eml': raw }); + assert.equal(loadMaildir(dir).INBOX.messages?.[0]?.raw, raw); + }); + + it('converts LF line breaks to CRLF', () => { + const dir = make({ 'cur/1.host:2,': 'Subject: lf\n\nline 1\nline 2\r\n' }); + assert.equal(loadMaildir(dir).INBOX.messages?.[0]?.raw, 'Subject: lf\r\n\r\nline 1\r\nline 2\r\n'); + }); + + it('refuses a missing directory and a subdirectory named INBOX', () => { + assert.throws(() => loadMaildir(path.join(os.tmpdir(), 'imapkit-no-such-dir-' + Date.now())), /Not a directory/); + const dir = make({ 'inbox/a.eml': message('a') }); + assert.throws(() => loadMaildir(dir), /INBOX/); + }); +}); + +describe('server with maildir storage', () => { + const dir = fixture({ + 'cur/1.host:2,S': message('one'), + 'new/2.host': message('two'), + '.Sent/cur/1.host:2,S': message('sent') + }); + after(() => fs.rmSync(dir, { recursive: true, force: true })); + + const ctx = setupServer(() => ({ storage: loadMaildir(dir) })); + + it('serves the messages, flags and folders', (t, done) => { + ctx.run(['A1 LOGIN testuser testpass', 'A2 LIST "" "*"', 'A3 SELECT INBOX', 'A4 FETCH 1:* (FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])'], output => { + const resp = output.toString('binary'); + assert.match(resp, /^\* LIST \([^)]*\) "\/" "Sent"\r$/m); + assert.match(resp, /^\* 2 EXISTS\r$/m); + assert.match(resp, /^\* 1 RECENT\r$/m); + assert.match(resp, /^\* 1 FETCH \(FLAGS \(\\Seen\) /m); + assert.match(resp, /^\* 2 FETCH \(FLAGS \(\\Recent\) /m); + assert.match(resp, /Subject: two/); + assert.match(resp, /^A4 OK/m); + done(); + }); + }); +});