ZaStoGram_desktop/Telegram/SourceFiles/mtproto/proxy/wss/socket.h
loop-uh 755fe43c87 Check connection: a path test that runs the real client code and writes one log
Desktop twin of the Android module (zsg_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 log,
tdata/pathtest/path-test-YYYYMMDD-HHMMSS.txt with a JSONL twin: 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. Same format and same ep-<8 hex> host ids as Android (golden files from the Java implementation are
reproduced byte for byte by tests/run_pathtest_core_test.sh).

The probe is not a second client: WssClientConfig and Zsg::Naive::NaiveClientConfig are now the single builders of the
zsgnaive config for both the real sockets and the probe, and FakeTLS profiles go through PrepareClientHelloRules +
PrepareClientHello, the calls TlsSocket::sendClientHello makes. Secrets are never read (random FakeTLS key, throw-away
Naive credentials, only the cover domain of a secret); every log field is a closed-vocabulary token.

UI: a section in the proxy box, an offer once in 30 minutes when the retry link appears. Guards: test_zsg_pathtest.py,
test_proxy_wss_default.py updated for the shared config builder.

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

244 lines
9.2 KiB
C++

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "mtproto/transport/details/mtproto_abstract_socket.h"
#include "zsg_naive/zsg_naive_api.h"
#include <QtNetwork/QTcpSocket>
#include <memory>
#include <optional>
namespace MTP::details {
struct WssRoute {
QString relayHost;
QString relayHostFallback; // retried once if relayHost fails (e.g. domain)
int relayPort = 443;
QString domain;
QString path;
bool tunnel = false; // path gets ?dst=<datacenter address> on connect
// Position in the Cloudflare front catalog (kwsN.<front domain>), or -1.
// The front forwards the WebSocket to Telegram Web itself, so unlike the
// tunnel it needs no destination and carries the byte stream as is.
int cdnSlot = -1;
int cdnDcId = 0;
// A front dialled over plain HTTP (ws://, port 80): no TLS, so no SNI for
// a network to match. A step after the TLS fronts, with its own health.
bool plain = false;
// Failure counting and suppression key when it must not follow the
// domain: every front domain of a DC shares one health record.
QString healthDomain;
// Network the route was chosen on (see WssTrackNetwork): its failures
// count against that network only, even when reported after a switch.
bool metered = false;
// DC of an official relay route, which picks relayHost from the DC's
// list of ingress addresses; 0 for fronts, the tunnel and custom relays.
int relayDcId = 0;
// Plain TCP to the DC's own address, the guarded step after the tunnel
// and before the fronts that ignore suppression. The socket factory makes
// a WssDirectStepSocket for it, not a WebSocket.
bool direct = false;
};
// The zsgnaive client config of a route, built in ONE place: the real WssSocket::startClient and the "Check
// connection" probe (zsg_pathtest) both use it, so the diagnostic cannot configure the handshake differently from the
// client. Owns the strings the config points to; keep it alive as long as the library client.
class WssClientConfig {
public:
explicit WssClientConfig(const WssRoute &route);
WssClientConfig(const WssClientConfig &other) = delete;
WssClientConfig &operator=(const WssClientConfig &other) = delete;
[[nodiscard]] const Zsg::Naive::WsConfig &config() const {
return _config;
}
private:
QByteArray _domain;
QByteArray _sni;
QByteArray _path;
Zsg::Naive::WsConfig _config;
};
// A phone's hotspot (Windows marks Android tethering as metered) reaches
// Telegram through the mobile operator, whose blocks differ from the home
// provider's. Relay health, suppression and the IP/DNS preference are kept
// separately for metered and unmetered networks. Call on the main thread.
void WssTrackNetwork();
// A passive snapshot for user-facing media diagnostics. It observes the
// relay preference and health maps, but never changes connection admission,
// retry timing or the lifetime of a live session.
struct WssRouteDiagnostics {
std::optional<WssRoute> route;
QString selectedRelayHost;
bool custom = false;
bool prefersFallback = false;
bool suppressed = false;
int consecutiveFailures = 0;
crl::time suppressedFor = 0;
};
// Official MTProto-over-WebSocket route for a data center, mirroring the
// web.telegram.org transport; while the DC's relay is suppressed, the
// Cloudflare fronts of tg-ws-proxy (kwsN.<front domain>), then the tunnel,
// then direct TCP (WssRoute::direct) unless that is paused. With everything
// suppressed the fronts stay the floor: unguarded direct TCP, which this used
// to fall back to, is what the blocking networks close.
//
// Every production DC (1-5) has a working web relay, but the ingress addresses are NOT interchangeable: each one serves
// only its own datacenters. Reaching the wrong ingress answers 302 (with an
// X-Redirect-Host header naming the right relay) or accepts the connection
// and stays silent - which is where the widespread "web sockets exist only
// for DC2/DC4" belief came from. Measured against live relays 2026-08-08.
[[nodiscard]] std::optional<WssRoute> WssOfficialRoute(
int16 protocolDcId);
// The relay of this DC has not answered on this network yet, or failed since
// it last did, while it is not suppressed. A session then races a Cloudflare
// front (WssFrontRoute) against it instead of waiting for the relay to be
// suppressed first.
[[nodiscard]] bool WssRelayUnproven(int16 protocolDcId);
[[nodiscard]] std::optional<WssRoute> WssFrontRoute(int16 protocolDcId);
// Expert-only user-configured relay (ProxyStealthOptions.wssCustom*), used
// for any DC when set and verified against the configured relay domain.
[[nodiscard]] std::optional<WssRoute> WssCustomRoute(
const ProxyStealthOptions &stealth);
[[nodiscard]] WssRouteDiagnostics WssRouteDiagnosticsForDc(
const ProxyStealthOptions &stealth,
int16 protocolDcId);
// The media relay of this DC is suppressed and its files go through the
// Cloudflare tunnel, where every connection freezes after ~16 KB downstream.
// File downloads then use small parts over many short-lived connections.
[[nodiscard]] bool WssMediaTunneled(int dcId);
// Direct TCP handed out by WssOfficialRoute as the guarded last step
// (WssRoute::direct): an ordinary TcpSocket underneath, watched so that one
// failure (no TCP, no answer within the connect budget, a session that ended
// short of 32 KB) pauses the step for this DC and network, and 32 KB of
// answers clear the pause history. Networks that block the relays often let
// TCP up and the first answers through and then throttle.
class WssDirectStepSocket final : public AbstractSocket {
public:
WssDirectStepSocket(
not_null<RuntimeEnvironment*> runtime,
not_null<QThread*> thread,
const QNetworkProxy &proxy,
bool protocolForFiles,
WssRoute route);
~WssDirectStepSocket();
void connectToHost(const QString &address, int port) override;
bool isGoodStartNonce(bytes::const_span nonce) override;
void timedOut() override;
bool isConnected() override;
bool hasBytesAvailable() override;
int64 read(bytes::span buffer) override;
void write(bytes::const_span prefix, bytes::const_span buffer) override;
int32 debugState() override;
QString debugPostfix() const override;
private:
void judge(const char *failure);
const std::unique_ptr<AbstractSocket> _tcp;
const WssRoute _route;
qint64 _bytesReceived = 0;
bool _ipv6 = false;
bool _judged = false;
rpl::lifetime _lifetime;
};
// MTProto-over-WebSocket(-over-TLS) transport. The TLS handshake (a Chrome 158
// ClientHello), the HTTP upgrade (a Chrome WebSocket request) and the RFC 6455
// framing are done by the zsgnaive library, so the connection looks like a
// browser's; this class owns a plain QTcpSocket, moves bytes between it and
// the library, and keeps the route and health bookkeeping. The obfuscated
// MTProto stream rides transparently inside binary messages, so the rest of
// the connection stack (obfuscation, protocol negotiation) is unchanged.
class WssSocket final : public AbstractSocket {
public:
WssSocket(
not_null<RuntimeEnvironment*> runtime,
not_null<QThread*> thread,
const QNetworkProxy &proxy,
bool protocolForFiles,
WssRoute route);
~WssSocket();
void connectToHost(const QString &address, int port) override;
bool isGoodStartNonce(bytes::const_span nonce) override;
void timedOut() override;
[[nodiscard]] bool takeRotation() override;
[[nodiscard]] bool plainDcMarker() const override;
bool isConnected() override;
bool hasBytesAvailable() override;
int64 read(bytes::span buffer) override;
void write(bytes::const_span prefix, bytes::const_span buffer) override;
int32 debugState() override;
QString debugPostfix() const override;
HandshakePhase handshakePhase() const override;
QString transportName() const override;
private:
void handleError(int errorCode, const QString &text = QString());
void connectToRelayHost();
void onTcpConnected();
void onReadyRead();
void startClient();
void releaseClient();
// Moves the library's outgoing bytes to the socket and reacts to its
// state. False means the socket reported a failure (and may be gone).
[[nodiscard]] bool pumpClient();
void finishUpgrade();
[[nodiscard]] bool handleRefusedUpgrade();
void collectMessages();
[[nodiscard]] bool outputDrained() const;
void noteFrontFailed();
void sendMessage(bytes::const_span data);
QTcpSocket _socket;
WssRoute _route;
const Zsg::Naive::Api *_api = nullptr;
Zsg::Naive::WsHandle *_client = nullptr;
std::unique_ptr<WssClientConfig> _clientConfig;
QByteArray _readBuffer;
bool _upgraded = false;
bool _usedFallback = false;
bool _hostFlipped = false;
bool _addressMoved = false;
QString _currentHost;
bool _tcpConnected = false;
QString _lastError; // the last failure of this socket (code and text), for the wss_session line
qint64 _bytesReceived = 0;
qint64 _bytesSent = 0;
bool _tunnelProven = false;
bool _frontAnswered = false;
bool _frontProven = false;
bool _frontFailureNoted = false;
int _upgradeRetries = 0;
bool _forFiles = false;
bool _rotated = false;
crl::time _openedAt = 0;
crl::time _upgradedAt = 0;
crl::time _firstDataAt = 0;
HandshakePhase _phase = HandshakePhase::None;
};
} // namespace MTP::details