"""Unified local proxy tunnel component with multiple backend implementations. Supported implementations: 1. HttpAuthTunnel (pure Python in-process socket tunnel for upstream HTTP basic-auth injection) 2. MihomoTunnel (subprocess tunnel using Mihomo / Clash Meta for advanced protocols and relay chaining) """ import os import time import socket import select import base64 import yaml import tempfile import shutil import subprocess import threading import urllib.request from abc import ABC, abstractmethod from typing import Optional, Dict, Any def get_free_port() -> int: """Finds an available TCP port on 127.0.0.1.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('127.0.0.1', 0)) return s.getsockname()[1] class BaseProxyTunnel(ABC): """Abstract base class for all local proxy tunnel implementations.""" def __init__(self): self.local_port: int = 0 self.running: bool = False @property def is_running(self) -> bool: return self.running @property def proxy_url(self) -> str: return f"127.0.0.1:{self.local_port}" @abstractmethod def start(self) -> str: """Starts the tunnel and returns the local proxy address (127.0.0.1:).""" pass @abstractmethod def stop(self) -> None: """Stops the tunnel and cleans up all allocated resources.""" pass def cut_all_connections(self) -> bool: """Optional hook to forcibly sever all active connections; returns False if unsupported.""" return False def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop() def __del__(self): try: self.stop() except Exception: pass class HttpAuthTunnel(BaseProxyTunnel): """ Pure Python in-process local HTTP proxy tunnel. 1. Injects Proxy-Authorization headers for upstream proxies without requiring external binaries. 2. Enables TCP_NODELAY and SO_KEEPALIVE to eliminate handshake and idle disconnect latency. 3. Uses select-multiplexed blocking I/O to guarantee data delivery. """ def __init__(self, upstream_ip: str, upstream_port: int, username: str = "", password: str = ""): super().__init__() self.upstream_ip = upstream_ip self.upstream_port = int(upstream_port) self.username = username self.password = password if username or password: auth_str = f"{username}:{password}" b64_auth = base64.b64encode(auth_str.encode()).decode() self.auth_header = f"Proxy-Authorization: Basic {b64_auth}\r\n" else: self.auth_header = "" self.server_socket: Optional[socket.socket] = None self.listen_thread: Optional[threading.Thread] = None def start(self) -> str: try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(('127.0.0.1', 0)) self.local_port = self.server_socket.getsockname()[1] self.server_socket.listen(128) self.running = True self.listen_thread = threading.Thread(target=self._accept_loop, daemon=True) self.listen_thread.start() return self.proxy_url except Exception as e: self.stop() raise RuntimeError(f"Failed to start HttpAuthTunnel: {e}") from e def stop(self) -> None: self.running = False if self.server_socket: try: self.server_socket.close() except Exception: pass self.server_socket = None def _accept_loop(self): while self.running: try: if self.server_socket: r, _, _ = select.select([self.server_socket], [], [], 1.0) if r: try: client_sock, _ = self.server_socket.accept() t = threading.Thread(target=self._handle_client, args=(client_sock,), daemon=True) t.start() except OSError: break except Exception: continue @staticmethod def _optimize_socket(sock: socket.socket): try: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32 * 1024) sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32 * 1024) except Exception: pass def _handle_client(self, client_sock: socket.socket): upstream_sock = None try: self._optimize_socket(client_sock) client_sock.settimeout(30) try: first_packet = client_sock.recv(32768) except socket.timeout: return if not first_packet: return upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._optimize_socket(upstream_sock) upstream_sock.settimeout(10) upstream_sock.connect((self.upstream_ip, self.upstream_port)) upstream_sock.settimeout(None) client_sock.settimeout(None) if self.auth_header: sep = b'\r\n' idx = first_packet.find(sep) if idx != -1: new_packet = first_packet[:idx + 2] + self.auth_header.encode() + first_packet[idx + 2:] else: new_packet = first_packet else: new_packet = first_packet upstream_sock.sendall(new_packet) self._pipe_sockets(client_sock, upstream_sock) except Exception: pass finally: self._close_socket(client_sock) self._close_socket(upstream_sock) def _pipe_sockets(self, sock1: socket.socket, sock2: socket.socket): sockets = [sock1, sock2] last_activity = time.time() idle_timeout = 120 while self.running: try: r, _, x = select.select(sockets, [], sockets, 1.0) if x: break if not r: if time.time() - last_activity > idle_timeout: break continue for s in r: try: data = s.recv(32768) except ConnectionResetError: data = None if not data: return target = sock2 if s is sock1 else sock1 try: target.sendall(data) except BrokenPipeError: return last_activity = time.time() except Exception: break @staticmethod def _close_socket(sock: Optional[socket.socket]): if sock: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass try: sock.close() except Exception: pass class MihomoTunnel(BaseProxyTunnel): """ Subprocess-based local proxy tunnel using Mihomo (Clash Meta). Supports multi-instance concurrency, advanced protocols (SS, Vmess, Trojan), and proxy chaining via 'dialer-proxy'. """ def __init__(self, mihomo_bin_path: str, exit_node: Dict[str, Any], relay_node: Optional[Dict[str, Any]] = None, enable_log: bool = False): super().__init__() self.mihomo_bin_path = os.path.abspath(mihomo_bin_path) self.exit_node = exit_node self.relay_node = relay_node self.enable_log = enable_log self.process: Optional[subprocess.Popen] = None self.api_port = 0 self.log_file_obj = None self.temp_dir = tempfile.mkdtemp(prefix="mihomo_tunnel_") self.config_path = os.path.join(self.temp_dir, "config.yaml") self.log_path = os.path.join(self.temp_dir, "run.log") def _generate_config(self): self.local_port = get_free_port() self.api_port = get_free_port() config = { "allow-lan": False, "bind-address": "127.0.0.1", "log-level": "warning" if self.enable_log else "silent", "mixed-port": self.local_port, "external-controller": f"127.0.0.1:{self.api_port}", "mode": "rule", "ipv6": False, "dns": { "enable": False }, "proxies": [], "rules": [] } exit_node_config = dict(self.exit_node) if self.relay_node: config["proxies"].append(self.relay_node) exit_node_config["dialer-proxy"] = self.relay_node["name"] config["proxies"].append(exit_node_config) config["rules"].append(f"MATCH,{exit_node_config['name']}") with open(self.config_path, 'w', encoding='utf-8') as f: yaml.dump(config, f, allow_unicode=False, sort_keys=False) def start(self) -> str: if not os.path.exists(self.mihomo_bin_path): raise FileNotFoundError(f"Mihomo binary not found: {self.mihomo_bin_path}") self._generate_config() if self.enable_log: self.log_file_obj = open(self.log_path, 'w', encoding='utf-8') stdout_target = self.log_file_obj else: stdout_target = subprocess.DEVNULL try: self.process = subprocess.Popen( [self.mihomo_bin_path, "-d", self.temp_dir, "-f", self.config_path], stdout=stdout_target, stderr=subprocess.STDOUT, cwd=self.temp_dir ) time.sleep(1.5) if self.process.poll() is not None: error_msg = "Mihomo failed to start and exited immediately." if self.enable_log: self.log_file_obj.close() with open(self.log_path, 'r', encoding='utf-8') as f: error_msg += f"\nLog:\n{f.read()}" raise RuntimeError(error_msg) self.running = True return self.proxy_url except Exception: self.stop() raise def cut_all_connections(self) -> bool: """Forces termination of all active connections in Mihomo via REST API.""" if not self.process or self.process.poll() is not None: return False try: url = f"http://127.0.0.1:{self.api_port}/connections" req = urllib.request.Request(url, method="DELETE") with urllib.request.urlopen(req, timeout=3) as response: return response.status in (200, 204) except Exception as e: if self.enable_log: print(f"[MihomoTunnel] Failed to cut connections: {e}") return False def stop(self) -> None: self.running = False if self.process and self.process.poll() is None: self.process.terminate() try: self.process.wait(timeout=3) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=3) self.process = None if self.log_file_obj and not self.log_file_obj.closed: self.log_file_obj.close() if os.path.exists(self.temp_dir): try: shutil.rmtree(self.temp_dir, ignore_errors=True) except Exception: pass # Aliases for backwards compatibility ProxyTunnel = HttpAuthTunnel MihomoProxyTunnel = MihomoTunnel