"""Mesure : chaque DNS bloque-t-il chaque domaine ? (DoH GET, RFC 8484, via curl en HTTP/2)

Usage : python3 mesure-dns-paris.py echantillon.json resultats.json
Un service de plus se passe en variable : EXTRA_RESOLVER="nom=https://.../dns-query".
Une case vaut « bloqué » quand le service répond une réponse de blocage qu'il documente
(voir BLOCK_ANSWERS), « passe » quand il donne une autre adresse, et « erreur » pour
REFUSED, SERVFAIL ou un échec réseau après trois essais. Les domaines sans réponse
sur le DNS de référence sans filtre sont écartés.
"""
import base64, json, os, struct, subprocess, sys
from concurrent.futures import ThreadPoolExecutor

RESOLVERS = {
    "reference": "https://cloudflare-dns.com/dns-query",
    "dns4eu_child": "https://child.joindns4.eu/dns-query",
    "mullvad_family": "https://family.dns.mullvad.net/dns-query",
    "adguard_family": "https://family.adguard-dns.com/dns-query",
    "cleanbrowsing_family": "https://doh.cleanbrowsing.org/doh/family-filter/",
    "cloudflare_family": "https://family.cloudflare-dns.com/dns-query",
    "opendns_familyshield": "https://doh.familyshield.opendns.com/dns-query",
}
if os.environ.get("EXTRA_RESOLVER"):
    name, url = os.environ["EXTRA_RESOLVER"].split("=", 1)
    RESOLVERS[name] = url

# Documented block answers. NXDOMAIN counts as a block for every service.
BLOCK_ANSWERS = {
    "ips": {"0.0.0.0", "51.15.69.11", "94.140.14.33", "94.140.14.35", "94.140.14.36"}
           | {f"146.112.61.{n}" for n in range(104, 111)},
    "cname_suffixes": (".dns.adguard.com", ".opendns.com"),
}

def wire(name):
    q = struct.pack(">HHHHHH", 0, 0x0100, 1, 0, 0, 0)
    for part in name.split("."):
        q += bytes([len(part)]) + part.encode()
    return q + b"\0" + struct.pack(">HH", 1, 1)

def read_name(d, i):
    labels, jumped, end = [], False, None
    while True:
        l = d[i]
        if l == 0:
            i += 1
            break
        if l & 0xC0 == 0xC0:
            if not jumped: end = i + 2
            i, jumped = ((l & 0x3F) << 8) | d[i + 1], True
            continue
        labels.append(d[i + 1:i + 1 + l].decode(errors="replace")); i += 1 + l
    return ".".join(labels), (end if jumped else i)

def parse(d):
    rcode = struct.unpack(">H", d[2:4])[0] & 0xF
    qd, an = struct.unpack(">HH", d[4:8])
    i = 12
    for _ in range(qd): i = read_name(d, i)[1] + 4
    ips, cnames = [], []
    for _ in range(an):
        i = read_name(d, i)[1]
        t, _, _, rl = struct.unpack(">HHIH", d[i:i + 10]); i += 10
        if t == 1: ips.append(".".join(map(str, d[i:i + 4])))
        elif t == 5: cnames.append(read_name(d, i)[0])
        i += rl
    return {"rcode": rcode, "ips": ips, "cnames": cnames}

def ask(url, name):
    b64 = base64.urlsafe_b64encode(wire(name)).rstrip(b"=").decode()
    last = {"error": "network"}
    for _ in range(3):
        r = subprocess.run(["curl", "-s", "--http2", "-m", "10", "-H", "accept: application/dns-message",
                            f"{url}?dns={b64}"], capture_output=True)
        if r.returncode == 0 and len(r.stdout) >= 12:
            try:
                last = parse(r.stdout)
            except Exception:
                continue
            if last["rcode"] != 2:  # retry SERVFAIL only
                return last
    return last

def verdict(a):
    if "error" in a or a["rcode"] in (2, 5) or a["rcode"] not in (0, 3):
        return "erreur"
    if a["rcode"] == 3:
        return "bloqué"
    if any(c.endswith(BLOCK_ANSWERS["cname_suffixes"]) for c in a["cnames"]):
        return "bloqué"
    if a["ips"] and set(a["ips"]) <= BLOCK_ANSWERS["ips"]:
        return "bloqué"
    return "passe"

if __name__ == "__main__":
    sample = json.load(open(sys.argv[1]))
    jobs = [(g, d, r) for g, ds in sample.items() for d in ds for r in RESOLVERS]
    with ThreadPoolExecutor(12) as ex:
        out = list(ex.map(lambda j: (j, ask(RESOLVERS[j[2]], j[1])), jobs))
    results = {}
    for (g, d, r), a in out:
        results.setdefault(g, {}).setdefault(d, {})[r] = a
    json.dump(results, open(sys.argv[2], "w"), indent=1)
