From 445bd8bbb9878ef0880cae7faf95f2fb5797b242 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Wed, 11 Nov 2026 15:35:26 +0100 Subject: [PATCH] Feature: Support the remote terminal on Android hosts The terminal tools were Windows/Linux only because the Android client had no COMMAND_SHELL handler: the server opened a shell sub-connection and the command was silently dropped, leaving exec_command to time out. This adds the PTY path on the client and the matching server gating. Client: COMMAND_SHELL on the main connection spawns a terminal thread that opens an authenticated sub-connection, sends TOKEN_TERMINAL_START and keeps the PTY alive until the server closes it. common/PTYHandler.h is reused, with a minSdk-21 openpty built from posix_openpt/grantpt and /system/bin/sh (mksh) as the shell. A new CLIENT_CAP_TERMINAL bit lets the server reject old APKs up front with -32005. Server: the tool masks, instructions and docs matrix accept APK. While verifying, exec_command left a second echoed copy of the command line in stdout: mksh forks with ECHO still on, so input written before its line editor takes over is echoed by the line discipline in addition to the shell's own redraw. The server now waits for the shell's first output (the prompt) before sending the command and sentinel, which restores the single-echo assumption the cleaning step relies on. terminal_exec on a ready session is unaffected. Verified on the Android 15 emulator: exec_command returns clean stdout and real exit codes for id/uname/df/ls (including a failing command), and terminal_open keeps cwd across commands, pipes work and close is clean. The committed ghost.apk is stale and must be rebuilt before release; a rebuilt APK was used for this testing. Co-Authored-By: deepseek-flash --- android/app/src/main/cpp/main.cpp | 62 +++++++++++++++++++++++- common/PTYHandler.h | 47 ++++++++++++++++++ common/commands.h | 4 ++ docs/Mcp_Next_Plan.md | 1 + mcp/tools.json | 18 ++++--- server/2015Remote/McpServer.cpp | 76 +++++++++++++++++++++++------- server/2015Remote/McpServer.h | 6 +++ server/2015Remote/context.h | 8 ++++ tools/mcp_tools/make_tools_json.py | 15 +++--- 9 files changed, 205 insertions(+), 32 deletions(-) diff --git a/android/app/src/main/cpp/main.cpp b/android/app/src/main/cpp/main.cpp index 2c6cffc..1867dde 100644 --- a/android/app/src/main/cpp/main.cpp +++ b/android/app/src/main/cpp/main.cpp @@ -26,6 +26,7 @@ #include "client/IOCPClient.h" #include "ScreenHandler.h" #include "ChatHandler.h" +#include "common/PTYHandler.h" // 远程终端(COMMAND_SHELL):与 Linux/macOS 共用 PTY 实现 #define XXH_INLINE_ALL #include "common/xxhash.h" #include "common/logger.h" @@ -781,6 +782,49 @@ static void ChatThread() LOGI("ChatThread exit"); } +// ------------------------------------------------------------------ 远程终端 +// 服务端 COMMAND_SHELL → 子连接 → 首包 TOKEN_TERMINAL_START → 服务端接管后发 +// CMD_TERMINAL_RESIZE + COMMAND_NEXT → PTY 读线程开始回传 shell 输出。 +// 与 ChatThread 同一套子连接要求(ConnAuth / 传输协议),但不依赖任何 Android 权限。 +static std::atomic g_termInFlight{false}; + +static void TerminalThread() +{ + // detached 线程:异常逃出去会 std::terminate;在途标志必须无条件还回去 + struct InFlightGuard { + ~InFlightGuard() { g_termInFlight.store(false); } + } guard; + + LOGI("TerminalThread start → %s:%d", g_serverIp.c_str(), g_serverPort); + try { + std::unique_ptr client(new IOCPClient(g_bExit, true)); + client->EnableSubConnAuth(true, g_myClientID); + // 与屏幕/日志/交谈子连接一致:继承配置的传输方式,WS/WSS 部署下直连会连不上反代 + client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType); + if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) { + LOGE("TerminalThread: connect failed"); + return; + } + // 构造即 openpty + fork shell;失败会抛异常,服务端按等待超时处理 + std::unique_ptr handler(new PTYHandler(client.get())); + client->setManagerCallBack(handler.get(), + IOCPManager::DataProcess, + IOCPManager::ReconnectProcess); + // 首包告诉服务端这是 PTY 会话(决定 UTF-8 编码与 POSIX 哨兵形态)。 + // PTY 读线程要等服务端的 COMMAND_NEXT 才开始回传,初始提示符不会混进命令输出。 + BYTE bToken = TOKEN_TERMINAL_START; + client->Send2Server((char*)&bToken, 1); + while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit) + Sleep(200); + // 先摘回调再让 handler 析构(析构会停 PTY 读线程并结束 shell) + client->setManagerCallBack(nullptr, nullptr, nullptr); + LOGI("TerminalThread: sub-conn closed"); + } catch (const std::exception& e) { + LOGE("TerminalThread exception: %s", e.what()); + } + LOGI("TerminalThread exit"); +} + // ------------------------------------------------------------------ 历史活动上报 // 主连接一次性快照(与 Windows/Linux 一致,服务端 TOKEN_REPORT_ACTIVITY 分支不 CancelIO)。 // 采样机每秒问一次 ControlService 的前台应用;这里只取 Dump(),几十微秒的活。 @@ -1259,9 +1303,23 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength) break; } - case COMMAND_SHELL: - LOGI("COMMAND_SHELL (not implemented)"); + case COMMAND_SHELL: { + // 远程终端(MCP exec_command / terminal_open,或主控菜单「终端」): + // 子连接 + PTY,没有任何 Android 权限依赖。同一时刻只允许一个会话: + // 服务端本身按主机去重,这里挡住用户连点造成的重复子连接。 + if (g_termInFlight.exchange(true)) { + LOGI("cmd: COMMAND_SHELL ignored (terminal already in flight)"); + break; + } + LOGI("cmd: COMMAND_SHELL → PTY sub-conn"); + try { + std::thread(TerminalThread).detach(); + } catch (const std::exception& e) { + g_termInFlight.store(false); + LOGE("Terminal thread failed: %s", e.what()); + } break; + } case COMMAND_UPDATE: LOGI("cmd: COMMAND_UPDATE len=%lu", (unsigned long)ulLength); diff --git a/common/PTYHandler.h b/common/PTYHandler.h index d12fa88..a64531a 100644 --- a/common/PTYHandler.h +++ b/common/PTYHandler.h @@ -24,6 +24,11 @@ // Platform-specific includes #ifdef __APPLE__ #include // macOS: openpty() +#elif defined(__ANDROID__) +// Android: bionic 的 里 openpty() 是 API 23 才引入的,而客户端 minSdk 是 21。 +// 改用 API 21 就有的 posix_openpt/grantpt/unlockpt/ptsname_r 自己拼一个 openpty。 +#include +#include #else #include // Linux: openpty() #endif @@ -44,6 +49,34 @@ #include "commands.h" #include "../client/IOCPClient.h" +#ifdef __ANDROID__ +// openpty() 的 minSdk 21 兼容实现(API 21 起 posix_openpt/grantpt/unlockpt/ptsname_r 可用)。 +// 与 bionic API 23 的实现等价:开一对 master/slave,可选设置初始窗口大小。 +inline int android_openpty(int* master, int* slave, const struct winsize* ws) +{ + int m = posix_openpt(O_RDWR | O_NOCTTY); + if (m < 0) return -1; + char name[128]; + if (grantpt(m) != 0 || unlockpt(m) != 0 || ptsname_r(m, name, sizeof(name)) != 0) { + close(m); + return -1; + } + int s = open(name, O_RDWR | O_NOCTTY); + if (s < 0) { + close(m); + return -1; + } + if (ws && ioctl(m, TIOCSWINSZ, ws) != 0) { + close(m); + close(s); + return -1; + } + *master = m; + *slave = s; + return 0; +} +#endif + /** * PTYHandler - Pseudo Terminal Handler * @@ -66,9 +99,15 @@ public: } // Create pseudo terminal pair +#ifdef __ANDROID__ + if (android_openpty(&m_master_fd, &m_slave_fd, nullptr) == -1) { + throw std::runtime_error("Failed to create pseudo terminal"); + } +#else if (openpty(&m_master_fd, &m_slave_fd, nullptr, nullptr, nullptr) == -1) { throw std::runtime_error("Failed to create pseudo terminal"); } +#endif // Set master fd to non-blocking mode int flags = fcntl(m_master_fd, F_GETFL, 0); @@ -213,6 +252,14 @@ private: execl("/bin/zsh", "zsh", "-l", "-i", nullptr); } execl("/bin/bash", "bash", "-l", "-i", nullptr); +#elif defined(__ANDROID__) + // Android 没有 bash:/system/bin/sh 是 mksh,常用命令由 toybox 提供。 + // 不做 login shell(没有 /etc/profile);HOME 由 App 沙箱提供,写文件落在 + // /data/user/0/com.yama.client 下。 + setenv("LANG", "C.UTF-8", 1); + setenv("LC_ALL", "C.UTF-8", 1); + execl("/system/bin/sh", "sh", "-i", nullptr); + execl("/system/bin/sh", "sh", nullptr); #else // Linux locale settings (C.UTF-8 is most portable) setenv("LANG", "C.UTF-8", 1); diff --git a/common/commands.h b/common/commands.h index 683b14e..2a6407a 100644 --- a/common/commands.h +++ b/common/commands.h @@ -148,6 +148,7 @@ inline int isValid_10s() #define CLIENT_CAP_LOCK_SCREEN 0x1000 // 屏幕子连接处理 COMMAND_SCREEN_CTRL_ALT_DEL(Android 映射为锁屏 GLOBAL_ACTION_LOCK_SCREEN) #define CLIENT_CAP_UNINSTALL 0x2000 // 主连接处理 TOKEN_UNINSTALL(Android 拉起系统卸载确认框;Windows 客户端一直支持但不声明) #define CLIENT_CAP_REMOTE_CHAT 0x4000 // 主连接处理 COMMAND_CHAT(远程交谈子连接;Windows 一直支持但不声明,目前只有新版 Android 声明) +#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,目前只有新版 Android 声明) #define TALK_DLG_MAXLEN 1024 // 最大输入字符长度 @@ -1314,6 +1315,9 @@ typedef struct LOGIN_INFOR { caps |= CLIENT_CAP_UNINSTALL; // 远程交谈(COMMAND_CHAT → 子连接 + 应用内聊天窗口):同上,老 APK 不认识这条命令。 caps |= CLIENT_CAP_REMOTE_CHAT; + // 远程终端(COMMAND_SHELL → PTY 子连接):老 APK 里 COMMAND_SHELL 是空实现, + // 服务端据此提前拒绝 exec_command / terminal_*,而不是等子连接超时。 + caps |= CLIENT_CAP_TERMINAL; #endif return caps; } diff --git a/docs/Mcp_Next_Plan.md b/docs/Mcp_Next_Plan.md index ea7bec1..50d7c99 100644 --- a/docs/Mcp_Next_Plan.md +++ b/docs/Mcp_Next_Plan.md @@ -132,6 +132,7 @@ | 电源操作 | `TOKEN_MACHINE_MANAGE` | ✅ `power_action` | — | | 卸载主机(被控程序) | `TOKEN_UNINSTALL` | ✅ `uninstall_host`(win + apk) | Android 新版拉起系统卸载确认框,需人工确认 | | 远程交谈 | `COMMAND_CHAT` | ✅ `chat_*`(win + apk) | Android 新版弹应用内聊天窗口(能力位 `CLIENT_CAP_REMOTE_CHAT`),老 APK 返回 `-32005` | +| 远程终端 | `COMMAND_SHELL` | ✅ `exec_command` / `terminal_*`(win + lnx + apk) | Android 新版复用 `common/PTYHandler.h`(`/system/bin/sh`,能力位 `CLIENT_CAP_TERMINAL`),老 APK 返回 `-32005` | | **客户端升级** | `COMMAND_UPDATE` | ❌ | 零客户端改动,需独立评审(见 §4.4) | | **上传执行 / 下载执行** | `COMMAND_UPLOAD_EXEC` / `COMMAND_DOWN_EXEC` | ❌ | 零客户端改动,需独立评审(见 §4.4) | | **代理映射** | `COMMAND_PROXY` | ❌ | 需独立设计(见 §4.3) | diff --git a/mcp/tools.json b/mcp/tools.json index a6bf6c4..25a9a06 100644 --- a/mcp/tools.json +++ b/mcp/tools.json @@ -2140,12 +2140,13 @@ }, { "name": "exec_command", - "description": "在指定在线 Windows 或 Linux 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。", + "description": "在指定在线 Windows、Linux 或 Android 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux/Android 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。Android 上 shell 是 /system/bin/sh(mksh),可用命令由 toybox 提供。", "gate": null, "write": true, "platforms": [ "win", - "lnx" + "lnx", + "apk" ], "impl": "mfc", "inputSchema": { @@ -2189,12 +2190,13 @@ }, { "name": "terminal_open", - "description": "在指定在线 Windows 或 Linux 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux 使用 POSIX PTY(UTF-8,is_pty=true)。", + "description": "在指定在线 Windows、Linux 或 Android 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux/Android 使用 POSIX PTY(UTF-8,is_pty=true),Android 的 shell 是 /system/bin/sh(mksh)。", "gate": "terminal", "write": true, "platforms": [ "win", - "lnx" + "lnx", + "apk" ], "impl": "mfc", "inputSchema": { @@ -2233,12 +2235,13 @@ }, { "name": "terminal_exec", - "description": "在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。", + "description": "在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。", "gate": "terminal", "write": true, "platforms": [ "win", - "lnx" + "lnx", + "apk" ], "impl": "mfc", "inputSchema": { @@ -2292,7 +2295,8 @@ "write": true, "platforms": [ "win", - "lnx" + "lnx", + "apk" ], "impl": "mfc", "inputSchema": { diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 56486e5..9cbf580 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -353,9 +353,11 @@ const char* kServerInstructions = u8"无障碍服务、抓屏依赖已授权录屏,两者都没有能力位可查,命令下发成功不代表生效)," u8"卸载主机(uninstall_host,会拉起系统的卸载确认框,需要有人在设备上点确认)、" u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内," - u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK,老 APK 返回 -32005),以及 " + u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK)、远程终端(exec_command / terminal_open / " + u8"terminal_exec / terminal_close,PTY 里跑 /system/bin/sh(mksh),命令由 toybox 提供," + u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005),以及 " u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持" - u8"(客户端未实现 SYSTEM 与 SHELL)。\n" + u8"(客户端未实现 SYSTEM 等命令)。\n" u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 " u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n" u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n" @@ -2485,7 +2487,7 @@ std::string BuildToolsListResult(const Json::Value& id) { if (!CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "exec_command"; - tool["description"] = u8"在指定在线 Windows 或 Linux 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。"; + tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux/Android 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。Android 上 shell 是 /system/bin/sh(mksh),可用命令由 toybox 提供。"; tool["inputSchema"] = BuildExecCommandInputSchema(); tool["outputSchema"] = BuildExecCommandOutputSchema(); @@ -2499,7 +2501,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "terminal_open"; - tool["description"] = u8"在指定在线 Windows 或 Linux 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux 使用 POSIX PTY(UTF-8,is_pty=true)。"; + tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux/Android 使用 POSIX PTY(UTF-8,is_pty=true),Android 的 shell 是 /system/bin/sh(mksh)。"; tool["inputSchema"] = BuildTerminalOpenInputSchema(); tool["outputSchema"] = BuildTerminalOpenOutputSchema(); tools.append(tool); @@ -2507,7 +2509,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "terminal_exec"; - tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。"; + tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。"; tool["inputSchema"] = BuildTerminalExecInputSchema(); tool["outputSchema"] = BuildTerminalExecOutputSchema(); tools.append(tool); @@ -4074,11 +4076,16 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); - // Linux 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。 + // Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); - const bool posix = (clientType == "LNX"); + const bool posix = (clientType == "LNX" || clientType == "APK"); if (clientType == "MAC") - return BuildError(id, -32005, "exec_command is only supported on Windows and Linux hosts"); + return BuildError(id, -32005, "exec_command is only supported on Windows, Linux and Android hosts"); + // 老 APK 的 COMMAND_SHELL 是空实现,发下去只会拖到超时;按能力位提前拒绝。 + if (clientType == "APK" && !ctx->SupportsTerminal()) + return BuildError(id, -32005, + "Android client is too old for exec_command: " + "the APK has no COMMAND_SHELL handler, upgrade the client first"); std::string command = Trim(GetStringArg(args, "command")); if (command.empty()) @@ -4127,6 +4134,9 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy // 编码:PTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。 UINT cp = (posix || isPty) ? CP_UTF8 : 936; + // POSIX 上等 shell 打印提示符再写命令,避免驱动多回显一份输入(见 WaitTerminalBootstrap)。 + if (posix && isPty) + mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000); // 哨兵形态见 BuildSentinelLines:POSIX PTY / ConPTY 下命令与哨兵分两行下发(吞行命令 // 不再超时),老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。 std::string cmdLine, sentLine; @@ -4686,7 +4696,13 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value& CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "MAC") { - errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows and Linux hosts"); + errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows, Linux and Android hosts"); + return false; + } + if (clientType == "APK" && !ctx->SupportsTerminal()) { + errJson = BuildError(id, -32005, + "Android client is too old for the persistent terminal: " + "the APK has no COMMAND_SHELL handler, upgrade the client first"); return false; } return true; @@ -4907,7 +4923,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM std::string errJson; if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; - const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX"); + const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX" || + ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK"); std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) @@ -4965,6 +4982,10 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM if (begin != 0) return sessionError(begin); + // 新会话的第一条命令可能与 shell 启动竞争,等提示符到达再写(见 WaitTerminalBootstrap)。 + if (posix && isPty) + mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000); + std::string cmdLine, sentLine; SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); @@ -10196,7 +10217,8 @@ static const long long kBatchDeadlineMs = 50000; // ===== 平台门禁:调用前拦掉「该客户端根本没实现」的组合 ===== // // 判据来自各平台客户端对相应 COMMAND_ 的处理实现,不能看「是否引用了常量」: -// - android/.../main.cpp:534-540 的 COMMAND_SYSTEM / COMMAND_SHELL 都是空实现 +// - android/.../main.cpp 的 COMMAND_SYSTEM 是空实现;COMMAND_SHELL 从 CLIENT_CAP_TERMINAL +// 开始才有 PTY 子连接(工具内部还会按能力位二次拦截老 APK) // - macOS 能处理 SEND_FILE_V2,但 DefaultCaps() 不给 SCREEN_PREVIEW,截屏仍不可用 // 表内容与 mcp/tools.json 的 platforms 字段一一对应, // tools/mcp_tools/check_platform_table.py 会校验两边一致。 @@ -10251,11 +10273,12 @@ const ToolPlatform kToolPlatforms[] = { // COMMAND_SCREEN_CTRL_ALT_DEL:只有 Android 客户端实现(映射为系统锁屏) { "remote_lock_screen", kPlatApk }, // macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放 - // (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用 - { "exec_command", kPlatWin|kPlatLnx }, - { "terminal_open", kPlatWin|kPlatLnx }, - { "terminal_exec", kPlatWin|kPlatLnx }, - { "terminal_close", kPlatWin|kPlatLnx }, + // (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用; + // Android 新版复用 common/PTYHandler.h(/system/bin/sh),声明 CLIENT_CAP_TERMINAL + { "exec_command", kPlatWin|kPlatLnx|kPlatApk }, + { "terminal_open", kPlatWin|kPlatLnx|kPlatApk }, + { "terminal_exec", kPlatWin|kPlatLnx|kPlatApk }, + { "terminal_close", kPlatWin|kPlatLnx|kPlatApk }, // macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870) { "kill_process", kPlatWin|kPlatLnx }, // ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action @@ -10730,10 +10753,13 @@ void CMcpServer::OnTerminalData(context* subCtx, const BYTE* data, ULONG len) { TermSession& s = sit->second; if (s.done || s.closed) return; // 已结束,忽略迟到数据 s.data.insert(s.data.end(), data, data + len); + // 第一屏输出到达 = shell 已接管终端(见 WaitTerminalBootstrap)。BeginTermCommand 会清 + // data,故就绪态需要单独记一个旗标,跨命令保持。 + s.sawOutput = true; if (FindSentinel(s.data, s.nonce, s.sentPos, s.exitCode)) { s.done = true; - m_TermCv.notify_all(); } + m_TermCv.notify_all(); // 唤醒 WaitTerminalBootstrap / WaitTerminalDone } void CMcpServer::OnTerminalClosed(context* subCtx) { @@ -10780,6 +10806,22 @@ bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& i return true; } +// 写命令前等 shell 启动完成。背景:PTY 的行规程负责回显输入,交互式 shell 进入行编辑 +// 模式后会关掉 ECHO 自己回显一份;但 shell 刚 fork 出来、还没走到读循环时 ECHO 仍开着, +// 这时写进去的输入会被驱动先回显一遍,shell 再回显一遍——服务端清洗(CutThroughEchoedLine) +// 只剔一份,多出来的「提示符 + 命令行」就留在 stdout 里。Android 的 mksh 启动比 bash 慢, +// 实测 exec_command 稳定触发(terminal_exec 因会话已就绪不触发)。shell 打印第一屏 +// (提示符)即表示行编辑已接管终端,此时写入只会回显一份。超时则照常写入,不阻塞功能。 +void CMcpServer::WaitTerminalBootstrap(uint64_t device_id, int timeoutMs) { + std::unique_lock lk(m_TermMutex); + auto it = m_TermSessions.find(device_id); + if (it == m_TermSessions.end()) return; + WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), [&] { + auto jt = m_TermSessions.find(device_id); + return jt == m_TermSessions.end() || jt->second.sawOutput || jt->second.closed; + }); +} + bool CMcpServer::WaitTerminalDone(uint64_t device_id, std::vector& out, int& exitCode, bool& closed, int timeoutMs) { std::unique_lock lk(m_TermMutex); diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index e5b4c6e..3b9aeb8 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -243,6 +243,11 @@ public: // 成功 true:out=截断到哨兵前的原始字节、exitCode=0/1(进程退出无哨兵时 -1)、closed=是否进程退出。 bool WaitTerminalDone(uint64_t device_id, std::vector& out, int& exitCode, bool& closed, int timeoutMs); + // 工具线程:写命令前等 shell 启动完成(收到第一屏输出,通常是提示符)。 + // 见 OnTerminalData 注释:Android 的 mksh 启动瞬间行规程仍开 ECHO,此时写入的 + // 字节会被驱动额外回显一份,与服务端清洗逻辑(只剔一份回显)对不上。 + void WaitTerminalBootstrap(uint64_t device_id, int timeoutMs); + // 工具线程:清理终端挂起(发送失败等提前退出路径)。 void ClearTermPending(uint64_t device_id); @@ -816,6 +821,7 @@ private: int exitCode = -1; bool done = false; // 哨兵命中 bool closed = false; // TOKEN_TERMINAL_CLOSE(进程退出) + bool sawOutput = false; // 收到过任意 shell 输出(启动提示符到达 = shell 就绪) // ===== 新增(持久终端)===== std::string sessionId; // 持久会话 token(一次性 exec 为空) bool persistent = false; diff --git a/server/2015Remote/context.h b/server/2015Remote/context.h index 7b198c1..65f9e29 100644 --- a/server/2015Remote/context.h +++ b/server/2015Remote/context.h @@ -163,6 +163,14 @@ public: return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_REMOTE_CHAT) != 0; } + // 检查客户端是否处理 COMMAND_SHELL(PTY 终端子连接)。同上:Linux/Windows 客户端 + // 一直支持但不声明,只有新版 Android 声明;老 APK 里 COMMAND_SHELL 是空实现。 + bool SupportsTerminal() const { + CString caps = GetClientData(ONLINELIST_CAPABILITIES); + if (caps.IsEmpty()) return false; + return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_TERMINAL) != 0; + } + // 检查客户端是否支持远程协议切换(COMMAND_SET_PROTO)。老客户端没有这个命令, // 收到也会走 default 丢弃,服务端据此把「协议切换」菜单置灰。 bool SupportsProtoSwitch() const { diff --git a/tools/mcp_tools/make_tools_json.py b/tools/mcp_tools/make_tools_json.py index 3b22dda..9744e1d 100644 --- a/tools/mcp_tools/make_tools_json.py +++ b/tools/mcp_tools/make_tools_json.py @@ -108,13 +108,15 @@ GATE = { # # 判定依据是**服务端实际放行**,不是客户端有没有实现。两者在 macOS 上会分叉: # exec_command / terminal_* / kill_process 的客户端实现是有的,但服务端刻意拦着 -# (McpServer.cpp:3652「macOS 本轮不开放」、6870),所以标 win/lnx。 +# (McpServer.cpp:3652「macOS 本轮不开放」、6870),所以标 win/lnx(终端族另有 apk)。 +# Android 同理:COMMAND_SHELL 只有声明 CLIENT_CAP_TERMINAL 的新版 APK 才处理, +# 老 APK 由工具内部按能力位返回 -32005。 # # 分组依据(全部经代码核对): # 全平台 —— 只读写服务端本地数据,与客户端平台无关 # win/lnx/mac —— client/、linux/、macos/ 都有该命令的处理分支,且服务端不拦 # win/lnx —— 远程控制只实现于 Windows/Linux(McpServer.cpp:2728); -# 以及 macOS 客户端有实现但服务端未开放的 exec_command / terminal_* / kill_process +# 以及 macOS 客户端有实现但服务端未开放的 kill_process # 仅 win —— 服务/注册表/键日志/活动历史/文件写/块输入/host_* /power_action # (power_action 实际走 TOKEN_MACHINE_MANAGE,不是通用电源命令) # @@ -160,10 +162,11 @@ PLATFORMS = { # macOS 客户端有 PTY 实现(macos/main.mm:753 起 ShellworkingThread),但服务端 # 本轮刻意不开放(McpServer.cpp:3652 注释「macOS 本轮不开放」),故实际不可用。 - "terminal_open": _WL, - "terminal_exec": _WL, - "terminal_close": _WL, - "exec_command": _WL, + # Android 新版复用 common/PTYHandler.h,声明 CLIENT_CAP_TERMINAL 后服务端才放行。 + "terminal_open": _WLA, + "terminal_exec": _WLA, + "terminal_close": _WLA, + "exec_command": _WLA, # macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870) "kill_process": _WL,