Fix: Harden the Android client connection lifecycle

Five review findings from the screen-preview work, all in the same
connection plumbing.

The main client handle is now a shared_ptr taken through GetMainClient().
ScreenPreviewThread, ActivityReportThread and sendClientMsg run detached
and can outlive ConnectionThread's teardown, so a raw pointer snapshot
could dereference freed memory; the copy they hold now keeps the client
alive until the send is done. sendClientMsg also uses one handle for
both the connected check and the send instead of reading the global
twice.

The reconnect loop now checks its connection generation in every
condition, so a thread that was asked to stop can no longer reconnect
after a quick nativeStop -> nativeInit reset g_bExit and g_running into
"running again", which produced two main connections with the same
client ID.

ActivityReportThread gets the same try/catch and RAII in-flight counter
as the preview thread: an exception used to call std::terminate, and one
failure left the counter above zero, silently dropping every later
get_activity_history.

nativeStop now stops the activity sampler, and Stop() clears m_started
so a service restart can start it again. Sub-connections (remote screen
and client log) now inherit g_SETTINGS.protoType like the main
connection; without it they silently dialed plain TCP even when WS/WSS
was configured.

Verified on the emulator against a local debug server: get_screenshot,
get_activity_history and get_client_log all still answer, and the log
sub-connection completes the TLS handshake.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-11 20:59:10 +01:00
1 parent f29150d20e
commit ac43ad92ef
2 files changed
+79 -34

No files matched your search

+76 -34
View File
@@ -4,6 +4,7 @@
#include <chrono>
#include <atomic>
#include <mutex>
#include <memory>
#include <set>
#include <vector>
#include <string>
@@ -204,8 +205,23 @@ uint64_t g_myClientID = 0; // sub_conn_thread.h 需要的
static std::atomic<bool> g_running{false};
static std::atomic<uint64_t> g_lastHeartbeatAckMs{0};
// 主连接句柄:COMMAND_UPDATE 失败回报要往主连接发 ClientMsg(与 Linux 端同一套路)。
// 只在 ConnectionThread 里赋值/置空,其他线程只读。
static IOCPClient* g_pMainClient = nullptr;
// 只在 ConnectionThread 里赋值/置空,其他线程通过 GetMainClient() 取一份 shared_ptr
// —— 抓屏/活动上报是 detached 线程,可能跑到 ConnectionThread 收尾之后,裸指针会有
// 悬空窗口,shared_ptr 让它们手里的那份把对象续命到用完为止。
static std::mutex g_mainClientMx;
static std::shared_ptr<IOCPClient> g_pMainClient;
static std::shared_ptr<IOCPClient> GetMainClient()
{
std::lock_guard<std::mutex> lk(g_mainClientMx);
return g_pMainClient;
}
static void SetMainClient(const std::shared_ptr<IOCPClient>& client)
{
std::lock_guard<std::mutex> lk(g_mainClientMx);
g_pMainClient = client;
}
#ifdef YAMA_TLS_CHANNEL
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)置位,心跳线程检测到后断开重连。
@@ -484,6 +500,9 @@ static void ScreenSpyThread()
LOGI("SST[%d]: creating IOCPClient", attempt);
client = std::make_unique<IOCPClient>(g_bExit, true);
client->EnableSubConnAuth(true, g_myClientID);
// 子连接同样要走配置的传输方式:不喂协议会静默按明文 TCP 直连,
// 配成 WS/WSS 时连不上反代(主连接在 ConnectionThread 里已经这么做了)
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
LOGI("SST[%d]: connecting %s:%d", attempt, g_serverIp.c_str(), g_serverPort);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
@@ -550,6 +569,8 @@ static void ClientLogThread()
try {
client = std::make_unique<IOCPClient>(g_bExit, true);
client->EnableSubConnAuth(true, g_myClientID);
// 同上:子连接必须继承配置的传输方式,否则 WS/WSS 部署下 get_client_log 连不上
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
LOGE("ClientLogThread: connect failed (attempt %d/3)", attempt);
Sleep(1000);
@@ -582,27 +603,34 @@ static std::atomic<int> g_activityReportsInFlight(0);
static void ActivityReportThread()
{
const uint64_t lastOk = g_lastActivityProbeOkMs.load(std::memory_order_relaxed);
const bool svcOn = lastOk != 0 && GetUnixMs() - lastOk < 5000; // 采样线程每秒跑一次
std::string text = LinuxActivity::ActivityHistory::Instance().Dump();
if (text.empty()) {
text = svcOn
? std::string(u8"[来源] 前台应用活动:暂无记录(没有停留超过 5 秒的前台应用)\n")
: std::string(u8"[来源] 需要开启无障碍服务(设置 → 无障碍 → YAMA)才能采集前台应用\n");
}
// detached 线程:异常逃出去会 std::terminate 整个客户端;计数也必须无条件还回去,
// 否则之后所有 get_activity_history 都被当成「已有报表在飞」丢掉
struct InFlightGuard {
~InFlightGuard() { g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed); }
} guard;
try {
const uint64_t lastOk = g_lastActivityProbeOkMs.load(std::memory_order_relaxed);
const bool svcOn = lastOk != 0 && GetUnixMs() - lastOk < 5000; // 采样线程每秒跑一次
std::string text = LinuxActivity::ActivityHistory::Instance().Dump();
if (text.empty()) {
text = svcOn
? std::string(u8"[来源] 前台应用活动:暂无记录(没有停留超过 5 秒的前台应用)\n")
: std::string(u8"[来源] 需要开启无障碍服务(设置 → 无障碍 → YAMA)才能采集前台应用\n");
}
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
memcpy(pkt.data() + 1, text.data(), text.size());
// 指针只取一次快照(与 sendClientMsg 同一套路):主连接随时可能被 ConnectionThread
// 收掉,反复解引用全局指针等于多一次悬空窗口
IOCPClient* mc = g_pMainClient;
bool sent = false;
if (mc && mc->IsConnected() && g_bExit == S_CLIENT_NORMAL)
sent = mc->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
LOGI("[Activity] report %zu bytes (%s)%s", text.size(), svcOn ? "foreground" : "no-accessibility",
sent ? "" : " FAILED");
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
memcpy(pkt.data() + 1, text.data(), text.size());
// shared_ptr 副本:ConnectionThread 之后收掉主连接也不会让这次发送悬空
auto mc = GetMainClient();
bool sent = false;
if (mc && mc->IsConnected() && g_bExit == S_CLIENT_NORMAL)
sent = mc->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
LOGI("[Activity] report %zu bytes (%s)%s", text.size(), svcOn ? "foreground" : "no-accessibility",
sent ? "" : " FAILED");
} catch (const std::exception& e) {
LOGE("[Activity] report failed: %s", e.what());
}
}
// ------------------------------------------------------------------ 屏幕预览
@@ -710,8 +738,8 @@ static void ScreenPreviewThread(ScreenPreviewReq req)
memcpy(pkt.data(), &hdr, sizeof(hdr));
if (bytes) memcpy(pkt.data() + sizeof(hdr), jpeg.data(), bytes);
// 与 ActivityReportThread 同一套路:全局指针只取一次快照
IOCPClient* mc = g_pMainClient;
// 与 ActivityReportThread 同一套路:先拿一份 shared_ptr,主连接被收掉也不悬空
auto mc = GetMainClient();
if (mc && mc->IsConnected() && g_bExit == S_CLIENT_NORMAL)
mc->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
LOGI("[Preview] reqId=%u %dx%d %u bytes status=%u", req.reqId, w, h, bytes, status);
@@ -727,7 +755,9 @@ static void ScreenPreviewThread(ScreenPreviewReq req)
// 所以统一截断后 memcpy。
static void sendClientMsg(const char* title, const char* text)
{
if (!g_pMainClient || !g_pMainClient->IsConnected()) return;
// Java 安装线程也会走这里;连接检查与发送必须用同一份句柄,否则中间被收掉就崩
auto mc = GetMainClient();
if (!mc || !mc->IsConnected()) return;
ClientMsg msg;
msg.cmd = TOKEN_CLIENT_MSG;
strncpy(msg.title, title ? title : "YAMA", sizeof(msg.title) - 1);
@@ -736,7 +766,7 @@ static void sendClientMsg(const char* title, const char* text)
if (n > sizeof(msg.text) - 1) n = sizeof(msg.text) - 1;
memcpy(msg.text, text, n);
}
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
mc->Send2Server((char*)&msg, sizeof(msg));
}
static void reportUpdateFailure(const std::string& reason)
@@ -1105,16 +1135,23 @@ static void ConnectionThread(uint64_t gen)
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
LOGI("ClientID=%" PRIu64, g_myClientID);
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, false));
// shared_ptr:抓屏/活动上报/升级回报是 detached 线程,可能拿着句柄跑到本线程收尾之后
std::shared_ptr<IOCPClient> client = std::make_shared<IOCPClient>(g_bExit, false);
client->setManagerCallBack(nullptr, DataProcess, nullptr);
g_pMainClient = client.get(); // 升级失败回报用;线程退出前置空
SetMainClient(client); // 升级失败回报用;线程退出前撤回
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 现已有 TLS 通道(OpenSSL),WSS
// 在有信任锚时正常握手,无锚时按明文 WS 回退、待服务端下发后升级(见 IOCPClient)。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
int g_connAttempt = 0;
while (S_CLIENT_NORMAL == g_bExit && g_running.load()) {
// 每次循环判断都带上代号:nativeStop 后 2 秒内进程被 nativeInit 重新拉起时,
// g_bExit/g_running 会被新一轮重置成「运行中」,旧线程醒来会再连一条主连接
// (同一 ClientID 双登录,且它会覆盖新一轮的主连接句柄)。
auto currentGen = [gen]() {
return gen == g_connGeneration.load(std::memory_order_acquire);
};
while (S_CLIENT_NORMAL == g_bExit && g_running.load() && currentGen()) {
char connMsg[64];
snprintf(connMsg, sizeof(connMsg), "connect #%d → %s:%d",
++g_connAttempt, g_serverIp.c_str(), g_serverPort);
@@ -1148,7 +1185,7 @@ static void ConnectionThread(uint64_t gen)
LOGI("Connected & login sent");
while (client->IsRunning() && client->IsConnected()
&& S_CLIENT_NORMAL == g_bExit && g_running.load())
&& S_CLIENT_NORMAL == g_bExit && g_running.load() && currentGen())
{
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
for (int i = 0; i < interval; ++i) {
@@ -1156,7 +1193,7 @@ static void ConnectionThread(uint64_t gen)
if (g_needReconnect.load(std::memory_order_acquire)) break;
#endif
if (!client->IsRunning() || !client->IsConnected()
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) {
|| g_bExit != S_CLIENT_NORMAL || !g_running.load() || !currentGen()) {
char dbg[96];
snprintf(dbg, sizeof(dbg), "drop@%ds run=%d conn=%d exit=%d run2=%d",
i, (int)client->IsRunning(), (int)client->IsConnected(),
@@ -1177,7 +1214,7 @@ static void ConnectionThread(uint64_t gen)
}
#endif
if (!client->IsRunning() || !client->IsConnected()
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) break;
|| g_bExit != S_CLIENT_NORMAL || !g_running.load() || !currentGen()) break;
if (ClientAuth::IsTimedOut()) {
PostStatus("timeout: masterSettings");
@@ -1226,8 +1263,9 @@ static void ConnectionThread(uint64_t gen)
if (g_connGeneration.load(std::memory_order_acquire) == gen) {
g_running.store(false);
// client 马上析构,别让别的线程拿到悬空指针;只清自己的那一个
if (g_pMainClient == client.get()) g_pMainClient = nullptr;
// 撤回本线程登记的句柄(只清自己那一个)。已经拿到 shared_ptr 副本的线程
// 会把 client 续命到发送结束,不存在悬空。
if (GetMainClient() == client) SetMainClient(nullptr);
}
LOGI("ConnectionThread exit (gen=%" PRIu64 ")", gen);
@@ -1382,6 +1420,10 @@ Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
LOGI("nativeStop");
g_bExit = S_CLIENT_EXIT;
g_running.store(false);
// 采样线程随服务一起停:否则 onDestroy 之后还在每秒查无障碍、记前台应用
// (后台耗电,且「已停止」期间的活动会出现在下次 get_activity_history 里)。
// Stop 之后 Stop 是幂等的,Start 可重新拉起。
LinuxActivity::ActivityHistory::Instance().Stop();
}
// 由 Kotlin 侧(安装流程)回报结果到服务端消息栏,走 TOKEN_CLIENT_MSG