ZaStoGram_desktop/Telegram/SourceFiles/zsg_pathtest/pathtest_runner.cpp
loop-uh f9095afd3b zsg_pathtest: stealth gate (selected server by default, all servers one at a time with a 10-20 s pause) and a headless developer hook
The probe no longer touches the whole proxy list at once: default scope is the proxy in use (or the WSS route
when none), every server only on the explicit Check all proxies tick; DNS/TCP of a host happen in its own turn.
ZSG_PATHTEST_SELFTEST runs the check without a window for real-traffic verification.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 14:08:47 +00:00

652 lines
21 KiB
C++

/*
ZaStoGram "Check connection" module: see pathtest_runner.h.
*/
#include "zsg_pathtest/pathtest_runner.h"
#include "core/application.h"
#include "core/core_settings.h"
#include "core/version.h"
#include "logs.h"
#include "mtproto/proxy/mtproxy/client_hello_builder.h"
#include "mtproto/proxy/mtproxy/client_hello_profile.h"
#include "mtproto/proxy/wss/socket.h"
#include "mtproto/runtime/proxy_data.h"
#include "settings.h"
#include "zsg_pathtest/pathtest_core.h"
#include "zsg_pathtest/pathtest_probe.h"
#include <crl/crl.h>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QElapsedTimer>
#include <QtCore/QFile>
#include <QtCore/QRandomGenerator>
#include <QtCore/QSysInfo>
#include <QtCore/QThread>
#include <QtCore/QTimeZone>
#include <QtCore/QTimer>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QNetworkInformation>
#include <algorithm>
#include <atomic>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
namespace Zsg::PathTest {
namespace {
constexpr auto kTlsTimeoutMs = 5000;
constexpr auto kAfterTlsMs = 2500;
constexpr auto kMaxProxies = 6;
constexpr auto kOfficialDc = 2;
// Hosts that answer everywhere a person can browse; one Russian, one global (a whitelist passes only the first).
const char *const kControlHosts[] = { "ya.ru", "www.cloudflare.com" };
enum class Probe {
None,
Naive,
WssOfficial,
WssControl,
FakeTls,
};
struct Profile {
std::string name;
Probe probe = Probe::None;
MTP::ProxyTlsProfile tls = MTP::ProxyTlsProfile::Auto;
};
struct Target {
QString host; // real name: written only when the person ticked it
int port = 443;
std::string role;
std::string kind;
std::string label;
QString sni; // the name the hello is aimed at
std::vector<Profile> profiles;
MTP::details::WssRoute route; // for the WSS probes
Host reportHost;
QString address;
bool dnsOk = false;
};
struct State {
std::atomic<bool> cancelled = false;
std::atomic<int> done = 0;
int total = 1;
std::mutex mutex;
std::unique_ptr<Report> report;
QElapsedTimer clock;
std::function<void(int)> progress;
};
std::atomic<bool> g_running = false;
std::shared_ptr<State> g_state;
[[nodiscard]] qint64 Elapsed(const State &state) {
return state.clock.elapsed();
}
void Add(State &state, Attempt attempt) {
auto lock = std::scoped_lock(state.mutex);
state.report->add(std::move(attempt));
}
void Step(State &state, int count) {
const auto now = state.done.fetch_add(count) + count;
if (state.progress) {
const auto percent = std::min(99, now * 100 / std::max(1, state.total));
auto callback = state.progress;
crl::on_main([=] { callback(percent); });
}
}
[[nodiscard]] bool HasTls(const Target &target) {
return std::any_of(
target.profiles.begin(),
target.profiles.end(),
[](const Profile &p) { return p.probe != Probe::None; });
}
void Resolve(State &state, Target &target) {
const auto at = Elapsed(state);
auto timer = QElapsedTimer();
timer.start();
auto literal = QHostAddress();
if (literal.setAddress(target.host)) {
target.address = target.host;
target.dnsOk = true;
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, "platform", kStepDns, 0, 0,
kOk, 0, -1, "", "literal"));
} else {
const auto info = QHostInfo::fromName(target.host);
auto chosen = QHostAddress();
for (const auto &candidate : info.addresses()) {
if (candidate.protocol() == QAbstractSocket::IPv4Protocol) {
chosen = candidate;
break;
}
if (chosen.isNull()) {
chosen = candidate;
}
}
if (info.error() == QHostInfo::NoError && !chosen.isNull()) {
target.address = chosen.toString();
target.dnsOk = true;
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, "platform", kStepDns, 0, 0,
kOk, timer.elapsed(), -1, "",
"addresses=" + std::to_string(std::min<int>(info.addresses().size(), 99))));
} else {
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, "platform", kStepDns, 0, 0,
kFailed, timer.elapsed(), -1, "", "unknown_host"));
}
}
Step(state, 1);
}
void PlainTcp(State &state, Target &target) {
if (!target.dnsOk) {
Step(state, 1);
return;
}
const auto at = Elapsed(state);
const auto result = ProbeTcp(target.address, target.port, 5000);
const auto ok = (result.cls == kOk);
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, "platform", kStepTcp, 0, 0,
ok ? kOk : kFailed, result.tcpMs >= 0 ? result.tcpMs : result.totalMs, -1, "",
ok ? "" : result.detail));
Step(state, 1);
}
[[nodiscard]] ProbeResult RunProbe(const Target &target, const Profile &profile) {
switch (profile.probe) {
case Probe::Naive:
return ProbeNaive(target.host, target.port, target.address, kTlsTimeoutMs, kAfterTlsMs);
case Probe::WssOfficial:
case Probe::WssControl:
return ProbeWss(target.route, target.address, target.port, kTlsTimeoutMs, kAfterTlsMs);
case Probe::FakeTls: {
// The same two calls TlsSocket::sendClientHello makes. A random 16-byte key: the secret is never read. No
// synthetic PSK and no fragmentation: both are stealth extras of a real connection, logged as absent.
auto key = QByteArray(16, Qt::Uninitialized);
for (auto &c : key) {
c = char(QRandomGenerator::global()->generate() & 0xff);
}
const auto domain = target.sni.toUtf8();
const auto rules = MTP::details::PrepareClientHelloRules(profile.tls);
const auto hello = MTP::details::PrepareClientHello(
rules,
bytes::make_span(domain),
bytes::make_span(key),
profile.tls,
std::nullopt);
if (hello.data.isEmpty()) {
auto result = ProbeResult();
result.cls = kOther;
result.detail = "hello_build_failed";
return result;
}
return ProbeRawHello(target.address, target.port, hello.data, kTlsTimeoutMs);
}
case Probe::None:
break;
}
auto result = ProbeResult();
result.cls = kOther;
result.detail = "no_probe";
return result;
}
void RealClientAttempts(State &state, const Target &target, const Profile &profile) {
for (auto i = 1; i <= kAttempts && !state.cancelled; ++i) {
const auto at = Elapsed(state);
const auto r = RunProbe(target, profile);
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, profile.name, kStepRealClient,
i, kAttempts, r.cls, r.ttfbMs, r.tcpMs, r.app, r.detail));
Step(state, 1);
if (i < kAttempts) {
QThread::msleep(kIntervalMs);
}
}
if (state.cancelled) {
Step(state, kAttempts);
}
}
void PlatformTlsAttempts(State &state, const Target &target) {
for (auto i = 1; i <= kAttempts && !state.cancelled; ++i) {
const auto at = Elapsed(state);
const auto r = ProbePlatformTls(target.address, target.port, target.sni, kTlsTimeoutMs);
Add(state, MakeAttempt(at, target.reportHost.id, target.role, target.kind, "qt_ssl", kStepPlatformTls,
i, kAttempts, r.cls, r.cls == kOk ? r.ttfbMs : -1, -1, "", r.detail));
Step(state, 1);
if (i < kAttempts) {
QThread::msleep(kIntervalMs);
}
}
if (state.cancelled) {
Step(state, kAttempts);
}
}
[[nodiscard]] std::vector<Profile> FakeTlsProfiles() {
using P = MTP::ProxyTlsProfile;
auto result = std::vector<Profile>();
// Every profile the client has; the two automatic modes are selectors, not hellos.
for (const auto tls : { P::Firefox, P::AndroidChrome, P::Yandex, P::FirefoxAndroid, P::AndroidOkHttp, P::ChromeModern }) {
auto profile = Profile();
profile.name = SafeToken(MTP::details::ClientHelloProfile(tls).id);
profile.probe = Probe::FakeTls;
profile.tls = tls;
result.push_back(std::move(profile));
}
return result;
}
// Main thread: reads the proxy list and the WSS route. Only the host, port, type and the cover domain of a FakeTLS
// secret are taken; user names, passwords and secret keys are never copied.
[[nodiscard]] std::vector<Target> BuildTargets(bool allServers, std::vector<std::string> *withheld) {
auto targets = std::vector<Target>();
auto seen = std::vector<QString>();
auto index = 0;
// Stealth rule (owner, 2026-11-29): by default ONE server, the one in use; the whole list only on a tick.
auto proxies = std::vector<MTP::ProxyData>();
if (allServers) {
for (const auto &proxy : Core::App().settings().proxy().list()) {
proxies.push_back(proxy);
}
} else if (Core::App().settings().proxy().isEnabled()) {
const auto selected = Core::App().settings().proxy().selected();
if (!selected.host.isEmpty()) {
proxies.push_back(selected);
}
}
for (const auto &proxy : proxies) {
if (int(targets.size()) >= kMaxProxies) {
break;
}
const auto key = proxy.host.toLower() + ':' + QString::number(proxy.port);
if (proxy.host.isEmpty() || std::find(seen.begin(), seen.end(), key) != seen.end()) {
continue;
}
seen.push_back(key);
++index;
auto target = Target();
target.host = proxy.host;
target.port = int(proxy.port ? proxy.port : 443);
target.role = kRoleTarget;
target.sni = proxy.host;
const auto number = std::to_string(index);
switch (proxy.type) {
case MTP::ProxyData::Type::Naive: {
target.kind = "naive";
target.label = "naive_entry_" + number;
auto profile = Profile();
profile.name = "naive_chrome";
profile.probe = Probe::Naive;
target.profiles.push_back(std::move(profile));
} break;
case MTP::ProxyData::Type::Mtproto: {
const auto secret = proxy.secretFromMtprotoPassword();
if (secret.size() > 17 && secret[0] == gsl::byte(0xee)) {
// Only the cover domain; the key part stays untouched.
target.kind = "faketls";
target.label = "faketls_entry_" + number;
target.sni = QString::fromUtf8(
reinterpret_cast<const char*>(secret.data()) + 17,
int(secret.size()) - 17);
target.profiles = FakeTlsProfiles();
} else {
target.kind = "mtproto_plain";
target.label = "mtproto_entry_" + number;
}
} break;
case MTP::ProxyData::Type::Web:
target.kind = "web";
target.label = "web_entry_" + number;
break;
case MTP::ProxyData::Type::Http:
target.kind = "http";
target.label = "http_entry_" + number;
break;
default:
target.kind = "socks5";
target.label = "socks5_entry_" + number;
break;
}
targets.push_back(std::move(target));
}
// The WSS route is what the client uses when no proxy is in use; with a proxy selected it is not on the path.
if (const auto route = (allServers || proxies.empty())
? MTP::details::WssOfficialRoute(kOfficialDc)
: std::nullopt;
route && !route->direct) {
auto target = Target();
target.host = route->relayHost;
target.port = route->relayPort;
target.role = kRoleTarget;
target.kind = route->tunnel ? "wss_tunnel" : (route->cdnSlot >= 0 ? "wss_front" : "wss_relay");
target.label = "wss_official_dc" + std::to_string(kOfficialDc);
target.sni = route->domain;
target.route = *route;
auto profile = Profile();
profile.name = "wss_chrome";
profile.probe = Probe::WssOfficial;
target.profiles.push_back(std::move(profile));
targets.push_back(std::move(target));
}
auto control = 0;
for (const auto host : kControlHosts) {
++control;
auto target = Target();
target.host = QString::fromLatin1(host);
target.port = 443;
target.role = kRoleControl;
target.kind = "control";
target.label = "control_" + std::to_string(control);
target.sni = target.host;
target.route.relayHost = target.host;
target.route.domain = target.host;
target.route.relayPort = 443;
target.route.path = QStringLiteral("/");
auto profile = Profile();
profile.name = "wss_chrome";
profile.probe = Probe::WssControl;
target.profiles.push_back(std::move(profile));
targets.push_back(std::move(target));
}
for (const auto tls : { MTP::ProxyTlsProfile::AndroidChrome, MTP::ProxyTlsProfile::ChromeModern }) {
if (MTP::details::ClientHelloProfile(tls).withheld) {
withheld->push_back(MTP::details::ClientHelloProfile(tls).id);
}
}
return targets;
}
[[nodiscard]] std::vector<EnvironmentEntry> Environment(
const QDateTime &started,
const std::vector<std::string> &withheld,
bool allServers) {
auto env = std::vector<EnvironmentEntry>();
const auto add = [&](const char *key, const QString &value) {
env.push_back({ key, value.toStdString() });
};
add("app", QStringLiteral("zastogram_desktop"));
add("app_version", QString::fromLatin1(AppVersionStr));
add("time_local", started.toOffsetFromUtc(started.offsetFromUtc()).toString(Qt::ISODate));
add("timezone", QString::fromLatin1(QTimeZone::systemTimeZoneId()));
add("timezone_offset_min", QString::number(started.offsetFromUtc() / 60));
add("os", QSysInfo::prettyProductName());
add("cpu", QSysInfo::currentCpuArchitecture());
auto network = QStringLiteral("unknown");
auto metered = QStringLiteral("unknown");
if (QNetworkInformation::loadDefaultBackend() || QNetworkInformation::instance()) {
if (const auto info = QNetworkInformation::instance()) {
using Media = QNetworkInformation::TransportMedium;
switch (info->transportMedium()) {
case Media::Ethernet: network = QStringLiteral("ethernet"); break;
case Media::Cellular: network = QStringLiteral("cellular"); break;
case Media::WiFi: network = QStringLiteral("wifi"); break;
case Media::Bluetooth: network = QStringLiteral("bluetooth"); break;
default: break;
}
if (info->supports(QNetworkInformation::Feature::Metered)) {
metered = info->isMetered() ? QStringLiteral("true") : QStringLiteral("false");
}
}
}
add("network_type", network);
add("network_metered", metered);
add("proxy_entries", QString::number(Core::App().settings().proxy().list().size()));
add("proxy_in_use", Core::App().settings().proxy().isEnabled() ? QStringLiteral("true") : QStringLiteral("false"));
add("probe_scope", allServers ? QStringLiteral("all_servers") : QStringLiteral("selected_only"));
add("probe_gate", QStringLiteral("one_host_at_a_time_pause_10_20s_controls_ride_with_first"));
add("attempts_per_probe", QString::number(kAttempts));
add("interval_ms", QString::number(kIntervalMs));
add("tls_timeout_ms", QString::number(kTlsTimeoutMs));
add("dns_resolver", QStringLiteral("platform_qhostinfo"));
add("probe_code", QStringLiteral("real_client_zsgnaive_config_and_hello_builder"));
add("faketls_fragmentation", QStringLiteral("none_in_probe"));
add("faketls_synthetic_psk", QStringLiteral("none_in_probe"));
add("faketls_key", QStringLiteral("random_not_the_secret"));
auto joined = QString();
for (const auto &id : withheld) {
joined += QString::fromStdString(id) + ' ';
}
add("faketls_withheld_profiles", joined.trimmed());
return env;
}
void WriteFile(const QString &path, const std::string &content) {
auto file = QFile(path);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
file.write(content.data(), qint64(content.size()));
}
}
// One window = one server (plus, in the first window, the controls): resolve, plain TCP, then the probes.
void RunWindow(State &state, const std::vector<Target*> &window) {
for (const auto target : window) {
if (state.cancelled) {
break;
}
Resolve(state, *target);
PlainTcp(state, *target);
}
// One worker per (host, profile) plus one platform-TLS worker per TLS host, staggered so that a host with
// several profiles is not hit by all of them in the same instant.
auto workers = std::vector<std::thread>();
auto stagger = 0;
for (const auto targetPtr : window) {
const auto &target = *targetPtr;
if (!target.dnsOk) {
for (const auto &profile : target.profiles) {
Add(state, MakeAttempt(Elapsed(state), target.reportHost.id, target.role, target.kind,
profile.name, kStepRealClient, 1, 1, kConnectFailed, -1, -1, "", "no_address"));
Step(state, kAttempts);
}
if (HasTls(target)) {
Step(state, kAttempts);
}
continue;
}
for (const auto &profile : target.profiles) {
const auto delay = 200 * stagger++;
workers.emplace_back([&state, delay, &target, &profile] {
QThread::msleep(delay);
RealClientAttempts(state, target, profile);
});
}
if (HasTls(target)) {
const auto delay = 200 * stagger++;
workers.emplace_back([&state, delay, &target] {
QThread::msleep(delay);
PlatformTlsAttempts(state, target);
});
}
}
for (auto &worker : workers) {
worker.join();
}
}
void Run(
std::shared_ptr<State> state,
std::vector<Target> targets,
std::vector<std::string> withheld,
QDateTime started,
bool realNames,
bool allServers,
std::function<void(QString)> done) {
auto hosts = std::vector<Host>();
for (auto &target : targets) {
target.reportHost = MakeHost(
target.host.toStdString(),
target.port,
target.kind,
target.role,
target.label);
hosts.push_back(target.reportHost);
}
const auto fileName = QStringLiteral("path-test-")
+ started.toString(QStringLiteral("yyyyMMdd-HHmmss"))
+ QStringLiteral(".txt");
state->report = std::make_unique<Report>(
fileName.toStdString(),
started.toOffsetFromUtc(started.offsetFromUtc()).toString(Qt::ISODate).toStdString(),
realNames,
Environment(started, withheld, allServers),
hosts);
auto total = 0;
for (const auto &target : targets) {
total += 2 + int(target.profiles.size()) * kAttempts + (HasTls(target) ? kAttempts : 0);
}
state->total = std::max(1, total);
state->clock.start();
// Stealth rule (owner, 2026-11-29): one server at a time, a random 10-20 s pause between two servers, and the
// controls (not the user's servers) ride along with the first one. Nothing resolves or connects to a later
// server before its turn.
auto windows = std::vector<std::vector<Target*>>();
for (auto &target : targets) {
if (target.role != kRoleControl) {
windows.push_back({ &target });
}
}
if (windows.empty()) {
windows.emplace_back();
}
for (auto &target : targets) {
if (target.role == kRoleControl) {
windows.front().push_back(&target);
}
}
auto firstWindow = true;
for (const auto &window : windows) {
if (!firstWindow) {
const auto pauseMs = 10000 + int(QRandomGenerator::global()->bounded(10001));
for (auto waited = 0; waited < pauseMs && !state->cancelled; waited += 100) {
QThread::msleep(100);
}
}
firstWindow = false;
if (state->cancelled) {
break;
}
RunWindow(*state, window);
}
state->report->setFinishedNote(state->cancelled ? "cancelled" : "complete");
const auto folder = LogsFolder();
const auto text = folder + '/' + fileName;
auto jsonl = text;
jsonl.replace(QStringLiteral(".txt"), QStringLiteral(".jsonl"));
WriteFile(text, state->report->toText());
WriteFile(jsonl, state->report->toJsonl());
g_running = false;
crl::on_main([=] {
if (state->progress) {
state->progress(100);
}
done(text);
});
}
} // namespace
bool Running() {
return g_running;
}
QString LogsFolder() {
const auto folder = cWorkingDir() + QStringLiteral("tdata/pathtest");
QDir().mkpath(folder);
return folder;
}
bool Start(
RunOptions options,
std::function<void(int)> progress,
std::function<void(QString)> done) {
if (g_running.exchange(true)) {
return false;
}
auto withheld = std::vector<std::string>();
auto targets = BuildTargets(options.allServers, &withheld);
g_state = std::make_shared<State>();
g_state->progress = std::move(progress);
const auto state = g_state;
const auto started = QDateTime::currentDateTime();
std::thread([=, targets = std::move(targets), withheld = std::move(withheld)]() mutable {
Run(state, std::move(targets), std::move(withheld), started, options.realNames, options.allServers, done);
}).detach();
return true;
}
void Cancel() {
if (const auto state = g_state) {
state->cancelled = true;
}
}
void StartSelfTestFromEnvironment() {
const auto value = qEnvironmentVariable("ZSG_PATHTEST_SELFTEST");
if (value.isEmpty()) {
return;
}
const auto parts = value.split(';', Qt::SkipEmptyParts);
if (parts.isEmpty()) {
return;
}
auto options = RunOptions();
options.allServers = parts[0].startsWith(QStringLiteral("all"));
options.realNames = parts[0].contains(QStringLiteral("+names"));
auto list = std::vector<MTP::ProxyData>();
for (auto i = 1; i < parts.size(); ++i) {
const auto fields = parts[i].split('@');
const auto address = (fields.size() > 1) ? fields[1].split(':') : QStringList();
if (address.size() != 2) {
continue;
}
auto entry = MTP::ProxyData();
entry.host = address[0];
entry.port = address[1].toUInt();
const auto kind = fields[0];
if (kind == QStringLiteral("naive")) {
entry.type = MTP::ProxyData::Type::Naive;
} else if (kind == QStringLiteral("faketls") || kind == QStringLiteral("mtproto")) {
entry.type = MTP::ProxyData::Type::Mtproto;
auto key = QByteArray();
for (auto b = 0; b != 16; ++b) {
key.push_back(char(QRandomGenerator::global()->generate() & 0xff));
}
auto secret = key.toHex();
if (kind == QStringLiteral("faketls") && fields.size() > 2) {
secret = QByteArray("ee") + secret + fields[2].toUtf8().toHex();
}
entry.password = QString::fromLatin1(secret);
} else {
continue;
}
list.push_back(std::move(entry));
}
if (!list.empty()) {
auto &proxies = Core::App().settings().proxy();
proxies.setList(list);
proxies.setSelected(list.front());
proxies.setSettings(MTP::ProxyData::Settings::Enabled);
}
QTimer::singleShot(4000, [=] {
Start(options, nullptr, [](QString path) {
LOG(("PathTest self-test: %1").arg(path.isEmpty() ? QStringLiteral("failed") : QStringLiteral("done")));
QTimer::singleShot(1000, [] { Core::Quit(); });
});
});
}
} // namespace Zsg::PathTest