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
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>
191 lines
8.2 KiB
C++
191 lines
8.2 KiB
C++
/*
|
|
* This is the source code of tgnet library v. 1.1
|
|
* It is licensed under GNU GPL v. 2 or later.
|
|
*/
|
|
|
|
#ifndef TGNET_WSS_SOCKET_H
|
|
#define TGNET_WSS_SOCKET_H
|
|
|
|
#include "../transport/TransportSocket.h"
|
|
|
|
#include <deque>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
struct zsg_ws; // opaque handle of libzsgnaive (global scope, see zsg_naive.h)
|
|
|
|
namespace tgnet {
|
|
namespace wss {
|
|
|
|
struct Route {
|
|
std::string relayHost;
|
|
std::string relayHostFallback;
|
|
std::string connectHost;
|
|
uint16_t relayPort = 443;
|
|
std::string domain;
|
|
std::string path = "/apiws";
|
|
bool viaFallback = false;
|
|
// The Worker tunnel reaches the DC over plain TCP, where bytes 60..61 of
|
|
// the obfuscation header must name the DC and traffic class.
|
|
bool tunnel = false;
|
|
// 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 address and carries the byte stream as is.
|
|
int32_t cdnSlot = -1;
|
|
int32_t cdnDcId = 0;
|
|
// Which of the front's two Cloudflare addresses this route dials.
|
|
int32_t cdnAddress = -1;
|
|
// 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 record.
|
|
bool plain = false;
|
|
// Key for failure counting and suppression when it must not follow the
|
|
// domain: every front domain of a DC shares one health record.
|
|
std::string healthDomain;
|
|
// Network the route was chosen on (see SetNetworkType): its failures count
|
|
// against that network only, even when reported after a switch.
|
|
int32_t network = 0;
|
|
// DC of an official relay route, which picks relayHost from the DC's list
|
|
// of ingress addresses; 0 for fronts and the tunnel.
|
|
int32_t relayDcId = 0;
|
|
// Plain TCP to the DC's own address: the guarded step after the tunnel and
|
|
// before the fronts that ignore suppression. Not a WSS socket: the caller
|
|
// dials dcAddress itself and reports the verdict (NoteDirectStepClosed).
|
|
bool direct = false;
|
|
};
|
|
|
|
// Wi-Fi and mobile data reach Telegram through different providers, so relay
|
|
// health, suppression and the IP/DNS preference are kept per network type.
|
|
void SetNetworkType(int32_t networkType);
|
|
|
|
// Telegram's public web relays cover production DC1-DC5. Media connections
|
|
// use the corresponding -1 relay, matching Telegram Web's transport catalog.
|
|
// While a DC's relay is suppressed as unreachable, the route switches to the
|
|
// Cloudflare front domains of tg-ws-proxy, then to the ZaStoGram Cloudflare
|
|
// Worker, which opens dcAddress (IPv4) over TCP itself, then to direct TCP
|
|
// (Route::direct) unless that is paused, and finally to the fronts again
|
|
// whatever their suppression.
|
|
bool OfficialRoute(int32_t dcId, bool mediaConnection, bool testBackend, const std::string &dcAddress, Route *route);
|
|
|
|
// Received bytes that prove a direct step: as with the fronts, networks that
|
|
// throttle Telegram let the first answers through and freeze the rest.
|
|
constexpr uint64_t kDirectProofBytes = 32 * 1024;
|
|
|
|
// Verdict on a direct step (Route::direct) once its socket closes. A failure
|
|
// (no TCP, no answer, or a session that ended short of kDirectProofBytes)
|
|
// pauses direct TCP for this DC and network at once; proof clears the pause
|
|
// history. Anything else (an idle close by the app) leaves it as it was.
|
|
void NoteDirectStepClosed(const Route &route, uint64_t receivedBytes, const char *failure);
|
|
|
|
// Whether OfficialRoute would still hand out this exact route: same network,
|
|
// not suppressed and not switched to the relay's DNS name.
|
|
bool RouteUsable(const Route &route);
|
|
|
|
// The Cloudflare front route that replaced a stale one after a failure moved
|
|
// the catalog position on; false if the route is not a front route.
|
|
bool FollowCdnRoute(const Route &stale, Route *fresh);
|
|
|
|
// Whether OfficialRoute would carry this DC through the Cloudflare tunnel now.
|
|
bool DatacenterTunneled(int32_t dcId, bool mediaConnection, bool testBackend);
|
|
|
|
// Keeps relay suppression across launches in this file (read once).
|
|
void SetRouteHealthPath(const std::string &path);
|
|
|
|
class Socket final : public transport::Socket {
|
|
public:
|
|
explicit Socket(Route route);
|
|
~Socket() override;
|
|
|
|
bool open(const struct sockaddr *address, socklen_t addressLength, std::string *diagnostic) override;
|
|
int fd() const override;
|
|
bool onEvent(uint32_t events, std::vector<std::vector<uint8_t>> &payloads, std::string *diagnostic) override;
|
|
bool write(const uint8_t *data, uint32_t size, std::string *diagnostic) override;
|
|
size_t queuedOutputBytes() const override;
|
|
bool isReady() const override;
|
|
bool wantsWrite() const override;
|
|
bool canWriteApplicationData() const override;
|
|
bool isClosed() const override;
|
|
transport::HandshakePhase handshakePhase() const override;
|
|
const char *transportName() const override;
|
|
void timedOut() override;
|
|
void timedOutMidPacket(bool midPacket) override;
|
|
void noteAppDataTimeout() override;
|
|
std::string takeSessionSummary() override;
|
|
uint64_t receivedBytes() const override;
|
|
void close() override;
|
|
|
|
const Route &route() const;
|
|
|
|
// A pool spare nobody is waiting for: its failures say too little about
|
|
// the relay to move real connections to another address or the tunnel.
|
|
void setSpeculative(bool value);
|
|
|
|
// The "Check connection" module (tgnet/pathtest) drives this very socket, handshake included, to measure what a
|
|
// network does to the real client. A probe must not teach the client anything: with this set, every write to
|
|
// the route health, the front rotation and the address preferences is skipped. The handshake code is untouched.
|
|
void setDiagnosticProbe(bool value);
|
|
|
|
private:
|
|
enum class State : uint8_t {
|
|
TcpConnecting,
|
|
Handshake, // TLS and the WebSocket upgrade, driven by libzsgnaive
|
|
Ready,
|
|
Closed,
|
|
};
|
|
|
|
bool finishTcpConnect(std::string *diagnostic);
|
|
bool startClient(std::string *diagnostic);
|
|
bool pumpNetwork(std::string *diagnostic);
|
|
bool flushNetwork(std::string *diagnostic);
|
|
bool readNetwork(bool *eof, std::string *diagnostic);
|
|
bool checkClientState(std::string *diagnostic);
|
|
void collectMessages(std::vector<std::vector<uint8_t>> &payloads);
|
|
void noteAttemptFailed();
|
|
void noteUpgradeSucceeded();
|
|
bool outputDrained() const;
|
|
const char *stateName() const;
|
|
Route routeConfig;
|
|
// Numeric address this socket dialled, to tell a dropped flow from a dead relay.
|
|
std::string peerAddress;
|
|
// The TLS + HTTP + WebSocket client of libzsgnaive (Chrome 158 handshake); sans-I/O, this class owns the socket.
|
|
::zsg_ws *client = nullptr;
|
|
int socketFd = -1;
|
|
State state = State::Closed;
|
|
transport::HandshakePhase phase = transport::HandshakePhase::None;
|
|
// Network bytes produced by the client and not yet accepted by the kernel.
|
|
std::vector<uint8_t> pending;
|
|
size_t pendingOffset = 0;
|
|
// The relay parses the 64-byte obfuscation header out of the payload of the
|
|
// FIRST binary frame alone — not out of the reassembled message and not out
|
|
// of the TCP stream. A shorter first frame is fatal and, worse, silent: the
|
|
// relay simply never answers. Hold the opening bytes back until the header
|
|
// is complete so no caller chunking can violate that.
|
|
std::vector<uint8_t> openingFrame;
|
|
bool openingFrameSent = false;
|
|
bool failureRecorded = false;
|
|
// Upgrades answered 503 on this TLS connection (Cloudflare front only).
|
|
uint32_t upgradeRetries = 0;
|
|
bool provenRecorded = false;
|
|
bool speculative = false;
|
|
bool diagnosticProbe = false;
|
|
bool fromPool = false;
|
|
// For the wss_session summary logged on close.
|
|
int64_t openedAtMs = 0;
|
|
int64_t readyAtMs = 0;
|
|
int64_t firstDataAtMs = 0;
|
|
// With first_data_ms it gives throughput: rx / (last - first).
|
|
int64_t lastDataAtMs = 0;
|
|
// Set for the duration of timedOutMidPacket(true).
|
|
bool timeoutMidPacket = false;
|
|
uint64_t bytesOut = 0;
|
|
uint64_t bytesIn = 0;
|
|
bool summaryTaken = false;
|
|
bool reachableRecorded = false;
|
|
};
|
|
|
|
std::unique_ptr<transport::Socket> CreateSocket(Route route);
|
|
|
|
} // namespace wss
|
|
} // namespace tgnet
|
|
|
|
#endif
|