zapret-kvn/xray_fluent/diagnostics/path_test/service.py
loop-uh a06dd17b2b Path-test (Windows): «Проверка соединения» on the logs page
DNS, TCP, platform TLS and the stock naive.exe (real config builder helper_config, dummy credentials, no own ClientHello) per
saved server host, one full log (text and JSONL, hosts masked unless ticked, also in the diagnostic archive). By button, one
selected server by default; all servers only on a tick, one at a time with 10-20 s pauses, cancel on the same button, gate
journal; egress allowlist entries with reasons. Work of the KVN session c_9doawlxyy2 (branch feat/path-test), squashed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 12:18:34 -05:00

96 lines
4.1 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.

"""Запуск проверки для приложения: узлы -> прогон -> один журнал на диске (и в архиве диагностики)."""
from __future__ import annotations
import time
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from . import log, steps, targets
from .model import Attempt, Environment, Outcome, Step, Target
from .naive_probe import NaiveClientProbe
from .runner import PathTestRunner
LAST_TEXT = "last.txt"
LAST_JSONL = "last.jsonl"
_NOTES = (
"tcp leg: the running client may pin the server address (trusted DoH, host-resolver-rules); here naive resolves the name "
"itself. TLS, and with it the fingerprint, is naive's in both.",
"only naive servers have the real-client step in this release; other protocols get DNS and TCP only.",
)
@dataclass(frozen=True, slots=True)
class PathTestResult:
text: str
jsonl: str
text_path: Path
def last_entries(directory: Path) -> dict[str, bytes]:
"""Последний журнал как записи архива диагностики (пусто, если проверок ещё не было)."""
entries: dict[str, bytes] = {}
for name in (LAST_TEXT, LAST_JSONL):
path = directory / name
if path.is_file():
entries[f"path-test/{name}"] = path.read_bytes()
return entries
def run(
nodes: Iterable[Any],
*,
include_host_names: bool,
directory: Path,
app_name: str,
app_version: str,
vpn_active: bool,
network_type: str,
timezone: str,
naive_path: Path | None,
progress: Callable[[int, int], None] | None = None,
selected_node_id: str | None = None,
all_servers: bool = False,
cancelled: Callable[[], bool] = lambda: False,
) -> PathTestResult:
target_list = targets.from_nodes(nodes, selected_id=selected_node_id, all_servers=all_servers)
probe = NaiveClientProbe(naive_path)
def skipped(step: Step) -> Attempt:
return Attempt(step, Outcome.NOT_RUN, 0, "protocol_not_covered", time.time())
def out_of_scope(t: Target) -> bool:
return t.kind not in ("naive", "control")
started = time.time()
outcome = PathTestRunner(
dns=lambda t: steps.dns(t.host),
tcp=lambda t: steps.tcp(t.host, t.port),
# Для не-naive протоколов TLS-рукопожатие с собственным именем сервера ничего не доказывает (REALITY и др.): честно «не выполнялось».
platform_tls=lambda t: skipped(Step.PLATFORM_TLS) if out_of_scope(t) else steps.platform_tls(t.host, t.port),
real_client=lambda t: (
# контрольный хост судится платформенным стеком: он не naive-сервер
Attempt(Step.REAL_CLIENT, *_as_real(steps.platform_tls(t.host, t.port))) if t.kind == "control"
else skipped(Step.REAL_CLIENT) if out_of_scope(t) else probe.attempt(t)
),
cancelled=cancelled,
).run(target_list, progress)
env = Environment(
app_name=app_name, app_version=app_version, started_at=started, timezone=timezone, network_type=network_type,
vpn_active=vpn_active, client_binary="naive.exe" if naive_path and naive_path.is_file() else "missing",
notes=(*_NOTES, *(("the VPN was active: the test traffic may have taken the VPN path; switch it off for a clean network "
"measurement.",) if vpn_active else ())),
)
text = log.render_text(env, outcome.results, outcome.verdicts, include_host_names)
jsonl = "\n".join(log.render_jsonl(env, outcome.results, outcome.verdicts, include_host_names))
directory.mkdir(parents=True, exist_ok=True)
(directory / LAST_TEXT).write_text(text, encoding="utf-8")
(directory / LAST_JSONL).write_text(jsonl, encoding="utf-8")
return PathTestResult(text, jsonl, directory / LAST_TEXT)
def _as_real(attempt: Attempt) -> tuple[Outcome, int, str, float]:
return attempt.outcome, attempt.millis, attempt.detail, attempt.at