Feature: Add on-demand TLS transport with hot-switch to the Android client

Reuse the Linux OpenSSL TlsChannel implementation (platform guard widened
to __linux__); the trust anchor lives in the app-private filesDir, injected
via TlsSetAnchorDir in nativeInit before the connection thread starts.
COMMAND_TLS_ENABLE/DISABLE save/remove the anchor, hot-reload and reconnect
only when the transport actually changes, so the master menu takes effect
within seconds without restarting the app. Login reports RES_TLS, refreshed
before each re-login. The reconnect flag is consumed before the drop check
and cleared before reconnecting so a switch racing a disconnect cannot
cause an extra reconnect/login cycle.

Cross-compile OpenSSL 3.5.0 per ABI with build_openssl_android.sh (NDK
clang + MSYS2 perl/make), integrated into build_android_libs.ps1
(-OpenSslOnly). Static libs and per-ABI headers are tracked like the
existing libzstd/libsign prebuilts; --exclude-libs keeps OpenSSL symbols
private to libyama.so, isolated from the Java-layer Conscrypt.

Co-Authored-By: Qoder <noreply@qoder.com>
This commit is contained in:
yuanyuanxiangandQoder committed 2026-11-11 11:56:32 +01:00
1 parent 36618b0ad0
commit 51747dc0ea
586 files changed
+183905 -35

No files matched your search

+119 -2
View File
@@ -5,6 +5,7 @@
#include <atomic>
#include <mutex>
#include <set>
#include <vector>
#include <string>
#include <cstring>
#include <cinttypes>
@@ -199,6 +200,12 @@ static std::atomic<uint64_t> g_lastHeartbeatAckMs{0};
// 只在 ConnectionThread 里赋值/置空,其他线程只读。
static IOCPClient* g_pMainClient = nullptr;
#ifdef YAMA_TLS_CHANNEL
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)置位,心跳线程检测到后断开重连。
// DataProcess(接收线程)写、心跳线程读,用 atomic。与 Linux 端 g_needReconnect 同套路。
static std::atomic<bool> g_needReconnect{false};
#endif
// ---- JNI 反向调用(DataProcess → ControlService / CaptureService)----
static JavaVM* g_jvm = nullptr;
static jclass g_ctrlClass = nullptr;
@@ -564,6 +571,53 @@ static void ApplyUpdateApk(const PBYTE szBuffer, ULONG ulLength)
CallCaptureStaticString(g_updateReceivedMid, path.c_str());
}
#ifdef YAMA_TLS_CHANNEL
// 信任锚已落盘/已删除:热重载 TLS 状态,仅在传输方式真正变化(明文↔TLS)时请求重连。
// 仅换证书(仍是 TLS)不打断现有会话,新锚从下一条新连接生效。与 Linux 端同一套路。
static void ApplyTlsAnchorChange()
{
bool before = TlsEnabled();
std::string err;
if (!TlsReload(err)) {
LOGI("TLS reload failed: %s (keeping current transport)", err.c_str());
return;
}
bool after = TlsEnabled();
if (before == after) {
LOGI("TLS trust anchor updated, transport unchanged (%s)", after ? "TLS" : "plaintext");
return;
}
g_needReconnect.store(true, std::memory_order_release);
LOGI("TLS transport switched to %s, reconnecting", after ? "TLS" : "plaintext");
}
// 登录 szReserved[19](RES_TLS)是当前传输状态快照,服务端在线列表 TLS 列取它。热切换后
// 重连会重新登录,登录前刷新该字段,否则列里一直显示旧值。只在主线程调用(同 SendLoginInfo)。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) { fields.push_back(s.substr(pos)); break; }
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i) joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
}
#endif // YAMA_TLS_CHANNEL
// ------------------------------------------------------------------ DataProcess
int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
{
@@ -664,6 +718,37 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
LOGI("COMMAND_SYSTEM (not implemented)");
break;
#ifdef YAMA_TLS_CHANNEL
case COMMAND_TLS_ENABLE: {
// 载荷与 Windows/Linux 一致:szBuffer+1 起为服务端证书 PEM 正文。落盘到 filesDir
// 后热重载并重连,立即切换(无需重启 App)。
if (ulLength > 1) {
std::string pem((const char*)szBuffer + 1, ulLength - 1);
std::string err;
if (TlsTrustAnchorSave(pem, err)) {
LOGI("TLS trust anchor received and saved");
ApplyTlsAnchorChange();
} else {
LOGI("TLS trust anchor save failed: %s", err.c_str());
}
} else {
LOGI("COMMAND_TLS_ENABLE without certificate payload, ignored");
}
break;
}
case COMMAND_TLS_DISABLE: {
// 撤销信任锚:删除文件并热重载,当前连接若是 TLS 就重连回明文。
std::string err;
if (TlsTrustAnchorRemove(err)) {
LOGI("TLS trust anchor removed");
ApplyTlsAnchorChange();
} else {
LOGI("TLS trust anchor removal: %s", err.c_str());
}
break;
}
#endif
default:
LOGI("cmd: unhandled cmd=%d len=%lu", (int)szBuffer[0], (unsigned long)ulLength);
break;
@@ -718,7 +803,11 @@ static void ConnectionThread()
logInfo.AddReserved(std::to_string(g_myClientID).c_str());
logInfo.AddReserved((int)getpid()); // PID
logInfo.AddReserved(FormatFileSize(GetFileSize(g_apkPath)).c_str()); // 文件大小
logInfo.AddReserved(0); // [19] RES_TLS(Android 无 TLS 通道)
#ifdef YAMA_TLS_CHANNEL
logInfo.AddReserved(TlsEnabled() ? 1 : 0); // [19] RES_TLS(有信任锚即 1)
#else
logInfo.AddReserved(0); // [19] RES_TLS(无 TLS 通道)
#endif
logInfo.AddReserved((int)std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - g_processStartMono).count()); // [20] RES_UPTIME
@@ -729,7 +818,8 @@ static void ConnectionThread()
client->setManagerCallBack(nullptr, DataProcess, nullptr);
g_pMainClient = client.get(); // 升级失败回报用;线程退出前置空
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 没有 TLS 通道,WSS 会 fail-closed。
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 现已有 TLS 通道(OpenSSL),WSS
// 在有信任锚时正常握手,无锚时按明文 WS 回退、待服务端下发后升级(见 IOCPClient)。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
int g_connAttempt = 0;
@@ -755,6 +845,9 @@ static void ConnectionThread()
strncpy(logInfo.szPCName, pcName.c_str(), sizeof(logInfo.szPCName) - 1);
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
}
#ifdef YAMA_TLS_CHANNEL
RefreshLoginTls(logInfo); // 传输方式可能已热切换,登录前刷新 RES_TLS
#endif
client->SendLoginInfo(logInfo.Speed(clock() - c));
g_lastHeartbeatAckMs.store(GetUnixMs(), std::memory_order_relaxed);
LOGI("Connected & login sent");
@@ -764,6 +857,9 @@ static void ConnectionThread()
{
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
for (int i = 0; i < interval; ++i) {
#ifdef YAMA_TLS_CHANNEL
if (g_needReconnect.load(std::memory_order_acquire)) break;
#endif
if (!client->IsRunning() || !client->IsConnected()
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) {
char dbg[96];
@@ -775,6 +871,16 @@ static void ConnectionThread()
}
Sleep(1000);
}
#ifdef YAMA_TLS_CHANNEL
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE):断开后由外层循环用新传输方式重连。
// 先消费标志再判掉线(与 Linux 同序):否则「切换命令撞上掉线」走掉线分支时标志
// 漏消费,重连登录后第一圈心跳立刻再断一次,多一轮无谓重连/登录。
if (g_needReconnect.exchange(false, std::memory_order_acq_rel)) {
PostStatus("TLS transport changed, reconnecting");
client->Disconnect();
break;
}
#endif
if (!client->IsRunning() || !client->IsConnected()
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) break;
@@ -812,6 +918,12 @@ static void ConnectionThread()
}
}
PostStatus("disconnected, retry...");
#ifdef YAMA_TLS_CHANNEL
// 兜底清零:内层 while 条件自身也可能在标志置位后退出(心跳发送期间掉线),那条
// 路径不经过上面的 exchange。重连本就按新传输方式走(TlsReload 收命令时已生效),
// 标志无需跨重连保留。
g_needReconnect.store(false, std::memory_order_release);
#endif
// Give server 2 s to remove old context from HostList; without this
// the immediate reconnect hits "already exists" and server skips SendMasterSettings.
std::this_thread::sleep_for(std::chrono::seconds(2));
@@ -876,6 +988,11 @@ Java_com_yama_client_YamaBridge_nativeInit(
g_versionCode = (int)versionCode;
LoadGroupName(); // 若文件存在则覆盖 g_SETTINGS.szGroupName(优先级高于编译时 patch)
#ifdef YAMA_TLS_CHANNEL
// 信任锚目录注入 App 私有 filesDir,必须在连接线程首次 TlsEnabled() 之前。
if (!g_filesDir.empty()) TlsSetAnchorDir(g_filesDir);
#endif
// 缓存 JVM 和 Class/Method 引用。必须在 Java 线程(nativeInit 调用栈)
// 里做 FindClass,否则 AttachCurrentThread 的后台线程只有系统 ClassLoader,
// 找不到 App 类,GetStaticMethodID 拿到 null 导致后续调用崩溃。