366 lines
12 KiB
Python
366 lines
12 KiB
Python
"""Append-only destination sessions on the managed mail receiver."""
|
|
|
|
import imaplib
|
|
import io
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
from contextlib import contextmanager, suppress
|
|
from select import select
|
|
from time import monotonic
|
|
|
|
from . import imap_import as imap
|
|
from .mail_node import MailboxSpec
|
|
from .mail_node_apply import (
|
|
check_registered_manifest,
|
|
credential_path,
|
|
home_is_prepared,
|
|
load_credentials,
|
|
locked_state,
|
|
retirement_guard,
|
|
)
|
|
from .node_maintenance import rollout_target
|
|
from .receiver_scope import authorized_request, socket_peer
|
|
|
|
SOCKET = "/run/coulobre-mail-apply.sock"
|
|
MARKER = b"!coulobre-mail-import-v1\n"
|
|
FRAME_LIMIT = 1024 * 1024
|
|
CONTROL_LIMIT = 8192
|
|
INVALID = "The destination import request or reply was invalid."
|
|
UNAVAILABLE = "The mail receiver could not open or continue the import."
|
|
|
|
|
|
def read_frame(stream, limit):
|
|
line = stream.readline(limit + 1)
|
|
if len(line) > limit or not line.endswith(b"\n"):
|
|
raise OSError(INVALID)
|
|
try:
|
|
data = json.loads(line)
|
|
except (ValueError, RecursionError):
|
|
raise imap.MailboxImportError(INVALID) from None
|
|
if not isinstance(data, dict):
|
|
raise imap.MailboxImportError(INVALID)
|
|
return data
|
|
|
|
|
|
def write_frame(stream, data):
|
|
stream.write(json.dumps(data, ensure_ascii=True).encode("ascii") + b"\n")
|
|
stream.flush()
|
|
|
|
|
|
def read_reply(stream):
|
|
reply = read_frame(stream, FRAME_LIMIT)
|
|
if set(reply) == {"result"}:
|
|
return reply["result"]
|
|
if reply == {"retry": True}:
|
|
raise OSError(UNAVAILABLE)
|
|
if set(reply) == {"problem"} and isinstance(reply["problem"], str):
|
|
raise imap.MailboxImportError(reply["problem"][:300])
|
|
raise OSError(INVALID)
|
|
|
|
|
|
class Destination:
|
|
def __init__(self, stream):
|
|
self.stream = stream
|
|
self.flags = frozenset()
|
|
|
|
def request(self, operation, *, body=None, **fields):
|
|
write_frame(self.stream, {"operation": operation, **fields})
|
|
if body is not None:
|
|
self.stream.write(body)
|
|
self.stream.flush()
|
|
return read_reply(self.stream)
|
|
|
|
def list_folders(self, *, root=False):
|
|
return [
|
|
imap.Folder(
|
|
name.encode("ascii"), sep.encode("ascii") if sep else None
|
|
)
|
|
for name, sep in self.request("list", root=root)
|
|
]
|
|
|
|
def select(self, folder, *, readonly=False):
|
|
validity, next_uid, flags = self.request(
|
|
"select", folder=folder.decode("ascii")
|
|
)
|
|
self.flags = frozenset(flag.encode("ascii") for flag in flags)
|
|
return validity, next_uid
|
|
|
|
def create(self, folder):
|
|
self.request("create", folder=folder.decode("ascii"))
|
|
|
|
def append(self, folder, message, flags):
|
|
self.request(
|
|
"append",
|
|
folder=folder.decode("ascii"),
|
|
date=message.date.decode("ascii"),
|
|
flags=[flag.decode("ascii") for flag in flags],
|
|
size=len(message.body),
|
|
body=message.body,
|
|
)
|
|
|
|
def reconcile(self, first, digest, timestamp):
|
|
return self.request(
|
|
"reconcile", first=first, digest=digest, timestamp=timestamp
|
|
)
|
|
|
|
|
|
@contextmanager
|
|
def open_destination(mailbox):
|
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
|
peer.settimeout(imap.IO_TIMEOUT)
|
|
try:
|
|
peer.connect(SOCKET)
|
|
except (FileNotFoundError, PermissionError):
|
|
raise imap.MailboxImportError(
|
|
"The import worker cannot access the mail receiver. "
|
|
"Ask the operator to check the worker and socket setup."
|
|
) from None
|
|
with peer.makefile("rwb") as stream:
|
|
stream.write(MARKER)
|
|
write_frame(stream, mailbox.manifest())
|
|
if read_reply(stream) is not True:
|
|
raise OSError(INVALID)
|
|
yield Destination(stream)
|
|
|
|
|
|
class TimedPipeReader(io.RawIOBase):
|
|
def __init__(self, descriptor):
|
|
self.descriptor = descriptor
|
|
|
|
def readable(self):
|
|
return True
|
|
|
|
def readinto(self, buffer):
|
|
if not select([self.descriptor], [], [], imap.IO_TIMEOUT)[0]:
|
|
raise TimeoutError(UNAVAILABLE)
|
|
return os.readv(self.descriptor, [buffer])
|
|
|
|
|
|
class PreauthenticatedIMAP(imaplib.IMAP4):
|
|
def __init__(self, process):
|
|
self.process = process
|
|
super().__init__()
|
|
|
|
def open(self, host="", port=0, timeout=None):
|
|
self.host, self.port = host, port
|
|
self.reader = io.BufferedReader(
|
|
TimedPipeReader(self.process.stdout.fileno())
|
|
)
|
|
self.writer = self.process.stdin.fileno()
|
|
os.set_blocking(self.writer, False)
|
|
|
|
def send(self, data):
|
|
deadline = monotonic() + imap.IO_TIMEOUT
|
|
remaining = memoryview(data)
|
|
while remaining:
|
|
wait = deadline - monotonic()
|
|
if wait <= 0 or not select([], [self.writer], [], wait)[1]:
|
|
raise TimeoutError(UNAVAILABLE)
|
|
try:
|
|
written = os.write(self.writer, remaining)
|
|
except BlockingIOError:
|
|
continue
|
|
remaining = remaining[written:]
|
|
|
|
def readline(self):
|
|
line = self.reader.readline(FRAME_LIMIT + 1)
|
|
if len(line) > FRAME_LIMIT:
|
|
raise imap.MailboxImportError(INVALID)
|
|
return line
|
|
|
|
def read(self, size):
|
|
if not 0 <= size <= imap.MAX_PACKET_BYTES:
|
|
raise imap.MailboxImportError(
|
|
"The destination literal exceeds the import limit."
|
|
)
|
|
return self.reader.read(size)
|
|
|
|
def shutdown(self):
|
|
self.reader.close()
|
|
|
|
|
|
@contextmanager
|
|
def preauthenticated_mailbox(mailbox):
|
|
# Dovecot rejects standalone root IMAP with a socket on stdout.
|
|
with subprocess.Popen(
|
|
["/usr/bin/doveadm", "exec", "imap", "-u", mailbox.address],
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
) as process:
|
|
try:
|
|
client = PreauthenticatedIMAP(process)
|
|
try:
|
|
if client.state != "AUTH":
|
|
raise imap.MailboxImportError(UNAVAILABLE)
|
|
yield client
|
|
finally:
|
|
client.shutdown()
|
|
finally:
|
|
process.kill()
|
|
|
|
|
|
@contextmanager
|
|
def active_mailbox(mailbox):
|
|
with locked_state(create=False) as directory:
|
|
if directory is None or retirement_guard(mailbox).exists():
|
|
raise imap.MailboxImportError(
|
|
"The destination mailbox is no longer ready."
|
|
)
|
|
record = load_credentials(credential_path(mailbox))
|
|
check_registered_manifest(record, mailbox)
|
|
if record.suspended or not home_is_prepared(record):
|
|
raise imap.MailboxImportError(
|
|
"The destination mailbox is no longer ready."
|
|
)
|
|
if rollout_target("mail"):
|
|
raise imap.MailboxImportError(
|
|
"The mail receiver is in upgrade maintenance."
|
|
)
|
|
yield
|
|
|
|
|
|
class ImportSession:
|
|
def __init__(self, mailbox, client):
|
|
self.mailbox = mailbox
|
|
self.client = client
|
|
self.folder = None
|
|
self.flags = frozenset()
|
|
|
|
def apply(self, request, stream):
|
|
operation = request.get("operation")
|
|
client = self.client
|
|
fields = request.keys() - {"operation"}
|
|
if (
|
|
operation == "list"
|
|
and fields == {"root"}
|
|
and type(request["root"]) is bool
|
|
):
|
|
return [
|
|
(
|
|
folder.name.decode(),
|
|
folder.separator.decode() if folder.separator else None,
|
|
)
|
|
for folder in imap.list_folders(client, root=request["root"])
|
|
]
|
|
if operation == "reconcile" and fields == {
|
|
"first",
|
|
"digest",
|
|
"timestamp",
|
|
}:
|
|
first, digest, timestamp = (
|
|
request[key] for key in ("first", "digest", "timestamp")
|
|
)
|
|
if (
|
|
self.folder is None
|
|
or type(first) is not int
|
|
or not 1 <= first <= 2**32 - 1
|
|
or not isinstance(digest, str)
|
|
or not re.fullmatch(r"[a-f0-9]{64}", digest)
|
|
or not isinstance(timestamp, str)
|
|
or len(timestamp) > 40
|
|
):
|
|
raise imap.MailboxImportError(INVALID)
|
|
with active_mailbox(self.mailbox):
|
|
return imap.reconcile(client, first, digest, timestamp)
|
|
if operation not in ("select", "create", "append"):
|
|
raise imap.MailboxImportError(INVALID)
|
|
required = {"folder"}
|
|
if operation == "append":
|
|
required |= {"date", "flags", "size"}
|
|
if fields != required or not isinstance(request["folder"], str):
|
|
raise imap.MailboxImportError(INVALID)
|
|
folder = request["folder"].encode("ascii")
|
|
quoted = imap.quote(folder)
|
|
if operation == "select":
|
|
validity, next_uid = imap.select(client, folder, readonly=False)
|
|
self.folder = folder
|
|
self.flags = imap.permanent_flags(client)
|
|
return (
|
|
validity,
|
|
next_uid,
|
|
sorted(flag.decode("ascii") for flag in self.flags),
|
|
)
|
|
if operation == "create":
|
|
with active_mailbox(self.mailbox):
|
|
if client.create(quoted)[0] != "OK":
|
|
raise imap.MailboxImportError(
|
|
"A destination folder could not be created."
|
|
)
|
|
return None
|
|
size, date, flags = (request[key] for key in ("size", "date", "flags"))
|
|
if (
|
|
folder != self.folder
|
|
or type(size) is not int
|
|
or not 0 <= size <= imap.MAX_MESSAGE_BYTES
|
|
or not isinstance(date, str)
|
|
or not isinstance(flags, list)
|
|
or len(flags) > 64
|
|
or any(not isinstance(flag, str) for flag in flags)
|
|
):
|
|
raise imap.MailboxImportError(INVALID)
|
|
date = date.encode("ascii")
|
|
if not imap.INTERNALDATE.fullmatch(b"INTERNALDATE " + date):
|
|
raise imap.MailboxImportError(INVALID)
|
|
flags = tuple(flag.encode("ascii") for flag in flags)
|
|
if imap.usable_flags(self.flags, flags)[0] != flags:
|
|
raise imap.MailboxImportError(INVALID)
|
|
body = stream.read(size)
|
|
if len(body) != size:
|
|
raise OSError(INVALID)
|
|
message = imap.Message(body, date, flags)
|
|
with active_mailbox(self.mailbox):
|
|
imap.append(client, folder, message, flags)
|
|
return None
|
|
|
|
|
|
def serve_import(source=None, output=None):
|
|
if source is None:
|
|
source = sys.stdin.buffer
|
|
if output is None:
|
|
output = sys.stdout.buffer
|
|
try:
|
|
if source.readline(len(MARKER) + 1) != MARKER:
|
|
raise imap.MailboxImportError(INVALID)
|
|
mailbox = MailboxSpec.from_manifest(read_frame(source, CONTROL_LIMIT))
|
|
peer = socket_peer()
|
|
if peer not in ("root", "coulobre-panel") and not (
|
|
peer and peer.startswith("coulobre-mail-p-")
|
|
):
|
|
raise imap.MailboxImportError(
|
|
"Use a domain-scoped mail receiver connection for imports."
|
|
)
|
|
with (
|
|
authorized_request("mail", mailbox, local_peer="coulobre-panel"),
|
|
active_mailbox(mailbox),
|
|
):
|
|
pass
|
|
with preauthenticated_mailbox(mailbox) as client:
|
|
session = ImportSession(mailbox, client)
|
|
write_frame(output, {"result": True})
|
|
while source.peek(1):
|
|
request = read_frame(source, CONTROL_LIMIT)
|
|
with authorized_request(
|
|
"mail", mailbox, local_peer="coulobre-panel"
|
|
):
|
|
result = session.apply(request, source)
|
|
write_frame(output, {"result": result})
|
|
except (OSError, imaplib.IMAP4.abort):
|
|
with suppress(OSError):
|
|
write_frame(output, {"retry": True})
|
|
return 1
|
|
except (ValueError, imaplib.IMAP4.error) as error:
|
|
with suppress(OSError):
|
|
problem = (
|
|
str(error)
|
|
if isinstance(error, imap.MailboxImportError)
|
|
else UNAVAILABLE
|
|
)
|
|
write_frame(output, {"problem": problem})
|
|
return 1
|
|
return 0
|