Files
SimpleRemoter/android/app/src/main/cpp/main.cpp
T
yuanyuanxiang b466f568ab Fix(client): refresh RES_UPTIME on every login so host popup shows the real runtime
双击 Linux 主机浮窗显示「启动信息 2026-11-14 13:33:52 + 1.3h」:日期是对的(进程确实从
11-14 06:33 起一直在跑,期间只有 TCP 重连),错的是时长——真实 6.2d,而 1.3h 正好等于当天
09:05:53 那次重连到双击时刻的间隔。

2cbed0d 加的 RES_UPTIME(登录时刻进程已运行秒数)在 Linux/macOS/Android 里跟着 LOGIN_INFOR
一起在重连循环外只构造一次、重连时原样重发,于是永远停在进程启动那一瞬的 0;服务端做
RES_UPTIME + GetAliveTime(),加出来就只剩「本次连接时长」。Windows 没有这个问题,它的
GetLoginInfo 在连接循环里每次重建。老客户端(build Oct 31 及更早)根本不发这个字段,服务端
退回 szStartTime 字符串、LNX 按北京时间比,反而正确——这就是「老版本显示正常」的原因。

改法:LOGIN_INFOR::SetReserved(index, v) 按 '|' 位置改写单个字段(末尾空槽原样保留、超长
整体放弃、越界拒绝),三个客户端把各自复制粘贴的「拆字段改 [19]」换成一行调用,并新增
RefreshLoginUptime 在每次 SendLoginInfo 前重算 [20](含 Linux 的分组变更重发路径)。

影响:只动登录包的第 21 个字段,结构体布局、字段顺序与协议不变,老主控忽略它。
已部署的旧 build 需重新下发才会恢复正常显示。

验证:SetReserved 用 MSVC 单测(21 字段位置不变、连改两次、空槽保留、补槽、超长与越界
拒绝)。三个客户端本体未编译:本机 WSL 被安全策略拦住、Docker 引擎未启动。
2026-11-20 10:43:17 +01:00

3236 lines
148 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#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 <cstdlib>
#include <ctime>
#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 "AudioHandler.h"
#include "common/PTYHandler.h" // 远程终端(COMMAND_SHELL):与 Linux/macOS 共用 PTY 实现
#include "common/host_transfer.h" // 主机转移(COMMAND_ASSIGN_MASTER):与 Linux/macOS 共用解析与记录编解码
#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"
// 文件管理(COMMAND_LIST_DRIVE):协议体复用 common/FileManager.h,Android 只补
// 盘符映射与存储根。子连接自己建(GetServerTarget),不走 RunSubConnThread——
// 后者拨的是 g_SETTINGS 里的出厂地址,转移主机后还是连旧主控。
#include "FileManagerAndroid.h"
#include "VideoHandlerAndroid.h" // 摄像头(COMMAND_WEBCAM)
#include "ProcessManagerAndroid.h" // 进程管理(COMMAND_SYSTEM,仅 root 设备)
#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
// AudioMonitor(语音监听:AudioRecord 采集 / AudioTrack 播放)
static jclass g_audioClass = nullptr;
static jmethodID g_audioStartMid = nullptr; // AudioMonitor.start()Z
static jmethodID g_audioStopMid = nullptr; // AudioMonitor.stop()V
static jmethodID g_audioPcmMid = nullptr; // AudioMonitor.onPcm([S)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
// 文件管理:StorageHelper 提供存储根与「所有文件访问」状态;NativeText 做 GBK 转换
// (Android 的 iconv 需要 API 28,客户端 minSdk 是 21)。
static jclass g_storageClass = nullptr;
static jmethodID g_rootsMid = nullptr; // StorageHelper.roots()[Ljava/lang/String;
static jmethodID g_allFilesMid = nullptr; // StorageHelper.allFilesAccess()Z
static jclass g_textClass = nullptr;
static jmethodID g_gbkToUtf8Mid = nullptr; // NativeText.gbkToUtf8([B)[B
static jmethodID g_utf8ToGbkMid = nullptr; // NativeText.utf8ToGbk([B)[B
// 摄像头:CameraCapture.start() 返回 [w,h](null=无相机/无权限),stop() 停止采集
static jclass g_cameraClass = nullptr;
static jmethodID g_cameraStartMid = nullptr; // ()[I
static jmethodID g_cameraStopMid = nullptr; // ()V
// 进程管理:RootProcess 通过 su 枚举 /proc 与 kill
static jclass g_rootClass = nullptr;
static jmethodID g_rootAvailableMid = nullptr; // ()Z
static jmethodID g_rootSnapshotMid = nullptr; // ()Ljava/lang/String;
static jmethodID g_rootKillMid = nullptr; // ([I)Z
// 心跳日志限流:每 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();
}
// ------------------------------------------------------------------ 文件管理 JNI
// 文件管理器跑在独立子连接线程(native 线程)里,每次调用 Java 前按需 attach。
static JNIEnv* AttachJniForCall(bool* attached)
{
*attached = false;
if (!g_jvm) return nullptr;
JNIEnv* env = nullptr;
jint st = g_jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (st == JNI_EDETACHED) {
if (g_jvm->AttachCurrentThread(&env, nullptr) != JNI_OK || !env) return nullptr;
*attached = true;
} else if (st != JNI_OK || !env) {
return nullptr;
}
return env;
}
static void DetachJniForCall(bool attached)
{
if (attached && g_jvm) g_jvm->DetachCurrentThread();
}
// Java 侧返回的每条形如 "I|/storage/emulated/0|Internal storage|0"
static std::vector<AndroidStorageRoot> QueryStorageRootsFromJava()
{
std::vector<AndroidStorageRoot> roots;
if (!g_jvm || !g_storageClass || !g_rootsMid) return roots;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return roots;
jobjectArray arr = (jobjectArray)env->CallStaticObjectMethod(g_storageClass, g_rootsMid);
if (env->ExceptionCheck()) {
env->ExceptionClear();
DetachJniForCall(attached);
return roots;
}
if (arr) {
const jsize n = env->GetArrayLength(arr);
for (jsize i = 0; i < n; ++i) {
jstring js = (jstring)env->GetObjectArrayElement(arr, i);
if (!js) continue;
const char* s = env->GetStringUTFChars(js, nullptr);
if (s) {
std::string line(s);
env->ReleaseStringUTFChars(js, s);
std::vector<std::string> parts;
size_t start = 0;
while (parts.size() < 3) {
size_t bar = line.find('|', start);
if (bar == std::string::npos) break;
parts.push_back(line.substr(start, bar - start));
start = bar + 1;
}
if (parts.size() == 3) parts.push_back(line.substr(start));
if (parts.size() == 4 && parts[0].size() == 1 && !parts[1].empty()) {
AndroidStorageRoot r;
r.letter = parts[0][0];
r.path = parts[1];
r.label = parts[2];
r.removable = (parts[3] == "1");
roots.push_back(std::move(r));
}
}
env->DeleteLocalRef(js);
}
env->DeleteLocalRef(arr);
}
if (env->ExceptionCheck()) env->ExceptionClear();
DetachJniForCall(attached);
return roots;
}
bool AndroidAllFilesAccess()
{
if (!g_jvm || !g_storageClass || !g_allFilesMid) return false;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return false;
jboolean ok = env->CallStaticBooleanMethod(g_storageClass, g_allFilesMid);
if (env->ExceptionCheck()) {
env->ExceptionClear();
ok = JNI_FALSE;
}
DetachJniForCall(attached);
return ok == JNI_TRUE;
}
static std::string CallTextConvert(jmethodID mid, const std::string& in)
{
if (!g_jvm || !g_textClass || !mid || in.empty()) return in;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return in;
std::string out = in;
jbyteArray arr = env->NewByteArray((jsize)in.size());
if (arr) {
env->SetByteArrayRegion(arr, 0, (jsize)in.size(), (const jbyte*)in.data());
jobject res = env->CallStaticObjectMethod(g_textClass, mid, arr);
if (!env->ExceptionCheck() && res) {
const jsize n = env->GetArrayLength((jbyteArray)res);
out.resize((size_t)n);
if (n > 0) env->GetByteArrayRegion((jbyteArray)res, 0, n, (jbyte*)&out[0]);
env->DeleteLocalRef(res);
} else if (env->ExceptionCheck()) {
env->ExceptionClear();
out = in;
}
env->DeleteLocalRef(arr);
}
if (env->ExceptionCheck()) env->ExceptionClear();
DetachJniForCall(attached);
return out;
}
// common/FileManager.h 与 common/FileTransferV2.h 在 __ANDROID__ 下调用这两个
// 函数代替 iconv;语义与 iconv 版一致:转换失败原样返回输入。
std::string AndroidGbkToUtf8(const std::string& input)
{
return CallTextConvert(g_gbkToUtf8Mid, input);
}
std::string AndroidUtf8ToGbk(const std::string& input)
{
return CallTextConvert(g_utf8ToGbkMid, input);
}
// 存储根缓存:打开文件管理器、每次路径映射都问一遍 Java 太贵;缓存 30 秒,
// SD 卡热插拔最多延迟半分钟。
static std::mutex g_rootsMx;
static std::vector<AndroidStorageRoot> g_rootsCache;
static std::atomic<long long> g_rootsCacheAt{0};
static std::vector<AndroidStorageRoot> AndroidStorageRootsCached()
{
const long long now = (long long)time(nullptr);
{
std::lock_guard<std::mutex> lk(g_rootsMx);
if (!g_rootsCache.empty() &&
now - g_rootsCacheAt.load(std::memory_order_relaxed) < 30) {
return g_rootsCache;
}
}
std::vector<AndroidStorageRoot> roots = QueryStorageRootsFromJava();
{
std::lock_guard<std::mutex> lk(g_rootsMx);
g_rootsCache = roots;
g_rootsCacheAt.store(now, std::memory_order_relaxed);
}
return roots;
}
std::vector<AndroidStorageRoot> AndroidQueryStorageRoots()
{
return AndroidStorageRootsCached();
}
std::string AndroidMapWinPathToUnix(const std::string& winPath)
{
std::string p = winPath;
// 老式 Unix 根写法(Linux 客户端用 "/:" 表示 /),Android 上按真实路径处理
if (p.size() >= 2 && p[0] == '/' && p[1] == ':')
p.erase(0, 2);
// 文件管理器工具栏的三个 Windows 快捷按钮(桌面 / 下载 / 用户主页)下发的是
// %USERPROFILE%\...;Android 没有 Desktop,映射到内部存储根/Download 才有意义。
const std::string kProfile = "%USERPROFILE%";
if (p.compare(0, kProfile.size(), kProfile) == 0) {
std::string rest = p.substr(kProfile.size());
for (auto& c : rest) if (c == '\\') c = '/';
while (!rest.empty() && rest[0] == '/') rest.erase(0, 1);
// 服务端下发的是 "%USERPROFILE%\Desktop\"(带尾反斜杠),归一化后是
// "Desktop/",不剥掉就永远匹配不上下面的 Desktop/Downloads 分支
while (!rest.empty() && rest.back() == '/') rest.pop_back();
std::string internal;
for (const auto& r : AndroidStorageRootsCached())
if (r.letter == 'I') { internal = r.path; break; }
if (internal.empty()) return p;
if (rest == "Downloads") return internal + "/Download";
if (rest == "Desktop") return internal;
if (rest.empty()) return internal;
return internal + "/" + rest;
}
if (p.size() >= 2 && p[1] == ':' && std::isalpha((unsigned char)p[0])) {
const char letter = (char)std::toupper((unsigned char)p[0]);
std::string rest = p.substr(2);
for (auto& c : rest) if (c == '\\') c = '/';
for (const auto& r : AndroidStorageRootsCached()) {
if (r.letter != letter) continue;
if (rest.empty()) return r.path;
if (rest[0] != '/') rest.insert(rest.begin(), '/');
return r.path + rest;
}
// 盘符不存在(比如 SD 卡已拔出):保留原样,让 opendir 明确失败
Mprintf("[FileManager] unknown drive %c in '%s'\n", letter, p.c_str());
}
for (auto& c : p) if (c == '\\') c = '/';
return p;
}
// ------------------------------------------------------------------ 摄像头 JNI
bool StartJavaCamera(int* outWidth, int* outHeight)
{
if (!g_jvm || !g_cameraClass || !g_cameraStartMid) {
LOGE("CAMERA: JNI not ready");
return false;
}
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return false;
bool ok = false;
jobject res = env->CallStaticObjectMethod(g_cameraClass, g_cameraStartMid);
if (env->ExceptionCheck()) {
env->ExceptionClear();
} else if (res) {
const jsize n = env->GetArrayLength((jintArray)res);
if (n >= 2) {
jint vals[2] = { 0, 0 };
env->GetIntArrayRegion((jintArray)res, 0, 2, vals);
if (vals[0] > 0 && vals[1] > 0) {
*outWidth = vals[0];
*outHeight = vals[1];
ok = true;
}
}
env->DeleteLocalRef(res);
}
DetachJniForCall(attached);
return ok;
}
void StopJavaCamera()
{
if (!g_jvm || !g_cameraClass || !g_cameraStopMid) return;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return;
env->CallStaticVoidMethod(g_cameraClass, g_cameraStopMid);
if (env->ExceptionCheck()) env->ExceptionClear();
DetachJniForCall(attached);
}
// ------------------------------------------------------------------ 进程管理 JNI
bool AndroidRootAvailable()
{
if (!g_jvm || !g_rootClass || !g_rootAvailableMid) return false;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return false;
jboolean ok = env->CallStaticBooleanMethod(g_rootClass, g_rootAvailableMid);
if (env->ExceptionCheck()) {
env->ExceptionClear();
ok = JNI_FALSE;
}
DetachJniForCall(attached);
return ok == JNI_TRUE;
}
std::string AndroidProcessSnapshot()
{
if (!g_jvm || !g_rootClass || !g_rootSnapshotMid) return "";
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return "";
std::string out;
jstring s = (jstring)env->CallStaticObjectMethod(g_rootClass, g_rootSnapshotMid);
if (env->ExceptionCheck()) {
env->ExceptionClear();
} else if (s) {
const char* c = env->GetStringUTFChars(s, nullptr);
if (c) {
out = c;
env->ReleaseStringUTFChars(s, c);
}
env->DeleteLocalRef(s);
}
DetachJniForCall(attached);
return out;
}
bool AndroidKillProcesses(const std::vector<int>& pids)
{
if (!g_jvm || !g_rootClass || !g_rootKillMid || pids.empty()) return false;
bool attached = false;
JNIEnv* env = AttachJniForCall(&attached);
if (!env) return false;
bool ok = false;
jintArray arr = env->NewIntArray((jsize)pids.size());
if (arr) {
env->SetIntArrayRegion(arr, 0, (jsize)pids.size(), (const jint*)pids.data());
if (!env->ExceptionCheck()) {
jboolean r = env->CallStaticBooleanMethod(g_rootClass, g_rootKillMid, arr);
if (env->ExceptionCheck()) env->ExceptionClear();
else ok = (r == JNI_TRUE);
} else {
env->ExceptionClear();
}
env->DeleteLocalRef(arr);
}
DetachJniForCall(attached);
return ok;
}
std::string AndroidMapUnixToWinPath(const std::string& unixPath)
{
for (const auto& r : AndroidStorageRootsCached()) {
if (unixPath == r.path)
return std::string(1, r.letter) + ":\\";
if (unixPath.size() > r.path.size() &&
unixPath.compare(0, r.path.size(), r.path) == 0 &&
unixPath[r.path.size()] == '/') {
std::string rest = unixPath.substr(r.path.size());
for (auto& c : rest) if (c == '/') c = '\\';
return std::string(1, r.letter) + ":" + rest;
}
}
// 不在任何存储根下(例如应用沙箱里的临时路径):退回 Linux 的 "/:\..." 写法
std::string result = "/:";
result += unixPath;
for (size_t i = 2; i < result.size(); ++i)
if (result[i] == '/') result[i] = '\\';
return result;
}
// 远程交谈: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();
}
// 语音监听:native 子连接解码出 PCM → AudioMonitor.onPcm(入 AudioTrack 播放)。
// 与 DispatchChatEvent 同一套 attach/detach 套路,供 AndroidAudioHandler::OnReceive 调用。
void DispatchAudioPcm(const int16_t* samples, size_t count)
{
if (!g_jvm || !g_audioClass || !g_audioPcmMid || !samples || !count) 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;
}
jshortArray arr = jenv->NewShortArray((jsize)count);
if (arr) {
jenv->SetShortArrayRegion(arr, 0, (jsize)count, (const jshort*)samples);
if (!jenv->ExceptionCheck()) {
jenv->CallStaticVoidMethod(g_audioClass, g_audioPcmMid, arr);
}
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
jenv->DeleteLocalRef(arr);
} else {
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
}
if (attached) g_jvm->DetachCurrentThread();
}
// 开始采集:AudioMonitor.start() 内部检查 RECORD_AUDIO、建 AudioRecord/AudioTrack。
// 返回 false(没权限 / 设备没有麦克风)时调用方回报服务端并放弃本次会话。
static bool StartJavaAudio()
{
if (!g_jvm || !g_audioClass || !g_audioStartMid) {
LOGE("AUDIO: JNI not ready (cls=%p start=%p)", g_audioClass, g_audioStartMid);
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 ok = jenv->CallStaticBooleanMethod(g_audioClass, g_audioStartMid);
if (jenv->ExceptionCheck()) { jenv->ExceptionClear(); ok = JNI_FALSE; }
if (attached) g_jvm->DetachCurrentThread();
return ok == JNI_TRUE;
}
// 停止采集/播放并回收 AudioRecord/AudioTrack(Kotlin 侧会 join 采集线程,
// 返回后不会再回调 nativeAudioSendPcm)
static void StopJavaAudio()
{
if (!g_jvm || !g_audioClass || !g_audioStopMid) 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_audioClass, g_audioStopMid);
if (jenv->ExceptionCheck()) jenv->ExceptionClear();
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;
}
// 服务器连接参数。平时只在 nativeInit 里写一次,但「转移主机」会在运行期改写它,
// 而抓屏/日志/交谈/音频/终端这些子连接线程都是在自己的循环里读它去建连——std::string
// 赋值会释放旧缓冲,别的线程正拿着 c_str() 就成了悬空读。所以读写统一走下面这对
// 函数(持锁拷贝一份再连),不要直接碰这两个全局量。
static std::mutex g_targetMu;
static std::string g_serverIp;
static int g_serverPort = 443;
// 取一份目标快照。子连接与主连接建连前都先拷一份,避免读到改写中的字符串。
static void GetServerTarget(std::string& ip, int& port)
{
std::lock_guard<std::mutex> lk(g_targetMu);
ip = g_serverIp;
port = g_serverPort;
}
static void SetServerTarget(const std::string& ip, int port)
{
std::lock_guard<std::mutex> lk(g_targetMu);
g_serverIp = ip;
g_serverPort = port;
}
// 设备信息(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;
}
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ScreenSpyThread start → %s:%d size=%dx%d", ip.c_str(), port, 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);
GetServerTarget(ip, port); // 转移主机后目标会变,每轮重取
LOGI("SST[%d]: connecting %s:%d", attempt, ip.c_str(), port);
if (!client->ConnectServer(ip.c_str(), port)) {
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()
{
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ClientLogThread start → %s:%d", ip.c_str(), port);
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);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
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;
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("ChatThread start → %s:%d", ip.c_str(), port);
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);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
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_AUDIO(主控「语音监听」)→ 子连接 + 首包 TOKEN_AUDIO_START →
// CAudioDlg 弹窗后回 COMMAND_NEXT → Kotlin 侧开 AudioRecord 采集(GSM 6.10/WAV49
// 上行);主控勾选「发送语音」后下行是裸 GSM 流。协议细节见 AudioHandler.h。
// 同一时刻只允许一个会话:服务端菜单重复点击/多主控会再发 COMMAND_AUDIO,
// 第二个子连接会被服务端当重复子连接吸收,这里直接忽略。
static std::atomic<bool> g_audioInFlight{false};
static std::mutex g_audioMx;
static AndroidAudioHandler* g_audioHandler = nullptr;
static void sendClientMsg(const char* title, const char* text); // 定义在下方的在线升级段
static void AudioThread()
{
// detached 线程:异常逃出去会 std::terminate;在途标志必须无条件还回去
struct InFlightGuard {
~InFlightGuard() { g_audioInFlight.store(false); }
} guard;
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("AudioThread start → %s:%d", ip.c_str(), port);
std::unique_ptr<IOCPClient> client;
std::unique_ptr<AndroidAudioHandler> handler;
bool started = false;
try {
client = std::make_unique<IOCPClient>(g_bExit, true);
client->EnableSubConnAuth(true, g_myClientID);
// 与屏幕/日志/交谈子连接一致:必须继承配置的传输方式(WS/WSS 部署)
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("AudioThread: connect failed");
return;
}
// 构造即发 TOKEN_AUDIO_START;服务端 CAudioDlg 打开后回单字节 COMMAND_NEXT
handler = std::make_unique<AndroidAudioHandler>(client.get());
client->setManagerCallBack(handler.get(),
IOCPManager::DataProcess,
IOCPManager::ReconnectProcess);
{
std::lock_guard<std::mutex> lk(g_audioMx);
g_audioHandler = handler.get();
}
if (!handler->WaitDialogOpen(8000)) {
// Windows 客户端同样等 8 秒;超时说明服务端没接管(老服务端/对话框被关)
LOGE("AudioThread: server dialog did not open within 8s");
sendClientMsg("Audio monitor", "The audio dialog did not open on the server");
} else if (!StartJavaAudio()) {
// 常见原因:用户没给 RECORD_AUDIO,或设备没有可用麦克风
LOGE("AudioThread: AudioRecord unavailable (RECORD_AUDIO not granted?)");
sendClientMsg("Audio monitor",
"Microphone unavailable: RECORD_AUDIO permission is not granted");
} else {
started = true;
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
Sleep(200);
LOGI("AudioThread: sub-conn closed");
}
} catch (const std::exception& e) {
LOGE("AudioThread exception: %s", e.what());
}
// 先停采集(join 采集线程,保证不再回调 nativeAudioSendPcm),再摘掉全局指针,
// 最后断开回调,让 handler 析构时没有任何线程还能碰它
if (started) StopJavaAudio();
{
std::lock_guard<std::mutex> lk(g_audioMx);
g_audioHandler = nullptr;
}
if (client) client->setManagerCallBack(nullptr, nullptr, nullptr);
// 局部变量按声明逆序析构(handler 先于 client),而 IOCPClient 的析构才会等待
// 接收线程退出。显式先销毁连接,避免接收线程正卡在 OnReceive 里时 handler 已被释放。
client.reset();
handler.reset();
LOGI("AudioThread 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;
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("TerminalThread start → %s:%d", ip.c_str(), port);
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);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
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");
}
// ------------------------------------------------------------------ 文件管理
// 服务端 COMMAND_LIST_DRIVE(主控「文件管理」对话框 / MCP list_files)→ 子连接 →
// 构造即发 TOKEN_DRIVE_LIST,服务端收到后打开对话框并把这条子连接交给它。
// 每个对话框一条子连接(与 Windows/Linux 一致),因此这里不限制并发。
static std::atomic<int> g_fsOpenedHinted{0};
static void FileManagerThread()
{
// 未授予「所有文件访问」时只提示一次:文件管理器仍可用(应用目录),
// 但整机目录可能列得出来读不了,提示运维去设置里开启。
if (!AndroidAllFilesAccess() && g_fsOpenedHinted.fetch_add(1) == 0) {
sendClientMsg("File manager",
"All-files access is not granted on this device. Only the app's own "
"folders are fully accessible; enable Settings > Apps > YAMA > "
"Special app access > All files access to browse the whole storage.");
}
std::string ip; int port;
GetServerTarget(ip, port);
LOGI(">>> FileManagerThread start → %s:%d", ip.c_str(), port);
try {
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
client->EnableSubConnAuth(true, g_myClientID);
// 转移主机后目标会变,每轮重取(不能用 g_SETTINGS 里的出厂地址)
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("FileManagerThread: connect failed");
return;
}
// 列大目录时每个名字都要做 GBK 转换;把这条子连接线程常驻 attach 到 JVM,
// 避免每个目录条目两次 AttachCurrentThread/DetachCurrentThread。
JNIEnv* env = nullptr;
bool attached = false;
if (g_jvm && g_jvm->GetEnv((void**)&env, JNI_VERSION_1_6) == JNI_EDETACHED) {
if (g_jvm->AttachCurrentThread(&env, nullptr) == JNI_OK) attached = true;
}
struct JniGuard {
bool attached;
~JniGuard() { if (attached && g_jvm) g_jvm->DetachCurrentThread(); }
} jniGuard{attached};
std::unique_ptr<AndroidFileManager> handler(new AndroidFileManager(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);
handler.reset();
client.reset();
} catch (const std::exception& e) {
LOGE("FileManagerThread exception: %s", e.what());
}
LOGI(">>> FileManagerThread exit");
}
// ------------------------------------------------------------------ 摄像头
// 服务端 COMMAND_WEBCAM(主控右键「视频管理」)→ 子连接 → Camera2 采集 JPEG →
// [TOKEN_WEBCAM_DIB][isCompress][fcc=JPGD][JPEG]。服务端用 turbojpeg 直解。
// 同一时刻只允许一个会话(服务端菜单重复点击会发多条命令,第二个子连接没有意义)。
static std::atomic<bool> g_videoInFlight{false};
static std::mutex g_videoMx;
static AndroidVideoHandler* g_videoHandler = nullptr;
static void VideoThread()
{
struct InFlightGuard {
~InFlightGuard() { g_videoInFlight.store(false); }
} guard;
std::string ip; int port;
GetServerTarget(ip, port);
LOGI("VideoThread start → %s:%d", ip.c_str(), port);
try {
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
client->EnableSubConnAuth(true, g_myClientID);
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
GetServerTarget(ip, port);
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("VideoThread: connect failed");
return;
}
std::unique_ptr<AndroidVideoHandler> handler(new AndroidVideoHandler(client.get()));
client->setManagerCallBack(handler.get(),
IOCPManager::DataProcess,
IOCPManager::ReconnectProcess);
{
std::lock_guard<std::mutex> lk(g_videoMx);
g_videoHandler = handler.get();
}
if (!handler->StartCapture()) {
// 无 CAMERA 权限 / 设备无摄像头 / 被其它应用占用。服务端没收到
// BITMAPINFO 就不会弹窗口,这里回一条消息说明原因。
LOGE("VideoThread: camera unavailable");
sendClientMsg("Camera",
"Camera unavailable: grant the CAMERA permission or close the app "
"that is using it");
} else {
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
Sleep(200);
LOGI("VideoThread: sub-conn closed");
}
handler->StopCapture();
{
std::lock_guard<std::mutex> lk(g_videoMx);
g_videoHandler = nullptr;
}
client->setManagerCallBack(nullptr, nullptr, nullptr);
// 先销毁 handler 再销毁连接:接收线程可能正卡在 OnReceive 里
handler.reset();
client.reset();
} catch (const std::exception& e) {
LOGE("VideoThread exception: %s", e.what());
}
LOGI("VideoThread exit");
}
// ------------------------------------------------------------------ 进程管理
// 服务端 COMMAND_SYSTEM(主控右键「进程管理」/ MCP list_processes)→ 子连接 →
// 构造即发 TOKEN_PSLIST。只在有 su 的设备上走得到这里(登录时声明
// CLIENT_CAP_PROCESS);非 root 设备由服务端提前拒绝,客户端再兜一层提示。
static std::atomic<bool> g_procInFlight{false};
static void ProcessThread()
{
struct InFlightGuard {
~InFlightGuard() { g_procInFlight.store(false); }
} guard;
std::string ip; int port;
GetServerTarget(ip, port);
LOGI(">>> ProcessThread start → %s:%d", ip.c_str(), port);
try {
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, true));
client->EnableSubConnAuth(true, g_myClientID);
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
GetServerTarget(ip, port); // 转移主机后目标会变
if (!client->ConnectServer(ip.c_str(), port)) {
LOGE("ProcessThread: connect failed");
return;
}
std::unique_ptr<AndroidProcessManager> handler(new AndroidProcessManager(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);
handler.reset();
client.reset();
} catch (const std::exception& e) {
LOGE("ProcessThread exception: %s", e.what());
}
LOGI(">>> ProcessThread 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)
{
// title / text 必须是纯 ASCII。ClientMsg 的两个字段在服务端按 ANSI(GBK) 解释
// (2015RemoteDlg.cpp 的 `_L(msg->title)`),而本文件是 UTF-8 源码——直接传中文
// 字面量过去,主控的消息栏里就是「杞Щ涓绘満」这种乱码。要发中文得先转 GBK,
// 而 Android 的 iconv 只在 API 28+ 才有,minSdk 21 上不能依赖它。
//
// 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)
{
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
}
#endif // YAMA_TLS_CHANNEL
// ============== 主机转移(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER)==============
// 服务端「转移主机」下发的载荷是 host:port:days:shine[:transport](见
// server/2015Remote/2015RemoteDlg.cpp assignFunction),解析与记录编解码在
// common/host_transfer.h,与 Linux/macOS 共用同一份代码。
//
// 与 Windows/Linux 的语义差别:那两个平台上主连接留在原主控不动、只在下次重连时
// 才过去,另起一个实例让新主控「立刻」看到这台主机。Android 的连接状态
// (ClientAuth 的校验态、心跳 ACK 看门狗、主连接句柄、g_bExit)全是进程级单例,
// 起第二条登录连接等于把这些全部参数化——这正是「分享主机」没做的原因。所以这里
// 用「立即切换」:改目标 → 断开 → 按新地址重连。新主控立刻看到主机,代价是原主控
// 立刻失去它;为防目标写错把主机彻底弄丢,持续一分钟连不上就退回原主控。
//
// 原主控是出包时烘焙的地址,只存在内存里(g_transferOrig),绝不写回记录——恢复时
// 读到的若还是转移目标,就成了原地打转(同 linux/main.cpp 的注释)。
static std::atomic<long long> g_transferValidTo{0}; // >0 = 处于转移状态(到期时刻)
static std::atomic<bool> g_transferPending{false}; // 接收线程已写下新目标,待主循环应用
static std::atomic<long long> g_transferAppliedAt{0}; // 切到转移目标的时刻,回退判据用
static std::atomic<bool> g_transferEndEarly{false};// true = 目标主控提前归还,不是到期
static std::mutex g_transferMu;
static HostTransfer::Target g_transferPendingTarget;
static HostTransfer::Endpoint g_transferOrig; // 烘焙的主控,到期/失败时恢复用
static std::once_flag g_transferOrigOnce;
static int g_transferFailStreak = 0; // 仅连接线程访问,无需原子
// 回退判据:连续失败次数 + 已尝试时长**同时**满足才退回原主控。只看次数会被网络
// 抖动误伤——Wi-Fi 卡一下就是连续几次失败,一次正常的转移会被无声撤销。加上 60 秒
// 下限后,只有「持续一分钟都连不上」才认定目标不可用。
static const int kTransferRevertAttempts = 3;
static const long long kTransferRevertGraceSec = 60;
// 转移主机的日志与回给主控的提示里,时间/时长都转成可读文本:
// "1763... " → "2026-11-17 02:35:12 +0100"
// 7205 → "2h 00m"
static std::string FormatUnixTimeHuman(long long epochSec)
{
const time_t t = (time_t)epochSec;
struct tm tmv;
if (!localtime_r(&t, &tmv)) return std::to_string(epochSec);
char buf[32] = { 0 };
if (strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmv) == 0)
return std::to_string(epochSec);
const long off = tmv.tm_gmtoff;
char zone[16] = { 0 };
snprintf(zone, sizeof(zone), "%c%02ld%02ld",
off < 0 ? '-' : '+', labs(off) / 3600, (labs(off) % 3600) / 60);
return std::string(buf) + " " + zone;
}
static std::string FormatDurationHuman(long long seconds)
{
if (seconds < 0) seconds = 0;
const long long h = seconds / 3600;
const long long m = (seconds % 3600) / 60;
const long long s = seconds % 60;
char buf[48] = { 0 };
if (h > 0) snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
else if (m > 0) snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
else snprintf(buf, sizeof(buf), "%llds", s);
return buf;
}
static std::string TransferRecordPath()
{
return g_filesDir.empty() ? std::string() : g_filesDir + "/yama_transfer";
}
// 记录只有一行 ip:port:transport:headerEnc:valid_to(见 HostTransfer::EncodeRecord)。
// 用文件而不是 SharedPreferences:native 侧没有 JNI 上下文,分组名也是这么存的。
static void SaveTransferRecord(const HostTransfer::Target& t)
{
const std::string path = TransferRecordPath();
if (path.empty()) return;
FILE* f = fopen(path.c_str(), "w");
if (!f) { LOGI("TRANSFER: cannot write %s", path.c_str()); return; }
fputs(HostTransfer::EncodeRecord(t).c_str(), f);
fclose(f);
}
static void ClearTransferRecord()
{
const std::string path = TransferRecordPath();
if (!path.empty()) unlink(path.c_str());
}
// 把端点应用到连接参数:g_serverIp/Port 给建连用,g_SETTINGS.protoType 给子连接继承
// (子连接在各自线程里 SetDefaultProto(g_SETTINGS.protoType))。Android 没有 SHINE/HELL
// 头加密,headerEnc 段忽略。
static void ApplyEndpointToTarget(const HostTransfer::Endpoint& ep)
{
SetServerTarget(ep.ip, ep.port);
if (ep.transport >= 0)
g_SETTINGS.protoType = (char)ep.transport;
}
static void RestoreOrigTarget()
{
ApplyEndpointToTarget(g_transferOrig);
LOGI("TRANSFER: restored to %s:%d", g_transferOrig.ip.c_str(), g_transferOrig.port);
}
// 转移是否已到期。内层循环按秒判断「该不该动」,这里只回答有没有到期。
// 用 >= 而不是 >:提前归还时把到期时刻设成「现在」,同一秒内就该生效。
static bool TransferExpired()
{
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
return vt > 0 && (long long)time(nullptr) >= vt;
}
// 启动时读记录:未过期就切到转移目标,过期/损坏就删掉。只在 nativeInit 调用。
static void LoadTransferRecord()
{
const std::string path = TransferRecordPath();
if (path.empty()) return;
FILE* f = fopen(path.c_str(), "r");
if (!f) return;
char buf[512] = {};
const size_t n = fread(buf, 1, sizeof(buf) - 1, f);
fclose(f);
HostTransfer::Target t;
if (n == 0 || !HostTransfer::DecodeRecord(std::string(buf, n), t)) {
LOGI("TRANSFER: bad record, ignored and removed");
ClearTransferRecord();
return;
}
const long long now = (long long)time(nullptr);
if (!t.Active(now)) {
LOGI("TRANSFER: record expired at %s, removed", FormatUnixTimeHuman(t.validTo).c_str());
ClearTransferRecord();
return;
}
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
g_transferAppliedAt.store(now, std::memory_order_relaxed);
ApplyEndpointToTarget(t.ep);
LOGI("TRANSFER: active, target %s:%d, %s left", t.ep.ip.c_str(), t.ep.port,
FormatDurationHuman(t.validTo - now).c_str());
}
// ------------------------------------------------------------------ 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:
// 完整结构 1024 字节;老服务端 / Go 服务端只回 HeartbeatACK_OldSize(32)。
// 短包同样要喂 ACK 看门狗,否则每 60s 断开重连一次。Windows 端按
// min(ulLength, 32) 兼容(KernelManager.cpp:2413)。
if (ulLength >= 1 + (ULONG)HeartbeatACK_OldSize) {
HeartbeatACK ack = {};
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
? sizeof(HeartbeatACK)
: (size_t)(ulLength - 1);
memcpy(&ack, szBuffer + 1, copyLen);
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_AUDIO: {
// 语音监听(主控菜单「语音监听」):子连接 + 上行 GSM 6.10。需要 RECORD_AUDIO;
// 没有权限时 StartJavaAudio 失败,回报服务端而不是静默无声。
if (g_audioInFlight.exchange(true)) {
LOGI("cmd: COMMAND_AUDIO ignored (audio session already in flight)");
break;
}
LOGI("cmd: COMMAND_AUDIO → audio sub-conn");
try {
std::thread(AudioThread).detach();
} catch (const std::exception& e) {
g_audioInFlight.store(false);
LOGE("Audio 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_LIST_DRIVE: {
// 文件管理(主控右键「文件管理」/ MCP list_files):每个对话框一条子连接
LOGI("cmd: COMMAND_LIST_DRIVE → file manager sub-conn");
try {
std::thread(FileManagerThread).detach();
} catch (const std::exception& e) {
LOGE("File manager thread failed: %s", e.what());
}
break;
}
case COMMAND_WEBCAM: {
// 摄像头管理(主控右键「视频管理」)
if (g_videoInFlight.exchange(true)) {
LOGI("cmd: COMMAND_WEBCAM ignored (camera session already in flight)");
break;
}
LOGI("cmd: COMMAND_WEBCAM → camera sub-conn");
try {
std::thread(VideoThread).detach();
} catch (const std::exception& e) {
g_videoInFlight.store(false);
LOGE("Video thread failed: %s", e.what());
}
break;
}
case COMMAND_SEND_FILE_V2:
case COMMAND_FILE_COMPLETE_V2: {
// 服务端 → 客户端的 V2 上传(MCP upload_file)。落盘路径经
// FileTransferV2::SetPathMapper 注入的盘符映射转成 /storage/...。
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, nullptr);
if (result != 0) LOGE("V2 file recv error: %d", result);
break;
}
case COMMAND_UPDATE:
LOGI("cmd: COMMAND_UPDATE len=%lu", (unsigned long)ulLength);
ApplyUpdateApk(szBuffer, ulLength);
break;
case COMMAND_SYSTEM: {
// 进程管理:Android 7+ 的 /proc 受 hidepid/SELinux 限制,只有 root 能枚举。
// 非 root 设备在登录时没有声明 CLIENT_CAP_PROCESS,正常情况下服务端会先拒绝;
// 这里再兜一层,避免老服务端/直发命令时无声挂起。
if (!AndroidRootAvailable()) {
LOGI("cmd: COMMAND_SYSTEM ignored (no root)");
sendClientMsg("Process manager",
"This Android host is not rooted: process management requires root");
break;
}
if (g_procInFlight.exchange(true)) {
LOGI("cmd: COMMAND_SYSTEM ignored (process session already in flight)");
break;
}
LOGI("cmd: COMMAND_SYSTEM → process sub-conn");
try {
std::thread(ProcessThread).detach();
} catch (const std::exception& e) {
g_procInFlight.store(false);
LOGE("Process thread failed: %s", e.what());
}
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
case COMMAND_ASSIGN_MASTER: {
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
// 同一个命令字节也承载「分享主机」(buf[1] = SHARE_TYPE_YAMA,见下面单独的 case)。
if (ulLength < 3) {
LOGI("cmd: ASSIGN too short (%lu), ignored", (unsigned long)ulLength);
break;
}
if (szBuffer[1] != SHARE_TYPE_YAMA_FOREVER) {
LOGI("cmd: ASSIGN type=%d not supported on Android", (int)szBuffer[1]);
sendClientMsg("Share host", "Android client does not support sharing a host");
break;
}
HostTransfer::Target t;
const long long now = (long long)time(nullptr);
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的
// 主机就被改到一个不存在的地址上去了。
LOGI("cmd: ASSIGN malformed payload, ignored");
break;
}
// 有效期内拒绝再次转移,与 Windows KernelManager 的 now <= valid_to 判断一致。
// 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后,和它相连的只有 B,
// 于是 B 发来的转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的
// 那一台)还有机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控
// 复原,中间那一跳就成了谁也不认的孤儿。
const bool toOriginal = (t.ep.ip == g_transferOrig.ip && t.ep.port == g_transferOrig.port);
const long long active = g_transferValidTo.load(std::memory_order_relaxed);
if (now <= active) {
// 唯一的例外:目标就是原主控。那是「提前归还」,不是再转一手——B 有权把
// 主机还给 A,否则一旦转错或临时用完,只能干等到期。
// 实现上不新增状态:把到期时刻设成「现在」,走心跳循环里那条已经验证过的
// 复原路径(清记录 → 换回原地址 → 重连)。代价是 A 不可达时主机会一直重试
// A,这与自然到期完全一致,没有引入新的失败形态。
//
// 注意这里**丢弃**了命令里的天数(t.validTo):有效期描述的是「多久之后回到
// 原主控」,已经回到原主控就没有倒计时可言了。服务端对话框强制天数 > 0,
// 所以操作员必然填了一个值,日志里把它记下来免得事后对不上。
if (toOriginal) {
LOGI("cmd: ASSIGN back to original master %s:%d, ending transfer early "
"(requested validity %s ignored)",
t.ep.ip.c_str(), t.ep.port,
FormatDurationHuman(t.validTo - now).c_str());
g_transferEndEarly.store(true, std::memory_order_relaxed);
g_transferValidTo.store(now, std::memory_order_relaxed);
sendClientMsg("Transfer host",
"Transfer ended early, returning to original master (validity ignored)");
break;
}
const std::string until = FormatUnixTimeHuman(active);
const std::string remain = FormatDurationHuman(active - now);
LOGI("cmd: ASSIGN ignored, already assigned until %s (%s left)",
until.c_str(), remain.c_str());
char msg[192];
snprintf(msg, sizeof(msg),
"Host is already transferred until %s (%s left), ignored",
until.c_str(), remain.c_str());
sendClientMsg("Transfer host", msg);
break;
}
// 当前没在转移,而目标就是原主控自己:无事可做。放行只会白白断线重连一次,
// 还留下一条「到期复原到自己」的记录。
if (toOriginal) {
LOGI("cmd: ASSIGN target equals original master, ignored");
break;
}
{
std::lock_guard<std::mutex> lk(g_transferMu);
g_transferPendingTarget = t;
g_transferPending.store(true, std::memory_order_release);
}
// 先挡住后续重复下发,再落盘:落盘失败也不至于被第二条命令覆盖。
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
SaveTransferRecord(t);
LOGI("cmd: ASSIGN → %s:%d for %s", t.ep.ip.c_str(), t.ep.port,
FormatDurationHuman(t.validTo - now).c_str());
PostStatus("transfer: switching master");
break;
}
case COMMAND_SHARE:
case COMMAND_SHARE_CANCEL:
// 「分享主机」/「取消分享」:Android 尚未实现。分享要在不改主连接的前提下
// 再起一条**完整登录**的连接,而登录相关的状态(ClientAuth 校验态、心跳 ACK
// 看门狗、主连接句柄)都是进程级单例,第二条连接会把第一条的状态顶掉——
// 要做得先把它们整体参数化,属另一件事。这里明确回一条消息,别让主控那边
// 以为下发成功了(Windows 客户端在无权限时也是这么回的)。
LOGI("cmd: SHARE not supported on Android (%d)", (int)szBuffer[0]);
sendClientMsg("Share host", "Android client does not support sharing a host");
break;
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};
// 登录 szReserved[20](RES_UPTIME)是「登录这一刻进程已经运行了多少秒」,服务端再加本次
// 上线时长才是当前运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是
// 进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,
// 浮窗只显示 1.3h)。只在主线程调用(同 SendLoginInfo)。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
long long up = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - g_processStartMono).count();
info.SetReserved(RES_UPTIME, std::to_string(up > 0 ? up : 0).c_str());
}
static void ConnectionThread(uint64_t gen)
{
{
std::string ip0; int port0;
GetServerTarget(ip0, port0);
LOGI("ConnectionThread → %s:%d", ip0.c_str(), port0);
}
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); // 升级失败回报用;线程退出前撤回
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()) {
// 转移主机:接收线程只写「待应用」,地址切换必须在本线程做——g_serverIp 是
// 建连用的全局量,只能在连接生命周期的持有线程改(同 linux/main.cpp)。
// 上一轮的连接已由心跳循环 Disconnect 掉,这里换地址再连。
if (g_transferPending.exchange(false, std::memory_order_acq_rel)) {
HostTransfer::Target t;
{
std::lock_guard<std::mutex> lk(g_transferMu);
t = g_transferPendingTarget;
}
ApplyEndpointToTarget(t.ep);
g_transferFailStreak = 0;
g_transferAppliedAt.store((long long)time(nullptr), std::memory_order_relaxed);
LOGI("TRANSFER: applying %s:%d", t.ep.ip.c_str(), t.ep.port);
}
std::string ip; int port;
GetServerTarget(ip, port);
char connMsg[64];
snprintf(connMsg, sizeof(connMsg), "connect #%d → %s:%d", ++g_connAttempt, ip.c_str(), port);
PostStatus(connMsg);
clock_t c = clock();
// 传输方式每轮重喂。两个原因:一是不传 conn 的构造路径拿不到注入的
// CONNECT_ADDRESS,协议不显式喂进去就会静默按明文 TCP 直连;二是转移主机
// 可能把目标换成另一台主控,它的前端未必和原主控同构(本主控走反代的 WSS、
// 对方直连设备端口时就得是 TCP)。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (!client->ConnectServer(ip.c_str(), port)) {
snprintf(connMsg, sizeof(connMsg), "connect #%d failed errno=%d", g_connAttempt, errno);
PostStatus(connMsg);
// 转移目标连不上:连续失败且已持续一分钟,才退回原主控并清掉记录,否则一个
// 写错的地址会让这台主机彻底失联——原主控那边此时已经看不到它了。
if (g_transferValidTo.load(std::memory_order_relaxed) > 0) {
++g_transferFailStreak;
const long long tried = (long long)time(nullptr)
- g_transferAppliedAt.load(std::memory_order_relaxed);
if (g_transferFailStreak >= kTransferRevertAttempts && tried >= kTransferRevertGraceSec) {
LOGI("TRANSFER: unreachable for %s (%d tries), reverting",
FormatDurationHuman(tried).c_str(), g_transferFailStreak);
g_transferValidTo.store(0, std::memory_order_relaxed);
g_transferFailStreak = 0;
ClearTransferRecord();
RestoreOrigTarget();
PostStatus("transfer: unreachable, reverted");
}
}
Sleep(5000);
continue;
}
g_transferFailStreak = 0;
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
RefreshLoginUptime(logInfo); // 同一条连接可能是几小时前断掉后重连的,按「现在」重算
// 屏幕预览能力位按运行时状态刷新:无障碍服务在跑才声明(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) |
// Android 的进程列表/杀进程依赖 root(hidepid=2 + SELinux),
// 没有 su 就不声明,服务端据此直接回 -32005 而不是等超时。
(AndroidRootAvailable() ? CLIENT_CAP_PROCESS : 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;
}
// 转移主机与到期复原按 1 秒粒度判断。放在心跳周期(30 秒)之外是有原因的:
// 这两件事都是「到点就该动」的,等满一个周期会让 0.001 天(86 秒)这种短
// 转移晚二十多秒才生效、晚二十多秒才复原。这里只 break,真正的断开与恢复
// 由循环外的检查统一做(避免 Disconnect 被调两次)。
if (g_transferPending.load(std::memory_order_acquire) || TransferExpired())
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 (g_transferPending.load(std::memory_order_acquire)) {
PostStatus("transfer: leaving current master");
client->Disconnect();
break;
}
// 转移结束:恢复出包时烘焙的主控。Windows/Linux 由 StartClient 的 assigned
// 分支做同一件事;Android 没有重启入口,就地改回并重连。
// 两种情况都会走到这里:自然到期,以及目标主控「提前归还」(它把到期时刻设成
// 了当时,见 DataProcess 的 COMMAND_ASSIGN_MASTER 分支)。
{
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
if (TransferExpired()) {
const bool early = g_transferEndEarly.exchange(false, std::memory_order_relaxed);
LOGI("TRANSFER: %s at %s, restoring original master",
early ? "ended early" : "expired", FormatUnixTimeHuman(vt).c_str());
g_transferValidTo.store(0, std::memory_order_relaxed);
ClearTransferRecord();
RestoreOrigTarget();
PostStatus(early ? "transfer: returned by new master" : "transfer: expired, back to original");
client->Disconnect();
break;
}
}
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;
};
SetServerTarget(g_SETTINGS.ServerIP(), 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)
// 转移主机:先抓一次出包时烘焙的主控(只抓第一次——之后 g_SETTINGS.protoType 可能
// 已被转移改写,再抓就把转移目标当成原主控了),再按落盘记录切到转移目标。
// 顺序不能反:LoadTransferRecord 会改 g_SETTINGS.protoType。
std::call_once(g_transferOrigOnce, []() {
g_transferOrig.ip = g_SETTINGS.ServerIP();
g_transferOrig.port = g_SETTINGS.ServerPort();
g_transferOrig.transport = (int)(unsigned char)g_SETTINGS.protoType;
g_transferOrig.headerEnc = g_SETTINGS.iHeaderEnc;
});
LoadTransferRecord();
#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");
}
// 语音监听:AudioMonitor 的启停与下行 PCM 回调
jclass audioCls = env->FindClass("com/yama/client/AudioMonitor");
if (env->ExceptionCheck()) { env->ExceptionClear(); audioCls = nullptr; }
if (audioCls) {
g_audioClass = (jclass)env->NewGlobalRef(audioCls);
g_audioStartMid = env->GetStaticMethodID(g_audioClass, "start", "()Z");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_audioStartMid = nullptr; }
if (!g_audioStartMid) LOGE("AudioMonitor.start not found");
g_audioStopMid = env->GetStaticMethodID(g_audioClass, "stop", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_audioStopMid = nullptr; }
if (!g_audioStopMid) LOGE("AudioMonitor.stop not found");
g_audioPcmMid = env->GetStaticMethodID(g_audioClass, "onPcm", "([S)V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_audioPcmMid = nullptr; }
if (!g_audioPcmMid) LOGE("AudioMonitor.onPcm not found");
} else {
LOGE("AudioMonitor 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");
}
// 文件管理:存储根 / 全盘访问状态 + GBK 转换
jclass storageCls = env->FindClass("com/yama/client/StorageHelper");
if (env->ExceptionCheck()) { env->ExceptionClear(); storageCls = nullptr; }
if (storageCls) {
g_storageClass = (jclass)env->NewGlobalRef(storageCls);
g_rootsMid = env->GetStaticMethodID(g_storageClass, "roots", "()[Ljava/lang/String;");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_rootsMid = nullptr; }
if (!g_rootsMid) LOGE("StorageHelper.roots not found");
g_allFilesMid = env->GetStaticMethodID(g_storageClass, "allFilesAccess", "()Z");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_allFilesMid = nullptr; }
if (!g_allFilesMid) LOGE("StorageHelper.allFilesAccess not found");
} else {
LOGE("StorageHelper class not found");
}
jclass textCls = env->FindClass("com/yama/client/NativeText");
if (env->ExceptionCheck()) { env->ExceptionClear(); textCls = nullptr; }
if (textCls) {
g_textClass = (jclass)env->NewGlobalRef(textCls);
g_gbkToUtf8Mid = env->GetStaticMethodID(g_textClass, "gbkToUtf8", "([B)[B");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_gbkToUtf8Mid = nullptr; }
if (!g_gbkToUtf8Mid) LOGE("NativeText.gbkToUtf8 not found");
g_utf8ToGbkMid = env->GetStaticMethodID(g_textClass, "utf8ToGbk", "([B)[B");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_utf8ToGbkMid = nullptr; }
if (!g_utf8ToGbkMid) LOGE("NativeText.utf8ToGbk not found");
} else {
LOGE("NativeText class not found");
}
// 摄像头:CameraCapture.start()/stop()
jclass cameraCls = env->FindClass("com/yama/client/CameraCapture");
if (env->ExceptionCheck()) { env->ExceptionClear(); cameraCls = nullptr; }
if (cameraCls) {
g_cameraClass = (jclass)env->NewGlobalRef(cameraCls);
g_cameraStartMid = env->GetStaticMethodID(g_cameraClass, "start", "()[I");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_cameraStartMid = nullptr; }
if (!g_cameraStartMid) LOGE("CameraCapture.start not found");
g_cameraStopMid = env->GetStaticMethodID(g_cameraClass, "stop", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_cameraStopMid = nullptr; }
if (!g_cameraStopMid) LOGE("CameraCapture.stop not found");
} else {
LOGE("CameraCapture class not found");
}
// 进程管理:RootProcess 的 root 探测 / 进程快照 / 杀进程
jclass rootCls = env->FindClass("com/yama/client/RootProcess");
if (env->ExceptionCheck()) { env->ExceptionClear(); rootCls = nullptr; }
if (rootCls) {
g_rootClass = (jclass)env->NewGlobalRef(rootCls);
g_rootAvailableMid = env->GetStaticMethodID(g_rootClass, "isRootAvailable", "()Z");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_rootAvailableMid = nullptr; }
if (!g_rootAvailableMid) LOGE("RootProcess.isRootAvailable not found");
g_rootSnapshotMid = env->GetStaticMethodID(g_rootClass, "snapshot", "()Ljava/lang/String;");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_rootSnapshotMid = nullptr; }
if (!g_rootSnapshotMid) LOGE("RootProcess.snapshot not found");
g_rootKillMid = env->GetStaticMethodID(g_rootClass, "kill", "([I)Z");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_rootKillMid = nullptr; }
if (!g_rootKillMid) LOGE("RootProcess.kill not found");
} else {
LOGE("RootProcess class not found");
}
}
}
// V2 文件上传(服务端 → 客户端)的落盘路径同样要按盘符映射,
// 否则 "I:\\DCIM\\a.jpg" 会被 UnixPath 当成 "/DCIM/a.jpg"。
FileTransferV2::SetPathMapper([](const std::string& p) {
return AndroidMapWinPathToUnix(p);
});
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();
{
std::string ip0; int port0;
GetServerTarget(ip0, port0);
LOGI("nativeInit OK server=%s:%d", ip0.c_str(), port0);
}
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;
}
// AudioMonitor 采集线程每读一次 PCM 调一次(8kHz/16bit/单声道,长度任意)。
// 这里只做搬运动作:攒够 160 采样交给 libgsm 编码,满 1000 字节发一个 TOKEN_AUDIO_DATA。
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeAudioSendPcm(JNIEnv* env, jobject, jshortArray samples)
{
if (!samples) return;
const jsize len = env->GetArrayLength(samples);
// 采集端一次读 320 采样(40ms);给异常调用留 1 秒上限,超了直接丢
if (len <= 0 || len > 8000) return;
std::lock_guard<std::mutex> lk(g_audioMx);
if (!g_audioHandler) return;
jshort* buf = env->GetShortArrayElements(samples, nullptr);
if (!buf) return;
g_audioHandler->SendPcm((const int16_t*)buf, (size_t)len);
env->ReleaseShortArrayElements(samples, buf, JNI_ABORT);
}
// 由 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);
}
// Camera2 每帧 JPEG(CameraCapture 的 ImageReader 回调线程)
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeOnCameraJpeg(JNIEnv* env, jobject, jbyteArray data)
{
if (!data) return;
const jsize len = env->GetArrayLength(data);
if (len <= 0) return;
jbyte* buf = env->GetByteArrayElements(data, nullptr);
if (!buf) return;
{
std::lock_guard<std::mutex> lk(g_videoMx);
if (g_videoHandler)
g_videoHandler->SendJpeg((const uint8_t*)buf, (size_t)len);
}
env->ReleaseByteArrayElements(data, buf, JNI_ABORT);
}
// 摄像头采集失败(无权限 / 被占用 / 会话配置失败):回报主控消息栏
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeOnCameraError(JNIEnv* env, jobject, jstring msg)
{
if (!msg) return;
const char* c = env->GetStringUTFChars(msg, nullptr);
if (!c) return;
LOGE("CAMERA: %s", c);
sendClientMsg("Camera", c);
env->ReleaseStringUTFChars(msg, c);
}
} // extern "C"