All checks were successful
Desktop source guards / guards (push) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
423 lines
13 KiB
C++
423 lines
13 KiB
C++
/*
|
|
ZaStoGram "Check connection" module: see pathtest_probe.h.
|
|
*/
|
|
#include "zsg_pathtest/pathtest_probe.h"
|
|
|
|
#include "mtproto/proxy/wss/socket.h"
|
|
#include "zsg_naive/zsg_naive_api.h"
|
|
#include "zsg_pathtest/pathtest_core.h"
|
|
|
|
#include <QtCore/QElapsedTimer>
|
|
#include <QtNetwork/QNetworkProxy>
|
|
#include <QtNetwork/QSslSocket>
|
|
#include <QtNetwork/QTcpSocket>
|
|
|
|
#include <algorithm>
|
|
#include <functional>
|
|
|
|
namespace Zsg::PathTest {
|
|
namespace {
|
|
|
|
// Any Telegram DC address will do: a probe never gets as far as the tunnel target.
|
|
constexpr auto kProbeDcAddress = "149.154.167.51";
|
|
// Throw-away credentials: a healthy Naive server answers them with a refusal, which proves its TLS is up.
|
|
constexpr auto kProbeUser = "zsg-pathtest";
|
|
constexpr auto kProbePassword = "zsg-pathtest";
|
|
|
|
[[nodiscard]] std::string ConnectToken(QAbstractSocket::SocketError error) {
|
|
switch (error) {
|
|
case QAbstractSocket::ConnectionRefusedError: return "refused";
|
|
case QAbstractSocket::SocketTimeoutError: return "tcp_timeout";
|
|
case QAbstractSocket::HostNotFoundError: return "no_address";
|
|
case QAbstractSocket::NetworkError: return "unreachable";
|
|
default: return "connect_error";
|
|
}
|
|
}
|
|
|
|
// What the real library does with the bytes; the driver only moves them.
|
|
struct Hooks {
|
|
std::function<size_t(uint8_t*, size_t)> take; // library -> network
|
|
std::function<void(const uint8_t*, size_t)> feed; // network -> library
|
|
std::function<bool()> tlsReady;
|
|
// Called every round after the bytes moved; true when the application layer answered or failed.
|
|
std::function<bool(ProbeResult&)> finished;
|
|
// Called when the library failed or closed before the application answered; fills app/detail.
|
|
std::function<void(ProbeResult&)> describeFailure;
|
|
};
|
|
|
|
[[nodiscard]] ProbeResult Drive(
|
|
const QString &address,
|
|
int port,
|
|
int timeoutMs,
|
|
int afterTlsMs,
|
|
const Hooks &hooks) {
|
|
auto result = ProbeResult();
|
|
auto total = QElapsedTimer();
|
|
total.start();
|
|
auto tcp = QTcpSocket();
|
|
tcp.setProxy(QNetworkProxy::NoProxy); // the probe dials the host itself, never through the app's proxy
|
|
tcp.connectToHost(address, quint16(port));
|
|
if (!tcp.waitForConnected(timeoutMs)) {
|
|
result.cls = kConnectFailed;
|
|
result.detail = ConnectToken(tcp.error());
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
result.tcpMs = total.elapsed();
|
|
auto sinceTcp = QElapsedTimer();
|
|
sinceTcp.start();
|
|
auto firstSeen = false;
|
|
auto tlsDone = false;
|
|
auto tlsAt = qint64(0);
|
|
const auto pump = [&] {
|
|
uint8_t chunk[16 * 1024];
|
|
auto taken = size_t(0);
|
|
while ((taken = hooks.take(chunk, sizeof(chunk))) > 0) {
|
|
tcp.write(reinterpret_cast<const char*>(chunk), qint64(taken));
|
|
}
|
|
tcp.waitForBytesWritten(200);
|
|
};
|
|
pump();
|
|
while (true) {
|
|
auto limit = qint64(timeoutMs);
|
|
if (tlsDone) {
|
|
limit = std::min(limit, tlsAt + qint64(afterTlsMs));
|
|
}
|
|
const auto elapsed = total.elapsed();
|
|
if (elapsed >= limit) {
|
|
break;
|
|
}
|
|
const auto wait = int(std::min<qint64>(limit - elapsed, 50));
|
|
const auto readable = (tcp.bytesAvailable() > 0)
|
|
|| tcp.waitForReadyRead(wait);
|
|
if (readable && tcp.bytesAvailable() > 0) {
|
|
if (!firstSeen) {
|
|
// Look at the first bytes BEFORE the library reads them; peek leaves them for it.
|
|
const auto head = tcp.peek(6);
|
|
firstSeen = !head.isEmpty();
|
|
result.ttfbMs = sinceTcp.elapsed();
|
|
result.cls = ClassifyFirstBytes(head);
|
|
if (result.cls != kServerHello) {
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
}
|
|
const auto data = tcp.readAll();
|
|
hooks.feed(
|
|
reinterpret_cast<const uint8_t*>(data.constData()),
|
|
size_t(data.size()));
|
|
pump();
|
|
} else if (tcp.state() != QAbstractSocket::ConnectedState) {
|
|
// The peer closed with nothing more to read. Qt reports a FIN and a reset alike (RemoteHostClosedError),
|
|
// so a reset is only told apart when the error text says so.
|
|
if (!firstSeen) {
|
|
const auto reset = tcp.errorString().contains(QStringLiteral("reset"), Qt::CaseInsensitive);
|
|
result.cls = reset ? kRst : kFin;
|
|
result.ttfbMs = sinceTcp.elapsed();
|
|
result.detail = "peer_closed";
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
hooks.describeFailure(result);
|
|
if (result.detail.empty()) {
|
|
result.detail = "peer_closed";
|
|
}
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
if (!tlsDone && hooks.tlsReady()) {
|
|
tlsDone = true;
|
|
tlsAt = total.elapsed();
|
|
if (!firstSeen) {
|
|
firstSeen = true;
|
|
result.cls = kServerHello;
|
|
result.ttfbMs = sinceTcp.elapsed();
|
|
}
|
|
}
|
|
if (hooks.finished(result)) {
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
}
|
|
if (!firstSeen) {
|
|
result.cls = kSilent;
|
|
result.detail = "no_answer";
|
|
} else if (tlsDone && result.app.empty()) {
|
|
result.app = "timeout";
|
|
}
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
const char *ClassifyFirstBytes(const QByteArray &head) {
|
|
if (head.isEmpty()) {
|
|
return kOther;
|
|
}
|
|
const auto type = uint8_t(head[0]);
|
|
// A TLS record starts with its type and the legacy version 0x03 0x0x.
|
|
const auto tlsVersion = (head.size() < 2) || (uint8_t(head[1]) == 0x03);
|
|
if (type == 0x16 && tlsVersion) {
|
|
return kServerHello;
|
|
} else if (type == 0x15 && tlsVersion) {
|
|
return kAlert;
|
|
}
|
|
return kOther;
|
|
}
|
|
|
|
std::string Token(const QString &text) {
|
|
auto out = std::string();
|
|
for (const auto ch : text.toLower().toLatin1()) {
|
|
auto c = ch;
|
|
const auto 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;
|
|
}
|
|
|
|
ProbeResult ProbeWss(
|
|
const MTP::details::WssRoute &route,
|
|
const QString &address,
|
|
int port,
|
|
int timeoutMs,
|
|
int afterTlsMs) {
|
|
auto loadError = QString();
|
|
const auto api = Zsg::Naive::LoadApi(&loadError);
|
|
if (!api) {
|
|
auto result = ProbeResult();
|
|
result.cls = kOther;
|
|
result.detail = "zsgnaive_missing";
|
|
return result;
|
|
}
|
|
// The very config the real WssSocket builds.
|
|
const auto config = MTP::details::WssClientConfig(route);
|
|
char error[256] = {};
|
|
const auto client = api->wsNew(&config.config(), error, sizeof(error));
|
|
if (!client) {
|
|
auto result = ProbeResult();
|
|
result.cls = kOther;
|
|
result.detail = "client_create_failed";
|
|
return result;
|
|
}
|
|
auto hooks = Hooks();
|
|
hooks.take = [&](uint8_t *buffer, size_t size) {
|
|
return api->wsTakeNetwork(client, buffer, size);
|
|
};
|
|
hooks.feed = [&](const uint8_t *data, size_t size) {
|
|
api->wsFeedNetwork(client, data, size);
|
|
};
|
|
hooks.tlsReady = [&] {
|
|
return api->wsState(client) >= Zsg::Naive::WsUpgrading;
|
|
};
|
|
hooks.describeFailure = [&](ProbeResult &result) {
|
|
result.detail = Token(QString::fromLatin1(api->wsError(client)));
|
|
};
|
|
hooks.finished = [&](ProbeResult &result) {
|
|
const auto state = api->wsState(client);
|
|
if (state == Zsg::Naive::WsOpen) {
|
|
result.app = "upgrade_ok";
|
|
return true;
|
|
} else if (state == Zsg::Naive::WsRefused) {
|
|
result.app = "upgrade_refused";
|
|
result.detail = "status=" + std::to_string(api->wsUpgradeStatus(client));
|
|
return true;
|
|
} else if (state == Zsg::Naive::WsFailed
|
|
|| state == Zsg::Naive::WsClosed) {
|
|
hooks.describeFailure(result);
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
auto result = Drive(address, port, timeoutMs, afterTlsMs, hooks);
|
|
api->wsFree(client);
|
|
return result;
|
|
}
|
|
|
|
ProbeResult ProbeNaive(
|
|
const QString &host,
|
|
int port,
|
|
const QString &address,
|
|
int timeoutMs,
|
|
int afterTlsMs) {
|
|
auto loadError = QString();
|
|
const auto api = Zsg::Naive::LoadApi(&loadError);
|
|
if (!api) {
|
|
auto result = ProbeResult();
|
|
result.cls = kOther;
|
|
result.detail = "zsgnaive_missing";
|
|
return result;
|
|
}
|
|
// The very config the real SharedConnection builds, with throw-away credentials.
|
|
const auto config = Zsg::Naive::NaiveClientConfig(
|
|
host,
|
|
port,
|
|
QString::fromLatin1(kProbeUser),
|
|
QString::fromLatin1(kProbePassword));
|
|
char error[256] = {};
|
|
const auto client = api->naiveNew(&config.config(), error, sizeof(error));
|
|
if (!client) {
|
|
auto result = ProbeResult();
|
|
result.cls = kOther;
|
|
result.detail = "client_create_failed";
|
|
return result;
|
|
}
|
|
const auto tunnel = api->naiveOpenTunnel(client, kProbeDcAddress, 443);
|
|
auto hooks = Hooks();
|
|
hooks.take = [&](uint8_t *buffer, size_t size) {
|
|
return api->naiveTakeNetwork(client, buffer, size);
|
|
};
|
|
hooks.feed = [&](const uint8_t *data, size_t size) {
|
|
api->naiveFeedNetwork(client, data, size);
|
|
};
|
|
hooks.tlsReady = [&] {
|
|
return api->naiveState(client) >= Zsg::Naive::NaivePreamble;
|
|
};
|
|
hooks.describeFailure = [&](ProbeResult &result) {
|
|
result.detail = Token(QString::fromLatin1(api->naiveError(client)));
|
|
};
|
|
hooks.finished = [&](ProbeResult &result) {
|
|
const auto state = api->naiveState(client);
|
|
if (state == Zsg::Naive::NaiveFailed
|
|
|| state == Zsg::Naive::NaiveClosed) {
|
|
hooks.describeFailure(result);
|
|
return true;
|
|
}
|
|
if (!tunnel) {
|
|
result.detail = "open_tunnel_failed";
|
|
return true;
|
|
}
|
|
const auto tunnelState = api->naiveTunnelState(client, tunnel);
|
|
if (tunnelState == Zsg::Naive::TunnelOpen) {
|
|
result.app = "tunnel_open";
|
|
return true;
|
|
} else if (tunnelState == Zsg::Naive::TunnelFailed) {
|
|
result.app = "tunnel_refused";
|
|
result.detail = "status="
|
|
+ std::to_string(api->naiveTunnelHttpStatus(client, tunnel));
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
auto result = Drive(address, port, timeoutMs, afterTlsMs, hooks);
|
|
api->naiveFree(client);
|
|
return result;
|
|
}
|
|
|
|
ProbeResult ProbeTcp(
|
|
const QString &address,
|
|
int port,
|
|
int timeoutMs) {
|
|
auto result = ProbeResult();
|
|
auto total = QElapsedTimer();
|
|
total.start();
|
|
auto tcp = QTcpSocket();
|
|
tcp.setProxy(QNetworkProxy::NoProxy); // the probe dials the host itself, never through the app's proxy
|
|
tcp.connectToHost(address, quint16(port));
|
|
if (tcp.waitForConnected(timeoutMs)) {
|
|
result.cls = kOk;
|
|
result.tcpMs = total.elapsed();
|
|
} else {
|
|
result.cls = kConnectFailed;
|
|
result.detail = ConnectToken(tcp.error());
|
|
}
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
|
|
ProbeResult ProbeRawHello(
|
|
const QString &address,
|
|
int port,
|
|
const QByteArray &hello,
|
|
int timeoutMs) {
|
|
auto result = ProbeResult();
|
|
auto total = QElapsedTimer();
|
|
total.start();
|
|
auto tcp = QTcpSocket();
|
|
tcp.setProxy(QNetworkProxy::NoProxy); // the probe dials the host itself, never through the app's proxy
|
|
tcp.connectToHost(address, quint16(port));
|
|
if (!tcp.waitForConnected(timeoutMs)) {
|
|
result.cls = kConnectFailed;
|
|
result.detail = ConnectToken(tcp.error());
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
result.tcpMs = total.elapsed();
|
|
auto sinceTcp = QElapsedTimer();
|
|
sinceTcp.start();
|
|
tcp.write(hello);
|
|
tcp.waitForBytesWritten(1000);
|
|
while (total.elapsed() < timeoutMs) {
|
|
const auto wait = int(std::min<qint64>(timeoutMs - total.elapsed(), 50));
|
|
if (tcp.bytesAvailable() > 0 || tcp.waitForReadyRead(wait)) {
|
|
if (tcp.bytesAvailable() > 0) {
|
|
result.cls = ClassifyFirstBytes(tcp.peek(6));
|
|
result.ttfbMs = sinceTcp.elapsed();
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
}
|
|
if (tcp.state() != QAbstractSocket::ConnectedState) {
|
|
const auto reset = tcp.errorString().contains(QStringLiteral("reset"), Qt::CaseInsensitive);
|
|
result.cls = reset ? kRst : kFin;
|
|
result.ttfbMs = sinceTcp.elapsed();
|
|
result.detail = "peer_closed";
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
}
|
|
result.cls = kSilent;
|
|
result.detail = "no_answer";
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
|
|
ProbeResult ProbePlatformTls(
|
|
const QString &address,
|
|
int port,
|
|
const QString &sni,
|
|
int timeoutMs) {
|
|
auto result = ProbeResult();
|
|
auto total = QElapsedTimer();
|
|
total.start();
|
|
auto socket = QSslSocket();
|
|
socket.setProxy(QNetworkProxy::NoProxy);
|
|
// Only whether the server answers TLS matters here, not whether its certificate is one we trust.
|
|
socket.setPeerVerifyMode(QSslSocket::VerifyNone);
|
|
socket.connectToHostEncrypted(address, quint16(port), sni);
|
|
if (socket.waitForEncrypted(timeoutMs)) {
|
|
result.cls = kOk;
|
|
result.ttfbMs = total.elapsed();
|
|
} else if (socket.state() == QAbstractSocket::ConnectedState) {
|
|
// TCP is up and TLS never completed within the time: the server is silent to this stack too.
|
|
result.cls = kSilent;
|
|
result.detail = "no_answer";
|
|
} else if (socket.error() == QAbstractSocket::RemoteHostClosedError) {
|
|
result.cls = kFin;
|
|
result.detail = "peer_closed";
|
|
} else if (socket.error() == QAbstractSocket::SslHandshakeFailedError) {
|
|
result.cls = kAlert;
|
|
result.detail = "tls_handshake_failed";
|
|
} else {
|
|
result.cls = kConnectFailed;
|
|
result.detail = ConnectToken(socket.error());
|
|
}
|
|
result.totalMs = total.elapsed();
|
|
return result;
|
|
}
|
|
|
|
} // namespace Zsg::PathTest
|