# Chained free-proxy test v2 for arena.ai from the Muse VM.
#
# v1 died on the first ConnectionResetError: check_one only caught
# socket.timeout, and work() had no guard, so one reset killed the whole
# 145k run. v2 fixes that and four more things:
#   (1) EVERY proxy is fully guarded - no single failure (reset, refused,
#       timeout, garbage) can kill the run; each becomes a counted result.
#   (2) List sanitised: valid public IPv4 only (drops 0.0.0.0, private,
#       loopback, reserved, multicast, bad ports); dropped count reported.
#   (3) :1080 entries are SOCKS, not HTTP - counted as socks_skip, never
#       fed to HTTP CONNECT (separate track, not in v2).
#   (4) --self-test probes the egress proxy CONNECT policy first:
#       CONNECT arena.ai:443 / 1.1.1.1:443 / 1.1.1.1:8080 / 1.1.1.1:80.
#       If the egress only allows :443, only :443 candidates are attemptable.
#   (5) Default concurrency 20 (v1 ran 100); per-stage timeouts.
#   (6) Early stop: 200 consecutive egress-stage failures -> stop with a
#       mechanism verdict instead of grinding the whole list.
#
# Path: VM -> egress proxy (auth from env, NEVER logged) -> candidate P ->
# CONNECT arena.ai:443 -> TLS GET /. PASS iff status 200 AND no
# cf-mitigated header AND body has no "Just a moment". SSL verification
# stays ON; no logins through proxies.
#
# Usage:
#   python test-arena-proxies-chained-v2.py --self-test
#   python test-arena-proxies-chained-v2.py --in proxies-all-20261130.txt \
#       --out arena_ok_chained_v2.txt --probe 30
#   python test-arena-proxies-chained-v2.py --in proxies-all-20261130.txt \
#       --out arena_ok_chained_v2.txt --concurrency 20
import argparse, base64, ipaddress, os, socket, ssl, sys, threading, time
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import unquote, urlparse

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/126.0 Safari/537.36")

EGRESS_STAGE = ("egress_tcp", "egress_connect", "egress_reset",
                "egress_timeout", "egress_oserror")


def _egress():
    raw = os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") or ""
    u = urlparse(raw)
    host = u.hostname or "hatch-egress-proxy"
    port = u.port or 3128
    auth = None
    if u.username:
        auth = base64.b64encode(
            f"{unquote(u.username)}:{unquote(u.password or '')}".encode()).decode()
    return host, port, auth


EGRESS_HOST, EGRESS_PORT, EGRESS_AUTH = _egress()


class BufReader:
    """Minimal buffered reader over a socket (keeps leftover bytes)."""

    def __init__(self, sock):
        self.sock = sock
        self.buf = b""

    def read_until(self, delim, limit=65536):
        while delim not in self.buf:
            chunk = self.sock.recv(4096)
            if not chunk:
                break
            self.buf += chunk
            if len(self.buf) > limit:
                break
        idx = self.buf.find(delim)
        if idx < 0:
            out, self.buf = self.buf, b""
            return out
        out, self.buf = self.buf[:idx + len(delim)], self.buf[idx + len(delim):]
        return out

    def read_some(self, n=65536):
        if self.buf:
            out, self.buf = self.buf[:n], self.buf[n:]
            return out
        return self.sock.recv(n)


def _parse_status(head):
    try:
        line = head.split(b"\r\n", 1)[0].decode("iso-8859-1", "replace")
        return int(line.split()[1])
    except Exception:
        return -1


def _parse_headers(head):
    headers = {}
    try:
        text = head.decode("iso-8859-1", "replace")
        for line in text.split("\r\n")[1:]:
            if ":" in line:
                k, v = line.split(":", 1)
                headers[k.strip().lower()] = v.strip()
    except Exception:
        pass
    return headers


def _classify(exc, stage):
    if isinstance(exc, socket.timeout):
        return stage + "_timeout"
    if isinstance(exc, ConnectionResetError):
        return stage + "_reset"
    if isinstance(exc, ConnectionRefusedError):
        return stage + "_refused"
    if isinstance(exc, OSError):
        return stage + "_oserror"
    return stage + "_error"


def egress_connect(host, port, timeout=15):
    """One CONNECT through the egress proxy. Returns (code, detail) where
    code is the HTTP status or -1 on transport failure; detail names it."""
    try:
        sock = socket.create_connection((EGRESS_HOST, EGRESS_PORT), timeout=timeout)
    except Exception as e:
        return -1, "egress_tcp:" + type(e).__name__
    try:
        sock.settimeout(timeout)
        br = BufReader(sock)
        req = f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n"
        if EGRESS_AUTH:
            req += f"Proxy-Authorization: Basic {EGRESS_AUTH}\r\n"
        req += "\r\n"
        sock.sendall(req.encode())
        head = br.read_until(b"\r\n\r\n")
        return _parse_status(head), "ok"
    except Exception as e:
        return -1, _classify(e, "egress")
    finally:
        try:
            sock.close()
        except Exception:
            pass


def self_test(timeout=15):
    """Probe the egress CONNECT policy. Prints one line per probe."""
    print("egress proxy: %s:%d (auth: %s)" % (EGRESS_HOST, EGRESS_PORT, "yes" if EGRESS_AUTH else "no"), flush=True)
    probes = [("arena.ai", 443), ("1.1.1.1", 443), ("1.1.1.1", 8080), ("1.1.1.1", 80)]
    results = {}
    for host, port in probes:
        code, detail = egress_connect(host, port, timeout)
        results[(host, port)] = (code, detail)
        print("  CONNECT %s:%d -> %s (%s)" % (host, port, code, detail), flush=True)
    ok443 = results[("arena.ai", 443)][0] == 200 and results[("1.1.1.1", 443)][0] == 200
    ok8080 = results[("1.1.1.1", 8080)][0] == 200
    ok80 = results[("1.1.1.1", 80)][0] == 200
    if not ok443:
        print("VERDICT: egress CONNECT to :443 fails - chained test cannot work", flush=True)
    elif ok8080 and ok80:
        print("VERDICT: egress allows CONNECT to 80/8080/443 - all candidate ports attemptable", flush=True)
    elif ok8080 or ok80:
        print("VERDICT: egress allows CONNECT to :443 plus some non-443 ports - most candidates attemptable", flush=True)
    else:
        print("VERDICT: egress allows CONNECT only to :443 - only :443 candidates attemptable", flush=True)
    return results


def check_one(proxy, timeout=15):
    """Returns (result, latency_ms, detail). Never raises."""
    ip, port_s = proxy.rsplit(":", 1)
    port = int(port_s)
    t0 = time.perf_counter()
    try:
        sock = socket.create_connection((EGRESS_HOST, EGRESS_PORT), timeout=timeout)
    except Exception as e:
        return (_classify(e, "egress"), None, "tcp to egress: " + type(e).__name__)
    try:
        sock.settimeout(timeout)
        br = BufReader(sock)
        # Stage 1: CONNECT to the candidate through the egress proxy.
        try:
            req = f"CONNECT {ip}:{port} HTTP/1.1\r\nHost: {ip}:{port}\r\n"
            if EGRESS_AUTH:
                req += f"Proxy-Authorization: Basic {EGRESS_AUTH}\r\n"
            req += "\r\n"
            sock.sendall(req.encode())
            head = br.read_until(b"\r\n\r\n")
        except Exception as e:
            return (_classify(e, "egress"), None, "CONNECT to candidate: " + type(e).__name__)
        code = _parse_status(head)
        if code != 200:
            return ("egress_connect", None, "egress CONNECT -> %s" % code)
        # Stage 2: CONNECT arena.ai:443 through the candidate.
        try:
            sock.sendall(b"CONNECT arena.ai:443 HTTP/1.1\r\n"
                         b"Host: arena.ai:443\r\n\r\n")
            head = br.read_until(b"\r\n\r\n")
        except Exception as e:
            return (_classify(e, "proxy"), None, "CONNECT arena.ai: " + type(e).__name__)
        code = _parse_status(head)
        if code != 200:
            return ("proxy_connect", None, "candidate CONNECT -> %s" % code)
        # Stage 3: TLS + GET / (verification ON).
        try:
            ctx = ssl.create_default_context()
            tls = ctx.wrap_socket(sock, server_hostname="arena.ai")
        except Exception as e:
            return (_classify(e, "tls"), None, "TLS: " + type(e).__name__)
        try:
            tls.settimeout(timeout)
            br = BufReader(tls)
            tls.sendall(
                f"GET / HTTP/1.1\r\nHost: arena.ai\r\nUser-Agent: {UA}\r\n"
                f"Accept: text/html,application/xhtml+xml\r\n"
                f"Connection: close\r\n\r\n".encode())
            head = br.read_until(b"\r\n\r\n")
        except Exception as e:
            return (_classify(e, "http"), None, "GET: " + type(e).__name__)
        code = _parse_status(head)
        headers = _parse_headers(head)
        if code != 200:
            return ("http_%d" % code, None, "GET -> %s" % code)
        if "cf-mitigated" in headers:
            return ("cf", None, "cf-mitigated header present")
        body = br.buf
        deadline = t0 + timeout * 3
        try:
            while len(body) < 262144 and time.perf_counter() < deadline:
                chunk = br.read_some(65536)
                if not chunk:
                    break
                body += chunk
                if b"Just a moment" in body:
                    break
        except Exception:
            pass
        if b"Just a moment" in body:
            return ("cf", None, "Just a moment in body")
        ms = int((time.perf_counter() - t0) * 1000)
        return ("pass", ms, "200 ok in %dms" % ms)
    finally:
        try:
            sock.close()
        except Exception:
            pass


def safe_check_one(proxy, timeout=15):
    """check_one plus a last-resort guard: this function never raises."""
    try:
        return check_one(proxy, timeout)
    except Exception as e:
        return ("worker_error", None, type(e).__name__ + ": " + str(e)[:120])


def load_proxies(path):
    """Returns (kept, socks, dropped). kept = valid public IPv4, port 1-65535,
    excluding :1080 (SOCKS track). socks = :1080 entries counted separately."""
    kept, socks, dropped = [], [], 0
    with open(path) as f:
        for ln in f:
            s = ln.strip()
            if not s or ":" not in s:
                dropped += 1
                continue
            ip, port_s = s.rsplit(":", 1)
            try:
                port = int(port_s)
                addr = ipaddress.IPv4Address(ip)
            except Exception:
                dropped += 1
                continue
            if not (1 <= port <= 65535):
                dropped += 1
                continue
            if (addr.is_private or addr.is_loopback or addr.is_reserved
                    or addr.is_multicast or addr.is_link_local
                    or addr.is_unspecified):
                dropped += 1
                continue
            if port == 1080:
                socks.append(s)
            else:
                kept.append(s)
    return kept, socks, dropped


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in", dest="infile", default="proxies-all-20261130.txt")
    ap.add_argument("--out", dest="outfile", default="arena_ok_chained_v2.txt")
    ap.add_argument("--limit", type=int, default=0, help="0 = all")
    ap.add_argument("--probe", type=int, default=0, help="run first N verbosely and stop")
    ap.add_argument("--concurrency", type=int, default=20)
    ap.add_argument("--timeout", type=float, default=15)
    ap.add_argument("--verbose", action="store_true")
    ap.add_argument("--progress", type=int, default=200)
    ap.add_argument("--self-test", action="store_true")
    ap.add_argument("--early-stop", type=int, default=200,
                    help="consecutive egress-stage failures that stop the run")
    args = ap.parse_args()

    if args.self_test:
        self_test()
        return 0

    kept, socks, dropped = load_proxies(args.infile)
    print("list: kept=%d socks(:1080)=%d dropped=%d" % (len(kept), len(socks), dropped), flush=True)
    proxies = kept
    if args.probe:
        proxies = proxies[:args.probe]
        args.verbose = True
    if args.limit:
        proxies = proxies[:args.limit]
    total = len(proxies)
    print("testing %d proxies, concurrency=%d, timeout=%ss" % (total, args.concurrency, args.timeout), flush=True)

    stats = {}
    lock = threading.Lock()
    passes = []
    done = [0]
    egress_streak = [0]
    stop = [False]
    out_f = open(args.outfile, "a", buffering=1)

    def work(proxy):
        if stop[0]:
            return
        result, ms, detail = safe_check_one(proxy, args.timeout)
        with lock:
            stats[result] = stats.get(result, 0) + 1
            done[0] += 1
            if result in EGRESS_STAGE:
                egress_streak[0] += 1
            else:
                egress_streak[0] = 0
            if result == "pass":
                passes.append((ms, proxy))
                out_f.write("%s\n" % proxy)
            if args.verbose:
                print("%16s %-22s %s" % (result, proxy, detail), flush=True)
            elif done[0] % args.progress == 0:
                print("[%d/%d] pass=%d stats=%s" % (done[0], total, stats.get("pass", 0), stats), flush=True)
            if egress_streak[0] >= args.early_stop and not args.probe:
                stop[0] = True
                print("EARLY STOP: %d consecutive egress-stage failures "
                      "(stats=%s) - mechanism verdict, not a proxy verdict" % (egress_streak[0], stats), flush=True)

    t0 = time.perf_counter()
    chunk = 200
    with ThreadPoolExecutor(max_workers=args.concurrency) as ex:
        for i in range(0, total, chunk):
            if stop[0]:
                break
            list(ex.map(work, proxies[i:i + chunk]))
    out_f.close()
    elapsed = time.perf_counter() - t0
    print("\nDONE %d/%d in %.0fs" % (done[0], total, elapsed), flush=True)
    print("stats: %s" % (stats,), flush=True)
    print("passes: %d (appended to %s)" % (len(passes), args.outfile), flush=True)
    if passes:
        passes.sort()
        with open(args.outfile, "w") as f:
            f.writelines("%s\n" % p for _, p in passes)
        print("sorted passes written to %s" % args.outfile, flush=True)
        for ms, p in passes[:20]:
            print("  OK %s %dms" % (p, ms), flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
