The Android client dropped CMD_QUALITY_LEVEL, CMD_FPS, CMD_QUALITY_PROFILES and CMD_SCREEN_TUNING as log lines, and hardcoded ScreenSettings.QualityLevel to Good. Because the server initializes adaptive quality from the client's reported level, that hardcoded value pinned every Android session to a fixed profile: adaptive quality could never start. ScreenTuning.kt now owns the state in SharedPreferences (level, max fps and the master's six-row profile table), and C++ only parses the wire format. The level is persisted when the master sets it explicitly, including -1 adaptive and -2 disabled, and is reported back in TOKEN_BITMAPINFO on the next screen session. A concrete level switch applies the profile bitrate at runtime via MediaCodec.setParameters(PARAMETER_KEY_VIDEO_BITRATE), which is smooth and needs no encoder rebuild. Frame rate is stored as-is (255 = unlimited, matching Windows) and only reaches KEY_FRAME_RATE at the next capture start, since surface encoders have no runtime fps cap. Ultra and High default to a zero bitrate because their Windows algorithms are DIFF/RGB565, so Android falls back to the previous 4000 kbps. CMD_SCREEN_TUNING stays log-only: all four flags belong to the Windows capture/x264 path and Android does not claim SCREEN_CAP_TUNING_FLAGS. CMD_SCREEN_SIZE is ignored; the server's pending resolution-change mark self-heals after one second. Verified on the emulator: a seeded Level 5 starts capture at 800 kbps/8 fps and the server title shows Minimal; a master-side switch to Good changes the live bitrate to 3000, and a restart picks up fps 30 from CMD_FPS. Co-Authored-By: deepseek-flash
2010 lines
92 KiB
C++
2010 lines
92 KiB
C++
#include <jni.h>
|
||
#include <android/log.h>
|
||
#include <thread>
|
||
#include <chrono>
|
||
#include <atomic>
|
||
#include <mutex>
|
||
#include <memory>
|
||
#include <set>
|
||
#include <vector>
|
||
#include <string>
|
||
#include <cstring>
|
||
#include <cinttypes>
|
||
#include <cstdio>
|
||
#include <unistd.h>
|
||
#include <fcntl.h>
|
||
#include <sys/stat.h>
|
||
#include <sys/select.h>
|
||
#include <sys/socket.h>
|
||
#include <netinet/in.h>
|
||
#include <netdb.h>
|
||
#include <arpa/inet.h>
|
||
|
||
#include "common/commands.h"
|
||
#include "common/client_auth_state.h"
|
||
#include "common/rtt_estimator.h"
|
||
#include "client/IOCPClient.h"
|
||
#include "ScreenHandler.h"
|
||
#include "ChatHandler.h"
|
||
#include "common/PTYHandler.h" // 远程终端(COMMAND_SHELL):与 Linux/macOS 共用 PTY 实现
|
||
#define XXH_INLINE_ALL
|
||
#include "common/xxhash.h"
|
||
#include "common/logger.h"
|
||
#include "common/ClientLogHandler.h"
|
||
// 历史活动:复用 Linux 端的采样机。linux/LinuxActivityHistory.h 里的 ActivityHistory
|
||
// 类与格式化函数都是平台无关的(X11 采样在 linux/main.cpp,不在头文件里),Android
|
||
// 只需注入自己的 probe(JNI 问 ControlService 要前台应用)。
|
||
#include "linux/LinuxActivityHistory.h"
|
||
|
||
#define LOG_TAG "YAMA"
|
||
// LOGI/LOGE 走 android_log_tag(logger.h):既进 logcat,也进 Logger 的内存 ring,
|
||
// 后者是 MCP get_client_log 的数据源。若只写 logcat,主控会拿到一份空日志。
|
||
#define LOGI(...) android_log_tag(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||
#define LOGE(...) android_log_tag(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||
|
||
// 1 = 状态提示显示到电视屏幕;0 = 只写 logcat,不显示到屏幕
|
||
#define SCREEN_STATUS_ENABLED 0
|
||
|
||
extern "C" int signMessage_c(const char* pk, int pkLen, const unsigned char* msg,
|
||
int msgLen, char* buf, int bufSize);
|
||
|
||
// ---- 设备信息 helper(登录时填充,仅调用一次)----
|
||
|
||
static int GetCpuCores() {
|
||
long n = sysconf(_SC_NPROCESSORS_ONLN);
|
||
return (n > 0) ? (int)n : 1;
|
||
}
|
||
|
||
static double GetMemoryGB() {
|
||
FILE* f = fopen("/proc/meminfo", "r");
|
||
if (!f) return 0.0;
|
||
char line[128];
|
||
unsigned long kb = 0;
|
||
while (fgets(line, sizeof(line), f)) {
|
||
if (sscanf(line, "MemTotal: %lu kB", &kb) == 1) break;
|
||
}
|
||
fclose(f);
|
||
return kb / (1024.0 * 1024.0);
|
||
}
|
||
|
||
// 遍历 cpu0-cpu7,取 cpuinfo_max_freq 最大值(大核频率)
|
||
static int GetCpuMHz() {
|
||
// 优先从 sysfs 读取(真机有效)
|
||
unsigned long maxKhz = 0;
|
||
char path[80];
|
||
for (int i = 0; i < 8; i++) {
|
||
snprintf(path, sizeof(path),
|
||
"/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
|
||
FILE* f = fopen(path, "r");
|
||
if (!f) continue;
|
||
unsigned long khz = 0;
|
||
if (fscanf(f, "%lu", &khz) == 1 && khz > maxKhz) maxKhz = khz;
|
||
fclose(f);
|
||
}
|
||
if (maxKhz > 0) return (int)(maxKhz / 1000);
|
||
|
||
// 回退:解析 /proc/cpuinfo 中的 "BogoMIPS"(模拟器可用)
|
||
FILE* f = fopen("/proc/cpuinfo", "r");
|
||
if (!f) return 0;
|
||
char line[128];
|
||
double bogomips = 0;
|
||
while (fgets(line, sizeof(line), f)) {
|
||
if (sscanf(line, "BogoMIPS : %lf", &bogomips) == 1 ||
|
||
sscanf(line, "bogomips : %lf", &bogomips) == 1) break;
|
||
}
|
||
fclose(f);
|
||
return bogomips > 0 ? (int)bogomips : 0;
|
||
}
|
||
|
||
static long GetFileSize(const std::string& path) {
|
||
if (path.empty()) return 0;
|
||
struct stat st;
|
||
return (stat(path.c_str(), &st) == 0) ? (long)st.st_size : 0;
|
||
}
|
||
|
||
static std::string FormatFileSize(long bytes) {
|
||
char buf[32];
|
||
if (bytes >= 1024 * 1024)
|
||
snprintf(buf, sizeof(buf), "%.1fM", bytes / (1024.0 * 1024.0));
|
||
else if (bytes >= 1024)
|
||
snprintf(buf, sizeof(buf), "%.1fK", bytes / 1024.0);
|
||
else
|
||
snprintf(buf, sizeof(buf), "%ldB", bytes);
|
||
return buf;
|
||
}
|
||
|
||
// 从 JSON 字符串中提取字符串字段值
|
||
static std::string JsonGetStr(const std::string& json, const char* key) {
|
||
std::string needle = std::string("\"") + key + "\":";
|
||
auto pos = json.find(needle);
|
||
if (pos == std::string::npos) return "";
|
||
pos += needle.size();
|
||
while (pos < json.size() && json[pos] == ' ') pos++;
|
||
if (pos >= json.size() || json[pos] != '"') return "";
|
||
pos++;
|
||
auto end = json.find('"', pos);
|
||
return (end == std::string::npos) ? "" : json.substr(pos, end - pos);
|
||
}
|
||
|
||
// 查询 ip-api.com,一次请求同时获取公网 IP 和地理位置(与 Windows 客户端同源)
|
||
// 在连接线程中同步调用,超时 3 秒
|
||
struct GeoResult {
|
||
std::string pubIp, location;
|
||
std::atomic<bool> ready{false};
|
||
};
|
||
|
||
static void FetchGeoInfoImpl(std::shared_ptr<GeoResult> out) {
|
||
struct addrinfo hints = {}, *res = nullptr;
|
||
hints.ai_family = AF_INET;
|
||
hints.ai_socktype = SOCK_STREAM;
|
||
if (getaddrinfo("ip-api.com", "80", &hints, &res) != 0 || !res) {
|
||
out->ready.store(true, std::memory_order_release); return;
|
||
}
|
||
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||
if (fd < 0) { freeaddrinfo(res); out->ready.store(true, std::memory_order_release); return; }
|
||
|
||
struct timeval tv = {3, 0};
|
||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
|
||
connect(fd, res->ai_addr, res->ai_addrlen);
|
||
fd_set wfds; FD_ZERO(&wfds); FD_SET(fd, &wfds);
|
||
bool connected = (select(fd + 1, nullptr, &wfds, nullptr, &tv) == 1);
|
||
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
|
||
|
||
if (connected) {
|
||
const char* req = "GET /json/?fields=status,query,country,city HTTP/1.0\r\n"
|
||
"Host: ip-api.com\r\n"
|
||
"Connection: close\r\n\r\n";
|
||
send(fd, req, strlen(req), 0);
|
||
|
||
std::string resp;
|
||
char buf[512];
|
||
ssize_t n;
|
||
while ((n = recv(fd, buf, sizeof(buf), 0)) > 0) resp.append(buf, (size_t)n);
|
||
|
||
auto sep = resp.find("\r\n\r\n");
|
||
if (sep != std::string::npos) {
|
||
const std::string body = resp.substr(sep + 4);
|
||
if (JsonGetStr(body, "status") == "success") {
|
||
out->pubIp = JsonGetStr(body, "query");
|
||
std::string city = JsonGetStr(body, "city");
|
||
std::string country = JsonGetStr(body, "country");
|
||
if (!city.empty() && !country.empty()) out->location = city + ", " + country;
|
||
else if (!country.empty()) out->location = country;
|
||
else if (!city.empty()) out->location = city;
|
||
}
|
||
}
|
||
}
|
||
close(fd);
|
||
freeaddrinfo(res);
|
||
out->ready.store(true, std::memory_order_release);
|
||
}
|
||
|
||
// getaddrinfo 在某些设备上会永久阻塞,用独立线程 + 5 秒轮询超时保护 ConnectionThread
|
||
static bool FetchGeoInfo(std::string& pubIp, std::string& location) {
|
||
pubIp.clear(); location.clear();
|
||
auto result = std::make_shared<GeoResult>();
|
||
std::thread(FetchGeoInfoImpl, result).detach();
|
||
for (int i = 0; i < 50 && !result->ready.load(std::memory_order_acquire); i++)
|
||
usleep(100000); // 100ms × 50 = 5 秒
|
||
if (!result->ready.load(std::memory_order_acquire)) return false;
|
||
pubIp = result->pubIp;
|
||
location = result->location;
|
||
return !pubIp.empty();
|
||
}
|
||
|
||
// 服务端通过 FLAG_GHOST("Hello, World!")定位此变量,patch szServerIP/szPort 后重签 APK
|
||
// 偏移:szServerIP at +32, szPort at +132(见 commands.h CONNECT_ADDRESS 定义)
|
||
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_ANDROID };
|
||
|
||
// ---- 全局状态 ----
|
||
// CPP-06: g_bExit 是全局变量,跨调用边界不会被编译器缓存进寄存器;
|
||
// IOCPClient 构造接受 const State& 持有引用,不能改为 atomic/volatile,
|
||
// 直接用 State;ARM 4 字节对齐写入硬件层面原子,实际安全。
|
||
State g_bExit{S_CLIENT_NORMAL};
|
||
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 里赋值/置空,其他线程通过 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)置位,心跳线程检测到后断开重连。
|
||
// 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;
|
||
static jmethodID g_ctrlMethod = nullptr;
|
||
static jmethodID g_getActiveWindowMid = nullptr;
|
||
static jmethodID g_activityTitleMid = nullptr; // ControlService.currentActivityTitle()
|
||
static jmethodID g_lockScreenMid = nullptr; // ControlService.lockScreen()V — COMMAND_SCREEN_CTRL_ALT_DEL
|
||
static jmethodID g_canLockMid = nullptr; // ControlService.canLockScreen()Z — 登录前能力探测
|
||
static jmethodID g_overlayMid = nullptr; // ControlService.setPrivacyOverlay(ZZ)V — 黑屏 / 锁键鼠
|
||
static jmethodID g_canOverlayMid = nullptr; // ControlService.canOverlay()Z — 登录前能力探测
|
||
// CaptureService.requestIdr() / forceFirstFrame() — ScreenSpyThread 子连接建立后触发
|
||
static jclass g_captureClass = nullptr;
|
||
static jmethodID g_requestIdrMid = nullptr;
|
||
static jmethodID g_forceFirstFrameMid = nullptr;
|
||
static jmethodID g_statusMid = nullptr; // CaptureService.onNativeStatus(String)
|
||
static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务
|
||
static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘
|
||
static jmethodID g_clipboardMid = nullptr; // CaptureService.onClipboardText([B)V — 远程剪贴板
|
||
static jmethodID g_uninstallMid = nullptr; // CaptureService.onUninstallRequested()V — TOKEN_UNINSTALL
|
||
// ScreenTuning(远程桌面画质/帧率协商:CMD_QUALITY_LEVEL / CMD_FPS / CMD_QUALITY_PROFILES)
|
||
static jclass g_tuningClass = nullptr;
|
||
static jmethodID g_getQualityLevelMid = nullptr; // ScreenTuning.getQualityLevel()I — 上报 ScreenSettings
|
||
static jmethodID g_getMaxFpsMid = nullptr; // ScreenTuning.getMaxFps()I
|
||
static jmethodID g_onQualityLevelMid = nullptr; // ScreenTuning.onQualityLevel(IZ)V
|
||
static jmethodID g_onFpsMid = nullptr; // ScreenTuning.onFps(I)V
|
||
static jmethodID g_onQualityProfilesMid = nullptr; // ScreenTuning.onQualityProfiles(String)V
|
||
// ChatSession(远程交谈界面:帧入站文本、发送按钮)
|
||
static jclass g_chatClass = nullptr;
|
||
static jmethodID g_chatEventMid = nullptr; // ChatSession.onNativeEvent(I[B)V
|
||
// ScreenShot(无障碍 takeScreenshot 抓屏,MCP get_screenshot 用)
|
||
static jclass g_shotClass = nullptr;
|
||
static jmethodID g_shotCanMid = nullptr; // ScreenShot.canCapture()Z
|
||
static jmethodID g_shotCaptureMid = nullptr; // ScreenShot.capture(II)Lcom/yama/client/ScreenShot$Shot;
|
||
static jmethodID g_shotDataMid = nullptr; // Shot.getData()[B
|
||
static jmethodID g_shotWidthMid = nullptr; // Shot.getWidth()I
|
||
static jmethodID g_shotHeightMid = nullptr; // Shot.getHeight()I
|
||
|
||
// 心跳日志限流:每 60 秒最多打一次
|
||
static std::atomic<uint64_t> g_lastHbLogMs{0};
|
||
|
||
static constexpr uint64_t HB_LOG_INTERVAL_MS = 60000;
|
||
|
||
// 供主连接和子连接共同调用:把 COMMAND_SCREEN_CONTROL 路由到 ControlService.onControlEvent()
|
||
// 定义在全局函数区;ScreenHandler.h 通过 extern 声明使用。
|
||
void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY)
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_ctrlMethod) {
|
||
LOGE("SCREEN_CONTROL: JNI not ready (ctrl=%p method=%p)", g_ctrlClass, g_ctrlMethod);
|
||
return;
|
||
}
|
||
if (msgVal != 0x200u)
|
||
LOGI("SCREEN_CONTROL: msg=0x%X pt=(%d,%d)", msgVal, ptX, ptY);
|
||
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
// CPP-03 fix: 检查 AttachCurrentThread 返回值,失败时 jenv 仍为 null
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jenv->CallStaticVoidMethod(g_ctrlClass, g_ctrlMethod,
|
||
(jint)msgVal, (jlong)wParam, (jint)ptX, (jint)ptY);
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 远程剪贴板:服务端下发 [COMMAND_SCREEN_SET_CLIPBOARD][GBK text],字节原样交给
|
||
// CaptureService.onClipboardText(Kotlin 侧按 GBK 解码后写系统剪贴板)。
|
||
// 与 DispatchControlEvent 同一套 attach/detach 套路,供屏幕子连接 OnReceive 调用。
|
||
void DispatchClipboardText(const uint8_t* data, size_t size)
|
||
{
|
||
if (!g_jvm || !g_captureClass || !g_clipboardMid) {
|
||
LOGE("CLIPBOARD: JNI not ready (cls=%p method=%p)", g_captureClass, g_clipboardMid);
|
||
return;
|
||
}
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
// 服务端已把剪贴板文本限制在 256 KB,这里再兜一层 1 MiB:超出直接丢,
|
||
// 不截断(半截文本写进剪贴板比不写更危险)
|
||
const size_t kMaxClipboardBytes = 1u << 20;
|
||
if (size > kMaxClipboardBytes) {
|
||
LOGE("CLIPBOARD: payload %zu bytes exceeds %zu, dropped", size, kMaxClipboardBytes);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return;
|
||
}
|
||
jbyteArray arr = jenv->NewByteArray((jsize)size);
|
||
if (!arr) {
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
LOGE("CLIPBOARD: NewByteArray(%zu) failed", size);
|
||
return;
|
||
}
|
||
jenv->SetByteArrayRegion(arr, 0, (jsize)size, (const jbyte*)data);
|
||
if (!jenv->ExceptionCheck()) {
|
||
jenv->CallStaticVoidMethod(g_captureClass, g_clipboardMid, arr);
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
LOGI("CLIPBOARD: dispatched %zu bytes", size);
|
||
} else {
|
||
jenv->ExceptionClear();
|
||
LOGE("CLIPBOARD: SetByteArrayRegion failed");
|
||
}
|
||
jenv->DeleteLocalRef(arr);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 远程交谈:native 子连接 → ChatSession.onNativeEvent(kind, data)。
|
||
// kind: 1 = 服务端已绑定,2 = 会话结束,3 = 一条 GBK 文本。data 只在 kind=3 时非空。
|
||
// 与 DispatchClipboardText 同一套 attach/detach 套路,供 AndroidChatHandler::OnReceive 调用。
|
||
void DispatchChatEvent(int kind, const uint8_t* data, size_t size)
|
||
{
|
||
if (!g_jvm || !g_chatClass || !g_chatEventMid) {
|
||
LOGE("CHAT: JNI not ready (cls=%p method=%p)", g_chatClass, g_chatEventMid);
|
||
return;
|
||
}
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jbyteArray arr = nullptr;
|
||
if (data && size) {
|
||
arr = jenv->NewByteArray((jsize)size);
|
||
if (!arr) {
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
LOGE("CHAT: NewByteArray(%zu) failed", size);
|
||
return;
|
||
}
|
||
jenv->SetByteArrayRegion(arr, 0, (jsize)size, (const jbyte*)data);
|
||
if (jenv->ExceptionCheck()) {
|
||
jenv->ExceptionClear();
|
||
jenv->DeleteLocalRef(arr);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return;
|
||
}
|
||
}
|
||
jenv->CallStaticVoidMethod(g_chatClass, g_chatEventMid, (jint)kind, arr);
|
||
if (jenv->ExceptionCheck()) {
|
||
jenv->ExceptionClear();
|
||
LOGE("CHAT: onNativeEvent(%d) threw", kind);
|
||
}
|
||
if (arr) jenv->DeleteLocalRef(arr);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 锁屏:服务端下发 COMMAND_SCREEN_CTRL_ALT_DEL(Android 无此组合键,映射为
|
||
// GLOBAL_ACTION_LOCK_SCREEN)。与 DispatchClipboardText 同一套 attach/detach 套路。
|
||
void DispatchLockScreen()
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_lockScreenMid) {
|
||
LOGE("LOCK_SCREEN: JNI not ready (cls=%p method=%p)", g_ctrlClass, g_lockScreenMid);
|
||
return;
|
||
}
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jenv->CallStaticVoidMethod(g_ctrlClass, g_lockScreenMid);
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
LOGI("LOCK_SCREEN: dispatched");
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 隐私 overlay:黑屏(COMMAND_SCREEN_BLANK)与锁键鼠(COMMAND_SCREEN_BLOCK_INPUT)
|
||
// 共用同一个无障碍 overlay,两个参数都是绝对状态(见 ScreenHandler.h 的 ApplyOverlay)。
|
||
void DispatchPrivacyOverlay(bool black, bool block)
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_overlayMid) {
|
||
LOGE("PRIVACY_OVERLAY: JNI not ready (cls=%p method=%p)", g_ctrlClass, g_overlayMid);
|
||
return;
|
||
}
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jenv->CallStaticVoidMethod(g_ctrlClass, g_overlayMid,
|
||
black ? JNI_TRUE : JNI_FALSE,
|
||
block ? JNI_TRUE : JNI_FALSE);
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
LOGI("PRIVACY_OVERLAY: dispatched black=%d block=%d", (int)black, (int)block);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// ── 远程桌面画质/帧率协商 ────────────────────────────────────────────────────
|
||
// 服务端在屏幕子连接里下发 CMD_QUALITY_LEVEL / CMD_FPS / CMD_QUALITY_PROFILES,
|
||
// 客户端把档位/码率表/帧率存进 SharedPreferences,下次建立子连接时随 ScreenSettings
|
||
// 上报(否则写死的 Good 会让服务端的自适应质量永远不启用)。C++ 只做协议解析,
|
||
// 档位到编码器的落点在 Kotlin(MediaCodec 在那一侧)。
|
||
|
||
// attach 当前线程取 JNIEnv(子连接接收线程通常处于 detached 状态);失败返回 nullptr。
|
||
static JNIEnv* AttachForJni(bool& attached)
|
||
{
|
||
attached = false;
|
||
if (!g_jvm) return nullptr;
|
||
JNIEnv* jenv = nullptr;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return nullptr;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return nullptr;
|
||
}
|
||
return jenv;
|
||
}
|
||
|
||
// 屏幕子连接建立时填 ScreenSettings 用;读不到(服务未起)时按 Good/20 兜底。
|
||
int GetClientQualityLevel()
|
||
{
|
||
if (!g_tuningClass || !g_getQualityLevelMid) return QUALITY_GOOD;
|
||
bool attached = false;
|
||
JNIEnv* jenv = AttachForJni(attached);
|
||
if (!jenv) return QUALITY_GOOD;
|
||
jint v = jenv->CallStaticIntMethod(g_tuningClass, g_getQualityLevelMid);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); v = QUALITY_GOOD; }
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return (int)v;
|
||
}
|
||
|
||
int GetClientMaxFps()
|
||
{
|
||
if (!g_tuningClass || !g_getMaxFpsMid) return 20;
|
||
bool attached = false;
|
||
JNIEnv* jenv = AttachForJni(attached);
|
||
if (!jenv) return 20;
|
||
jint v = jenv->CallStaticIntMethod(g_tuningClass, g_getMaxFpsMid);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); v = 20; }
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return (int)v;
|
||
}
|
||
|
||
// CMD_QUALITY_LEVEL:level 有符号(-2 关闭 / -1 自适应 / 0-5 具体档位),persist 表示落盘。
|
||
void DispatchQualityLevel(int level, bool persist)
|
||
{
|
||
if (!g_tuningClass || !g_onQualityLevelMid) {
|
||
LOGE("QUALITY: JNI not ready (cls=%p method=%p)", g_tuningClass, g_onQualityLevelMid);
|
||
return;
|
||
}
|
||
bool attached = false;
|
||
JNIEnv* jenv = AttachForJni(attached);
|
||
if (!jenv) return;
|
||
jenv->CallStaticVoidMethod(g_tuningClass, g_onQualityLevelMid,
|
||
(jint)level, persist ? JNI_TRUE : JNI_FALSE);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); LOGE("QUALITY: onQualityLevel threw"); }
|
||
LOGI("QUALITY: level=%d persist=%d", level, (int)persist);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// CMD_FPS:byte[1] = 最大帧率(255 = 不限)。帧率只在下次开抓时生效(见 ScreenTuning 注释)。
|
||
void DispatchMaxFps(int fps)
|
||
{
|
||
if (!g_tuningClass || !g_onFpsMid) {
|
||
LOGE("QUALITY: JNI not ready (cls=%p method=%p)", g_tuningClass, g_onFpsMid);
|
||
return;
|
||
}
|
||
bool attached = false;
|
||
JNIEnv* jenv = AttachForJni(attached);
|
||
if (!jenv) return;
|
||
jenv->CallStaticVoidMethod(g_tuningClass, g_onFpsMid, (jint)fps);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); LOGE("QUALITY: onFps threw"); }
|
||
LOGI("QUALITY: maxFps=%d", fps);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// CMD_QUALITY_PROFILES:6 档 × 4 字段,C++ 侧拼成 "fps,width,algo,bitrate;..." 交 Kotlin 解析落盘。
|
||
void DispatchQualityProfilesCsv(const char* csv)
|
||
{
|
||
if (!g_tuningClass || !g_onQualityProfilesMid) {
|
||
LOGE("QUALITY: JNI not ready (cls=%p method=%p)", g_tuningClass, g_onQualityProfilesMid);
|
||
return;
|
||
}
|
||
bool attached = false;
|
||
JNIEnv* jenv = AttachForJni(attached);
|
||
if (!jenv) return;
|
||
jstring s = jenv->NewStringUTF(csv);
|
||
if (!s) {
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
LOGE("QUALITY: NewStringUTF failed");
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return;
|
||
}
|
||
jenv->CallStaticVoidMethod(g_tuningClass, g_onQualityProfilesMid, s);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); LOGE("QUALITY: onQualityProfiles threw"); }
|
||
jenv->DeleteLocalRef(s);
|
||
LOGI("QUALITY: profiles %s", csv);
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
static std::string GetActiveWindowFromJava()
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_getActiveWindowMid) return "Android";
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return "Android";
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return "Android";
|
||
}
|
||
jstring js = (jstring)jenv->CallStaticObjectMethod(g_ctrlClass, g_getActiveWindowMid);
|
||
std::string result = "Android";
|
||
if (js && !jenv->ExceptionOccurred()) {
|
||
const char* c = jenv->GetStringUTFChars(js, nullptr);
|
||
if (c) { result = c; jenv->ReleaseStringUTFChars(js, c); }
|
||
jenv->DeleteLocalRef(js);
|
||
}
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return result;
|
||
}
|
||
|
||
// ---- 历史活动采样 ----
|
||
// ControlService.currentActivityTitle():null = 无障碍服务没启用(或 JNI 未就绪),
|
||
// "Locked" = 锁屏/息屏,其余是「应用名 (包名)」或桌面。
|
||
static bool GetActivityTitleFromJava(std::string& out)
|
||
{
|
||
out.clear();
|
||
if (!g_jvm || !g_ctrlClass || !g_activityTitleMid) return false;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return false;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return false;
|
||
}
|
||
jstring js = (jstring)jenv->CallStaticObjectMethod(g_ctrlClass, g_activityTitleMid);
|
||
bool ok = false;
|
||
if (js) {
|
||
if (!jenv->ExceptionCheck()) {
|
||
const char* c = jenv->GetStringUTFChars(js, nullptr);
|
||
if (c) { out = c; jenv->ReleaseStringUTFChars(js, c); ok = true; }
|
||
}
|
||
jenv->DeleteLocalRef(js);
|
||
}
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return ok;
|
||
}
|
||
|
||
// 最近一次成功问到前台应用的时间:决定「历史活动」空报告里给的是权限提示还是
|
||
// 「暂无记录」。用时间而不是布尔:无障碍服务被关掉后要能重新给出权限提示。
|
||
static std::atomic<uint64_t> g_lastActivityProbeOkMs{0};
|
||
|
||
// ActivityHistory 采样线程每秒调一次;winId=0 表示空闲(锁屏、服务未启用、取不到标题)。
|
||
static LinuxActivity::ProbeResult ProbeActivityFromJava()
|
||
{
|
||
LinuxActivity::ProbeResult r;
|
||
std::string title;
|
||
if (!GetActivityTitleFromJava(title)) return r;
|
||
g_lastActivityProbeOkMs.store(GetUnixMs(), std::memory_order_relaxed);
|
||
if (title.empty() || title == "Locked") return r;
|
||
r.winId = (unsigned long)XXH64(title.data(), title.size(), 0);
|
||
r.title = std::move(title);
|
||
return r;
|
||
}
|
||
|
||
// 服务器连接参数
|
||
static std::string g_serverIp;
|
||
static int g_serverPort = 443;
|
||
|
||
// 设备信息(nativeInit 传入)
|
||
static std::string g_androidId;
|
||
static std::string g_deviceModel;
|
||
static std::string g_androidVersion;
|
||
static std::string g_screenRes;
|
||
static std::string g_username;
|
||
static std::string g_apkPath;
|
||
static std::string g_filesDir; // context.filesDir,无需权限,用于持久化分组名
|
||
static std::string g_versionName = "0"; // BuildConfig.VERSION_NAME,登录时上报到版本列
|
||
static int g_versionCode = 0; // BuildConfig.VERSION_CODE
|
||
|
||
static void SaveGroupName() {
|
||
if (g_filesDir.empty()) return;
|
||
std::string path = g_filesDir + "/yama_group";
|
||
FILE* f = fopen(path.c_str(), "w");
|
||
if (!f) { LOGI("SaveGroupName: cannot open %s", path.c_str()); return; }
|
||
fputs(g_SETTINGS.szGroupName, f);
|
||
fclose(f);
|
||
LOGI("Group saved: %s", g_SETTINGS.szGroupName);
|
||
}
|
||
|
||
static void LoadGroupName() {
|
||
if (g_filesDir.empty()) return;
|
||
std::string path = g_filesDir + "/yama_group";
|
||
FILE* f = fopen(path.c_str(), "r");
|
||
if (!f) return;
|
||
char buf[24] = {};
|
||
if (fgets(buf, sizeof(buf), f)) {
|
||
size_t len = strlen(buf);
|
||
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) buf[--len] = '\0';
|
||
if (len > 0) {
|
||
memset(g_SETTINGS.szGroupName, 0, sizeof(g_SETTINGS.szGroupName));
|
||
strncpy(g_SETTINGS.szGroupName, buf, sizeof(g_SETTINGS.szGroupName) - 1);
|
||
LOGI("Group loaded from file: %s", buf);
|
||
}
|
||
}
|
||
fclose(f);
|
||
}
|
||
|
||
// 屏幕尺寸(Java 侧 MediaCodec 配置后通过 nativeSetScreenSize 设置)
|
||
// 初始化为 0;ScreenSpyThread 等到非零后再读,避免在 nativeSetScreenSize 之前
|
||
// 拿到默认值 1280×720 发给服务端导致 decoder 尺寸错误黑屏。
|
||
static std::atomic<int> g_screenWidth{0};
|
||
static std::atomic<int> g_screenHeight{0};
|
||
|
||
// 活跃子连接的 handler 集合(受 g_shMutex 保护);支持多个浏览者/控制者同时连接
|
||
static std::set<AndroidScreenHandler*> g_screenHandlers;
|
||
static std::mutex g_shMutex;
|
||
|
||
// ------------------------------------------------------------------ 屏幕子连接线程
|
||
// 通过 JNI 调用 CaptureService 的静态方法,复用同一套 attach/detach 模板。
|
||
static void CallCaptureStaticVoid(jmethodID mid)
|
||
{
|
||
if (!g_jvm || !g_captureClass || !mid) return;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jenv->CallStaticVoidMethod(g_captureClass, mid);
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 带一个 String 参数的静态方法调用(onUpdateReceived(path))
|
||
static void CallCaptureStaticString(jmethodID mid, const char* s)
|
||
{
|
||
if (!g_jvm || !g_captureClass || !mid || !s) return;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return;
|
||
}
|
||
jstring js = jenv->NewStringUTF(s);
|
||
if (js) {
|
||
jenv->CallStaticVoidMethod(g_captureClass, mid, js);
|
||
jenv->DeleteLocalRef(js);
|
||
}
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
|
||
// 触发编码器输出关键帧(setParameters REQUEST_SYNC_FRAME)
|
||
static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid); }
|
||
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
|
||
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
|
||
|
||
// 向 CaptureService.onNativeStatus() 发送状态 Toast(连接线程诊断用)
|
||
static void PostStatus(const char* msg) {
|
||
LOGI("STATUS: %s", msg);
|
||
#if SCREEN_STATUS_ENABLED
|
||
if (!g_jvm || !g_captureClass || !g_statusMid) return;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
if (g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6) == JNI_EDETACHED) {
|
||
g_jvm->AttachCurrentThread(&jenv, nullptr);
|
||
attached = true;
|
||
}
|
||
if (jenv) {
|
||
jstring js = jenv->NewStringUTF(msg);
|
||
if (js) {
|
||
jenv->CallStaticVoidMethod(g_captureClass, g_statusMid, js);
|
||
jenv->DeleteLocalRef(js);
|
||
}
|
||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||
}
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
#endif
|
||
}
|
||
|
||
static void ScreenSpyThread()
|
||
{
|
||
// 等待 Java 侧 startCapture() 调用 nativeSetScreenSize 设置真实分辨率。
|
||
// 若在此之前读到默认值 0,SendBitmapInfo 会发错误尺寸给服务端,
|
||
// 导致浏览器 initDecoder 尺寸与 H.264 SPS 不一致 → decode error → 黑屏。
|
||
for (int i = 0; i < 100 && g_screenWidth.load() == 0 && g_running.load(); ++i)
|
||
Sleep(50); // 最多等 5 秒
|
||
|
||
int w = g_screenWidth.load();
|
||
int h = g_screenHeight.load();
|
||
if (w == 0 || h == 0) {
|
||
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
|
||
return;
|
||
}
|
||
LOGI("ScreenSpyThread start → %s:%d size=%dx%d", g_serverIp.c_str(), g_serverPort, w, h);
|
||
|
||
// 服务端只发一次 COMMAND_SCREEN_SPY 就等子连接,子连接失败必须自己重试
|
||
for (int attempt = 1; attempt <= 20 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
|
||
// 声明在 try 外部,确保 catch 中 handler 仍有效,可安全从 g_screenHandlers 移除
|
||
std::unique_ptr<IOCPClient> client;
|
||
std::unique_ptr<AndroidScreenHandler> handler;
|
||
try {
|
||
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)) {
|
||
LOGI("ScreenSpyThread: connect failed (attempt %d/20), retry 2s", attempt);
|
||
Sleep(2000);
|
||
continue;
|
||
}
|
||
LOGI("SST[%d]: connected, creating handler w=%d h=%d", attempt, w, h);
|
||
|
||
handler = std::make_unique<AndroidScreenHandler>(client.get(), w, h);
|
||
LOGI("SST[%d]: handler created, inserting to set", attempt);
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
g_screenHandlers.insert(handler.get());
|
||
}
|
||
|
||
LOGI("SST[%d]: setManagerCallBack", attempt);
|
||
client->setManagerCallBack(handler.get(),
|
||
IOCPManager::DataProcess,
|
||
IOCPManager::ReconnectProcess);
|
||
LOGI("SST[%d]: SendBitmapInfo", attempt);
|
||
handler->SendBitmapInfo();
|
||
LOGI("SST[%d]: ForceFirstFrame", attempt);
|
||
ForceFirstFrameFromJava();
|
||
LOGI("SST[%d]: RequestIdr", attempt);
|
||
RequestIdrFromJava();
|
||
LOGI("SST[%d]: entering wait loop", attempt);
|
||
|
||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||
Sleep(200);
|
||
|
||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
g_screenHandlers.erase(handler.get());
|
||
}
|
||
} catch (const std::exception& e) {
|
||
LOGE("ScreenSpyThread exception (attempt %d): %s", attempt, e.what());
|
||
// 先清除回调,再析构 handler:防止 client 在 handler 析构后仍持有其指针
|
||
if (client) client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
if (handler) {
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
g_screenHandlers.erase(handler.get());
|
||
}
|
||
Sleep(2000);
|
||
continue;
|
||
}
|
||
break; // 正常结束,不再重试
|
||
}
|
||
LOGI("ScreenSpyThread exit");
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 运行日志上报
|
||
// 对应 Windows 的 CClientLogManager / Linux 的 ClientLogThread。
|
||
// 服务端 COMMAND_QUERY_LOG → 开子连接 → 首包 TOKEN_REPORT_LOG + Logger 内存 ring 全量。
|
||
// 必须走子连接:服务端 TOKEN_REPORT_LOG 分支取走首包后会 CancelIO,若回在主连接上,
|
||
// 被关掉的就是主连接本身(客户端当场掉线)。
|
||
static void ClientLogThread()
|
||
{
|
||
LOGI("ClientLogThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
|
||
for (int attempt = 1; attempt <= 3 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
|
||
std::unique_ptr<IOCPClient> client;
|
||
std::unique_ptr<ClientLogHandler> handler;
|
||
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);
|
||
continue;
|
||
}
|
||
// ctor 里就把 ring 全量发出去了;服务端取走首包即关闭子连接
|
||
handler = std::make_unique<ClientLogHandler>(client.get());
|
||
client->setManagerCallBack(handler.get(),
|
||
IOCPManager::DataProcess,
|
||
IOCPManager::ReconnectProcess);
|
||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||
Sleep(200);
|
||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
LOGI("ClientLogThread: sub-conn closed by server (attempt %d)", attempt);
|
||
break; // 服务端取走日志即主动断开,属正常结束
|
||
} catch (const std::exception& e) {
|
||
LOGE("ClientLogThread exception (attempt %d): %s", attempt, e.what());
|
||
if (client) client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
Sleep(1000);
|
||
}
|
||
}
|
||
LOGI("ClientLogThread exit");
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 远程交谈
|
||
// 服务端 COMMAND_CHAT → 开子连接 → 首包 TOKEN_CHAT_START → 服务端绑定后回 [0]。
|
||
// 同一时刻只允许一个交谈线程:服务端可能重复下发(重连后手动再点一次「远程交谈」),
|
||
// 第二个子连接会被服务端当重复子连接吸收,这里直接忽略。
|
||
static std::atomic<bool> g_chatInFlight{false};
|
||
static std::mutex g_chatMx;
|
||
static AndroidChatHandler* g_chatHandler = nullptr;
|
||
|
||
static void ChatThread()
|
||
{
|
||
// detached 线程:异常逃出去会 std::terminate 整个客户端;在途标志也必须无条件还回去,
|
||
// 否则之后所有 COMMAND_CHAT 都被当成「已有交谈在跑」丢掉
|
||
struct InFlightGuard {
|
||
~InFlightGuard() { g_chatInFlight.store(false); }
|
||
} guard;
|
||
|
||
LOGI("ChatThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
|
||
for (int attempt = 1; attempt <= 3 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
|
||
std::unique_ptr<IOCPClient> client;
|
||
std::unique_ptr<AndroidChatHandler> handler;
|
||
try {
|
||
client = std::make_unique<IOCPClient>(g_bExit, true);
|
||
client->EnableSubConnAuth(true, g_myClientID);
|
||
// 与屏幕/日志子连接相同:必须继承配置的传输方式,否则 WS/WSS 部署下连不上反代
|
||
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
|
||
LOGE("ChatThread: connect failed (attempt %d/3)", attempt);
|
||
Sleep(1000);
|
||
continue;
|
||
}
|
||
// 构造即发 TOKEN_CHAT_START;服务端绑定后回单字节 [0] → Kotlin 弹聊天界面
|
||
handler = std::make_unique<AndroidChatHandler>(client.get());
|
||
client->setManagerCallBack(handler.get(),
|
||
IOCPManager::DataProcess,
|
||
IOCPManager::ReconnectProcess);
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_chatMx);
|
||
g_chatHandler = handler.get();
|
||
}
|
||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||
Sleep(200);
|
||
{
|
||
// 先摘掉 Java 可见的指针,再让 handler 析构:nativeChatSend 持同一把锁,
|
||
// 不会拿到正在销毁的对象
|
||
std::lock_guard<std::mutex> lk(g_chatMx);
|
||
g_chatHandler = nullptr;
|
||
}
|
||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
LOGI("ChatThread: sub-conn closed (attempt %d)", attempt);
|
||
break; // 会话结束/对端断开不重连:服务端会话已随子连接失效,需要新的 chat_open
|
||
} catch (const std::exception& e) {
|
||
LOGE("ChatThread exception (attempt %d): %s", attempt, e.what());
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_chatMx);
|
||
g_chatHandler = nullptr;
|
||
}
|
||
if (client) client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
Sleep(1000);
|
||
}
|
||
}
|
||
// 会话结束(含一直没连上):Kotlin 侧未打开过界面时会直接忽略
|
||
DispatchChatEvent(2, nullptr, 0);
|
||
LOGI("ChatThread exit");
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 远程终端
|
||
// 服务端 COMMAND_SHELL → 子连接 → 首包 TOKEN_TERMINAL_START → 服务端接管后发
|
||
// CMD_TERMINAL_RESIZE + COMMAND_NEXT → PTY 读线程开始回传 shell 输出。
|
||
// 与 ChatThread 同一套子连接要求(ConnAuth / 传输协议),但不依赖任何 Android 权限。
|
||
static std::atomic<bool> g_termInFlight{false};
|
||
|
||
static void TerminalThread()
|
||
{
|
||
// detached 线程:异常逃出去会 std::terminate;在途标志必须无条件还回去
|
||
struct InFlightGuard {
|
||
~InFlightGuard() { g_termInFlight.store(false); }
|
||
} guard;
|
||
|
||
LOGI("TerminalThread start → %s:%d", g_serverIp.c_str(), g_serverPort);
|
||
try {
|
||
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
|
||
client->EnableSubConnAuth(true, g_myClientID);
|
||
// 与屏幕/日志/交谈子连接一致:继承配置的传输方式,WS/WSS 部署下直连会连不上反代
|
||
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
|
||
LOGE("TerminalThread: connect failed");
|
||
return;
|
||
}
|
||
// 构造即 openpty + fork shell;失败会抛异常,服务端按等待超时处理
|
||
std::unique_ptr<PTYHandler> handler(new PTYHandler(client.get()));
|
||
client->setManagerCallBack(handler.get(),
|
||
IOCPManager::DataProcess,
|
||
IOCPManager::ReconnectProcess);
|
||
// 首包告诉服务端这是 PTY 会话(决定 UTF-8 编码与 POSIX 哨兵形态)。
|
||
// PTY 读线程要等服务端的 COMMAND_NEXT 才开始回传,初始提示符不会混进命令输出。
|
||
BYTE bToken = TOKEN_TERMINAL_START;
|
||
client->Send2Server((char*)&bToken, 1);
|
||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||
Sleep(200);
|
||
// 先摘回调再让 handler 析构(析构会停 PTY 读线程并结束 shell)
|
||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||
LOGI("TerminalThread: sub-conn closed");
|
||
} catch (const std::exception& e) {
|
||
LOGE("TerminalThread exception: %s", e.what());
|
||
}
|
||
LOGI("TerminalThread exit");
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 历史活动上报
|
||
// 主连接一次性快照(与 Windows/Linux 一致,服务端 TOKEN_REPORT_ACTIVITY 分支不 CancelIO)。
|
||
// 采样机每秒问一次 ControlService 的前台应用;这里只取 Dump(),几十微秒的活。
|
||
// 同一时刻只跑一份:服务端每主机单飞行,连点也只是重复请求。
|
||
static std::atomic<int> g_activityReportsInFlight(0);
|
||
|
||
static void ActivityReportThread()
|
||
{
|
||
// 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());
|
||
// 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());
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 屏幕预览
|
||
// 对应 Windows/Linux 的 COMMAND_SCREEN_PREVIEW_REQ → TOKEN_SCREEN_PREVIEW_RSP。
|
||
// Android 的 JPEG 在 Kotlin 侧(ScreenShot,无障碍 takeScreenshot)编码好,这里只搬运;
|
||
// 与 Linux 回 BGRX 不同,服务端对 JPEG 直接透传,不再二次编码。
|
||
static std::atomic<int> g_previewInFlight(0);
|
||
|
||
// 抓一帧 JPEG:JNI 调 ScreenShot.capture(maxWidth, quality),把 Shot 的数据/宽高取回来。
|
||
// 失败(无障碍没开、系统限流、编码失败)返回 false,调用方回 CAPTURE_FAILED。
|
||
static bool CaptureScreenJpeg(uint16_t maxWidth, uint8_t quality,
|
||
std::vector<uint8_t>& jpeg, int& w, int& h)
|
||
{
|
||
jpeg.clear();
|
||
w = h = 0;
|
||
if (!g_jvm || !g_shotClass || !g_shotCaptureMid || !g_shotDataMid ||
|
||
!g_shotWidthMid || !g_shotHeightMid)
|
||
return false;
|
||
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return false;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return false;
|
||
}
|
||
|
||
bool ok = false;
|
||
jobject shot = jenv->CallStaticObjectMethod(g_shotClass, g_shotCaptureMid,
|
||
(jint)maxWidth, (jint)quality);
|
||
if (shot && !jenv->ExceptionCheck()) {
|
||
jbyteArray arr = (jbyteArray)jenv->CallObjectMethod(shot, g_shotDataMid);
|
||
if (!jenv->ExceptionCheck() && arr) {
|
||
jint bw = jenv->CallIntMethod(shot, g_shotWidthMid);
|
||
jint bh = jenv->CallIntMethod(shot, g_shotHeightMid);
|
||
if (!jenv->ExceptionCheck() && bw > 0 && bh > 0) {
|
||
jsize len = jenv->GetArrayLength(arr);
|
||
if (len > 0) {
|
||
jpeg.resize((size_t)len);
|
||
jenv->GetByteArrayRegion(arr, 0, len, (jbyte*)jpeg.data());
|
||
if (!jenv->ExceptionCheck()) {
|
||
w = bw;
|
||
h = bh;
|
||
ok = true;
|
||
}
|
||
}
|
||
}
|
||
jenv->DeleteLocalRef(arr);
|
||
}
|
||
jenv->DeleteLocalRef(shot);
|
||
}
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
if (!ok) jpeg.clear();
|
||
return ok;
|
||
}
|
||
|
||
// 登录前探测:无障碍服务在跑(API 30+)才声明 CLIENT_CAP_SCREEN_PREVIEW,
|
||
// 服务端据此放行 get_screenshot。能力位随每次登录刷新,无障碍被关掉重连后会撤回。
|
||
static bool ScreenPreviewAvailable()
|
||
{
|
||
if (!g_jvm || !g_shotClass || !g_shotCanMid) return false;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return false;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return false;
|
||
}
|
||
jboolean can = jenv->CallStaticBooleanMethod(g_shotClass, g_shotCanMid);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); can = JNI_FALSE; }
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return can == JNI_TRUE;
|
||
}
|
||
|
||
// 登录前探测:无障碍服务在跑且 API 28+ 才声明 CLIENT_CAP_LOCK_SCREEN,
|
||
// 服务端据此放行 remote_lock_screen。与 ScreenPreviewAvailable 一样随每次登录刷新,
|
||
// 无障碍被关掉重连后会撤回,避免服务端假报「已锁上」。
|
||
static bool LockScreenAvailable()
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_canLockMid) return false;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return false;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return false;
|
||
}
|
||
jboolean can = jenv->CallStaticBooleanMethod(g_ctrlClass, g_canLockMid);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); can = JNI_FALSE; }
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return can == JNI_TRUE;
|
||
}
|
||
|
||
// 登录前探测:无障碍服务在跑且 API 22+(TYPE_ACCESSIBILITY_OVERLAY)才声明
|
||
// CLIENT_CAP_PRIVACY_OVERLAY,服务端据此放行 Android 的 remote_block_input。
|
||
// 与 LockScreenAvailable 一样随每次登录刷新:无障碍被关掉重连后撤回。
|
||
static bool OverlayAvailable()
|
||
{
|
||
if (!g_jvm || !g_ctrlClass || !g_canOverlayMid) return false;
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||
if (st == JNI_EDETACHED) {
|
||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return false;
|
||
attached = true;
|
||
} else if (st != JNI_OK || !jenv) {
|
||
return false;
|
||
}
|
||
jboolean can = jenv->CallStaticBooleanMethod(g_ctrlClass, g_canOverlayMid);
|
||
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); can = JNI_FALSE; }
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
return can == JNI_TRUE;
|
||
}
|
||
|
||
// 抓屏可能耗几十~几百毫秒(系统回调 + 编码),必须离开接收线程;超额请求直接丢弃
|
||
// (服务端会超时按「预览不可用」降级,与 Linux/Windows 的限流一致)。
|
||
static void ScreenPreviewThread(ScreenPreviewReq req)
|
||
{
|
||
struct InFlightGuard {
|
||
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
|
||
} guard;
|
||
|
||
std::vector<uint8_t> jpeg;
|
||
int w = 0, h = 0;
|
||
uint8_t status = CaptureScreenJpeg(req.maxWidth, req.jpegQuality, jpeg, w, h)
|
||
? (uint8_t)SCREEN_PREVIEW_OK
|
||
: (uint8_t)SCREEN_PREVIEW_CAPTURE_FAILED;
|
||
|
||
uint32_t bytes = (status == SCREEN_PREVIEW_OK) ? (uint32_t)jpeg.size() : 0;
|
||
std::vector<uint8_t> pkt(sizeof(ScreenPreviewRspHeader) + bytes, 0);
|
||
ScreenPreviewRspHeader hdr;
|
||
memset(&hdr, 0, sizeof(hdr));
|
||
hdr.token = TOKEN_SCREEN_PREVIEW_RSP;
|
||
hdr.reqId = req.reqId;
|
||
hdr.status = status;
|
||
hdr.format = SCREEN_PREVIEW_FMT_JPEG; // 失败时 format 无意义,填 JPEG 保持包头合法
|
||
hdr.width = (uint16_t)w;
|
||
hdr.height = (uint16_t)h;
|
||
hdr.bytes = bytes;
|
||
memcpy(pkt.data(), &hdr, sizeof(hdr));
|
||
if (bytes) memcpy(pkt.data() + sizeof(hdr), jpeg.data(), bytes);
|
||
|
||
// 与 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);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 在线升级
|
||
// 载荷布局:[COMMAND_UPDATE:1][APK 大小:8 LE][APK:size][xxh64:8 LE]
|
||
// 校验通过后写到 filesDir/update.apk,交给 Kotlin 的 PackageInstaller 会话去装
|
||
// (必须系统安装器 + 人工确认,APP 不能静默自替换)。
|
||
// 任何失败都只回报、不退出:当前版本继续跑,服务端能看到原因。
|
||
|
||
// ClientMsg 的 text/title 是定长数组,strcpy_s 遇到超长会触发无效参数处理器直接崩,
|
||
// 所以统一截断后 memcpy。
|
||
static void sendClientMsg(const char* title, const char* text)
|
||
{
|
||
// 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);
|
||
if (text) {
|
||
size_t n = strlen(text);
|
||
if (n > sizeof(msg.text) - 1) n = sizeof(msg.text) - 1;
|
||
memcpy(msg.text, text, n);
|
||
}
|
||
mc->Send2Server((char*)&msg, sizeof(msg));
|
||
}
|
||
|
||
static void reportUpdateFailure(const std::string& reason)
|
||
{
|
||
LOGI("UPDATE failed: %s", reason.c_str());
|
||
PostStatus(("update: " + reason).c_str());
|
||
sendClientMsg("Android update failed", reason.c_str());
|
||
}
|
||
|
||
static void ApplyUpdateApk(const PBYTE szBuffer, ULONG ulLength)
|
||
{
|
||
const size_t headerLen = 1 + sizeof(uint64_t);
|
||
const size_t trailerLen = sizeof(uint64_t);
|
||
if (ulLength < headerLen + trailerLen) {
|
||
reportUpdateFailure("payload too short");
|
||
return;
|
||
}
|
||
uint64_t size = 0;
|
||
memcpy(&size, szBuffer + 1, sizeof(size));
|
||
if (size < 1024 || size > (uint64_t)(ulLength - headerLen - trailerLen)) {
|
||
reportUpdateFailure("payload size invalid");
|
||
return;
|
||
}
|
||
const unsigned char* payload = szBuffer + headerLen;
|
||
uint64_t expect = 0;
|
||
memcpy(&expect, payload + size, sizeof(expect));
|
||
uint64_t actual = (uint64_t)XXH64(payload, (size_t)size, 0);
|
||
if (actual != expect) {
|
||
char buf[96];
|
||
snprintf(buf, sizeof(buf), "xxh64 mismatch (payload corrupted: %u bytes)", (unsigned)size);
|
||
reportUpdateFailure(buf);
|
||
return;
|
||
}
|
||
if (payload[0] != 'P' || payload[1] != 'K' || payload[2] != 0x03 || payload[3] != 0x04) {
|
||
reportUpdateFailure("payload is not an APK");
|
||
return;
|
||
}
|
||
if (g_filesDir.empty()) {
|
||
reportUpdateFailure("filesDir not set");
|
||
return;
|
||
}
|
||
std::string path = g_filesDir + "/update.apk";
|
||
int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||
if (fd < 0) {
|
||
reportUpdateFailure("cannot create " + path + ": " + strerror(errno));
|
||
return;
|
||
}
|
||
bool ok = true;
|
||
size_t off = 0;
|
||
while (off < (size_t)size) {
|
||
ssize_t n = write(fd, payload + off, (size_t)size - off);
|
||
if (n <= 0) {
|
||
if (n < 0 && errno == EINTR) continue;
|
||
ok = false;
|
||
break;
|
||
}
|
||
off += (size_t)n;
|
||
}
|
||
if (ok) ok = (fsync(fd) == 0);
|
||
if (close(fd) != 0) ok = false;
|
||
if (!ok) {
|
||
std::string err = strerror(errno);
|
||
unlink(path.c_str());
|
||
reportUpdateFailure("cannot write " + path + ": " + err);
|
||
return;
|
||
}
|
||
|
||
LOGI("UPDATE: saved %s (%llu bytes), handing to installer", path.c_str(),
|
||
(unsigned long long)size);
|
||
char msg[128];
|
||
snprintf(msg, sizeof(msg), "APK received (%.1f MB), opening system installer",
|
||
(double)size / (1024.0 * 1024.0));
|
||
PostStatus(msg);
|
||
// 拉不起来(无障碍没开/系统限制)时 Kotlin 侧会改发通知,failure 只回报真正的前置错误
|
||
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)
|
||
{
|
||
if (!szBuffer || !ulLength) return TRUE;
|
||
int allowed = (int)ClientAuth::IsCommandAllowed(szBuffer[0]);
|
||
if (!allowed) {
|
||
LOGI("DataProcess cmd=%d len=%lu allowed=%d",
|
||
(int)(unsigned char)szBuffer[0], (unsigned long)ulLength, allowed);
|
||
return TRUE;
|
||
}
|
||
|
||
switch (szBuffer[0]) {
|
||
case COMMAND_BYE:
|
||
PostStatus("BYE from server");
|
||
g_bExit = S_CLIENT_EXIT;
|
||
break;
|
||
|
||
case TOKEN_UNINSTALL: {
|
||
// 卸载主机(主控在线列表的「卸载主机」= 单字节命令,与 Windows 客户端同义)。
|
||
// Android 不允许应用静默卸载自己:先回 COMMAND_BYE 并退出连接(服务端随即把
|
||
// 本机移出在线列表),再拉起系统的卸载确认框;设备上点确认后包才真正删除。
|
||
// 用户点取消的话客户端已经退出,需要人工重新打开 App。
|
||
PostStatus("UNINSTALL from server");
|
||
if (auto mc = GetMainClient()) {
|
||
BYTE bye = COMMAND_BYE;
|
||
mc->Send2Server((char*)&bye, 1);
|
||
}
|
||
g_bExit = S_CLIENT_EXIT;
|
||
CallCaptureStaticVoid(g_uninstallMid);
|
||
break;
|
||
}
|
||
|
||
case CMD_HEARTBEAT_ACK:
|
||
if (ulLength >= 1 + (ULONG)sizeof(HeartbeatACK)) {
|
||
HeartbeatACK ack;
|
||
memcpy(&ack, szBuffer + 1, sizeof(HeartbeatACK));
|
||
uint64_t now = GetUnixMs();
|
||
g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed);
|
||
int64_t rtt = (int64_t)now - (int64_t)ack.Time;
|
||
if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < rtt)
|
||
rtt -= ack.ProcessingMs;
|
||
g_rttEstimator.update_from_sample((double)rtt);
|
||
if (now - g_lastHbLogMs.load(std::memory_order_relaxed) >= HB_LOG_INTERVAL_MS) {
|
||
g_lastHbLogMs.store(now, std::memory_order_relaxed);
|
||
LOGI("HeartbeatACK RTT=%" PRId64 "ms SRTT=%.1fms", rtt, g_rttEstimator.srtt * 1000.0);
|
||
}
|
||
}
|
||
break;
|
||
|
||
case CMD_MASTERSETTING: {
|
||
MasterSettings settings;
|
||
if (ClientAuth::HandleMasterSettings(szBuffer + 1, (int)ulLength - 1, &settings)) {
|
||
if (settings.ReportInterval > 0)
|
||
g_heartbeatInterval = std::max(settings.ReportInterval, 30);
|
||
LOGI("MasterSettings OK interval=%ds (server=%d)", g_heartbeatInterval, settings.ReportInterval);
|
||
PostStatus("masterSettings: OK");
|
||
} else {
|
||
PostStatus("masterSettings: FAIL");
|
||
}
|
||
break;
|
||
}
|
||
|
||
case COMMAND_SCREEN_SPY: {
|
||
// 每个 COMMAND_SCREEN_SPY 对应一个独立子连接,支持多人同时观看/控制
|
||
size_t active;
|
||
{ std::lock_guard<std::mutex> lk(g_shMutex); active = g_screenHandlers.size(); }
|
||
LOGI("cmd: COMMAND_SCREEN_SPY len=%lu active=%zu w=%d h=%d",
|
||
(unsigned long)ulLength, active, g_screenWidth.load(), g_screenHeight.load());
|
||
std::thread(ScreenSpyThread).detach();
|
||
break;
|
||
}
|
||
|
||
case COMMAND_CHAT: {
|
||
// 远程交谈(主控右键「远程交谈」/ MCP chat_open):子连接 + 应用内聊天界面
|
||
if (g_chatInFlight.exchange(true)) {
|
||
LOGI("cmd: COMMAND_CHAT ignored (chat already in flight)");
|
||
break;
|
||
}
|
||
LOGI("cmd: COMMAND_CHAT → sub-conn");
|
||
try {
|
||
std::thread(ChatThread).detach();
|
||
} catch (const std::exception& e) {
|
||
g_chatInFlight.store(false);
|
||
LOGE("Chat thread failed: %s", e.what());
|
||
}
|
||
break;
|
||
}
|
||
|
||
case COMMAND_SCREEN_CONTROL: {
|
||
if (ulLength < 1 + 48u) { LOGI("SCREEN_CONTROL(main): too short %u", ulLength); break; }
|
||
const uint8_t* p = szBuffer + 1;
|
||
uint64_t msgVal = 0, wParam = 0, lParam = 0;
|
||
memcpy(&msgVal, p + 8, 8);
|
||
memcpy(&wParam, p + 16, 8);
|
||
memcpy(&lParam, p + 24, 8);
|
||
int32_t ptX = (int32_t)(int16_t)(lParam & 0xFFFF);
|
||
int32_t ptY = (int32_t)(int16_t)((lParam >> 16) & 0xFFFF);
|
||
DispatchControlEvent((uint32_t)msgVal, wParam, ptX, ptY);
|
||
break;
|
||
}
|
||
|
||
case CMD_SET_GROUP: {
|
||
std::string grp;
|
||
if (ulLength > 1) {
|
||
grp.assign((const char*)szBuffer + 1, ulLength - 1);
|
||
auto z = grp.find('\0');
|
||
if (z != std::string::npos) grp.resize(z);
|
||
}
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
memset(g_SETTINGS.szGroupName, 0, sizeof(g_SETTINGS.szGroupName));
|
||
strncpy(g_SETTINGS.szGroupName, grp.c_str(), sizeof(g_SETTINGS.szGroupName) - 1);
|
||
}
|
||
SaveGroupName();
|
||
LOGI("Group changed to: %s", grp.c_str());
|
||
break;
|
||
}
|
||
|
||
case COMMAND_QUERY_LOG:
|
||
// MCP get_client_log / 主控「运行日志」窗口:一次子连接取 ring 全量快照
|
||
LOGI("cmd: COMMAND_QUERY_LOG → sub-conn");
|
||
std::thread(ClientLogThread).detach();
|
||
break;
|
||
|
||
case COMMAND_QUERY_ACTIVITY:
|
||
// MCP get_activity_history / 主控「历史活动」窗口:主连接回一次快照
|
||
if (g_activityReportsInFlight.fetch_add(1) >= 1) {
|
||
g_activityReportsInFlight.fetch_sub(1); // 已有报表在飞,重复请求丢弃
|
||
break;
|
||
}
|
||
LOGI("cmd: COMMAND_QUERY_ACTIVITY → main conn snapshot");
|
||
try {
|
||
std::thread(ActivityReportThread).detach();
|
||
} catch (const std::exception& e) {
|
||
// 线程起不来要把在途计数还回去,否则之后的历史活动请求全被当成「忙」丢掉
|
||
g_activityReportsInFlight.fetch_sub(1);
|
||
LOGE("Activity report thread failed: %s", e.what());
|
||
}
|
||
break;
|
||
|
||
case COMMAND_SCREEN_PREVIEW_REQ: {
|
||
// MCP get_screenshot / 在线列表缩略图:主连接回一次 JPEG
|
||
if (ulLength < sizeof(ScreenPreviewReq)) break;
|
||
ScreenPreviewReq req;
|
||
memcpy(&req, szBuffer, sizeof(req));
|
||
if (g_previewInFlight.fetch_add(1) >= 1) {
|
||
g_previewInFlight.fetch_sub(1); // 已有抓屏在跑,重复请求丢弃
|
||
break;
|
||
}
|
||
LOGI("cmd: COMMAND_SCREEN_PREVIEW_REQ reqId=%u maxWidth=%u quality=%u",
|
||
req.reqId, req.maxWidth, req.jpegQuality);
|
||
try {
|
||
std::thread(ScreenPreviewThread, req).detach();
|
||
} catch (const std::exception& e) {
|
||
// 线程起不来要把在途计数还回去,否则之后所有预览请求都被当成「忙」丢掉
|
||
g_previewInFlight.fetch_sub(1);
|
||
LOGE("Screen preview thread failed: %s", e.what());
|
||
}
|
||
break;
|
||
}
|
||
|
||
case COMMAND_SHELL: {
|
||
// 远程终端(MCP exec_command / terminal_open,或主控菜单「终端」):
|
||
// 子连接 + PTY,没有任何 Android 权限依赖。同一时刻只允许一个会话:
|
||
// 服务端本身按主机去重,这里挡住用户连点造成的重复子连接。
|
||
if (g_termInFlight.exchange(true)) {
|
||
LOGI("cmd: COMMAND_SHELL ignored (terminal already in flight)");
|
||
break;
|
||
}
|
||
LOGI("cmd: COMMAND_SHELL → PTY sub-conn");
|
||
try {
|
||
std::thread(TerminalThread).detach();
|
||
} catch (const std::exception& e) {
|
||
g_termInFlight.store(false);
|
||
LOGE("Terminal thread failed: %s", e.what());
|
||
}
|
||
break;
|
||
}
|
||
|
||
case COMMAND_UPDATE:
|
||
LOGI("cmd: COMMAND_UPDATE len=%lu", (unsigned long)ulLength);
|
||
ApplyUpdateApk(szBuffer, ulLength);
|
||
break;
|
||
|
||
case COMMAND_SYSTEM:
|
||
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;
|
||
}
|
||
return TRUE;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 网络主线程
|
||
// 进程已运行秒数(RES_UPTIME)的单调基准。steady_clock 在 Android 上对应
|
||
// CLOCK_MONOTONIC,不受系统时间调整影响;库加载即开始计时。
|
||
static const auto g_processStartMono = std::chrono::steady_clock::now();
|
||
|
||
// 每轮 nativeInit 生成一个代号:旧连接线程可能晚于新一轮才走到收尾代码,
|
||
// 只有当前代号的主线程才能清 g_running / g_pMainClient,否则会把新一轮连接
|
||
// 的状态清掉(服务重启 CaptureService 时真会撞上)。
|
||
static std::atomic<uint64_t> g_connGeneration{0};
|
||
|
||
static void ConnectionThread(uint64_t gen)
|
||
{
|
||
LOGI("ConnectionThread → %s:%d", g_serverIp.c_str(), g_serverPort);
|
||
|
||
PostStatus("geo: fetching...");
|
||
std::string g_pubIp, g_location;
|
||
FetchGeoInfo(g_pubIp, g_location);
|
||
PostStatus(("geo: " + (g_pubIp.empty() ? "failed" : g_pubIp)).c_str());
|
||
|
||
LOGIN_INFOR logInfo;
|
||
{
|
||
std::string pcName = g_deviceModel;
|
||
if (g_SETTINGS.szGroupName[0]) { pcName += '/'; pcName += g_SETTINGS.szGroupName; }
|
||
strncpy(logInfo.szPCName, pcName.c_str(), sizeof(logInfo.szPCName) - 1);
|
||
}
|
||
strncpy(logInfo.OsVerInfoEx, g_androidVersion.c_str(), sizeof(logInfo.OsVerInfoEx) - 1);
|
||
strncpy(logInfo.szStartTime, ToPekingTimeAsString(nullptr).c_str(), sizeof(logInfo.szStartTime) - 1);
|
||
logInfo.dwCPUMHz = GetCpuMHz();
|
||
logInfo.bWebCamIsExist = 0;
|
||
|
||
g_myClientID = XXH64(g_androidId.c_str(), g_androidId.size(), 0);
|
||
|
||
logInfo.AddReserved("APK");
|
||
logInfo.AddReserved(64); // OS bits
|
||
logInfo.AddReserved(GetCpuCores()); // CPU 核数
|
||
logInfo.AddReserved(GetMemoryGB()); // 内存 GB
|
||
logInfo.AddReserved(g_apkPath.empty() ? "/data/app/com.yama.client"
|
||
: g_apkPath.c_str()); // 文件路径
|
||
logInfo.AddReserved("?");
|
||
logInfo.AddReserved(logInfo.szStartTime);
|
||
logInfo.AddReserved("?");
|
||
logInfo.AddReserved(64); // 程序位数
|
||
logInfo.AddReserved("");
|
||
logInfo.AddReserved(g_location.c_str()); // [10] 地理位置
|
||
logInfo.AddReserved(g_pubIp.c_str()); // [11] 公网 IP
|
||
logInfo.AddReserved(("v" + g_versionName + " (" + std::to_string(g_versionCode) + ")").c_str());
|
||
logInfo.AddReserved(g_username.c_str());
|
||
logInfo.AddReserved(0); // IsRunningAsAdmin
|
||
logInfo.AddReserved(g_screenRes.c_str());
|
||
logInfo.AddReserved(std::to_string(g_myClientID).c_str());
|
||
logInfo.AddReserved((int)getpid()); // PID
|
||
logInfo.AddReserved(FormatFileSize(GetFileSize(g_apkPath)).c_str()); // 文件大小
|
||
#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
|
||
|
||
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
|
||
LOGI("ClientID=%" PRIu64, g_myClientID);
|
||
|
||
// shared_ptr:抓屏/活动上报/升级回报是 detached 线程,可能拿着句柄跑到本线程收尾之后
|
||
std::shared_ptr<IOCPClient> client = std::make_shared<IOCPClient>(g_bExit, false);
|
||
client->setManagerCallBack(nullptr, DataProcess, nullptr);
|
||
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;
|
||
// 每次循环判断都带上代号: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);
|
||
PostStatus(connMsg);
|
||
clock_t c = clock();
|
||
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
|
||
snprintf(connMsg, sizeof(connMsg), "connect #%d failed errno=%d", g_connAttempt, errno);
|
||
PostStatus(connMsg);
|
||
Sleep(5000);
|
||
continue;
|
||
}
|
||
|
||
PostStatus("connected! sending login...");
|
||
ClientAuth::OnNewConnection();
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
std::string pcName = g_deviceModel;
|
||
if (g_SETTINGS.szGroupName[0]) { pcName += '/'; pcName += g_SETTINGS.szGroupName; }
|
||
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
|
||
// 屏幕预览能力位按运行时状态刷新:无障碍服务在跑才声明(API 30+ 的 takeScreenshot),
|
||
// 服务端据此放行 get_screenshot;无障碍被关掉后重连会撤回,避免服务端白等抓屏。
|
||
// 锁屏同理:无障碍服务在跑且 API 28+ 才声明。
|
||
// 隐私 overlay(黑屏 / 锁键鼠)同理:无障碍服务在跑且 API 22+ 才声明。
|
||
logInfo.SetCaps(LOGIN_INFOR::DefaultCaps() |
|
||
(ScreenPreviewAvailable() ? CLIENT_CAP_SCREEN_PREVIEW : 0) |
|
||
(LockScreenAvailable() ? CLIENT_CAP_LOCK_SCREEN : 0) |
|
||
(OverlayAvailable() ? CLIENT_CAP_PRIVACY_OVERLAY : 0));
|
||
client->SendLoginInfo(logInfo.Speed(clock() - c));
|
||
g_lastHeartbeatAckMs.store(GetUnixMs(), std::memory_order_relaxed);
|
||
LOGI("Connected & login sent");
|
||
|
||
while (client->IsRunning() && client->IsConnected()
|
||
&& S_CLIENT_NORMAL == g_bExit && g_running.load() && currentGen())
|
||
{
|
||
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() || !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(),
|
||
(int)(g_bExit == S_CLIENT_NORMAL), (int)g_running.load());
|
||
PostStatus(dbg);
|
||
break;
|
||
}
|
||
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() || !currentGen()) break;
|
||
|
||
if (ClientAuth::IsTimedOut()) {
|
||
PostStatus("timeout: masterSettings");
|
||
continue;
|
||
}
|
||
|
||
{
|
||
int ackTO = (interval * 3 > 60) ? interval * 3 : 60;
|
||
uint64_t last = g_lastHeartbeatAckMs.load(std::memory_order_relaxed);
|
||
uint64_t now = GetUnixMs();
|
||
if (last > 0 && now > last && now - last > (uint64_t)ackTO * 1000ULL) {
|
||
PostStatus("timeout: ACK");
|
||
continue;
|
||
}
|
||
}
|
||
|
||
Heartbeat hb;
|
||
hb.Time = GetUnixMs();
|
||
hb.Ping = (int)(g_rttEstimator.srtt * 1000.0);
|
||
std::string aw = GetActiveWindowFromJava();
|
||
strncpy(hb.ActiveWnd, aw.c_str(), sizeof(hb.ActiveWnd) - 1);
|
||
|
||
BYTE buf[sizeof(Heartbeat) + 1];
|
||
buf[0] = TOKEN_HEARTBEAT;
|
||
memcpy(buf + 1, &hb, sizeof(Heartbeat));
|
||
client->Send2Server((char*)buf, sizeof(buf));
|
||
{
|
||
uint64_t now2 = GetUnixMs();
|
||
if (now2 - g_lastHbLogMs.load(std::memory_order_relaxed) >= HB_LOG_INTERVAL_MS) {
|
||
// ACK 分支会更新 g_lastHbLogMs,这里仅在没有 ACK 时兜底打印
|
||
LOGI("Heartbeat Ping=%dms", hb.Ping);
|
||
}
|
||
}
|
||
}
|
||
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));
|
||
}
|
||
|
||
if (g_connGeneration.load(std::memory_order_acquire) == gen) {
|
||
g_running.store(false);
|
||
// 撤回本线程登记的句柄(只清自己那一个)。已经拿到 shared_ptr 副本的线程
|
||
// 会把 client 续命到发送结束,不存在悬空。
|
||
if (GetMainClient() == client) SetMainClient(nullptr);
|
||
}
|
||
LOGI("ConnectionThread exit (gen=%" PRIu64 ")", gen);
|
||
|
||
if (g_bExit == S_CLIENT_EXIT && g_jvm && g_captureClass && g_nativeExitMid) {
|
||
JNIEnv* jenv = nullptr;
|
||
bool attached = false;
|
||
if (g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6) == JNI_EDETACHED) {
|
||
g_jvm->AttachCurrentThread(&jenv, nullptr);
|
||
attached = true;
|
||
}
|
||
if (jenv) {
|
||
jenv->CallStaticVoidMethod(g_captureClass, g_nativeExitMid);
|
||
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
|
||
}
|
||
if (attached) g_jvm->DetachCurrentThread();
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ JNI
|
||
extern "C" {
|
||
|
||
JNIEXPORT jint JNICALL
|
||
Java_com_yama_client_YamaBridge_nativeInit(
|
||
JNIEnv* env, jobject,
|
||
jstring serverIp, jint serverPort,
|
||
jstring androidId, jstring deviceModel,
|
||
jstring androidVersion, jstring screenRes,
|
||
jstring username, jstring apkPath, jstring filesDir,
|
||
jstring versionName, jint versionCode)
|
||
{
|
||
// CPP-01 fix: CAS 原子地完成"检查+设置",消除 check-then-act 竞争
|
||
bool expected = false;
|
||
if (!g_running.compare_exchange_strong(expected, true)) {
|
||
LOGI("already running"); return -1;
|
||
}
|
||
|
||
auto toStr = [&](jstring js) -> std::string {
|
||
if (!js) return "";
|
||
const char* c = env->GetStringUTFChars(js, nullptr);
|
||
std::string s = c ? c : "";
|
||
env->ReleaseStringUTFChars(js, c);
|
||
return s;
|
||
};
|
||
|
||
g_serverIp = g_SETTINGS.ServerIP();
|
||
g_serverPort = g_SETTINGS.ServerPort();
|
||
g_androidId = toStr(androidId);
|
||
g_deviceModel = toStr(deviceModel);
|
||
g_androidVersion = toStr(androidVersion);
|
||
g_screenRes = toStr(screenRes);
|
||
g_username = toStr(username);
|
||
g_apkPath = toStr(apkPath);
|
||
g_filesDir = toStr(filesDir);
|
||
std::string verName = toStr(versionName);
|
||
if (!verName.empty()) g_versionName = verName;
|
||
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 导致后续调用崩溃。
|
||
if (g_jvm == nullptr) {
|
||
if (env->GetJavaVM(&g_jvm) == JNI_OK) {
|
||
jclass cls = env->FindClass("com/yama/client/ControlService");
|
||
if (cls) {
|
||
g_ctrlClass = (jclass)env->NewGlobalRef(cls);
|
||
g_ctrlMethod = env->GetStaticMethodID(g_ctrlClass, "onControlEvent", "(IJII)V");
|
||
if (!g_ctrlMethod) LOGE("ControlService.onControlEvent not found");
|
||
g_getActiveWindowMid = env->GetStaticMethodID(g_ctrlClass, "getActiveWindow", "()Ljava/lang/String;");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_getActiveWindowMid = nullptr; }
|
||
if (!g_getActiveWindowMid) LOGE("ControlService.getActiveWindow not found");
|
||
g_activityTitleMid = env->GetStaticMethodID(g_ctrlClass, "currentActivityTitle", "()Ljava/lang/String;");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_activityTitleMid = nullptr; }
|
||
if (!g_activityTitleMid) LOGE("ControlService.currentActivityTitle not found");
|
||
g_lockScreenMid = env->GetStaticMethodID(g_ctrlClass, "lockScreen", "()V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_lockScreenMid = nullptr; }
|
||
if (!g_lockScreenMid) LOGE("ControlService.lockScreen not found");
|
||
g_canLockMid = env->GetStaticMethodID(g_ctrlClass, "canLockScreen", "()Z");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_canLockMid = nullptr; }
|
||
if (!g_canLockMid) LOGE("ControlService.canLockScreen not found");
|
||
g_overlayMid = env->GetStaticMethodID(g_ctrlClass, "setPrivacyOverlay", "(ZZ)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_overlayMid = nullptr; }
|
||
if (!g_overlayMid) LOGE("ControlService.setPrivacyOverlay not found");
|
||
g_canOverlayMid = env->GetStaticMethodID(g_ctrlClass, "canOverlay", "()Z");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_canOverlayMid = nullptr; }
|
||
if (!g_canOverlayMid) LOGE("ControlService.canOverlay not found");
|
||
} else {
|
||
LOGE("ControlService class not found");
|
||
}
|
||
jclass capCls = env->FindClass("com/yama/client/CaptureService");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); capCls = nullptr; }
|
||
if (capCls) {
|
||
g_captureClass = (jclass)env->NewGlobalRef(capCls);
|
||
g_requestIdrMid = env->GetStaticMethodID(g_captureClass, "requestIdr", "()V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_requestIdrMid = nullptr; }
|
||
if (!g_requestIdrMid) LOGE("CaptureService.requestIdr not found");
|
||
// GetStaticMethodID 找不到方法时会挂起 JNI 异常;必须清除,
|
||
// 否则 nativeInit 返回时 Java 层会抛出 NoSuchMethodError 崩溃。
|
||
g_forceFirstFrameMid = env->GetStaticMethodID(g_captureClass, "forceFirstFrame", "()V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_forceFirstFrameMid = nullptr; }
|
||
if (!g_forceFirstFrameMid) LOGE("CaptureService.forceFirstFrame not found");
|
||
g_statusMid = env->GetStaticMethodID(g_captureClass, "onNativeStatus", "(Ljava/lang/String;)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_statusMid = nullptr; }
|
||
if (!g_statusMid) LOGE("CaptureService.onNativeStatus not found");
|
||
g_nativeExitMid = env->GetStaticMethodID(g_captureClass, "onNativeExit", "()V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_nativeExitMid = nullptr; }
|
||
if (!g_nativeExitMid) LOGE("CaptureService.onNativeExit not found");
|
||
g_updateReceivedMid = env->GetStaticMethodID(g_captureClass, "onUpdateReceived", "(Ljava/lang/String;)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_updateReceivedMid = nullptr; }
|
||
if (!g_updateReceivedMid) LOGE("CaptureService.onUpdateReceived not found");
|
||
g_clipboardMid = env->GetStaticMethodID(g_captureClass, "onClipboardText", "([B)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_clipboardMid = nullptr; }
|
||
if (!g_clipboardMid) LOGE("CaptureService.onClipboardText not found");
|
||
g_uninstallMid = env->GetStaticMethodID(g_captureClass, "onUninstallRequested", "()V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_uninstallMid = nullptr; }
|
||
if (!g_uninstallMid) LOGE("CaptureService.onUninstallRequested not found");
|
||
UseAndroidLog(PostStatus);
|
||
} else {
|
||
LOGE("CaptureService class not found");
|
||
}
|
||
// 屏幕预览:返回对象是 ScreenShot$Shot,JNI 签名用 '$' 写嵌套类
|
||
jclass shotCls = env->FindClass("com/yama/client/ScreenShot");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); shotCls = nullptr; }
|
||
if (shotCls) {
|
||
g_shotClass = (jclass)env->NewGlobalRef(shotCls);
|
||
g_shotCanMid = env->GetStaticMethodID(g_shotClass, "canCapture", "()Z");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_shotCanMid = nullptr; }
|
||
if (!g_shotCanMid) LOGE("ScreenShot.canCapture not found");
|
||
g_shotCaptureMid = env->GetStaticMethodID(g_shotClass, "capture",
|
||
"(II)Lcom/yama/client/ScreenShot$Shot;");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_shotCaptureMid = nullptr; }
|
||
if (!g_shotCaptureMid) LOGE("ScreenShot.capture not found");
|
||
jclass shotResultCls = env->FindClass("com/yama/client/ScreenShot$Shot");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); shotResultCls = nullptr; }
|
||
if (shotResultCls) {
|
||
g_shotDataMid = env->GetMethodID(shotResultCls, "getData", "()[B");
|
||
g_shotWidthMid = env->GetMethodID(shotResultCls, "getWidth", "()I");
|
||
g_shotHeightMid = env->GetMethodID(shotResultCls, "getHeight", "()I");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); }
|
||
if (!g_shotDataMid || !g_shotWidthMid || !g_shotHeightMid)
|
||
LOGE("ScreenShot$Shot getters not found");
|
||
} else {
|
||
LOGE("ScreenShot$Shot class not found");
|
||
}
|
||
} else {
|
||
LOGE("ScreenShot class not found");
|
||
}
|
||
// 远程交谈:ChatSession.onNativeEvent(int, byte[]) —— 入站事件与文本
|
||
jclass chatCls = env->FindClass("com/yama/client/ChatSession");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); chatCls = nullptr; }
|
||
if (chatCls) {
|
||
g_chatClass = (jclass)env->NewGlobalRef(chatCls);
|
||
g_chatEventMid = env->GetStaticMethodID(g_chatClass, "onNativeEvent", "(I[B)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_chatEventMid = nullptr; }
|
||
if (!g_chatEventMid) LOGE("ChatSession.onNativeEvent not found");
|
||
} else {
|
||
LOGE("ChatSession class not found");
|
||
}
|
||
// 远程桌面画质/帧率协商:ScreenTuning 的读写入口(见本文件上方的说明)
|
||
jclass tuningCls = env->FindClass("com/yama/client/ScreenTuning");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); tuningCls = nullptr; }
|
||
if (tuningCls) {
|
||
g_tuningClass = (jclass)env->NewGlobalRef(tuningCls);
|
||
g_getQualityLevelMid = env->GetStaticMethodID(g_tuningClass, "getQualityLevel", "()I");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_getQualityLevelMid = nullptr; }
|
||
if (!g_getQualityLevelMid) LOGE("ScreenTuning.getQualityLevel not found");
|
||
g_getMaxFpsMid = env->GetStaticMethodID(g_tuningClass, "getMaxFps", "()I");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_getMaxFpsMid = nullptr; }
|
||
if (!g_getMaxFpsMid) LOGE("ScreenTuning.getMaxFps not found");
|
||
g_onQualityLevelMid = env->GetStaticMethodID(g_tuningClass, "onQualityLevel", "(IZ)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onQualityLevelMid = nullptr; }
|
||
if (!g_onQualityLevelMid) LOGE("ScreenTuning.onQualityLevel not found");
|
||
g_onFpsMid = env->GetStaticMethodID(g_tuningClass, "onFps", "(I)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onFpsMid = nullptr; }
|
||
if (!g_onFpsMid) LOGE("ScreenTuning.onFps not found");
|
||
g_onQualityProfilesMid = env->GetStaticMethodID(g_tuningClass, "onQualityProfiles", "(Ljava/lang/String;)V");
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onQualityProfilesMid = nullptr; }
|
||
if (!g_onQualityProfilesMid) LOGE("ScreenTuning.onQualityProfiles not found");
|
||
} else {
|
||
LOGE("ScreenTuning class not found");
|
||
}
|
||
}
|
||
}
|
||
|
||
g_bExit = S_CLIENT_NORMAL;
|
||
// 历史活动采样:每秒问一次前台应用。Start 幂等(服务重启 nativeStop→nativeInit
|
||
// 不会重复起线程);采样与连接无关,断线期间照样记,随进程一起结束。
|
||
LinuxActivity::ActivityHistory::Instance().Start(ProbeActivityFromJava);
|
||
// g_running 已在 CAS 中设为 true,不重复 store
|
||
const uint64_t gen = g_connGeneration.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||
std::thread(ConnectionThread, gen).detach();
|
||
LOGI("nativeInit OK server=%s:%d", g_serverIp.c_str(), g_serverPort);
|
||
return 0;
|
||
}
|
||
|
||
JNIEXPORT void JNICALL
|
||
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
|
||
JNIEXPORT void JNICALL
|
||
Java_com_yama_client_YamaBridge_nativeReportMessage(JNIEnv* env, jobject, jstring msg)
|
||
{
|
||
if (!msg) return;
|
||
const char* c = env->GetStringUTFChars(msg, nullptr);
|
||
if (!c) return;
|
||
LOGI("REPORT: %s", c);
|
||
sendClientMsg("Android update", c);
|
||
env->ReleaseStringUTFChars(msg, c);
|
||
}
|
||
|
||
// 由 ChatSession 在用户点「发送」时调用。入参已是 GBK 字节(Kotlin 侧严格编码,
|
||
// 表示不了的字符不会落到这里);native 只补结尾 NUL 并写入交谈子连接。
|
||
JNIEXPORT jboolean JNICALL
|
||
Java_com_yama_client_YamaBridge_nativeChatSend(JNIEnv* env, jobject, jbyteArray data)
|
||
{
|
||
if (!data) return JNI_FALSE;
|
||
const jsize len = env->GetArrayLength(data);
|
||
// 与 Windows 客户端输入缓冲一致:4000 GBK 字节上限(4096 缓冲留出 NUL 与余量)
|
||
if (len <= 0 || len > 4000) return JNI_FALSE;
|
||
std::vector<uint8_t> buf((size_t)len);
|
||
env->GetByteArrayRegion(data, 0, len, (jbyte*)buf.data());
|
||
if (env->ExceptionCheck()) { env->ExceptionClear(); return JNI_FALSE; }
|
||
std::lock_guard<std::mutex> lk(g_chatMx);
|
||
if (!g_chatHandler) {
|
||
LOGI("CHAT: send dropped, no active session");
|
||
return JNI_FALSE;
|
||
}
|
||
const bool ok = g_chatHandler->SendText(buf.data(), buf.size());
|
||
LOGI("CHAT: send %d bytes -> %d", (int)len, ok ? 1 : 0);
|
||
return ok ? JNI_TRUE : JNI_FALSE;
|
||
}
|
||
|
||
// 由 CaptureService 在 MediaCodec 配置完成后调用,告知 C++ 侧实际捕获尺寸
|
||
JNIEXPORT void JNICALL
|
||
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
|
||
{
|
||
g_screenWidth.store(width);
|
||
g_screenHeight.store(height);
|
||
LOGI("ScreenSize=%dx%d", width, height);
|
||
}
|
||
|
||
// 由 CaptureService 的 MediaCodec.Callback 调用,投递 H.264 NALU
|
||
JNIEXPORT void JNICALL
|
||
Java_com_yama_client_YamaBridge_nativeOnH264Frame(
|
||
JNIEnv* env, jobject,
|
||
jbyteArray data, jint offset, jint size, jboolean isKeyframe)
|
||
{
|
||
// CPP-04 fix: 验证 offset/size 边界,防止越界读写导致崩溃
|
||
if (!data || offset < 0 || size <= 0) return;
|
||
jsize arrLen = env->GetArrayLength(data);
|
||
if ((jlong)offset + size > arrLen) {
|
||
LOGE("nativeOnH264Frame: bounds violation offset=%d size=%d arrLen=%d", offset, size, arrLen);
|
||
return;
|
||
}
|
||
|
||
jbyte* buf = env->GetByteArrayElements(data, nullptr);
|
||
if (!buf) return;
|
||
|
||
{
|
||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||
for (auto* h : g_screenHandlers)
|
||
h->OnFrameData((const uint8_t*)buf + offset, (uint32_t)size, (bool)isKeyframe);
|
||
}
|
||
|
||
env->ReleaseByteArrayElements(data, buf, JNI_ABORT);
|
||
}
|
||
|
||
} // extern "C"
|