zapret-kvn/xray_fluent/diagnostics/path_test/steps.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

91 lines
4.2 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.

"""Простые шаги проверки: DNS, TCP и платформенный TLS (контроль). Рукопожатия своего вида не строятся."""
from __future__ import annotations
import socket
import ssl
import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
from .model import Attempt, Outcome, Step
DNS_TIMEOUT_S = 5.0
TCP_TIMEOUT_S = 5.0
TLS_TIMEOUT_S = 6.0
def _attempt(step: Step, outcome: Outcome, started: float, detail: str = "") -> Attempt:
return Attempt(step, outcome, max(0, int((time.time() - started) * 1000)), detail, started)
def dns(host: str, timeout: float = DNS_TIMEOUT_S) -> Attempt:
started = time.time()
pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="path-test-dns")
try:
future = pool.submit(socket.getaddrinfo, host, None, 0, socket.SOCK_STREAM)
try:
answers = future.result(timeout)
except FutureTimeout:
return _attempt(Step.DNS, Outcome.DNS_FAILED, started, "timeout")
except socket.gaierror:
return _attempt(Step.DNS, Outcome.DNS_FAILED, started, "unknown_host")
except OSError as exc:
return _attempt(Step.DNS, Outcome.DNS_FAILED, started, type(exc).__name__)
return _attempt(Step.DNS, Outcome.OK, started, f"answers={len({a[4][0] for a in answers})}")
finally:
pool.shutdown(wait=False, cancel_futures=True)
def classify_connect(error: BaseException) -> Outcome:
if isinstance(error, (socket.timeout, TimeoutError)):
return Outcome.TIMEOUT
if isinstance(error, ConnectionRefusedError):
return Outcome.REFUSED
if isinstance(error, socket.gaierror):
return Outcome.DNS_FAILED
return Outcome.UNREACHABLE
def tcp(host: str, port: int, timeout: float = TCP_TIMEOUT_S) -> Attempt:
started = time.time()
try:
with socket.create_connection((host, port), timeout=timeout):
pass
return _attempt(Step.TCP, Outcome.OK, started)
except OSError as exc:
return _attempt(Step.TCP, classify_connect(exc), started, type(exc).__name__)
def classify_tls(error: BaseException) -> tuple[Outcome, str]:
"""Только настоящий alert или увиденный сертификат считаются ответом: обычный обрыв рукопожатия НЕ ответ."""
if isinstance(error, ssl.SSLCertVerificationError):
return Outcome.ALERT, "server_certificate_seen"
message = str(error).lower()
if isinstance(error, (socket.timeout, TimeoutError)):
return Outcome.SILENT, "no_answer"
if isinstance(error, ConnectionRefusedError):
return Outcome.REFUSED, "tcp"
# Windows: сервер, принявший и тут же закрывшего соединение, даёт ConnectionAbortedError (10053), это обрыв, а не «недоступен».
if isinstance(error, (ConnectionResetError, ConnectionAbortedError, BrokenPipeError)) or "reset" in message:
return Outcome.RESET, "connection_reset"
if "alert" in message:
return Outcome.ALERT, "tls_alert"
if isinstance(error, ssl.SSLEOFError) or "eof" in message or "closed" in message or "terminated" in message:
return Outcome.CLOSED, "closed_before_server_hello"
if isinstance(error, ssl.SSLError):
return Outcome.CLOSED, "handshake_error"
if isinstance(error, OSError):
return classify_connect(error), "tcp"
return Outcome.CLOSED, type(error).__name__
def platform_tls(host: str, port: int, timeout: float = TLS_TIMEOUT_S) -> Attempt:
started = time.time()
context = ssl.create_default_context()
try:
with socket.create_connection((host, port), timeout=timeout) as raw:
raw.settimeout(timeout)
with context.wrap_socket(raw, server_hostname=host) as tls:
return _attempt(Step.PLATFORM_TLS, Outcome.HANDSHAKE_OK, started, f"protocol={tls.version()}")
except Exception as exc: # noqa: BLE001 - любая ошибка рукопожатия классифицируется, не пробрасывается
outcome, detail = classify_tls(exc)
return _attempt(Step.PLATFORM_TLS, outcome, started, detail)