ZaStoGram/TMessagesProj/jni/tgnet/pathtest/PathTestProbe.cpp
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

342 lines
11 KiB
C++

#include "PathTestProbe.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include <chrono>
#include <vector>
namespace tgnet {
namespace pathtest {
namespace {
int64_t NowMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch())
.count();
}
bool Contains(const std::string &text, const char *needle) {
return text.find(needle) != std::string::npos;
}
// What an orderly close or a reset before any TLS byte looks like in the real sockets' own diagnostics.
const char *ClassifyDiagnostic(const std::string &diagnostic) {
if (Contains(diagnostic, "eof") || Contains(diagnostic, "peer_closed") || Contains(diagnostic, "closed")) {
return "fin";
}
// A send into a connection the peer already reset fails the same way a read does.
if (Contains(diagnostic, "read_failed") || Contains(diagnostic, "write_failed") || Contains(diagnostic, "socket_error")
|| Contains(diagnostic, "reset")) {
return "rst";
}
return "other";
}
const char *ConnectErrorToken(int error) {
switch (error) {
case ECONNREFUSED: return "refused";
case ETIMEDOUT: return "tcp_timeout";
case ENETUNREACH:
case EHOSTUNREACH: return "unreachable";
case ECONNRESET: return "reset";
default: return "connect_error";
}
}
} // namespace
const char *ClassifyFirstBytes(const uint8_t *data, size_t size) {
if (size == 0) {
return "other";
}
// A TLS record starts with its type and the legacy version 0x03 0x0x.
const bool tlsVersion = size < 2 || data[1] == 0x03;
if (data[0] == 0x16 && tlsVersion) {
return "server_hello";
}
if (data[0] == 0x15 && tlsVersion) {
return "alert";
}
return "other";
}
std::string Token(const std::string &text) {
std::string out;
for (char c : text) {
if (c >= 'A' && c <= 'Z') {
c = static_cast<char>(c - 'A' + 'a');
}
const bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == ':' || c == '=' || c == '-';
if (!ok) {
c = '_';
}
if (c == '_' && (out.empty() || out.back() == '_')) {
continue;
}
out.push_back(c);
if (out.size() >= 48) {
break;
}
}
while (!out.empty() && out.back() == '_') {
out.pop_back();
}
return out;
}
std::string Encode(const Result &r) {
return "class=" + r.cls + ";tcp_ms=" + std::to_string(r.tcpMs) + ";ttfb_ms=" + std::to_string(r.ttfbMs)
+ ";total_ms=" + std::to_string(r.totalMs) + ";app=" + r.app + ";detail=" + r.detail;
}
Result ProbeTransport(transport::Socket &socket, const sockaddr *address, socklen_t length, int timeoutMs, int afterTlsMs) {
Result r;
const int64_t start = NowMs();
std::string diagnostic;
if (!socket.open(address, length, &diagnostic)) {
r.cls = "connect_failed";
r.detail = Token(diagnostic);
r.totalMs = NowMs() - start;
socket.close();
return r;
}
bool tcpUp = false;
bool firstSeen = false;
bool tlsReady = false;
bool finished = false;
int64_t tcpAt = 0;
int64_t tlsAt = 0;
std::vector<std::vector<uint8_t>> payloads;
while (!finished) {
const int64_t now = NowMs();
int64_t limit = start + timeoutMs;
if (tlsReady) {
limit = std::min(limit, tlsAt + afterTlsMs);
}
if (now >= limit) {
break;
}
const int fd = socket.fd();
if (fd < 0) {
break;
}
pollfd entry = {};
entry.fd = fd;
entry.events = static_cast<short>(POLLIN | POLLRDHUP | (socket.wantsWrite() ? POLLOUT : 0));
const int ready = poll(&entry, 1, static_cast<int>(std::min<int64_t>(limit - now, 50)));
if (ready < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if (ready == 0) {
continue;
}
// Look at the first bytes BEFORE the real socket reads them; MSG_PEEK leaves them for it.
if (tcpUp && !firstSeen && (entry.revents & (POLLIN | POLLHUP | POLLERR | POLLRDHUP))) {
uint8_t head[6];
const ssize_t n = recv(fd, head, sizeof(head), MSG_PEEK | MSG_DONTWAIT);
if (n > 0) {
firstSeen = true;
r.ttfbMs = NowMs() - tcpAt;
r.cls = ClassifyFirstBytes(head, static_cast<size_t>(n));
if (r.cls != "server_hello") {
finished = true; // an alert or a non-TLS answer ends the attempt; keep its class
break;
}
} else if (n == 0) {
r.cls = "fin";
r.ttfbMs = NowMs() - tcpAt;
finished = true;
break;
} else if (errno == ECONNRESET || errno == EPIPE || errno == ETIMEDOUT) {
r.cls = "rst";
r.ttfbMs = NowMs() - tcpAt;
finished = true;
break;
}
}
payloads.clear();
diagnostic.clear();
const bool alive = socket.onEvent(static_cast<uint32_t>(entry.revents), payloads, &diagnostic);
const transport::HandshakePhase phase = socket.handshakePhase();
if (!tcpUp && phase >= transport::HandshakePhase::TcpConnected) {
tcpUp = true;
tcpAt = NowMs();
r.tcpMs = tcpAt - start;
}
if (!tlsReady && phase >= transport::HandshakePhase::TlsReady) {
tlsReady = true;
tlsAt = NowMs();
if (!firstSeen) {
firstSeen = true;
r.cls = "server_hello";
r.ttfbMs = tlsAt - tcpAt;
}
}
if (!alive) {
r.detail = Token(diagnostic);
if (!tcpUp) {
r.cls = "connect_failed";
} else if (!firstSeen) {
r.cls = ClassifyDiagnostic(diagnostic);
} else {
// The server answered; what failed is a later layer. Keep what the real socket said.
if (Contains(diagnostic, "tunnel_refused")) {
r.app = "tunnel_refused";
} else if (Contains(diagnostic, "upgrade_failed")) {
r.app = "upgrade_refused";
}
}
finished = true;
break;
}
if (socket.isReady()) {
r.app = std::string(socket.transportName()) == "naive" ? "tunnel_open" : "upgrade_ok";
finished = true;
}
}
if (!finished && r.app.empty()) {
if (!tcpUp) {
r.cls = "connect_failed";
r.detail = "tcp_timeout";
} else if (!firstSeen) {
r.cls = "silent";
r.detail = "no_answer";
} else if (r.cls == "server_hello" && tlsReady) {
r.app = "timeout";
}
}
r.totalMs = NowMs() - start;
socket.close();
return r;
}
Result ProbeRawHello(const sockaddr *address, socklen_t length, const uint8_t *hello, uint32_t helloSize, int timeoutMs) {
Result r;
const int64_t start = NowMs();
const int fd = ::socket(address->sa_family, SOCK_STREAM, 0);
if (fd < 0) {
r.cls = "connect_failed";
r.detail = "socket_failed";
return r;
}
const int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
auto finish = [&](Result &result) {
result.totalMs = NowMs() - start;
::close(fd);
return result;
};
if (::connect(fd, address, length) != 0 && errno != EINPROGRESS) {
r.cls = "connect_failed";
r.detail = ConnectErrorToken(errno);
return finish(r);
}
// Wait for the connect to finish.
for (;;) {
const int64_t now = NowMs();
if (now >= start + timeoutMs) {
r.cls = "connect_failed";
r.detail = "tcp_timeout";
return finish(r);
}
pollfd entry = {fd, POLLOUT, 0};
const int ready = poll(&entry, 1, static_cast<int>(std::min<int64_t>(start + timeoutMs - now, 50)));
if (ready < 0 && errno != EINTR) {
r.cls = "connect_failed";
r.detail = "poll_failed";
return finish(r);
}
if (ready > 0) {
int error = 0;
socklen_t errorLength = sizeof(error);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &errorLength);
if (error != 0) {
r.cls = "connect_failed";
r.detail = ConnectErrorToken(error);
return finish(r);
}
break;
}
}
const int64_t tcpAt = NowMs();
r.tcpMs = tcpAt - start;
// Send the hello.
uint32_t sent = 0;
while (sent < helloSize) {
const ssize_t n = ::send(fd, hello + sent, helloSize - sent, MSG_NOSIGNAL);
if (n > 0) {
sent += static_cast<uint32_t>(n);
continue;
}
if (n < 0 && errno == EINTR) {
continue;
}
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (NowMs() >= start + timeoutMs) {
r.cls = "silent";
r.detail = "send_stalled";
return finish(r);
}
pollfd entry = {fd, POLLOUT, 0};
poll(&entry, 1, 50);
continue;
}
r.cls = (errno == ECONNRESET || errno == EPIPE) ? "rst" : "other";
r.detail = "send_failed";
return finish(r);
}
// Wait for the first bytes.
for (;;) {
const int64_t now = NowMs();
if (now >= start + timeoutMs) {
r.cls = "silent";
r.detail = "no_answer";
return finish(r);
}
pollfd entry = {fd, static_cast<short>(POLLIN | POLLRDHUP), 0};
const int ready = poll(&entry, 1, static_cast<int>(std::min<int64_t>(start + timeoutMs - now, 50)));
if (ready < 0 && errno != EINTR) {
break;
}
if (ready <= 0) {
continue;
}
uint8_t head[6];
const ssize_t n = recv(fd, head, sizeof(head), MSG_DONTWAIT);
if (n > 0) {
r.cls = ClassifyFirstBytes(head, static_cast<size_t>(n));
r.ttfbMs = NowMs() - tcpAt;
return finish(r);
}
if (n == 0) {
r.cls = "fin";
r.ttfbMs = NowMs() - tcpAt;
return finish(r);
}
if (errno == ECONNRESET || errno == EPIPE || errno == ETIMEDOUT) {
r.cls = "rst";
r.ttfbMs = NowMs() - tcpAt;
return finish(r);
}
}
r.cls = "other";
r.detail = "poll_failed";
return finish(r);
}
} // namespace pathtest
} // namespace tgnet