Bladeren bron

feat: add proxy tunnel toolkit and supporting utility modules

hujiarui 3 weken geleden
bovenliggende
commit
89548a27c9

+ 1 - 1
README.md

@@ -486,7 +486,7 @@ coordinate/
 │   └── ...
 ├── toolkit/                 # 通用底层工具库
 │   ├── captcha_breaker.py   # 通用多模态大模型验证码识别器
-│   ├── mihomo_tunnel.py     # 智能代理隧道与节点管理
+│   ├── proxy_tunnel.py      # 本地代理隧道(支持 HttpAuth 与 Mihomo 双实现)
 │   ├── backoff.py           # 指数退避重试器
 │   └── cloud_api.py      # 云端邮箱验证码与配置同步
 ├── tools/                   # 运维与开发工具

+ 1 - 1
gco_wrapper.py

@@ -3,7 +3,7 @@ import collections
 from enum import Enum, auto
 from typing import Callable, Type, Any, Dict
 from core_types import GroupConfig, GroupStatus
-from log_macros import VSC_INFO
+from logger_setup import VSC_INFO
 
 class State(Enum):
     CREATED = auto()

+ 1 - 1
keygens/tls_keygen.py

@@ -26,7 +26,7 @@ from DrissionPage import ChromiumPage, ChromiumOptions
 import configure
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from toolkit.cloud_api import CloudApi
-from toolkit.mihomo_tunnel import MihomoTunnel
+from toolkit.proxy_tunnel import MihomoTunnel
 from core_types import BizLogicError 
 from utils.mouse import HumanMouse
 from utils.keyboard import HumanKeyboard

+ 1 - 1
keygens/vfs_keygen.py

@@ -30,7 +30,7 @@ from cryptography.hazmat.backends import default_backend
 import configure
 from DrissionPage import ChromiumPage, ChromiumOptions
 from core_types import RateLimiteddError, BizLogicError
-from toolkit.mihomo_tunnel import MihomoTunnel
+from toolkit.proxy_tunnel import MihomoTunnel
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 
 # ==========================================

+ 0 - 23
log_macros.py

@@ -1,23 +0,0 @@
-import logging
-
-# Holds internal logger instance, defaults to Root Logger to avoid uninitialized errors
-_active_logger = logging.getLogger()
-
-def set_active_logger(logger: logging.Logger):
-    """Called by external logging configuration utilities to redirect all macro output."""
-    global _active_logger
-    _active_logger = logger
-
-# --- Macro definitions (supports group_id structured extra metadata) ---
-
-def VSC_INFO(tag, message, *args, group_id: str = ""):
-    _active_logger.info(f"[{tag}] {message}", *args, extra={"group_id": group_id})
-
-def VSC_DEBUG(tag, message, *args, group_id: str = ""):
-    _active_logger.debug(f"[{tag}] {message}", *args, extra={"group_id": group_id})
-
-def VSC_WARN(tag, message, *args, group_id: str = ""):
-    _active_logger.warning(f"[{tag}] {message}", *args, extra={"group_id": group_id})
-
-def VSC_ERROR(tag, message, *args, group_id: str = ""):
-    _active_logger.error(f"[{tag}] {message}", *args, extra={"group_id": group_id})

+ 34 - 8
logger_setup.py

@@ -2,7 +2,33 @@ import os
 import logging
 from logging.handlers import RotatingFileHandler
 
-import log_macros
+# Holds internal logger instance, defaults to Root Logger to avoid uninitialized errors
+_active_logger = logging.getLogger()
+
+
+def set_active_logger(logger: logging.Logger):
+    """Called by external logging configuration utilities to redirect all macro output."""
+    global _active_logger
+    _active_logger = logger
+
+
+# --- Macro definitions (supports group_id structured extra metadata) ---
+
+def VSC_INFO(tag, message, *args, group_id: str = ""):
+    _active_logger.info(f"[{tag}] {message}", *args, extra={"group_id": group_id})
+
+
+def VSC_DEBUG(tag, message, *args, group_id: str = ""):
+    _active_logger.debug(f"[{tag}] {message}", *args, extra={"group_id": group_id})
+
+
+def VSC_WARN(tag, message, *args, group_id: str = ""):
+    _active_logger.warning(f"[{tag}] {message}", *args, extra={"group_id": group_id})
+
+
+def VSC_ERROR(tag, message, *args, group_id: str = ""):
+    _active_logger.error(f"[{tag}] {message}", *args, extra={"group_id": group_id})
+
 
 def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None) -> logging.Logger:
     """
@@ -13,26 +39,26 @@ def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None)
 
     logger = logging.getLogger(app_name)
     logger.setLevel(logging.INFO)
-    
+
     # Avoid adding duplicate handlers
     if not logger.handlers:
         log_file = os.path.join(log_dir, f"{app_name.lower()}.log")
-        
+
         # 1. Console handler
         console_handler = logging.StreamHandler()
         console_handler.setLevel(logging.INFO)
-        
+
         # 2. File handler
         file_handler = RotatingFileHandler(
             log_file, maxBytes=10 * 1024 * 1024, backupCount=10, encoding='utf-8'
         )
         file_handler.setLevel(logging.INFO)
-        
+
         # Formatter
         formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
         console_handler.setFormatter(formatter)
         file_handler.setFormatter(formatter)
-        
+
         logger.addHandler(console_handler)
         logger.addHandler(file_handler)
 
@@ -41,7 +67,7 @@ def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None)
             if h not in logger.handlers:
                 logger.addHandler(h)
 
-    # Inject logger into log_macros
-    log_macros.set_active_logger(logger)
+    # Inject logger into active macro logger
+    set_active_logger(logger)
 
     return logger

+ 1 - 1
plugin_factory.py

@@ -3,7 +3,7 @@ import importlib.util
 import sys
 import os
 from plugin import IPlugin
-from log_macros import VSC_ERROR, VSC_INFO
+from logger_setup import VSC_ERROR, VSC_INFO
 
 class PluginFactory:
     """

+ 1 - 1
toolkit/cloud_api.py

@@ -7,7 +7,7 @@ from typing import Dict, Any, List, Optional
 
 import configure
 from core_types import PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
-from log_macros import VSC_ERROR, VSC_INFO, VSC_WARN, VSC_DEBUG
+from logger_setup import VSC_ERROR, VSC_INFO, VSC_WARN, VSC_DEBUG
 
 
 class CloudApi:

+ 0 - 197
toolkit/mihomo_tunnel.py

@@ -1,197 +0,0 @@
-import os
-import time
-import socket
-import subprocess
-import yaml
-import tempfile
-import shutil
-import urllib.request
-
-
-class MihomoTunnel:
-    """
-    Manage local proxy tunnels using Mihomo (Clash Meta).
-    Supports multi-instance concurrency with isolated temp directories.
-    Adapted for the new 'dialer-proxy' chain routing mechanism.
-    """
-    def __init__(self, mihomo_bin_path, exit_node, relay_node=None, enable_log=False):
-        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 = None
-        self.local_port = 0
-        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 _get_free_port(self):
-        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-            s.bind(('127.0.0.1', 0))
-            return s.getsockname()[1]
-
-    def _generate_config(self):
-        self.local_port = self._get_free_port()
-        self.api_port = self._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": []
-        }
-
-        # Deep copy to avoid modifying the original dictionary 
-        # in case it is reused by other instances.
-        exit_node_config = dict(self.exit_node)
-
-        # Handle proxy chaining using the new 'dialer-proxy' feature
-        if self.relay_node:
-            # 1. Add relay node to proxies
-            config["proxies"].append(self.relay_node)
-            
-            # 2. Tell the exit node to dial through the relay node
-            exit_node_config["dialer-proxy"] = self.relay_node["name"]
-        
-        # 3. Add exit node to proxies
-        config["proxies"].append(exit_node_config)
-        
-        # 4. Route all traffic to the exit node
-        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):
-        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)
-
-            return f"127.0.0.1:{self.local_port}"
-
-        except Exception as e:
-            self.stop()
-            raise e
-
-    def cut_all_connections(self):
-        """
-        Forces termination of all active connections in the proxy pool via Mihomo API.
-        Commonly used when an IP block is detected or switching proxy routes to immediately interrupt hung requests.
-        """
-        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):
-        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
-
-    def __del__(self):
-        self.stop()
-
-# ================= TEST SCRIPT =================
-if __name__ == "__main__":
-    MIHOMO_EXE = "E:/coordinator/mihomo-windows-amd64-alpha-98aa7e6/mihomo-windows-amd64.exe" if os.name == 'nt' else "./mihomo"
-
-    exit_node = {
-        "name": "ExitNode",
-        "type": "http",
-        "server": "46.203.77.84",
-        "port": 41588,
-        "username": "nKX6cH1jvBWJlFZ",
-        "password": "vySUmO3VMCKkYDS"
-    }
-
-    relay_node = {
-        "name": "RelayNode",
-        "type": "ss",
-        "server": "odko6qmr.mobilfunk.top",
-        "port": 12012,
-        "cipher": "aes-128-gcm",
-        "password": "haMLMXirByn6rGVh",
-        "plugin": "obfs",
-        "plugin-opts": {
-            "mode": "http",
-            "host": "c0f69828a7c1.microsoft.com"
-        },
-        "udp": True
-    }
-
-    print("Starting Mihomo Tunnel...")
-    
-    # Enable log to False for production (no disk writing, no console output)
-    tunnel = MihomoTunnel(MIHOMO_EXE, exit_node, relay_node, enable_log=True)
-    
-    try:
-        local_proxy = tunnel.start()
-        print(f"Success! Proxy mapped to: {local_proxy}")
-        
-        while True:
-            time.sleep(10)
-    except KeyboardInterrupt:
-        print("\nStopping tunnel...")
-    except Exception as e:
-        print(f"\nError: {e}")
-    finally:
-        tunnel.stop()
-        print("Tunnel closed and temp files cleaned.")

+ 3 - 3
toolkit/notifier.py

@@ -1,7 +1,7 @@
 from typing import Dict, Callable, Optional
 from core_types import QueryResult, BookResult
 from toolkit.cloud_api import CloudApi
-from toolkit.thread_pool import ThreadPool
+from toolkit.task_executor import submit_background
 
 
 def notify_date_changes(
@@ -39,7 +39,7 @@ def notify_date_changes(
             if logger:
                 logger(f"Failed to notify date change to cloud: {e}")
 
-    ThreadPool.getInstance().enqueue(_push_to_wx)
+    submit_background(_push_to_wx)
     return True
 
 
@@ -77,5 +77,5 @@ def notify_book_result(
             if logger:
                 logger(f"Failed to notify book result to cloud: {e}")
 
-    ThreadPool.getInstance().enqueue(_push_to_wx)
+    submit_background(_push_to_wx)
     return True

+ 5 - 12
toolkit/proxy_manager.py

@@ -11,9 +11,9 @@ from typing import List, Dict, Any, Optional
 import requests
 import configure
 from toolkit.cloud_api import CloudApi
-from toolkit.thread_pool import ThreadPool
+from toolkit.task_executor import submit_background
 from core_types import BizLogicError
-from log_macros import VSC_INFO, VSC_WARN, VSC_ERROR, VSC_DEBUG
+from logger_setup import VSC_INFO, VSC_WARN, VSC_ERROR, VSC_DEBUG
 
 
 class ProxyManager:
@@ -108,9 +108,7 @@ class ProxyManager:
                 with self._lock:
                     self._probing_ports.discard(port)
 
-        try:
-            ThreadPool.getInstance().enqueue(_do_probe)
-        except Exception:
+        if not submit_background(_do_probe):
             t = threading.Thread(target=_do_probe, daemon=True)
             t.start()
 
@@ -163,9 +161,7 @@ class ProxyManager:
                 with self._lock:
                     self._fetching_reputation.discard(plugin_name)
 
-        try:
-            ThreadPool.getInstance().enqueue(_fetch_worker)
-        except Exception:
+        if not submit_background(_fetch_worker):
             threading.Thread(target=_fetch_worker, daemon=True).start()
         return (cache_entry.get("map", {}) if cache_entry else {})
 
@@ -457,7 +453,4 @@ class ProxyManager:
             except Exception:
                 pass
 
-        try:
-            ThreadPool.getInstance().enqueue(_report_worker)
-        except Exception:
-            pass
+        submit_background(_report_worker)

+ 256 - 88
toolkit/proxy_tunnel.py

@@ -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 threading
 import select
 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_port = int(upstream_port)
         self.username = username
         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:
             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) # Increase listen backlog
-            
+            self.server_socket.listen(128)
+
             self.running = True
-            
             self.listen_thread = threading.Thread(target=self._accept_loop, daemon=True)
             self.listen_thread.start()
-            
-            return f"127.0.0.1:{self.local_port}"
+
+            return self.proxy_url
         except Exception as e:
             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
         if self.server_socket:
             try:
                 self.server_socket.close()
             except Exception:
                 pass
-        self.server_socket = None
+            self.server_socket = None
 
     def _accept_loop(self):
         while self.running:
             try:
                 if self.server_socket:
-                    # Use select instead of settimeout to reduce CPU idle spinning
                     r, _, _ = select.select([self.server_socket], [], [], 1.0)
                     if r:
                         try:
@@ -71,118 +135,95 @@ class ProxyTunnel:
             except Exception:
                 continue
 
-    def _optimize_socket(self, sock):
-        """Socket options optimization"""
+    @staticmethod
+    def _optimize_socket(sock: socket.socket):
         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)
-            
-            # 2. Enable KeepAlive: prevent firewalls from terminating idle connections
             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:
             pass
 
-    def _handle_client(self, client_sock):
+    def _handle_client(self, client_sock: socket.socket):
         upstream_sock = None
         try:
             self._optimize_socket(client_sock)
-            client_sock.settimeout(30) 
-            
-            # 1. Read first packet (32KB buffer)
+            client_sock.settimeout(30)
+
             try:
                 first_packet = client_sock.recv(32768)
             except socket.timeout:
-                return # Client connected without sending data
-                
+                return
+
             if not first_packet:
                 return
 
-            # 2. Connect to upstream
             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))
-            
-            # Switch to blocking mode once connected; multiplexing handled by select
+
             upstream_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:
                 new_packet = first_packet
 
-            # 4. Send first packet (blocking sendall to guarantee integrity)
             upstream_sock.sendall(new_packet)
-            
-            # 5. Bi-directional proxy forwarding
             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, 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]
         last_activity = time.time()
-        IDLE_TIMEOUT = 120 # Extended idle timeout
-        
+        idle_timeout = 120
+
         while self.running:
             try:
-                # Listen for readable sockets
                 r, _, x = select.select(sockets, [], sockets, 1.0)
-                
-                if x: break # Socket exception
-                
+                if x:
+                    break
+
                 if not r:
-                    if time.time() - last_activity > IDLE_TIMEOUT:
+                    if time.time() - last_activity > idle_timeout:
                         break
                     continue
-                
+
                 for s in r:
                     try:
-                        # Attempt read
                         data = s.recv(32768)
                     except ConnectionResetError:
                         data = None
-                    
+
                     if not data:
-                        return # Connection closed
-                    
-                    # Determine forwarding destination
+                        return
+
                     target = sock2 if s is sock1 else sock1
-                    
-                    # Blocking sendall: pauses thread if network is congested without packet drops
                     try:
                         target.sendall(data)
                     except BrokenPipeError:
                         return
-                        
+
                     last_activity = time.time()
-                    
             except Exception:
                 break
 
-    def _close_socket(self, sock):
-        """Gracefully closes socket."""
+    @staticmethod
+    def _close_socket(sock: Optional[socket.socket]):
         if sock:
             try:
-                # Send FIN packet to signal completion
                 sock.shutdown(socket.SHUT_RDWR)
             except Exception:
                 pass
@@ -191,5 +232,132 @@ class ProxyTunnel:
             except Exception:
                 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

+ 26 - 6
toolkit/task_executor.py

@@ -6,12 +6,13 @@ resources on timeout and retain a failed group until those calls unwind.
 import logging
 import queue
 import threading
+from typing import Optional
 
 from utils.resource_lifecycle import join_threads
 
 
 class TaskExecutor:
-    def __init__(self, max_workers, name):
+    def __init__(self, max_workers: int, name: str):
         self._slots = threading.BoundedSemaphore(max_workers)
         self._queue = queue.Queue(maxsize=max_workers)
         self._lock = threading.Lock()
@@ -23,18 +24,18 @@ class TaskExecutor:
     def _worker(self):
         while not self._closed.is_set() or not self._queue.empty():
             try:
-                fn, args = self._queue.get(timeout=0.05)
+                fn, args, kwargs = self._queue.get(timeout=0.05)
             except queue.Empty:
                 continue
             try:
-                fn(*args)
+                fn(*args, **kwargs)
             except Exception:
-                logging.getLogger(__name__).exception('Background browser job failed')
+                logging.getLogger(__name__).exception('Background job failed')
             finally:
                 self._slots.release()
                 self._queue.task_done()
 
-    def submit(self, fn, *args):
+    def submit(self, fn, *args, **kwargs):
         with self._lock:
             if self._closed.is_set() or not self._slots.acquire(blocking=False):
                 return False
@@ -44,7 +45,7 @@ class TaskExecutor:
                                               name=f'{self._name}-{len(self._threads)}')
                     thread.start()
                     self._threads.append(thread)
-                self._queue.put_nowait((fn, args))
+                self._queue.put_nowait((fn, args, kwargs))
             except Exception:
                 self._slots.release()
                 raise
@@ -54,3 +55,22 @@ class TaskExecutor:
         with self._lock:
             self._closed.set()
         return join_threads(self._threads, timeout)
+
+
+_background_executor: Optional[TaskExecutor] = None
+_bg_lock = threading.Lock()
+
+
+def get_background_executor(max_workers: int = 16) -> TaskExecutor:
+    """Returns a shared daemon background TaskExecutor for lightweight async jobs."""
+    global _background_executor
+    if _background_executor is None:
+        with _bg_lock:
+            if _background_executor is None:
+                _background_executor = TaskExecutor(max_workers=max_workers, name='Background')
+    return _background_executor
+
+
+def submit_background(fn, *args, **kwargs) -> bool:
+    """Convenience helper to submit a job to the shared background executor."""
+    return get_background_executor().submit(fn, *args, **kwargs)

+ 0 - 52
toolkit/thread_pool.py

@@ -1,52 +0,0 @@
-# toolkit/thread_pool.py
-import threading
-from concurrent.futures import ThreadPoolExecutor, Future
-from log_macros import VSC_INFO, VSC_ERROR
-
-class ThreadPool:
-    """
-    @brief ThreadPool singleton class
-    Simulates C++ ThreadPool using Python's ThreadPoolExecutor.
-    """
-    _instance = None
-    _lock = threading.Lock()
-
-    def __new__(cls, max_workers: int = 10):
-        with cls._lock:
-            if cls._instance is None:
-                cls._instance = super().__new__(cls)
-                cls._instance._executor = ThreadPoolExecutor(max_workers=max_workers)
-                VSC_INFO("thread_pool", "ThreadPool initialized with %d workers", max_workers)
-            return cls._instance
-
-    @staticmethod
-    def getInstance(max_workers: int = 10):
-        """Gets ThreadPool singleton instance."""
-        return ThreadPool(max_workers)
-
-    def enqueue(self, func, *args, **kwargs) -> Future:
-        """
-        @brief Enqueues a task to the thread pool.
-        @param func Function to execute
-        @param args Positional arguments for the function
-        @param kwargs Keyword arguments for the function
-        @return Future object representing execution result
-        """
-        try:
-            future = self._executor.submit(func, *args, **kwargs)
-            return future
-        except Exception as e:
-            VSC_ERROR("thread_pool", "Failed to enqueue task: %s", str(e))
-            raise
-
-    def shutdown(self, wait: bool = True):
-        """
-        @brief Shuts down the thread pool.
-        @param wait If True, waits for all pending futures to complete.
-        """
-        with ThreadPool._lock:
-            if self._executor:
-                VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)
-                self._executor.shutdown(wait=wait)
-                self._executor = None
-            ThreadPool._instance = None

+ 1 - 1
utils/plugin_utils.py

@@ -15,7 +15,7 @@ from urllib.parse import urlencode
 
 import configure
 from core_types import BizLogicError, NotFoundError
-from toolkit.mihomo_tunnel import MihomoTunnel
+from toolkit.proxy_tunnel import MihomoTunnel
 from utils.fingerprint_utils import FingerprintGenerator
 from DrissionPage import ChromiumOptions