File size: 11,236 Bytes
1155296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
checkproxy.py — Check proxy HANG LOAT, TU DETECT loai (HTTP / SOCKS5 / SOCKS4).
Chi dung thu vien chuan (stdlib), khong can cai gi.

Quang het proxy vao 1 file (moi dong 1 con), tool tu nhan dien & check:

  host:port:user:pass              <- tu thu http -> socks5 -> socks4
  host:port:user:pass (Http)       <- duoi (Http)/(Socks5)/(Socks4) -> check dung loai do
  socks5://user:pass@host:port     <- co scheme -> check dung loai do
  http://host:port                 <- proxy khong auth cung duoc
  user:pass@host:port
  # dong bat dau bang # bi bo qua

Dung:
  python3 checkproxy.py proxies.txt                 # check file
  cat proxies.txt | python3 checkproxy.py           # doc stdin
  python3 checkproxy.py proxies.txt -t 200 -T 10    # 200 luong, timeout 10s
  python3 checkproxy.py proxies.txt -o alive.txt    # luu proxy SONG ra file
"""
import sys, re, time, json, socket, struct, base64, argparse
from concurrent.futures import ThreadPoolExecutor, as_completed

# Trang test: tra IP thoat that + quoc gia, qua HTTP port 80 (di duoc qua moi loai proxy)
T_HOST, T_PORT = "ip-api.com", 80
T_PATH = "/json/?fields=status,query,country,city,isp"

C = {"g": "\033[92m", "r": "\033[91m", "y": "\033[93m", "d": "\033[90m",
     "c": "\033[96m", "x": "\033[0m"}

SCHEME_MAP = {"http": "http", "https": "http", "socks5": "socks5", "socks5h": "socks5",
              "socks4": "socks4", "socks4a": "socks4", "socks": "socks5"}


def parse_line(line):
    """Tra (scheme_or_None, host, port, user, pwd) hoac None."""
    line = line.strip()
    if not line or line.startswith("#"):
        return None
    scheme = None
    m = re.match(r"^(\w+)://(.*)$", line)                  # scheme:// o dau
    if m:
        scheme = SCHEME_MAP.get(m.group(1).lower())
        line = m.group(2)
    tag = re.search(r"\(([^)]*)\)\s*$", line)              # (Http)/(Socks5) o duoi
    if tag:
        scheme = scheme or SCHEME_MAP.get(re.sub(r"[^a-z0-9]", "", tag.group(1).lower()))
        line = line[:tag.start()].strip()
    line = line.split()[0] if " " in line else line        # bo chu thua
    if "@" in line:                                        # user:pass@host:port
        cred, hp = line.rsplit("@", 1)
        hpp = hp.split(":")
        if len(hpp) < 2:
            return None
        host, port = hpp[0], hpp[1]
        up = cred.split(":", 1)
        user, pwd = up[0], (up[1] if len(up) > 1 else "")
    else:
        parts = line.split(":")
        if len(parts) >= 4:                               # host:port:user:pass
            host, port, user, pwd = parts[0], parts[1], parts[2], ":".join(parts[3:])
        elif len(parts) == 2:                             # host:port
            host, port, user, pwd = parts[0], parts[1], "", ""
        else:
            return None
    if not port.isdigit():
        return None
    return scheme, host, int(port), user, pwd


# ---------- doc HTTP response (HTTP/1.0 -> server dong ket noi, khong chunk) ----------
def _read_all(s, cap=65536):
    buf = b""
    while len(buf) < cap:
        try:
            chunk = s.recv(4096)
        except socket.timeout:
            break
        if not chunk:
            break
        buf += chunk
    return buf


def _parse_http(raw):
    """Tra (status_code:int, body:str). Loi -> (-1, '')."""
    if b"\r\n\r\n" not in raw:
        return -1, ""
    head, _, body = raw.partition(b"\r\n\r\n")
    first = head.split(b"\r\n", 1)[0].decode("latin1", "ignore")
    parts = first.split()
    code = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else -1
    return code, body.decode("utf-8", "ignore")


def _http_request_line_via_target(s):
    """Gui GET (path tuong doi) qua 1 socket DA tunnel toi target."""
    req = ("GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: Mozilla/5.0\r\n"
           "Connection: close\r\n\r\n" % (T_PATH, T_HOST))
    s.sendall(req.encode())
    return _parse_http(_read_all(s))


# ---------- 3 loai proxy ----------
def via_http(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout)
    s.settimeout(timeout)
    try:
        req = "GET http://%s%s HTTP/1.0\r\nHost: %s\r\n" % (T_HOST, T_PATH, T_HOST)
        if user:
            cred = base64.b64encode(("%s:%s" % (user, pwd)).encode()).decode()
            req += "Proxy-Authorization: Basic %s\r\n" % cred
        req += "User-Agent: Mozilla/5.0\r\nConnection: close\r\n\r\n"
        s.sendall(req.encode())
        code, body = _parse_http(_read_all(s))
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


def _recvn(s, n):
    buf = b""
    while len(buf) < n:
        c = s.recv(n - len(buf))
        if not c:
            raise RuntimeError("conn closed")
        buf += c
    return buf


def via_socks5(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout)
    s.settimeout(timeout)
    try:
        methods = b"\x00\x02" if user else b"\x00"
        s.sendall(bytes([5, len(methods)]) + methods)
        ver, method = _recvn(s, 2)
        if method == 2:                                   # username/password (RFC1929)
            if not user:
                raise RuntimeError("can auth")
            s.sendall(b"\x01" + bytes([len(user)]) + user.encode()
                      + bytes([len(pwd)]) + pwd.encode())
            if _recvn(s, 2)[1] != 0:
                raise RuntimeError("sai user/pass")
        elif method != 0:
            raise RuntimeError("no method")
        dh = T_HOST.encode()
        s.sendall(b"\x05\x01\x00\x03" + bytes([len(dh)]) + dh + struct.pack(">H", T_PORT))
        rep = _recvn(s, 4)
        if rep[1] != 0:
            raise RuntimeError("connect rep %d" % rep[1])
        atyp = rep[3]                                     # doc not dia chi bound
        if atyp == 1:
            _recvn(s, 6)
        elif atyp == 3:
            _recvn(s, _recvn(s, 1)[0] + 2)
        elif atyp == 4:
            _recvn(s, 18)
        code, body = _http_request_line_via_target(s)
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


def via_socks4(host, port, user, pwd, timeout):
    s = socket.create_connection((host, port), timeout)
    s.settimeout(timeout)
    try:
        uid = (user or "").encode()
        # SOCKS4a: IP 0.0.0.1 + domain sau userid -> proxy tu resolve
        s.sendall(b"\x04\x01" + struct.pack(">H", T_PORT) + b"\x00\x00\x00\x01"
                  + uid + b"\x00" + T_HOST.encode() + b"\x00")
        r = _recvn(s, 8)
        if r[1] != 0x5A:
            raise RuntimeError("reject 0x%02X" % r[1])
        code, body = _http_request_line_via_target(s)
        if code == 200:
            return body
        raise RuntimeError("HTTP %s" % (code if code > 0 else "?"))
    finally:
        s.close()


CHECKERS = {"http": via_http, "socks5": via_socks5, "socks4": via_socks4}
TRY_ORDER = ["http", "socks5", "socks4"]


def check(raw, timeout):
    p = parse_line(raw)
    if not p:
        return {"raw": raw.strip(), "ok": False, "err": "format sai", "skip": True}
    scheme, host, port, user, pwd = p
    norm = "{}:{}:{}:{}".format(host, port, user, pwd) if user else "{}:{}".format(host, port)

    # TCP connect 1 lan: refused/timeout -> chet luon, khoi thu 3 loai
    t0 = time.time()
    try:
        socket.create_connection((host, port), timeout).close()
    except Exception as e:
        return {"raw": norm, "ok": False,
                "err": "connect: " + (str(e).split("] ")[-1][:24] or "timeout"),
                "ms": int((time.time() - t0) * 1000)}

    order = [scheme] if scheme else TRY_ORDER
    last = "?"
    for typ in order:
        ts = time.time()
        try:
            body = CHECKERS[typ](host, port, user, pwd, timeout)
            d = json.loads(body)
            if d.get("status") != "success":
                last = "resp la"; continue
            return {"raw": norm, "ok": True, "type": typ,
                    "ms": int((time.time() - ts) * 1000),
                    "ip": d.get("query", "?"),
                    "geo": "{} · {}".format(d.get("country", "?"), (d.get("isp") or "")[:22])}
        except Exception as e:
            last = str(e)[:26]
    return {"raw": norm, "ok": False, "err": last, "ms": int((time.time() - t0) * 1000),
            "tried": "/".join(order)}


def main():
    ap = argparse.ArgumentParser(description="Check proxy hang loat, tu detect HTTP/SOCKS5/SOCKS4.")
    ap.add_argument("file", nargs="?", help="file proxy (moi dong 1 con). Bo trong = stdin.")
    ap.add_argument("-t", "--threads", type=int, default=50, help="so luong song song (mac dinh 50)")
    ap.add_argument("-T", "--timeout", type=int, default=12, help="timeout moi con, giay (mac dinh 12)")
    ap.add_argument("-o", "--out", default="alive.txt", help="file luu proxy SONG (mac dinh alive.txt)")
    a = ap.parse_args()

    src = open(a.file, encoding="utf-8", errors="ignore") if a.file else sys.stdin
    lines = [l for l in src.read().splitlines() if l.strip() and not l.strip().startswith("#")]
    if a.file:
        src.close()
    if not lines:
        print("Khong co proxy nao de check."); return

    print("{}» Check {} proxy · {} luong · timeout {}s · tu detect HTTP/SOCKS5/SOCKS4{}\n".format(
        C["y"], len(lines), a.threads, a.timeout, C["x"]))

    alive, dead, done = [], 0, 0
    TCOL = {"http": C["c"], "socks5": C["g"], "socks4": C["y"]}
    with ThreadPoolExecutor(max_workers=a.threads) as ex:
        futs = [ex.submit(check, l, a.timeout) for l in lines]
        for f in as_completed(futs):
            r = f.result()
            done += 1
            tag = "[{}/{}]".format(done, len(lines))
            if r["ok"]:
                alive.append(r)
                print("{}{} ✓{} {}{:<7}{} {:<22} {:>5}ms  {}  {}{}".format(
                    C["g"], tag, C["x"], TCOL.get(r["type"], ""), r["type"], C["x"],
                    r["raw"], r["ms"], r["ip"], r["geo"], C["x"]))
            else:
                dead += 1
                print("{}{} ✗ {:<22} {}{}".format(
                    C["d"], tag, r.get("raw", "")[:22], r["err"], C["x"]))

    alive.sort(key=lambda x: x["ms"])
    with open(a.out, "w", encoding="utf-8") as fo:
        for r in alive:                                   # luu kem scheme de tai su dung
            host_port = r["raw"]
            fo.write("{}://{}\n".format(r["type"], host_port))

    by = {}
    for r in alive:
        by[r["type"]] = by.get(r["type"], 0) + 1
    print("\n{}━━━ KET QUA ━━━{}".format(C["y"], C["x"]))
    print("  {}SONG: {}{}   {}CHET: {}{}   tong {}   ({})".format(
        C["g"], len(alive), C["x"], C["r"], dead, C["x"], len(lines),
        ", ".join("{} {}".format(k, v) for k, v in by.items()) or "—"))
    if alive:
        a0 = alive[0]
        print("  Nhanh nhat: {}{}://{}  {}ms{}".format(C["g"], a0["type"], a0["raw"], a0["ms"], C["x"]))
        print("  → Da luu {} proxy song (kem scheme) vao: {}{}{}".format(len(alive), C["y"], a.out, C["x"]))


if __name__ == "__main__":
    main()