-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_converter.py
More file actions
198 lines (162 loc) · 6.75 KB
/
Copy pathproxy_converter.py
File metadata and controls
198 lines (162 loc) · 6.75 KB
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
import asyncio
import argparse
import struct
import urllib.parse
import socket
async def pipe(reader, writer):
try:
while True:
data = await reader.read(8192)
if not data:
break
writer.write(data)
await writer.drain()
except Exception:
pass
finally:
writer.close()
async def handle_socks2http(reader, writer, upstream_host, upstream_port):
try:
ver_nmethods = await reader.readexactly(2)
if ver_nmethods[0] != 5:
writer.close()
return
methods = await reader.readexactly(ver_nmethods[1])
writer.write(b'\x05\x00')
await writer.drain()
req = await reader.readexactly(4)
if req[1] != 1: # Only CONNECT supported
writer.write(b'\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00')
await writer.drain()
writer.close()
return
atyp = req[3]
if atyp == 1:
addr = socket.inet_ntoa(await reader.readexactly(4))
elif atyp == 3:
domain_len = (await reader.readexactly(1))[0]
addr = (await reader.readexactly(domain_len)).decode()
elif atyp == 4:
addr = socket.inet_ntop(socket.AF_INET6, await reader.readexactly(16))
else:
writer.close()
return
port_bytes = await reader.readexactly(2)
port = struct.unpack('!H', port_bytes)[0]
up_reader, up_writer = await asyncio.open_connection(upstream_host, upstream_port)
connect_req = f"CONNECT {addr}:{port} HTTP/1.1\r\nHost: {addr}:{port}\r\n\r\n"
up_writer.write(connect_req.encode())
await up_writer.drain()
resp = await up_reader.readuntil(b'\r\n\r\n')
if not resp.startswith(b'HTTP/1.1 200') and not resp.startswith(b'HTTP/1.0 200'):
writer.write(b'\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00')
await writer.drain()
writer.close()
up_writer.close()
return
writer.write(b'\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00')
await writer.drain()
asyncio.create_task(pipe(reader, up_writer))
asyncio.create_task(pipe(up_reader, writer))
except Exception:
writer.close()
async def handle_http2socks(reader, writer, upstream_host, upstream_port):
try:
line = await reader.readuntil(b'\r\n')
parts = line.decode().strip().split()
if len(parts) < 3:
writer.close()
return
method, url, version = parts
headers = b''
while True:
hline = await reader.readuntil(b'\r\n')
headers += hline
if hline == b'\r\n':
break
if method.upper() == 'CONNECT':
host, port = url.split(':')
port = int(port)
up_reader, up_writer = await asyncio.open_connection(upstream_host, upstream_port)
up_writer.write(b'\x05\x01\x00')
await up_writer.drain()
resp = await up_reader.readexactly(2)
if resp != b'\x05\x00':
writer.close()
up_writer.close()
return
host_bytes = host.encode()
req = b'\x05\x01\x00\x03' + bytes([len(host_bytes)]) + host_bytes + struct.pack('!H', port)
up_writer.write(req)
await up_writer.drain()
resp = await up_reader.readexactly(10)
if resp[1] != 0:
writer.close()
up_writer.close()
return
writer.write(b'HTTP/1.1 200 Connection Established\r\n\r\n')
await writer.drain()
asyncio.create_task(pipe(reader, up_writer))
asyncio.create_task(pipe(up_reader, writer))
else:
parsed = urllib.parse.urlparse(url)
host = parsed.hostname or url.split('/')[0]
port = parsed.port or 80
up_reader, up_writer = await asyncio.open_connection(upstream_host, upstream_port)
up_writer.write(b'\x05\x01\x00')
await up_writer.drain()
resp = await up_reader.readexactly(2)
if resp != b'\x05\x00':
writer.close()
up_writer.close()
return
host_bytes = host.encode()
req = b'\x05\x01\x00\x03' + bytes([len(host_bytes)]) + host_bytes + struct.pack('!H', port)
up_writer.write(req)
await up_writer.drain()
resp = await up_reader.readexactly(10)
if resp[1] != 0:
writer.close()
up_writer.close()
return
path = parsed.path if hasattr(parsed, 'path') else '/'
if getattr(parsed, 'query', ''): path += '?' + parsed.query
if not path: path = '/'
new_req = f"{method} {path} {version}\r\n".encode() + headers
up_writer.write(new_req)
await up_writer.drain()
asyncio.create_task(pipe(reader, up_writer))
asyncio.create_task(pipe(up_reader, writer))
except Exception:
writer.close()
async def main():
parser = argparse.ArgumentParser(description="Proxy Converter")
parser.add_argument("--socks2http", action="append", metavar="LISTEN_PORT:UPSTREAM_PORT", help="SOCKS5 listener forwarding to HTTP upstream")
parser.add_argument("--http2socks", action="append", metavar="LISTEN_PORT:UPSTREAM_PORT", help="HTTP listener forwarding to SOCKS5 upstream")
args = parser.parse_args()
servers = []
if args.socks2http:
for mapping in args.socks2http:
listen_p, upstream_p = map(int, mapping.split(':'))
handler = lambda r, w, uh="127.0.0.1", up=upstream_p: handle_socks2http(r, w, uh, up)
server = await asyncio.start_server(handler, '127.0.0.1', listen_p)
servers.append(server)
print(f"SOCKS2HTTP: Listening on {listen_p} -> 127.0.0.1:{upstream_p}")
if args.http2socks:
for mapping in args.http2socks:
listen_p, upstream_p = map(int, mapping.split(':'))
handler = lambda r, w, uh="127.0.0.1", up=upstream_p: handle_http2socks(r, w, uh, up)
server = await asyncio.start_server(handler, '127.0.0.1', listen_p)
servers.append(server)
print(f"HTTP2SOCKS: Listening on {listen_p} -> 127.0.0.1:{upstream_p}")
if not servers:
print("No proxy mappings specified.")
return
async with asyncio.TaskGroup() as tg:
for s in servers:
tg.create_task(s.serve_forever())
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass