zapret-kvn/xray_fluent/engines/naive/manager.py
loop-uh 67ca37f257 Start fallback: a connect on a line that answers nothing is left in about 8 s and goes on with another entry
The naive tunnel check gives up after 5 s (was 25 s) when another line can be tried, the failed line backs off 1/5/10 min,
at most 3 lines per connect. Real keys on win10: connected on the working line in 9.2-9.5 s, without it the same click
failed after 26.6 s and stayed disconnected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 14:49:02 -05:00

392 lines
19 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Lifecycle of the stock naive client (``core/naive.exe``) as a loopback SOCKS5 helper behind the sing-box front.
The helper reads ``{"listen": "socks://user:pass@127.0.0.1:port", "proxy": "https://id:secret@host:port"}``; sing-box
dials the loopback port with the random credentials, the same seam as the Hysteria2 and Xray helpers. The config file
holds the key's secret, so it exists only while the process starts (naive reads it at launch) and is deleted as soon as
the process is up or fails, never kept on disk for the whole session.
"""
from __future__ import annotations
from collections import deque
import ipaddress
import json
import os
import threading
from pathlib import Path
import time
from PyQt6.QtCore import QObject, QProcess, QTimer, pyqtSignal
from ...application.async_steps import (
TransitionSteps,
run_in_worker,
run_steps_blocking,
sleep_ms,
wait_process_finished,
wait_process_started,
)
from ...constants import NAIVE_PATH_DEFAULT, RUNTIME_DIR
from ...diagnostics.export import capture_runtime_config
from ...diagnostics.runtime_logging import RuntimeNodeIdentity, redact_runtime_log
from ...network import server_family
from ...network.bootstrap_dns import resolve_bootstrap
from ..sidecar import wait_for_loopback_relay_steps
from ..socks_probe import HTTPS_ENDPOINTS, probe_https
#: The first tunnel check retries instead of treating the first refusal as the answer (a node needs a moment after a key
#: is issued; the bot's canary keys were ready in 6-20 s). 25 s, not more: a wrong or expired key must not hold a connect
#: for over a minute with no word (owner report 2026-11-27, "thinking for a very long time").
READY_TIMEOUT_SECONDS = 25.0
PROBE_TIMEOUT_SECONDS = 3.0
#: Hard wall time of one probe step (see `_tunnel_ready_steps`).
PROBE_WALL_SECONDS = 4.0
RECENT_LINES = 40
#: «IPv6 к серверу первым»: how long the pinned IPv6 address gets to carry the first request before the same server is
#: tried over IPv4 (the Hysteria2 helper uses the same window).
_IPV6_FAMILY_WINDOW_S = 4.0
_RETRY_OTHER_FAMILY = object()
class NaiveManager(QObject):
log_received = pyqtSignal(str)
error = pyqtSignal(str)
warning = pyqtSignal(str)
failure = pyqtSignal(object)
stopped = pyqtSignal(int)
state_changed = pyqtSignal(bool)
def __init__(self, parent=None):
super().__init__(parent)
self._process = QProcess(self)
self._process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)
self._process.readyReadStandardOutput.connect(self._read)
self._process.finished.connect(self._finished)
self._process.errorOccurred.connect(self._process_error)
self._running = False
# The controller shortens the first tunnel check (seconds) when another line can be tried (start fallback).
self.ready_timeout_seconds: float | None = None
self._expected = False
self._failed = False
self._buffer = b""
self._secrets: tuple[str, ...] = ()
self._context: RuntimeNodeIdentity | None = None
self._config_path: Path | None = None
self._recent: deque[str] = deque(maxlen=RECENT_LINES)
self.diagnostic_config = None
self.last_failure: tuple[str, str] | None = None
#: «IPv6 к серверу первым» (controller): the trusted IPv6 address is pinned first; a server that does not answer
#: over it within `_IPV6_FAMILY_WINDOW_S` is restarted on its IPv4 address (like the Hysteria2 helper).
self.server_ipv6_first = False
self._family_pin: tuple[str, str, tuple[str, ...]] | None = None
self._family_retry_address: str | None = None
self._family_failed: tuple[str, str] | None = None
# ── state ────────────────────────────────────────────────────────────
@property
def is_running(self) -> bool:
return self._running and not self._failed and self._process.state() != QProcess.ProcessState.NotRunning
@property
def process_alive(self) -> bool:
"""A spawned process exists, even if readiness was never confirmed."""
return self._process.state() != QProcess.ProcessState.NotRunning
@property
def recent_output_lines(self) -> tuple[str, ...]:
return tuple(self._recent)
def _clean(self, raw: str) -> str:
return redact_runtime_log(raw, secrets=self._secrets)
def _report(self, stage: str, raw: str) -> None:
from ...diagnostics.runtime_errors import core_failure
clean = self._clean(raw)
identity = self._context.fields() if self._context else ""
message = f"[naive][stage={stage} {identity}] {clean}"
if self.last_failure is None:
# The first report of an attempt is its cause; later ones are fallout.
self.last_failure = (stage, clean)
self.log_received.emit(message)
self.error.emit(message)
self.failure.emit(core_failure("naive", stage, clean, target_id=self._context.ref if self._context else ""))
# ── start ────────────────────────────────────────────────────────────
def start(self, config: dict, relay_port: int, *, relay_username: str, relay_password: str, context=None,
secrets: tuple[str, ...] = (), server_host: str = "", should_continue=None) -> bool:
# Synchronous driver of the same steps: shutdown and tests only.
return bool(run_steps_blocking(self.start_steps(
config, relay_port, relay_username=relay_username, relay_password=relay_password, context=context,
secrets=secrets, server_host=server_host, should_continue=should_continue)))
def start_steps(self, config: dict, relay_port: int, *, relay_username: str, relay_password: str, context=None,
secrets: tuple[str, ...] = (), server_host: str = "", should_continue=None) -> TransitionSteps:
if not (yield from self.stop_steps()):
return False
self._expected = self._failed = False
self.last_failure = None
self._buffer = b""
self._recent.clear()
self._context = context
self._secrets = tuple(s for s in (*secrets, relay_username, relay_password) if s)
cancelled = lambda: should_continue is not None and not should_continue() # noqa: E731
self._family_pin = None
self._family_retry_address = None
self._family_failed = None
try:
exe = NAIVE_PATH_DEFAULT
if not exe.is_file():
raise OSError("naive.exe is missing from the installed core bundle")
base_config = config
while True:
config = yield from self._pin_trusted_address_steps(base_config, server_host)
if cancelled():
return False
self.diagnostic_config = capture_runtime_config(exe, config)
self._config_path = self._write_config(config)
self._process.setProgram(str(exe))
self._process.setArguments([str(self._config_path)])
self._process.setWorkingDirectory(str(exe.parent))
self._process.start()
if not (yield wait_process_started(self._process, 5000)):
raise OSError(self._process.errorString())
if not (yield from wait_for_loopback_relay_steps(
relay_port,
should_continue=lambda: not self._failed and not cancelled()
and self._process.state() != QProcess.ProcessState.NotRunning,
)):
if cancelled():
yield from self.stop_steps()
return False
raise OSError("naive did not open its local SOCKS port")
# naive has read its config by now; the secret no longer needs to sit on disk.
self._cleanup_config()
fallback = self._ipv6_fallback_address()
ready = yield from self._tunnel_ready_steps(
relay_port, relay_username, relay_password, cancelled,
family_window=_IPV6_FAMILY_WINDOW_S if fallback else None,
)
if ready is _RETRY_OTHER_FAMILY and fallback:
host, address, _ordered = self._family_pin or ("", "", ())
self._family_failed = (host, address)
self._family_retry_address = fallback
self.log_received.emit(
f"[naive][stage=address_family] server did not answer over IPv6 in {_IPV6_FAMILY_WINDOW_S:g} s, "
"retrying over IPv4")
yield from self.stop_steps()
self._expected = False
self._recent.clear()
continue
if not ready:
yield from self.stop_steps()
return False
break
except (OSError, ValueError) as exc:
if not self._failed:
self._report("startup", str(exc))
yield from self.stop_steps()
return False
finally:
self._cleanup_config()
self._remember_family()
self._running = True
self.state_changed.emit(True)
return True
def _remember_family(self) -> None:
"""The family that carried the first request is remembered; an IPv6 that failed is remembered only now, once IPv4
proved the server (and the key) fine, so a wrong key never marks IPv6 as dead."""
if self._family_pin is None:
return
host, address, _ordered = self._family_pin
if self._family_failed is not None:
server_family.MEMORY.failed(*self._family_failed)
server_family.MEMORY.succeeded(host, address)
@property
def pinned_family(self) -> int | None:
"""Семейство адреса, на который закреплено соединение с сервером (4/6), иначе ``None``."""
if self._family_pin is None:
return None
return 6 if ":" in self._family_pin[1] else 4
def _ipv6_fallback_address(self) -> str | None:
"""The IPv4 of the same server, when this attempt pinned IPv6 and there is something to fall back to."""
if self._family_pin is None or self._family_retry_address is not None:
return None
_host, address, ordered = self._family_pin
if ":" not in address:
return None
return server_family.has_other_family(ordered, address)
def _pin_trusted_address_steps(self, config: dict, host: str) -> TransitionSteps:
"""The server's address from the app's trusted DoH, handed to naive as ``host-resolver-rules``.
Like the Hysteria2 helper, naive would otherwise ask the system resolver, and a network that forges those answers
leaves a live server with «no such host» or a wrong address. The TLS name stays the host name (Chromium's
``MAP name ip`` keeps SNI and the certificate check). Without «IPv6 first» the first IPv4 address is pinned (an
IPv6-only server is left for naive to resolve). With it the IPv6 address goes first, unless the family memory says
this name answered over IPv4 or not over IPv6, and `start_steps` restarts on IPv4 when IPv6 stays silent. No
trusted answer leaves the name for naive to resolve.
"""
self._family_pin = None
host = str(host or "").strip().lower()
if not host:
return config
try:
ipaddress.ip_address(host)
return config
except ValueError:
pass
try:
resolution = yield run_in_worker(lambda: resolve_bootstrap(host))
except (OSError, UnicodeError):
return config
if resolution.source == "system" or not resolution.addresses:
return config
ordered = server_family.order_addresses(
host, resolution.addresses, ipv6_first=self.server_ipv6_first, memory=server_family.MEMORY)
address = self._family_retry_address if self._family_retry_address in ordered else (ordered[0] if ordered else "")
if not address or (":" in address and not self.server_ipv6_first):
return config
self._family_pin = (host, address, tuple(ordered))
family = "IPv6" if ":" in address else "IPv4"
self.log_received.emit(f"[naive][stage=resolve] server address from trusted DNS ({resolution.source}), {family}")
target = f"[{address}]" if ":" in address else address
return {**config, "host-resolver-rules": f"MAP {host} {target}"}
def _write_config(self, config: dict) -> Path:
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
path = RUNTIME_DIR / f"naive_config_{os.getpid()}_{time.monotonic_ns()}.json"
payload = dict(config)
payload.setdefault("log", "") # empty path = console: the manager reads the errors from the pipe
data = json.dumps(payload, separators=(",", ":")).encode("utf-8")
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as handle:
handle.write(data)
return path
def _cleanup_config(self) -> None:
path, self._config_path = self._config_path, None
if path is not None:
try:
path.unlink()
except OSError:
pass
def _tunnel_ready_steps(self, port: int, username: str, password: str, cancelled,
family_window: float | None = None) -> TransitionSteps:
"""One HTTPS request through naive to the key's server proves the key is accepted and the path works.
With ``family_window`` (the server was pinned to IPv6) it returns ``_RETRY_OTHER_FAMILY`` once that many seconds
passed without a working request, instead of waiting out the whole timeout."""
started = time.monotonic()
deadline = started + (self.ready_timeout_seconds or READY_TIMEOUT_SECONDS)
errors: dict[str, str] = {}
def attempt(endpoint) -> str | None:
"""One probe, never longer than PROBE_WALL_SECONDS: a newer click can only be served between two steps, so a
step that ran for half a minute (three endpoints, several socket waits each) held the whole app on
«Подключение…» (measured on win10, 2026-11-27: a click on a VLESS server waited 29 s behind a dead key)."""
box: list[str | None] = []
def run() -> None:
try:
probe_https(port, username=username, password=password, endpoint=endpoint,
timeout=PROBE_TIMEOUT_SECONDS)
box.append(None)
except (OSError, ValueError) as exc:
box.append(f"{type(exc).__name__}: {exc}")
thread = threading.Thread(target=run, name="naive-probe", daemon=True)
thread.start()
thread.join(PROBE_WALL_SECONDS)
return box[0] if box else f"no answer in {PROBE_WALL_SECONDS:.0f} s"
turn = 0
while time.monotonic() < deadline:
if self._failed or cancelled() or self._process.state() == QProcess.ProcessState.NotRunning:
return False
endpoint = HTTPS_ENDPOINTS[turn % len(HTTPS_ENDPOINTS)]
turn += 1
outcome = yield run_in_worker(lambda endpoint=endpoint: attempt(endpoint))
if outcome is None:
return True
errors[endpoint[0]] = str(outcome)
# The next probe would start after the 1 s pause: give up on this family when that is past the window.
if family_window is not None and time.monotonic() - started + 1.0 >= family_window:
return _RETRY_OTHER_FAMILY
yield sleep_ms(1000)
last_error = "; ".join(f"{host}: {text}" for host, text in errors.items())
if not self._failed and not cancelled():
tail = " | ".join(self._recent)
self._report("tunnel_readiness", f"No request got through the NaiveProxy server: {last_error}. {tail}")
return False
# ── output and exit ──────────────────────────────────────────────────
def _read(self) -> None:
self._buffer += bytes(self._process.readAllStandardOutput())
if len(self._buffer) > 1024 * 1024:
self._buffer = self._buffer[-65536:]
while b"\n" in self._buffer:
line, self._buffer = self._buffer.split(b"\n", 1)
text = self._clean(line.decode("utf-8", errors="replace"))
if not text:
continue
self._recent.append(text)
self.log_received.emit(f"[naive] {text}")
def _process_error(self, _error) -> None:
if not self._expected:
self._failed = True
self._report("process", self._process.errorString())
def _finished(self, exit_code, _status) -> None:
self._read()
was_running = self._running
self._running = False
self._cleanup_config()
if not self._expected and not self._failed:
self._failed = True
self._report("process", f"naive process exited with code {exit_code}")
if was_running:
self.state_changed.emit(False)
self.stopped.emit(exit_code)
# ── stop ─────────────────────────────────────────────────────────────
def stop(self, expected: bool = True) -> bool:
return bool(run_steps_blocking(self.stop_steps(expected=expected)))
def request_stop(self, expected: bool = True) -> None:
"""Close admission now without waiting (signal handlers): kill after the same 1.5 s grace."""
self._expected = expected
if self._process.state() == QProcess.ProcessState.NotRunning:
self._running = False
return
self._process.terminate()
QTimer.singleShot(1500, self._kill_if_running)
def _kill_if_running(self) -> None:
if self._process.state() != QProcess.ProcessState.NotRunning:
self._process.kill()
def stop_steps(self, expected: bool = True) -> TransitionSteps:
self._expected = expected
if self._process.state() != QProcess.ProcessState.NotRunning:
# naive is a console program without a stdin protocol: a console process on Windows ignores terminate()
# for a hidden window, so kill after a short grace.
self._process.terminate()
if not (yield wait_process_finished(self._process, 800)):
self._process.kill()
if not (yield wait_process_finished(self._process, 1500)):
return False
self._cleanup_config()
self._running = False
return True