proxy_tunnel.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. """Unified local proxy tunnel component with multiple backend implementations.
  2. Supported implementations:
  3. 1. HttpAuthTunnel (pure Python in-process socket tunnel for upstream HTTP basic-auth injection)
  4. 2. MihomoTunnel (subprocess tunnel using Mihomo / Clash Meta for advanced protocols and relay chaining)
  5. """
  6. import os
  7. import time
  8. import socket
  9. import select
  10. import base64
  11. import yaml
  12. import tempfile
  13. import shutil
  14. import subprocess
  15. import threading
  16. import urllib.request
  17. from abc import ABC, abstractmethod
  18. from typing import Optional, Dict, Any
  19. def get_free_port() -> int:
  20. """Finds an available TCP port on 127.0.0.1."""
  21. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  22. s.bind(('127.0.0.1', 0))
  23. return s.getsockname()[1]
  24. class BaseProxyTunnel(ABC):
  25. """Abstract base class for all local proxy tunnel implementations."""
  26. def __init__(self):
  27. self.local_port: int = 0
  28. self.running: bool = False
  29. @property
  30. def is_running(self) -> bool:
  31. return self.running
  32. @property
  33. def proxy_url(self) -> str:
  34. return f"127.0.0.1:{self.local_port}"
  35. @abstractmethod
  36. def start(self) -> str:
  37. """Starts the tunnel and returns the local proxy address (127.0.0.1:<port>)."""
  38. pass
  39. @abstractmethod
  40. def stop(self) -> None:
  41. """Stops the tunnel and cleans up all allocated resources."""
  42. pass
  43. def cut_all_connections(self) -> bool:
  44. """Optional hook to forcibly sever all active connections; returns False if unsupported."""
  45. return False
  46. def __enter__(self):
  47. self.start()
  48. return self
  49. def __exit__(self, exc_type, exc_val, exc_tb):
  50. self.stop()
  51. def __del__(self):
  52. try:
  53. self.stop()
  54. except Exception:
  55. pass
  56. class HttpAuthTunnel(BaseProxyTunnel):
  57. """
  58. Pure Python in-process local HTTP proxy tunnel.
  59. 1. Injects Proxy-Authorization headers for upstream proxies without requiring external binaries.
  60. 2. Enables TCP_NODELAY and SO_KEEPALIVE to eliminate handshake and idle disconnect latency.
  61. 3. Uses select-multiplexed blocking I/O to guarantee data delivery.
  62. """
  63. def __init__(self, upstream_ip: str, upstream_port: int, username: str = "", password: str = ""):
  64. super().__init__()
  65. self.upstream_ip = upstream_ip
  66. self.upstream_port = int(upstream_port)
  67. self.username = username
  68. self.password = password
  69. if username or password:
  70. auth_str = f"{username}:{password}"
  71. b64_auth = base64.b64encode(auth_str.encode()).decode()
  72. self.auth_header = f"Proxy-Authorization: Basic {b64_auth}\r\n"
  73. else:
  74. self.auth_header = ""
  75. self.server_socket: Optional[socket.socket] = None
  76. self.listen_thread: Optional[threading.Thread] = None
  77. def start(self) -> str:
  78. try:
  79. self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  80. self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  81. self.server_socket.bind(('127.0.0.1', 0))
  82. self.local_port = self.server_socket.getsockname()[1]
  83. self.server_socket.listen(128)
  84. self.running = True
  85. self.listen_thread = threading.Thread(target=self._accept_loop, daemon=True)
  86. self.listen_thread.start()
  87. return self.proxy_url
  88. except Exception as e:
  89. self.stop()
  90. raise RuntimeError(f"Failed to start HttpAuthTunnel: {e}") from e
  91. def stop(self) -> None:
  92. self.running = False
  93. if self.server_socket:
  94. try:
  95. self.server_socket.close()
  96. except Exception:
  97. pass
  98. self.server_socket = None
  99. def _accept_loop(self):
  100. while self.running:
  101. try:
  102. if self.server_socket:
  103. r, _, _ = select.select([self.server_socket], [], [], 1.0)
  104. if r:
  105. try:
  106. client_sock, _ = self.server_socket.accept()
  107. t = threading.Thread(target=self._handle_client, args=(client_sock,), daemon=True)
  108. t.start()
  109. except OSError:
  110. break
  111. except Exception:
  112. continue
  113. @staticmethod
  114. def _optimize_socket(sock: socket.socket):
  115. try:
  116. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  117. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  118. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32 * 1024)
  119. sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32 * 1024)
  120. except Exception:
  121. pass
  122. def _handle_client(self, client_sock: socket.socket):
  123. upstream_sock = None
  124. try:
  125. self._optimize_socket(client_sock)
  126. client_sock.settimeout(30)
  127. try:
  128. first_packet = client_sock.recv(32768)
  129. except socket.timeout:
  130. return
  131. if not first_packet:
  132. return
  133. upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  134. self._optimize_socket(upstream_sock)
  135. upstream_sock.settimeout(10)
  136. upstream_sock.connect((self.upstream_ip, self.upstream_port))
  137. upstream_sock.settimeout(None)
  138. client_sock.settimeout(None)
  139. if self.auth_header:
  140. sep = b'\r\n'
  141. idx = first_packet.find(sep)
  142. if idx != -1:
  143. new_packet = first_packet[:idx + 2] + self.auth_header.encode() + first_packet[idx + 2:]
  144. else:
  145. new_packet = first_packet
  146. else:
  147. new_packet = first_packet
  148. upstream_sock.sendall(new_packet)
  149. self._pipe_sockets(client_sock, upstream_sock)
  150. except Exception:
  151. pass
  152. finally:
  153. self._close_socket(client_sock)
  154. self._close_socket(upstream_sock)
  155. def _pipe_sockets(self, sock1: socket.socket, sock2: socket.socket):
  156. sockets = [sock1, sock2]
  157. last_activity = time.time()
  158. idle_timeout = 120
  159. while self.running:
  160. try:
  161. r, _, x = select.select(sockets, [], sockets, 1.0)
  162. if x:
  163. break
  164. if not r:
  165. if time.time() - last_activity > idle_timeout:
  166. break
  167. continue
  168. for s in r:
  169. try:
  170. data = s.recv(32768)
  171. except ConnectionResetError:
  172. data = None
  173. if not data:
  174. return
  175. target = sock2 if s is sock1 else sock1
  176. try:
  177. target.sendall(data)
  178. except BrokenPipeError:
  179. return
  180. last_activity = time.time()
  181. except Exception:
  182. break
  183. @staticmethod
  184. def _close_socket(sock: Optional[socket.socket]):
  185. if sock:
  186. try:
  187. sock.shutdown(socket.SHUT_RDWR)
  188. except Exception:
  189. pass
  190. try:
  191. sock.close()
  192. except Exception:
  193. pass
  194. class MihomoTunnel(BaseProxyTunnel):
  195. """
  196. Subprocess-based local proxy tunnel using Mihomo (Clash Meta).
  197. Supports multi-instance concurrency, advanced protocols (SS, Vmess, Trojan),
  198. and proxy chaining via 'dialer-proxy'.
  199. """
  200. def __init__(self, mihomo_bin_path: str, exit_node: Dict[str, Any],
  201. relay_node: Optional[Dict[str, Any]] = None, enable_log: bool = False):
  202. super().__init__()
  203. self.mihomo_bin_path = os.path.abspath(mihomo_bin_path)
  204. self.exit_node = exit_node
  205. self.relay_node = relay_node
  206. self.enable_log = enable_log
  207. self.process: Optional[subprocess.Popen] = None
  208. self.api_port = 0
  209. self.log_file_obj = None
  210. self.temp_dir = tempfile.mkdtemp(prefix="mihomo_tunnel_")
  211. self.config_path = os.path.join(self.temp_dir, "config.yaml")
  212. self.log_path = os.path.join(self.temp_dir, "run.log")
  213. def _generate_config(self):
  214. self.local_port = get_free_port()
  215. self.api_port = get_free_port()
  216. config = {
  217. "allow-lan": False,
  218. "bind-address": "127.0.0.1",
  219. "log-level": "warning" if self.enable_log else "silent",
  220. "mixed-port": self.local_port,
  221. "external-controller": f"127.0.0.1:{self.api_port}",
  222. "mode": "rule",
  223. "ipv6": False,
  224. "dns": {
  225. "enable": False
  226. },
  227. "proxies": [],
  228. "rules": []
  229. }
  230. exit_node_config = dict(self.exit_node)
  231. if self.relay_node:
  232. config["proxies"].append(self.relay_node)
  233. exit_node_config["dialer-proxy"] = self.relay_node["name"]
  234. config["proxies"].append(exit_node_config)
  235. config["rules"].append(f"MATCH,{exit_node_config['name']}")
  236. with open(self.config_path, 'w', encoding='utf-8') as f:
  237. yaml.dump(config, f, allow_unicode=False, sort_keys=False)
  238. def start(self) -> str:
  239. if not os.path.exists(self.mihomo_bin_path):
  240. raise FileNotFoundError(f"Mihomo binary not found: {self.mihomo_bin_path}")
  241. self._generate_config()
  242. if self.enable_log:
  243. self.log_file_obj = open(self.log_path, 'w', encoding='utf-8')
  244. stdout_target = self.log_file_obj
  245. else:
  246. stdout_target = subprocess.DEVNULL
  247. try:
  248. self.process = subprocess.Popen(
  249. [self.mihomo_bin_path, "-d", self.temp_dir, "-f", self.config_path],
  250. stdout=stdout_target,
  251. stderr=subprocess.STDOUT,
  252. cwd=self.temp_dir
  253. )
  254. time.sleep(1.5)
  255. if self.process.poll() is not None:
  256. error_msg = "Mihomo failed to start and exited immediately."
  257. if self.enable_log:
  258. self.log_file_obj.close()
  259. with open(self.log_path, 'r', encoding='utf-8') as f:
  260. error_msg += f"\nLog:\n{f.read()}"
  261. raise RuntimeError(error_msg)
  262. self.running = True
  263. return self.proxy_url
  264. except Exception:
  265. self.stop()
  266. raise
  267. def cut_all_connections(self) -> bool:
  268. """Forces termination of all active connections in Mihomo via REST API."""
  269. if not self.process or self.process.poll() is not None:
  270. return False
  271. try:
  272. url = f"http://127.0.0.1:{self.api_port}/connections"
  273. req = urllib.request.Request(url, method="DELETE")
  274. with urllib.request.urlopen(req, timeout=3) as response:
  275. return response.status in (200, 204)
  276. except Exception as e:
  277. if self.enable_log:
  278. print(f"[MihomoTunnel] Failed to cut connections: {e}")
  279. return False
  280. def stop(self) -> None:
  281. self.running = False
  282. if self.process and self.process.poll() is None:
  283. self.process.terminate()
  284. try:
  285. self.process.wait(timeout=3)
  286. except subprocess.TimeoutExpired:
  287. self.process.kill()
  288. self.process.wait(timeout=3)
  289. self.process = None
  290. if self.log_file_obj and not self.log_file_obj.closed:
  291. self.log_file_obj.close()
  292. if os.path.exists(self.temp_dir):
  293. try:
  294. shutil.rmtree(self.temp_dir, ignore_errors=True)
  295. except Exception:
  296. pass
  297. # Aliases for backwards compatibility
  298. ProxyTunnel = HttpAuthTunnel
  299. MihomoProxyTunnel = MihomoTunnel