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

195 lines
7.7 KiB
C++

#include "PathTestJni.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <openssl/rand.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <memory>
#include <string>
#include <vector>
#include "../../mtproxy/MtProxyClientHelloPolicy.h"
#include "../../mtproxy/MtProxyServerFlightParser.h"
#include "../../zsg_naive/NaiveSocket.h"
#include "../FakeTlsClientHello.h"
#include "../wss/WssSocket.h"
#include "PathTestProbe.h"
namespace tgnet {
namespace pathtest {
namespace {
// Attempt kinds (PathTestNative.java).
constexpr int kKindNaive = 1;
constexpr int kKindWssOfficial = 2;
constexpr int kKindFakeTls = 3;
constexpr int kKindControl = 4;
// Any Telegram DC address will do: a probe never gets as far as the tunnel target.
constexpr const char *kProbeDcAddress = "149.154.167.51";
// Credentials the probe sends. They are not the user's: a Naive server answers 407 to them when its TLS is up, which
// is the proof the probe wants.
constexpr const char *kProbeUser = "zsg-pathtest";
constexpr const char *kProbePassword = "zsg-pathtest";
std::string ToString(JNIEnv *env, jstring s) {
if (s == nullptr) {
return std::string();
}
const char *chars = env->GetStringUTFChars(s, nullptr);
std::string result(chars != nullptr ? chars : "");
if (chars != nullptr) {
env->ReleaseStringUTFChars(s, chars);
}
return result;
}
bool FillAddress(const std::string &text, int port, sockaddr_storage *storage, socklen_t *length) {
memset(storage, 0, sizeof(*storage));
auto *v4 = reinterpret_cast<sockaddr_in *>(storage);
if (inet_pton(AF_INET, text.c_str(), &v4->sin_addr) == 1) {
v4->sin_family = AF_INET;
v4->sin_port = htons(static_cast<uint16_t>(port));
*length = sizeof(sockaddr_in);
return true;
}
auto *v6 = reinterpret_cast<sockaddr_in6 *>(storage);
if (inet_pton(AF_INET6, text.c_str(), &v6->sin6_addr) == 1) {
v6->sin6_family = AF_INET6;
v6->sin6_port = htons(static_cast<uint16_t>(port));
*length = sizeof(sockaddr_in6);
return true;
}
return false;
}
Result Failed(const char *detail) {
Result r;
r.cls = "connect_failed";
r.detail = detail;
return r;
}
Result RunAttempt(int kind, const std::string &address, int port, const std::string &name, int profile, int timeoutMs,
int afterTlsMs) {
sockaddr_storage storage;
socklen_t length = 0;
if (!FillAddress(address, port, &storage, &length)) {
return Failed("bad_address");
}
const sockaddr *sa = reinterpret_cast<const sockaddr *>(&storage);
switch (kind) {
case kKindNaive: {
// The very factory ConnectionSocket calls for a Naive proxy entry, with throw-away credentials.
std::unique_ptr<transport::Socket> socket = naive::CreateFor(
name, static_cast<uint16_t>(port), kProbeUser, kProbePassword, kProbeDcAddress, 443);
return ProbeTransport(*socket, sa, length, timeoutMs, afterTlsMs);
}
case kKindWssOfficial: {
// |profile| carries the DC id here. OfficialRoute is the route the client itself would take now.
wss::Route route;
if (!wss::OfficialRoute(profile, false, false, kProbeDcAddress, &route) || route.direct) {
return Failed(route.direct ? "route_direct" : "no_route");
}
wss::Socket socket(route);
socket.setDiagnosticProbe(true);
return ProbeTransport(socket, sa, length, timeoutMs, afterTlsMs);
}
case kKindControl: {
// The same WSS client (Chrome handshake) aimed at a host that answers everywhere; its HTTP upgrade is
// refused, which is fine: TLS being ready is the signal.
wss::Route route;
route.relayHost = name;
route.connectHost = name;
route.relayPort = static_cast<uint16_t>(port);
route.domain = name;
route.path = "/";
wss::Socket socket(route);
socket.setDiagnosticProbe(true);
return ProbeTransport(socket, sa, length, timeoutMs, afterTlsMs);
}
case kKindFakeTls: {
// A random 16-byte key: the user's secret is never read. A real MTProxy answers the wrong digest the way
// it answers any other web client, which is enough to see whether the hello gets an answer at all.
std::string key(16, '\0');
if (RAND_bytes(reinterpret_cast<uint8_t *>(&key[0]), static_cast<int>(key.size())) != 1) {
for (size_t i = 0; i < key.size(); i++) {
key[i] = static_cast<char>(time(nullptr) * 31 + i * 17);
}
}
std::vector<uint8_t> buffer(MT_PROXY_SERVER_FLIGHT_MAX_BYTES + 64);
uint32_t size = 0;
if (!composeFakeTlsClientHello(profile, name, name, key, static_cast<int32_t>(time(nullptr)), buffer.data(),
&size)) {
Result r;
r.cls = "other";
r.detail = "hello_contract_failed";
return r;
}
return ProbeRawHello(sa, length, buffer.data(), size, timeoutMs);
}
default:
return Failed("bad_kind");
}
}
jstring nativeAttempt(JNIEnv *env, jclass, jint kind, jstring address, jint port, jstring name, jint profile,
jint timeoutMs, jint afterTlsMs) {
const Result r = RunAttempt(kind, ToString(env, address), port, ToString(env, name), profile, timeoutMs, afterTlsMs);
return env->NewStringUTF(Encode(r).c_str());
}
// "connect_host|port|domain|kind" of the route the client would take for |dcId| now, or an empty string.
jstring nativeDescribeOfficial(JNIEnv *env, jclass, jint dcId) {
wss::Route route;
if (!wss::OfficialRoute(dcId, false, false, kProbeDcAddress, &route)) {
return env->NewStringUTF("");
}
const char *kind = route.direct ? "direct"
: route.tunnel ? "tunnel"
: route.cdnSlot >= 0 ? (route.plain ? "front_plain" : "front")
: "relay";
const std::string text = route.connectHost + "|" + std::to_string(route.relayPort) + "|" + route.domain + "|" + kind;
return env->NewStringUTF(text.c_str());
}
// "default=3;1:firefox:0,2:android_chrome:1,..." - every FakeTLS profile the client has (the two automatic modes
// are selectors, not hellos) with the client's own name and whether it withholds the profile from the wire.
jstring nativeFakeTlsProfiles(JNIEnv *env, jclass) {
std::string text = "default=" + std::to_string(mtProxyDefaultTlsProfile()) + ";";
bool first = true;
for (int32_t id = MT_PROXY_TLS_PROFILE_FIREFOX; id <= MT_PROXY_TLS_PROFILE_LEGACY_NO_GREASE; id++) {
if (id == MT_PROXY_TLS_PROFILE_AUTO_ROTATE) {
continue;
}
if (!first) {
text += ",";
}
first = false;
text += std::to_string(id) + ":" + Token(fakeTlsProfileName(id)) + ":" + (mtProxyTlsProfileWithheld(id) ? "1" : "0");
}
return env->NewStringUTF(text.c_str());
}
const JNINativeMethod kMethods[] = {
{"native_attempt", "(ILjava/lang/String;ILjava/lang/String;III)Ljava/lang/String;", reinterpret_cast<void *>(nativeAttempt)},
{"native_describeOfficial", "(I)Ljava/lang/String;", reinterpret_cast<void *>(nativeDescribeOfficial)},
{"native_fakeTlsProfiles", "()Ljava/lang/String;", reinterpret_cast<void *>(nativeFakeTlsProfiles)},
};
} // namespace
bool RegisterPathTestJni(JNIEnv *env) {
jclass clazz = env->FindClass("org/telegram/zastogram/pathtest/PathTestNative");
if (clazz == nullptr) {
return false;
}
return env->RegisterNatives(clazz, kMethods, sizeof(kMethods) / sizeof(kMethods[0])) >= 0;
}
} // namespace pathtest
} // namespace tgnet