168 lines
5.4 KiB
Python
168 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""th_proxy_router.py — local rotating upstream proxy for Chrome CDP.
|
|
|
|
Listens on 127.0.0.1:8077. Forwards HTTP/HTTPS(CONNECT) through a pool of
|
|
upstream free proxies (_good_proxies.txt), rotating the active upstream every
|
|
ROTATE_SEC seconds or immediately on connection failure.
|
|
|
|
Chrome launched with --proxy-server=http://127.0.0.1:8077 gets a fresh exit IP
|
|
without restarts.
|
|
"""
|
|
import socket, select, threading, time, sys, os
|
|
|
|
LISTEN_HOST, LISTEN_PORT = "127.0.0.1", 8077
|
|
ROTATE_SEC = 75
|
|
PROXY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_good_proxies.txt")
|
|
|
|
class Pool:
|
|
def __init__(self):
|
|
self.lock = threading.Lock()
|
|
self.proxies = []
|
|
self.cur = None
|
|
self.since = 0
|
|
self.bad = set()
|
|
self.reload()
|
|
|
|
def reload(self):
|
|
try:
|
|
ps = [l.strip() for l in open(PROXY_FILE) if l.strip()]
|
|
except Exception:
|
|
ps = []
|
|
with self.lock:
|
|
self.proxies = ps
|
|
self.bad.clear()
|
|
self.cur = None
|
|
|
|
def get(self):
|
|
with self.lock:
|
|
now = time.time()
|
|
if self.cur and (now - self.since) < ROTATE_SEC and self.cur not in self.bad:
|
|
return self.cur
|
|
cands = [p for p in self.proxies if p not in self.bad]
|
|
if not cands:
|
|
self.bad.clear()
|
|
cands = list(self.proxies)
|
|
if not cands:
|
|
return None
|
|
# pick next different from current
|
|
pick = None
|
|
for p in cands:
|
|
if p != self.cur:
|
|
pick = p; break
|
|
self.cur = pick or cands[0]
|
|
self.since = now
|
|
return self.cur
|
|
|
|
def mark_bad(self, p):
|
|
with self.lock:
|
|
self.bad.add(p)
|
|
if self.cur == p:
|
|
self.cur = None
|
|
|
|
POOL = Pool()
|
|
|
|
def parse_proxy(p):
|
|
# http://ip:port
|
|
s = p.split("://", 1)[-1]
|
|
ip, _, port = s.partition(":")
|
|
return ip, int(port or 80)
|
|
|
|
def pipe(a, b):
|
|
try:
|
|
while True:
|
|
r, _, _ = select.select([a, b], [], [], 60)
|
|
if not r: break
|
|
for s in r:
|
|
data = s.recv(65536)
|
|
if not data: return
|
|
(b if s is a else a).sendall(data)
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
for s in (a, b):
|
|
try: s.close()
|
|
except Exception: pass
|
|
|
|
def connect_upstream(target_host, target_port):
|
|
"""Return (upstream_sock, proxy_used) connected to target through pool proxy."""
|
|
tried = 0
|
|
while tried < 6:
|
|
p = POOL.get()
|
|
if not p: return None, None
|
|
pip, pport = parse_proxy(p)
|
|
try:
|
|
us = socket.create_connection((pip, pport), timeout=12)
|
|
req = f"CONNECT {target_host}:{target_port} HTTP/1.1\r\nHost: {target_host}:{target_port}\r\n\r\n"
|
|
us.sendall(req.encode())
|
|
resp = b""
|
|
us.settimeout(12)
|
|
while b"\r\n\r\n" not in resp:
|
|
chunk = us.recv(4096)
|
|
if not chunk: break
|
|
resp += chunk
|
|
first = resp.split(b"\r\n", 1)[0].decode(errors="ignore")
|
|
if "200" in first:
|
|
return us, p
|
|
us.close()
|
|
POOL.mark_bad(p)
|
|
except Exception:
|
|
POOL.mark_bad(p)
|
|
tried += 1
|
|
return None, None
|
|
|
|
def handle(client):
|
|
try:
|
|
client.settimeout(30)
|
|
head = b""
|
|
while b"\r\n\r\n" not in head:
|
|
chunk = client.recv(65536)
|
|
if not chunk: return
|
|
head += chunk
|
|
lines = head.split(b"\r\n")
|
|
method, target, _ = lines[0].decode(errors="ignore").split(" ", 2)
|
|
if method == "CONNECT":
|
|
host, _, port = target.partition(":")
|
|
us, used = connect_upstream(host, int(port or 443))
|
|
if not us:
|
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n"); return
|
|
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
pipe(client, us)
|
|
else:
|
|
# plain HTTP proxy request: forward as-is via upstream proxy
|
|
p = POOL.get()
|
|
if not p:
|
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n"); return
|
|
pip, pport = parse_proxy(p)
|
|
try:
|
|
us = socket.create_connection((pip, pport), timeout=12)
|
|
us.sendall(head)
|
|
pipe(client, us)
|
|
except Exception:
|
|
POOL.mark_bad(p)
|
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
try: client.close()
|
|
except Exception: pass
|
|
|
|
def main():
|
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
srv.bind((LISTEN_HOST, LISTEN_PORT))
|
|
srv.listen(64)
|
|
print(f"router up on {LISTEN_HOST}:{LISTEN_PORT}, pool={len(POOL.proxies)}", flush=True)
|
|
# periodic pool reload every 5 min (file may be refreshed externally)
|
|
def reloader():
|
|
while True:
|
|
time.sleep(300)
|
|
POOL.reload()
|
|
print(f"pool reloaded: {len(POOL.proxies)}", flush=True)
|
|
threading.Thread(target=reloader, daemon=True).start()
|
|
while True:
|
|
c, _ = srv.accept()
|
|
threading.Thread(target=handle, args=(c,), daemon=True).start()
|
|
|
|
if __name__ == "__main__":
|
|
main()
|