ZaStoGram/TMessagesProj/jni/tgnet/pathtest/test/pathtest_servers.py
loop-uh a918b73f48
Some checks failed
Build three ZaStoGram APKs / build (armeabi-v7a, ZaStoGram-standalone-armeabi-v7a, Armv7, armv7) (push) Failing after 49s
Build three ZaStoGram APKs / build (arm64-v8a, ZaStoGram-standalone-arm64-v8a, Arm64, arm64) (push) Failing after 51s
ZaStoGram source guards / guards (push) Failing after 40s
Build three ZaStoGram APKs / build (x86, ZaStoGram-standalone-x86, X86, x86) (push) Failing after 1m8s
Check connection: a path test that runs the real client code and writes one log
New module (jni/tgnet/pathtest, org.telegram.zastogram.pathtest): for every proxy of the list, the official WSS route
and two control hosts it makes 12 attempts 1.5 s apart through the REAL client code and writes one text log with a
JSONL twin into the logs folder (so the logs screen and its zip export carry it): per-attempt lines (server_hello,
alert, rst, fin, silent, connect_failed with time to first byte, DNS and TCP times), a summary table and a plain
verdict per host and profile.

The probe is not a second client: Naive entries go through naive::CreateFor, the WSS route through the real
wss::Socket (setDiagnosticProbe switches off route-health writes), FakeTLS profiles through composeFakeTlsClientHello,
now the single place ConnectionSocket also builds its hello. The probe peeks the first server bytes to classify the
answer. Secrets are never read (random FakeTLS key, throw-away Naive credentials, only the cover domain of a secret),
hosts are ep-<8 hex of sha256(host:port)> unless real names are ticked, every log field is a closed-vocabulary token.

UI: a row in the proxy settings, an offer after a failed proxy check, share button. Tests: JVM tests of the pure
logic, a native host test against the real WssSocket.cpp and local servers (silent, fin, rst, alert, http, overloaded),
guards updated for the shared hello composer. Verified on an x86_64 emulator against lab shapes and the real relay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 12:36:51 +00:00

161 lines
4.9 KiB
Python
Executable file

#!/usr/bin/env python3
"""Local servers that behave like the things a network or a node can do to a TLS client, for the host test of the
"Check connection" probe (pathtest_host_test.cpp). Prints one JSON line with the ports, then serves until killed.
tls real TLS 1.3 server (lab certificate, SAN proxy.test), answers every request with HTTP 404 and closes
silent accepts, reads the hello, never answers (the 2026-11-29 case: TCP opens, zero bytes come back)
fin reads the hello, closes in order
rst reads the hello, closes with a reset (SO_LINGER 0)
alert reads the hello, sends a fatal TLS alert (handshake_failure) and closes
http answers any bytes with a plain HTTP page (not TLS)
slow a TLS server that answers only every third connection (an overloaded accept queue)
Also writes the ClientHello of an ordinary TLS client (python ssl, SNI proxy.test) to HELLO_FILE: the raw-hello probe
sends it, so every answer class can be checked without the composer of ConnectionSocket.cpp.
"""
import json
import os
import socket
import ssl
import struct
import subprocess
import sys
import tempfile
import threading
import time
OUT = sys.argv[1] # directory for cert, key, hello
def make_cert():
cert = os.path.join(OUT, "lab.pem")
key = os.path.join(OUT, "lab.key")
subprocess.run(["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes",
"-keyout", key, "-out", cert, "-days", "2", "-subj", "/CN=proxy.test",
"-addext", "subjectAltName=DNS:proxy.test"], check=True, capture_output=True)
return cert, key
def make_hello():
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO()
obj = ctx.wrap_bio(incoming, outgoing, server_hostname="proxy.test")
try:
obj.do_handshake()
except ssl.SSLWantReadError:
pass
data = outgoing.read()
assert data[0] == 0x16, "not a TLS record"
with open(os.path.join(OUT, "hello.bin"), "wb") as f:
f.write(data)
def listener():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((os.environ.get("PATHTEST_BIND", "127.0.0.1"), 0)) # 0.0.0.0 to serve an emulator on another host
s.listen(64)
return s
def serve(sock, handler):
def loop():
while True:
try:
conn, _ = sock.accept()
except OSError:
return
threading.Thread(target=handler, args=(conn,), daemon=True).start()
threading.Thread(target=loop, daemon=True).start()
def read_hello(conn):
conn.settimeout(3)
try:
return conn.recv(65536)
except OSError:
return b""
def h_silent(conn):
read_hello(conn)
time.sleep(30)
conn.close()
def h_fin(conn):
read_hello(conn)
conn.shutdown(socket.SHUT_RDWR)
conn.close()
def h_rst(conn):
read_hello(conn)
conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
conn.close()
def h_alert(conn):
read_hello(conn)
conn.sendall(bytes([0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x28]))
conn.close()
def h_http(conn):
read_hello(conn)
conn.sendall(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
conn.close()
def make_tls_handler(cert, key, every=1):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
ctx.load_cert_chain(cert, key)
counter = {"n": 0}
lock = threading.Lock()
def handler(conn):
with lock:
counter["n"] += 1
mine = counter["n"]
if every > 1 and mine % every != 0:
time.sleep(30) # overloaded: the connection sits in the queue, never served
conn.close()
return
try:
conn.settimeout(5)
tls = ctx.wrap_socket(conn, server_side=True)
tls.recv(65536)
tls.sendall(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
tls.close()
except Exception:
try:
conn.close()
except Exception:
pass
return handler
def main():
cert, key = make_cert()
make_hello()
ports = {}
for name, handler in (("tls", make_tls_handler(cert, key)), ("silent", h_silent), ("fin", h_fin), ("rst", h_rst),
("alert", h_alert), ("http", h_http), ("slow", make_tls_handler(cert, key, every=3))):
s = listener()
ports[name] = s.getsockname()[1]
serve(s, handler)
# a port nobody listens on
s = listener()
ports["closed"] = s.getsockname()[1]
s.close()
ports["cert"] = cert
ports["hello"] = os.path.join(OUT, "hello.bin")
print(json.dumps(ports), flush=True)
while True:
time.sleep(1)
main()