#!/usr/bin/python3 -I
# Wombat-Email: delivery to a private mailbox (installer/65-private.sh). Postfix's pipe hands over one
# message for one recipient (as the user wombat-pgp); it's encrypted to the mailbox's public key and
# then handed to Dovecot over LMTP, so only encrypted mail is ever stored.
#
#   wombat-email-pgp-deliver SENDER RECIPIENT     message on stdin
#   wombat-email-pgp-deliver --encrypt KEYFILE    message on stdin, the encrypted one on stdout: for
#                                                 copies a mail app saves (Sent, Drafts) in a private
#                                                 mailbox (Dovecot's IMAPSieve filter, 65-private.sh);
#                                                 exit 1 and nothing on stdout when it's already
#                                                 encrypted or anything fails (the copy stays as it came)
#
# PGP/MIME (RFC 3156) with the headers protected (RFC 9788): the whole original message, Subject
# included, is inside the encrypted part; outside, the Subject reads "..." and the other headers stay
# as they came (the Spam folder and the allow and block lists still go by them).
# Mail that is already encrypted (PGP/MIME, inline PGP, S/MIME) is stored as it came.
#
# Never stores plain text by mistake: without the key, or when anything fails, Postfix is told to try
# again later (exit 75) and keeps the message in its queue.
import os, re, secrets, smtplib, subprocess, sys, tempfile
from email.parser import BytesHeaderParser
from email.policy import compat32

EX_NOUSER, EX_UNAVAILABLE, EX_TEMPFAIL = 67, 69, 75
KEYS = '/var/lib/wombat-email/pgp-keys'
LMTP = '/run/dovecot/wombat-pgp-lmtp'
MOVED = {'content-type', 'content-transfer-encoding', 'content-disposition', 'content-id',
         'content-description', 'content-language', 'content-location', 'content-md5', 'mime-version'}
PROTECTED = ('Subject', 'From', 'To', 'Cc', 'Reply-To', 'Date', 'Message-ID', 'In-Reply-To', 'References')


def fail(code, text):
    print(text)   # Postfix puts this in the log, and in the bounce when it is one
    sys.exit(code)


def split(raw):
    """The header block and the body, each as it came (line ends as they came)."""
    m = re.search(rb'\r?\n\r?\n', raw)
    if not m:
        return raw, b''
    return raw[:m.start()], raw[m.end():]


def header_lines(block):
    """[(name, whole raw line incl. folding)] in their order."""
    out, cur = [], None
    for line in block.split(b'\n'):
        line = line.rstrip(b'\r')
        if line[:1] in (b' ', b'\t') and cur is not None:
            cur[1] += b'\r\n' + line
        elif b':' in line:
            cur = [line.split(b':', 1)[0].strip().decode('ascii', 'replace'), line]
            out.append(cur)
    return [(n, l) for n, l in out]


def already_encrypted(msg, body):
    ctype = msg.get_content_type()
    if ctype == 'multipart/encrypted':
        return True
    if ctype in ('application/pkcs7-mime', 'application/x-pkcs7-mime') and 'enveloped' in str(msg.get('Content-Type', '')).lower():
        return True
    if ctype == 'text/plain' and body.lstrip()[:27] == b'-----BEGIN PGP MESSAGE-----':
        return True
    return False


def crlf(b):
    return re.sub(rb'\r?\n', b'\r\n', b)


def encrypt(raw, keyfile):
    block, body = split(raw)
    msg = BytesHeaderParser(policy=compat32).parsebytes(block + b'\n\n')
    if already_encrypted(msg, body):
        return raw
    lines = header_lines(block)
    # inside: the original content headers (Content-Type marked as carrying protected headers), the
    # protected headers' copies, then the body exactly as it came
    inner = []
    ctype = next((l for n, l in lines if n.lower() == 'content-type'), b'Content-Type: text/plain; charset=us-ascii')
    inner.append(ctype + b'; protected-headers="v1"')
    inner += [l for n, l in lines if n.lower() in MOVED and n.lower() not in ('content-type', 'mime-version')]
    want = {p.lower() for p in PROTECTED}
    inner += [l for n, l in lines if n.lower() in want]
    inner_bytes = crlf(b'\r\n'.join(inner) + b'\r\n\r\n' + body)

    with tempfile.TemporaryDirectory(prefix='wombat-pgp-') as home:
        os.chmod(home, 0o700)
        r = subprocess.run(['/usr/bin/gpg', '--batch', '--no-tty', '--quiet', '--homedir', home,
                            '--no-auto-key-locate', '--trust-model', 'always', '--armor',
                            '--recipient-file', keyfile, '--encrypt', '--output', '-'],
                           input=inner_bytes, capture_output=True, timeout=120)
    if r.returncode != 0 or b'-----BEGIN PGP MESSAGE-----' not in r.stdout:
        fail(EX_TEMPFAIL, '4.3.0 encrypting for the private mailbox failed: ' + r.stderr.decode(errors='replace').strip()[-300:])

    b = 'wombat-' + secrets.token_hex(12)
    outer = [l for n, l in lines if n.lower() not in MOVED and n.lower() != 'subject']
    outer += [b'Subject: ...', b'MIME-Version: 1.0',
              ('Content-Type: multipart/encrypted; protocol="application/pgp-encrypted";\r\n boundary="%s"' % b).encode()]
    parts = ('This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)\r\n'
             '--%s\r\nContent-Type: application/pgp-encrypted\r\nContent-Description: PGP/MIME version identification\r\n\r\nVersion: 1\r\n\r\n'
             '--%s\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n'
             'Content-Description: OpenPGP encrypted message\r\nContent-Disposition: inline; filename="encrypted.asc"\r\n\r\n' % (b, b)).encode()
    return b'\r\n'.join(outer) + b'\r\n\r\n' + parts + crlf(r.stdout) + ('\r\n--%s--\r\n' % b).encode()


def with_pictures_kept(box, raw):
    """The message with its remote pictures fetched now and kept on this server (installer/91-images.sh):
    the last moment the server sees it before it's encrypted. As it came when that's off or fails."""
    ask = '/usr/local/libexec/wombat-email-images-ask'
    if not os.path.isfile(ask):
        return raw
    try:
        r = subprocess.run([ask, box], input=raw, capture_output=True, timeout=70)
    except (OSError, subprocess.SubprocessError):
        return raw
    return r.stdout if r.returncode == 0 and len(r.stdout) > 100 else raw


def without_receipt_requests(box, raw):
    """The message without its read receipt requests (installer/92-receipts.sh), before it's encrypted:
    the inside copy of the headers would keep them. As it came when that's off or fails."""
    prog = '/usr/local/libexec/wombat-email-receipts'
    if not os.path.isfile(prog):
        return raw
    try:
        r = subprocess.run([prog, box], input=raw, capture_output=True, timeout=30)
    except (OSError, subprocess.SubprocessError):
        return raw
    return r.stdout if r.returncode == 0 and len(r.stdout) > 20 else raw


def filter_mode(keyfile):
    global fail
    def fail(code, text):   # noqa: F811  (nothing on stdout: Dovecot keeps the copy as it came)
        print(text, file=sys.stderr)
        sys.exit(1)
    raw = sys.stdin.buffer.read()
    data = encrypt(raw, keyfile)
    if data is raw:
        sys.exit(1)   # already encrypted: nothing to change
    sys.stdout.buffer.write(data)
    sys.exit(0)


def main():
    if len(sys.argv) == 3 and sys.argv[1] == '--encrypt':
        if not os.path.isfile(sys.argv[2]):
            print('no key file %s' % sys.argv[2], file=sys.stderr)
            sys.exit(1)
        filter_mode(sys.argv[2])
    if len(sys.argv) != 3:
        fail(EX_TEMPFAIL, '4.3.5 wombat-email-pgp-deliver: wrong arguments')
    sender, rcpt = sys.argv[1], sys.argv[2].lower()
    local, _, domain = rcpt.rpartition('@')
    box = local.split('+', 1)[0] + '@' + domain   # the mailbox, without a +tag
    keyfile = os.path.join(KEYS, box + '.pgp')
    if '/' in box or not os.path.isfile(keyfile):
        fail(EX_TEMPFAIL, '4.3.0 no public key on this server for %s yet' % box)
    raw = sys.stdin.buffer.read()
    raw = with_pictures_kept(box, raw)
    raw = without_receipt_requests(box, raw)
    data = encrypt(raw, keyfile)
    try:
        with smtplib.LMTP(LMTP, timeout=300) as s:
            s.ehlo_or_helo_if_needed()
            utf8 = ['SMTPUTF8'] if not (sender.isascii() and rcpt.isascii()) else []
            s.sendmail(sender or '<>', [rcpt], data, mail_options=utf8)
    except smtplib.SMTPRecipientsRefused as e:
        code, text = next(iter(e.recipients.values()))
        fail(EX_TEMPFAIL if 400 <= code < 500 else EX_NOUSER, '%d %s' % (code, text.decode(errors='replace')))
    except smtplib.SMTPResponseException as e:
        fail(EX_TEMPFAIL if 400 <= e.smtp_code < 500 else EX_UNAVAILABLE, '%d %s' % (e.smtp_code, e.smtp_error.decode(errors='replace')))
    except (OSError, smtplib.SMTPException) as e:
        fail(EX_TEMPFAIL, '4.3.0 Dovecot did not take the message: %s' % e)
    sys.exit(0)


if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        raise
    except Exception as e:   # whatever it is, the message stays in Postfix's queue (or, filtering, as it came)
        fail(EX_TEMPFAIL, '4.3.0 wombat-email-pgp-deliver: %s: %s' % (type(e).__name__, e))
