# The mail library

Reading, receiving, checking and delivering mail, in Mote: the
[mail extension](../extensions/mail/README.md)'s library, beside its
[`mailSend`](mail.md). Ordinary Mote over [readers](data.md#large-files),
[`server listen`](back-end.md#accepting-connections-server-listen),
[`net.lookup`](back-end.md#dns-records) and the back end's
[signatures](data.md#signatures-with-a-key-pair). Back to the [map](README.md).

| File | | Where it runs |
|---|---|---|
| `pkg:mail/parse.mote` | A message (RFC 5322, MIME): its header, its parts at any depth, each body decoded a piece at a time. | page, `off fn`, back end |
| `pkg:mail/mbox.mote` | A mailbox file, a message at a time, with each one's place. | page, `off fn`, back end |
| `pkg:mail/address.mote` | Addresses taken apart, checked and compared; Punycode; the Public Suffix List and DMARC's organisational domain. | page, `off fn`, back end |
| `pkg:mail/server.mote` | An SMTP server on `server listen`: who mail is taken for, and what becomes of it, said by the program. | back end |
| `pkg:mail/auth.mote` | DKIM verified and signed, SPF, DMARC, ARC verified and sealed. | back end |
| `pkg:mail/deliver.mote` | Delivery to each recipient's mail exchangers, STARTTLS, MTA-STS, a queue tried again on a schedule, bounces made and read. | back end |

Each file is taken alone (`use "pkg:mail/parse.mote"` brings none of
`mailSend`'s settings with it). A program takes the extension as any
other:

```toml
[packages]
mail = "../mote/extensions/mail"
```

## Reading a message

```mote
use "pkg:mail/parse.mote"

// A message picked in the page: its header and the place of every part, read in a worker
// a piece at a time; each attachment written to a private file, never whole in memory.
off fn take(f: picked): string
  let r = fs.open(f)?
  let m = mailParse(r)?
  for p in m.parts
    if p.disposition == "attachment" && !p.container
      mailSave(r, p, `mail/${m.messageId}/${p.path}`)?
  r.close()
  return `${m.from[0]?.address ?? ""}: ${m.subject} (${m.parts.length} parts)`
```

**`mailParse(r, {end, quoting, textMax}?)`** reads a message from where the
reader `r` is (`fs.open` of a file, a file picked unread, bytes, a .zip's
entry) to `end` (unsaid: the reader's end), once, from start to end, holding
a piece of 64 KB and one line at a time. It gives a `MailParsed`:

| Field | |
|---|---|
| `headers` | Every field of the message's header, in order: `{name, value}`, the value unfolded (the line breaks of folding taken out) and read as UTF-8 where its bytes are (RFC 6532), each other byte as windows-1252. Encoded words are left in it: `mailWords(value)` reads them. `mailHeader(fields, name)` is the first of a name (`""` when none), `mailHeaderAll(fields, name)` all of them. |
| `from` `sender` `replyTo` `to` `cc` `bcc` | Address lists: `MailAddr {name, address, group}`, the display name's encoded words read, `group` the group the address was written in (`team: a@x, b@y;`). Several `To:` fields are one list. |
| `subject` | Its encoded words read. |
| `date` | Milliseconds UTC; `0` when there is none or it is not a date. |
| `messageId` `inReplyTo` `references` | Without angle brackets. |
| `parts` | Every part, in the order they stand, a container before its parts (below). |
| `text` `html` | The first `text/plain` and the first `text/html` that are not attachments, decoded and read in their character set. |
| `size` `bodyStart` | How many bytes the message is; where its body begins. |
| `problems` | What was wrong with the message and was taken anyway, in words. |

**A part**, `MailPart`:

| Field | |
|---|---|
| `path` | Where it is: `""` for the message itself; `"1"`, `"2"` for the parts of a multipart, `"1.2"` for the second part of the first; a message inside a message (`message/rfc822`) has its message as one part, `".1"`. |
| `depth` | How deep: 0 for the message. |
| `type` | Lower case. `text/plain` when the part says none (`message/rfc822` inside a `multipart/digest`). |
| `params` `charset` | The type's parameters, `{name, value}`, with RFC 2231's continuations joined (`name*0`, `name*1`) and its character sets read (`name*=utf-8''%E2%82%AC`); `charset` among them, lower case. |
| `disposition` `name` | `"inline"`, `"attachment"` or `""`; the file's name (the disposition's `filename`, else the type's `name`), its encoded words read (a sender's habit RFC 2231 does not allow). |
| `id` | Its `Content-ID`, without brackets: what `cid:` in the HTML names. |
| `encoding` | `"7bit"` `"8bit"` `"binary"` `"base64"` `"quoted-printable"`. |
| `headers` | The part's own fields. |
| `container` | It holds parts: a multipart, or a message inside. |
| `start` `end` | Where its body is in the source: its first byte and the one after its last (the line break before a boundary is the boundary's). |
| `lines` | How many lines its body is. |
| `text` `cut` | A text part that is not an attachment: its text, decoded, when its body is at most `textMax` bytes (1 MB unsaid); else `""` and `cut`. |

**A part's body** is read when it is asked for, from the same reader (or
another of the same source):

| Call | |
|---|---|
| `mailPiece(r, part, before?, quoting?, size?)` | The next piece of the body, decoded from its transfer encoding: `{data, at, rest, done}`. `before` is the piece before (none for the first); about `size` bytes of the source a piece (64 KB). A file `seek`s there at no cost; a reader that inflates as it reads goes back by reading again from its start. |
| `mailSave(r, part, path, quoting?)` | The body, decoded, written to a file a piece at a time ([`fs.writer`](data.md#writing-as-it-is-made)): how many bytes. |
| `mailBody(r, part, quoting?)` | The body as bytes, whole: for one that is small. |
| `mailText(r, part, quoting?)` | A text part's text, however long, read in its character set. |
| `mailParseBytes(b, o?)` | A message given as bytes, whole. |
| `mailDecode(b, charset)` | Bytes in a character set, as a part's text is read: the label's set, else UTF-8 where it is, else windows-1252. |
| `mailWords(text)` · `mailParams(text)` · `mailAddrs(text)` · `mailDateRead(text)` · `mailIds(text)` | A header's pieces: encoded words read; `type; a=b` and its parameters; an address list; a date; message ids. |

**Mail as senders write it is taken**, and what was put right is in
`problems`: line ends of a bare LF; a boundary never closed (its part ends
at the message's end); a part after the closing boundary; a multipart with
no boundary (read as text); a header line that is no field (the body
begins there); encoded words in quoted parameters and inside words;
encoded words that cut a character in two (the bytes of words next to each
other are joined before they are read); base64 with no padding, with
letters after its padding, with other characters among it; quoted-printable
with spaces at its lines' ends or an `=` that is not followed by hex;
a character set nobody knows (read as UTF-8, else windows-1252); raw 8-bit
bytes in a header; an mbox's "From " line before the header.

**Character sets.** A part's text is read with `b.text(label)`
([language.md](language.md#bytes)): UTF-8 and UTF-16 by the host's own
decoder; the 28 single-byte sets of the WHATWG Encoding Standard
(ISO-8859-1 to -16, windows-1250 to -1258, KOI8-R, KOI8-U, macintosh, IBM866,
…) by tables made from the standard's own files; the multi-byte ones
(Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5 with Hong Kong's
extensions, EUC-KR) by the charsets battery, the standard's own decoders and
index files ([language.md](language.md#the-legacy-multi-byte-sets)). All of
them the same in a page, a worker and the back end, malformed bytes too:
a part in Big5 reads the same on the page that showed it and in the back end
that indexed it. Only a label the standard does not know is read as UTF-8,
else windows-1252 (`mailDecode`). A program that parses mail carries the
battery (its labels come from the messages), and fetches it on the page
before it parses there.

**The same structure everywhere.** The page, a worker and the back end give
one message the same `MailParsed`, byte for byte, its bodies' bytes too:
`tests/mail_lib/app.mote` parses a message of nested parts (mixed, related,
alternative), text in windows-1251 and ISO-8859-2, a picture by `cid:`, a
message inside in KOI8-R, a file named by RFC 2231, and parts in Shift_JIS
and in Big5 (with a malformed pair, which a browser's own decoder reads
otherwise) in the three places and compares the three (`tests/all.sh
real_mail_lib`).

## A mailbox file

```mote
use "pkg:mail/parse.mote"
use "pkg:mail/mbox.mote"

shape Read
  offset: number
  count: number

// Every message of an mbox, from where an earlier read stopped, in a worker.
off fn read(f: picked, from: number): Read
  let r = fs.open(f)?
  r.seek(from)?
  let n = 0
  let m = mailMboxNext(r)?
  while m != none
    let parsed = mailParseBytes(m.data)?
    n += 1
    m = mailMboxNext(r)?
  let at = r.at
  r.close()
  return {offset: at, count: n}
```

**`mailMboxNext(r, {quoting, data}?)`** is the next message from where `r`
is, or `none` at the end: `MailMbox {start, from, bodyAt, end, data}`. A
message begins at a line that begins `From `, which is the mbox's, not the
message's (`from` is what that line says after it: the envelope's sender
and a date); `bodyAt` and `end` are where the message is (the line break
before the next `From ` is the mbox's too); `data` is the message, its
quoting taken back. `r` is left at the next message's `From ` line, so
`r.at` is the offset to keep and `seek` to, to go on later.

- **`quoting`**: `"mboxrd"` (unsaid): every line of `>`s and `From ` lost one
  `>` when it was written, `>From ` was `From `, `>>From ` was `>From `.
  `"mboxo"`: only `>From ` is taken back (the older form, which cannot tell
  the two apart). `""`: as it is.
- **`data: false`**: only where the message is, for one too large to hold:
  then `r.seek(m.bodyAt)` and `mailParse(r, {end: m.end, quoting: "mboxrd"})`.
  With `data` (unsaid), a message of more than 64 MB fails, `"toobig"`.
- `mailMboxQuote(message)` quotes a message as mboxrd writes it, for a
  program that writes one; `mailMboxUnquote(bytes, quoting)` takes it back.
- A message is held at a time, and the reader's piece: an mbox of
  gigabytes is read with the page's memory where it began.
  `tests/all.sh real_mail_lib` makes an mbox of 5 GB (1 GB on a disk with
  less than 12 GB free) and reads it in a worker, every message parsed, in
  about a minute: the tab's process grew by about 170 MB and stayed there
  (`tests/out/mail_lib-memory.txt` has the numbers of each run).

## Addresses

```mote
use "pkg:mail/address.mote"

fn sameSender(a: string, b: string): bool = mailAddrSame(a, b)
fn orgOf(domain: string): string = mailOrgDomain(domain)
```

| Call | |
|---|---|
| `mailAddrParse(text)` | One address of a header's words (`"Ada <ada@example.com>"`, `"ada@example.com (Ada)"`): `MailAddr?`. `mailAddrs(text)` is a list of them. |
| `mailAddrSplit(address)` | `{local, domain}`: before and after the last `@`. |
| `mailAddrValid(address)` | Whether it is an address: dot-atoms or a quoted local part, 64 and 255 at most (RFC 5321 4.5.3.1), a domain of labels (any Unicode a name may have, checked in its ASCII form) or an address in brackets. UTF-8 in the local part is RFC 6531's. |
| `mailAddrSame(a, b)` | Whether two are one mailbox: the domains alike in ASCII and lower case, the local parts alike but for case. |
| `mailAddrAscii(address)` | The domain in ASCII, lower case; the local part as written: what to keep and to send to a server that does not say SMTPUTF8. |
| `mailDomainAscii(domain)` · `mailDomainUnicode(domain)` | A domain's labels as `xn--` and their Punycode, or back. The Unicode is lowered and put in NFC first, and the dots of other scripts (`。．｡`) are dots: what IDNA 2008 asks of a name as written. UTS 46's wider mapping (full-width letters, its special cases) is not done. |
| `mailPunyEncode(label)` · `mailPunyDecode(text)` | RFC 3492 itself; `none` for text that is not Punycode. |
| `mailPublicSuffix(domain)` | The part a registry gives names under (`co.uk`, `github.io`), by the Public Suffix List: its longest rule that matches, an exception's one label less, the last label when none does. |
| `mailOrgDomain(domain)` | DMARC's organisational domain (RFC 7489 3.2): the public suffix and one label more; a public suffix is its own. |

**The Public Suffix List** ships with the extension, in
`extensions/mail/psl.mote`: both its sections (ICANN's and the private
domains', as DMARC's readers take them), 10,513 rules in a text of 125 KB,
looked up where it stands (no table is built at start). It is made by
`node tools/psl-table.mjs` from `public_suffix_list.dat` at a pinned commit
of github.com/publicsuffix/list, held to its SHA-256; the commit and the
hash are written at the top of the file. To take a newer list, set the
commit in the script and run it (it says the new hash, to be written there
once the change is looked at). The list is under the Mozilla Public
License 2.0. A page that uses `mailOrgDomain` carries the table.

Tested in `extensions/mail/tests_address.mote` (`mote test`, in
`tests/all.sh real_mail_lib`): Punycode both ways against every sample of
RFC 3492 section 7.1, written into the test as the RFC gives them; domains;
addresses; the list's wildcards, exceptions and private section.

## Receiving: an SMTP server

```mote
use "pkg:mail/server.mote"

// Mail for example.com is taken; a message is parsed from the file it was written to.
fn smtpRecipient(s: SmtpSession, to: string): SmtpAnswer
  if mailAddrSplit(to).domain.toLowerCase() == "example.com" return smtpAccept()
  return smtpRefuse("5.7.1 Relaying is not done here")

fn smtpMessage(m: SmtpMessage): SmtpAnswer
  let r = smtpOpen(m)?
  let parsed = mailParse(r)?
  r.close()
  fs.move(m.path, `inbox/${m.id}.eml`)?
  return smtpAccept()

server listen smtp(c) port=env("SMTP_PORT") cert=env("TLS_CERT") key=env("TLS_KEY") timeout=300000 maxIp=10 refuse="421 4.7.0 Too many connections\r\n" limit 60 per minute by ip
  smtpServe(c)?
```

**`smtpServe(c)`** is a whole session on a connection a
[`server listen`](back-end.md#accepting-connections-server-listen) block was
handed: the greeting, then each command, until `QUIT`, a failure of the
connection, or the back end stopping (`421`, then closed). ESMTP, with
`SIZE` (RFC 1870), `PIPELINING` (RFC 2920: commands sent all at once are
read and answered in order), `8BITMIME` (RFC 6152), `SMTPUTF8` (RFC 6531),
`CHUNKING` (`BDAT`, RFC 3030), `ENHANCEDSTATUSCODES` (RFC 2034) and
`STARTTLS` (RFC 3207: with the listener's certificate; what was sent in the
clear after it is let go, and everything said before is forgotten).

**What the program says** (`wants fn`s: [language.md](language.md#what-a-package-wants-of-its-taker)):

| | |
|---|---|
| `fn smtpRecipient(s: SmtpSession, to: string): SmtpAnswer` | Required. Each `RCPT TO`: `smtpAccept()` (250), `smtpRefuse(text?)` (550, or any 5xx), `smtpDefer(text?)` (451, or any 4xx). Nothing is taken that it does not accept: a server that took everything would be an open relay. A failure is a 451. |
| `fn smtpMessage(m: SmtpMessage): SmtpAnswer` | Required. A message taken whole: `{id, session, from, to, path, size, at, spool, data, key}`. Its bytes, a `Received:` field first, are where the [spool](#where-an-arriving-body-is-kept-the-spool) kept them: `smtpOpen(m)?` is a reader of them whichever it is. A file (`m.path`) is deleted once this has answered, so `fs.move` it (or read what is wanted) before. What it answers is what the client is told: a 2xx takes the message, a 4xx asks for it again later, a 5xx refuses it. A failure is a 451, and a line of the log. |
| `fn smtpSpool(): string` · `fn smtpSpoolKey(): json` | Optional. Where a body is kept as it arrives: `SMTP_SPOOL`, else `"file"`; and the key of a sealed one (unsaid: a key of each message's own). [Below](#where-an-arriving-body-is-kept-the-spool). |
| `fn smtpSender(s: SmtpSession, from: string): SmtpAnswer` | Optional (unsaid: all). `MAIL FROM`, before anything is taken: SPF goes here. `from` is `""` for a bounce (`<>`). |
| `fn smtpName(): string` | The name it greets with: `SMTP_NAME`, else `mote.localhost`. |
| `fn smtpMax(): number` | The largest message, in bytes: `SMTP_MAX`, else 25 MB. Said in `EHLO`; `MAIL FROM … SIZE=` past it is refused at once; a body past it is read to its end, let go, and refused (552). |
| `fn smtpTls(): bool` · `fn smtpRequireTls(): bool` | Whether `STARTTLS` is offered (`SMTP_TLS=off` for a listener with no certificate); whether `MAIL` waits for it (`SMTP_REQUIRE_TLS=1`: a submission port's rule, never port 25's). |

`SmtpSession` is `{remote, port, helo, ehlo, tls, from, utf8, body, size, to}`:
who is connected, what they said they are, and the envelope so far.

- **The body is never held whole** (but in memory, when the program says
  so: below). `DATA`'s lines are read one at a time
  (as bytes: 8-bit text is kept as it came), their dots taken back (RFC 5321
  4.5.2) and written to the file as they come; `BDAT`'s chunks are read 64 KB
  at a time. A client that leaves mid-message leaves nothing behind.
- **Refused before the program is asked**: a command before `EHLO` or out of
  its order (503); a command line over 4096 bytes (500, and the session goes
  on); a parameter it does not know (555); an address that is not one (553),
  or in UTF-8 without `SMTPUTF8` (553 5.6.7); more than 100 recipients (452).
  Ten bad commands close the session.
- `VRFY` and `EXPN` say nothing (252). There is no `AUTH`: this is a server
  that receives (an MX), not one people send through.
- A connection's limits (how many at once, from one address, how fast) are
  the listener's: `max=`, `maxIp=`, `limit … by ip`, `timeout=`.

Tested by `tests/all.sh real_mail_server` (`tests/mail_server/app.mote`,
`tests/mail_server.drive.mjs`): what `EHLO` offers; eight commands sent at
once and each recipient's answer (taken, refused, deferred, not ours); a
dot-stuffed line; every command out of order or wrong; a line of 10,000
bytes; a body over `SIZE`; `BDAT` in two chunks; `STARTTLS` with commands
sent in the clear after it; a client gone mid-message (nothing left in the
spool); one that says nothing (421 after the listener's `timeout`); and the
mail extension's own SMTP client (`MAIL_PROVIDER=smtp`, which requires
`STARTTLS`) sending a message with an attachment, parsed as it was taken.

### Where an arriving body is kept: the spool

```mote
use "pkg:mail/server.mote"
use "pkg:mail/auth.mote"

fn smtpRecipient(s: SmtpSession, to: string): SmtpAnswer
  if mailAddrSplit(to).domain.toLowerCase() == "example.com" return smtpAccept()
  return smtpRefuse()

// No byte of a message from outside is on the disk unsealed: the spool is sealed as it is
// written, and what is kept is that file, moved, still sealed under the program's key.
fn smtpSpool(): string = "sealed"
fn smtpSpoolKey(): json = crypto.aes.key(bytes.hex(secret("SPOOL_KEY"))?)?

fn smtpMessage(m: SmtpMessage): SmtpAnswer
  let r = smtpOpen(m)?
  let dkim = mailDkimVerify(r)?
  r.seek(0)?
  let parsed = mailParse(r, {textMax: 0})?
  r.close()
  log.info("taken", {subject: parsed.subject, dkim: dkim.map(d => d.result).join(" ")})
  fs.move(m.path, `inbox/${m.id}.sealed`)?
  return smtpAccept()

server listen smtp(c) port=env("SMTP_PORT") cert=env("TLS_CERT") key=env("TLS_KEY")
  smtpServe(c)?
```

**`fn smtpSpool(): string`** says where a body is kept from its first byte
until `smtpMessage` has answered (unsaid, the setting `SMTP_SPOOL`, else
`"file"`):

| | |
|---|---|
| `"file"` | A plain file of the data folder, `smtp/spool/<id>.eml`, written as it comes (as it has always been). |
| `"sealed"` | The same file, [sealed](data.md#sealed-files) as it is written (`fs.writer(path, {seal: key})`): AES-256-GCM a chunk of 64 KiB at a time, the chunk being filled the one thing in memory in the clear. No byte of the message is on the disk unsealed at any moment. |
| `"memory"` | Bytes in memory, never on the disk, up to `smtpMax()` (the `SIZE` said in `EHLO`): a body past it is read to its end and let go as it comes (what was held is let go at once), and refused, 552, as in the other two: never written to the disk instead. The message is `m.data`. |

Another word is a 451 for each message (and a line of the log).

**The key of a sealed spool** is the program's `fn smtpSpoolKey(): json`:
32 bytes, or what `crypto.aes.key` gave (a key kept in a
[secret](back-end.md#secrets), as above, or made from one by
`crypto.hkdf`). It is asked for as each message begins, and again by
`smtpOpen`, and never kept in `SmtpMessage`. Unsaid (`none`), each message
has a key of its own, made at random as it begins and held, as a key the
host keeps, in `m.key` for as long as the message is handled: then nothing
can read the file once the message is let go, whoever has the disk, and
`smtpOpen(m)` is the one way to read it meanwhile (the program cannot keep
that file to read later: with its own key, it can).

**Reading it.** `smtpOpen(m)?` is a [reader](data.md#large-files) of the
message whichever the spool: the file, decrypted a chunk at a time as it is
read where it is sealed; the bytes where it is in memory. `mailParse`,
`mailPiece`, `mailDkimVerify`, `mailDmarc` and `mailArcVerify` read through
it as they read any reader: what each holds in the clear is its piece (64 KB)
and a line, and a sealed reader its chunk. None of them writes a file of its
own; the library's one call that writes, `mailSave(r, part, path)`, writes
where the program says, plain: to keep a part sealed, write its pieces
(`mailPiece`) with `fs.writer(path, {seal: key})`. Beyond a chunk, what is
in memory in the clear is what the program asks for: `mailParse` keeps a
text part of at most `textMax` (1 MB unsaid) decoded in `text`, `html` and
`parts[].text` (`{textMax: 0}` keeps none); `mailBody` and `mailText` give a
body whole.

**After the answer.** The spool's file is deleted once `smtpMessage` has
answered, whatever it answered (and at once for a client that leaves
mid-message, or a body past `SIZE`). A sealed file is deleted, not
overwritten first: every byte it ever had on the disk was sealed, so there
is nothing in the clear to overwrite (and on a disk that is an SSD or a
journalling file system, overwriting in place reaches nothing anyway). A
crash, or a back end stopped mid-message, leaves at most a sealed file in
`smtp/spool/`, which no reader takes without its key and, lacking its last
chunk, none takes at all (`"damaged"`); clear `smtp/spool/` as the back
end starts if such leftovers matter. A message in memory is let go once it
is answered (JavaScript gives no way to wipe what was let go: it is gone
when the memory is used again).

Tested by `tests/all.sh real_mail_spool` (`tests/mail_spool/app.mote`,
`tests/mail_spool.drive.mjs`; the sealed files beneath it in
`tests/sealed/app.mote`): the program run three times, sealed under its own
key, sealed with a key of each message's own, and in memory with `SIZE`
just over 20 MB. In each, a message of 20 MB signed with DKIM (Ed25519, its
key published by a stand-in DNS server) sent by `DATA`, the data folder read
again and again while it goes, every file searched for pieces of the body
(a pause half way until a sealed spool file of half the message is there);
then 3 MB by `BDAT` in three chunks. Each is taken, `mailDkimVerify` through
`smtpOpen` passes, the body the parser decodes through it has the hash of
what was sent, and no piece of the body is ever found in the clear, during
or after (in memory, no spool file is ever there at all). The file kept
under the program's key is opened by the drive with Node's own AES-GCM, by
the format as [written down](data.md#sealed-files), and is the `Received:`
field and the message as sent; spoilt five ways (a bit changed, the last
chunk cut off, cut in a chunk, two chunks swapped, one dropped) the program
reads each as `"damaged"`. In memory, 22 MB by `DATA` and by `BDAT` are
refused, 552, with nothing on the disk. The key is not in the log.

## Who sent it: DKIM, SPF, DMARC, ARC

```mote
use "pkg:mail/server.mote"
use "pkg:mail/auth.mote"

fn smtpRecipient(s: SmtpSession, to: string): SmtpAnswer
  if mailAddrSplit(to).domain.toLowerCase() == "example.com" return smtpAccept()
  return smtpRefuse()

// Each message checked as it is taken; a DMARC policy of reject is kept to; the results are
// written first, as a receiver writes them.
fn smtpMessage(m: SmtpMessage): SmtpAnswer
  let spf = mailSpf(m.session.remote, m.from, m.session.helo)?
  let r = fs.open(m.path)?
  let dkim = mailDkimVerify(r)?
  let dmarc = mailDmarc(r, spf, dkim)?
  let arc = mailArcVerify(r)?
  r.close()
  if dmarc.disposition == "reject" && arc.result != "pass" return smtpRefuse("5.7.1 DMARC says this is not from who it says")
  let w = fs.writer(`inbox/${m.id}.eml`)?
  w.write(mailAuthResults("mx.example.com", spf, dkim, dmarc, arc))?
  w.write(fs.bytes(m.path)?)?
  w.close()?
  return smtpAccept()

server listen smtp(c) port=env("SMTP_PORT") cert=env("TLS_CERT") key=env("TLS_KEY")
  smtpServe(c)?
```

The back end's: each asks DNS ([`net.lookup`](back-end.md#dns-records)) and
DKIM checks signatures with [`crypto.verify`](data.md#signatures-with-a-key-pair).
Each takes `MailDns` last, `{timeout, servers, now}`: `servers` is the
resolver to ask (unsaid, the machine's), `now` the moment in seconds that
`x=` is judged by. A lookup that gets no answer is a `temperror`, never
"there is no record".

**DKIM.** `mailDkimVerify(r, o?)` checks every `DKIM-Signature` of the
message from where `r` is (ten at most): `MailDkimResult {result, why,
domain, selector, identity, alg, signed, partial}`, `result` one of
`pass`, `fail` (the body or the fields are not what was signed; expired),
`neutral`, `temperror` (DNS), `permerror` (a signature or key that is not
right, a key revoked or not there). `rsa-sha256` and `ed25519-sha256`
(RFC 8463); `rsa-sha1` is refused, as RFC 8301 says. `simple` and `relaxed`
for the header and the body, `l=` (`partial`: part of the body was not
signed), `x=`, `t=s` and `i=`. The body is read a line at a time and hashed
as it is read (SHA-256 in Mote, a piece at a time: `mailShaStart`,
`mailShaAdd`, `mailShaEnd`), never held whole. A key record a resolver
hands as several records (Bun's does, for one of several strings) is joined
again.

`mailDkimSign(r, {domain, selector, key, alg, headers, canon, identity,
at, expires})` gives the `DKIM-Signature` field to put first:
`relaxed/relaxed` and `rsa-sha256` unsaid; `key` is PEM (PKCS #8, or PKCS #1
for RSA) or a JWK's text (an Ed25519 key: `{"kty":"OKP","crv":"Ed25519","d":…,"x":…}`),
kept in a [`secret`](back-end.md#secrets); `headers` unsaid are From, To,
Cc, Subject, Date, Message-ID and the rest a reply and a list need, those
the message has.

**SPF.** `mailSpf(ip, from, helo, o?)`: `{result, domain, why, lookups}`,
`result` one of `pass` `fail` `softfail` `neutral` `none` `temperror`
`permerror`, for MAIL FROM's domain, or HELO's for a bounce. Every
mechanism (`all` `include` `a` `mx` `ptr` `ip4` `ip6` `exists`, with prefix
lengths), `redirect=`, the qualifiers, the macros (`%{s l o d i p h v}` with
a count of labels, `r` and delimiters, `%%` `%_` `%-`; `%{p}` is
`unknown`, as RFC 7208 lets it be), the limit of 10 lookups, of 2 that find
nothing (void lookups) and of 10 MX names; two records are a `permerror`.

**DMARC.** `mailDmarc(r, spf, dkim, o?, roll?)` reads the message's From
(one address, else `permerror`) and gives `MailDmarcResult {result, domain,
policyDomain, policy, disposition, pct, spfAligned, dkimAligned, record,
why}`. The record is the From domain's, else its organisational domain's
(`mailOrgDomain`, the Public Suffix List); `sp=` for a subdomain; `adkim=`
and `aspf=` relaxed (the organisational domains alike) or strict (the
domains alike); `pct=`: when the draw (`roll`, 0 to 99; unsaid, random) is
not under it, `reject` is taken as `quarantine` and `quarantine` as `none`
(RFC 7489 6.6.4); `disposition` is what to do. `mailDmarcFor(domain, …)`
is the same for a From domain already read. Reports (`rua=`, `ruf=`) are
not sent.

**ARC.** `mailArcVerify(r, o?)`: `{result, sets, failed, why, results}`:
the chain's sets whole and in order (50 at most), each `cv=` as it should
be, the latest `ARC-Message-Signature` checked as DKIM checks a signature,
every `ARC-Seal` over the sets up to it; `results` is the latest
`ARC-Authentication-Results`, what the last hop saw. `mailArcSeal(r,
{domain, selector, key, alg, results, server, at, cv})` gives the three
fields of the next set, for a hop that changes a message (a list) and
passes it on: give it `cv`, the chain as it arrived (`mailArcVerify` before
the change).

`mailAuthResults(server, spf, dkim, dmarc, arc)` writes an
`Authentication-Results` field (RFC 8601).

**Tested** in `extensions/mail/tests_auth.mote` (`mote test`, in
`tests/all.sh real_mail_lib`), DNS answered by the test itself (`given
dns`, [testing.md](testing.md#tests-in-the-program)):

- **RFC 8463**'s signed message passes, both its `ed25519-sha256` and its
  `rsa-sha256` signature, with its two keys as its appendix A.2 gives them;
  a changed word of its body fails the body hash, a changed field the
  signature; spaces and case changed in transit still pass (relaxed).
- **RFC 6376**'s example (appendix A.2, the key of appendix C) does **not**
  pass as printed, and cannot: it says `c=simple/simple`, and its `bh=` is
  the hash of its body canonicalised *relaxed* (the test shows both hashes;
  the RFC's errata say so of the example). Its canonicalisation examples
  (section 3.4.6) hold, and the same message signed again with the
  appendix's key, `simple/simple`, passes.
- Signing with both algorithms and each of the four canonicalisations,
  checked by the verifier; `x=`; a key revoked, absent, or unanswered.
- SPF: include, redirect, a macro of reversed labels, a, mx, ip4, ip6,
  qualifiers, two records, none, no answer, more than 10 lookups, more than
  2 void ones, a bounce checked by HELO's name, the macros of RFC 7208 7.4.
- DMARC: aligned by SPF, by DKIM's subdomain, not aligned; a subdomain with
  the organisational domain's record and its `sp=`; strict alignment;
  `pct=` drawn and not; no record, a bad one, no answer; a From of two
  addresses.
- ARC: a chain of two sets (RSA, then Ed25519) sealed here and checked,
  the second hop having changed the subject; a change after the last seal;
  a set taken out. (Checked against this library's own sealing: no
  published set of ARC vectors is run.)

## Sending to the world

```mote
use "pkg:mail/deliver.mote"

// A message written to a file and queued: tried at once, and again later for whoever could
// not be reached; signed first with the domain's DKIM key.
server fn send(to: string, subject: string, text: string): string requires signedIn
  let body = `From: shop@example.com\r\nTo: ${to}\r\nSubject: ${subject}\r\nDate: ${mailDateOf(now())}\r\nMessage-ID: <${uid()}@example.com>\r\n\r\n${text}\r\n`
  let field = mailDkimSign(fs.open(bytes(body))?, {domain: "example.com", selector: "mote1", key: secret("DKIM_KEY")})?
  let path = `outbox/${uid()}.eml`
  fs.write(path, field + body)?
  return mailQueue("shop@example.com", [to], path)?

// Told when every recipient is settled: a bounce to the sender for those that failed.
fn mailDelivered(q: MailQueued, results: MailRecipient[]): bool
  let failed = results.filter(r => r.status != "delivered")
  if failed.length > 0 log.warn("not delivered", {to: failed.map(r => `${r.to}: ${r.code} ${r.text}`).join("; ")})
  return true
```

**`mailDeliver(from, to, path, o?)`** sends a message (a file of the data
folder: its header and body as they are to go) to each recipient, now, and
gives what became of each: `MailRecipient {to, status, code, text, host,
tls, sts}`, `status` one of `delivered`, `deferred` (try again later) and
`bounced` (it will never be). Recipients are grouped by domain, and for each:

- **The mail exchangers** (`mailExchangers(domain, o?)`): its MX records in
  order of preference; the domain itself when it has none (RFC 5321 5.1);
  none for a null MX (RFC 7505: bounced, 556). Each in turn, until one
  answers: a host with no address, no connection, or a greeting that is not
  2xx (a 421 "too busy") passes to the next; once one answers, what it says
  of each recipient is what happens (a 5xx bounces, a 4xx defers).
- **STARTTLS whenever it is offered**, its certificate not asked about
  (opportunistic: what is sent is hidden from all but someone sitting
  between); a server that offers none gets the message in the clear.
- **MTA-STS** (RFC 8461): `_mta-sts.<domain>`'s TXT record, then the policy
  from `https://mta-sts.<domain>/.well-known/mta-sts.txt` (no redirects, 64 KB
  at most), kept in the model `MailSts` for its `max_age` and fetched again
  when the record's `id` changes (and kept to when DNS does not answer).
  `enforce`: only the MX hosts the policy names are tried, each only over
  TLS with a certificate good for its name (else deferred); `testing`:
  delivered as ever, and what the policy would have refused said in `sts`.
- `SIZE`, `8BITMIME` and `SMTPUTF8` are said where the server offers them; a
  message with an address in UTF-8 to a server that does not take SMTPUTF8
  is bounced (553). The file is sent a line at a time, its dots doubled.
- Options, `MailDeliverOptions`: `helo` (`MAIL_HELO`, else `SMTP_NAME`),
  `timeout` (60 s; DATA's end waits ten times as long), `servers` (a
  resolver to ask), `via` (`[{host, address, port}]`: hosts reached another
  way: a smart host, or a test's own servers), `ca`, `stsBase` (a test's
  place for the policies).

**The queue.** `mailQueue(from, to, path)` keeps the message in the model
`MailQueued` and tries it at once in a [`job fn`](back-end.md#later-job-fn)
(`mailDeliverLater`): whoever was deferred is tried again after 5 and 15
minutes, then 1, 2, 4, 8 and 16 hours, then a day at a time (`MAIL_RETRY`
says other times, in ms, or the program's `fn mailRetrySchedule():
number[]`); past the last, those still deferred are bounced ("given up
after n tries"). Once every recipient is settled the row goes, and the
message with it, and the program's `fn mailDelivered(q: MailQueued,
results: MailRecipient[]): bool` is told. `fn mailDeliverOptions():
MailDeliverOptions` gives the queue's options.

**The queued message is a stored file**, `MailQueued.message` (a
[`file`](models.md#files) field, kept with `files.keep`), and the file at
`path` is taken away as it is queued. So a try is made by whichever back
end takes the job, from an empty data folder too, and with
[`MOTE_FILES`](back-end.md#stored-files-in-an-object-store) the message is
in the object store, not on one machine's disk; the database's backups and
`mote migrate --to postgres` carry it as any stored file. A file field
rather than bytes on the row: a message with attachments may be tens of
MB, which a row would carry into every read of the queue, and a store
keeps it off the database. Each try writes it to `mail-out/<id>.eml` of
the trying back end's data folder for the length of the try (the message
is read whole once a try, as `files.bytes` reads). Rows queued by an
earlier build, whose message is only the file at `path`, are carried by a
`migrate` block as the new build first starts on the folder (where the
file is on that back end's disk); one not carried is still tried from
`path`. Tested by `tests/all.sh real_mail_handover`: a row queued as
before, carried and delivered; and two back ends at one Postgres and one
object store, the second, with an empty data folder, taking the try the
first could not finish.

**Bounces** (RFC 3464). `mailDsnRead(r)` reads one (a `multipart/report` of
`message/delivery-status`) into `MailDsn {reportingMta, arrival,
recipients, messageId, subject}`, each recipient `{recipient, original,
action, status, diagnostic, remoteMta}`, and the returned message's
Message-ID and Subject (from `message/rfc822` or `text/rfc822-headers`);
`none` for a message that is not one. `mailDsnMake(server, q, failed,
returnedHead)` writes one, to the sender of a queued message, for those it
failed (a give-up is status 4.4.7).

Tested by `tests/all.sh real_mail_deliver` (`tests/mail_deliver/app.mote`,
`tests/mail_deliver.drive.mjs`): three SMTP servers of the program's own on
loopback (one with STARTTLS, one that turns everything away, one with no
STARTTLS) and a stand-in DNS server (`tests/dns_standin.mjs` with
`tests/mail_deliver/dns.json`, asked through `servers`): the first MX
turning a message away and the next taking it (one recipient refused);
a domain with no MX; a null MX; MTA-STS enforced with no MX it names, with
one it names and its certificate checked, with one that has no STARTTLS,
in testing, and a policy fetched once and kept; a domain with no address;
the queue tried at once, one recipient deferred and taken on the next try,
another given up on after the schedule, and the bounces made for them read
back. A real bounce's form (Postfix's, written by hand) is read in
`extensions/mail/tests_deliver.mote`.

## Checking it with the real world

What the tests here cannot do needs a domain, a machine the internet
reaches on port 25, and mail accounts at Gmail, Outlook.com and Fastmail.
Below, `example.com` is your domain, `203.0.113.10` the machine's address
and `mx.example.com` its name: put yours in their place.

**1. The machine.** A server whose provider lets port 25 through both ways
(many clouds block it until asked: AWS, Google Cloud, Azure and DigitalOcean
do), with a reverse DNS (PTR) record for `203.0.113.10` that says
`mx.example.com` (set at the provider). A certificate for `mx.example.com`
(`certbot certonly --standalone -d mx.example.com`). Bun may listen on 25 as
a user that is not root after `sudo setcap 'cap_net_bind_service=+ep'
"$(command -v bun)"`.

**2. DNS records.**

```text
mx.example.com.               A     203.0.113.10
example.com.                  MX    10 mx.example.com.
example.com.                  TXT   "v=spf1 ip4:203.0.113.10 -all"
mote1._domainkey.example.com. TXT   "v=DKIM1; k=rsa; p=<the public key, below>"
_dmarc.example.com.           TXT   "v=DMARC1; p=none; rua=mailto:dmarc@example.com"
```

The DKIM key: `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048
-out dkim.pem`; its `p=` is `openssl pkey -in dkim.pem -pubout -outform DER
| base64 | tr -d '\n'` (a TXT string holds 255 characters: a resolver joins
the strings of one record, so split it into several strings of one record).

**3. The program**, `mx.mote`, with `mote.toml` naming the extension:

```mote
app "Mail check"
use "pkg:mail/server.mote"
use "pkg:mail/auth.mote"
use "pkg:mail/deliver.mote"

model Seen
  key: string
  from: string
  results: string
  at: time = now

fn smtpRecipient(s: SmtpSession, to: string): SmtpAnswer
  if mailAddrSplit(to).domain.toLowerCase() == "example.com" return smtpAccept()
  return smtpRefuse("5.7.1 Relaying is not done here")

fn smtpMessage(m: SmtpMessage): SmtpAnswer
  let spf = mailSpf(m.session.remote, m.from, m.session.helo)?
  let r = fs.open(m.path)?
  let dkim = mailDkimVerify(r)?
  let dmarc = mailDmarc(r, spf, dkim)?
  let arc = mailArcVerify(r)?
  r.close()
  let said = mailAuthResults("mx.example.com", spf, dkim, dmarc, arc)
  log.info("mail taken", {from: m.from, tls: m.session.tls, results: said})
  Seen.add({key: m.id, from: m.from, results: said})?
  return smtpAccept()

server listen smtp(c) port=env("SMTP_PORT") cert=env("TLS_CERT") key=env("TLS_KEY") timeout=300000 maxIp=10 limit 60 per minute by ip
  smtpServe(c)?

server route GET "/seen"(req) requires anyone
  return {json: Seen.find({}, {order: "at desc"})?.map(s => ({from: s.from, results: s.results}))}

server route POST "/send"(req) requires anyone
  let b = req.json()?
  let body = `From: check@example.com\r\nTo: ${b.to}\r\nSubject: A check from Mote\r\nDate: ${mailDateOf(now())}\r\nMessage-ID: <${uid()}@example.com>\r\n\r\nIf this arrived, the check worked.\r\n`
  let field = mailDkimSign(fs.open(bytes(body))?, {domain: "example.com", selector: "mote1", key: secret("DKIM_KEY")})?
  let path = `outbox/${uid()}.eml`
  fs.write(path, field + body)?
  let got = mailDeliver("check@example.com", [`${b.to}`], path)?
  return {json: got.map(r => `${r.to} ${r.status} ${r.code} ${r.host} tls ${r.tls}`)}
```

```sh
mote build mx.mote
SMTP_PORT=25 SMTP_NAME=mx.example.com MAIL_HELO=mx.example.com \
  TLS_CERT=/etc/letsencrypt/live/mx.example.com/fullchain.pem TLS_KEY=/etc/letsencrypt/live/mx.example.com/privkey.pem \
  DKIM_KEY="$(cat dkim.pem)" bun dist/server/main.js --port 8080
```

(Keep `/seen` and `/send` behind your own address, or take them out, once
the check is done: as written anyone may call them.)

**4. Receiving.** From each of Gmail, Outlook.com and Fastmail, send a
message to `check@example.com`. Each must show in the log (`"msg":"mail
taken"`) and at `curl http://localhost:8080/seen`, with `tls: true` and:

| From | What proves it |
|---|---|
| Gmail | `spf=pass smtp.mailfrom=gmail.com`, `dkim=pass header.d=gmail.com`, `dmarc=pass header.from=gmail.com` |
| Outlook.com | `spf=pass smtp.mailfrom=outlook.com`, `dkim=pass header.d=outlook.com`, `dmarc=pass header.from=outlook.com` |
| Fastmail | `spf=pass smtp.mailfrom=fastmail.com` (or its own sending domain), `dkim=pass` for `fastmail.com` (and `messagingengine.com`), `dmarc=pass header.from=fastmail.com` |

A `temperror` is DNS not answering the machine (check its resolver); a
`dkim=fail` there is the finding to bring back, with the message (`fs` keeps
none: add `fs.move(m.path, …)` to keep it).

**5. Sending.** `curl -X POST localhost:8080/send -d '{"to":"you@gmail.com"}'`
gives `delivered 250 … tls true` (Gmail's MX takes STARTTLS). In Gmail,
the message's ⋮ → "Show original" must say **SPF: PASS with IP
203.0.113.10**, **DKIM: 'PASS' with domain example.com**, **DMARC: 'PASS'**.
The same to an Outlook.com address: its message's source has
`Authentication-Results: … dkim=pass (signature was verified)
header.d=example.com; … dmarc=pass action=none header.from=example.com`.
Fastmail's has `dkim=pass … header.d=example.com` and `dmarc=pass`.
That is "DKIM verifies at a real receiver".
