File size: 7,030 Bytes
3ec0f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
from __future__ import annotations

import json
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlsplit, urlunsplit

from curl_ca_bundle import curl_session_kwargs

try:
    from curl_cffi.requests import Session as CurlSession
except Exception:  # pragma: no cover - exercised only in a minimal install
    CurlSession = None

try:
    import requests
except Exception:  # pragma: no cover - exercised only in a minimal install
    requests = None


TRACE = "https://www.cloudflare.com/cdn-cgi/trace"


def _redact_proxy(proxy: str) -> str:
    """Keep diagnostics useful without echoing proxy credentials."""
    try:
        parsed = urlsplit(str(proxy))
        if not parsed.scheme or not parsed.netloc:
            return str(proxy)
        host = parsed.hostname or ""
        if parsed.port:
            host = f"{host}:{parsed.port}"
        return urlunsplit((parsed.scheme, host, parsed.path, parsed.query, parsed.fragment))
    except Exception:
        return "<proxy>"


def _redact_error(error: str, proxy: str) -> str:
    message = str(error or "")
    return message.replace(str(proxy or ""), _redact_proxy(proxy))[:240]


def _country(response) -> str:
    text = str(getattr(response, "text", "") or "").strip()
    fields = {
        line.split("=", 1)[0].strip().lower(): line.split("=", 1)[1].strip()
        for line in text.splitlines()
        if "=" in line
    }
    value = fields.get("loc") or fields.get("country") or fields.get("countrycode")
    if value:
        return str(value).upper()[:8]
    try:
        body = response.json()
    except Exception:
        body = None
    if isinstance(body, dict):
        value = body.get("country_code") or body.get("countryCode") or body.get("country")
        if value:
            return str(value).upper()[:8]
    # A few country endpoints return a bare ISO code.
    if len(text) <= 8 and text.isalpha():
        return text.upper()
    return ""


def _probe_client(proxy: str, client_name: str):
    session = None
    try:
        if client_name.startswith("curl_"):
            if CurlSession is None:
                raise RuntimeError("curl_cffi unavailable")
            session = CurlSession(
                impersonate=client_name.removeprefix("curl_"),
                **curl_session_kwargs(),
            )
        else:
            if requests is None:
                raise RuntimeError("requests unavailable")
            session = requests.Session()
        session.trust_env = False
        session.proxies = {"http": proxy, "https": proxy}
        response = session.get(TRACE, timeout=(8, 12))
        status = int(getattr(response, "status_code", 0) or 0)
        country = _country(response) if status == 200 else ""
        return {"transport": client_name, "status": status, "country": country}
    except Exception as exc:
        return {"transport": client_name, "status": 0, "country": "", "error": str(exc)[:240]}
    finally:
        try:
            if session is not None:
                session.close()
        except Exception:
            pass


def check(proxy, expected):
    proxy = str(proxy or "").strip()
    expected = str(expected or "US").upper()
    attempts = []
    for client_name in ("curl_firefox144", "curl_chrome146", "requests_openssl"):
        result = _probe_client(proxy, client_name)
        attempts.append(result)
        if result.get("country") == expected:
            return {
                "proxy": proxy,
                "state": "match",
                "country": expected,
                "transport": result.get("transport"),
                "attempts": attempts,
            }
    countries = [str(item.get("country") or "") for item in attempts if item.get("country")]
    mismatch = next((value for value in countries if value != expected), "")
    return {
        "proxy": proxy,
        "state": "mismatch" if mismatch else "inconclusive",
        "country": mismatch,
        "attempts": attempts,
    }


def validate(values, expected, limit=30):
    source = []
    for item in values:
        value = str(item or "").strip()
        if value and value not in source:
            source.append(value)
    source = source[:100]
    results = []
    with ThreadPoolExecutor(max_workers=min(24, max(1, len(source)))) as pool:
        futures = {pool.submit(check, proxy, expected): proxy for proxy in source}
        for future in as_completed(futures):
            try:
                results.append(future.result())
            except Exception as exc:
                results.append({"proxy": futures[future], "state": "inconclusive", "error": str(exc)[:240], "attempts": []})
    valid = [item["proxy"] for item in results if item.get("state") == "match"][:limit]
    inconclusive = [item["proxy"] for item in results if item.get("state") == "inconclusive"][:limit]
    mismatch = [item["proxy"] for item in results if item.get("state") == "mismatch"]
    diagnostics = []
    for item in results:
        attempts = []
        for attempt in item.get("attempts") or []:
            safe_attempt = dict(attempt)
            if safe_attempt.get("error"):
                safe_attempt["error"] = _redact_error(safe_attempt["error"], item.get("proxy") or "")
            attempts.append(safe_attempt)
        diagnostics.append({
            "proxy": _redact_proxy(item.get("proxy") or ""),
            "state": item.get("state"),
            "country": item.get("country") or "",
            "attempts": attempts,
        })
    return valid, len(source), inconclusive, mismatch, diagnostics


def main():
    data = json.loads(sys.stdin.read() or "{}")
    if "proxies" in data:
        expected = str(data.get("expected") or "US").upper()
        limit = max(1, min(30, int(data.get("limit") or 3)))
        valid, total, inconclusive, mismatch, diagnostics = validate(data.get("proxies") or [], expected, limit)
        result = {
            "ok": bool(valid), "proxies": valid, "expected": expected, "total": total,
            "valid": len(valid), "inconclusive": inconclusive, "mismatch": mismatch,
            "diagnostics": diagnostics,
        }
        print(json.dumps(result))
        return 0 if valid else 2
    entry, entry_total, entry_inconclusive, entry_mismatch, entry_diag = validate(data.get("entry") or [], "US")
    exit, exit_total, exit_inconclusive, exit_mismatch, exit_diag = validate(data.get("exit") or [], "TR")
    result = {
        "ok": bool(entry and exit), "entry": entry, "exit": exit,
        "entry_total": entry_total, "exit_total": exit_total,
        "entry_valid": len(entry), "exit_valid": len(exit),
        "entry_inconclusive": entry_inconclusive, "exit_inconclusive": exit_inconclusive,
        "entry_mismatch": entry_mismatch, "exit_mismatch": exit_mismatch,
        "entry_diagnostics": entry_diag, "exit_diagnostics": exit_diag,
    }
    print(json.dumps(result))
    return 0 if entry and exit else 2


if __name__ == "__main__":
    raise SystemExit(main())