Feature: support process management on rooted Android hosts

Android 7 起 /proc 是 hidepid=2 + SELinux,普通 APK 连其它 PID 都看不到,
因此进程管理做成 root-only:登录时探测 su(常见路径 + which su,都不行再
su -c id 兜底),有 root 才声明 CLIENT_CAP_PROCESS。否定结果只缓存 5 分钟,
避免用户误点一次「拒绝」后整个进程生命周期都用不了。

- 客户端:RootProcess.kt 通过 su 枚举 /proc、批量 kill;子连接协议与 Linux
  一致(TOKEN_PSLIST / COMMAND_KILLPROCESS / 空 TOKEN_WSLIST)。
- 服务端:MCP list_processes/kill_process 与 GUI 进程管理对无能力位的 APK
  直接回「需要 root」,不再下发 COMMAND_SYSTEM 后干等超时。

验证:Android 编译通过;模拟器上的 su 仅 root:shell 可执行,验证了非 root
拒绝路径(MCP -32005 + GUI 提示)。真 root 设备的枚举/kill 待实机验证。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
yuanyuanxiangandClaude Code committed 2026-11-16 21:26:19 +01:00
1 parent 998c16edc5
commit b7f87c958a
8 files changed
+447 -10

No files matched your search

@@ -0,0 +1,126 @@
// ProcessManagerAndroid.h - Android 进程管理(COMMAND_SYSTEM)
//
// 协议与 Linux(linux/SystemManager.h)完全一致:
// 子连接构造即发 [TOKEN_PSLIST][pid:4][名字:架构\0][完整路径\0]...
// 收到 COMMAND_PSLIST → 重发列表
// 收到 COMMAND_KILLPROCESS → [pid:4]*,杀完刷新
// 收到 COMMAND_WSLIST → 回空窗口列表(Android 没有 Windows 意义上的窗口)
//
// 能力前提:Android 7+ 的 /proc 是 hidepid=2 + SELinux untrusted_app 限制,
// 普通 APK 枚举不到其它进程。本模块只在设备有 su 时启用(登录时按
// RootProcess.isRootAvailable() 声明 CLIENT_CAP_PROCESS),非 root 设备上服务端
// 直接返回「不支持」,不会下发 COMMAND_SYSTEM。
//
// 枚举/杀进程都交给 RootProcess.kt(su shell),这里只做协议封装。
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "common/commands.h"
#include "common/logger.h"
#include "client/IOCPClient.h"
#define LOGE_PROC(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_PROC", __VA_ARGS__)
// 由 main.cpp 通过 JNI 实现(RootProcess.kt)
bool AndroidRootAvailable();
std::string AndroidProcessSnapshot(); // "pid\tcomm\texe\n"
bool AndroidKillProcesses(const std::vector<int>& pids);
class AndroidProcessManager : public IOCPManager
{
public:
explicit AndroidProcessManager(IOCPClient* client) : m_client(client)
{
// 与 Linux 一致:构造即发首包,服务端据此打开进程管理器
SendProcessList();
}
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
{
if (!szBuffer || ulLength == 0) return;
switch (szBuffer[0]) {
case COMMAND_PSLIST:
SendProcessList();
break;
case COMMAND_KILLPROCESS: {
std::vector<int> pids;
for (ULONG i = 1; i + 4 <= ulLength; i += 4) {
int32_t pid = 0;
memcpy(&pid, szBuffer + i, sizeof(int32_t));
if (pid > 1) pids.push_back(pid);
}
AndroidKillProcesses(pids);
Sleep(100); // 给内核回收留一点时间,再刷新列表
SendProcessList();
break;
}
case COMMAND_WSLIST: {
// Android 没有可枚举的桌面窗口;回空列表让服务端的窗口管理器不挂起
BYTE token = (BYTE)TOKEN_WSLIST;
if (m_client) m_client->Send2Server((char*)&token, 1);
break;
}
default:
LOGE_PROC("unhandled cmd=%d", (int)szBuffer[0]);
break;
}
}
private:
void SendProcessList()
{
if (!m_client) return;
const std::string text = AndroidProcessSnapshot();
std::vector<uint8_t> buf;
buf.reserve(64 * 1024);
buf.push_back((uint8_t)TOKEN_PSLIST);
const char* arch = (sizeof(void*) == 8) ? "arm64" : "arm";
size_t start = 0;
size_t count = 0;
while (start < text.size()) {
size_t nl = text.find('\n', start);
std::string line = text.substr(
start, nl == std::string::npos ? std::string::npos : nl - start);
start = (nl == std::string::npos) ? text.size() : nl + 1;
if (line.empty()) continue;
size_t t1 = line.find('\t');
if (t1 == std::string::npos) continue;
size_t t2 = line.find('\t', t1 + 1);
std::string pidStr = line.substr(0, t1);
std::string name = (t2 == std::string::npos)
? line.substr(t1 + 1)
: line.substr(t1 + 1, t2 - t1 - 1);
std::string path = (t2 == std::string::npos) ? "" : line.substr(t2 + 1);
const long pid = strtol(pidStr.c_str(), nullptr, 10);
if (pid <= 0) continue;
// 与 Linux 端一致:名字后面拼 ":架构",服务端按这个名字显示
name += ":";
name += arch;
const uint32_t dwPid = (uint32_t)pid;
const uint8_t* p = (const uint8_t*)&dwPid;
buf.insert(buf.end(), p, p + sizeof(dwPid));
buf.insert(buf.end(), name.begin(), name.end());
buf.push_back(0);
buf.insert(buf.end(), path.begin(), path.end());
buf.push_back(0);
++count;
}
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
LOGE_PROC("SendProcessList: %zu process(es), %zu bytes", count, buf.size());
}
IOCPClient* m_client = nullptr;
};
+152 -3
View File
@@ -43,6 +43,7 @@
// 后者拨的是 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,
@@ -292,6 +293,11 @@ static jmethodID g_utf8ToGbkMid = nullptr; // NativeText.utf8ToGbk([B)[
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};
@@ -624,6 +630,69 @@ void StopJavaCamera()
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()) {
@@ -1563,6 +1632,46 @@ static void VideoThread()
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(),几十微秒的活。
@@ -2254,9 +2363,29 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
ApplyUpdateApk(szBuffer, ulLength);
break;
case COMMAND_SYSTEM:
LOGI("COMMAND_SYSTEM (not implemented)");
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: {
@@ -2527,7 +2656,10 @@ static void ConnectionThread(uint64_t gen)
logInfo.SetCaps(LOGIN_INFOR::DefaultCaps() |
(ScreenPreviewAvailable() ? CLIENT_CAP_SCREEN_PREVIEW : 0) |
(LockScreenAvailable() ? CLIENT_CAP_LOCK_SCREEN : 0) |
(OverlayAvailable() ? CLIENT_CAP_PRIVACY_OVERLAY : 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");
@@ -2899,6 +3031,23 @@ Java_com_yama_client_YamaBridge_nativeInit(
} 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");
}
}
}
@@ -0,0 +1,122 @@
package com.yama.client
import android.os.SystemClock
import android.util.Log
import java.io.File
import java.util.concurrent.TimeUnit
/**
* 进程管理(COMMAND_SYSTEM)的 Android 端。
*
* Android 7 起 /proc 挂载带 hidepid=2,且 SELinux 的 untrusted_app 域看不到其它
* PID——普通 APK 连进程名都枚举不出来,更杀不掉别人。因此这项能力只在取得 root
* (su)的设备上声明 CLIENT_CAP_PROCESS,非 root 设备由服务端直接拒绝。
*
* 数据格式与服务端 TOKEN_PSLIST 对齐:[pid:4][名字:架构\0][完整路径\0]...
* 这里只负责产出 "pid\tcomm\texe\n" 文本,二进制封装在 native 侧
* (android/app/src/main/cpp/ProcessManagerAndroid.h),避免在 Kotlin 里重复协议常量。
*/
object RootProcess {
private const val TAG = "YAMA_PROC"
private const val SU_TIMEOUT_SEC = 6L
private const val SU_PROBE_TIMEOUT_SEC = 3L
// 否定结果只缓存 5 分钟:用户可能只是当时点了「拒绝」,重启 App 才能恢复太蠢
private const val NEGATIVE_TTL_MS = 5 * 60 * 1000L
private val suCandidates = listOf(
"/system/bin/su", "/system/xbin/su", "/sbin/su", "/su/bin/su",
"/debug_ramdisk/su", "/data/adb/ksu/bin/su", "/data/adb/magisk/su"
)
@Volatile private var cachedTrue = false
@Volatile private var cachedFalseAt = 0L
/** su 是否存在。true 永久缓存;false 只缓存 5 分钟。 */
@JvmStatic
@Synchronized
fun isRootAvailable(): Boolean {
if (cachedTrue) return true
val now = SystemClock.elapsedRealtime()
if (cachedFalseAt != 0L && now - cachedFalseAt < NEGATIVE_TTL_MS) return false
var exists = suCandidates.any { runCatching { File(it).exists() }.getOrDefault(false) } ||
runCatching {
val p = ProcessBuilder("which", "su").redirectErrorStream(true).start()
val done = p.waitFor(2, TimeUnit.SECONDS)
if (!done) { p.destroyForcibly(); false } else p.exitValue() == 0
}.getOrDefault(false)
// 路径探测对 Magisk/DenyList 之类「隐藏 su」的配置不可靠;再做一次真实调用。
// 这会触发一次 root 授权框(只在探测时),授权成功才认为有 root。
// 探测超时用 3 秒,别让登录等太久。
if (!exists) {
val out = runSu("id", SU_PROBE_TIMEOUT_SEC)
exists = out != null && out.contains("uid=0")
}
if (exists) cachedTrue = true else cachedFalseAt = now
Log.i(TAG, "root available=$exists")
return exists
}
/**
* 通过 su 枚举 /proc。返回每行 "pid\tcomm\texe",失败返回空串。
* 脚本在 root shell 里跑,应用自身的 SELinux 限制不适用。
*/
@JvmStatic
fun snapshot(): String {
if (!isRootAvailable()) return ""
// 单引号包裹的 sh 脚本;printf 的 \t \n 由 sh 解释
// comm/exe 里可能含制表符/换行(进程名可被 prctl 改成任意内容),
// 先 tr 成空格,否则 native 侧按 \t 解析会被伪造的进程名打乱。
val script =
"for p in /proc/[0-9]*; do " +
"pid=\${p##*/}; " +
"comm=\$(cat \$p/comm 2>/dev/null | tr '\\t\\n\\r' ' '); " +
"exe=\$(readlink \$p/exe 2>/dev/null | tr '\\t\\n\\r' ' '); " +
"if [ -n \"\$comm\" ]; then printf '%s\\t%s\\t%s\\n' \"\$pid\" \"\$comm\" \"\$exe\"; fi; " +
"done"
return runSu(script) ?: ""
}
/** 批量 SIGKILL。返回是否全部下发(不保证进程已退出)。 */
@JvmStatic
fun kill(pids: IntArray): Boolean {
if (!isRootAvailable() || pids.isEmpty()) return false
val list = pids.filter { it > 1 }.joinToString(" ")
if (list.isEmpty()) return false
val out = runSu("kill -9 $list")
Log.i(TAG, "kill [$list] -> ${out != null}")
return out != null
}
private fun runSu(script: String, timeoutSec: Long = SU_TIMEOUT_SEC): String? {
return runCatching {
val p = ProcessBuilder("su", "-c", script)
.redirectErrorStream(true)
.start()
// 必须在等待的同时把 stdout 读走:几百个进程的输出可能超过管道缓冲,
// 写满后子进程会阻塞,waitFor 只能等到超时。
val out = StringBuilder()
val reader = Thread {
runCatching {
p.inputStream.bufferedReader().use { out.append(it.readText()) }
}
}
reader.isDaemon = true
reader.start()
val done = p.waitFor(timeoutSec, TimeUnit.SECONDS)
if (!done) {
p.destroyForcibly()
Log.w(TAG, "su timed out")
return@runCatching null
}
reader.join(1000)
val text = out.toString()
// 用户拒绝授权时 su 通常返回非 0,且输出为空/拒绝信息
if (p.exitValue() != 0 && text.isBlank()) null else text
}.onFailure { Log.w(TAG, "su failed: $it") }.getOrNull()
}
}