|
@@ -1,65 +1,129 @@
|
|
|
|
|
+"""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 socket
|
|
|
-import threading
|
|
|
|
|
import select
|
|
import select
|
|
|
import base64
|
|
import base64
|
|
|
-import time
|
|
|
|
|
|
|
+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:<port>)."""
|
|
|
|
|
+ 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 ProxyTunnel:
|
|
|
|
|
|
|
+
|
|
|
|
|
+class HttpAuthTunnel(BaseProxyTunnel):
|
|
|
"""
|
|
"""
|
|
|
- Local proxy tunnel manager
|
|
|
|
|
- 1. Enables TCP_NODELAY to eliminate handshake latency.
|
|
|
|
|
- 2. Enables KeepAlive to prevent idle disconnection.
|
|
|
|
|
- 3. Uses blocking sendall with select polling to prevent data loss.
|
|
|
|
|
|
|
+ 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, upstream_port, username, password):
|
|
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self, upstream_ip: str, upstream_port: int, username: str = "", password: str = ""):
|
|
|
|
|
+ super().__init__()
|
|
|
self.upstream_ip = upstream_ip
|
|
self.upstream_ip = upstream_ip
|
|
|
self.upstream_port = int(upstream_port)
|
|
self.upstream_port = int(upstream_port)
|
|
|
self.username = username
|
|
self.username = username
|
|
|
self.password = password
|
|
self.password = password
|
|
|
-
|
|
|
|
|
- # Pre-compute Proxy-Authorization header
|
|
|
|
|
- auth_str = f"{username}:{password}"
|
|
|
|
|
- b64_auth = base64.b64encode(auth_str.encode()).decode()
|
|
|
|
|
- self.auth_header = f"Proxy-Authorization: Basic {b64_auth}\r\n"
|
|
|
|
|
-
|
|
|
|
|
- self.server_socket = None
|
|
|
|
|
- self.local_port = 0
|
|
|
|
|
- self.running = False
|
|
|
|
|
- self.listen_thread = None
|
|
|
|
|
|
|
|
|
|
- def start(self):
|
|
|
|
|
|
|
+ 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:
|
|
try:
|
|
|
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
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.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
-
|
|
|
|
|
self.server_socket.bind(('127.0.0.1', 0))
|
|
self.server_socket.bind(('127.0.0.1', 0))
|
|
|
self.local_port = self.server_socket.getsockname()[1]
|
|
self.local_port = self.server_socket.getsockname()[1]
|
|
|
- self.server_socket.listen(128) # Increase listen backlog
|
|
|
|
|
-
|
|
|
|
|
|
|
+ self.server_socket.listen(128)
|
|
|
|
|
+
|
|
|
self.running = True
|
|
self.running = True
|
|
|
-
|
|
|
|
|
self.listen_thread = threading.Thread(target=self._accept_loop, daemon=True)
|
|
self.listen_thread = threading.Thread(target=self._accept_loop, daemon=True)
|
|
|
self.listen_thread.start()
|
|
self.listen_thread.start()
|
|
|
-
|
|
|
|
|
- return f"127.0.0.1:{self.local_port}"
|
|
|
|
|
|
|
+
|
|
|
|
|
+ return self.proxy_url
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
self.stop()
|
|
self.stop()
|
|
|
- raise RuntimeError(f"Failed to start tunnel: {e}")
|
|
|
|
|
|
|
+ raise RuntimeError(f"Failed to start HttpAuthTunnel: {e}") from e
|
|
|
|
|
|
|
|
- def stop(self):
|
|
|
|
|
|
|
+ def stop(self) -> None:
|
|
|
self.running = False
|
|
self.running = False
|
|
|
if self.server_socket:
|
|
if self.server_socket:
|
|
|
try:
|
|
try:
|
|
|
self.server_socket.close()
|
|
self.server_socket.close()
|
|
|
except Exception:
|
|
except Exception:
|
|
|
pass
|
|
pass
|
|
|
- self.server_socket = None
|
|
|
|
|
|
|
+ self.server_socket = None
|
|
|
|
|
|
|
|
def _accept_loop(self):
|
|
def _accept_loop(self):
|
|
|
while self.running:
|
|
while self.running:
|
|
|
try:
|
|
try:
|
|
|
if self.server_socket:
|
|
if self.server_socket:
|
|
|
- # Use select instead of settimeout to reduce CPU idle spinning
|
|
|
|
|
r, _, _ = select.select([self.server_socket], [], [], 1.0)
|
|
r, _, _ = select.select([self.server_socket], [], [], 1.0)
|
|
|
if r:
|
|
if r:
|
|
|
try:
|
|
try:
|
|
@@ -71,118 +135,95 @@ class ProxyTunnel:
|
|
|
except Exception:
|
|
except Exception:
|
|
|
continue
|
|
continue
|
|
|
|
|
|
|
|
- def _optimize_socket(self, sock):
|
|
|
|
|
- """Socket options optimization"""
|
|
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ def _optimize_socket(sock: socket.socket):
|
|
|
try:
|
|
try:
|
|
|
- # 1. Disable Nagle's algorithm: packets sent immediately without buffer delay
|
|
|
|
|
- # Crucial for preventing HttpClient timeouts
|
|
|
|
|
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
|
-
|
|
|
|
|
- # 2. Enable KeepAlive: prevent firewalls from terminating idle connections
|
|
|
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
|
|
-
|
|
|
|
|
- # 3. Increase buffer sizes
|
|
|
|
|
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
|
|
|
|
|
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32*1024)
|
|
|
|
|
|
|
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32 * 1024)
|
|
|
|
|
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32 * 1024)
|
|
|
except Exception:
|
|
except Exception:
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
- def _handle_client(self, client_sock):
|
|
|
|
|
|
|
+ def _handle_client(self, client_sock: socket.socket):
|
|
|
upstream_sock = None
|
|
upstream_sock = None
|
|
|
try:
|
|
try:
|
|
|
self._optimize_socket(client_sock)
|
|
self._optimize_socket(client_sock)
|
|
|
- client_sock.settimeout(30)
|
|
|
|
|
-
|
|
|
|
|
- # 1. Read first packet (32KB buffer)
|
|
|
|
|
|
|
+ client_sock.settimeout(30)
|
|
|
|
|
+
|
|
|
try:
|
|
try:
|
|
|
first_packet = client_sock.recv(32768)
|
|
first_packet = client_sock.recv(32768)
|
|
|
except socket.timeout:
|
|
except socket.timeout:
|
|
|
- return # Client connected without sending data
|
|
|
|
|
-
|
|
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
if not first_packet:
|
|
if not first_packet:
|
|
|
return
|
|
return
|
|
|
|
|
|
|
|
- # 2. Connect to upstream
|
|
|
|
|
upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
- self._optimize_socket(upstream_sock) # Optimize upstream socket
|
|
|
|
|
-
|
|
|
|
|
- upstream_sock.settimeout(10) # Connect timeout: 10s
|
|
|
|
|
|
|
+ self._optimize_socket(upstream_sock)
|
|
|
|
|
+ upstream_sock.settimeout(10)
|
|
|
upstream_sock.connect((self.upstream_ip, self.upstream_port))
|
|
upstream_sock.connect((self.upstream_ip, self.upstream_port))
|
|
|
-
|
|
|
|
|
- # Switch to blocking mode once connected; multiplexing handled by select
|
|
|
|
|
|
|
+
|
|
|
upstream_sock.settimeout(None)
|
|
upstream_sock.settimeout(None)
|
|
|
client_sock.settimeout(None)
|
|
client_sock.settimeout(None)
|
|
|
-
|
|
|
|
|
- # 3. Inject 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:]
|
|
|
|
|
|
|
+
|
|
|
|
|
+ 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:
|
|
else:
|
|
|
new_packet = first_packet
|
|
new_packet = first_packet
|
|
|
|
|
|
|
|
- # 4. Send first packet (blocking sendall to guarantee integrity)
|
|
|
|
|
upstream_sock.sendall(new_packet)
|
|
upstream_sock.sendall(new_packet)
|
|
|
-
|
|
|
|
|
- # 5. Bi-directional proxy forwarding
|
|
|
|
|
self._pipe_sockets(client_sock, upstream_sock)
|
|
self._pipe_sockets(client_sock, upstream_sock)
|
|
|
-
|
|
|
|
|
except Exception:
|
|
except Exception:
|
|
|
pass
|
|
pass
|
|
|
finally:
|
|
finally:
|
|
|
self._close_socket(client_sock)
|
|
self._close_socket(client_sock)
|
|
|
self._close_socket(upstream_sock)
|
|
self._close_socket(upstream_sock)
|
|
|
|
|
|
|
|
- def _pipe_sockets(self, sock1, sock2):
|
|
|
|
|
- """
|
|
|
|
|
- Forwarding logic:
|
|
|
|
|
- Maintains blocking socket mode while using select to poll readable state.
|
|
|
|
|
- """
|
|
|
|
|
|
|
+ def _pipe_sockets(self, sock1: socket.socket, sock2: socket.socket):
|
|
|
sockets = [sock1, sock2]
|
|
sockets = [sock1, sock2]
|
|
|
last_activity = time.time()
|
|
last_activity = time.time()
|
|
|
- IDLE_TIMEOUT = 120 # Extended idle timeout
|
|
|
|
|
-
|
|
|
|
|
|
|
+ idle_timeout = 120
|
|
|
|
|
+
|
|
|
while self.running:
|
|
while self.running:
|
|
|
try:
|
|
try:
|
|
|
- # Listen for readable sockets
|
|
|
|
|
r, _, x = select.select(sockets, [], sockets, 1.0)
|
|
r, _, x = select.select(sockets, [], sockets, 1.0)
|
|
|
-
|
|
|
|
|
- if x: break # Socket exception
|
|
|
|
|
-
|
|
|
|
|
|
|
+ if x:
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
if not r:
|
|
if not r:
|
|
|
- if time.time() - last_activity > IDLE_TIMEOUT:
|
|
|
|
|
|
|
+ if time.time() - last_activity > idle_timeout:
|
|
|
break
|
|
break
|
|
|
continue
|
|
continue
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
for s in r:
|
|
for s in r:
|
|
|
try:
|
|
try:
|
|
|
- # Attempt read
|
|
|
|
|
data = s.recv(32768)
|
|
data = s.recv(32768)
|
|
|
except ConnectionResetError:
|
|
except ConnectionResetError:
|
|
|
data = None
|
|
data = None
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
if not data:
|
|
if not data:
|
|
|
- return # Connection closed
|
|
|
|
|
-
|
|
|
|
|
- # Determine forwarding destination
|
|
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
target = sock2 if s is sock1 else sock1
|
|
target = sock2 if s is sock1 else sock1
|
|
|
-
|
|
|
|
|
- # Blocking sendall: pauses thread if network is congested without packet drops
|
|
|
|
|
try:
|
|
try:
|
|
|
target.sendall(data)
|
|
target.sendall(data)
|
|
|
except BrokenPipeError:
|
|
except BrokenPipeError:
|
|
|
return
|
|
return
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
last_activity = time.time()
|
|
last_activity = time.time()
|
|
|
-
|
|
|
|
|
except Exception:
|
|
except Exception:
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
- def _close_socket(self, sock):
|
|
|
|
|
- """Gracefully closes socket."""
|
|
|
|
|
|
|
+ @staticmethod
|
|
|
|
|
+ def _close_socket(sock: Optional[socket.socket]):
|
|
|
if sock:
|
|
if sock:
|
|
|
try:
|
|
try:
|
|
|
- # Send FIN packet to signal completion
|
|
|
|
|
sock.shutdown(socket.SHUT_RDWR)
|
|
sock.shutdown(socket.SHUT_RDWR)
|
|
|
except Exception:
|
|
except Exception:
|
|
|
pass
|
|
pass
|
|
@@ -191,5 +232,132 @@ class ProxyTunnel:
|
|
|
except Exception:
|
|
except Exception:
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
- def __del__(self):
|
|
|
|
|
- self.stop()
|
|
|
|
|
|
|
+
|
|
|
|
|
+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
|