-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
426 lines (368 loc) · 14.1 KB
/
Copy pathproxy.py
File metadata and controls
426 lines (368 loc) · 14.1 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""Async HTTP→SOCKS5 proxy with SSH tunnel management."""
import asyncio
import logging
import os
import socket
import struct
import subprocess
import threading
import time
from collections import deque
from stats import Stats
logger = logging.getLogger("magic-proxy.proxy")
SOCKS5_TIMEOUT = 15 # seconds for SOCKS5 handshake
RELAY_BUF = 65536 # bytes per read
DRAIN_THRESHOLD = 256 * 1024 # bytes between explicit drains
PORT_PROBE_TIMEOUT = 0.1 # seconds for connecting-state probe
async def socks5_connect(host: str, port: int, socks_addr: str):
"""Establish a SOCKS5 connection (no auth) through the tunnel."""
socks_host, socks_port = socks_addr.split(":")
reader, writer = await asyncio.wait_for(
asyncio.open_connection(socks_host, int(socks_port)),
timeout=SOCKS5_TIMEOUT,
)
try:
async def handshake():
writer.write(b"\x05\x01\x00")
await writer.drain()
resp = await reader.readexactly(2)
if resp != b"\x05\x00":
raise RuntimeError(f"SOCKS5 handshake rejected: {resp.hex()}")
try:
ip = socket.inet_aton(host)
addr_type = b"\x01"
addr = ip
except OSError:
addr_type = b"\x03"
addr = len(host).to_bytes(1, "big") + host.encode()
writer.write(b"\x05\x01\x00" + addr_type + addr + struct.pack("!H", port))
await writer.drain()
header = await reader.readexactly(4)
if header[0] != 0x05 or header[1] != 0x00:
raise RuntimeError(f"SOCKS5 connect failed: status={header[1]}")
atyp = header[3]
if atyp == 0x01:
await reader.readexactly(6)
elif atyp == 0x03:
length = (await reader.readexactly(1))[0]
await reader.readexactly(length + 2)
elif atyp == 0x04:
await reader.readexactly(18)
else:
raise RuntimeError(f"SOCKS5 unknown address type: {atyp}")
await asyncio.wait_for(handshake(), timeout=SOCKS5_TIMEOUT)
return reader, writer
except Exception:
writer.close()
try:
await writer.wait_closed()
except Exception:
pass
raise
async def bidirectional_relay(ra, wa, rb, wb, stats):
"""Half-close-aware relay: each direction drains independently, then EOFs."""
async def relay(src, dst, record):
bytes_since_drain = 0
try:
while True:
data = await src.read(RELAY_BUF)
if not data:
break
dst.write(data)
record(len(data))
bytes_since_drain += len(data)
if bytes_since_drain >= DRAIN_THRESHOLD:
await dst.drain()
bytes_since_drain = 0
try:
await dst.drain()
except Exception:
pass
except (ConnectionError, OSError, asyncio.CancelledError):
pass
finally:
try:
if dst.can_write_eof():
dst.write_eof()
except Exception:
pass
await asyncio.gather(
relay(ra, wb, stats.record_up),
relay(rb, wa, stats.record_down),
return_exceptions=True,
)
for w in (wa, wb):
try:
w.close()
except Exception:
pass
async def handle_connect(client_reader, client_writer, host, port, socks_addr, stats):
"""Handle HTTP CONNECT (HTTPS) tunneling."""
stats.inc_connections()
try:
while True:
line = await client_reader.readline()
if line == b"\r\n" or line == b"":
break
try:
remote_reader, remote_writer = await socks5_connect(host, port, socks_addr)
except Exception as e:
logger.error("SOCKS5 connect to %s:%s failed: %s", host, port, e)
client_writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
await client_writer.drain()
client_writer.close()
return
client_writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
await client_writer.drain()
await bidirectional_relay(client_reader, client_writer, remote_reader, remote_writer, stats)
finally:
stats.dec_connections()
async def handle_http(client_reader, client_writer, request_line, socks_addr, stats):
"""Handle plain HTTP request via SOCKS5."""
stats.inc_connections()
try:
method, url, _ = request_line.decode().split(maxsplit=2)
if url.startswith("http://"):
url = url[7:]
host, _, rest = url.partition("/")
if ":" in host:
host, port_str = host.split(":", 1)
port = int(port_str)
else:
port = 80
try:
remote_reader, remote_writer = await socks5_connect(host, port, socks_addr)
except Exception as e:
logger.error("SOCKS5 connect to %s:%s failed: %s", host, port, e)
client_writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
await client_writer.drain()
client_writer.close()
return
path = "/" + rest if rest else "/"
remote_writer.write(f"{method} {path} HTTP/1.1\r\n".encode())
while True:
line = await client_reader.readline()
if line == b"\r\n" or line == b"":
break
remote_writer.write(line)
remote_writer.write(b"\r\n")
await remote_writer.drain()
await bidirectional_relay(client_reader, client_writer, remote_reader, remote_writer, stats)
finally:
stats.dec_connections()
async def handle_client(client_reader, client_writer, socks_addr, stats):
"""Process one HTTP proxy client."""
try:
request_line = await client_reader.readline()
if not request_line:
client_writer.close()
return
parts = request_line.decode(errors="replace").split()
if len(parts) < 2:
client_writer.close()
return
method, target = parts[0], parts[1]
if method == "CONNECT":
host, _, port_str = target.partition(":")
if not port_str:
client_writer.close()
return
await handle_connect(client_reader, client_writer, host, int(port_str), socks_addr, stats)
else:
await handle_http(client_reader, client_writer, request_line, socks_addr, stats)
except asyncio.CancelledError:
raise
except (ConnectionResetError, BrokenPipeError, asyncio.IncompleteReadError) as e:
# Client closed mid-stream — normal browser/curl behavior, not an error.
logger.debug("client disconnected: %s", e)
try:
client_writer.close()
except Exception:
pass
except Exception:
logger.exception("Error handling client")
try:
client_writer.close()
except Exception:
pass
class SSHMonitor:
"""Manages an SSH SOCKS5 tunnel subprocess."""
def __init__(self):
self.process = None
self._status = "stopped"
self._error_msg = ""
self._cmd_str = ""
self._log_lines = deque(maxlen=100)
self._log_lock = threading.Lock()
self._start_time = 0
self._log_thread = None
self._current_name = ""
@property
def status(self):
return self._status
@property
def error_msg(self):
return self._error_msg
@property
def cmd_str(self):
return self._cmd_str
@property
def log(self) -> str:
with self._log_lock:
lines = list(self._log_lines)
return "\n".join(lines[-5:])
@property
def elapsed(self) -> float:
if self._start_time and self._status in ("connecting", "connected"):
return time.monotonic() - self._start_time
return 0
@property
def current_name(self) -> str:
return self._current_name
def start(self, tunnel: dict, socks5_port: int, password: str = ""):
"""Start the SSH tunnel subprocess for the given tunnel config."""
self.stop()
user = tunnel.get("ssh_user", "")
host = tunnel["ssh_host"]
port = str(tunnel.get("ssh_port", 22))
auth_type = tunnel.get("auth_type", "key")
compression = tunnel.get("ssh_compression", True)
destination = f"{user}@{host}" if user else host
ssh_args = [
"-D", str(socks5_port),
"-N",
"-o", "ExitOnForwardFailure=yes",
"-o", "StrictHostKeyChecking=accept-new",
]
if compression:
ssh_args.append("-C")
ssh_args.extend(["-p", port, destination])
# sshpass via fd avoids leaking the password into `ps`.
pass_fds = ()
r_fd = None
if auth_type == "password":
r_fd, w_fd = os.pipe()
try:
os.write(w_fd, (password + "\n").encode())
finally:
os.close(w_fd)
cmd = ["sshpass", "-d", str(r_fd), "ssh"] + ssh_args
pass_fds = (r_fd,)
display_cmd = ["sshpass", "-d", "***", "ssh"] + ssh_args
else:
key = tunnel.get("ssh_key", "")
cmd = ["ssh", "-i", key] + ssh_args
display_cmd = cmd
self._cmd_str = " ".join(display_cmd)
self._current_name = tunnel.get("name", destination)
self._status = "connecting"
self._error_msg = ""
with self._log_lock:
self._log_lines.clear()
self._start_time = time.monotonic()
try:
self.process = subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
pass_fds=pass_fds,
)
finally:
if r_fd is not None:
try:
os.close(r_fd)
except OSError:
pass
self._log_thread = threading.Thread(target=self._read_stderr, daemon=True)
self._log_thread.start()
logger.info("SSH starting: %s", self._cmd_str)
def _read_stderr(self):
# Owns the stderr pipe: closes it in finally so the fd always releases
# (on EOF when ssh exits, or on exception). This close must NOT happen on
# the main thread — BufferedReader.close() takes the buffer lock this
# loop holds while blocked in read(), which deadlocked _quit.
try:
for line in self.process.stderr:
decoded = line.decode(errors="replace").rstrip()
if decoded:
with self._log_lock:
self._log_lines.append(decoded)
except Exception:
logger.exception("stderr reader crashed")
finally:
try:
self.process.stderr.close()
except Exception:
pass
def stop(self, blocking=True):
"""Stop the SSH process.
Order matters: terminate() FIRST, then wait. We never close stderr here
— the reader thread owns that pipe and closes it on EOF (see
_read_stderr). Calling stderr.close() on this thread deadlocks:
BufferedReader.close() blocks on the same buffer lock the reader holds
while blocked in read(). That deadlock, not process.wait(), is the real
"click Quit, app hangs" bug.
blocking=False (quit path) sends SIGTERM and returns immediately; the
pipe and reader thread are reclaimed when the process exits.
"""
if self.process is None:
return
self.process.terminate()
if not blocking:
# Drop the handle; the OS process exits on the already-delivered SIGTERM.
self.process = None
self._status = "stopped"
return
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self._wait_log_thread()
self.process = None
self._status = "stopped"
def _wait_log_thread(self):
if self._log_thread and self._log_thread.is_alive():
self._log_thread.join(timeout=1)
def check(self, socks5_port: int):
"""Poll the subprocess; only probe the SOCKS5 port while connecting."""
if self.process is None:
return
ret = self.process.poll()
if ret is not None:
self._status = "error"
self._wait_log_thread()
with self._log_lock:
lines = list(self._log_lines)
self._error_msg = "\n".join(lines) or f"SSH exited with code {ret}"
logger.warning("SSH exited (%s): %s", ret, self._error_msg)
self.process = None
return
# Once we're connected the SSH process death is the only thing left to
# observe; skipping the probe keeps the UI thread from blocking on
# connect() every second.
if self._status != "connecting":
return
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(PORT_PROBE_TIMEOUT)
s.connect(("127.0.0.1", socks5_port))
self._status = "connected"
logger.info("SSH tunnel ready on port %d", socks5_port)
except (ConnectionRefusedError, OSError):
pass
finally:
s.close()
async def run_proxy(config: dict, stats: Stats, control: dict):
"""Start the HTTP→SOCKS5 proxy server (runs in background thread's asyncio loop)."""
socks_addr = f"127.0.0.1:{config['socks5_port']}"
listen_host, listen_port = config["http_listen"].rsplit(":", 1)
listen_port = int(listen_port)
server = await asyncio.start_server(
lambda r, w: handle_client(r, w, socks_addr, stats),
listen_host, listen_port,
)
control["server"] = server
logger.info("HTTP proxy listening on %s:%d → SOCKS5 %s", listen_host, listen_port, socks_addr)
async with server:
await server.serve_forever()