Files

132 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Tiny SOCKS5 (1080) and HTTP CONNECT/absolute-URI (8081) proxies for the
proxy verification. No auth, TCP only.
"""
import select
import socket
import struct
import threading
def recv_exact(conn, n):
buf = b''
while len(buf) < n:
d = conn.recv(n - len(buf))
if not d:
raise ConnectionError('closed')
buf += d
return buf
def pump(a, b):
try:
while True:
r, _, _ = select.select([a, b], [], [], 300)
if not r:
continue
for s in r:
data = s.recv(65536)
if not data:
return
(b if s is a else a).sendall(data)
except OSError:
pass
finally:
for s in (a, b):
try:
s.close()
except OSError:
pass
def socks_conn(conn):
try:
ver, n = recv_exact(conn, 2)
recv_exact(conn, n)
conn.sendall(bytes([5, 0]))
ver, cmd, rsv, atyp = recv_exact(conn, 4)
if atyp == 1:
addr = socket.inet_ntoa(recv_exact(conn, 4))
elif atyp == 3:
ln = recv_exact(conn, 1)[0]
addr = recv_exact(conn, ln).decode()
elif atyp == 4:
addr = socket.inet_ntop(socket.AF_INET6, recv_exact(conn, 16))
else:
raise ValueError('atyp')
port = struct.unpack('!H', recv_exact(conn, 2))[0]
print(f'socks CONNECT {addr}:{port}', flush=True)
remote = socket.create_connection((addr, port), timeout=15)
conn.sendall(bytes([5, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
pump(conn, remote)
except Exception as e: # noqa: BLE001
print('socks error', e, flush=True)
conn.close()
def http_conn(conn):
try:
buf = b''
while b'\r\n\r\n' not in buf:
d = conn.recv(65536)
if not d:
return
buf += d
head, rest = buf.split(b'\r\n\r\n', 1)
lines = head.split(b'\r\n')
method, target, version = lines[0].split(b' ')
if method == b'CONNECT':
host, _, port = target.decode().partition(':')
remote = socket.create_connection((host, int(port or 443)), timeout=15)
conn.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')
if rest:
remote.sendall(rest)
print(f'http CONNECT {host}:{port}', flush=True)
pump(conn, remote)
return
if not target.startswith(b'http://'):
conn.sendall(b'HTTP/1.1 400 Bad Request\r\n\r\n')
conn.close()
return
rest_of_url = target[len(b'http://'):]
hostport, _, path = rest_of_url.partition(b'/')
host, _, port = hostport.partition(b':')
port = int(port or b'80')
hdrs = [l for l in lines[1:]
if not l.lower().startswith(b'proxy-') and not l.lower().startswith(b'connection:')]
clen = 0
for l in hdrs:
if l.lower().startswith(b'content-length:'):
clen = int(l.split(b':', 1)[1].strip())
body = rest
while len(body) < clen:
d = conn.recv(65536)
if not d:
break
body += d
request = b' '.join([method, b'/' + path, version]) + b'\r\n' + \
b'\r\n'.join(hdrs) + b'\r\nConnection: close\r\n\r\n' + body[:clen]
remote = socket.create_connection((host.decode(), port), timeout=15)
remote.sendall(request)
print(f'http {method.decode()} {host.decode()}:{port}/{path.decode(errors="replace")}', flush=True)
pump(conn, remote)
except Exception as e: # noqa: BLE001
print('http error', e, flush=True)
conn.close()
def serve(port, handler):
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('127.0.0.1', port))
srv.listen(64)
print(f'listening on 127.0.0.1:{port}', flush=True)
while True:
conn, _ = srv.accept()
threading.Thread(target=handler, args=(conn,), daemon=True).start()
threading.Thread(target=serve, args=(1080, socks_conn), daemon=True).start()
threading.Thread(target=serve, args=(8081, http_conn), daemon=True).start()
threading.Event().wait()