#!/usr/bin/python3 -I
# Wombat-Email: pictures in mail, fetched by the server when the mail arrives (installer/91-images.sh).
#
# A picture loaded from the sender's server tells the sender that the mail was opened, when, and from
# which IP address (so roughly where); many carry a code per recipient in their address. Here every
# remote picture of an arriving HTML message is fetched at once, by the server, whether the mail is
# ever opened or not, and kept on this server; the message is changed to show the kept copy:
#
#   https://HOSTNAME/wm-img/<id>.<n>.<sig>.<ext>     id: 32 hex, random per message
#                                                    n: the picture's number in the message
#                                                    sig: HMAC-SHA256(secret, "<id>.<n>"), 32 hex
#                                                    ext: png jpg gif webp avif svg bmp ico
#
# Apache serves those files as they are (85-web): it never fetches anything, so the address can't be
# used as a proxy, and the reader's IP, cookies and referrer never leave this server. Each sender only
# ever sees this server fetch its pictures, at delivery, for every message alike.
#
# Left as they came: signed or encrypted mail (S/MIME, PGP/MIME: a change would break the signature),
# spam (the same rules as the Spam folder, 70-spam: fetching would tell a spammer the address works),
# mailboxes with it switched off, and any picture that can't be fetched (its address stays).
#
#   (no arguments)  one request, under systemd (wombat-email-images.socket, Accept=yes): from Dovecot's
#                   delivery filter or the private mailboxes' delivery (wombat-email-images-ask)
#                   in:  "MAILBOX\n" then the message;  out: "SAME\n", or "NEW\n" then the new message
#   --clean         (root, every morning from the daily report) removes the pictures of messages that
#                   are gone: a message carries its id in the header X-Wombat-Images
#   --stats         (root) messages and size kept, as JSON
import base64, binascii, concurrent.futures, hashlib, hmac, html, http.client, ipaddress, json, os, quopri, re
import secrets, shutil, socket, ssl, struct, subprocess, sys, time
from email.generator import BytesGenerator
from email.parser import BytesParser
from email.policy import compat32
from io import BytesIO
from urllib.parse import urljoin, urlsplit

BASE = '/var/lib/wombat-email/images'
STORE = BASE + '/store'
SECRET = BASE + '/secret'
OFF = BASE + '/off'                 # mailboxes with it off, one per line; "*" = off for the whole server
HOST = os.environ.get('WE_HOSTNAME', '')
HEADER = 'X-Wombat-Images'

MAX_MESSAGE = 25 * 1024 * 1024      # larger messages are left as they are
MAX_PICTURES = 60                   # per message; the rest keep their address
MAX_SIZE = 8 * 1024 * 1024          # per picture
MAX_TOTAL = 48 * 1024 * 1024        # per message
TIME_TOTAL = 40                     # seconds for all of a message's pictures (Dovecot waits 60)
TIME_ONE = 15                       # seconds for one picture, redirects included
CONNECT = 5
REDIRECTS = 4
WORKERS = 8
PORTS = {80, 443, 8080, 8443}
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'
ACCEPT = 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'

# tags whose src is a picture (VML: Outlook's backgrounds); background= on any tag; poster on video
SRC_TAGS = {'img', 'input', 'image', 'v:imagedata', 'v:fill', 'v:image'}
CSS_URL = re.compile(r'''url\(\s*(["']?)([^"')\s]{1,4096})\1\s*\)''', re.I)
NAME = re.compile(r'[a-zA-Z][a-zA-Z0-9:._-]*')
ANAME = re.compile(r'''[^\s"'>/=]+''')
UVAL = re.compile(r'[^\s>]+')
WS = ' \t\r\n\f'


# ---------------------------------------------------------------------------- which pictures, and where

def picture_url(raw):
    """The absolute http(s) address in an attribute or url(), or None (cid:, data:, relative, ...)."""
    u = html.unescape(raw).strip()
    # the forms browsers load too: //x and \\x, https:/x and https:\\x (one slash or backslashes)
    m = re.match(r'(?i)(https?:)?[/\\]+(?=[a-z0-9\[])', u)
    if m and (m.group(1) or m.end() >= 2):
        rest = u[m.end():]
        cut = re.search(r'[?#]', rest)
        cut = cut.start() if cut else len(rest)
        u = (m.group(1) or 'https:') + '//' + rest[:cut].replace('\\', '/') + rest[cut:]   # before the query, \ is /
    if len(u) > 4096 or not re.match(r'(?i)https?://', u):
        return None
    if any(c in u for c in '\r\n\t\x00 "\'<>'):
        return None
    return u


def css_rewrite(css, sub):
    return CSS_URL.sub(lambda m: (lambda new: 'url(%s%s%s)' % (m.group(1), new, m.group(1)) if new else m.group(0))(sub(m.group(2))), css)


def srcset_rewrite(value, sub):
    out = []
    for cand in re.split(r',(?=\s)|,(?=\s*(?:https?:)?//)', value):
        m = re.match(r'(\s*)(\S+)(.*)$', cand, re.S)
        if not m:
            out.append(cand)
            continue
        new = sub(m.group(2))
        out.append(m.group(1) + (new or m.group(2)) + m.group(3))
    return ','.join(out)


def html_rewrite(s, sub):
    """The HTML with each remote picture's address replaced by sub(address) (None = leave it).
    A scanner rather than a parser, so everything it doesn't change stays byte for byte."""
    out, i, n = [], 0, len(s)
    while True:
        j = s.find('<', i)
        if j < 0:
            out.append(s[i:])
            break
        out.append(s[i:j])
        m = NAME.match(s, j + 1)
        if not m:
            out.append('<')
            i = j + 1
            continue
        tag = m.group(0).lower()
        k, edits, broken = m.end(), [], False
        while k < n:
            while k < n and s[k] in WS + '/':
                k += 1
            if k >= n or s[k] == '>':
                break
            am = ANAME.match(s, k)
            if not am:
                k += 1
                continue
            attr, k = am.group(0).lower(), am.end()
            p = k
            while p < n and s[p] in WS:
                p += 1
            if p >= n or s[p] != '=':
                continue
            p += 1
            while p < n and s[p] in WS:
                p += 1
            if p < n and s[p] in '"\'':
                e = s.find(s[p], p + 1)
                if e < 0:
                    broken = True
                    break
                vs, ve, q, k = p + 1, e, s[p], e + 1
            else:
                vm = UVAL.match(s, p)
                if not vm:
                    continue
                vs, ve, q, k = p, vm.end(), '', vm.end()
            value = s[vs:ve]
            new = None
            if (attr == 'src' and tag in SRC_TAGS) or attr == 'background' or (attr == 'poster' and tag == 'video'):
                u = picture_url(value)
                new = sub(u) if u else None
            elif attr == 'srcset' and tag in ('img', 'source'):
                plain = html.unescape(value)
                got = srcset_rewrite(plain, lambda x: (lambda u: sub(u) if u else None)(picture_url(x)))
                new = got if got != plain else None
            elif attr == 'style':
                plain = html.unescape(value)
                got = css_rewrite(plain, lambda x: (lambda u: sub(u) if u else None)(picture_url(x)))
                new = got if got != plain else None
            if new is not None:
                quote = q or '"'
                new = new.replace('&', '&amp;').replace(quote, '&quot;' if quote == '"' else '&#39;')
                edits.append((vs, ve, new, q))
        if broken:
            out.append(s[j:])
            break
        end = min(k + 1, n)
        piece, last = [], j
        for vs, ve, new, q in edits:
            piece.append(s[last:vs] + (new if q else '"' + new + '"'))
            last = ve
        piece.append(s[last:end])
        out.append(''.join(piece))
        i = end
        if tag == 'style':   # the style sheet up to </style>
            c = s.lower().find('</style', i)
            c = n if c < 0 else c
            out.append(css_rewrite(s[i:c], lambda x: (lambda u: sub(u) if u else None)(picture_url(x))))
            i = c
    return ''.join(out)


# ---------------------------------------------------------------------------- fetching, safely

class Refused(Exception):
    pass


def public_addresses(host, port):
    """The host's addresses, all of them public, or Refused: no private, loopback, link-local,
    shared, multicast or reserved address, so the sender can't make the server reach inside."""
    try:
        infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
    except (socket.gaierror, UnicodeError) as e:
        raise Refused('no address: %s' % e)
    out = []
    for fam, _, _, _, sa in infos:
        ip = ipaddress.ip_address(sa[0].split('%')[0])
        if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
            ip = ip.ipv4_mapped
        if not ip.is_global or ip.is_multicast:
            raise Refused('not a public address: %s' % ip)
        out.append((fam, sa))
    if not out:
        raise Refused('no address')
    return out


def sniff(data, ctype):
    """The picture's kind from its first bytes (never from what the sender says), or None."""
    h = data[:64]
    if h.startswith(b'\x89PNG\r\n\x1a\n'):
        return 'png'
    if h.startswith(b'\xff\xd8\xff'):
        return 'jpg'
    if h[:6] in (b'GIF87a', b'GIF89a'):
        return 'gif'
    if h[:4] == b'RIFF' and h[8:12] == b'WEBP':
        return 'webp'
    if h[4:8] == b'ftyp' and h[8:12] in (b'avif', b'avis'):
        return 'avif'
    if h[:2] == b'BM' and len(data) > 26:
        return 'bmp'
    if h[:4] == b'\x00\x00\x01\x00':
        return 'ico'
    if 'svg' in ctype:
        head = data[:2048].lstrip(b'\xef\xbb\xbf \t\r\n').lower()
        if (head.startswith(b'<svg') or head.startswith(b'<?xml') or head.startswith(b'<!--')) and b'<svg' in data[:65536].lower():
            low = data.lower()
            # served with a sandboxing policy anyway (85-web); these are refused all the same
            if b'<script' in low or b'foreignobject' in low or re.search(rb'\son[a-z]+\s*=', low) or b'javascript:' in low:
                return None
            return 'svg'
    return None


def fetch(url, deadline):
    """(ext, bytes) of the picture at url, or Refused."""
    for _ in range(REDIRECTS + 1):
        left = deadline - time.monotonic()
        if left <= 0:
            raise Refused('took too long')
        p = urlsplit(url)
        scheme = p.scheme.lower()
        if scheme not in ('http', 'https') or not p.hostname or p.username or p.password:
            raise Refused('not an http(s) address')
        try:
            port = p.port or (443 if scheme == 'https' else 80)
        except ValueError:
            raise Refused('bad port')
        if port not in PORTS:
            raise Refused('port %d' % port)
        try:
            host = p.hostname.encode('idna').decode('ascii')
        except UnicodeError:
            raise Refused('bad host name')
        sock, last = None, None
        for fam, sa in public_addresses(host, port):
            try:
                sock = socket.socket(fam, socket.SOCK_STREAM)
                sock.settimeout(min(CONNECT, max(0.5, deadline - time.monotonic())))
                sock.connect(sa)
                break
            except OSError as e:
                last, sock = e, sock.close()
        if sock is None:
            raise Refused('no connection: %s' % last)
        try:
            sock.settimeout(max(0.5, min(10, deadline - time.monotonic())))
            if scheme == 'https':
                sock = ssl.create_default_context().wrap_socket(sock, server_hostname=host)
                conn = http.client.HTTPSConnection(host, port)
            else:
                conn = http.client.HTTPConnection(host, port)
            conn.sock = sock
            path = (p.path or '/') + ('?' + p.query if p.query else '')
            conn.putrequest('GET', path, skip_host=True, skip_accept_encoding=True)
            conn.putheader('Host', host if port in (80, 443) else '%s:%d' % (host, port))
            conn.putheader('User-Agent', UA)
            conn.putheader('Accept', ACCEPT)
            conn.putheader('Accept-Language', 'en-US,en;q=0.9')
            conn.putheader('Connection', 'close')
            conn.endheaders()
            r = conn.getresponse()
            if r.status in (301, 302, 303, 307, 308):
                loc = r.getheader('Location')
                if not loc:
                    raise Refused('redirect without an address')
                url = urljoin(url, loc.strip())
                continue
            if r.status != 200:
                raise Refused('HTTP %d' % r.status)
            ctype = (r.getheader('Content-Type') or '').split(';')[0].strip().lower()
            if not (ctype.startswith('image/') or ctype in ('', 'application/octet-stream', 'binary/octet-stream')
                    or (ctype in ('text/xml', 'application/xml') and urlsplit(url).path.lower().endswith('.svg'))):
                raise Refused('not a picture: %s' % ctype)
            if (r.getheader('Content-Encoding') or 'identity').lower() not in ('identity', ''):
                raise Refused('encoded: %s' % r.getheader('Content-Encoding'))
            size = r.getheader('Content-Length')
            if size and size.isdigit() and int(size) > MAX_SIZE:
                raise Refused('too big')
            data = bytearray()
            while len(data) <= MAX_SIZE:
                if time.monotonic() > deadline:
                    raise Refused('took too long')
                chunk = r.read(65536)
                if not chunk:
                    break
                data += chunk
            if len(data) > MAX_SIZE:
                raise Refused('too big')
            svg_named = urlsplit(url).path.lower().endswith('.svg')
            ext = sniff(bytes(data), 'image/svg+xml' if svg_named and ctype in ('', 'text/xml', 'application/xml', 'application/octet-stream') else ctype)
            if not ext:
                raise Refused('not a picture we keep (%s)' % (ctype or 'no type'))
            return ext, bytes(data)
        except (OSError, http.client.HTTPException, ssl.SSLError) as e:
            raise Refused('%s: %s' % (type(e).__name__, e))
        finally:
            try:
                sock.close()
            except OSError:
                pass
    raise Refused('too many redirects')


# ---------------------------------------------------------------------------- the message

def leave_alone(msg, box):
    """Why this message stays as it came, or ''."""
    for part in msg.walk():
        ct = part.get_content_type()
        if ct in ('multipart/signed', 'multipart/encrypted', 'application/pkcs7-signature', 'application/x-pkcs7-signature'):
            return 'signed or encrypted'
        if ct in ('application/pkcs7-mime', 'application/x-pkcs7-mime'):
            return 'S/MIME'
    if str(msg.get('X-Wombat-Summary', '')).strip() == '1':
        return 'the Spam summary'
    hdr = lambda name: ','.join(str(v) for v in (msg.get_all(name) or []))
    if (',%s,' % box) in hdr('X-Wombat-Block'):
        return 'spam (blocked sender)'
    if (',%s,' % box) in hdr('X-Wombat-Allow'):
        return ''
    if any(str(v).strip().lower().startswith('yes') for v in (msg.get_all('X-Spam') or [])):
        return 'spam'
    return ''


def html_parts(msg):
    for part in msg.walk():
        if part.get_content_type() != 'text/html' or part.is_multipart():
            continue
        if str(part.get('Content-Disposition', '')).lower().startswith('attachment'):
            continue
        yield part


def text_of(part):
    """(text, codec): the part's HTML as text that turns back into the same bytes, or None."""
    data = part.get_payload(decode=True)
    if data is None:
        return None
    cs = (part.get_content_charset() or 'us-ascii').lower()
    if re.match(r'(utf-?(16|32)|ucs-?[24]|iso-2022|utf-7)', cs):
        try:
            return data.decode(cs), cs
        except (LookupError, UnicodeError):
            return None
    return data.decode('latin-1'), 'latin-1'   # byte for byte: addresses and markup are ASCII in these


def set_text(part, text, codec):
    data = text.encode(codec)
    cte = str(part.get('Content-Transfer-Encoding', '7bit')).strip().lower()
    if cte == 'base64':
        part.set_payload(base64.encodebytes(data).decode('ascii'))
    elif cte == 'quoted-printable':
        part.set_payload(quopri.encodestring(data).decode('ascii'))
    elif any(len(l) > 990 for l in data.split(b'\n')):
        part.set_payload(quopri.encodestring(data).decode('ascii'))
        if 'Content-Transfer-Encoding' in part:
            part.replace_header('Content-Transfer-Encoding', 'quoted-printable')
        else:
            part['Content-Transfer-Encoding'] = 'quoted-printable'
    else:
        part.set_payload(data.decode('ascii', 'surrogateescape'))


def boxes_off():
    import fcntl
    try:
        with open(OFF) as f:
            fcntl.flock(f, fcntl.LOCK_SH)   # the panel rewrites it under LOCK_EX
            return {l.strip().lower() for l in f if l.strip()}
    except OSError:
        return set()


def handle(box, raw, log):
    """The new message, or None to keep it as it came."""
    off = boxes_off()
    if '*' in off or box in off:
        return None
    if not HOST or len(raw) > MAX_MESSAGE:
        return None
    msg = BytesParser(policy=compat32).parsebytes(raw)
    why = leave_alone(msg, box)
    if why:
        log('left alone: %s' % why)
        return None
    parts = []
    for part in html_parts(msg):
        t = text_of(part)
        if t:
            parts.append((part, t[0], t[1]))
    if not parts:
        return None

    # every remote picture, once, in the order they come
    urls = []
    def collect(u):
        if u not in urls:
            urls.append(u)
        return None
    for _, text, _ in parts:
        if 'BEGIN PGP SIGNED MESSAGE' in text:
            log('left alone: inline PGP signature')
            return None
        html_rewrite(text, collect)
    if not urls:
        return None
    wanted = urls[:MAX_PICTURES]

    deadline = time.monotonic() + TIME_TOTAL
    got, total = {}, 0
    pool = concurrent.futures.ThreadPoolExecutor(WORKERS)
    futs = {pool.submit(fetch, u, min(deadline, time.monotonic() + TIME_ONE)): u for u in wanted}
    try:
        for f in concurrent.futures.as_completed(futs, timeout=TIME_TOTAL + 2):
            try:
                ext, data = f.result()
            except Exception:   # Refused, or anything else: that picture keeps its address
                continue
            if total + len(data) <= MAX_TOTAL:
                total += len(data)
                got[futs[f]] = (ext, data)
    except concurrent.futures.TimeoutError:
        pass
    pool.shutdown(wait=False, cancel_futures=True)   # a fetch still hanging is dropped (the process ends after answering)
    if not got:
        log('%d pictures, none fetched' % len(wanted))
        return None

    # keep them: store/<id[:2]>/<id>/<n>.<sig>.<ext>, and meta.json with the mailbox and the time
    with open(SECRET, 'rb') as f:
        secret = f.read()
    mid = secrets.token_hex(16)
    d = os.path.join(STORE, mid[:2], mid)
    os.makedirs(os.path.dirname(d), mode=0o711, exist_ok=True)
    os.mkdir(d, 0o711)
    os.chmod(d, 0o711)
    names = {}
    for n, u in enumerate([u for u in wanted if u in got], 1):
        ext, data = got[u]
        sig = hmac.new(secret, ('%s.%d' % (mid, n)).encode(), hashlib.sha256).hexdigest()[:32]
        name = '%d.%s.%s' % (n, sig, ext)
        tmp = os.path.join(d, '.' + name)
        with open(tmp, 'wb') as f:
            f.write(data)
        os.chmod(tmp, 0o644)
        os.rename(tmp, os.path.join(d, name))
        names[u] = 'https://%s/wm-img/%s.%d.%s.%s' % (HOST, mid, n, sig, ext)
    with open(os.path.join(d, 'meta.json'), 'w') as f:
        json.dump({'box': box, 'time': int(time.time()), 'pictures': len(names), 'bytes': total}, f)
    os.chmod(os.path.join(d, 'meta.json'), 0o600)

    for part, text, codec in parts:
        new = html_rewrite(text, lambda u: names.get(u))
        if new != text:
            set_text(part, new, codec)
    del msg[HEADER]
    msg[HEADER] = mid
    nl = '\r\n' if b'\r\n' in raw[:4096] else '\n'
    buf = BytesIO()
    BytesGenerator(buf, mangle_from_=False, maxheaderlen=0, policy=compat32.clone(linesep=nl)).flatten(msg, linesep=nl)
    log('%d of %d pictures kept as %s (%d KB)%s' % (len(names), len(wanted), mid, total // 1024,
        ', %d more left as they were' % (len(urls) - len(wanted)) if len(urls) > len(wanted) else ''))
    return buf.getvalue()


# ---------------------------------------------------------------------------- the service

def serve():
    import pwd
    sock = socket.socket(fileno=sys.stdin.fileno())
    try:
        pid, uid, gid = struct.unpack('3i', sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize('3i')))
        who = pwd.getpwuid(uid).pw_name
    except (OSError, KeyError):
        who = '?'
    if who not in ('vmail', 'wombat-pgp', 'root'):
        print('refused: asked by %s' % who, file=sys.stderr)
        return
    buf = bytearray()
    while len(buf) <= MAX_MESSAGE + 1024:
        chunk = sock.recv(1 << 20)
        if not chunk:
            break
        buf += chunk
    nl = buf.find(b'\n')
    box = bytes(buf[:nl]).decode('utf-8', 'replace').strip().lower() if nl > 0 else ''
    if not re.fullmatch(r'[^\s/@]+@[a-z0-9.-]+', box) or len(buf) > MAX_MESSAGE + 1024:
        sock.sendall(b'SAME\n')
        return
    log = lambda text: print('%s: %s' % (box, text), file=sys.stderr)
    try:
        new = handle(box, bytes(buf[nl + 1:]), log)
    except Exception as e:   # whatever it is, the message is delivered as it came
        log('left alone after an error: %s: %s' % (type(e).__name__, e))
        new = None
    sock.sendall(b'NEW\n' + new if new else b'SAME\n')
    sock.close()
    sys.stdout.flush(); sys.stderr.flush()
    os._exit(0)   # without waiting for a fetch that still hangs


def live_ids(box):
    """The ids the mailbox's messages still carry, or None when it can't be told (the mailbox is
    gone: an empty set)."""
    r = subprocess.run(['doveadm', 'user', box], capture_output=True, timeout=60)
    if r.returncode == 67 or (r.returncode != 0 and b'not exist' in r.stderr + r.stdout):
        return set()
    if r.returncode != 0:
        return None
    r = subprocess.run(['doveadm', '-f', 'flow', 'fetch', '-u', box, 'hdr.' + HEADER.lower(), 'HEADER', HEADER, ''],
                       capture_output=True, timeout=1800)
    if r.returncode != 0:
        return None
    return set(re.findall(rb'[0-9a-f]{32}', r.stdout.lower()))


def clean():
    """Pictures whose message is gone (deleted, or its mailbox removed) go; a day's grace for mail
    still on its way into the mailbox."""
    by_box = {}
    for shard in os.listdir(STORE) if os.path.isdir(STORE) else []:
        for mid in os.listdir(os.path.join(STORE, shard)):
            d = os.path.join(STORE, shard, mid)
            try:
                with open(os.path.join(d, 'meta.json')) as f:
                    meta = json.load(f)
            except (OSError, ValueError):
                if time.time() - os.path.getmtime(d) > 86400:
                    shutil.rmtree(d, ignore_errors=True)
                continue
            if time.time() - meta.get('time', 0) > 86400:
                by_box.setdefault(str(meta.get('box', '')), []).append((mid, d))
    gone = 0
    for box, dirs in sorted(by_box.items()):
        live = live_ids(box) if re.fullmatch(r'[^\s/@]+@[a-z0-9.-]+', box) else set()
        if live is None:
            continue
        for mid, d in dirs:
            if mid.encode() not in live:
                shutil.rmtree(d, ignore_errors=True)
                gone += 1
    for shard in os.listdir(STORE) if os.path.isdir(STORE) else []:
        try:
            os.rmdir(os.path.join(STORE, shard))
        except OSError:
            pass
    print('removed: %d' % gone)


def stats():
    n = size = 0
    for root, dirs, files in os.walk(STORE):
        if 'meta.json' in files:
            n += 1
        size += sum(os.path.getsize(os.path.join(root, f)) for f in files)
    print(json.dumps({'messages': n, 'bytes': size}))


if __name__ == '__main__':
    os.umask(0o022)
    if sys.argv[1:] == ['--clean']:
        clean()
    elif sys.argv[1:] == ['--stats']:
        stats()
    elif len(sys.argv) == 1:
        serve()
    else:
        sys.exit('usage: wombat-email-images [--clean | --stats]')
