#!/usr/bin/python3 -I
"""Wombat-Email: mail the big mailbox providers refused or held back, in plain words: what it means, whether
mail to them got through afterwards, and what to do (the provider's own form, with what to put in it). For the
daily report (wombat-email-report) and the panel. Installed by installer/95-report.sh as
/usr/local/libexec/wombat-email-delivery.

    wombat-email-delivery [HOURS] [--json]      the last HOURS (default 24) of Postfix's deliveries
    wombat-email-delivery HOURS --log FILE      the same from a saved journal (tests)
    wombat-email-delivery 168 --save            into /var/lib/wombat-email/delivery.json for the panel (run by
                                                wombat-email-delivery.path when the panel asks, and by the report)

Only refusals and holds that come from the receiving side's reputation or block lists, or its authentication
checks, are listed: a mistyped address or a full mailbox is the sender's business, not the server's.
The meanings and forms come from the providers' own pages (checked 2026-11-08): Microsoft (mail.live.com's
troubleshooting page, olcsupport.office.com for Outlook.com/Hotmail, sender.office.com for Microsoft 365),
Google (Gmail SMTP errors and codes, support.google.com/mail/answer/188131 and 81126), Yahoo/AOL
(senders.yahooinc.com: TS codes are deferrals, "Open Ticket" on its Contact page), Apple (support.apple.com/102322:
icloudadmin@apple.com with the details listed there).
"""
import json
import os
import re
import subprocess
import sys
import time

sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

args = [a for a in sys.argv[1:] if not a.startswith("--")]
hours = int(args[0]) if args else 24
as_json = "--json" in sys.argv
save = "--save" in sys.argv
SAVED = "/var/lib/wombat-email/delivery.json"
REQUEST = "/var/lib/wombat-email/requests/delivery"
log_file = sys.argv[sys.argv.index("--log") + 1] if "--log" in sys.argv else None


def server_ip():
    try:
        return we.server_ip()
    except Exception:
        return ""


IP = server_ip()

# Who receives for a recipient, from the server Postfix handed the message to
PROVIDERS = [
    ("Microsoft", re.compile(r"\.(protection\.outlook\.com|outlook\.com|hotmail\.com)$")),
    ("Google", re.compile(r"(\.|^)(google\.com|googlemail\.com)$")),
    ("Yahoo and AOL", re.compile(r"\.(yahoodns\.net|yahoo\.com|aol\.com)$")),
    ("Apple (iCloud)", re.compile(r"\.(icloud\.com|me\.com|apple\.com)$")),
    ("Comcast", re.compile(r"\.comcast\.net$")),
]

# What a refusal or hold means. (provider or None for any, pattern, kind, what it means, what to do, where)
# kind: "list" a block list or reputation (outside the server's control; usually passes), "auth" the message
# failed the receiver's checks of SPF, DKIM or DMARC, "dns" the server's own DNS (reverse DNS).
MS_FORM = "https://olcsupport.office.com/"
RULES = [
    ("Microsoft", r"\bS3150\b", "list",
     "Microsoft's block list covers part of your hosting provider's network, or Microsoft is limiting how much mail it takes from your server's address (S3150). It usually lifts by itself within a few days.",
     "If it keeps happening, ask Microsoft to look with the Outlook.com sender support form, giving your server's address and the refusal below.", MS_FORM),
    ("Microsoft", r"\bS3140\b", "list",
     "Microsoft has your server's address, or part of your hosting provider's network, on its block list (S3140). This one doesn't lift by itself.",
     "Ask Microsoft to remove it with the Outlook.com sender support form, giving your server's address and the refusal below. If the automatic answer says nothing is wrong, reply to its email to reach a person.", MS_FORM),
    ("Microsoft", r"5\.7\.606|banned sending IP", "list",
     "Microsoft 365 (business mailboxes) has your server's address on its block list (5.7.606).",
     "Remove it yourself on Microsoft's delist portal: enter your server's address and follow the link it emails you.", "https://sender.office.com/"),
    ("Microsoft", r"4\.7\.650|rate limited due to IP reputation", "list",
     "Microsoft is taking mail from your server's address slowly for now, because of its reputation (4.7.650). The server keeps trying.",
     "Nothing, unless it lasts for days; then the Outlook.com sender support form.", MS_FORM),
    ("Google", r"[45]\.7\.28\b", "list",
     "Gmail saw an unusual amount of unwanted mail from your server's address or your hosting provider's network, and is limiting it for now (4.7.28).",
     "Usually nothing: it passes as the rate drops. If it lasts, read Gmail's sender guidelines; Google has no form to ask.", "https://support.google.com/mail/answer/188131"),
    ("Google", r"[45]\.7\.25\b", "dns",
     "Gmail refused the message because your server's address has no reverse DNS (PTR), or it doesn't match the server's name (5.7.25).",
     "Set the reverse DNS at your VPS host to the server's name: Status in the panel shows what it should be.", ""),
    ("Google", r"[45]\.7\.(26|27|30|32|40)\b", "auth",
     "Gmail says the message didn't pass its checks for the domain in its From line: SPF, DKIM or DMARC (5.7.26 and friends).",
     "If the From address is one of your domains, open DNS in the panel and use Check and fix. If it's someone else's (a forwarded message, a form that sends as the visitor), that's expected: send from your own address instead.", "https://support.google.com/mail/answer/81126"),
    ("Google", r"5\.7\.1\b", "list",
     "Gmail refused the message as likely unwanted, or because of your server's or domain's reputation (5.7.1).",
     "Read Gmail's page on why it blocks messages; Google has no form to ask.", "https://support.google.com/mail/answer/188131"),
    ("Google", r"4\.7\.0\b.*(reputation|suspicious|PTR)", "list",
     "Gmail is holding mail back for now because of your server's reputation (4.7.0). The server keeps trying.",
     "Usually nothing.", "https://support.google.com/mail/answer/188131"),
    ("Yahoo and AOL", r"\[TS\w+\]", "list",
     "Yahoo (and AOL, the same servers) is holding mail back: complaints, a poor reputation for your server's address, or unusual traffic. It's temporary and the server keeps trying.",
     "If the same code keeps coming back for days, open a ticket with Yahoo (Problems Delivering Mails, Open Ticket) with the refusal below.", "https://senders.yahooinc.com/contact/"),
    ("Apple (iCloud)", r"\b5\.\d\.\d+\b|\[(CS|HM)\d+\]", "list",
     "iCloud refused the message; its refusal says why (Apple's codes like CS01 aren't published).",
     "If it keeps happening, email Apple's postmaster team at icloudadmin@apple.com with your domain, your server's address, the refusal below, and when it started.", "https://support.apple.com/en-us/102322"),
    ("Comcast", r"\b5\.\d\.\d+\b|RL\d+|BL\d+", "list",
     "Comcast refused the message; its refusal names the reason and usually a page with more.",
     "Follow the address in the refusal below, or Comcast's postmaster page.", "https://postmaster.comcast.net/"),
    (None, r"spamhaus", "list",
     "The receiving server refused it because a Spamhaus block list names your server's address or its network.",
     "Look your address up at Spamhaus; it says why, and how to ask for removal.", "https://check.spamhaus.org/"),
    (None, r"barracuda", "list",
     "The receiving server uses Barracuda's block list, which names your server's address.",
     "Look your address up at Barracuda and ask for removal there.", "https://www.barracudacentral.org/lookups"),
    (None, r"spamcop", "list",
     "The receiving server uses SpamCop's block list, which names your server's address. SpamCop's listings end by themselves within a day once the reports stop.",
     "Look your address up at SpamCop to see why.", "https://www.spamcop.net/bl.shtml"),
    (None, r"uceprotect", "list",
     "The receiving server uses UCEPROTECT, which lists whole hosting networks for what other customers send.",
     "Nothing you can do yourself (it asks for payment to remove, which isn't worth it); its listings pass by themselves.", ""),
]
RULES = [(p, re.compile(rx, re.I), k, means, todo, link) for p, rx, k, means, todo, link in RULES]

LINE = re.compile(r"^(\S+) \S+ postfix/smtp\[\d+\]: (\w+): to=<([^>]*)>, (?:orig_to=<[^>]*>, )?relay=([^\[,]+)(?:\[[^\]]*\])?[^,]*, .*?dsn=([\d.]+), status=(sent|bounced|deferred) \((.*)\)$")


def provider_of(relay, rcpt):
    relay = relay.lower().rstrip(".")
    domain = rcpt.rsplit("@", 1)[-1].lower()
    for name, rx in PROVIDERS:
        if rx.search(relay) or rx.search("." + domain):
            return name
    return None


def read_lines():
    if log_file:
        return open(log_file, errors="replace").read().splitlines()
    return subprocess.run(["journalctl", "-t", "postfix/smtp", "--since", f"-{hours}h", "-o", "short-iso", "--no-pager", "-q"],
                          capture_output=True, text=True).stdout.splitlines()


problems = {}   # (provider, rule index) -> what happened
events = []
for line in read_lines():
    m = LINE.match(line)
    if not m:
        continue
    when, qid, rcpt, relay, dsn, status, text = m.groups()
    prov = provider_of(relay, rcpt)
    # a provider not in the list goes by its server's domain (for the block lists any server may use)
    events.append((when, prov or ".".join(relay.lower().rstrip(".").split(".")[-2:]), prov is not None, status, text, rcpt))

for idx, (when, prov, big, status, text, rcpt) in enumerate(events):
    if status == "sent":
        continue
    for i, (p, rx, kind, means, todo, link) in enumerate(RULES):
        if (p is None or p == prov) and rx.search(text):
            key = (prov, i)
            e = problems.setdefault(key, {"provider": key[0], "kind": kind, "means": means, "todo": todo, "link": link,
                                          "refused": 0, "held": 0, "first": when, "last": when, "last_i": idx, "sample": "", "recipients": set()})
            e["refused" if status == "bounced" else "held"] += 1
            e["last"], e["last_i"] = when, idx   # by order in the log: several lines can share a second
            e["sample"] = re.sub(r"\s*\(in reply to [^)]*\)$", "", re.sub(r"^host \S+ said: ", "", text))[:400]
            e["recipients"].add(rcpt.lower())
            break

out = []
for (prov, _), e in problems.items():
    e["delivered_since"] = sum(1 for when, p, big, status, *_ in events[e.pop("last_i") + 1:] if p == prov and status == "sent")
    # the provider's own code when it gives one (S3150, [TSS04], [CS01]), else the standard one (5.7.1)
    code = re.search(r"\b(S3\d{3})\b|\[((?:TS|CS|HM)\w+)\]", e["sample"]) or re.search(r"\b([45]\.\d\.\d+)\b", e["sample"])
    e["code"] = next((g for g in code.groups() if g), "") if code else ""
    e["recipients"] = len(e["recipients"])
    out.append(e)
out.sort(key=lambda e: e["last"], reverse=True)

if save:
    if os.path.lexists(REQUEST):
        os.remove(REQUEST)   # the panel's request, answered (only its existence counts)
    with open(SAVED + ".new", "w") as f:
        json.dump({"checked": int(time.time()), "hours": hours, "ip": IP, "problems": out}, f)
    os.chmod(SAVED + ".new", 0o644)
    os.replace(SAVED + ".new", SAVED)
elif as_json:
    print(json.dumps({"hours": hours, "ip": IP, "problems": out}))
else:
    if not out:
        print(f"No mail refused or held back by the big providers in the last {hours} hours.")
    for e in out:
        n = e["refused"] + e["held"]
        print(f"{e['provider']}: {'refused' if e['refused'] else 'held back'} {n} message{'s' if n != 1 else ''}"
              + (f" ({e['code']})" if e["code"] else "") + f", last at {e['last']}; {e['delivered_since']} delivered to them since")
        print(f"  {e['means']}")
        print(f"  What to do: {e['todo']}" + (f" {e['link']}" if e["link"] else ""))
        print(f"  Your server's address: {IP}")
        print(f"  The refusal: {e['sample']}")
