Files

96 lines
3.2 KiB
Python

"""Local HTTP CONNECT relays with upstream Basic auth, for Chrome --proxy-server.
Usage: python relay2.py decodo_pool.json [base_port]
Writes relays.json: [{local: "127.0.0.1:9431", up: "host:port", user: "..."}]
"""
import base64, json, socket, sys, threading, time
def pipe(a, b):
try:
while True:
r, _, _ = select.select([a, b], [], [], 60)
if not r:
continue
for s in r:
d = s.recv(65536)
if not d:
return
(b if s is a else a).sendall(d)
except Exception:
pass
finally:
for s in (a, b):
try:
s.close()
except Exception:
pass
import select
def handle(cli, up_host, up_port, auth):
try:
data = b""
while b"\r\n\r\n" not in data:
ch = cli.recv(4096)
if not ch:
cli.close(); return
data += ch
if len(data) > 65536: break
line = data.split(b"\r\n")[0].decode("latin1")
method, target, _ = line.split(" ")
up = socket.create_connection((up_host, up_port), 20)
if method.upper() == "CONNECT":
hdr = "CONNECT %s HTTP/1.1\r\nHost: %s\r\n" % (target, target)
if auth:
hdr += "Proxy-Authorization: Basic %s\r\n" % auth
up.sendall((hdr + "\r\n").encode())
resp = b""
while b"\r\n\r\n" not in resp:
c = up.recv(4096)
if not c: break
resp += c
if b" 200" not in resp.split(b"\r\n")[0]:
cli.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
cli.close(); up.close(); return
cli.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
pipe(cli, up)
else:
rest = data.replace(b"Proxy-Connection:", b"X-Drop:")
if auth:
rest = rest.replace(b"\r\n\r\n", b"\r\nProxy-Authorization: Basic " + auth.encode() + b"\r\n\r\n", 1)
up.sendall(rest)
pipe(cli, up)
except Exception:
try: cli.close()
except Exception: pass
def serve(port, host, uport, auth):
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", port))
srv.listen(64)
while True:
c, _ = srv.accept()
threading.Thread(target=handle, args=(c, host, uport, auth), daemon=True).start()
if __name__ == "__main__":
pool = json.load(open(sys.argv[1], encoding="utf-8"))
base = int(sys.argv[2]) if len(sys.argv) > 2 else 9431
info, i = [], 0
for p in pool:
host, port = p["host"], int(p["port"])
auth = None
if p.get("user") and p.get("pass"):
auth = base64.b64encode(("%s:%s" % (p["user"], p["pass"])).encode()).decode()
threading.Thread(target=serve, args=(base + i, host, port, auth), daemon=True).start()
info.append({"local": "127.0.0.1:%d" % (base + i), "up": "%s:%s" % (host, port), "user": p.get("user")})
i += 1
json.dump(info, open("relays.json", "w"), indent=1)
print("relays up:", json.dumps(info), flush=True)
while True:
time.sleep(3600)