#!/usr/bin/env python3
"""Read-only public network smoke; no account, payment or API credentials."""
import argparse
import ipaddress
import json
import os
import secrets
import socket
import struct
import subprocess

FAKE4 = ipaddress.ip_network("198.19.0.0/16")
FAKE6 = ipaddress.ip_network("fd74:6f70:656e::/48")


def read_exact(stream, size):
    value = b""
    while len(value) < size:
        part = stream.recv(size - len(value))
        if not part:
            raise RuntimeError("Truncated TCP DNS reply")
        value += part
    return value


def dns_query(name, kind=1, server="192.168.35.1", port=53, tcp=False):
    ident = secrets.randbelow(65536)
    question = b"".join(bytes([len(label)]) + label.encode("ascii") for label in name.rstrip(".").split("."))
    packet = struct.pack("!HHHHHH", ident, 256, 1, 0, 0, 0) + question + b"\0" + struct.pack("!HH", kind, 1)
    if tcp:
        with socket.create_connection((server, port), timeout=5) as client:
            client.sendall(struct.pack("!H", len(packet)) + packet)
            reply = read_exact(client, struct.unpack("!H", read_exact(client, 2))[0])
    else:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
            client.settimeout(5)
            client.connect((server, port))
            client.send(packet)
            reply = client.recv(65535)
    if len(reply) < 12 or struct.unpack("!H", reply[:2])[0] != ident:
        raise RuntimeError("Invalid DNS reply")

    def skip_name(offset):
        while True:
            length = reply[offset]
            offset += 1
            if length == 0:
                return offset
            if length & 192 == 192:
                return offset + 1
            if length > 63:
                raise RuntimeError("Invalid DNS label")
            offset += length

    offset = 12
    for _ in range(struct.unpack("!H", reply[4:6])[0]):
        offset = skip_name(offset) + 4
    addresses = []
    for _ in range(struct.unpack("!H", reply[6:8])[0]):
        offset = skip_name(offset)
        record_type, _, ttl, length = struct.unpack("!HHIH", reply[offset:offset + 10])
        offset += 10
        if record_type in (1, 28):
            addresses.append((ipaddress.ip_address(reply[offset:offset + length]), ttl))
        offset += length
    return reply[3] & 15, addresses


def request(url, resolve=None):
    # Explicitly remove all proxy env vars, disable curlrc and bypass explicit
    # proxies: success must come from the system's domain-specific routing.
    env = {key: value for key, value in os.environ.items() if "proxy" not in key.lower()}
    args = ["curl", "-q", "--noproxy", "*", "--connect-timeout", "8", "--max-time", "25",
            "-sS", "-L", "-o", "/dev/null", "-w", "%{http_code} %{remote_ip}"]
    if resolve:
        args += ["--resolve", resolve]
    result = subprocess.run([*args, url], env=env, capture_output=True, text=True, timeout=30)
    if result.returncode:
        raise RuntimeError(f"Public HTTPS smoke failed (curl exit {result.returncode})")
    status, address = result.stdout.split()
    if not 200 <= int(status) <= 499:
        raise RuntimeError("No successful TLS/HTTP transport")
    return {"http_status": int(status), "remote_ip": address}


def smoke(server, port, http):
    result = {"dns_positive": 0, "dns_negative": 0, "dns_ip_hints_suppressed": 0, "https": {}}
    for name in ("chatgpt.com", "openai.com", "api.openai.com", "subdomain.chatgpt.com", "MiXeD.openai.com"):
        for tcp in (False, True):
            for kind, pool in ((1, FAKE4), (28, FAKE6)):
                code, answers = dns_query(name, kind, server, port, tcp)
                assert code == 0 and answers and all(address in pool and ttl <= 60 for address, ttl in answers), name
                result["dns_positive"] += 1
        for kind in (64, 65):
            code, answers = dns_query(name, kind, server, port)
            assert code == 0 and not answers, name
            result["dns_ip_hints_suppressed"] += 1
    for name in ("example.com", "github.com", "notopenai.com", "openai.com.example.org", "chatgpt.com.invalid"):
        for tcp in (False, True):
            _, answers = dns_query(name, server=server, port=port, tcp=tcp)
            assert all(address not in FAKE4 and address not in FAKE6 for address, _ in answers), name
            result["dns_negative"] += 1
    if http:
        for url in ("https://chatgpt.com/codex/install.sh", "https://openai.com/", "https://api.openai.com/v1/models"):
            response = request(url)
            assert ipaddress.ip_address(response["remote_ip"]) in FAKE4 or ipaddress.ip_address(response["remote_ip"]) in FAKE6
            result["https"][url] = response
        control = request("https://example.com/")
        assert ipaddress.ip_address(control["remote_ip"]) not in FAKE4
        result["https"]["https://example.com/"] = control
        _, addresses = dns_query("api.openai.com", 28, server, port)
        response = request("https://api.openai.com/v1/models", f"api.openai.com:443:[{addresses[0][0]}]")
        assert ipaddress.ip_address(response["remote_ip"]) in FAKE6
        result["https"]["IPv6 api.openai.com"] = response
    return result


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--server", default="192.168.35.1")
    parser.add_argument("--port", type=int, default=53)
    parser.add_argument("--http", action="store_true")
    options = parser.parse_args()
    print(json.dumps(smoke(options.server, options.port, options.http), indent=2))
