#include "stdafx.h" #include "McpServer.h" #include "jsoncpp/json.h" #include "HostJson.h" // BuildHostJson(单台主机序列化公共函数) #include "context.h" // context 接口 #include "2015RemoteDlg.h" // CMy2015RemoteDlg 成员(m_HostList/m_cs/m_ClientMap)+ VERSION_STR #include "WebService.h" // 远程控制复用屏幕子连接(StartRemoteDesktop / GetScreenContext / GetScreenSize) #include "Server.h" // CONTEXT_OBJECT 定义(GetScreenContext 返回 CONTEXT_OBJECT* → context* 上转型) #include "LangManager.h" // _TR(审计日志标题语言映射) #include "common/file_upload.h" // V2 文件传输(RecvFileChunkV2 / HandleFileCompleteV2 / 包结构) #include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用) #include "McpMachine.h" // 主机管理 / 连接管理工具族 #include "McpChat.h" // 远程交谈工具族 #include "McpBuildClient.h" // 生成客户端工具族(build_client) #include #include #ifndef _WIN64 #ifdef _DEBUG #pragma comment(lib, "jsoncpp/jsoncppd.lib") #else #pragma comment(lib, "jsoncpp/jsoncpp.lib") #endif #else #ifdef _DEBUG #pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib") #else #pragma comment(lib, "jsoncpp/jsoncpp_x64.lib") #endif #endif // P6 download_file 复用 V2 落盘接口,需 FileManagerDlg 同款密码哈希 / HMAC 参数 // (声明见 CPasswordDlg.h,避免在此引入重量级 MFC 头)。 std::string GetPwdHash(); std::string GetHMAC(int offset); // 共享助手(JsonToString/BuildResult/ParseHostIdArg/FindMainContext/ToUtf8/ToAnsi/...) // 已抽到 McpInternal.cpp;此处引入后调用点保持原样。 using namespace McpInternal; namespace { // JSON-RPC id 的「展示文本」:字符串 id 取原文、整数 id 取十进制数字。 // 与紧凑序列化(字符串带引号)相对:mcp_list_sessions 输出的是文本,调用方原样 // 回传给 mcp_cancel_session / notifications/cancelled 也能命中。 std::string McpRequestIdText(const Json::Value& v) { if (v.isString()) return v.asString(); if (v.isInt64()) return std::to_string(v.asInt64()); if (v.isUInt64()) return std::to_string(v.asUInt64()); return JsonToString(v); // 其余类型(null / 浮点)不会出现在 tools/call 的 id 上 } } // namespace // ============================================================================ // P11:progress / cancelled —— 在飞调用上下文与 SSE 进度通道 // ============================================================================ // // 传输层事实:本服务端每个 POST 只回一个 JSON 响应,没有 SSE。MCP Streamable HTTP // 允许(并要求客户端接受)POST 的响应是 text/event-stream——带 _meta.progressToken // 的 tools/call 就走这条路径:工具在独立线程执行,进度通知与最终响应都从同一个 // chunked 流写出。不需要额外的 GET 流,也不影响不带 token 的请求(仍是一次性 JSON)。 namespace { // 客户端读得慢时最多积压的进度通知条数:进度是「最新值有意义」的信号,丢最旧的。 const size_t kProgressQueueMax = 64; std::string SseMessage(const std::string& json) { return "event: message\ndata: " + json + "\n\n"; } // 进度数值:本服务端的进度都是整数(字节/文件数/条数)。%g 只有 6 位有效数字, // 67108864 会被写成 6.71089e+07 —— 客户端拿它算百分比就偏了,故整数值按十进制整数 // 输出;非整数(理论上的比例值)才退回 %g。 std::string FormatProgressNum(double v) { char buf[64]; if (v >= -9.0e15 && v <= 9.0e15 && v == (double)(long long)v) _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%lld", (long long)v); else _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%g", v); return buf; } } // namespace // 一次 SSE 请求的写出队列。工具线程 Push,httplib 的 content provider 线程 Pump。 struct McpProgressChannel { std::mutex mu; std::condition_variable cv; std::deque events; bool finished = false; std::string finalBody; // 反向引用用 weak_ptr:McpCallContext 持有 channel,不能形成循环。 std::weak_ptr call; void Push(std::string ev) { std::lock_guard lk(mu); if (events.size() >= kProgressQueueMax) events.pop_front(); events.push_back(std::move(ev)); cv.notify_one(); } void Finish(std::string body) { { std::lock_guard lk(mu); finalBody = std::move(body); finished = true; } cv.notify_one(); } // 由 httplib 反复调用:有事件就写一条,收尾时写最终响应并结束流。 // 客户端提前断开(write 失败)→ 置取消位,让仍在跑的工具尽快停下并清理。 bool Pump(httplib::DataSink& sink) { std::unique_lock lk(mu); while (events.empty() && !finished) cv.wait_for(lk, std::chrono::milliseconds(500)); if (!events.empty()) { std::string ev = std::move(events.front()); events.pop_front(); lk.unlock(); if (!sink.write(ev.data(), ev.size())) { if (auto c = call.lock()) c->cancelled.store(true); return false; } return true; } std::string body = std::move(finalBody); lk.unlock(); std::string ev = SseMessage(body); sink.write(ev.data(), ev.size()); // 写失败也要收尾(客户端已走,done 自己会跳过) // 必须显式收尾:httplib 的 chunked provider 在返回 false 时不会补终止块 // (write_content_chunked 直接返回 Canceled),客户端会看到「传输被截断」 // —— curl 报 18,.NET 报 "Unable to read data from the transport connection"。 // done() 会写出 0\r\n\r\n 并把 data_available 置 false,因此这里返回 true, // 让 provider 循环按正常结束退出。 sink.done(); return true; } }; void McpCallContext::EmitProgress(double current, double total, bool hasTotal) { if (!hasProgressToken || !channel) return; { std::lock_guard lk(progressMu); const auto now = std::chrono::steady_clock::now(); if (lastProgressAt.time_since_epoch().count() != 0 && now - lastProgressAt < std::chrono::milliseconds(1000)) return; lastProgressAt = now; } std::string json = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":{\"progressToken\":"; json += progressTokenJson; json += ",\"progress\":"; json += FormatProgressNum(current); if (hasTotal) { json += ",\"total\":"; json += FormatProgressNum(total); } json += "}}"; channel->Push(SseMessage(json)); } // 「当前线程正在跑的 MCP 调用」上下文。工具实现(含 McpMachine.cpp / McpChat.cpp)在 // 工具线程上直接取它,MFC 的 IO/UI 线程永远是空的。 // // 这里刻意不用 C++ 的 thread_local:本工程有一部分代码跑在 shellcode / MemoryModule // 手工映射出来的线程上(见 common/SafeString.h 的同类告警),实测给服务端加一个静态 // thread_local(哪怕只是一个 int)就会让进程启动约 1s 后跳飞。改用 FLS(Fiber Local // Storage):纯 Win32 的每线程槽,不依赖 PE 的 TLS 目录,线程退出时由系统回调释放。 namespace { DWORD g_mcpCallSlot = FLS_OUT_OF_INDEXES; using McpCallSlotPtr = std::shared_ptr*; void NTAPI McpCallSlotDetach(void* p) { delete static_cast(p); } // 静态构造时取槽位:FlsAlloc 只为整个进程分配一个索引,与线程数无关。 struct McpCallSlotInit { McpCallSlotInit() { g_mcpCallSlot = FlsAlloc(McpCallSlotDetach); } } g_mcpCallSlotInit; inline McpCallSlotPtr LoadCallSlot() { if (g_mcpCallSlot == FLS_OUT_OF_INDEXES) return nullptr; return static_cast(FlsGetValue(g_mcpCallSlot)); } } // namespace std::shared_ptr CurrentMcpCall() { McpCallSlotPtr p = LoadCallSlot(); return p ? *p : std::shared_ptr(); } bool McpCallCancelled() { McpCallSlotPtr p = LoadCallSlot(); return p && *p && (*p)->IsCancelled(); } void McpCallProgress(double current) { McpCallSlotPtr p = LoadCallSlot(); if (p && *p) (*p)->EmitProgress(current, 0, false); } void McpCallProgress(double current, double total) { McpCallSlotPtr p = LoadCallSlot(); if (p && *p) (*p)->EmitProgress(current, total, true); } namespace { // 作用域内把当前线程的在飞上下文设为 call,离开时恢复上一层(普通路径与 SSE 工具线程共用)。 // 所有权:槽里保存的是堆上那份 shared_ptr 副本,离开时 delete 掉(释放本层引用); // 上一层指针仍由外层 McpCallScope 拥有,这里只把槽位恢复回去。 struct McpCallScope { explicit McpCallScope(std::shared_ptr c) { prev_ = LoadCallSlot(); auto slot = new std::shared_ptr(std::move(c)); if (g_mcpCallSlot == FLS_OUT_OF_INDEXES || !FlsSetValue(g_mcpCallSlot, slot)) { delete slot; // 取不到槽位时退化为「本线程没有在飞调用」,工具照常执行 return; } set_ = true; } ~McpCallScope() { if (!set_) return; delete LoadCallSlot(); // 释放本层持有的引用(槽位里的那份) FlsSetValue(g_mcpCallSlot, prev_); } McpCallScope(const McpCallScope&) = delete; McpCallScope& operator=(const McpCallScope&) = delete; private: McpCallSlotPtr prev_ = nullptr; bool set_ = false; }; // 切片上限:取消后工具层最多再等这么久就回到自己的超时清理分支。 const int kWaitCancelSliceMs = 500; std::chrono::steady_clock::time_point DeadlineAfter(int timeoutMs) { return std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); } // 带取消的有限期等待:把一次长等待切成 ≤500ms 的片,每片之间检查取消位。 // 返回 pred 是否满足;超时与取消都返回 false —— 调用方按各自既有的超时分支清理, // 取消本身不需要另写一条清理路径(失败结果由分发层统一改写成 -32800)。 template bool WaitWithCancel(std::unique_lock& lk, std::condition_variable& cv, std::chrono::steady_clock::time_point deadline, Pred pred) { for (;;) { if (pred()) return true; if (McpCallCancelled()) return false; const auto now = std::chrono::steady_clock::now(); if (now >= deadline) return false; auto slice = deadline - now; if (slice > std::chrono::milliseconds(kWaitCancelSliceMs)) slice = std::chrono::milliseconds(kWaitCancelSliceMs); cv.wait_for(lk, slice); } } } // namespace namespace { // P2b 工具等待响应的超时(ms)改为运行期可配:CMcpServer::ToolTimeoutMs(),默认 20000, // 由 settings.ini 的 [settings] McpToolTimeoutMs 覆盖(见 2015RemoteDlg 的 MCP 初始化块)。 // initialize.instructions(MCP 2025-06-18 起为 result 的顶层字段)。模型看不到 docs/, // 这套服务端的「隐性知识」只能靠这里讲清楚:主机 id 的来源与形态、工具的可见性与开关、 // 错误码对应的动作、典型任务编排、以及「一台主机同时只能有一个请求在飞」的约束。 // 用 u8 字面量拼接:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK。 const char* kServerInstructions = u8"这是 YAMA 主控服务端的 MCP 端点,用于读取并操作已上线的主机(被控端)。以下规则优先于各个工具的描述。\n" u8"\n" u8"1) 主机 id\n" u8"id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算,不要猜测、也不要把示例值当真。" u8"需要 id 时先用 list_hosts 取得(默认只列在线;include_offline=true 连离线一起列);离线主机除 " u8"host_set_remark、host_set_watch_level 外都不能操作。拿不到 id 就向用户确认。\n" u8"\n" u8"2) 工具的可见性与开关\n" u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、" u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、" u8"远程交谈(chat)、生成客户端(build)各有独立开关。工具不在列表里通常就不可用,直接调用会被拒(-32006 或 -32005);" u8"例外是下文提到的降级别名(list_processes / list_windows / list_services、operate_window / " u8"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——" u8"它们不在列表里但仍可调用。" u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具," u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level / build_client 仍会列出,调用时才被拒;" u8"get_keylog 只受 McpKeylog 开关控制(与只读模式无关):开关关闭时它不在列表里;只读模式下" u8"只是它的 clear / set_offline 参数被拒,读取不受影响。\n" u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / " u8"win32_services 等,支持 pid/title/status 等服务端过滤,字段更全),list_processes / " u8"list_windows / list_services 是它在 McpMachine=0 时的降级路径。窗口与服务控制同样只有一套" u8"名字(需 McpManage=1):McpMachine=0 时是 operate_window / control_service,开启后是 " u8"host_control_window / host_control_service;后者也接受 close/show 与 set_auto/set_manual" u8"(转给前一套实现)。危险的主机管理动作目前只有两类——冻结/恢复进程、stop/restart 服务——" u8"另需 McpMachineDangerous=1:工具照常列出,调用时返回 -32006。\n" u8"\n" u8"3) 错误码与动作\n" u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n" u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁," u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长," u8"用 mcp_list_sessions 可看全部会话。确需打断用 mcp_cancel_session,但它只能取消在飞调用(kind=call);" u8"持久会话要按类型关闭(id 与 session_id 都要给):terminal → terminal_close,remote_control → remote_close," u8"chat → chat_close。pending / file_transfer 是某次在飞调用的等待态,取消那次调用就一并释放。\n" u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n" u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n" u8"-32006 策略拒绝:开关未开、只读模式,或目标端能力不足(老客户端不声明 CLIENT_CAP_V2 时," u8"download_file / upload_file / read_file / copy_files_c2c 会返回 -32006),重试无效:" u8"前者需管理员改服务端配置,后者需升级客户端。\n" u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n" u8"-32012 参数被校验拒绝(命令里的 shell 元字符、控制字符等):按 message 修正参数后重试。" u8"历史版本用 -32008 表示同一语义,遇到时按同样方式处理。\n" u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n" u8"-32001 多为超时,也可能是工具自身失败或已被取消:先看 message。是超时时,工具支持 timeout_ms " u8"就先加大重试一次,不支持就缩小范围(分页、限定目录/单台)再试;子连接/会话没建立、同一主机" u8"反复超时通常重试无效(主机卡住、链路断、老客户端不认命令),先用 mcp_list_sessions 观察;" u8"message 写 Request cancelled 的表示客户端已中止,可直接重试;http_probe 解析失败、" u8"目标端未确认写入等其他 -32001 按 message 处理,加大 timeout_ms 没用。\n" u8"-32800 请求被取消:这是客户端自己取消(notifications/cancelled / mcp_cancel_session / 连接断开)" u8"导致的中止,不是主机故障;主机占用已释放,可以直接重试。\n" u8"-32602 参数错误:按 message 修正后重试。\n" u8"\n" u8"4) 典型编排\n" u8"看主机:get_host_detail 先看 clientType 与 monitors,再决定用哪些工具;列表结果是快照," u8"主机可能在你操作期间掉线。\n" u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条," u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ 看文本内容用 read_file(按字节解码,自动识别 UTF-8/GBK," u8"offset=-N 看尾部,不要用 type/Get-Content 读配置和日志)→ download_file 取回、upload_file 送到目标。" u8"注意 local_dir / local_path 指 MCP 服务端(主控)所在机器的本地路径,不是模型或用户所在机器的路径。" u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关)," u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、" u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。" u8"列表结果按 limit/offset 分页,total 是命中数、totalAll 是过滤前的总数。\n" u8"进程排查:host_inspect(aspects=[\"processes\"])或 list_processes 定位,kill_process 结束。这类动作没有真实回执," u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n" u8"GUI 自动化:remote_open 取得 session_id 与分辨率(screen_w/screen_h)→ get_screenshot 看画面 → " u8"get_foreground_window 确认前台窗口(或用 remote_mouse / remote_keyboard 的 expect_hwnd 做前置校验)→ " u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。" u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(Windows/Android;必须带 max_block_ms,到期自动解除;" u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n" u8"命令执行:exec_command 一次性取输出(受白名单约束);同一主机已有持久终端会话时它会被 -32003 拒绝" u8"(改用 terminal_exec 复用该会话,或 terminal_close(id, session_id) 立刻关掉;空闲会话 300s 后会在下一次" u8" exec_command / terminal_* 调用时自动回收)。terminal_exec 无需先 terminal_open:带 command 时" u8"自动复用或创建该主机的持久会话(cwd/环境变量跨命令保持,闲置 300 秒回收),结果里带回 session_id," u8"后续轮询用它;只有需要显式管理会话时才用 terminal_open / terminal_close。\n" u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名," u8"不跟随重定向,响应体上限 64KB),不要为此自己写 Invoke-WebRequest / curl;Windows 与 Linux 可用," u8"macOS 与 Android 不支持。\n" u8"生成客户端:用户说「生成一个连某地址的 Linux/Windows 客户端」时用 build_client(需开启 build 开关且关闭只读)。" u8"它把模板 patch 成本主控的上线配置后写到服务端本机,结果里 path 是服务端路径;要送到目标机再用 upload_file" u8"(Windows/Linux/macOS 可用,Android 需用户自行安装),但 macOS/Android 的产物还需要重签(结果 tips 会给出命令)。" u8"host/port 省略时取服务端当前有效主控地址。已存在同名文件默认拒绝,需要覆盖时显式传 overwrite=true。\n" u8"\n" u8"5) 客户端平台差异\n" u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 " u8"list_hosts / get_host_detail 的 capabilities.platform 确认,宁可先查一次,不要先试后错。\n" u8"支持面从宽到窄依次是 win > lnx > apk ≈ mac:Windows 是唯一全量支持的平台,Linux 次之," u8"Android 与 macOS 只覆盖一部分(Android 偏远程控制与截屏,macOS 偏文件与进程)。拿不准时按这个顺序假设。\n" u8"win(EXE / DLL / MEXE / SC / MDLL):全部工具可用。\n" u8"lnx(LNX):不支持服务、注册表、键日志、文件搜索/删除/移动/建目录、" u8"窗口列表(list_windows)与窗口信息(get_foreground_window)、网络连接列表与断开" u8"(list_network_connections / kill_network_connection)、" u8"块输入、host_* 全族(host_set_remark / host_set_watch_level 除外,它们只改服务端本地数据," u8"任何平台都可用)、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机" u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n" u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / " u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、" u8"活动历史(get_activity_history)、" u8"exec_command、terminal_open / terminal_exec / terminal_close" u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process、http_probe;" u8"文件传输、进程列表、日志可用。\n" u8"apk(APK):支持主机列表(list_hosts)/ 详情 / 搜索 / " u8"审计日志 / 服务状态 / 会话管理、运行日志(get_client_log)、活动历史" u8"(get_activity_history,前台应用停留记录)、截屏(get_screenshot,只支持 mode=screen," u8"要靠无障碍服务 takeScreenshot,Android 11+ 且开启无障碍才行),远程控制全族" u8"(remote_open / remote_close / remote_mouse / remote_keyboard / remote_clipboard," u8"输入被翻译成触摸手势与 ESC(返回)/ HOME(桌面)/ APPS(任务列表)/ PRINTSCREEN(截屏)" u8"等全局动作,只支持整屏目标;remote_lock_screen 用系统的锁屏动作;注入依赖" u8"无障碍服务、抓屏依赖已授权录屏,两者都没有能力位可查,命令下发成功不代表生效)," u8"卸载主机(uninstall_host,会拉起系统的卸载确认框,需要有人在设备上点确认)、" u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内," 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 等命令)。\n" u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 " u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n" u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)" u8"可能表现为 -32001 超时,平台门禁 McpPlatformGuard=0 关闭时也会这样。反之,遇到超时" u8"也别直接当成平台不支持,先按上面的矩阵确认平台。\n" u8"\n" u8"6) 安全约定\n" u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。" u8"涉及删除、重启、结束进程、关机等不可逆操作时,先把目标和影响范围讲给用户,得到确认再执行。" u8"主机上可能有人正在办公,注入输入、截屏、关机都是会被察觉的动作。"; // initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo + instructions) std::string BuildInitializeResult(const Json::Value& id) { Json::Value result(Json::objectValue); result["protocolVersion"] = "2025-06-18"; Json::Value caps(Json::objectValue); caps["tools"] = Json::Value(Json::objectValue); result["capabilities"] = caps; Json::Value serverInfo(Json::objectValue); serverInfo["name"] = "yama"; serverInfo["version"] = VERSION_STR; result["serverInfo"] = serverInfo; result["instructions"] = kServerInstructions; return BuildResult(id, result); } // ping 健康检查:返回空 result std::string BuildPingResult(const Json::Value& id) { return BuildResult(id, Json::Value(Json::objectValue)); } // ========== P2a 通用辅助 ========== // 读取 tools/call 的入参(MCP 规范:params.arguments 为工具入参对象) Json::Value GetCallArguments(const Json::Value& params) { if (params.isObject() && params.isMember("arguments") && params["arguments"].isObject()) return params["arguments"]; return Json::Value(Json::objectValue); } // ========== P2b 辅助 ========== // 从 "title|status|pid|r1|r2" 解析(自末尾 4 个 '|' 反推),兼容只有标题的老客户端。 // 逻辑复刻 SystemDlg.cpp::ParseWindowAttrs。 void ParseWindowAttrsStr(const char* s, std::string& title, std::string& status, uint64_t& pid) { title.clear(); status = "normal"; pid = 0; if (!s || !*s) return; std::string t(s); int len = (int)t.size(); int pipePos[4] = { -1, -1, -1, -1 }; int cnt = 0; for (int i = len - 1; i >= 0 && cnt < 4; --i) { if (t[i] == '|') pipePos[cnt++] = i; } if (cnt < 4) { // 老格式:只有标题 title = t; return; } pid = strtoull(t.c_str() + pipePos[2] + 1, nullptr, 10); status = t.substr(pipePos[3] + 1, pipePos[2] - pipePos[3] - 1); title = t.substr(0, pipePos[3]); } // 解析 TOKEN_PSLIST 缓冲(data[0]=token,其后为 [pid:4][name:arch\0][path\0] 记录)。 // 进程名/路径为客户端 ANSI(编码由 cp 指定),转 UTF-8 输出。 Json::Value ParseProcessList(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 2) return arr; const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; // 跳过 TOKEN 字节 while (off + sizeof(DWORD) <= len) { DWORD pid = *(const DWORD*)(p + off); off += sizeof(DWORD); const char* exeFile = p + off; size_t exeLen = BoundedStrlen(exeFile, len - off); if (exeLen >= len - off) break; // 未以 '\0' 结尾,异常数据 if (exeLen == 0) break; // 空进程名 = 尾部零填充(LocalSize 对齐),停止解析 off += exeLen + 1; const char* fullPath = p + off; size_t pathLen = BoundedStrlen(fullPath, len - off); if (pathLen >= len - off) break; off += pathLen + 1; std::string name(exeFile, exeLen); std::string arch; size_t colon = name.find(':'); if (colon != std::string::npos) { arch = name.substr(colon + 1); name = name.substr(0, colon); } Json::Value item(Json::objectValue); item["pid"] = (Json::UInt64)pid; item["name"] = ToUtf8(name.c_str(), cp); item["arch"] = arch.empty() ? "N/A" : ToUtf8(arch.c_str(), cp); item["path"] = ToUtf8(fullPath, cp); arr.append(item); } return arr; } // 解析 TOKEN_WSLIST 缓冲(data[0]=token,其后为 [hwnd:4][title|status|pid|r1|r2\0] 记录)。 // 窗口标题为客户端 UTF-8(老客户端为 CP_ACP),用 cp 解码后转 UTF-8 输出。 Json::Value ParseWindowList(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 2) return arr; const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; while (off + sizeof(DWORD) <= len) { DWORD hwnd = *(const DWORD*)(p + off); off += sizeof(DWORD); const char* titleWithAttrs = p + off; size_t tlen = BoundedStrlen(titleWithAttrs, len - off); if (tlen >= len - off) break; if (tlen == 0) break; // 空记录 = 尾部零填充(LocalSize 对齐),停止解析 off += tlen + 1; std::string title, status; uint64_t pid = 0; ParseWindowAttrsStr(titleWithAttrs, title, status, pid); Json::Value item(Json::objectValue); item["hwnd"] = (Json::UInt64)hwnd; item["title"] = ToUtf8(title.c_str(), cp); item["status"] = status; item["pid"] = (Json::UInt64)pid; arr.append(item); } return arr; } // 解析 TOKEN_DRIVE_LIST 缓冲(data[0]=token,其后为 // [letter:1][GetDriveType:1][totalMB:4][freeMB:4][typeName\0][fileSystem\0] 记录, // 以 letter=='\0' 终止)。typeName/fileSystem 为客户端 ANSI(编码由 cp 指定)。 Json::Value ParseDriveList(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 2) return arr; const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; // 跳过 TOKEN 字节 while (off + 10 <= len && p[off] != '\0') { char letter = p[off]; unsigned int type = (unsigned int)(unsigned char)p[off + 1]; DWORD totalMB = *(const DWORD*)(p + off + 2); DWORD freeMB = *(const DWORD*)(p + off + 6); off += 10; const char* typeName = p + off; size_t tlen = BoundedStrlen(typeName, len - off); if (tlen >= len - off) break; off += tlen + 1; const char* fileSystem = p + off; size_t flen = BoundedStrlen(fileSystem, len - off); if (flen >= len - off) break; off += flen + 1; std::string drive; drive += letter; drive += ":\\"; Json::Value item(Json::objectValue); item["drive"] = drive; item["type"] = (Json::UInt64)type; item["typeName"] = ToUtf8(typeName, cp); item["fileSystem"] = ToUtf8(fileSystem, cp); item["totalMB"] = (Json::UInt64)totalMB; item["freeMB"] = (Json::UInt64)freeMB; arr.append(item); } return arr; } // 文件管理通道上的名字解码。协议约定是客户端 ANSI/GBK(Windows 的 FindFirstFileA、 // Linux/macOS 的 common/FileManager.h 都按 GBK 收发),但 POSIX 客户端的 utf8ToGbk // 遇到 GBK 无法表示的字符会原样返回 UTF-8。cp=CP_UTF8(POSIX 调用方)时先按 GBK // 严格解码:能解开就当 GBK(线上常态);解不开说明客户端透传了 UTF-8,按 UTF-8 用。 // 反过来「先试 UTF-8」不行——约 18% 的常用汉字 GBK 双字节恰好也是合法 UTF-8 // (如 目录 = C4 BF C2 BC = "Ŀ¼"),会解成拉丁字母。已知限制:透传的 UTF-8 // 字节若恰好也是合法 GBK(例如 emoji)仍会被当 GBK 解,客户端侧编码转换本身不可逆。 std::string DecodeListingName(const char* s, UINT cp) { if (cp == CP_UTF8) { if (MultiByteToWideChar(936, MB_ERR_INVALID_CHARS, s, -1, NULL, 0) > 0) return ToUtf8(s, 936); return std::string(s); } return ToUtf8(s, cp); } // 解析 TOKEN_FILE_LIST 缓冲(data[0]=token,其后为 // [attr:1][filename\0][sizeHigh:4][sizeLow:4][ftLastWriteTime:8] 记录)。 // 文件名为客户端 ANSI(编码由 cp 指定,见 DecodeListingName);attr 非 0 表示目录 // (FILE_ATTRIBUTE_DIRECTORY)。 // maxEntries 只限制构建出的条目数:超出时提前返回,并通过 truncated 告知数据里还有 // 更多记录(调用方据此区分「目录就这么大」和「服务端解析上限到了」)。 Json::Value ParseFileList(const std::vector& data, int maxEntries, UINT cp, bool* truncated = nullptr) { Json::Value arr(Json::arrayValue); if (truncated) *truncated = false; if (data.size() < 2) return arr; const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; int count = 0; while (off + 1 <= len) { bool isDir = (p[off] & FILE_ATTRIBUTE_DIRECTORY) != 0; off += 1; const char* name = p + off; size_t nlen = BoundedStrlen(name, len - off); if (nlen >= len - off) break; if (nlen == 0) break; // 空记录 = 尾部零填充(LocalAlloc 对齐),停止解析 if (count >= maxEntries) { // 还有记录但已达上限:数据不完整 if (truncated) *truncated = true; break; } off += nlen + 1; if (off + 16 > len) break; DWORD sizeHigh = *(const DWORD*)(p + off); DWORD sizeLow = *(const DWORD*)(p + off + 4); ULONGLONG size = ((ULONGLONG)sizeHigh << 32) | sizeLow; // 修改时间(FILETIME,100ns since 1601-01-01)→ Unix 秒 // FILETIME 在线上是 dwLowDateTime(低 4 字节) 在前、dwHighDateTime(高 4 字节) 在后 // (客户端 memcpy(&ftLastWriteTime, sizeof(FILETIME)),见 FileManager.cpp::SendFilesList)。 DWORD ftLow = *(const DWORD*)(p + off + 8); DWORD ftHigh = *(const DWORD*)(p + off + 12); off += 16; ULONGLONG ft = ((ULONGLONG)ftHigh << 32) | ftLow; Json::Int64 mtime = (Json::Int64)(ft / 10000000ULL) - 11644473600LL; Json::Value item(Json::objectValue); item["name"] = DecodeListingName(name, cp); item["isDir"] = isDir; item["size"] = (Json::UInt64)size; item["mtime"] = mtime; arr.append(item); ++count; } return arr; } // 解析 TOKEN_SERVERLIST 缓冲(data[0]=token,其后为 // [displayName\0][serviceName\0][binaryPath\0][runWay\0][autoRun\0] 记录)。 // 字段全部来自 Windows A 接口(EnumServicesStatus / QueryServiceConfig),为客户端 // ANSI(编码由 cp 指定)。以 displayName 与 serviceName 同时为空作为尾部零填充 // (LocalAlloc/LocalReAlloc LMEM_ZEROINIT 对齐)的终止条件。 Json::Value ParseServiceList(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 2) return arr; const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; // 跳过 TOKEN 字节 while (off < len) { const char* f[5]; bool ok = true; for (int i = 0; i < 5; ++i) { size_t n = BoundedStrlen(p + off, len - off); if (n >= len - off) { ok = false; break; } // 未以 '\0' 结尾,异常数据 f[i] = p + off; off += n + 1; } if (!ok) break; // displayName 与 serviceName 都为空 → 尾部零填充,停止解析 if (f[0][0] == '\0' && f[1][0] == '\0') break; Json::Value item(Json::objectValue); item["display_name"] = ToUtf8(f[0], cp); item["service_name"] = ToUtf8(f[1], cp); item["binary_path"] = ToUtf8(f[2], cp); item["status"] = ToUtf8(f[3], cp); // Stopped/Running/Paused/... 英文 item["start_type"] = ToUtf8(f[4], cp); // Boot-Start/Auto-Start/Demand-Start/... 英文 arr.append(item); } return arr; } // ========== list_registry:注册表解析 ========== // 注册表 REGMSG 头(client RegisterOperation.cpp / server RegisterDlg.cpp 各自本地定义,此处同构)。 struct RegMsgHeader { int count; // 名字个数 DWORD size; // 名字大小(定宽) DWORD valsize; // 值大小(定宽) }; // client KEYVALUE 枚举(RegisterOperation.cpp):MREG_SZ=0 … MREG_NONE=6。 enum RegValueType { REG_T_SZ = 0, REG_T_DWORD = 1, REG_T_BINARY = 2, REG_T_EXPAND_SZ = 3, REG_T_MULTI_SZ = 4, REG_T_QWORD = 5, REG_T_NONE = 6, }; // client MYKEY 枚举:根键 token。 enum RegRootToken { REG_ROOT_CLASSES_ROOT = 0, REG_ROOT_CURRENT_USER = 1, REG_ROOT_LOCAL_MACHINE = 2, REG_ROOT_USERS = 3, REG_ROOT_CURRENT_CONFIG = 4, }; // ASCII 不区分大小写前缀匹配(注册表根键名大小写不敏感)。 bool StrPrefixCI(const std::string& s, const char* prefix, size_t len) { if (s.size() < len) return false; for (size_t i = 0; i < len; ++i) { char a = s[i], b = prefix[i]; if (a >= 'A' && a <= 'Z') a += 32; if (b >= 'A' && b <= 'Z') b += 32; if (a != b) return false; } return true; } // 值类型名(可读字符串) const char* RegTypeName(BYTE type) { switch (type) { case REG_T_SZ: return "REG_SZ"; case REG_T_DWORD: return "REG_DWORD"; case REG_T_BINARY: return "REG_BINARY"; case REG_T_EXPAND_SZ: return "REG_EXPAND_SZ"; case REG_T_MULTI_SZ: return "REG_MULTI_SZ"; case REG_T_QWORD: return "REG_QWORD"; case REG_T_NONE: return "REG_NONE"; default: return "REG_UNKNOWN"; } } // 将注册表值数据格式化为字符串。valSize 为定宽(client 按 MaxDataLen+1 填充), // 字符串类取到 '\0' 为止、数值类取定长前缀;REG_BINARY 长度无法从协议还原,按 valSize 输出 hex。 std::string FormatRegData(BYTE type, const BYTE* val, size_t valSize, UINT cp) { switch (type) { case REG_T_SZ: case REG_T_EXPAND_SZ: return ToUtf8((const char*)val, cp); case REG_T_MULTI_SZ: { // 多个 '\0' 结尾串、双 '\0' 结束 std::string out; size_t i = 0; while (i < valSize && val[i] != '\0') { const char* s = (const char*)(val + i); size_t n = BoundedStrlen(s, valSize - i); if (!out.empty()) out += "\n"; out += ToUtf8(s, cp); i += n + 1; } return out; } case REG_T_DWORD: { // 4 字节小端 if (valSize < 4) return ""; DWORD v = 0; memcpy(&v, val, 4); char buf[64]; sprintf(buf, "0x%08lX (%lu)", (unsigned long)v, (unsigned long)v); return buf; } case REG_T_QWORD: { // 8 字节小端 if (valSize < 8) return ""; uint64_t v = 0; memcpy(&v, val, 8); char buf[96]; sprintf(buf, "0x%016I64X (%I64u)", (unsigned __int64)v, (unsigned __int64)v); return buf; } case REG_T_BINARY: { // hex,尾部可能含 0 填充 std::string out; char buf[4]; for (size_t i = 0; i < valSize; ++i) { sprintf(buf, "%02X", val[i]); out += buf; } return out; } case REG_T_NONE: default: return ""; } } // 解析 TOKEN_REG_PATH 缓冲:[token:1][RegMsgHeader:12][count * size 定宽子键名]。cp 为客户端 ANSI。 Json::Value ParseRegPath(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 1 + sizeof(RegMsgHeader)) return arr; const char* p = (const char*)data.data(); size_t off = 1; // 跳过 TOKEN 字节 RegMsgHeader hdr; memcpy(&hdr, p + off, sizeof(hdr)); off += sizeof(hdr); int count = hdr.count; size_t nameSize = hdr.size; for (int i = 0; i < count; ++i) { if (off + nameSize > data.size()) break; const char* name = p + off; off += nameSize; if (name[0] == '\0') break; // 空名 = 尾部零填充,停止 arr.append(ToUtf8(name, cp)); } return arr; } // 解析 TOKEN_REG_KEY 缓冲:[token:1][RegMsgHeader:12][count * {type:1,name:size,data:valsize}]。 Json::Value ParseRegKey(const std::vector& data, UINT cp) { Json::Value arr(Json::arrayValue); if (data.size() < 1 + sizeof(RegMsgHeader)) return arr; const char* p = (const char*)data.data(); size_t off = 1; // 跳过 TOKEN 字节 RegMsgHeader hdr; memcpy(&hdr, p + off, sizeof(hdr)); off += sizeof(hdr); int count = hdr.count; size_t nameSize = hdr.size; size_t valSize = hdr.valsize; for (int i = 0; i < count; ++i) { if (off + 1 + nameSize + valSize > data.size()) break; BYTE type = (BYTE)p[off]; off += 1; const char* name = p + off; // 定宽 nameSize 内以 '\0' 结尾 off += nameSize; const BYTE* val = (const BYTE*)(p + off); off += valSize; Json::Value item(Json::objectValue); item["name"] = ToUtf8(name, cp); item["type"] = RegTypeName(type); item["data"] = FormatRegData(type, val, valSize, cp); arr.append(item); } return arr; } // 解析 "HKEY_LOCAL_MACHINE\Software\..." → rootToken + 相对子键路径(去掉根键名与首个 '\')。 // 返回 false 表示 path 为空(调用方列根键)或未匹配任何根键(调用方报错)。 bool ParseRegistryPath(const std::string& path, BYTE& rootToken, std::string& relPath) { struct RootMap { const char* name; BYTE token; }; static const RootMap roots[] = { { "HKEY_CLASSES_ROOT", REG_ROOT_CLASSES_ROOT }, { "HKEY_CURRENT_USER", REG_ROOT_CURRENT_USER }, { "HKEY_LOCAL_MACHINE", REG_ROOT_LOCAL_MACHINE }, { "HKEY_USERS", REG_ROOT_USERS }, { "HKEY_CURRENT_CONFIG", REG_ROOT_CURRENT_CONFIG }, }; if (path.empty()) return false; for (const RootMap& r : roots) { size_t n = strlen(r.name); if (StrPrefixCI(path, r.name, n)) { rootToken = r.token; relPath = path.substr(n); if (!relPath.empty() && relPath[0] == '\\') relPath.erase(0, 1); return true; } } return false; } // 列根键(path 为空):返回 5 个固定根键,无需查询客户端。 std::string BuildRegistryRoots(const Json::Value& id) { Json::Value keys(Json::arrayValue); const char* roots[] = { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CURRENT_CONFIG" }; for (const char* r : roots) keys.append(r); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); // path 恒为 "":根键这一层没有路径,但补上它能让「列根键」与「列子键」返回同一组 // 字段(path/keys,子键那次多一个 values),调用方不必按分支判断。 structuredContent["path"] = ""; structuredContent["keys"] = keys; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"共 ") + std::to_string((int)keys.size()) + std::string(u8" 个根键。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // 收集所有在线主机 JSON 数组(m_cs 锁内遍历,复用 BuildHostJson 序列化,方案 C) void CollectOnlineHosts(CMy2015RemoteDlg* parent, Json::Value& hosts) { if (!parent) return; EnterCriticalSection(&parent->m_cs); for (context* ctx : parent->m_HostList) { if (!ctx || !ctx->IsLogin()) continue; hosts.append(BuildHostJson(ctx, parent->m_ClientMap)); } LeaveCriticalSection(&parent->m_cs); } // MAP_AUTH 的三态(见 common/commands.h):0 未授权 / 1 超级管理员授权 / 2 管理员授权 / 9 禁止登录。 // 导出成字符串而不是布尔:AUTH_FORBIDDEN 与 UNAUTHORIZED 对运维是两回事。 const char* AuthStatusName(int auth) { switch (auth) { case AUTHED_BY_SUPER: return "authorized_by_super"; case AUTHED_BY_ADMIN: return "authorized_by_admin"; case AUTH_FORBIDDEN: return "forbidden"; default: return "unauthorized"; } } // 离线主机 JSON:字段与 BuildHostJson 同形,缺实时字段(rtt/version/activeWindow/screen/clientType)。 // ClientValue.Location 已统一按 UTF-8 存储(见 AddList 的 NormalizeLocationToUtf8),直接透传; // 其余窄字符串来自客户端的 CString,按 CP_ACP 转 UTF-8。 Json::Value BuildOfflineHostJson(_ClientList* clientMap, uint64_t key, const ClientValue& cv) { Json::Value h(Json::objectValue); h["id"] = std::to_string(key); h["name"] = ToUtf8(cv.ComputerName, CP_ACP); if (clientMap) { CString remark = clientMap->GetClientMapData(key, MAP_NOTE); if (!remark.IsEmpty()) h["remark"] = ToUtf8(remark.GetString(), CP_ACP); } h["ip"] = std::string(cv.IP); h["os"] = ToUtf8(cv.OsName, CP_ACP); h["location"] = std::string(cv.Location); h["online"] = false; h["group"] = "default"; // 分组只存在于在线 context 上,离线条目拿不到 h["last_seen"] = std::string(cv.LastLoginTime); h["install_time"] = std::string(cv.InstallTime); h["authStatus"] = AuthStatusName(cv.Authorized); return h; } // 收集全部已知主机(m_cs 锁内)。在线主机取实时字段,离线主机取 m_ClientMap 元数据快照。 // includeOnline / includeOffline 决定保留哪一类:两者都 false 时返回空数组。 void CollectAllHosts(CMy2015RemoteDlg* parent, Json::Value& hosts, bool includeOnline, bool includeOffline) { if (!parent || !parent->m_ClientMap) return; EnterCriticalSection(&parent->m_cs); // 在线集合始终要建:用来判断 map 里的条目当前是否在线(决定它算哪一类) std::unordered_map online; for (context* ctx : parent->m_HostList) { if (ctx && ctx->IsLogin()) online[ctx->GetClientID()] = ctx; } std::set emitted; for (const auto& kv : parent->m_ClientMap->GetAll()) { auto it = online.find(kv.first); if (it != online.end()) { if (includeOnline) { Json::Value h = BuildHostJson(it->second, parent->m_ClientMap); if (h.isObject()) h["authStatus"] = AuthStatusName(kv.second.Authorized); hosts.append(h); emitted.insert(kv.first); } } else if (includeOffline) { hosts.append(BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second)); } } // 在线但还没写进 m_ClientMap 的新客户端(首次上线瞬间)也要能列出来 if (includeOnline) { for (const auto& kv : online) { if (!emitted.count(kv.first)) { Json::Value h = BuildHostJson(kv.second, parent->m_ClientMap); if (h.isObject()) h["authStatus"] = AuthStatusName(UNAUTHORIZED); // 不在 map 里即从未登记 hosts.append(h); } } } LeaveCriticalSection(&parent->m_cs); } // ===== C3:list_hosts 的公共过滤 ===== // 口径与 list_hosts 一致:条件都可选、AND 组合、子串匹配、ASCII 不区分大小写。 // 只过滤已有字段,不额外拉取主机数据;离线主机没有 clientType(历史记录里不存), // 所以带 client_type 条件时离线主机不会命中——需要按平台筛历史主机请用 os。 struct HostListFilter { std::string group; std::string os; std::string clientType; bool Any() const { return !group.empty() || !os.empty() || !clientType.empty(); } }; HostListFilter ReadHostListFilter(const Json::Value& args) { HostListFilter f; f.group = GetStringArg(args, "group"); f.os = GetStringArg(args, "os"); f.clientType = GetStringArg(args, "client_type"); return f; } void ApplyHostListFilter(const Json::Value& in, const HostListFilter& f, Json::Value& out) { out = Json::Value(Json::arrayValue); for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) { const Json::Value& h = in[i]; if (!f.group.empty() && !ContainsCI(JsonStrField(h, "group"), f.group)) continue; if (!f.os.empty() && !ContainsCI(JsonStrField(h, "os"), f.os)) continue; if (!f.clientType.empty() && !ContainsCI(JsonStrField(h, "clientType"), f.clientType)) continue; out.append(h); } } void AppendHostListFilterProps(Json::Value& props) { Json::Value groupProp(Json::objectValue); groupProp["type"] = "string"; groupProp["description"] = u8"按分组过滤(子串,不区分大小写)。省略则不过滤。"; props["group"] = groupProp; Json::Value osProp(Json::objectValue); osProp["type"] = "string"; osProp["description"] = u8"按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。"; props["os"] = osProp; Json::Value typeProp(Json::objectValue); typeProp["type"] = "string"; typeProp["description"] = u8"按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。"; props["client_type"] = typeProp; } // ========== 工具 schema ========== // 单台主机字段 schema(hosts 数组元素 / 单机详情共用的形状) Json::Value BuildHostItemSchema() { Json::Value itemProps(Json::objectValue); const char* strFields[] = { "id", "name", "remark", "ip", "os", "location", "rtt", "version", "activeWindow", "group", "screen", "clientType", // 以下两项只有离线主机(来自 m_ClientMap 的历史记录)才有值 "last_seen", "install_time" }; for (const char* f : strFields) { Json::Value p(Json::objectValue); p["type"] = "string"; itemProps[f] = p; } Json::Value onlineProp(Json::objectValue); onlineProp["type"] = "boolean"; itemProps["online"] = onlineProp; // 客户端登录时上报的 TLS 传输标志(老客户端恒为 false) Json::Value tlsProp(Json::objectValue); tlsProp["type"] = "boolean"; itemProps["tls"] = tlsProp; // 主机授权状态:unauthorized / authorized_by_super / authorized_by_admin / forbidden Json::Value authProp(Json::objectValue); authProp["type"] = "string"; itemProps["authStatus"] = authProp; return itemProps; } // 列表型 outputSchema 的公共翻页字段,字段名与 McpMachine.cpp 的 host_inspect 保持一致 void AppendPageOutputProps(Json::Value& props) { const char* intFields[] = { "total", "totalAll", "offset", "limit" }; for (const char* f : intFields) { Json::Value p(Json::objectValue); p["type"] = "integer"; props[f] = p; } Json::Value moreProp(Json::objectValue); moreProp["type"] = "boolean"; props["hasMore"] = moreProp; } // list_hosts 的 outputSchema(hosts 数组) Json::Value BuildHostOutputSchema() { Json::Value props(Json::objectValue); Json::Value hostsProp(Json::objectValue); hostsProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; items["properties"] = BuildHostItemSchema(); hostsProp["items"] = items; props["hosts"] = hostsProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("hosts"); schema["required"] = required; return schema; } // get_host_detail 的 outputSchema(单台主机) Json::Value BuildHostDetailOutputSchema() { Json::Value props(Json::objectValue); // get_host_detail 在通用主机字段之外还补技术字段与 capabilities;schema 只声明 // capabilities——它是「该不该调某个工具」的判据,其余字段缺声明不影响取值。 Json::Value hostProps = BuildHostItemSchema(); { auto boolProp = [](const char* desc) { Json::Value p(Json::objectValue); p["type"] = "boolean"; p["description"] = desc; return p; }; Json::Value capProps(Json::objectValue); Json::Value platform(Json::objectValue); platform["type"] = "string"; platform["description"] = u8"客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK"; capProps["platform"] = platform; capProps["screenPreview"] = boolProp(u8"能否截屏(get_screenshot 的前提)"); capProps["screenRegion"] = boolProp( u8"能否按区域/窗口/显示器原生分辨率截屏(get_screenshot 的 mode=region/window/monitor 前提);" u8"仅声明 CLIENT_CAP_SCREEN_REGION 的新 Windows 客户端为 true"); capProps["remoteControl"] = boolProp( u8"能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);" u8"Android 客户端只支持整屏目标,且需要已授权录屏与无障碍服务;" u8"还要求服务端 Web 远程服务已启动(WebSvrPort>0)"); capProps["fileTransferV2"] = boolProp(u8"是否支持 V2 文件传输(download_file / upload_file 的前提)"); capProps["c2cPaths"] = boolProp(u8"能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)"); capProps["registry"] = boolProp(u8"是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true"); capProps["windowInfo"] = boolProp( u8"是否支持窗口信息(get_foreground_window、host_inspect 的 windows 项坐标/前后台字段、" u8"operate_window/host_control_window 的 activate);仅声明 CLIENT_CAP_WINDOW_INFO 的新客户端为 true"); Json::Value caps(Json::objectValue); caps["type"] = "object"; caps["properties"] = capProps; hostProps["capabilities"] = caps; } Json::Value hostProp(Json::objectValue); hostProp["type"] = "object"; hostProp["properties"] = hostProps; props["host"] = hostProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("host"); schema["required"] = required; return schema; } // list_hosts 的 inputSchema(P1-1:三个主机列表工具合并;全部可选) // 旧名 list_online_hosts / search_hosts / list_all_hosts 作为别名保留,参数在这里一并声明。 Json::Value BuildListHostsInputSchema() { Json::Value props(Json::objectValue); Json::Value queryProp(Json::objectValue); queryProp["type"] = "string"; queryProp["description"] = u8"关键字:子串匹配计算机名、备注或 IP(ASCII 不区分大小写)。省略则不过滤。"; props["query"] = queryProp; Json::Value nameProp(Json::objectValue); nameProp["type"] = "string"; nameProp["description"] = u8"只按计算机名/备注过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。"; props["name"] = nameProp; Json::Value ipProp(Json::objectValue); ipProp["type"] = "string"; ipProp["description"] = u8"只按 IP 过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。"; props["ip"] = ipProp; Json::Value onlineProp(Json::objectValue); onlineProp["type"] = "boolean"; onlineProp["description"] = u8"true(默认)返回在线主机;false 只返回离线主机(历史连接过、当前未连接)。"; props["online"] = onlineProp; Json::Value includeOfflineProp(Json::objectValue); includeOfflineProp["type"] = "boolean"; includeOfflineProp["description"] = u8"是否把离线主机一起返回,默认 false(只给在线);online=false 时无意义。list_all_hosts 别名默认 true。"; props["include_offline"] = includeOfflineProp; AppendHostListFilterProps(props); AppendPagingProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // get_host_detail 的 inputSchema(id 必填;只读工具另支持 ids[] 批量) Json::Value BuildGetHostDetailInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一"; props["id"] = idProp; AppendBatchIdsProp(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; MakeIdOrIdsRequired(schema); return schema; } // 列表型单主机工具(list_processes / list_windows / list_services):{ id } + limit/offset Json::Value BuildPagedHostListInputSchema() { Json::Value schema = BuildGetHostDetailInputSchema(); AppendPagingProps(schema["properties"]); return schema; } // list_processes / list_windows:在分页参数之上再加服务端过滤(name 子串 + pid 精确)。 // 过滤在分页之前生效,所以 total 是命中数、totalAll 是过滤前的总数。 Json::Value BuildFilteredPagedHostListInputSchema(const char* nameDesc, const char* pidDesc) { Json::Value schema = BuildPagedHostListInputSchema(); Json::Value props = schema["properties"]; // 拷贝后补字段,避免直接改返回的引用树 Json::Value nameProp(Json::objectValue); nameProp["type"] = "string"; nameProp["description"] = nameDesc; props["name"] = nameProp; Json::Value pidProp(Json::objectValue); pidProp["type"] = "integer"; pidProp["description"] = pidDesc; props["pid"] = pidProp; schema["properties"] = props; return schema; } // list_processes 的 outputSchema(processes 数组) Json::Value BuildProcessListOutputSchema() { Json::Value props(Json::objectValue); Json::Value procsProp(Json::objectValue); procsProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); Json::Value pidProp(Json::objectValue); pidProp["type"] = "integer"; itemProps["pid"] = pidProp; const char* strFields[] = { "name", "arch", "path" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; itemProps[f] = s; } items["properties"] = itemProps; procsProp["items"] = items; props["processes"] = procsProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("processes"); schema["required"] = required; return schema; } // list_windows 的 outputSchema(windows 数组) Json::Value BuildWindowListOutputSchema() { Json::Value props(Json::objectValue); Json::Value winsProp(Json::objectValue); winsProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); Json::Value hwndProp(Json::objectValue); hwndProp["type"] = "integer"; itemProps["hwnd"] = hwndProp; Json::Value pidProp(Json::objectValue); pidProp["type"] = "integer"; itemProps["pid"] = pidProp; const char* strFields[] = { "title", "status" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; itemProps[f] = s; } items["properties"] = itemProps; winsProp["items"] = items; props["windows"] = winsProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("windows"); schema["required"] = required; return schema; } // get_activity_history 的 outputSchema(records 数组 + 原始文本 + 翻页字段) Json::Value BuildActivityHistoryOutputSchema() { Json::Value props(Json::objectValue); Json::Value recordsProp(Json::objectValue); recordsProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "string"; recordsProp["items"] = items; recordsProp["description"] = u8"本次窗口内的记录,每条一行「[时间] [标题] 时长」。新在前。"; props["records"] = recordsProp; Json::Value rawProp(Json::objectValue); rawProp["type"] = "string"; rawProp["description"] = u8"与 records 同源的纯文本(records 按行拼接),窗口外的记录不包含。"; props["activityHistory"] = rawProp; Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; truncProp["description"] = u8"因 64 KB 字节预算而比 limit 少返回了条目(此时 hasMore 也为 true)。"; props["truncated"] = truncProp; AppendPageOutputProps(props); // total / totalAll / offset / limit / hasMore Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // list_services 的 outputSchema(services 数组) Json::Value BuildServiceListOutputSchema() { Json::Value props(Json::objectValue); Json::Value svcsProp(Json::objectValue); svcsProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); const char* strFields[] = { "display_name", "service_name", "binary_path", "status", "start_type" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; itemProps[f] = s; } items["properties"] = itemProps; svcsProp["items"] = items; props["services"] = svcsProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("services"); schema["required"] = required; return schema; } // ========== P7 输入/输出 schema ========== // 公共:为 props 追加必填的 id 字符串属性。 static void AddIdRequiredProp(Json::Value& props) { Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; } // 公共:组装 {id, ...额外必填} 的 object schema。 static Json::Value FinalizeIdSchema(Json::Value props, std::initializer_list extraRequired) { Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); for (const char* r : extraRequired) required.append(r); schema["required"] = required; return schema; } // 公共:{ ok: boolean } 输出 schema(operate_window / control_service / power_action 共用)。 static Json::Value BuildOkOutputSchema() { Json::Value props(Json::objectValue); Json::Value ok(Json::objectValue); ok["type"] = "boolean"; props["ok"] = ok; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildKillProcessInputSchema() { Json::Value props(Json::objectValue); AddIdRequiredProp(props); Json::Value pidsProp(Json::objectValue); pidsProp["type"] = "array"; Json::Value pidItems(Json::objectValue); pidItems["type"] = "integer"; pidsProp["items"] = pidItems; pidsProp["description"] = u8"要终止的进程 PID 列表(至少 1 个)"; props["pids"] = pidsProp; Json::Value dryRunProp(Json::objectValue); dryRunProp["type"] = "boolean"; dryRunProp["description"] = u8"true 时只校验 PID 是否还存在并返回将被影响的对象,不发送任何终止命令(默认 false)"; props["dry_run"] = dryRunProp; return FinalizeIdSchema(props, { "pids" }); } Json::Value BuildKillProcessOutputSchema() { Json::Value props(Json::objectValue); Json::Value remProp(Json::objectValue); remProp["type"] = "array"; Json::Value remItems(Json::objectValue); remItems["type"] = "integer"; remProp["items"] = remItems; remProp["description"] = u8"杀完后仍在运行的 PID(含权限不足未能终止的)"; props["remaining"] = remProp; Json::Value dryProp(Json::objectValue); dryProp["type"] = "boolean"; dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送终止命令"; props["dry_run"] = dryProp; Json::Value targetsProp(Json::objectValue); targetsProp["type"] = "array"; targetsProp["description"] = u8"dry_run 时将被终止的进程(pid/name/path)"; props["targets"] = targetsProp; Json::Value missingProp(Json::objectValue); missingProp["type"] = "array"; missingProp["description"] = u8"dry_run 时已不存在的 PID"; props["missing"] = missingProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildOperateWindowInputSchema() { Json::Value props(Json::objectValue); AddIdRequiredProp(props); Json::Value hwndProp(Json::objectValue); hwndProp["type"] = "integer"; hwndProp["description"] = u8"窗口句柄,取 list_windows 返回的 hwnd 字段"; props["hwnd"] = hwndProp; Json::Value actionProp(Json::objectValue); actionProp["type"] = "string"; actionProp["description"] = u8"操作:close(关闭) | show(显示) | hide(隐藏) | minimize(最小化) | maximize(最大化) | restore(还原) | activate(激活到前台,需新客户端)"; props["action"] = actionProp; Json::Value dryRunProp(Json::objectValue); dryRunProp["type"] = "boolean"; dryRunProp["description"] = u8"true 时只校验窗口是否还存在并返回将被影响的对象,不发送任何窗口命令(默认 false)"; props["dry_run"] = dryRunProp; return FinalizeIdSchema(props, { "hwnd", "action" }); } Json::Value BuildOperateWindowOutputSchema() { Json::Value props(Json::objectValue); Json::Value ok(Json::objectValue); ok["type"] = "boolean"; ok["description"] = u8"命令已下发(不代表窗口已按预期变化);action=activate 时为前台复核结果"; props["ok"] = ok; Json::Value dryProp(Json::objectValue); dryProp["type"] = "boolean"; dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送窗口命令"; props["dry_run"] = dryProp; Json::Value actionProp(Json::objectValue); actionProp["type"] = "string"; props["action"] = actionProp; Json::Value windowProp(Json::objectValue); // action=activate 复核时若没找到目标窗口,window 为 null(字段存在但值为空)。 Json::Value windowTypes(Json::arrayValue); windowTypes.append("object"); windowTypes.append("null"); windowProp["type"] = windowTypes; windowProp["description"] = u8"dry_run 时的目标窗口;action=activate 时为复核到的窗口快照(hwnd/title/pid/rect/flags 等),复核未找到为 null"; props["window"] = windowProp; Json::Value stateProp(Json::objectValue); stateProp["type"] = "string"; stateProp["description"] = u8"action=activate 时的复核状态:foreground / background / missing / unknown"; props["state"] = stateProp; Json::Value verifyErrProp(Json::objectValue); verifyErrProp["type"] = "string"; verifyErrProp["description"] = u8"action=activate 且前台复核请求失败时的错误说明"; props["verifyError"] = verifyErrProp; Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; truncProp["description"] = u8"为 true 时表示复核用的可见窗口列表被 96 条单次上限截断," u8"未找到目标不代表窗口不存在(此时 state=unknown)"; props["truncated"] = truncProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildControlServiceInputSchema() { Json::Value props(Json::objectValue); AddIdRequiredProp(props); Json::Value nameProp(Json::objectValue); nameProp["type"] = "string"; nameProp["description"] = u8"服务名,取 list_services 返回的 service_name 字段"; props["service_name"] = nameProp; Json::Value actionProp(Json::objectValue); actionProp["type"] = "string"; actionProp["description"] = u8"操作:start(启动) | stop(停止) | set_auto(设为自动) | set_manual(设为手动)"; props["action"] = actionProp; return FinalizeIdSchema(props, { "service_name", "action" }); } Json::Value BuildControlServiceOutputSchema() { return BuildOkOutputSchema(); } Json::Value BuildPowerActionInputSchema() { Json::Value props(Json::objectValue); AddIdRequiredProp(props); Json::Value actionProp(Json::objectValue); actionProp["type"] = "string"; actionProp["description"] = u8"操作:logout(注销) | shutdown(关机) | reboot(重启)"; props["action"] = actionProp; Json::Value waitProp(Json::objectValue); waitProp["type"] = "boolean"; waitProp["description"] = u8"true 时先等主机下线、再等它重新上线(默认 false,发完即返回)。超时不算失败,看返回的 went_offline / came_back。"; props["wait"] = waitProp; Json::Value waitMsProp(Json::objectValue); waitMsProp["type"] = "integer"; waitMsProp["minimum"] = 1000; waitMsProp["maximum"] = 600000; waitMsProp["description"] = u8"等离线与等回线各自的时限(毫秒,默认 60000);一次调用最长约为 2×wait_ms"; props["wait_ms"] = waitMsProp; return FinalizeIdSchema(props, { "action" }); } // power_action 的输出:sent 只代表命令写进了 socket(电源命令没有回执)。 // wait=true 时用主连接在线状态验证:went_offline / came_back / elapsed_ms。 Json::Value BuildPowerActionOutputSchema() { Json::Value props(Json::objectValue); Json::Value ok(Json::objectValue); ok["type"] = "boolean"; ok["description"] = u8"命令已下发(不代表已经关机/重启)"; props["ok"] = ok; Json::Value sent(Json::objectValue); sent["type"] = "boolean"; sent["description"] = u8"命令已送达主机"; props["sent"] = sent; Json::Value off(Json::objectValue); off["type"] = "boolean"; off["description"] = u8"主机是否真的下线了(wait=true 时观察到的;wait=false 恒为 false)"; props["went_offline"] = off; Json::Value back(Json::objectValue); back["type"] = "boolean"; back["description"] = u8"主机下线后是否重新上线(logout 一般不会自动回来)"; props["came_back"] = back; Json::Value elapsed(Json::objectValue); elapsed["type"] = "integer"; elapsed["description"] = u8"本次等待实际耗时(毫秒)"; props["elapsed_ms"] = elapsed; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // list_registry 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列根键) Json::Value BuildListRegistryInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一"; props["id"] = idProp; AppendBatchIdsProp(props); Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"注册表键路径(如 HKEY_LOCAL_MACHINE\\Software);省略或传空则返回 5 个根键"; props["path"] = pathProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; MakeIdOrIdsRequired(schema); return schema; } // list_registry 的 outputSchema(keys 字符串数组 / values 对象数组) Json::Value BuildListRegistryOutputSchema() { Json::Value props(Json::objectValue); Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; props["path"] = pathProp; Json::Value keysProp(Json::objectValue); keysProp["type"] = "array"; Json::Value keyItems(Json::objectValue); keyItems["type"] = "string"; keysProp["items"] = keyItems; props["keys"] = keysProp; Json::Value valsProp(Json::objectValue); valsProp["type"] = "array"; valsProp["description"] = u8"该键下的值;path 为空(列根键)时不返回本字段"; Json::Value valItems(Json::objectValue); valItems["type"] = "object"; Json::Value valProps(Json::objectValue); const char* strFields[] = { "name", "type", "data" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; valProps[f] = s; } valItems["properties"] = valProps; valsProp["items"] = valItems; props["values"] = valsProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; // 只把 keys 标成必填。values 在「列根键」分支里不存在(根键下没有值), // 早先把它一并 required,导致文档描述的第一种用法(省略 path)必然被 // 客户端判为不符合 outputSchema(-32602: data must have required property 'values')。 Json::Value required(Json::arrayValue); required.append("keys"); schema["required"] = required; return schema; } // exec_command 的 inputSchema(id 必填、command 必填、timeout_ms 可选) Json::Value BuildExecCommandInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value cmdProp(Json::objectValue); cmdProp["type"] = "string"; cmdProp["description"] = u8"要执行的命令(受只读模式与命令白名单约束,仅允许只读命令前缀;Windows 与 Linux 使用各自的内置默认白名单)"; props["command"] = cmdProp; Json::Value timeoutProp(Json::objectValue); timeoutProp["type"] = "integer"; timeoutProp["description"] = u8"等待输出完成的超时毫秒数(可选,默认 20000,上限 600000)"; props["timeout_ms"] = timeoutProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("command"); schema["required"] = required; return schema; } // exec_command 的 outputSchema(stdout 文本 / exit_code) Json::Value BuildExecCommandOutputSchema() { Json::Value props(Json::objectValue); Json::Value stdoutProp(Json::objectValue); stdoutProp["type"] = "string"; stdoutProp["description"] = u8"命令输出(已剥哨兵与 ANSI 转义)"; props["stdout"] = stdoutProp; Json::Value exitProp(Json::objectValue); exitProp["type"] = "integer"; exitProp["description"] = u8"退出码:PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)"; props["exit_code"] = exitProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("stdout"); required.append("exit_code"); schema["required"] = required; return schema; } // get_client_log 的 inputSchema:{ id } + limit / filter(+ ids 批量) // // 不加 limit 时,一次快照是客户端 ring buffer 的全量(最多 1000 行、实测 90 KB), // 单条工具结果直接超出客户端上限——取到了却塞不下,等于取不到。默认只回末尾 // 200 行:故障排查看的是最后发生了什么,不是开机时的第一行。 Json::Value BuildClientLogInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一"; props["id"] = idProp; Json::Value limitProp(Json::objectValue); limitProp["type"] = "integer"; limitProp["description"] = u8"最多返回末尾多少行,默认 200,上限 2000;返回的是最近的日志,不是开头的"; props["limit"] = limitProp; Json::Value filterProp(Json::objectValue); filterProp["type"] = "string"; filterProp["description"] = u8"只看包含该子串的行(ASCII 不区分大小写,如 error / TIMEOUT);过滤后再取末尾 limit 行"; props["filter"] = filterProp; AppendBatchIdsProp(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; MakeIdOrIdsRequired(schema); return schema; } // get_client_log 的 outputSchema(日志文本 + 行数统计) Json::Value BuildClientLogOutputSchema() { Json::Value props(Json::objectValue); Json::Value logProp(Json::objectValue); logProp["type"] = "string"; logProp["description"] = u8"日志文本(按行,\\n 分隔);已按 limit/filter 裁剪"; props["log"] = logProp; auto intProp = [](const char* desc) { Json::Value p(Json::objectValue); p["type"] = "integer"; p["description"] = desc; return p; }; props["lines_total"] = intProp(u8"客户端快照的总行数"); props["lines_matched"] = intProp(u8"filter 命中后的行数(无 filter 时等于 lines_total)"); props["lines_returned"] = intProp(u8"本次实际返回的行数"); Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; truncProp["description"] = u8"true 表示命中行数多于本次返回,log 只是末尾一段"; props["truncated"] = truncProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("log"); schema["required"] = required; return schema; } // get_audit_log 的 outputSchema(服务端消息/审计日志条目数组) Json::Value BuildAuditLogOutputSchema() { Json::Value props(Json::objectValue); Json::Value entriesProp(Json::objectValue); entriesProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); const char* strFields[] = { "type", "time", "msg" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; itemProps[f] = s; } items["properties"] = itemProps; entriesProp["items"] = items; props["entries"] = entriesProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("entries"); schema["required"] = required; return schema; } // get_server_status 的 outputSchema(服务端自身状态;嵌套对象只声明类型,不逐字段展开) Json::Value BuildServerStatusOutputSchema() { Json::Value props(Json::objectValue); const char* strFields[] = { "app_name", "version", "exe_build_time", "bind" }; for (const char* f : strFields) { Json::Value s(Json::objectValue); s["type"] = "string"; props[f] = s; } const char* intFields[] = { "uptime_sec", "port", "blocked_auth_ips" }; for (const char* f : intFields) { Json::Value n(Json::objectValue); n["type"] = "integer"; props[f] = n; } const char* objFields[] = { "switches", "hosts", "sessions" }; for (const char* f : objFields) { Json::Value o(Json::objectValue); o["type"] = "object"; props[f] = o; } Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; schema["required"] = Json::Value(Json::arrayValue); return schema; } // get_screenshot 的 outputSchema(image 元数据;base64 数据在 content 的 image 块中) Json::Value BuildScreenshotOutputSchema() { Json::Value props(Json::objectValue); Json::Value imageProp(Json::objectValue); imageProp["type"] = "object"; Json::Value imageProps(Json::objectValue); Json::Value mimeProp(Json::objectValue); mimeProp["type"] = "string"; imageProps["mimeType"] = mimeProp; const char* intFields[] = { "width", "height", "bytes" }; for (const char* f : intFields) { Json::Value s(Json::objectValue); s["type"] = "integer"; imageProps[f] = s; } imageProp["properties"] = imageProps; props["image"] = imageProp; Json::Value capProp(Json::objectValue); capProp["type"] = "object"; Json::Value capProps(Json::objectValue); Json::Value capMode(Json::objectValue); capMode["type"] = "string"; capProps["mode"] = capMode; const char* capInts[] = { "x", "y", "width", "height", "scale" }; for (const char* f : capInts) { Json::Value s(Json::objectValue); s["type"] = "integer"; capProps[f] = s; } Json::Value capNative(Json::objectValue); capNative["type"] = "boolean"; capProps["native"] = capNative; capProp["properties"] = capProps; props["capture"] = capProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("image"); schema["required"] = required; return schema; } // 窗口对象 schema(get_foreground_window 的 window 字段,与 WindowEntryToJson 同口径) Json::Value BuildWindowObjectSchema() { Json::Value obj(Json::objectValue); obj["type"] = "object"; Json::Value p(Json::objectValue); const char* ints[] = { "hwnd", "pid", "left", "top", "right", "bottom", "width", "height", "zOrder" }; for (const char* f : ints) { Json::Value s(Json::objectValue); s["type"] = "integer"; p[f] = s; } Json::Value title(Json::objectValue); title["type"] = "string"; p["title"] = title; const char* bools[] = { "visible", "minimized", "maximized", "isForeground" }; for (const char* f : bools) { Json::Value s(Json::objectValue); s["type"] = "boolean"; p[f] = s; } obj["properties"] = p; return obj; } // get_foreground_window 的 outputSchema(window 为 null 表示当前没有可枚举的前台窗口) Json::Value BuildGetForegroundWindowOutputSchema() { Json::Value props(Json::objectValue); Json::Value winProp = BuildWindowObjectSchema(); Json::Value winTypes(Json::arrayValue); winTypes.append("object"); winTypes.append("null"); winProp["type"] = winTypes; props["window"] = winProp; Json::Value cntProp(Json::objectValue); cntProp["type"] = "integer"; props["windowCount"] = cntProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("window"); required.append("windowCount"); schema["required"] = required; return schema; } // get_screenshot 的 inputSchema(id 必填;mode/region/window/monitor 需新 Windows 客户端) Json::Value BuildGetScreenshotInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value modeProp(Json::objectValue); modeProp["type"] = "string"; Json::Value modeEnum(Json::arrayValue); modeEnum.append("screen"); modeEnum.append("region"); modeEnum.append("window"); modeEnum.append("monitor"); modeProp["enum"] = modeEnum; modeProp["description"] = u8"抓取范围,默认 screen。screen=整个虚拟桌面(可缩放);region=指定矩形;window=指定窗口;monitor=指定显示器。region/window/monitor 默认按源尺寸 1:1 抓取(原生分辨率,适合 OCR/视觉读字),只有显式传 max_width 才缩放;这三种需要较新的 Windows 客户端(能力位 CLIENT_CAP_SCREEN_REGION),否则返回 -32005。"; props["mode"] = modeProp; Json::Value xProp(Json::objectValue); xProp["type"] = "integer"; xProp["description"] = u8"region 模式:矩形左上角的虚拟桌面 X 坐标(可为负;多显示器时以虚拟桌面左上角为原点)。省略按 0 处理。"; props["x"] = xProp; Json::Value yProp(Json::objectValue); yProp["type"] = "integer"; yProp["description"] = u8"region 模式:矩形左上角的虚拟桌面 Y 坐标(可为负)。省略按 0 处理。"; props["y"] = yProp; Json::Value wProp(Json::objectValue); wProp["type"] = "integer"; wProp["description"] = u8"region 模式必填:矩形宽度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。"; props["width"] = wProp; Json::Value hProp(Json::objectValue); hProp["type"] = "integer"; hProp["description"] = u8"region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。"; props["height"] = hProp; Json::Value hwndProp(Json::objectValue); Json::Value hwndTypes(Json::arrayValue); hwndTypes.append("integer"); hwndTypes.append("string"); hwndProp["type"] = hwndTypes; hwndProp["description"] = u8"window 模式必填:窗口句柄(整数或 0x 前缀字符串),取 host_inspect 的 windows 项 / get_foreground_window 返回的 hwnd。窗口最小化时无法抓取(返回错误),先 activate/restore。"; props["hwnd"] = hwndProp; Json::Value monProp(Json::objectValue); monProp["type"] = "integer"; monProp["description"] = u8"monitor 模式:显示器序号,0=主显示器(默认),1..N 为其余显示器(按系统枚举顺序)。序号越界返回错误。"; props["monitor"] = monProp; Json::Value mwProp(Json::objectValue); mwProp["type"] = "integer"; mwProp["description"] = u8"期望图片最大宽度(像素,钳制到 64~1920)。screen 模式省略或传 0 时沿用 RTT 自适应缩略图档位(最大 1024);region/window/monitor 模式省略/传 0 时按源尺寸 1:1 抓取(原生分辨率),显式传入才等比缩小。"; props["max_width"] = mwProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; // region 需 width/height、window 需 hwnd(handler 会以 -32602 拒);monitor 有默认 0, // 无需条件。x/y 在 region 下可省略(按 0),故不进 then。 AppendConditionalRequired(schema, "mode", { "region" }, { "width", "height" }); AppendConditionalRequired(schema, "mode", { "window" }, { "hwnd" }); return schema; } // get_foreground_window 的 inputSchema(id 必填) Json::Value BuildGetForegroundWindowInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; return schema; } // list_files 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列盘) Json::Value BuildListFilesInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;" u8"Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录," u8"按真实目录列举。"; props["path"] = pathProp; AppendBatchIdsProp(props); AppendPagingProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; MakeIdOrIdsRequired(schema); return schema; } // list_files 的 outputSchema(drives 数组 / files 数组,二者其一非空) Json::Value BuildListFilesOutputSchema() { Json::Value props(Json::objectValue); Json::Value drivesProp(Json::objectValue); drivesProp["type"] = "array"; Json::Value driveItems(Json::objectValue); driveItems["type"] = "object"; Json::Value driveProps(Json::objectValue); const char* driveStr[] = { "drive", "typeName", "fileSystem" }; for (const char* f : driveStr) { Json::Value s(Json::objectValue); s["type"] = "string"; driveProps[f] = s; } const char* driveInt[] = { "type", "totalMB", "freeMB" }; for (const char* f : driveInt) { Json::Value s(Json::objectValue); s["type"] = "integer"; driveProps[f] = s; } driveItems["properties"] = driveProps; drivesProp["items"] = driveItems; props["drives"] = drivesProp; Json::Value filesProp(Json::objectValue); filesProp["type"] = "array"; Json::Value fileItems(Json::objectValue); fileItems["type"] = "object"; Json::Value fileProps(Json::objectValue); Json::Value nameProp(Json::objectValue); nameProp["type"] = "string"; fileProps["name"] = nameProp; Json::Value isDirProp(Json::objectValue); isDirProp["type"] = "boolean"; fileProps["isDir"] = isDirProp; const char* fileInt[] = { "size", "mtime" }; for (const char* f : fileInt) { Json::Value s(Json::objectValue); s["type"] = "integer"; fileProps[f] = s; } fileItems["properties"] = fileProps; filesProp["items"] = fileItems; props["files"] = filesProp; // 目录条目超过解析上限(10 万条)时为 true,此时 total 只是上限内的数量。 Json::Value truncatedProp(Json::objectValue); truncatedProp["type"] = "boolean"; truncatedProp["description"] = u8"目录条目超过服务端解析上限(100000 条)时为 true;" u8"仅在返回 files 时可能出现,此时 total 不是真实总数。"; props["truncated"] = truncatedProp; AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // ===== P4 前置声明(定义见下方「tools/call 分派」前)===== Json::Value BuildTerminalOpenInputSchema(); Json::Value BuildTerminalOpenOutputSchema(); Json::Value BuildTerminalExecInputSchema(); Json::Value BuildTerminalExecOutputSchema(); Json::Value BuildTerminalCloseInputSchema(); Json::Value BuildTerminalCloseOutputSchema(); std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildTerminalClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== P5 前置声明(定义见下方「tools/call 分派」前)===== Json::Value BuildRemoteOpenInputSchema(); Json::Value BuildRemoteOpenOutputSchema(); Json::Value BuildRemoteCloseInputSchema(); Json::Value BuildRemoteCloseOutputSchema(); Json::Value BuildRemoteKeyboardInputSchema(); Json::Value BuildRemoteKeyboardOutputSchema(); Json::Value BuildRemoteMouseInputSchema(); Json::Value BuildRemoteMouseOutputSchema(); Json::Value BuildRemoteClipboardInputSchema(); Json::Value BuildRemoteClipboardOutputSchema(); Json::Value BuildRemoteBlockInputInputSchema(); Json::Value BuildRemoteBlockInputOutputSchema(); std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteBlockInput(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== P6 前置声明(定义见下方「tools/call 分派」前)===== Json::Value BuildDownloadFileInputSchema(); Json::Value BuildDownloadFileOutputSchema(); std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // P0-3:按字节读远端文本文件(复用 download_file 的 V2 接收端,读后即删临时文件) Json::Value BuildReadFileInputSchema(); Json::Value BuildReadFileOutputSchema(); std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // P1-2:在被管主机上请求私有网段 HTTP 地址(复用持久终端的 shell 通道) Json::Value BuildHttpProbeInputSchema(); Json::Value BuildHttpProbeOutputSchema(); std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); Json::Value BuildUploadFileInputSchema(); Json::Value BuildUploadFileOutputSchema(); std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); Json::Value BuildCopyFilesC2CInputSchema(); Json::Value BuildCopyFilesC2COutputSchema(); std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); Json::Value BuildRemoteLockScreenInputSchema(); Json::Value BuildRemoteLockScreenOutputSchema(); std::string BuildRemoteLockScreen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== P7 前置声明(定义见下方「tools/call 分派」前)===== Json::Value BuildKillProcessInputSchema(); Json::Value BuildKillProcessOutputSchema(); Json::Value BuildOperateWindowInputSchema(); Json::Value BuildOperateWindowOutputSchema(); Json::Value BuildControlServiceInputSchema(); Json::Value BuildControlServiceOutputSchema(); Json::Value BuildPowerActionInputSchema(); Json::Value BuildPowerActionOutputSchema(); std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); Json::Value BuildUninstallHostInputSchema(); Json::Value BuildUninstallHostOutputSchema(); std::string BuildUninstallHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== B1 前置声明(主机库元数据,定义见「tools/call 分派」前)===== Json::Value BuildHostSetRemarkInputSchema(); Json::Value BuildHostSetRemarkOutputSchema(); Json::Value BuildHostSetWatchLevelInputSchema(); Json::Value BuildHostSetWatchLevelOutputSchema(); std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== B2 前置声明(search_file,定义见「tools/call 分派」前)===== Json::Value BuildSearchFileInputSchema(); Json::Value BuildSearchFileOutputSchema(); std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== P10-B 前置声明(文件系统写操作,定义见「tools/call 分派」前)===== Json::Value BuildDeletePathInputSchema(); Json::Value BuildDeletePathOutputSchema(); Json::Value BuildMovePathInputSchema(); Json::Value BuildMovePathOutputSchema(); Json::Value BuildCreateFolderInputSchema(); Json::Value BuildCreateFolderOutputSchema(); std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // tools/list std::string BuildToolsListResult(const Json::Value& id) { Json::Value result(Json::objectValue); Json::Value tools(Json::arrayValue); // P2-2:主机管理开启时,list_processes / list_windows / list_services 由 host_inspect // 的 processes / windows / win32_services 项覆盖,不再出现在 tools/list;但名字仍在 // 分派处可用(见 Call),老调用方不会断。关闭主机管理时它们必须出现——那是这台 // 服务端唯一能列进程/窗口/服务的路径(McpMachine 默认关)。 const bool showDegradedLists = !McpServer().IsMachineEnabled(); // 1) list_hosts(P1-1:合并 list_online_hosts / search_hosts / list_all_hosts; // 旧名作为别名保留在分发处,不出现在 tools/list) { Json::Value tool(Json::objectValue); tool["name"] = "list_hosts"; tool["description"] = u8"列主机:默认只返回在线主机(含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息),include_offline=true 时连离线主机(历史连接过、当前未连接,来自主机列表记录)一起返回,在线主机排在最前面。query 子串匹配计算机名/备注/IP;group / os / client_type 为附加过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写);online=false 只看离线主机。过滤在分页之前生效:total 为命中台数,totalAll 为过滤前的主机库台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType(按平台筛历史主机请用 os),group 恒为 default。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。"; tool["inputSchema"] = BuildListHostsInputSchema(); tool["outputSchema"] = BuildHostOutputSchema(); tools.append(tool); } // 3) get_host_detail(P2a:单机详情,纯内存) { Json::Value tool(Json::objectValue); tool["name"] = "get_host_detail"; tool["description"] = u8"获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。"; tool["inputSchema"] = BuildGetHostDetailInputSchema(); tool["outputSchema"] = BuildHostDetailOutputSchema(); tools.append(tool); } // 4) list_processes(P2b:主连接 RPC,进程列表;P2-2:主机管理开启时由 host_inspect 取代) if (showDegradedLists) { Json::Value tool(Json::objectValue); tool["name"] = "list_processes"; tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。仅在 McpMachine=0(主机管理工具关闭)时出现——那是本服务端唯一能列进程的路径;开启主机管理后改用 host_inspect 的 processes 项(字段更全、支持 arch 过滤)。"; tool["inputSchema"] = BuildFilteredPagedHostListInputSchema( u8"按映像名子串过滤,ASCII 不区分大小写(如 chrome)", u8"按 PID 精确过滤"); tool["outputSchema"] = BuildProcessListOutputSchema(); tools.append(tool); } // 5) list_windows(P2b:主连接 RPC,窗口列表;P2-2:主机管理开启时由 host_inspect 取代) if (showDegradedLists) { Json::Value tool(Json::objectValue); tool["name"] = "list_windows"; tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回。可选 name(窗口标题子串,ASCII 不区分大小写)/ pid(所属进程,精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。仅在 McpMachine=0(主机管理工具关闭)时出现;开启主机管理后改用 host_inspect 的 windows 项(字段更全,含窗口矩形与 z 序)。"; tool["inputSchema"] = BuildFilteredPagedHostListInputSchema( u8"按窗口标题子串过滤,ASCII 不区分大小写(如 notepad);匹配的是标题不是进程名", u8"按窗口所属进程的 PID 精确过滤"); tool["outputSchema"] = BuildWindowListOutputSchema(); tools.append(tool); } // 6) get_activity_history(P2b:主连接 RPC,历史活动记录) { Json::Value tool(Json::objectValue); tool["name"] = "get_activity_history"; tool["description"] = u8"获取指定在线主机的历史活动记录。Windows、有桌面的 Linux 与 macOS 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」(macOS 无录屏授权时标题退化为应用名);Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。"; tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset tool["outputSchema"] = BuildActivityHistoryOutputSchema(); tools.append(tool); } // 7) get_screenshot(P2c:屏幕预览链路,主连接 RPC) { Json::Value tool(Json::objectValue); tool["name"] = "get_screenshot"; tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows、带 X11 桌面的 Linux 与 macOS(登录时已授予录屏权限)客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。"; tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选 tool["outputSchema"] = BuildScreenshotOutputSchema(); tools.append(tool); } // 7b) get_foreground_window(窗口信息 RPC,CLIENT_CAP_WINDOW_INFO,仅 Windows) { Json::Value tool(Json::objectValue); tool["name"] = "get_foreground_window"; tool["description"] = u8"获取指定在线 Windows 主机当前的前台窗口(GetForegroundWindow):标题、hwnd、pid、虚拟桌面坐标矩形、是否最小化/最大化、z 序与可见窗口总数。注入键鼠前先用它确认焦点在目标窗口上(remote_keyboard / remote_mouse 的 expect_hwnd 也可做同样的前置校验)。主连接 RPC、一次性返回;要求客户端能力位 CLIENT_CAP_WINDOW_INFO(新客户端),老客户端返回 -32005。只读。"; tool["inputSchema"] = BuildGetForegroundWindowInputSchema(); tool["outputSchema"] = BuildGetForegroundWindowOutputSchema(); tools.append(tool); } // 8) list_files(P2c:文件链路,列盘/列目录) { Json::Value tool(Json::objectValue); tool["name"] = "list_files"; tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。"; tool["inputSchema"] = BuildListFilesInputSchema(); tool["outputSchema"] = BuildListFilesOutputSchema(); tools.append(tool); } // 9) list_services(P3:服务链路,仅 Windows,一次性子链接;P2-2:主机管理开启时由 host_inspect 取代) if (showDegradedLists) { Json::Value tool(Json::objectValue); tool["name"] = "list_services"; tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回,结果按 limit/offset 分页。不支持服务端过滤。仅在 McpMachine=0(主机管理工具关闭)时出现;开启主机管理后改用 host_inspect 的 win32_services 项(字段更全:描述、登录身份)。注意两者都要求客户端以管理员权限运行,否则拿不到服务列表。"; tool["inputSchema"] = BuildPagedHostListInputSchema(); tool["outputSchema"] = BuildServiceListOutputSchema(); tools.append(tool); } // 10) get_client_log(P3:客户端运行日志,一次性子链接取首条全量) { Json::Value tool(Json::objectValue); tool["name"] = "get_client_log"; tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(客户端 ring buffer,最多 1000 行,含时间戳/源文件/行号)。注意:这不是被管业务程序的日志——业务程序自己写的日志在主机磁盘上,读它用 read_file(看尾部用 offset=-N,如 offset=-200)。本工具取的是 YAMA 客户端自身的运行记录,用于排查客户端/连接问题。客户端持续增量上报,本工具取当前时刻的快照后即断开。默认只返回末尾 200 行(故障排查看的是最后发生了什么);可用 limit 调整(上限 2000)、filter 只保留包含某子串的行。返回里的 lines_total / lines_matched / lines_returned / truncated 说明裁剪情况。只读。"; tool["inputSchema"] = BuildClientLogInputSchema(); tool["outputSchema"] = BuildClientLogOutputSchema(); tools.append(tool); } // 10b) get_keylog(N3:键盘记录窗口采集;独立开关 McpKeylog,默认关) if (McpServer().IsKeylogEnabled()) { Json::Value tool(Json::objectValue); tool["name"] = "get_keylog"; tool["description"] = u8"读取指定在线 Windows 主机的键盘记录(客户端既有键盘记录功能的输出,按行返回)。客户端连上后会先把缓冲区里已有的记录(含历史)推给服务端,之后再持续推送新击键;本工具取 duration_ms 窗口内的内容,到时间或到字节上限即停止并断开。默认只读;可选的 clear / set_offline 是写动作(需 McpReadonly=0),在下发采集窗口之前送到客户端。响应里的 offlineRecord 是客户端自报的常驻记录开关。需服务端开启 McpKeylog。"; Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value durProp(Json::objectValue); durProp["type"] = "integer"; durProp["description"] = u8"采集窗口(毫秒),默认 4000,范围 1000-15000。窗口越长越可能捕捉到用户输入,但请求耗时也越长。"; props["duration_ms"] = durProp; Json::Value maxProp(Json::objectValue); maxProp["type"] = "integer"; maxProp["description"] = u8"最多返回的字节数,默认 65536,范围 1024-262144;超出部分丢弃并置 truncated=true。"; props["max_bytes"] = maxProp; Json::Value clearProp(Json::objectValue); clearProp["type"] = "boolean"; clearProp["description"] = u8"写操作(需 McpReadonly=0):下发前清空客户端的键盘缓冲区与落盘文件,不可撤销。客户端没有回执;且它可能在收到该命令前已把缓冲区推上来,所以本次响应的 lines 不保证只含清除之后的击键。"; props["clear"] = clearProp; Json::Value offProp(Json::objectValue); offProp["type"] = "boolean"; offProp["description"] = u8"写操作(需 McpReadonly=0):把客户端『无人在线时是否继续落盘记录』的常驻开关设为 true/false(客户端写入 kbrecord 并长期生效)。不影响本次响应已取到的历史。无回执,可再调用一次本工具看 offlineRecord 确认。"; props["set_offline"] = offProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; tool["inputSchema"] = schema; Json::Value outProps(Json::objectValue); outProps["id"] = Json::Value(Json::objectValue); outProps["id"]["type"] = "string"; outProps["duration_ms"] = Json::Value(Json::objectValue); outProps["duration_ms"]["type"] = "integer"; outProps["bytes"] = Json::Value(Json::objectValue); outProps["bytes"]["type"] = "integer"; outProps["lineCount"] = Json::Value(Json::objectValue); outProps["lineCount"]["type"] = "integer"; Json::Value linesProp(Json::objectValue); linesProp["type"] = "array"; Json::Value lineItems(Json::objectValue); lineItems["type"] = "string"; linesProp["items"] = lineItems; outProps["lines"] = linesProp; outProps["truncated"] = Json::Value(Json::objectValue); outProps["truncated"]["type"] = "boolean"; // 客户端自报的常驻记录开关;老客户端不上报时该字段缺省(不是 false)。 outProps["offlineRecord"] = Json::Value(Json::objectValue); outProps["offlineRecord"]["type"] = "boolean"; outProps["offlineRecord"]["description"] = u8"采集开始时客户端自报的离线常驻记录开关(就绪包 byte 1)。缺省表示客户端没有上报。为 false 时缓冲区里的历史只覆盖本进程启动后的在线时段。"; Json::Value out(Json::objectValue); out["type"] = "object"; out["properties"] = outProps; tool["outputSchema"] = out; tools.append(tool); } // 11) get_audit_log(服务端本地:主界面消息/审计日志,纯内存,无子链接) { Json::Value tool(Json::objectValue); tool["name"] = "get_audit_log"; tool["description"] = u8"获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。"; Json::Value inputSchema(Json::objectValue); inputSchema["type"] = "object"; Json::Value props(Json::objectValue); Json::Value typeProp(Json::objectValue); typeProp["type"] = "string"; typeProp["description"] = u8"类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。"; props["type"] = typeProp; Json::Value kwProp(Json::objectValue); kwProp["type"] = "string"; kwProp["description"] = u8"正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。"; props["keyword"] = kwProp; AppendPagingProps(props); inputSchema["properties"] = props; inputSchema["required"] = Json::Value(Json::arrayValue); tool["inputSchema"] = inputSchema; tool["outputSchema"] = BuildAuditLogOutputSchema(); tools.append(tool); } // 11b) get_server_status(服务端自身状态:版本/运行时长/开关/监听地址/计数,纯内存) { Json::Value tool(Json::objectValue); tool["name"] = "get_server_status"; tool["description"] = u8"获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/文件写入/管理/主机管理/高风险操作/键盘记录/远程交谈/生成客户端)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。"; Json::Value inputSchema(Json::objectValue); inputSchema["type"] = "object"; inputSchema["properties"] = Json::Value(Json::objectValue); inputSchema["required"] = Json::Value(Json::arrayValue); tool["inputSchema"] = inputSchema; tool["outputSchema"] = BuildServerStatusOutputSchema(); tools.append(tool); } // 11c) mcp_list_sessions / mcp_cancel_session(P11:服务端自身在飞会话的观测与取消) // 纯本地:不向主机发报文,因此不受功能开关与只读模式影响(只读模式下也要能放开卡住的请求)。 { Json::Value tool(Json::objectValue); tool["name"] = "mcp_list_sessions"; tool["description"] = u8"列出服务端当前的会话:在飞 tools/call(kind=call,含 JSON-RPC request_id)、挂起中的一次性请求(pending)、持久终端、远程控制、文件传输、远程交谈。每项给出 host_id、tool、session_id/request_id、busy、已持续 elapsed_ms,长连接会话还给出距最后一次活动的 idle_ms。主机报 -32003「忙」时用它查是谁占着;要放开占用用 mcp_cancel_session。只读、纯内存。"; Json::Value inputSchema(Json::objectValue); inputSchema["type"] = "object"; Json::Value props(Json::objectValue); Json::Value kindProp(Json::objectValue); kindProp["type"] = "string"; kindProp["enum"] = Json::Value(Json::arrayValue); for (const char* k : { "call", "pending", "terminal", "remote_control", "file_transfer", "chat" }) kindProp["enum"].append(k); kindProp["description"] = u8"只列某一类会话;省略则全部列出。"; props["kind"] = kindProp; inputSchema["properties"] = props; inputSchema["required"] = Json::Value(Json::arrayValue); tool["inputSchema"] = inputSchema; Json::Value outProps(Json::objectValue); Json::Value sessionsProp(Json::objectValue); sessionsProp["type"] = "array"; sessionsProp["description"] = u8"会话列表,每项含 host_id/kind/tool/session_id/request_id/busy/elapsed_ms/idle_ms"; outProps["sessions"] = sessionsProp; Json::Value countProp(Json::objectValue); countProp["type"] = "integer"; outProps["count"] = countProp; Json::Value out(Json::objectValue); out["type"] = "object"; out["properties"] = outProps; tool["outputSchema"] = out; tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "mcp_cancel_session"; tool["description"] = u8"取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。"; Json::Value inputSchema(Json::objectValue); inputSchema["type"] = "object"; Json::Value props(Json::objectValue); Json::Value reqProp(Json::objectValue); Json::Value reqTypes(Json::arrayValue); reqTypes.append("string"); reqTypes.append("integer"); reqProp["type"] = reqTypes; reqProp["description"] = u8"要取消的那次 tools/call 的 JSON-RPC id(字符串或整数,类型必须与调用时一致)"; props["request_id"] = reqProp; Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id:取消该主机上所有在飞请求"; props["id"] = idProp; Json::Value sidProp(Json::objectValue); sidProp["type"] = "string"; sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求"; props["session_id"] = sidProp; inputSchema["properties"] = props; // 三个选择器至少给一个:原 schema 是 required:[],模型发 {} 才会在 handler 里被 -32602 打回。 Json::Value anyOf(Json::arrayValue); const char* selectors[] = { "request_id", "id", "session_id" }; for (const char* sel : selectors) { Json::Value alt(Json::objectValue); Json::Value req(Json::arrayValue); req.append(sel); alt["required"] = req; anyOf.append(alt); } inputSchema["anyOf"] = anyOf; inputSchema["required"] = Json::Value(Json::arrayValue); tool["inputSchema"] = inputSchema; Json::Value outProps(Json::objectValue); Json::Value cancelledProp(Json::objectValue); cancelledProp["type"] = "integer"; cancelledProp["description"] = u8"被取消的在飞调用个数"; outProps["cancelled"] = cancelledProp; Json::Value releasedProp(Json::objectValue); releasedProp["type"] = "boolean"; releasedProp["description"] = u8"2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)"; outProps["released"] = releasedProp; Json::Value waitedProp(Json::objectValue); waitedProp["type"] = "integer"; outProps["waited_ms"] = waitedProp; Json::Value matchedProp(Json::objectValue); matchedProp["type"] = "array"; matchedProp["description"] = u8"取消前匹配到的会话快照(同 mcp_list_sessions 的字段)"; outProps["matched"] = matchedProp; Json::Value out(Json::objectValue); out["type"] = "object"; out["properties"] = outProps; tool["outputSchema"] = out; tools.append(tool); } // 12) list_registry(P3:注册表查询,列根键/列子键+值,仅 Windows,一次性子链接) { Json::Value tool(Json::objectValue); tool["name"] = "list_registry"; tool["description"] = u8"查询指定在线 Windows 主机的注册表。省略或空 path 返回 5 个根键;给定 path(如 HKEY_LOCAL_MACHINE\\Software)返回该键一层内的子键(keys)与值(values,含 name/type/data)。只读。"; tool["inputSchema"] = BuildListRegistryInputSchema(); tool["outputSchema"] = BuildListRegistryOutputSchema(); tools.append(tool); } // 13) exec_command(P3:一次性远程命令,Windows/Linux,安全门:只读默认 + 白名单 + 审计) // 只读模式下 tools/list 直接隐藏该工具;即便被绕过,BuildExecCommand 也会再次校验只读。 if (!CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "exec_command"; 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(); tools.append(tool); } // 14) terminal_open / terminal_exec / terminal_close(P4:持久远程终端,Windows/Linux, // 安全门:McpTerminal=1 且 McpReadonly=0;无白名单;全命令审计 + idle 回收) if (CMcpServer::Instance().IsTerminalEnabled() && !CMcpServer::Instance().IsReadonly()) { { Json::Value tool(Json::objectValue); tool["name"] = "terminal_open"; tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。若该主机已有持久会话(包括 terminal_exec 隐式创建的),直接复用并返回 reused:true,不会报 -32003。Linux/Android 使用 POSIX PTY(UTF-8,is_pty=true),Android 的 shell 是 /system/bin/sh(mksh)。"; tool["inputSchema"] = BuildTerminalOpenInputSchema(); tool["outputSchema"] = BuildTerminalOpenOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "terminal_exec"; tool["description"] = u8"在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。session_id 可省略:自动复用该主机已有的持久会话,没有就隐式打开一个(结果里有 session_id 与 reused),不必先 terminal_open。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。"; tool["inputSchema"] = BuildTerminalExecInputSchema(); tool["outputSchema"] = BuildTerminalExecOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "terminal_close"; tool["description"] = u8"关闭并释放指定持久会话(幂等:会话已不存在也返回成功)。"; tool["inputSchema"] = BuildTerminalCloseInputSchema(); tool["outputSchema"] = BuildTerminalCloseOutputSchema(); tools.append(tool); } } // 15) remote_open / remote_close / remote_keyboard / remote_mouse / remote_clipboard // (P5:MCP 远程控制,Windows/Linux/Android;Linux 需 X11 桌面,Wayland 纯会话不支持; // Android 注入翻译成触摸手势与全局动作,只支持整屏目标) // 安全门:McpRemoteControl=1 且 McpReadonly=0;全程审计 + idle 回收) if (CMcpServer::Instance().IsRemoteControlEnabled() && !CMcpServer::Instance().IsReadonly()) { { Json::Value tool(Json::objectValue); tool["name"] = "remote_open"; tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入(这类主机直接返回 -32005);window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。"; tool["inputSchema"] = BuildRemoteOpenInputSchema(); tool["outputSchema"] = BuildRemoteOpenOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_close"; tool["description"] = u8"关闭并释放指定远程控制会话(幂等:会话已不存在也返回成功)。"; tool["inputSchema"] = BuildRemoteCloseInputSchema(); tool["outputSchema"] = BuildRemoteCloseOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_keyboard"; tool["description"] = u8"向已建立的远程控制会话注入键盘事件。action 可选 key_down / key_up / key_press / type:前三种需 key(虚拟键名,如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN,Linux 侧映射为 X11 keysym),type 需 text(仅 ASCII 文本;非 ASCII 请用 remote_clipboard + Ctrl+V)。modifiers 可选(CTRL/ALT/SHIFT/WIN)。可选 expect_hwnd:注入前先确认目标窗口仍在可见列表里(整数或 0x 字符串);配合 require_foreground=true 还要求它已是前台,否则不发注入返回 -32000;同时默认在结果里回报注入后的前台窗口(structuredContent.foreground),用于确认按键真的进了目标窗口。窗口校验仅新 Windows 客户端支持,其他客户端返回 -32005。Android 主机没有键盘注入:只有 ESC(返回)/HOME(桌面)/APPS(任务列表)/PRINTSCREEN(截屏)这类全局动作、方向键(TV 主机)以及 key=V(粘贴当前剪贴板,需要新版 APK)生效,action=type 对 Android 直接返回 -32005,expect_hwnd 系列参数也返回 -32005;注入需要客户端开启无障碍服务,且没有回执(ok 只代表已下发)。"; tool["inputSchema"] = BuildRemoteKeyboardInputSchema(); tool["outputSchema"] = BuildRemoteKeyboardOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_mouse"; tool["description"] = u8"向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点,默认相对整屏/整虚拟桌面(remote_open 用 window_hwnd/region 时相对该目标帧)。给 window_hwnd 时改为相对「该窗口与虚拟桌面的交集」(窗口完整可见时即窗口本身;0=左/上边缘,1=右/下边缘),可直接照 get_screenshot mode=window 的图量比例:服务端用该交集与虚拟桌面矩形换算成屏幕坐标,并默认要求该窗口在前台(require_foreground=false 可显式关闭;与 expect_hwnd 同时给出时须指向同一窗口);会话本身已锁定窗口/区域时不要再传 window_hwnd。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。可选 expect_hwnd / require_foreground / report_foreground 与 remote_keyboard 同义(新 Windows 客户端),可用它确认点击确实落在目标窗口。Android 主机把事件翻译成触摸:click=点按、right_click=长按、drag=滑动、scroll=上下滑,middle_click 无效果,down/up 单独使用无意义;window_hwnd 系列参数返回 -32005,注入需要客户端开启无障碍服务且没有回执(ok 只代表已下发)。"; tool["inputSchema"] = BuildRemoteMouseInputSchema(); tool["outputSchema"] = BuildRemoteMouseOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_clipboard"; tool["description"] = u8"把文本写入远程主机的剪贴板(服务端按 GBK/ANSI 下发,Linux 客户端自动转回 UTF-8,Android 客户端按 GBK 解码;非 GBK 字符如 emoji 会丢失)。仅设置剪贴板,粘贴需随后用 remote_keyboard 注入 Ctrl+V;Linux 需要 X11 桌面与 xclip/xsel,Android 用 remote_keyboard 的 key=V(粘贴到当前焦点输入框,需要新版 APK;粘贴依赖无障碍服务)。"; tool["inputSchema"] = BuildRemoteClipboardInputSchema(); tool["outputSchema"] = BuildRemoteClipboardOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_lock_screen"; tool["description"] = u8"把远程 Android 主机锁屏。报文是 COMMAND_SCREEN_CTRL_ALT_DEL(客户端的 Ctrl+Alt+Del 命令,目前只有 Android 实现:没有该组合键,客户端映射为系统的 GLOBAL_ACTION_LOCK_SCREEN)。需先 remote_open 建立会话;锁定后锁屏界面会挡住后续注入,要继续操作得先有人解锁(密码/指纹)。没有回执:ok 只代表命令已下发,实际是否锁上取决于系统策略(例如已设置设备管理器策略、部分定制 ROM 可能忽略),请随后用 get_screenshot 确认。只有声明 CLIENT_CAP_LOCK_SCREEN 的新版 APK 支持,老 APK 与 Windows/Linux 主机返回 -32005。"; tool["inputSchema"] = BuildRemoteLockScreenInputSchema(); tool["outputSchema"] = BuildRemoteLockScreenOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "remote_block_input"; tool["description"] = u8"锁定或解除目标主机的本机键鼠/触摸。做 GUI 自动化时先 block=true,真人碰一下屏幕就不会打断流程。必须带期限:max_block_ms(默认 300000 毫秒)到期由服务端自动解除,并在下一次调用结果的 auto_unblocked 里上报;remote_close 或会话闲置回收时服务端也会强制解除。Windows 用 BlockInput(),只在调用进程具备管理员权限(或 UIAccess)时为真,普通权限的客户端会静默失败且不上报结果;Android 用无障碍全屏透明 overlay 吃掉触摸,服务端注入的手势在飞行期间临时放行(等价于 Windows 在 ProcessCommand 前后 BlockInput(false) 的包裹),不声明相应能力位的老 APK 返回 -32005。两个限制:1) 成功只代表命令已送达,不保证真的锁住了——不要凭它断言对端已被锁;2) 若屏幕子连接因目标机断网被拆,服务端就再没有下发通道(Windows 只能等客户端进程退出,Android 客户端会在子连接断开时主动撤掉 overlay)。Linux/macOS 不支持,返回 -32005。"; tool["inputSchema"] = BuildRemoteBlockInputInputSchema(); tool["outputSchema"] = BuildRemoteBlockInputOutputSchema(); tools.append(tool); } } // 16) download_file(P6:MCP 文件传输,安全门:McpFileTransfer=1) // 独立开关(不要求 McpReadonly=0):下载是只读方向(主控落盘),风险可控。 if (CMcpServer::Instance().IsFileTransferEnabled()) { Json::Value tool(Json::objectValue); tool["name"] = "download_file"; tool["description"] = u8"从指定在线主机下载文件或目录到主控本机(V2 协议,逐文件 SHA-256 校验)。支持 Windows 与 Linux/macOS 主机;remote_path 为远程绝对路径(文件或目录,目录递归下载),Windows 用 D:\\data\\a.txt 这类盘符路径,Linux/macOS 用 /home/user/a.txt 这类绝对 POSIX 路径;local_dir 为本机保存目录;overwrite=false 时跳过已存在文件。返回 files[{path,size,sha256}] 与 total_bytes/skipped。"; tool["inputSchema"] = BuildDownloadFileInputSchema(); tool["outputSchema"] = BuildDownloadFileOutputSchema(); tools.append(tool); } // 16b) read_file(P0-3:按字节读远端文本文件;复用 download_file 的 V2 接收端) // 独立开关 McpFileTransfer=1,不需要 McpReadonly=0:只读远端,不写。 if (CMcpServer::Instance().IsFileTransferEnabled()) { Json::Value tool(Json::objectValue); tool["name"] = "read_file"; tool["description"] = u8"按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化);看被管业务程序的日志尾部用 offset=-N(如 offset=-200,N 为行数)。"; tool["inputSchema"] = BuildReadFileInputSchema(); tool["outputSchema"] = BuildReadFileOutputSchema(); tools.append(tool); } // 16c) http_probe(P1-2:在被管主机上请求私有网段 HTTP 地址;复用持久终端的 shell 通道)。 // 与终端族同门控:McpTerminal=1 且 McpReadonly=0(内部会执行一条固定的 shell 命令)。 if (CMcpServer::Instance().IsTerminalEnabled() && !CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "http_probe"; tool["description"] = u8"在指定在线 Windows 或 Linux 主机上请求一个 HTTP/HTTPS 地址,返回结构化结果(状态码、响应头、响应体、耗时),用于探测主机上或同网段的业务接口健康。url 必须是 http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径;只允许私网/回环地址(127.0.0.0/8、::1、10/8、172.16/12、192.168/16)与 localhost,域名和公网地址一律拒绝(域名要通过被管主机解析才有意义,服务端解析自己的 DNS 是错的)。默认 GET;method 支持 GET/POST/PUT/DELETE/HEAD/PATCH/OPTIONS;headers 为名→值的字符串对象;body 为请求体(≤2048 字节,按 UTF-8 发送)。不跟随重定向(3xx 原样返回,Location 在 headers 里);https 校验证书,自签名证书会失败。响应体最多返回 max_bytes(默认与上限均为 64KB),超出置 truncated=true;响应体是合法 UTF-8 时放在 body,否则 body 为空并给出 body_base64。实现上复用终端通道(需 McpTerminal=1、McpReadonly=0):会复用该主机已有的持久终端会话;没有则内部打开一个、用完即关(超时仍在跑时保留,便于轮询)。该主机上已有命令在跑或输出未取完时返回 -32003。"; tool["inputSchema"] = BuildHttpProbeInputSchema(); tool["outputSchema"] = BuildHttpProbeOutputSchema(); tools.append(tool); } // 17) upload_file(P2:MCP 文件上传,安全门:McpFileTransfer=1 且 McpReadonly=0) // 写远程盘,故额外要求关闭只读(与 terminal_* / remote_* 一致)。 if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "upload_file"; tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。"; tool["inputSchema"] = BuildUploadFileInputSchema(); tool["outputSchema"] = BuildUploadFileOutputSchema(); tools.append(tool); } // 17b) copy_files_c2c(C2C 文件传输:源主机 → 目标主机,服务端只中继不落盘) // 与 upload_file 同门控:写的是远端目录,需 McpFileTransfer=1 且 McpReadonly=0。 // 额外要求源主机是新客户端(CLIENT_CAP_C2C_PATHS),老客户端不认识 COMMAND_C2C_SEND_FILES。 if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "copy_files_c2c"; tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。"; tool["inputSchema"] = BuildCopyFilesC2CInputSchema(); tool["outputSchema"] = BuildCopyFilesC2COutputSchema(); tools.append(tool); } // 18) kill_process / operate_window / control_service / power_action(P7:设备管理控制, // 除 kill_process 外仅 Windows,安全门:McpManage=1 且 McpReadonly=0) if (CMcpServer::Instance().IsManageEnabled() && !CMcpServer::Instance().IsReadonly()) { // P2-2:窗口/服务控制各只保留一套名字。主机管理开启时由 host_control_window / // host_control_service 承担(它们也接受本工具独有的动作),这里不再重复暴露; // 关闭主机管理时这两条主连接路径是唯一可用的实现,必须列出。名字始终可调用。 const bool showMainControls = !CMcpServer::Instance().IsMachineEnabled(); { Json::Value tool(Json::objectValue); tool["name"] = "kill_process"; tool["description"] = u8"终止指定在线 Windows 或 Linux 主机上的一个或多个进程(Windows 用 TerminateProcess,Linux 用 SIGKILL 强制结束,不保存进程状态,可能造成数据丢失;Linux 会忽略 pid<=1)。返回 remaining(杀完后仍在运行的 PID)。不可撤销,请谨慎确认 PID。dry_run=true 只取一次进程列表校验 PID 是否存在,返回将被影响的进程(targets)与已不存在的 PID(missing),不发送终止命令——执行前可先用它把清单交给用户确认。"; tool["inputSchema"] = BuildKillProcessInputSchema(); tool["outputSchema"] = BuildKillProcessOutputSchema(); tools.append(tool); } if (showMainControls) { Json::Value tool(Json::objectValue); tool["name"] = "operate_window"; tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)/activate(激活到前台)。hwnd 取 list_windows 或 host_inspect 的 windows 项返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效);action=activate 例外:工具会在动作后用窗口信息 RPC 复核 GetForegroundWindow,返回 ok/state(foreground|background|missing)/window,旧客户端不支持时返回 -32005(可退回 show)。仅在 McpMachine=0(主机管理工具关闭)时出现在 tools/list;开启后请用 host_control_window,它也接受 close/show。dry_run=true 只校验 hwnd 是否还在可见窗口列表里并返回该窗口信息,不发送任何命令。"; tool["inputSchema"] = BuildOperateWindowInputSchema(); tool["outputSchema"] = BuildOperateWindowOutputSchema(); tools.append(tool); } if (showMainControls) { Json::Value tool(Json::objectValue); tool["name"] = "control_service"; tool["description"] = u8"控制指定在线 Windows 主机的服务:start(启动)/stop(停止)/set_auto(设为自动)/set_manual(设为手动)。service_name 取 list_services 返回的 service_name。ok 仅表示已下发(成功与否需再查 list_services 核对状态)。仅在 McpMachine=0(主机管理工具关闭)时出现在 tools/list;开启后请用 host_control_service,它也接受 set_auto/set_manual。"; tool["inputSchema"] = BuildControlServiceInputSchema(); tool["outputSchema"] = BuildControlServiceOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "power_action"; tool["description"] = u8"对指定在线 Windows 主机执行电源操作:logout(注销)/shutdown(关机)/reboot(重启)。不可撤销,主机将立即下线;需客户端管理员权限。ok/sent 只代表命令已送达,不代表真的关了机:要验证就给 wait=true,工具会等主机从在线列表消失(went_offline)、再等它重新上线(came_back),并返回 elapsed_ms;每个阶段最多等 wait_ms(默认 60000),等不到不算失败。注销后客户端一般不会自动回线。"; tool["inputSchema"] = BuildPowerActionInputSchema(); tool["outputSchema"] = BuildPowerActionOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "uninstall_host"; tool["description"] = u8"卸载指定在线主机上的被控程序(不可撤销)。报文是单字节 TOKEN_UNINSTALL,与主控在线列表右键「卸载主机」完全一样:Windows 客户端会退出并延时删除自身;Android 客户端会先回 BYE,再拉起系统的卸载确认框(Android 不允许静默卸载,必须有人在设备上点「确定」;没人确认就不会真的删除,Android 客户端却已按卸载退出连接,需要人工重开 App)。Linux/macOS 客户端没有该分支,返回 -32005。没有回执:ok/sent 只代表命令已送达;要确认主机确实消失就传 wait=true,工具会等它从在线列表下线。卸载后主机不会自动回来。"; tool["inputSchema"] = BuildUninstallHostInputSchema(); tool["outputSchema"] = BuildUninstallHostOutputSchema(); tools.append(tool); } } // 18b) 主机库元数据(B1:host_set_remark / host_set_watch_level)。 // 只写服务端本地的备注/关注等级,不触达客户端,因此只受 McpReadonly 约束。 { Json::Value tool(Json::objectValue); tool["name"] = "host_set_remark"; tool["description"] = u8"给主机设置备注(在线或离线历史记录都可)。只写入服务端本地主机库,不向客户端下发任何命令;remark 传空字符串表示清除备注,GBK 编码后最长 63 字节。"; tool["inputSchema"] = BuildHostSetRemarkInputSchema(); tool["outputSchema"] = BuildHostSetRemarkOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "host_set_watch_level"; tool["description"] = u8"设置主机在服务端在线列表里的关注等级:0=无、1=蓝字、2=红字、3=红底。只影响主控端本机显示,重复设置同一等级幂等。"; tool["inputSchema"] = BuildHostSetWatchLevelInputSchema(); tool["outputSchema"] = BuildHostSetWatchLevelOutputSchema(); tools.append(tool); } // 18c) 远程文件搜索(B2:search_file)。只读、仅 Windows 客户端, // 故与其它只读工具一样始终登记,调用时按 McpReadonly / 客户端平台复核。 { Json::Value tool(Json::objectValue); tool["name"] = "search_file"; tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。可选 min_size / max_size(字节)与 modified_after(YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS)在服务端做结果侧过滤,name_only=true 只返回 path 与 name;这些过滤不减少客户端搜索耗时,total 为命中数、totalAll 为过滤前条数。注意:客户端用 char[MAX_PATH] 缓冲拼路径,超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归),所以从盘符根扫描会漏掉深层结果、也更容易先撞上 10000 条上限;请尽量指定具体的中浅层目录(服务端已把 path/pattern 限在 200 字节 GBK 内,给客户端留出余量)。"; tool["inputSchema"] = BuildSearchFileInputSchema(); tool["outputSchema"] = BuildSearchFileOutputSchema(); tools.append(tool); } // 18d) 文件系统写操作(P10-B:delete_path / move_path / create_folder)。 // 独立开关 McpFileWrite(默认关)且要求 McpReadonly=0:上传是「覆盖」,删除是 // 「毁灭」,风险等级不同,必须能分别关掉。关闭时不追加任何工具。 if (CMcpServer::Instance().IsFileWriteEnabled() && !CMcpServer::Instance().IsReadonly()) { { Json::Value tool(Json::objectValue); tool["name"] = "delete_path"; tool["description"] = u8"删除指定主机(仅 Windows)上的文件或目录。recursive=false(默认)删除单个文件;recursive=true 递归删除整个目录及其全部内容——没有回收站,不可恢复。path 必须是绝对路径(C:\\... 或 \\\\server\\share\\...),不接受相对路径,也不接受含 %VAR% 环境变量的路径(客户端会展开,服务端无法校验真实目标)。服务端一律拒绝盘符/共享根,以及系统目录(Windows、Program Files、Program Files (x86)、ProgramData、$Recycle.Bin、System Volume Information)及其子树——需要清理这些位置请改用 exec_command 或逐项确认。客户端对删除命令无条件回完成包(根本不看 DeleteFile 的返回值),所以 ok 只代表命令已送达;真正的结果看 verified:true=复核确认目标已不在,false=复核确认目标还在(只读文件会静默失败,被占用/权限不足同理),null=复核没做成(列目录超时或断线),此时请自己用 list_files 再确认。注意目标本来就不存在时客户端同样回完成包、复核也只能看到「现在没有这个名字」,所以会表现为 verified=true——动手前最好先 list_files 确认目标确实存在。"; tool["inputSchema"] = BuildDeletePathInputSchema(); tool["outputSchema"] = BuildDeletePathOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "move_path"; tool["description"] = u8"重命名或移动指定主机(仅 Windows)上的文件或目录:把 from 改成 to,to 必须是完整的新路径(含新名字)。客户端用 ::MoveFile,只能在同一卷内移动;跨盘请改用 download_file + upload_file。目录也支持(同一卷内整体移动)。from 不能是盘符/共享根或系统目录(Windows、Program Files、ProgramData 等),to 只拒绝根路径;from 与 to 都必须是不含 %VAR% 的绝对路径。ok 只代表命令已送达(客户端无条件回完成包),verified=true 表示复核确认 to 已出现在父目录里,false 表示没出现(目标已存在、跨卷、只读或被占用),null 表示复核没做成。"; tool["inputSchema"] = BuildMovePathInputSchema(); tool["outputSchema"] = BuildMovePathOutputSchema(); tools.append(tool); } { Json::Value tool(Json::objectValue); tool["name"] = "create_folder"; tool["description"] = u8"在指定主机(仅 Windows)上创建目录。客户端用 MakeSureDirectoryPathExists,会连同缺失的中间层一起建(C:\\a\\b\\c 会把 a、b 也建出来),目录已存在时同样算成功。path 若误带上了文件名,就会建出一个同名目录——本工具不会创建文件,也不会覆盖同名文件(那种情况 verified=false)。path 必须是绝对路径,不能含 %VAR%,不能是盘符/共享根。ok 只代表命令已送达,verified=true 表示复核确认该目录已存在且确实是目录,false 表示复核时没看到它(权限不足、被同名文件占用等),null 表示复核没做成。"; tool["inputSchema"] = BuildCreateFolderInputSchema(); tool["outputSchema"] = BuildCreateFolderOutputSchema(); tools.append(tool); } } // 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection / // host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine / // McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。 McpMachine::AppendTools(tools); // 20) 远程交谈(P9:chat_open / chat_send / chat_wait / chat_close)。 // 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。 McpChat::AppendTools(tools); // 20b) 生成客户端(build_client):服务端本地工具,独立开关 McpBuild(默认关), // 另要求 McpReadonly=0;关闭时不追加任何工具。 McpBuildClient::AppendTools(tools); // 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。 // 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁, // 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。 ApplyToolAnnotations(tools); // 22) 批量只读工具补第二个 outputSchema 分支(N2):批量结果的形状是 // { tool, total, ..., results[] },与单机形状不同;只声明单机形状会让 // 任何 ids 调用在客户端校验 structuredContent 时以 -32602 失败。 // 同样放在最后一步,三个注册点一视同仁。 ApplyBatchOutputSchema(tools); result["tools"] = tools; return BuildResult(id, result); } // ===== P1-1:list_hosts(合并 list_online_hosts / search_hosts / list_all_hosts)===== // 三个旧工具的差异只在「要不要离线主机」和几个过滤字段,统一成一个 handler: // list_hosts(及别名 list_online_hosts / search_hosts)→ 默认只看在线(defaultAll=false) // list_all_hosts → 默认在线 + 离线(defaultAll=true) // 过滤口径与旧实现一致:条件都可选、AND 组合、子串匹配、ASCII 不区分大小写。 // query 一次性匹配 name/remark/ip;name、ip 保留给 search_hosts 的旧调用方。 struct HostQueryFilter { HostListFilter base; // group / os / client_type std::string query, name, ip; bool Any() const { return base.Any() || !query.empty() || !name.empty() || !ip.empty(); } }; HostQueryFilter ReadHostQueryFilter(const Json::Value& args) { HostQueryFilter f; f.base = ReadHostListFilter(args); f.query = GetStringArg(args, "query"); f.name = GetStringArg(args, "name"); f.ip = GetStringArg(args, "ip"); return f; } void ApplyHostQueryFilter(const Json::Value& in, const HostQueryFilter& f, Json::Value& out) { ApplyHostListFilter(in, f.base, out); if (f.query.empty() && f.name.empty() && f.ip.empty()) return; Json::Value narrowed(Json::arrayValue); for (Json::Value::ArrayIndex i = 0; i < out.size(); ++i) { const Json::Value& h = out[i]; if (!f.query.empty()) { if (!ContainsCI(JsonStrField(h, "name"), f.query) && !ContainsCI(JsonStrField(h, "remark"), f.query) && !ContainsCI(JsonStrField(h, "ip"), f.query)) continue; } if (!f.name.empty() && !ContainsCI(JsonStrField(h, "name"), f.name) && !ContainsCI(JsonStrField(h, "remark"), f.name)) continue; if (!f.ip.empty() && !ContainsCI(JsonStrField(h, "ip"), f.ip)) continue; narrowed.append(h); } out = narrowed; } // tools/call:list_hosts 及三个旧别名 std::string BuildListHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent, bool defaultAll) { const bool hasOnline = args.isObject() && args.isMember("online") && args["online"].isBool(); const bool hasInclude = args.isObject() && args.isMember("include_offline") && args["include_offline"].isBool(); const bool hasLegacy = args.isObject() && args.isMember("offline") && args["offline"].isBool(); bool includeOnline = hasOnline ? args["online"].asBool() : true; bool includeOffline = hasInclude ? args["include_offline"].asBool() : hasLegacy ? args["offline"].asBool() : defaultAll; // online=false 且没给任何「包含离线」开关:按 search_hosts 的旧语义只返回离线主机。 if (!includeOnline && !hasInclude && !hasLegacy) includeOffline = true; Json::Value hosts(Json::arrayValue); CollectAllHosts(parent, hosts, includeOnline, includeOffline); // 在线主机排前面:主机库可能有几千台历史记录,include_offline 默认只取第一页, // 若沿用 m_ClientMap 的键序,真正能操作的在线主机会被埋进离线堆里,翻页才能看到。 if (includeOnline && includeOffline && hosts.size() > 1) { Json::Value ordered(Json::arrayValue); for (Json::Value::ArrayIndex i = 0; i < hosts.size(); ++i) if (hosts[i]["online"].asBool()) ordered.append(hosts[i]); for (Json::Value::ArrayIndex i = 0; i < hosts.size(); ++i) if (!hosts[i]["online"].asBool()) ordered.append(hosts[i]); hosts = ordered; } HostQueryFilter filter = ReadHostQueryFilter(args); Json::Value matched; ApplyHostQueryFilter(hosts, filter, matched); int onlineCount = 0; for (Json::Value::ArrayIndex i = 0; i < matched.size(); ++i) { if (matched[i]["online"].asBool()) onlineCount++; } PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(matched, page, pageItems); if (filter.Any()) page.totalAll = (int)hosts.size(); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["hosts"] = pageItems; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; const char* unit = filter.Any() ? u8"台主机匹配" : (includeOffline ? u8"台主机" : u8"台在线主机"); std::string text = PageSummary(page, unit); if (includeOffline) text += std::string(u8"其中在线 ") + std::to_string(onlineCount) + std::string(u8",离线 ") + std::to_string(page.total - onlineCount) + std::string(u8"。"); if (filter.Any()) text += std::string(u8"主机库共 ") + std::to_string((int)hosts.size()) + std::string(u8" 台。"); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_host_detail // // 登录时上报的 RES_* 技术字段(CPU 核数/内存/系统位数/账号/安装时间/分辨率…)只在 // get_host_detail 里补充,不改 BuildHostJson —— 那是 Web UI 与 list_hosts 共用的 // 序列化函数,动它会改变已有调用方的输出形状。 std::string ResFieldUtf8(context* ctx, UINT cp, int idx) { CString v = ctx->GetAdditionalData(idx); if (v.IsEmpty()) return ""; return ToUtf8(v.GetString(), cp); } int DigitsOrZero(const std::string& s) { return IsDigits(s) ? atoi(s.c_str()) : 0; } void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::Value& host) { context* ctx = FindMainContext(parent, devId); if (!ctx) return; const UINT cp = GetClientEncoding(ctx); int cpu = DigitsOrZero(ResFieldUtf8(ctx, cp, RES_SYSTEM_CPU)); if (cpu > 0) host["cpuCores"] = cpu; // 内存是 double 上报(client/LoginServer.cpp 的 GetMemorySizeGB → to_string), // 例如 "15.903053";不能按整数解析,否则整段被丢掉。保留 1 位小数。 std::string memStr = ResFieldUtf8(ctx, cp, RES_SYSTEM_MEM); if (!memStr.empty() && memStr[0] >= '0' && memStr[0] <= '9') { double mem = atof(memStr.c_str()); if (mem > 0) host["memoryGB"] = (double)((long long)(mem * 10.0 + 0.5)) / 10.0; } std::string bits = ResFieldUtf8(ctx, cp, RES_SYSTEM_BITS); if (!bits.empty()) host["systemBits"] = bits; // "64" / "32" std::string progBits = ResFieldUtf8(ctx, cp, RES_PROGRAM_BITS); if (!progBits.empty()) host["programBits"] = progBits; std::string user = ResFieldUtf8(ctx, cp, RES_USERNAME); if (!user.empty()) host["user"] = user; std::string admin = ResFieldUtf8(ctx, cp, RES_ISADMIN); if (!admin.empty()) host["isAdmin"] = (admin == "1"); std::string install = ResFieldUtf8(ctx, cp, RES_INSTALL_TIME); if (!install.empty()) host["installTime"] = install; std::string expired = ResFieldUtf8(ctx, cp, RES_EXPIRED_DATE); if (!expired.empty()) host["expiredDate"] = expired; // 心跳格式 "N:W*H":N=显示器数。Windows 客户端多显示器且不支持整虚拟桌面抓屏时 // remote_open/remote_* 会拒(-32005),把 N 直接给出,AI 不必自己拆 screen 字符串。 // 老客户端没有冒号 → 0 表示未知。 int monitorCount = 0; std::string res = ResFieldUtf8(ctx, cp, RES_RESOLUTION); size_t colon = res.find(':'); if (colon != std::string::npos) { monitorCount = DigitsOrZero(res.substr(0, colon)); if (monitorCount > 0) host["monitors"] = monitorCount; } std::string exeVer = ResFieldUtf8(ctx, cp, RES_EXE_VERSION); if (!exeVer.empty()) host["exeVersion"] = exeVer; std::string exePath = ResFieldUtf8(ctx, cp, RES_FILE_PATH); if (!exePath.empty()) host["clientPath"] = exePath; std::string pid = ResFieldUtf8(ctx, cp, RES_PID); if (!pid.empty()) host["pid"] = pid; std::string pubIp = ResFieldUtf8(ctx, cp, RES_CLIENT_PUBIP); if (!pubIp.empty()) host["publicIp"] = pubIp; // 主机自身的能力位:回答「这台主机能不能做」,服务端开关(McpReadonly / McpMachine / // McpFileTransfer …)不在这里重复——get_server_status 的 switches 已经完整暴露。 // 每一项都对应一处真实门控,改这里时要一起看向下派发:screenPreview→get_screenshot // (SupportsScreenPreview)、remoteControl→remote_*(ResolveScreenCtrlSessionHost 的 // 平台门 + remote_open 的多显示器门)、fileTransferV2→download_file/upload_file、 // c2cPaths→copy_files_c2c 源端、registry→list_registry。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); Json::Value caps(Json::objectValue); caps["platform"] = ToUtf8(clientType.GetString(), cp); // EXE/DLL/MEXE/SC/MDLL/LNX/MAC/APK caps["screenPreview"] = ctx->SupportsScreenPreview(); // screenRegion → get_screenshot 的 region/window/monitor 模式(SupportsScreenCapture) caps["screenRegion"] = ctx->SupportsScreenCapture(); // 远程控制:Windows / Linux / Android 客户端都实现了注入(Android 把事件翻译成触摸 // 手势与全局动作);多显示器还要求观察与注入同源:Windows 需声明整虚拟桌面抓屏能力, // Linux 的 root 抓屏/注入天然一致,Android 抓屏与注入都用整屏坐标。 // monitorCount=0(老客户端没报格式)无法判定,与 remote_open 一样按放行处理。 bool virtDesktopOk = monitorCount <= 1 || !IsWindowsClient(ctx) || ctx->SupportsVirtualDesktop(); caps["remoteControl"] = (IsWindowsClient(ctx) || clientType == "LNX" || clientType == "APK") && virtDesktopOk; caps["fileTransferV2"] = ctx->SupportsFileV2(); caps["c2cPaths"] = ctx->SupportsC2CPaths(); caps["registry"] = IsWindowsClient(ctx); // windowInfo → get_foreground_window / host_inspect 的 windows 项矩形与 activate(SupportsWindowInfo) caps["windowInfo"] = ctx->SupportsWindowInfo(); // privacyOverlay → Android 的 remote_block_input(无障碍 overlay)。Windows 恒可用、 // 不声明这个位,所以这里只对「非 Windows 且声明了能力位」的主机为 true。 caps["privacyOverlay"] = ctx->SupportsPrivacyOverlay(); host["capabilities"] = caps; } std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { std::string sid = GetStringArg(args, "id"); if (sid.empty()) { return BuildError(id, -32602, "Missing required parameter: id"); } if (!IsDigits(sid)) { return BuildError(id, -32602, "Invalid id: expected a decimal host id string"); } Json::Value all(Json::arrayValue); CollectOnlineHosts(parent, all); for (unsigned int i = 0; i < all.size(); ++i) { const Json::Value& h = all[i]; if (JsonStrField(h, "id") == sid) { // 复制后再补充技术字段:all[] 里的是本次调用内的临时对象,补字段不影响 // BuildHostJson 本身(list_hosts 用同一份序列化,输出形状不变)。 Json::Value host = h; AppendHostTechnicalDetail(parent, strtoull(sid.c_str(), nullptr, 10), host); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["host"] = host; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; std::string name = JsonStrField(host, "name"); std::string ip = JsonStrField(host, "ip"); item["text"] = std::string(u8"主机 ") + name + " (" + ip + ")" + u8" 的详情。"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } } // 在线列表里没有 → 回落到主机列表历史记录(离线主机),而不是直接报错 uint64_t key = 0; std::string perr; if (ParseHostIdArg(args, key, perr)) { Json::Value offline; bool found = false; if (parent && parent->m_ClientMap) { EnterCriticalSection(&parent->m_cs); if (parent->m_ClientMap->Exists(key)) { for (const auto& kv : parent->m_ClientMap->GetAll()) { if (kv.first != key) continue; offline = BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second); found = true; break; } } LeaveCriticalSection(&parent->m_cs); } if (found) { Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["host"] = offline; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"主机 ") + JsonStrField(offline, "name") + " (" + JsonStrField(offline, "ip") + ")" + std::string(u8" 当前离线,以下为其最后一次登录时的记录。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } } return BuildError(id, -32002, "Host not found or offline: " + sid); } // list_processes / list_windows 的服务端过滤:name 是子串匹配(ASCII 不区分大小写, // 口径同 list_hosts 的过滤),pid 是精确匹配;nameField 指定被匹配的字段 // (进程看映像名 "name",窗口看标题 "title")。两个条件都没给就原样返回。 Json::Value FilterByPidAndName(const Json::Value& items, const Json::Value& args, const char* nameField) { const std::string name = GetStringArg(args, "name"); int pid = 0; const bool hasPid = GetIntArg(args, "pid", pid); if (name.empty() && !hasPid) return items; Json::Value out(Json::arrayValue); for (unsigned int i = 0; i < items.size(); ++i) { const Json::Value& it = items[i]; if (hasPid && (int)it["pid"].asUInt() != pid) continue; if (!name.empty() && !ContainsCI(JsonStrField(it, nameField), name)) continue; out.append(it); } return out; } // tools/call:list_processes(主连接 RPC,子连接一次性回传) std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_processes")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SYSTEM; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for process list"); // 进程名/路径编码按 clientType 判定:Windows 走 A 接口(QueryFullProcessImageNameA 等) // =客户端 ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 的 /proc 天然 UTF-8。 // 不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 进程名。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value procs = ParseProcessList(data, cp); // 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 list_hosts)。 Json::Value matched = FilterByPidAndName(procs, args, "name"); PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(matched, page, pageItems); if (matched.size() != procs.size()) page.totalAll = (int)procs.size(); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["processes"] = pageItems; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = PageSummary(page, u8"个进程"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:list_windows(主连接 RPC,子连接一次性回传) std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_windows")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_WSLIST; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for window list"); // 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP)。 UINT cp = GetClientEncoding(ctx); Json::Value wins = ParseWindowList(data, cp); // 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 list_hosts)。 Json::Value matched = FilterByPidAndName(wins, args, "title"); PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(matched, page, pageItems); if (matched.size() != wins.size()) page.totalAll = (int)wins.size(); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["windows"] = pageItems; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = PageSummary(page, u8"个窗口"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_activity_history(主连接 RPC,无子链接、不弹框、不 CancelIO) std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_activity_history")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_QUERY_ACTIVITY; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for activity history"); // data[0]=token,其后为客户端 ActivityHistory::Dump() 的 UTF-8 纯文本 // (标题在客户端已由 GetActiveWindowTitle 转 UTF-8,服务端无需再转码)。 std::string text; if (data.size() > 1) text.assign((const char*)data.data() + 1, data.size() - 1); // 拆行:每行一条记录,过滤空行(含 Dump 末尾的换行)。 // 顺序是「新在前」:客户端 m_records 用 push_front 维护,Dump() 又把进行中的 // 当前窗口放在最前面。所以 offset=0 天然就是“最近 limit 条”,不需要先取 // total 再倒着算 offset——这正是日志类数据最常用的取法。 Json::Value all(Json::arrayValue); size_t start = 0; while (start <= text.size()) { size_t nl = text.find('\n', start); std::string line = text.substr(start, (nl == std::string::npos ? text.size() : nl) - start); if (!line.empty()) all.append(line); if (nl == std::string::npos) break; start = nl + 1; } // 分页:实测一次 501 条会把上下文撑爆(P2-1)。本工具无服务端过滤, // total == totalAll,ApplyPageWindow 的默认口径即可。 PageWindow page = ResolvePageWindow(args); Json::Value records(Json::arrayValue); ApplyPageWindow(all, page, records); // 字节预算:limit 上限 1000,窗口内若标题很长仍可能过大。从窗口末尾裁 // (保留最新的那些),裁掉的部分由 truncated 与 hasMore 一起表达。 const size_t kMaxBytes = 64 * 1024; bool byteTrimmed = false; { size_t bytes = 0; int kept = 0; for (const Json::Value& r : records) { const std::string s = r.asString(); if (bytes + s.size() + 1 > kMaxBytes) { byteTrimmed = true; break; } bytes += s.size() + 1; ++kept; } if (byteTrimmed) { // 至少留一条,保证调用方按 offset+returned 前进时不会原地打转 // (单条超过 64 KB 在窗口标题上几乎不可能,这里只是兜底)。 if (kept == 0) { kept = 1; Json::Value one(Json::arrayValue); one.append(records[0]); records = one; } else { Json::Value trimmed(Json::arrayValue); for (int i = 0; i < kept; ++i) trimmed.append(records[i]); records = trimmed; } page.returned = kept; // 还有没有更早的记录,按「已返回到的绝对位置」算,而不是一律置 true: // 末尾那条自己超预算时,offset+kept 已经等于 total,不该再报 hasMore。 page.hasMore = (page.offset + kept < page.total); } } // activityHistory 是同一份数据的纯文本形态:必须按窗口重建, // 否则整包原文会绕过分页,等于没分页。 std::string shown; for (const Json::Value& r : records) { shown += r.asString(); shown += '\n'; } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["records"] = records; structuredContent["activityHistory"] = shown; structuredContent["truncated"] = byteTrimmed; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; // 正文外的 JSON 块只放 records:activityHistory 是同一份数据的原文, // 整包外露等于同样内容出现三遍。 Json::Value textPayload(Json::objectValue); textPayload["records"] = records; SetStructuredTextPayload(result, textPayload); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"共 ") + std::to_string(page.total) + std::string(u8" 条历史活动记录(新在前),本次返回第 ") + std::to_string(page.offset) + std::string(u8" 条起的 ") + std::to_string(page.returned) + std::string(u8" 条") + (page.hasMore ? std::string(u8";hasMore=true 表示还有更早的记录,可用 offset=") + std::to_string(page.offset + page.returned) + std::string(u8" 继续取。") : std::string(u8"。")); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // 读可选整数参数(缺省/ null 时用 defVal);越界/类型错误返回 false 并填好错误响应 static bool GetOptIntInRange(const Json::Value& id, const Json::Value& args, const char* key, int lo, int hi, int defVal, int& out, std::string& errJson) { out = defVal; if (!args.isMember(key) || args[key].isNull()) return true; if (!args[key].isInt()) { errJson = BuildError(id, -32602, std::string("Invalid ") + key + ": expected an integer"); return false; } int n = args[key].asInt(); if (n < lo || n > hi) { errJson = BuildError(id, -32602, std::string("Invalid ") + key + ": out of range [" + std::to_string(lo) + "," + std::to_string(hi) + "]"); return false; } out = n; return true; } // 定义在文件后部(expect_hwnd 解析),这里先声明以便 get_screenshot 复用 static bool GetOptionalWindowArg(const Json::Value& args, const char* key, uint32_t& out, bool& present, std::string& err); static std::string Trim(const std::string& s); // tools/call:get_screenshot(屏幕预览链路,主连接 RPC,不建子链接、不弹框) std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 能力位门槛:只有能抓屏的客户端才声明 CLIENT_CAP_SCREEN_PREVIEW // (Windows 恒声明;Linux 仅在登录时探测到可用 X11 桌面才声明),否则返回明确错误 if (!ctx->SupportsScreenPreview()) return BuildError(id, -32005, "Host does not support screen preview"); // ---- 抓取范围 ---- std::string modeStr = Trim(GetStringArg(args, "mode")); if (modeStr.empty()) modeStr = "screen"; int mode = -1; if (modeStr == "screen") mode = SCREEN_CAPTURE_VDESKTOP; else if (modeStr == "region") mode = SCREEN_CAPTURE_REGION; else if (modeStr == "window") mode = SCREEN_CAPTURE_WINDOW; else if (modeStr == "monitor") mode = SCREEN_CAPTURE_MONITOR; else return BuildError(id, -32602, "Invalid mode: " + modeStr + " (expect screen|region|window|monitor)"); // 新客户端(CLIENT_CAP_SCREEN_REGION)支持 v2;老客户端只能整屏。 const bool supportsRegion = ctx->SupportsScreenCapture(); if (mode != SCREEN_CAPTURE_VDESKTOP && !supportsRegion) return BuildError(id, -32005, "mode=region/window/monitor requires a newer Windows client " "(screen region capability); use mode=screen instead"); std::string errJson; int rx = 0, ry = 0, rw = 0, rh = 0, monitorIdx = 0; uint32_t hwnd = 0; if (mode == SCREEN_CAPTURE_REGION) { if (!GetOptIntInRange(id, args, "x", -100000, 100000, 0, rx, errJson)) return errJson; if (!GetOptIntInRange(id, args, "y", -100000, 100000, 0, ry, errJson)) return errJson; if (!args.isMember("width") || args["width"].isNull()) return BuildError(id, -32602, "Missing required parameter: width (mode=region)"); if (!args.isMember("height") || args["height"].isNull()) return BuildError(id, -32602, "Missing required parameter: height (mode=region)"); if (!GetOptIntInRange(id, args, "width", 1, 8192, 0, rw, errJson)) return errJson; if (!GetOptIntInRange(id, args, "height", 1, 8192, 0, rh, errJson)) return errJson; } else if (mode == SCREEN_CAPTURE_WINDOW) { bool hasHwnd = false; std::string oerr; if (!GetOptionalWindowArg(args, "hwnd", hwnd, hasHwnd, oerr)) return BuildError(id, -32602, oerr); if (!hasHwnd) return BuildError(id, -32602, "Missing required parameter: hwnd (mode=window)"); } else if (mode == SCREEN_CAPTURE_MONITOR) { if (!GetOptIntInRange(id, args, "monitor", 0, 255, 0, monitorIdx, errJson)) return errJson; } // max_width:screen 模式下缺省/0 沿用 RTT 自适应缩略图档位;region/window/monitor // 缺省/0 表示原生分辨率(1:1),显式传入才等比缩放。 bool hasMaxWidth = false; int maxWidthArg = 0; if (args.isMember("max_width") && !args["max_width"].isNull()) { if (!args["max_width"].isInt()) return BuildError(id, -32602, "Invalid max_width: expected an integer"); maxWidthArg = args["max_width"].asInt(); // 与 inputSchema 描述一致:钳制到 [64,1920](老行为),不因越界直接报错 if (maxWidthArg > 0) { if (maxWidthArg < 64) maxWidthArg = 64; if (maxWidthArg > 1920) maxWidthArg = 1920; hasMaxWidth = true; } else { maxWidthArg = 0; } } CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_screenshot")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); uint16_t reqId = mcp.NextPreviewReqId(); mcp.SetPendingReqId(devId, reqId); // 复用 MFC 预览的 RTT/FRP 自适应参数挑选,避免重复实现 GetTargetQualityLevel 逻辑 WORD maxWidth = 0; BYTE quality = 0; parent->ChooseScreenPreviewParams(ctx, maxWidth, quality); if (hasMaxWidth) maxWidth = (WORD)maxWidthArg; if (mode == SCREEN_CAPTURE_VDESKTOP) { if (supportsRegion) { // 新客户端也走 v2:多回一份源矩形元数据,但目标仍是整屏 + 缩放。 ScreenPreviewReqEx ex = {}; ex.mode = SCREEN_CAPTURE_VDESKTOP; parent->SendScreenPreviewRequestEx(ctx, reqId, maxWidth, quality, ex); } else { parent->SendScreenPreviewRequest(ctx, reqId, maxWidth, quality); } } else { ScreenPreviewReqEx ex = {}; ex.mode = (uint8_t)mode; if (!hasMaxWidth) ex.flags |= SCREEN_CAPTURE_F_NATIVE; ex.x = rx; ex.y = ry; ex.w = rw; ex.h = rh; ex.hwnd = hwnd; ex.monitor = (uint16_t)monitorIdx; parent->SendScreenPreviewRequestEx(ctx, reqId, maxWidth, quality, ex); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for screenshot"); // data = [ScreenPreviewRspHeader][JPEG][可选 ScreenCaptureMeta] if (data.size() < sizeof(ScreenPreviewRspHeader)) return BuildError(id, -32000, "Invalid screenshot response"); const ScreenPreviewRspHeader* hdr = reinterpret_cast(data.data()); if (hdr->status == SCREEN_PREVIEW_BAD_TARGET) { if (mode == SCREEN_CAPTURE_WINDOW) return BuildError(id, -32009, "Window hwnd=" + std::to_string(hwnd) + " is not capturable (not found, minimized, off-screen, " "or larger than 8192 px per side)"); if (mode == SCREEN_CAPTURE_MONITOR) return BuildError(id, -32602, "Monitor index " + std::to_string(monitorIdx) + " is out of range"); if (mode == SCREEN_CAPTURE_REGION) return BuildError(id, -32602, "Capture region is empty after clipping to the virtual desktop"); return BuildError(id, -32000, "Screen is not capturable"); } if (hdr->status != SCREEN_PREVIEW_OK || hdr->format != SCREEN_PREVIEW_FMT_JPEG || hdr->bytes == 0 || data.size() < sizeof(ScreenPreviewRspHeader) + hdr->bytes) { // Android 的抓屏依赖无障碍服务(takeScreenshot),失败时给一句可操作的提示 // (kPlatApk 与 CurrentClientPlatform 定义在文件后部,这里直接看 RES_CLIENT_TYPE)。 // 客户端把所有失败(未开无障碍、系统限流、编码/分配失败、回调超时)都归为 // CAPTURE_FAILED,所以提示要列常见原因而不是断言某一条,细节引导去看客户端日志。 std::string hint; if (hdr->status == SCREEN_PREVIEW_CAPTURE_FAILED && ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK") hint = ": Android client could not capture — check the YAMA accessibility service " "(Android 11+), system screenshot rate limiting, and get_client_log for the " "capture/encode error"; return BuildError(id, -32000, "Screenshot capture failed (status " + std::to_string((int)hdr->status) + ")" + hint); } // 可选尾块:实际抓取的源矩形 + 缩放比例(老客户端不回)。 // 偏移 = 16 + bytes,可能不是 4 字节对齐,按字节拷贝到局部变量再读。 bool hasMeta = false; ScreenCaptureMeta meta = {}; if (data.size() >= sizeof(ScreenPreviewRspHeader) + hdr->bytes + sizeof(ScreenCaptureMeta)) { memcpy(&meta, data.data() + sizeof(ScreenPreviewRspHeader) + hdr->bytes, sizeof(meta)); hasMeta = (meta.magic == SCREEN_CAPTURE_META_MAGIC); } std::string b64 = httplib::detail::base64_encode( std::string((const char*)data.data() + sizeof(ScreenPreviewRspHeader), hdr->bytes)); Json::Value image(Json::objectValue); image["mimeType"] = "image/jpeg"; image["width"] = (Json::UInt64)hdr->width; image["height"] = (Json::UInt64)hdr->height; image["bytes"] = (Json::UInt64)hdr->bytes; Json::Value capture(Json::objectValue); capture["mode"] = modeStr; if (hasMeta) { capture["x"] = meta.x; capture["y"] = meta.y; capture["width"] = meta.w; capture["height"] = meta.h; capture["scale"] = (int)meta.scale; capture["native"] = meta.scale >= 100; } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["image"] = image; // 元数据(不含 base64,避免在 content 之外重复大 payload) structuredContent["capture"] = capture; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "image"; item["data"] = b64; item["mimeType"] = "image/jpeg"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_foreground_window(窗口信息 RPC,主连接,不建子链接、不弹框) std::string BuildGetForegroundWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); std::vector wins; std::string ferr; int rc = FetchWindowInfo(ctx, devId, "get_foreground_window", 0, wins, ferr); if (rc == 1) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); if (rc == 4) return BuildError(id, -32005, "Host does not support window info (old client)"); if (rc != 0) return BuildError(id, rc == 2 ? -32001 : -32000, "Failed to get window info: " + ferr); const WindowEntry* fg = nullptr; for (const WindowEntry& e : wins) { if (e.flags & WINDOWINFO_FOREGROUND) { fg = &e; break; } } Json::Value structuredContent(Json::objectValue); structuredContent["windowCount"] = (Json::UInt)wins.size(); structuredContent["window"] = fg ? WindowEntryToJson(*fg) : Json::Value(Json::nullValue); Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; if (fg) { item["text"] = std::string(u8"前台窗口:") + fg->title + " (hwnd=" + std::to_string(fg->hwnd) + ", pid=" + std::to_string(fg->pid) + ", rect=" + std::to_string(fg->left) + "," + std::to_string(fg->top) + "," + std::to_string(fg->right) + "," + std::to_string(fg->bottom) + ")"; } else { item["text"] = std::string(u8"未找到前台窗口(可能被 UAC/安全桌面遮挡,或客户端为老版本)"); } content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // 新客户端的结构化失败回报布局:[token:1][win32/status:4 LE]。读取其中 4 字节错误码。 static DWORD ReadWin32Payload(const std::vector& data) { DWORD v = 0; if (data.size() >= 1 + sizeof(DWORD)) memcpy(&v, data.data() + 1, sizeof(DWORD)); return v; } // 客户端结构化失败 → MCP 错误码: // 5 ERROR_ACCESS_DENIED → -32010(目标存在但权限不足;重试无意义) // 2/3 ERROR_FILE/PATH_NOT_FOUND → -32009(目标不存在) // 其余 → -32000(文案带出 win32 码) static std::string BuildRemoteWin32Error(const Json::Value& id, DWORD win32err, const std::string& subject, const std::string& hint = "") { std::string detail = " (win32=" + std::to_string((int)win32err) + ")"; if (!hint.empty()) detail += ". " + hint; if (win32err == ERROR_ACCESS_DENIED) return BuildError(id, -32010, subject + ": access denied" + detail); if (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND) return BuildError(id, -32009, subject + ": target not found" + detail); return BuildError(id, -32000, subject + ": client reported failure" + detail); } // tools/call:list_files(列盘走 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST; // 列目录走 COMMAND_LIST_DRIVE 开子链接后,再下发 COMMAND_LIST_FILES→TOKEN_FILE_LIST) static const int kListFilesMaxEntries = 100000; // 解析上限,仅为兜住病态目录 std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); std::string path = GetStringArg(args, "path"); // 编码:文件管理通道在线上是客户端 ANSI/GBK —— Windows 客户端走 A 接口 // (FindFirstFileA);Linux/macOS 客户端在 common/FileManager.h 里对收到的路径做 // gbkToUtf8、对发出的名字做 utf8ToGbk,与 download_file/upload_file 的 936 约定 // 一致。不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解线上的 GBK 字节。 // 名字解析对 POSIX 用 CP_UTF8 作「先按 GBK 严格解、解不开再当 UTF-8」的开关 // (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool posixFs = (clientType == "LNX" || clientType == "MAC"); const UINT nameCp = posixFs ? CP_UTF8 : 936; // Windows 上 "."、"/"、"\\" 是「列盘」的历史写法;POSIX 上 "/" 是真实目录 // (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。 const bool listDrives = path.empty() || (!posixFs && (path == "." || path == "/" || path == "\\")); std::string ansiPath; if (!listDrives) { if (posixFs) { // 客户端对收到的路径先做 gbkToUtf8:能转 GBK 就发 GBK;含 GBK 表示不了的 // 字符(韩文等)时客户端 iconv 会失败并原样使用输入,所以这里直接发 UTF-8, // 两边才能对上(ToAnsi 在这里会静默替换成 '?')。 if (!Utf8ToCpExact(path, 936, ansiPath)) ansiPath = path; } else { ansiPath = ToAnsi(path, 936); } } CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_files", ansiPath)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for file list"); // 新客户端在失败分支回 TOKEN_FILE_LIST_ERROR(路径不存在/非法/不可访问)→ 立即转译; // 老客户端没有这个包,仍按「空目录」处理(行为不变)。 if (!data.empty() && data[0] == TOKEN_FILE_LIST_ERROR) return BuildRemoteWin32Error(id, ReadWin32Payload(data), "Failed to list \"" + path + "\""); Json::Value drives(Json::arrayValue); Json::Value files(Json::arrayValue); bool truncated = false; if (listDrives) { drives = ParseDriveList(data, nameCp); } else { // 整目录解析后再分页:先按 500 条截断会让 total/hasMore 说谎(超过 500 条的 // 目录永远翻不到后面的条目)。上限 100000 条只为兜住病态目录。 files = ParseFileList(data, kListFilesMaxEntries, nameCp, &truncated); } PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(listDrives ? drives : files, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); if (listDrives) { structuredContent["drives"] = pageItems; } else { structuredContent["files"] = pageItems; structuredContent["truncated"] = truncated; // 一律带出,便于按 schema 校验 } WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = listDrives ? PageSummary(page, u8"个驱动器") : PageSummary(page, u8"个条目"); if (truncated) item["text"] = item["text"].asString() + std::string(u8"目录条目超过服务端解析上限 ") + std::to_string(kListFilesMaxEntries) + std::string(u8" 条,total 只是上限内的数量;请缩小目录范围") + (posixFs ? std::string(u8"。") : std::string(u8"或改用 search_file。")); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:list_services(主连接下发 COMMAND_SERVICES,子连接一次性回传 TOKEN_SERVERLIST) std::string BuildListServices(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 服务管理仅 Windows 客户端实现(EnumServicesStatus 等 A 接口);LNX/MAC 无 Windows // 服务概念,提前返回避免 20s 超时等待。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC") return BuildError(id, -32005, "list_services is only supported on Windows hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_services")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SERVICES; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for service list"); // TOKEN_SERVICE_ERROR:客户端 OpenSCManager 失败(典型=未提权,win32=5)。 if (!data.empty() && data[0] == TOKEN_SERVICE_ERROR) return BuildRemoteWin32Error(id, ReadWin32Payload(data), "Failed to enumerate services", "service enumeration requires the client to run elevated (administrator)"); // 服务名/路径/显示名来自 Windows A 接口 = 客户端 ANSI(GBK/936),按 clientType 判定。 UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value services = ParseServiceList(data, cp); PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(services, page, pageItems); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["services"] = pageItems; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = PageSummary(page, u8"个服务"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:list_registry(主连接下发 COMMAND_REGEDIT → 子连接 TOKEN_REGEDIT → 下发 // COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY 两包;path 空 = 列根键,无需查询客户端) std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 注册表仅 Windows 客户端实现(RegOpenKeyEx 等 A 接口);LNX/MAC/APK 没有注册表。 // APK 原来漏在门外:命令能下发,但客户端不会回 TOKEN_REGEDIT,只能白等到超时。 if (!IsWindowsClient(ctx)) return BuildError(id, -32005, "list_registry is only supported on Windows hosts"); // 注册表键路径与返回的键/值都是客户端 ANSI(RegisterManager 用 A 接口)= GBK/936。 const UINT cp = 936; std::string path = GetStringArg(args, "path"); BYTE rootToken = 0; std::string relPath; if (!ParseRegistryPath(path, rootToken, relPath)) { if (path.empty()) return BuildRegistryRoots(id); // 空 path → 列根键 return BuildError(id, -32602, "Invalid path: expected a root key like HKEY_LOCAL_MACHINE\\Software"); } // 客户端 RegisterOperation 以 char KeyPath[MAX_PATH] 承载相对子键路径(SetPath→strcpy 无界), // 超长会栈溢出。按 UTF-8 字节数做保守上限(GBK/936 字节数 ≤ UTF-8,故只查 UTF-8 即可)。 if (relPath.size() >= MAX_PATH) return BuildError(id, -32602, "Registry path too long (exceeds MAX_PATH)"); // rootToken 编码进 path[0] 供 OnRegeditReady 拆分。 std::string rootAndPath = std::string(1, (char)rootToken) + ToAnsi(relPath, cp); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_registry", rootAndPath)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_REGEDIT; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector subkeys, values; if (!mcp.WaitPendingRegistry(devId, subkeys, values, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for registry data"); // TOKEN_REG_ERROR:RegOpenKeyEx 失败(键/路径不存在或拒绝访问),此时只有这一包, // 不做 ParseRegPath/ParseRegKey(它们会把错误包误当记录数据)。 if (!subkeys.empty() && subkeys[0] == TOKEN_REG_ERROR) return BuildRemoteWin32Error(id, ReadWin32Payload(subkeys), "Failed to open \"" + path + "\""); Json::Value keysArr = ParseRegPath(subkeys, cp); Json::Value valsArr = ParseRegKey(values, cp); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["path"] = path; structuredContent["keys"] = keysArr; structuredContent["values"] = valsArr; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"共 ") + std::to_string((int)keysArr.size()) + std::string(u8" 个子键、") + std::to_string((int)valsArr.size()) + std::string(u8" 个值。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ========== P3:exec_command ========== // exec_command 默认白名单:只读命令前缀(逗号分隔,前缀匹配,大小写不敏感)。 // 只放查询/只读类命令;写命令(del/copy/move/reg add/sc stop/...)一律不在列。 // sc 只放查询类子命令(qc/enumdepend/sdshow);sc start/stop/config/create/delete 都是写。 static const char* kDefaultCmdWhitelist = "dir,type,cd,chdir,ver,hostname,whoami,where,tasklist,systeminfo,ipconfig,netstat," "path,set,find,findstr,reg query,sc query,sc qc,sc enumdepend,sc sdshow," "ping,tracert,nslookup,getmac,driverquery,query,gpresult," "arp -a,route print,schtasks /query"; // Linux 默认白名单:同一条命令名的 POSIX 语义与 Windows 不同(find/sort/date/hostname // 都能写文件或改系统状态),故单独维护,只放参数也基本只读的命令。注意 env 不在列: // `env rm -rf /` 会执行任意程序,等于白名单失效。管理员配置了 McpCmdWhitelist 时以 // 配置为准(两种平台共用同一份显式配置)。 static const char* kDefaultCmdWhitelistPosix = "ls,cat,head,tail,grep,egrep,fgrep,wc,file,stat,pwd,id,whoami,uname,uptime," "df,du,free,ps,ss,netstat,lsblk,lsusb,lspci," "ip addr show,ip route show,ip link show,ip -s," "systemctl status,systemctl list-units,journalctl,dmesg," "last,lastb,w,who,printenv,getent,which,whereis"; // POSIX shell 元字符:& | < > 与 ; 都能在同一条命令行里追加命令,反引号与 $( / ${ 能 // 执行子命令,! 在交互式 bash 里会触发历史展开。全部拒绝,防止绕过白名单前缀。 static bool ContainsForbiddenPosixShellChars(const std::string& s) { for (size_t i = 0; i < s.size(); ++i) { char c = s[i]; if (c == '&' || c == '|' || c == '<' || c == '>' || c == ';' || c == '`' || c == '!') return true; if (c == '$' && i + 1 < s.size() && (s[i + 1] == '(' || s[i + 1] == '{')) return true; } return false; } // 去首尾空白(空格/制表符/回车/换行)。 static std::string Trim(const std::string& s) { size_t b = s.find_first_not_of(" \t\r\n"); if (b == std::string::npos) return ""; return s.substr(b, s.find_last_not_of(" \t\r\n") - b + 1); } // 去尾部空白(含尾部 CR/LF)。 static std::string TrimRight(const std::string& s) { size_t e = s.find_last_not_of(" \t\r\n"); return (e == std::string::npos) ? "" : s.substr(0, e + 1); } // 命令白名单校验:命令(trim + ASCII 小写)以某白名单项为前缀,且其后字符为空/空格/制表符, // 防止 "dirx" 前缀误配 "dir"。多词前缀(sc query / reg query)也按完整前缀匹配。 static bool IsCommandAllowed(const std::string& command, const std::string& whitelist) { std::string c = ToLowerAscii(Trim(command)); if (c.empty()) return false; size_t start = 0; while (start < whitelist.size()) { size_t comma = whitelist.find(',', start); std::string item = Trim(whitelist.substr( start, comma == std::string::npos ? std::string::npos : comma - start)); if (!item.empty()) { std::string p = ToLowerAscii(item); if (c.size() >= p.size() && c.compare(0, p.size(), p) == 0 && (c.size() == p.size() || c[p.size()] == ' ' || c[p.size()] == '\t')) { return true; } } if (comma == std::string::npos) break; start = comma + 1; } return false; } // 剥 ANSI 转义序列(CSI/OSC/单字节 ESC),避免终端彩色码污染返回文本。 static std::string StripAnsi(const std::string& s) { std::string out; out.reserve(s.size()); for (size_t i = 0; i < s.size(); ++i) { if (s[i] != '\x1b') { out += s[i]; continue; } ++i; // 吞 ESC if (i < s.size() && s[i] == '[') { // CSI ... 结尾 @–~ while (++i < s.size() && !(s[i] >= '@' && s[i] <= '~')) {} } else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ST(ESC \) while (++i < s.size() && s[i] != '\x07' && s[i] != '\x1b') {} // ST 是两字节 "ESC \":这里停在 ESC 上,须把 '\' 一起吞掉,否则会残留在输出里。 if (i + 1 < s.size() && s[i] == '\x1b' && s[i + 1] == '\\') ++i; } // 其它单字节 ESC 序列吞掉当前字节即可(循环 ++i 会跳过它) } return out; } // 去掉 ConPTY 把整行输入回显造成的噪声:line 是发送过的命令行(含唯一 nonce 或 "@echo off & " // 前缀),输出里若出现这段文本(连同其后的换行)则剔除。回显会被 80 列折行插入换行, // 所以比较时跳过 '\r'/'\n';随机 nonce/固定前缀保证命令真实输出不可能整行命中。 // 只删第一处命中(输入回显只发生一次)。 static void StripEchoedLine(std::string& s, const std::string& line) { if (line.empty() || s.empty()) return; const size_t n = s.size(), m = line.size(); for (size_t i = 0; i < n; ++i) { size_t j = 0, k = i; while (j < m && k < n) { const char c = s[k]; if (c == '\r' || c == '\n') { ++k; continue; } if (c != line[j]) break; ++j; ++k; } if (j != m) continue; while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k; // 连同回显行尾换行一起删 s.erase(i, k - i); return; } } // 把缓冲区开头一直删到回显行结束(含行尾换行)。ConPTY 起 shell 时会先回放启动画面与 // 提示符(一长串空行 + "Microsoft Windows [Version ...]" + "C:\path>"),紧接着才是我们这行 // 输入的回显;回显行即「真实输出的起点」,因此删到它结束可把启动噪声一并去掉。 // 返回 false 表示没找到回显(例如客户端不回显),此时不动缓冲区。 static bool CutThroughEchoedLine(std::string& s, const std::string& line) { if (line.empty() || s.empty()) return false; const size_t n = s.size(), m = line.size(); for (size_t i = 0; i < n; ++i) { size_t j = 0, k = i; while (j < m && k < n) { const char c = s[k]; if (c == '\r' || c == '\n') { ++k; continue; } if (c != line[j]) break; ++j; ++k; } if (j != m) continue; while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k; s.erase(0, k); return true; } return false; } // 去掉开头的空行(启动画面残留 / 上一行命令尾部的空行)。 static void TrimLeadingNewlines(std::string& s) { size_t i = 0; while (i < s.size() && (s[i] == '\r' || s[i] == '\n')) ++i; if (i) s.erase(0, i); } // 擦掉输出里**残留**的哨兵文本。ConPTY 送回来的是「屏幕渲染流」而不是字节流:光标重绘 // 会把同一行再输出一次,剥掉 VT 序列后同一段文字就重复出现。于是哨兵可能留有副本 // (实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 "abc__MCP_DONE_x__0")。 // nonce 每条命令随机生成,命令的真实输出不可能包含它,故按 nonce 文本擦除既彻底又安全。 // 比较时跳过 '\r'/'\n'(折行回显);`%errorlevel%` 是回显模板本身,一并擦到行尾。 static void StripSentinelText(std::string& s, const std::string& nonce) { if (nonce.empty() || s.empty()) return; const std::string marker = "__MCP_DONE_" + nonce + "__"; size_t i = 0; while (i < s.size()) { size_t j = 0, k = i; while (j < marker.size() && k < s.size()) { const char c = s[k]; if (c == '\r' || c == '\n') { ++k; continue; } if (c != marker[j]) break; ++j; ++k; } if (j != marker.size()) { ++i; continue; } size_t end = k; if (end < s.size() && s[end] == '-') ++end; while (end < s.size() && s[end] >= '0' && s[end] <= '9') ++end; if (end < s.size() && s[end] == '%') // 回显模板 ...__%errorlevel% while (end < s.size() && s[end] != '\r' && s[end] != '\n') ++end; size_t begin = i; // 连带前面残留的 "echo " if (begin >= 5 && _strnicmp(s.c_str() + begin - 5, "echo ", 5) == 0) begin -= 5; s.erase(begin, end - begin); i = begin; } } // 输入回显清洗(P4):PTY 下删「命令行」与「哨兵行」两处回显。非 PTY 只删哨兵行—— // 老 ShellManager 在客户端按写入长度自行跳过回显,删命令行反而可能吃掉命令自身的输出 // (如 `echo echo hello`)。 static std::string StripEchoedInput(const std::string& s, bool isPty, const std::string& cmdLine, const std::string& sentLine, const std::string& nonce) { std::string out = s; bool cut = isPty && CutThroughEchoedLine(out, cmdLine); if (isPty && !cut) StripEchoedLine(out, cmdLine); // 没回显时退回按整行删 StripEchoedLine(out, sentLine); StripSentinelText(out, nonce); TrimLeadingNewlines(out); return out; } // 哨兵行有三种形态(见 docs/Mcp_Design.md §12.1): // - POSIX PTY(posix=true,Linux):命令与哨兵**分两行**下发,哨兵用 echo 内置命令 + // $? 取上一行的真实退出码。不能用 Windows 的 "@echo off & ..." / %errorlevel%: // POSIX shell 会把它们当成字面量,FindSentinel 永远匹配不到。 // - ConPTY(is_pty=true):命令与哨兵**分两行**下发。哨兵独立成行执行,于是 rem / cmd / c // exit / if / for 这类「吞行」命令不会连哨兵一起吞掉(P1);哨兵用 %errorlevel% 取真实 // 退出码,回显文本里是字面 "%errorlevel%"、不是数字,FindSentinel 只认数字,折行回显再也 // 不会被误判成哨兵(P3),也能返回真实退出码而非 0/1。 // - 老 ShellManager(is_pty=false):客户端按写入字节数跳过回显,多写一行会吃掉上一行的 // 输出,故仍用单行 && / || 形式(老客户端维持既有行为,已知不支持 rem / cmd /c)。 static void BuildSentinelLines(bool isPty, bool posix, const std::string& command, const std::string& nonce, std::string& cmdLine, std::string& sentLine) { if (posix) { cmdLine = command; sentLine = "echo __MCP_DONE_" + nonce + "__$?"; return; } if (!isPty) { cmdLine = command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1"; sentLine.clear(); return; } cmdLine = "@echo off & " + command; sentLine = "echo __MCP_DONE_" + nonce + "__%errorlevel%"; } // 组包下发;cmdLine/sentLine 回传给调用方用于剔除输入回显。sentLine 为空表示单行形态。 static void SendSentinelLines(context* subCtx, bool isPty, bool posix, const std::string& command, const std::string& nonce, std::string& cmdLine, std::string& sentLine) { BuildSentinelLines(isPty, posix, command, nonce, cmdLine, sentLine); UINT cp = (posix || isPty) ? CP_UTF8 : 936; // Linux 的交互式 bash 每读一行都打印 PS1,提示符会混进 stdout(Windows ConPTY 不会), // 故先清空 PS1 再执行。这一行的回显在命令行回显之前,会被 CutThroughEchoedLine 连同 // 启动画面一起切掉,不进入返回文本。 std::string wire; if (posix) wire = "PS1=\r\n"; wire += ToAnsi(cmdLine, cp) + "\r\n"; if (!sentLine.empty()) wire += ToAnsi(sentLine, cp) + "\r\n"; subCtx->Send2Client((BYTE*)wire.data(), (ULONG)wire.size()); } // 命令是否含控制字符(<0x20,含 \r\n)。\r\n 会把命令拆成多行:一次性 exec 里会绕过 // 白名单执行任意后续行(安全);持久终端里只有末行被哨兵包装、退出码失真(正确性)。二者都拒绝。 static bool ContainsControlChar(const std::string& s) { for (char ch : s) if ((unsigned char)ch < 0x20) return true; return false; } // POSIX 命令里是否有「后台执行」用的 &:哨兵在下一行立即执行,后台命令的输出与退出码 // 都不可信。&&(串联)、&> / &>>(重定向)以及 2>&1 里的 & 都放行;引号与反斜杠转义内 // 的 & 不算。仅 PTY 会话会用到(老非 PTY 仍整体拒绝 & 与 |)。 static bool HasPosixBackgroundAmpersand(const std::string& s) { bool inSingle = false, inDouble = false, esc = false; for (size_t i = 0; i < s.size(); ++i) { const char c = s[i]; if (esc) { esc = false; continue; } if (c == '\\' && !inSingle) { esc = true; continue; } if (inSingle) { if (c == '\'') inSingle = false; continue; } if (inDouble) { if (c == '"') inDouble = false; continue; } if (c == '\'') { inSingle = true; continue; } if (c == '"') { inDouble = true; continue; } if (c != '&') continue; if (i + 1 < s.size() && (s[i + 1] == '&' || s[i + 1] == '>')) { ++i; continue; } if (i > 0 && s[i - 1] == '>') continue; // 2>&1 / >&2 return true; } return false; } static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒) // 终端会话的简短标签(-32003 与 mcp_list_sessions 共用同一写法,避免两处漂移)。 static std::string TerminalLabel(const std::string& sessionId) { return sessionId.empty() ? std::string("exec_command") : std::string("terminal session_id=") + sessionId; } // exec_command 被终端挡住时的完整报错:带会话名/session_id 与闲置/已跑时长,并给出正确出路。 // 不复用 BusyMessage:那边的描述顺序会优先报 pending/文件传输,可能把别的占用者算到终端头上。 static std::string TerminalBusyMessage(uint64_t devId) { for (const auto& s : CMcpServer::Instance().ListSessions()) { if (s.kind != "terminal" || s.device != devId) continue; std::string detail = " (" + TerminalLabel(s.sessionId); if (s.idleMs >= 0) detail += ", idle=" + std::to_string(s.idleMs / 1000) + "s"; if (s.elapsedMs >= 0) detail += ", elapsed=" + std::to_string(s.elapsedMs / 1000) + "s"; detail += ")"; if (s.tool == "exec_command") { return "Device busy: another exec_command is still running for this host" + detail + "; wait for it to finish, or cancel that call with mcp_cancel_session(request_id)"; } return "Device busy: a persistent terminal session is already open for this host" + detail + "; reuse it with terminal_exec, or close it with terminal_close(id, session_id); " "idle sessions are reclaimed after 300s"; } return "Device busy: a terminal session is already active for this host"; } // tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 → // 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。 std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 客户端也有完整 PTY // (common/PTYHandler.h,zsh/bash 交互),是否可用改由 CLIENT_CAP_TERMINAL 判定: // 老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented,发下去只会拖到超时。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool posix = (clientType == "LNX" || clientType == "APK" || clientType == "MAC"); if (clientType == "MAC" && !ctx->SupportsTerminal()) return BuildError(id, -32005, "macOS client is too old for exec_command: " "it does not declare CLIENT_CAP_TERMINAL; upgrade the client first"); // 老 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()) return BuildError(id, -32602, "Missing required parameter: command"); CMcpServer& mcp = CMcpServer::Instance(); // 安全门 1:只读模式直接拒绝(默认只读,exec_command 需显式关只读才可用)。 if (mcp.IsReadonly()) return BuildError(id, -32006, "exec_command is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); // 安全门 2:拒绝 shell 元字符与控制字符(\r\n 会把命令拆成多行绕过白名单),防注入。 // POSIX 下还要挡 ; 反引号 $( ${ !;^ 在 POSIX 里不是元字符,不能沿用 Windows 的字符集 // (否则 grep -v '^#' 这类只读命令会被误拒)。 const bool badMeta = posix ? ContainsForbiddenPosixShellChars(command) : (command.find_first_of("&|<>^") != std::string::npos); if (badMeta || ContainsControlChar(command)) return BuildError(id, kErrValidation, "Command contains forbidden shell characters: " + command); // 安全门 3:命令白名单前缀校验(显式配置优先;否则按平台用内置默认表)。 std::string whitelist = mcp.GetCmdWhitelist(); if (whitelist.empty()) whitelist = posix ? kDefaultCmdWhitelistPosix : kDefaultCmdWhitelist; if (!IsCommandAllowed(command, whitelist)) return BuildError(id, -32007, "Command not allowed by whitelist: " + command); int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; std::string nonce = GenerateRandomToken().substr(0, 8); // 持久终端闲置回收原先只在 terminal_open/exec/close/http_probe 入口触发;exec_command // 不走这些入口,于是「开过一次 terminal_exec → 之后 exec_command 永远 -32003」。 // 这里补一次 sweep,并让报错带上 session_id 与替代路径。 mcp.SweepIdleTerminals(kTermIdleTimeoutSec); if (!mcp.BeginTermPending(devId, command, nonce)) return BuildError(id, -32003, TerminalBusyMessage(devId)); // 主连接下发 COMMAND_SHELL,客户端建立 shell 子连接并回 TOKEN_*_START。 BYTE cmd = COMMAND_SHELL; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearTermPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } context* subCtx = nullptr; bool isPty = false; if (!mcp.WaitTerminalReady(devId, subCtx, isPty, timeoutMs)) return BuildError(id, -32001, "Timeout waiting for shell to start"); // 编码: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; // 等待提示符期间 shell 可能已退出:OnTerminalClosed 会把子连接指针置空、OfflineProc 随后把它 // 归还连接池(可能被新连接复用)。确认仍是本会话的子连接才写,否则直接交给 WaitTerminalDone // 收尾(会话已 closed,立刻返回已收集的输出),避免往别人的连接里灌命令。 if (mcp.IsTermSubCtxLive(devId, std::string(), subCtx)) SendSentinelLines(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); std::vector raw; int exitCode = -1; bool closed = false; if (!mcp.WaitTerminalDone(devId, raw, exitCode, closed, timeoutMs)) { if (!closed) subCtx->CancelIO(); return BuildError(id, -32001, "Timeout waiting for command output"); } if (!closed) subCtx->CancelIO(); // 关子链接,结束 shell 进程;shell 已退出时指针可能已回收 // 清洗:raw → UTF-8 → 剥 ANSI → CRLF 归一 → 去 ConPTY 回显命令行 → TrimRight。 // raw 已截断到哨兵前。 std::string stdoutStr; if (!raw.empty()) { std::string rawStr((const char*)raw.data(), raw.size()); stdoutStr = StripAnsi(ToUtf8(rawStr.c_str(), cp)); size_t p = 0; while ((p = stdoutStr.find("\r\n", p)) != std::string::npos) stdoutStr.erase(p, 1); stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce); stdoutStr = TrimRight(stdoutStr); } // 审计:命令执行落服务端消息/审计日志(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " exec: " + command; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP命令执行"))); // 标题走语言映射(GBK,随语言切换) } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["stdout"] = stdoutStr; structuredContent["exit_code"] = exitCode; result["structuredContent"] = structuredContent; // stdout 已在正文里,正文外的 JSON 块只补退出码(只读 content 的客户端也能看到)。 Json::Value textPayload(Json::objectValue); textPayload["exit_code"] = exitCode; SetStructuredTextPayload(result, textPayload); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = stdoutStr.empty() ? std::string(u8"(无输出)") : stdoutStr; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_client_log(主连接下发 COMMAND_QUERY_LOG,子连接回传 TOKEN_REPORT_LOG) std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_client_log")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_QUERY_LOG; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, u8"Timeout waiting for client log. 客户端在超时内没有回传日志:常见原因是该客户端" u8"版本尚未实现日志上报(Linux/MAC 需 2026-10-30 之后的客户端),也可能是子连接" u8"建立失败。可先用 get_host_detail 看 capabilities,或改用 download_file 直接取" u8"客户端日志文件。"); // data[0]=token,其后为 Logger 内存 ring buffer 的日志文本(无 '\0' 终止)。 // 客户端在子连接建立时 m_sentIdx=0 返回全量,随后每 3s 推增量;MessageHandle 在 // 取走首条全量后立即 CancelIO 关子链接,增量不再到达,故此处即为完整快照。 // 日志文本为客户端 ANSI(Windows 走 vsnprintf A 版),按 clientType 判定编码: // POSIX 客户端(LNX/MAC/APK)一律 UTF-8,Windows 是 GBK。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); UINT cp = (clientType == "LNX" || clientType == "MAC" || clientType == "APK") ? CP_UTF8 : 936; std::string log; if (data.size() > 1) { std::string raw((const char*)data.data() + 1, data.size() - 1); log = ToUtf8(raw.c_str(), cp); } // 行级裁剪:客户端快照是全量(最多 1000 行、实测 90 KB),直接整段塞进结果会超出 // 客户端的工具结果上限。默认只回末尾 200 行——排障关心的是最后发生了什么。 int limit = 200; if (args.isMember("limit") && args["limit"].isInt()) limit = args["limit"].asInt(); if (limit <= 0) limit = 200; if (limit > 2000) limit = 2000; const std::string filter = GetStringArg(args, "filter"); std::vector lines; { size_t b = 0; while (b < log.size()) { size_t e = log.find('\n', b); std::string one = (e == std::string::npos) ? log.substr(b) : log.substr(b, e - b); if (!one.empty() && one.back() == '\r') one.pop_back(); lines.push_back(one); if (e == std::string::npos) break; b = e + 1; } } const int linesTotal = (int)lines.size(); std::vector matched; matched.reserve(lines.size()); for (const auto& one : lines) { if (filter.empty() || ContainsCI(one, filter)) matched.push_back(one); } const int linesMatched = (int)matched.size(); // 从末尾往前取:同时受 limit 行数与 64 KB 字节预算约束(单行可能是超长的堆栈或 // 报文转储,只按行数截断仍可能撑爆结果)。两个约束哪个先到就用哪个。 const size_t kMaxBytes = 64 * 1024; std::string shown; int linesReturned = 0; bool contentTruncated = false; { size_t budget = kMaxBytes; size_t firstKept = (size_t)linesMatched; // 保留 [firstKept, linesMatched) while (firstKept > 0 && (int)((size_t)linesMatched - firstKept) < limit) { const size_t need = matched[firstKept - 1].size() + 1; if (need > budget) break; budget -= need; --firstKept; } if (firstKept == (size_t)linesMatched && linesMatched > 0) { // 末尾一行自己就超过预算:至少回它的尾部(排障看的是最后发生了什么), // 而不是回空串让人以为客户端没有日志。 const std::string& last = matched.back(); if (last.size() > kMaxBytes) { shown = last.substr(last.size() - kMaxBytes); contentTruncated = true; } else { shown = last; } shown += '\n'; linesReturned = 1; } else { for (size_t i = firstKept; i < (size_t)linesMatched; ++i) { shown += matched[i]; shown += '\n'; } linesReturned = linesMatched - (int)firstKept; } } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["log"] = shown; structuredContent["lines_total"] = linesTotal; structuredContent["lines_matched"] = linesMatched; structuredContent["lines_returned"] = linesReturned; structuredContent["truncated"] = (linesMatched > linesReturned) || contentTruncated; result["structuredContent"] = structuredContent; std::string text; if (linesTotal == 0) { text = u8"客户端暂无内存日志。"; } else { text = std::string(u8"客户端运行日志:共 ") + std::to_string(linesTotal) + std::string(u8" 行"); if (!filter.empty()) text += std::string(u8",匹配 \"") + filter + std::string(u8"\" 的 ") + std::to_string(linesMatched) + std::string(u8" 行"); text += std::string(u8",返回末尾 ") + std::to_string(linesReturned) + std::string(u8" 行"); if (linesMatched > linesReturned || contentTruncated) text += std::string(u8"(还有更多,可调大 limit 或加 filter)"); text += std::string(u8"。"); } Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_audit_log(服务端本地消息日志,读取 UI 日志列表的线程安全镜像) std::string BuildGetAuditLog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { std::string fType = GetStringArg(args, "type"); std::string fKeyword = GetStringArg(args, "keyword"); Json::Value all(Json::arrayValue); int rawCount = 0; if (parent) { EnterCriticalSection(&parent->m_cs); // m_MessageLog 新在前、旧在后(与界面一致),直接顺序输出。 // 镜像本身有 1000 条环形上限(MAX_MESSAGE_COUNT),过滤与分页都在内存里做,代价可忽略。 for (const auto& e : parent->m_MessageLog) { std::string ty = ToUtf8(e.type.c_str(), 936); std::string tm = ToUtf8(e.time.c_str(), 936); std::string ms = ToUtf8(e.msg.c_str(), 936); rawCount++; if (!fType.empty() && !ContainsCI(ty, fType)) continue; if (!fKeyword.empty() && !ContainsCI(ms, fKeyword)) continue; Json::Value item(Json::objectValue); item["type"] = ty; item["time"] = tm; item["msg"] = ms; all.append(item); } LeaveCriticalSection(&parent->m_cs); } PageWindow page = ResolvePageWindow(args); Json::Value entries; ApplyPageWindow(all, page, entries); page.totalAll = rawCount; // 过滤前的总条数:total 是命中数,totalAll 是镜像里全部条数 Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["entries"] = entries; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; std::string text = PageSummary(page, u8"条日志"); if (!fType.empty() || !fKeyword.empty()) text += std::string(u8"过滤前共 ") + std::to_string(rawCount) + std::string(u8" 条。"); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:get_server_status(服务端自身状态:版本/构建时间/运行时长/开关/监听地址/计数) std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent) { CMcpServer& srv = CMcpServer::Instance(); Json::Value status(Json::objectValue); status["app_name"] = BRAND_APP_NAME; status["version"] = VERSION_STR; // exe 的最后写入时间就是链接时间,比 __DATE__/__TIME__ 可靠(后者是编译本 .cpp 的时间)。 { char exe[MAX_PATH] = { 0 }; if (GetModuleFileNameA(NULL, exe, MAX_PATH) > 0) { WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExA(exe, GetFileExInfoStandard, &fad)) { FILETIME local = fad.ftLastWriteTime; FileTimeToLocalFileTime(&fad.ftLastWriteTime, &local); SYSTEMTIME st = { 0 }; if (FileTimeToSystemTime(&local, &st)) { char buf[32] = { 0 }; wsprintfA(buf, "%04d-%02d-%02d %02d:%02d:%02d", (int)st.wYear, (int)st.wMonth, (int)st.wDay, (int)st.wHour, (int)st.wMinute, (int)st.wSecond); status["exe_build_time"] = buf; } } } } // 进程运行时长:从进程创建时间算起(不是系统开机时间,也不受 MCP 启停影响)。 { FILETIME createTime, exitTime, kernelTime, userTime, nowFt; if (GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime)) { GetSystemTimeAsFileTime(&nowFt); ULARGE_INTEGER c, n; c.LowPart = createTime.dwLowDateTime; c.HighPart = createTime.dwHighDateTime; n.LowPart = nowFt.dwLowDateTime; n.HighPart = nowFt.dwHighDateTime; LONGLONG ticks100ns = (LONGLONG)(n.QuadPart - c.QuadPart); if (ticks100ns > 0) status["uptime_sec"] = (Json::Int64)(ticks100ns / 10000000LL); } } status["bind"] = srv.GetBind(); status["port"] = srv.GetPort(); // 开关只报「开/关」,不输出 token、白名单内容等敏感配置。 Json::Value switches(Json::objectValue); switches["readonly"] = srv.IsReadonly(); switches["terminal"] = srv.IsTerminalEnabled(); switches["remote_control"] = srv.IsRemoteControlEnabled(); switches["file_transfer"] = srv.IsFileTransferEnabled(); switches["file_write"] = srv.IsFileWriteEnabled(); switches["manage"] = srv.IsManageEnabled(); switches["machine"] = srv.IsMachineEnabled(); switches["machine_dangerous"] = srv.IsMachineDangerousEnabled(); switches["keylog"] = srv.IsKeylogEnabled(); switches["chat"] = srv.IsChatEnabled(); switches["build"] = srv.IsBuildEnabled(); status["switches"] = switches; int onlineCount = 0, offlineCount = 0; if (parent) { Json::Value all(Json::arrayValue); CollectAllHosts(parent, all, true, true); for (Json::Value::ArrayIndex i = 0; i < all.size(); ++i) { if (all[i]["online"].asBool()) onlineCount++; else offlineCount++; } } Json::Value hosts(Json::objectValue); hosts["online"] = onlineCount; hosts["offline"] = offlineCount; status["hosts"] = hosts; int pending = 0, terminal = 0, screenCtrl = 0, fileXfer = 0, chat = 0, blockedIps = 0; srv.GetRuntimeCounters(pending, terminal, screenCtrl, fileXfer, chat, blockedIps); Json::Value sessions(Json::objectValue); sessions["pending"] = pending; // 一次性/管理/键盘记录挂起会话 sessions["terminal"] = terminal; sessions["remote_control"] = screenCtrl; sessions["file_transfer"] = fileXfer; sessions["chat"] = chat; status["sessions"] = sessions; status["blocked_auth_ips"] = blockedIps; Json::Value result(Json::objectValue); // outputSchema 声明的就是顶层字段;不要再套一层 "status",否则按 schema 取字段 // (structuredContent.version 等)的客户端拿不到任何东西。 result["structuredContent"] = status; std::string text = std::string(BRAND_APP_NAME) + " v" + VERSION_STR + std::string(u8",已运行 ") + std::to_string((long long)status["uptime_sec"].asInt64()) + std::string(u8" 秒,监听 ") + srv.GetBind() + ":" + std::to_string(srv.GetPort()) + std::string(u8";在线主机 ") + std::to_string(onlineCount) + std::string(u8" 台、离线 ") + std::to_string(offlineCount) + std::string(u8" 台。"); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P11:mcp_list_sessions / mcp_cancel_session ===== // // 这两个工具只看/只改服务端自己的会话表,不向任何主机发报文,因此不受功能开关与 // 只读模式限制——它们回答的是「谁占着这台主机、怎么把占用放开」,包括只读模式下 // 卡住的长请求。取消是异步的:工具线程在 ≤500ms 的等待切片内退出并走既有清理路径, // 这里再轮询同等条件最多 2s,好让返回的 released 反映「主机是否真的松开了」。 namespace { const int kCancelWaitMs = 2000; // mcp_cancel_session 等「主机松开」的上限 } static std::string BuildMcpListSessions(const Json::Value& id, const Json::Value& args) { const std::string kindFilter = ToLowerAscii(GetStringArg(args, "kind")); static const char* kKinds[] = { "call", "pending", "terminal", "remote_control", "file_transfer", "chat" }; if (!kindFilter.empty()) { bool known = false; for (const char* k : kKinds) if (kindFilter == k) { known = true; break; } if (!known) return BuildError(id, -32602, "kind must be one of call/pending/terminal/remote_control/" "file_transfer/chat"); } const auto all = CMcpServer::Instance().ListSessions(); Json::Value arr(Json::arrayValue); std::string text; int shown = 0; for (const auto& s : all) { if (!kindFilter.empty() && s.kind != kindFilter) continue; Json::Value o(Json::objectValue); if (s.device != 0) o["host_id"] = std::to_string(s.device); o["kind"] = s.kind; o["tool"] = s.tool; if (!s.sessionId.empty()) o["session_id"] = s.sessionId; if (!s.requestId.empty()) o["request_id"] = s.requestId; o["busy"] = s.busy; if (s.elapsedMs >= 0) o["elapsed_ms"] = (Json::Int64)s.elapsedMs; if (s.idleMs >= 0) o["idle_ms"] = (Json::Int64)s.idleMs; arr.append(o); if (shown < 20) { // 正文只列前 20 条,完整内容在 structuredContent if (!text.empty()) text += u8";"; if (s.device != 0) text += std::string(u8"主机 ") + std::to_string(s.device) + u8" "; text += s.kind + "/" + s.tool; if (s.elapsedMs >= 0) text += std::string(u8"(已 ") + std::to_string(s.elapsedMs / 1000) + u8"s)"; ++shown; } } Json::Value sc(Json::objectValue); sc["sessions"] = arr; sc["count"] = (int)arr.size(); if (arr.empty()) { text = u8"当前没有在飞请求或长连接会话,主机都空闲。"; } else { text = std::string(u8"共 ") + std::to_string((int)arr.size()) + u8" 个会话:" + text; if ((int)arr.size() > shown) text += std::string(u8"…(正文只列前 ") + std::to_string(shown) + u8" 个)"; } Json::Value result(Json::objectValue); result["structuredContent"] = sc; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Value& args) { // request_id:按 JSON-RPC id 精确取消一次 tools/call(与 notifications/cancelled 等价)。 // 同时接受紧凑写法与 mcp_list_sessions 里给出的文本写法(见 CancelCallById)。 std::string reqIdKey; std::string reqIdText; if (args.isObject() && args.isMember("request_id")) { const Json::Value& v = args["request_id"]; if (!(v.isString() || v.isInt() || v.isUInt() || v.isInt64() || v.isUInt64())) return BuildError(id, -32602, "request_id must be a string or integer: the JSON-RPC id of a tools/call"); reqIdKey = JsonToString(v); reqIdText = McpRequestIdText(v); } uint64_t devId = 0; const bool hasDev = args.isObject() && args.isMember("id"); if (hasDev && !ReadUInt64Arg(args, "id", devId)) return BuildError(id, -32602, "id must be a decimal host id string"); // "0" 能通过整数校验,但会让设备过滤失效(matches 里 devId!=0 才比), // 变成「取消全服所有在飞调用」——宁可拒绝。 if (hasDev && devId == 0) return BuildError(id, -32602, "id must be a non-zero host id string"); const std::string sessionId = GetStringArg(args, "session_id"); if (reqIdKey.empty() && !hasDev && sessionId.empty()) return BuildError(id, -32602, "Provide at least one of request_id (a tools/call id), id (host id), " "or session_id"); // 条件匹配函数:request_id 优先,其余条件按「都给就必须都满足」。 auto matches = [&](const CMcpServer::SessionSnapshot& s) { if (!reqIdKey.empty()) return s.idKey == reqIdKey || s.requestId == reqIdText; if (hasDev && devId != 0 && s.device != devId) return false; if (!sessionId.empty() && s.sessionId != sessionId) return false; return true; }; CMcpServer& srv = CMcpServer::Instance(); const auto self = CurrentMcpCall(); // 取消工具自身也在这张表里,不算「匹配到」也不取消 Json::Value matched(Json::arrayValue); for (const auto& s : srv.ListSessions()) { if (self && s.kind == "call" && s.idKey == self->idKey) continue; if (!matches(s)) continue; Json::Value o(Json::objectValue); if (s.device != 0) o["host_id"] = std::to_string(s.device); o["kind"] = s.kind; o["tool"] = s.tool; if (!s.sessionId.empty()) o["session_id"] = s.sessionId; if (!s.requestId.empty()) o["request_id"] = s.requestId; o["cancellable"] = (s.kind == "call"); // 本工具只能打断在飞调用 matched.append(o); } int cancelled = 0; if (!reqIdKey.empty()) cancelled = srv.CancelCallById(reqIdKey, reqIdText) ? 1 : 0; else cancelled = srv.CancelCalls(devId, sessionId); // 等主机松开(最多 2s):调用还在表里就说明工具线程还没走完清理。 int waitedMs = 0; bool released = false; if (cancelled > 0) { while (waitedMs < kCancelWaitMs) { bool stillThere = false; for (const auto& s : srv.ListSessions()) { // 只轮询 kind=call:取消动不到持久会话,它们赖在表里不代表「在收尾」。 // 也要跳过取消工具自身——它一直在表里,否则 released 永远等不到 true。 if (s.kind != "call") continue; if (self && s.idKey == self->idKey) continue; if (matches(s)) { stillThere = true; break; } } if (!stillThere) { released = true; break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); waitedMs += 100; } } Json::Value sc(Json::objectValue); sc["cancelled"] = cancelled; sc["released"] = released; sc["waited_ms"] = waitedMs; sc["matched"] = matched; std::string text; if (cancelled == 0) { if (matched.empty()) { text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。"; } else { // 只匹配到持久会话/挂起表项:本工具只能取消 kind=call,说清楚下一步该用哪个工具。 std::string kinds; for (const auto& m : matched) { const std::string k = m["kind"].asString(); if (kinds.find(k) == std::string::npos) { if (!kinds.empty()) kinds += "/"; kinds += k; } } text = u8"匹配到 " + std::to_string((int)matched.size()) + u8" 个会话(kind=" + kinds + u8"),但都不是可取消的在飞调用(kind=call)。持久会话请按类型关闭(id 与 session_id 都要给):" u8"terminal → terminal_close,remote_control → remote_close,chat → chat_close;" u8"pending / file_transfer 是所属在飞调用的等待态,取消那次调用即可一并释放。"; } } else if (released) { text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," + std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。"; } else { text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求,但 " + std::to_string(kCancelWaitMs) + u8" ms 内仍在收尾(主机可能要等到客户端回包或超时);" u8"稍后用 mcp_list_sessions 复查。"; } Json::Value result(Json::objectValue); result["structuredContent"] = sc; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)===== static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用 // 超时轮询(P0-2):超时不再销毁会话,改为返回部分输出 + 可继续轮询,因此需要三个上限。 static const int kTermMaxDataBytes = 8 * 1024 * 1024; // 单条命令原始输出硬上限(超出丢最旧字节) static const int kTermMaxOutputBytes = 64 * 1024; // 单次 terminal_exec 返回的原始输出上限 static const int kTermBusyMaxSec = 3600; // busy 兜底:命令跑满 1 小时强制回收 // 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 macOS。 // 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。 static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent, uint64_t& devId, context*& ctx, std::string& errJson) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.IsTerminalEnabled() || mcp.IsReadonly()) { errJson = BuildError(id, -32006, "Persistent terminal is disabled: requires McpTerminal=1 and McpReadonly=0"); return false; } std::string err; if (!ParseHostIdArg(args, devId, err)) { errJson = BuildError(id, -32602, err); return false; } ctx = FindMainContext(parent, devId); if (!ctx) { errJson = BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); return false; } CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "MAC" && !ctx->SupportsTerminal()) { errJson = BuildError(id, -32005, "macOS client is too old for the persistent terminal: " "it does not declare CLIENT_CAP_TERMINAL; upgrade the client first"); 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; } // 发送哨兵命令行(复用 exec_command 的哨兵逻辑);回传所发送的两行, // 供调用方剔除 PTY 把输入整行回显造成的噪声。cp 由平台/isPty 决定。 static void SendTerminalCommandLine(context* subCtx, bool isPty, bool posix, const std::string& command, const std::string& nonce, std::string& cmdLine, std::string& sentLine) { SendSentinelLines(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); } // 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 → // 去输入回显 → TrimRight。 // trimTrailing=false 用于「本次只交付片段」:块尾的换行/空格属于这一块,必须原样保留, // 否则下一块的输出会和这一块的最后一行粘在一起(P0-2 逐块交付踩过:LINE-17LINE-18)。 static std::string CleanTerminalOutput(const std::vector& raw, UINT cp, bool isPty, const std::string& cmdLine, const std::string& sentLine, const std::string& nonce, bool trimTrailing = true) { std::string stdoutStr; if (!raw.empty()) { std::string rawStr((const char*)raw.data(), raw.size()); stdoutStr = StripAnsi(ToUtf8(rawStr.c_str(), cp)); size_t p = 0; while ((p = stdoutStr.find("\r\n", p)) != std::string::npos) stdoutStr.erase(p, 1); stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce); if (trimTrailing) stdoutStr = TrimRight(stdoutStr); } return stdoutStr; } // terminal_open 的 inputSchema(id 必填、timeout_ms 可选) Json::Value BuildTerminalOpenInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value timeoutProp(Json::objectValue); timeoutProp["type"] = "integer"; timeoutProp["description"] = u8"等待 shell 启动的超时毫秒数(可选,默认 20000,上限 600000)"; props["timeout_ms"] = timeoutProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; return schema; } Json::Value BuildTerminalOpenOutputSchema() { Json::Value props(Json::objectValue); Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"持久会话 token,后续 terminal_exec / terminal_close 用"; props["session_id"] = sid; Json::Value pty(Json::objectValue); pty["type"] = "boolean"; pty["description"] = u8"true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)"; props["is_pty"] = pty; Json::Value reused(Json::objectValue); reused["type"] = "boolean"; reused["description"] = u8"true=该主机已有持久会话,本次直接复用(未新建);false=本次新建"; props["reused"] = reused; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("session_id"); required.append("is_pty"); schema["required"] = required; return schema; } Json::Value BuildTerminalExecInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"会话 token。带 command 时可省略:自动复用该主机已有的持久会话,没有就在内部打开一个(结果里有 session_id 与 reused)。轮询模式必须提供"; props["session_id"] = sid; Json::Value cmdProp(Json::objectValue); cmdProp["type"] = "string"; cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令"; props["command"] = cmdProp; Json::Value timeoutProp(Json::objectValue); timeoutProp["type"] = "integer"; timeoutProp["description"] = u8"本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可"; props["timeout_ms"] = timeoutProp; Json::Value maxOutProp(Json::objectValue); maxOutProp["type"] = "integer"; maxOutProp["description"] = u8"单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余"; props["max_output_bytes"] = maxOutProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; // 执行(带 command)可省略 session_id,轮询(不带 command)必须带 session_id; // 两者都没有时 handler 直接 -32602。用 anyOf 把这条只写在描述里的约束落到 schema。 Json::Value anyOf(Json::arrayValue); for (const char* key : { "command", "session_id" }) { Json::Value alt(Json::objectValue); Json::Value req(Json::arrayValue); req.append(key); alt["required"] = req; anyOf.append(alt); } schema["anyOf"] = anyOf; return schema; } Json::Value BuildTerminalExecOutputSchema() { Json::Value props(Json::objectValue); Json::Value stdoutProp(Json::objectValue); stdoutProp["type"] = "string"; stdoutProp["description"] = u8"本次新增的输出(已剥哨兵与 ANSI 转义)"; props["stdout"] = stdoutProp; Json::Value doneProp(Json::objectValue); doneProp["type"] = "boolean"; doneProp["description"] = u8"false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效"; props["done"] = doneProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"会话 token,原样回传,便于续接轮询"; props["session_id"] = sid; Json::Value ptyProp(Json::objectValue); ptyProp["type"] = "boolean"; ptyProp["description"] = u8"true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)"; props["is_pty"] = ptyProp; Json::Value reusedProp(Json::objectValue); reusedProp["type"] = "boolean"; reusedProp["description"] = u8"true=复用了该主机已有的持久会话;false=本次隐式新建(省略 session_id 时)"; props["reused"] = reusedProp; Json::Value exitProp(Json::objectValue); exitProp["type"] = "integer"; exitProp["description"] = u8"退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)"; props["exit_code"] = exitProp; Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; truncProp["description"] = u8"true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回"; props["truncated"] = truncProp; Json::Value dropProp(Json::objectValue); dropProp["type"] = "integer"; dropProp["description"] = u8"因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)"; props["dropped_bytes"] = dropProp; Json::Value elapsedProp(Json::objectValue); elapsedProp["type"] = "integer"; elapsedProp["description"] = u8"本次调用实际等待的毫秒数"; props["elapsed_ms"] = elapsedProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("stdout"); required.append("done"); required.append("session_id"); schema["required"] = required; return schema; } Json::Value BuildTerminalCloseInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"terminal_open 返回的 session_id"; props["session_id"] = sid; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); schema["required"] = required; return schema; } Json::Value BuildTerminalCloseOutputSchema() { Json::Value props(Json::objectValue); Json::Value closed(Json::objectValue); closed["type"] = "boolean"; closed["description"] = u8"恒为 true(关闭幂等)"; props["closed"] = closed; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("closed"); schema["required"] = required; return schema; } // tools/call:terminal_open(打开持久 shell 会话,返回 session_id;用毕须 terminal_close) std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleTerminals(kTermIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; std::string sessionId = GenerateRandomToken(); if (!mcp.BeginTermOpen(devId, sessionId)) { // 该 host 已有持久会话(可能是 terminal_exec 隐式建的):直接复用它并返回 token, // 而不是报 -32003 让调用方对着一个看不见的会话干瞪眼(P0-1 风险 2)。 bool reusedPty = false; if (mcp.ReuseTermSession(devId, sessionId, reusedPty) != 0) return BuildError(id, -32003, "Device busy: a terminal session for this host is still starting"); Json::Value reusedResult(Json::objectValue); Json::Value reusedSc(Json::objectValue); reusedSc["session_id"] = sessionId; reusedSc["is_pty"] = reusedPty; reusedSc["reused"] = true; reusedResult["structuredContent"] = reusedSc; Json::Value reusedText(Json::objectValue); reusedText["session_id"] = sessionId; reusedText["reused"] = true; SetStructuredTextPayload(reusedResult, reusedText); reusedResult["isError"] = false; return BuildResult(id, reusedResult); } BYTE cmd = COMMAND_SHELL; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearTermPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } context* subCtx = nullptr; bool isPty = false; if (!mcp.WaitTerminalReady(devId, subCtx, isPty, timeoutMs)) return BuildError(id, -32001, "Timeout waiting for shell to start"); // 审计:打开会话(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " term-open: session " + sessionId; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP持久终端"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["session_id"] = sessionId; structuredContent["is_pty"] = isPty; structuredContent["reused"] = false; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = sessionId; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // terminal_exec 的结果 JSON:一次调用可能只拿到片段(超时/轮询/截断),done 与 truncated // 各自表达「命令是否结束」与「本块之后是否还有输出」,模型据此决定是否继续轮询。 static std::string BuildTerminalExecResult(const Json::Value& id, const std::string& sessionId, const std::string& output, bool done, bool closed, int exitCode, bool truncated, size_t droppedBytes, int elapsedMs, bool isPty, bool reused) { const int finalExit = done ? (closed ? -1 : exitCode) : -1; Json::Value structuredContent(Json::objectValue); structuredContent["stdout"] = output; structuredContent["done"] = done; structuredContent["session_id"] = sessionId; structuredContent["is_pty"] = isPty; structuredContent["reused"] = reused; if (done) structuredContent["exit_code"] = finalExit; structuredContent["truncated"] = truncated; if (droppedBytes > 0) structuredContent["dropped_bytes"] = (Json::UInt64)droppedBytes; structuredContent["elapsed_ms"] = elapsedMs; Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; // 同 exec_command:stdout 在正文里,正文外只补状态字段。 Json::Value textPayload(Json::objectValue); textPayload["done"] = done; textPayload["session_id"] = sessionId; if (done) textPayload["exit_code"] = finalExit; textPayload["truncated"] = truncated; if (droppedBytes > 0) textPayload["dropped_bytes"] = (Json::UInt64)droppedBytes; SetStructuredTextPayload(result, textPayload); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; if (!output.empty()) item["text"] = output; else item["text"] = done ? std::string(u8"(无输出)") : std::string(u8"(暂无新输出,命令仍在运行,继续轮询)"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:terminal_exec // 带 command → 在已打开的持久会话中执行一条命令(无白名单;PTY 下允许管道/串联) // 不带 command、只传 session_id → 轮询模式:等待/取回当前命令的增量输出 // 超时不再销毁会话:返回 done:false + 已产生的输出,会话保持 busy,后续轮询直到 done:true。 std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleTerminals(kTermIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX" || ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" || ctx->GetAdditionalData(RES_CLIENT_TYPE) == "MAC"); // command 省略 = 轮询模式(P0-2);session_id 可省略(P0-1:带 command 时自动建/复用默认会话)。 std::string command = Trim(GetStringArg(args, "command")); const bool isPoll = command.empty(); std::string sessionId = GetStringArg(args, "session_id"); if (isPoll && sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id (polling needs the session token)"); auto sessionError = [&](int code) -> std::string { // 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。 std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId); if (!destroyed.empty()) return BuildError(id, -32002, destroyed); if (code == 4) return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session"); if (code == 6) return BuildError(id, -32003, "Device busy: the previous command finished but its output is not fully drained; " "call terminal_exec with only session_id to collect the rest first"); if (code == 2) return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId); if (code == 3) return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId); if (code == 5) return BuildError(id, -32002, "Terminal session is already closing: " + sessionId); if (code == 7) return BuildError(id, -32002, "Terminal session is idle: no command is running; pass command to execute one"); return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)"); }; int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; int maxOutputBytes = kTermMaxOutputBytes; if (GetIntArg(args, "max_output_bytes", v) && v >= 1024 && v <= 1024 * 1024) maxOutputBytes = v; const auto started = std::chrono::steady_clock::now(); std::string nonce, cmdLine, sentLine; bool isPty = false; bool reused = true; // session_id 由调用方提供或复用了已有会话 // 没给 session_id:复用该主机已有的持久会话;没有就按 terminal_open 的同一路径隐式建一个 // (对外不暴露 open/close,结果里带回 session_id 与 reused)。 if (sessionId.empty()) { int openOrReuse = mcp.OpenOrReuseTermSession(devId, sessionId, reused); if (openOrReuse != 0) return BuildError(id, -32003, "Device busy: a terminal session for this host is still starting"); if (!reused) { BYTE openCmd = COMMAND_SHELL; if (!ctx->Send2Client(&openCmd, 1)) { mcp.ClearTermPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } context* openSubCtx = nullptr; bool openPty = false; if (!mcp.WaitTerminalReady(devId, openSubCtx, openPty, CMcpServer::Instance().ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for shell to start"); if (parent) { std::string text = "host " + std::to_string(devId) + " term-open (implicit): session " + sessionId; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP持久终端"))); } } } if (!isPoll) { // 先只读查会话形态:PTY 会话才允许管道/串联;失败时状态不变。 int peek = mcp.PeekTermSession(devId, sessionId, isPty); if (peek != 0) return sessionError(peek); // 正确性门(非安全门):换行会拆成多行、只有末行被哨兵包装,一律拒绝。 // 管道 | 与 && 串联在 PTY 会话(ConPTY / POSIX PTY)下是安全的:哨兵独立成行执行, // 拿到的是整条管道/串联的退出码。老非 PTY 客户端仍是单行哨兵,继续拒绝 & 与 |。 if (ContainsControlChar(command)) return BuildError(id, kErrValidation, "Command contains a control character (newline/tab); send one line per call"); if (!isPty && command.find_first_of("&|") != std::string::npos) return BuildError(id, kErrValidation, "Pipes and & require a PTY session (newer client); this session uses the legacy " "non-PTY shell. Run the commands as separate terminal_exec calls"); if (posix && HasPosixBackgroundAmpersand(command)) return BuildError(id, kErrValidation, "Background execution (&) breaks output capture; use && to chain commands " "or run it in a separate session"); nonce = GenerateRandomToken().substr(0, 8); context* subCtx = nullptr; int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty); if (begin != 0) return sessionError(begin); // 新会话的第一条命令可能与 shell 启动竞争,等提示符到达再写(见 WaitTerminalBootstrap)。 if (posix && isPty) mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000); // 等待期间 shell 可能已退出(子连接断开后指针交还连接池、可能被复用):确认仍是本会话 // 的子连接才写;不写则下面 WaitTermCommand 立即按 closed 收尾(会话结束、需重新 open)。 if (mcp.IsTermSubCtxLive(devId, sessionId, subCtx)) SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); // 审计:命令执行(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " term-exec [" + sessionId + "]: " + command; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP持久终端"))); } } std::vector raw; int exitCode = -1; bool done = false, closed = false, truncated = false; size_t droppedBytes = 0; int waitResult = mcp.WaitTermCommand(devId, sessionId, raw, done, exitCode, closed, truncated, droppedBytes, isPty, nonce, maxOutputBytes, timeoutMs, isPoll); if (waitResult == 2) // 取消:会话已销毁(分发层会把错误改写成 -32800) return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed"); if (waitResult != 0 && waitResult != 1) return sessionError(waitResult); int elapsedMs = (int)std::chrono::duration_cast( std::chrono::steady_clock::now() - started).count(); // shell 退出时 WaitTermCommand 会清理会话与路由(本次被 max_output_bytes 截断时先保留, // 等后续轮询把尾巴取完再清理);子连接本身已由客户端关闭,无需 CancelIO。 // 轮询块没有命令回显可剥(回显只在首块);命令路径带 cmdLine/sentLine 走完整清洗。 // 片段交付(命令未结束或本次被 max_output_bytes 截断)保留块尾空白,拼接才不粘连。 const bool finalChunk = done && !truncated; std::string stdoutStr = CleanTerminalOutput(raw, (posix || isPty) ? CP_UTF8 : 936, isPty, isPoll ? std::string() : cmdLine, isPoll ? std::string() : sentLine, nonce, finalChunk); return BuildTerminalExecResult(id, sessionId, stdoutStr, done, closed, exitCode, truncated, droppedBytes, elapsedMs, isPty, reused); } // tools/call:terminal_close(关闭持久会话;幂等,session_id 不匹配报错) std::string BuildTerminalClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleTerminals(kTermIdleTimeoutSec); if (!mcp.IsTerminalEnabled() || mcp.IsReadonly()) return BuildError(id, -32006, "Persistent terminal is disabled: requires McpTerminal=1 and McpReadonly=0"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); int r = mcp.CloseTermSession(devId, sessionId); if (r == 2) return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId); // 审计:关闭会话(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " term-close: session " + sessionId; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP持久终端"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["closed"] = true; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"closed"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P5:MCP 远程控制(remote_open / remote_close)===== static const int kScreenCtrlIdleTimeoutSec = 300; // 远程控制 idle 回收超时(秒) // 共享前置:校验 McpRemoteControl && !readonly → 解析 id → FindMainContext → 拒绝 macOS。 // 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。 static bool ResolveScreenCtrlSessionHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent, uint64_t& devId, context*& ctx, std::string& errJson) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.IsRemoteControlEnabled() || mcp.IsReadonly()) { errJson = BuildError(id, -32006, "Remote control is disabled: requires McpRemoteControl=1 and McpReadonly=0"); return false; } std::string err; if (!ParseHostIdArg(args, devId, err)) { errJson = BuildError(id, -32602, err); return false; } ctx = FindMainContext(parent, devId); if (!ctx) { errJson = BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); return false; } CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "MAC") { errJson = BuildError(id, -32005, "Remote control is only supported on Windows, Linux and Android hosts"); return false; } return true; } // remote_open 的 inputSchema(id 必填、timeout_ms / window_hwnd / region 可选) Json::Value BuildRemoteOpenInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value timeoutProp(Json::objectValue); timeoutProp["type"] = "integer"; timeoutProp["description"] = u8"等待屏幕子连接建立 + 分辨率到达的超时毫秒数(可选,默认 20000,上限 600000)"; props["timeout_ms"] = timeoutProp; Json::Value hwndProp(Json::objectValue); Json::Value hwndTypes(Json::arrayValue); hwndTypes.append("integer"); hwndTypes.append("string"); hwndProp["type"] = hwndTypes; hwndProp["description"] = u8"可选:只推该窗口(DWM 可见边框,含标题栏),帧尺寸与归一化坐标都相对该窗口,带宽和点击精度都优于整屏。取 host_inspect 的 windows 项 / get_foreground_window 返回的 hwnd(整数或 0x 前缀字符串);最小化窗口会被拒绝(-32009)。与 region 互斥。要求客户端能力位 CLIENT_CAP_WINDOW_INFO(新 Windows 客户端),老客户端返回 -32005。"; props["window_hwnd"] = hwndProp; Json::Value regionProp(Json::objectValue); regionProp["type"] = "object"; regionProp["description"] = u8"可选:只推该矩形区域(虚拟桌面物理像素,超出部分自动裁剪;裁剪后为空返回 -32009)。与 window_hwnd 互斥。region 内的归一化坐标 0..1 相对该矩形。要求新 Windows 客户端(窗口信息响应带虚拟桌面矩形),否则返回 -32005。"; Json::Value regionProps(Json::objectValue); Json::Value rxProp(Json::objectValue); rxProp["type"] = "integer"; rxProp["description"] = u8"矩形左上角 X(虚拟桌面绝对坐标,可为负;省略按 0)"; regionProps["x"] = rxProp; Json::Value ryProp(Json::objectValue); ryProp["type"] = "integer"; ryProp["description"] = u8"矩形左上角 Y(虚拟桌面绝对坐标,可为负;省略按 0)"; regionProps["y"] = ryProp; Json::Value rwProp(Json::objectValue); rwProp["type"] = "integer"; rwProp["description"] = u8"矩形宽度(像素,1~8192)"; regionProps["width"] = rwProp; Json::Value rhProp(Json::objectValue); rhProp["type"] = "integer"; rhProp["description"] = u8"矩形高度(像素,1~8192)"; regionProps["height"] = rhProp; regionProp["properties"] = regionProps; Json::Value regionRequired(Json::arrayValue); regionRequired.append("width"); regionRequired.append("height"); regionProp["required"] = regionRequired; props["region"] = regionProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); schema["required"] = required; return schema; } Json::Value BuildRemoteOpenOutputSchema() { Json::Value props(Json::objectValue); Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"控制会话 token,后续 remote_mouse / remote_keyboard / remote_close 用"; props["session_id"] = sid; Json::Value target(Json::objectValue); target["type"] = "string"; target["description"] = u8"抓屏帧目标:screen=整屏/整虚拟桌面;window=目标窗口;region=指定区域"; props["target"] = target; Json::Value sw(Json::objectValue); sw["type"] = "integer"; sw["description"] = u8"抓屏帧宽度(发送帧像素:整屏/整虚拟桌面/目标窗口/区域,可能已等比缩放),用于把归一化坐标 0..1 映射为像素"; props["screen_w"] = sw; Json::Value sh(Json::objectValue); sh["type"] = "integer"; sh["description"] = u8"抓屏帧高度(发送帧像素)"; props["screen_h"] = sh; Json::Value win(Json::objectValue); win["type"] = "integer"; win["description"] = u8"window 目标时的窗口句柄;其他目标不返回"; props["window_hwnd"] = win; Json::Value region(Json::objectValue); region["type"] = "object"; region["description"] = u8"region 目标时实际生效的矩形(虚拟桌面坐标,已裁剪;width/height 为物理像素)"; Json::Value regionProps(Json::objectValue); const char* regionKeys[] = { "x", "y", "width", "height" }; for (const char* k : regionKeys) { Json::Value v(Json::objectValue); v["type"] = "integer"; regionProps[k] = v; } region["properties"] = regionProps; props["region"] = region; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("session_id"); required.append("target"); required.append("screen_w"); required.append("screen_h"); schema["required"] = required; return schema; } Json::Value BuildRemoteCloseInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); schema["required"] = required; return schema; } Json::Value BuildRemoteCloseOutputSchema() { Json::Value props(Json::objectValue); Json::Value closed(Json::objectValue); closed["type"] = "boolean"; closed["description"] = u8"恒为 true(幂等)"; props["closed"] = closed; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("closed"); schema["required"] = required; return schema; } // region 对象的整数字段(GetIntArg 只查顶层键) static bool GetNestedIntArg(const Json::Value& obj, const char* key, int& out) { if (!obj.isMember(key)) return false; const Json::Value& v = obj[key]; if (!v.isNumeric()) return false; out = v.asInt(); return true; } // 窗口信息单次查询结果(定义在窗口工具族附近,remote_open 的窗口目标也要用) struct WindowLookup { int rc = 0; // FetchWindowInfo 返回码 std::string err; bool found = false; bool foreground = false; bool truncated = false; // 客户端可见窗口多于单包上限,列表不完整 WindowDesktopRect desktop; // 新客户端才有的虚拟桌面矩形(window_hwnd 相对坐标用) WindowEntry entry; // 命中的窗口记录(未命中时字段无意义) Json::Value json; // 目标窗口快照;未找到时为 null }; static WindowLookup LookupWindow(context* ctx, uint64_t devId, const char* tool, uint32_t hwnd); static std::string WindowRpcErrorJson(const Json::Value& id, uint64_t devId, int rc, const std::string& err); static std::string WindowNotFoundErrorJson(const Json::Value& id, uint32_t hwnd, bool truncated); // tools/call:remote_open(建立隐藏屏幕子连接 + 取抓屏帧尺寸) std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; // 能力位前置:Linux 的抓屏与注入都走 X11(Xorg/XWayland),客户端只在 DISPLAY 可用时 // 才在登录里声明 CLIENT_CAP_SCREEN_PREVIEW;声明了能力位(非空 caps)却没有这一位, // 说明是纯 Wayland/无 X11 的会话,抓不到帧也注入不了——提前返回 -32005,免得白等 // timeout_ms 再报「子连接超时」,还留下一次 web-triggered 标记的清理。老客户端 // (caps 为空)无从判定,与多显示器门一样按放行处理(老的 COMMAND_SCREEN_SPY 链路仍可用)。 // Android 不能套这个门:APK 的 SCREEN_PREVIEW 位只代表 API 30+ 且无障碍在运行(用于 // get_screenshot 的 takeScreenshot),而远程控制抓屏走 MediaProjection、注入走 // dispatchGesture——没有这一位的主机远程控制仍可能可用。 CString hostClientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool declaresCaps = !ctx->GetClientData(ONLINELIST_CAPABILITIES).IsEmpty(); if (declaresCaps && hostClientType == "LNX" && !ctx->SupportsScreenPreview()) return BuildError(id, -32005, "Remote control requires screen preview capability (X11/Xorg desktop on Linux); " "this host does not declare it"); // ---- 帧目标(可选):window_hwnd 只推窗口,region 只推矩形;缺省推整屏/整虚拟桌面 ---- uint32_t windowHwnd = 0; bool hasWindow = false; RECT requestedRegion = { 0, 0, 0, 0 }; bool hasRegion = false; { std::string oerr; if (!GetOptionalWindowArg(args, "window_hwnd", windowHwnd, hasWindow, oerr)) return BuildError(id, -32602, oerr); if (args.isMember("region") && !args["region"].isNull()) { const Json::Value& rg = args["region"]; if (!rg.isObject()) return BuildError(id, -32602, "Invalid region: expected an object {x,y,width,height}"); int rx = 0, ry = 0, rw = 0, rh = 0; const bool ok = (!rg.isMember("x") || GetNestedIntArg(rg, "x", rx)) && (!rg.isMember("y") || GetNestedIntArg(rg, "y", ry)) && GetNestedIntArg(rg, "width", rw) && GetNestedIntArg(rg, "height", rh); if (!ok) return BuildError(id, -32602, "Invalid region: x/y/width/height must be integers"); if (rw < 1 || rw > 8192 || rh < 1 || rh > 8192) return BuildError(id, -32602, "Invalid region: width/height must be 1..8192"); if (rx < -1000000 || rx > 1000000 || ry < -1000000 || ry > 1000000) return BuildError(id, -32602, "Invalid region: x/y out of range"); requestedRegion = RECT{ rx, ry, rx + rw, ry + rh }; hasRegion = true; } if (hasWindow && hasRegion) return BuildError(id, -32602, "window_hwnd and region are mutually exclusive"); if ((hasWindow || hasRegion) && !ctx->SupportsWindowInfo()) return BuildError(id, -32005, "window_hwnd/region targets require window info capability, " "which this host does not support (newer Windows clients only)"); } // 窗口目标:确认窗口存在且可捕获(窗口列表 RPC);区域目标:取虚拟桌面矩形, // 用于把物理坐标换算成客户端发送帧坐标。两者都只在新 Windows 客户端可用。 WindowLookup targetWin; RECT effectiveRegion = { 0, 0, 0, 0 }; if (hasWindow) { targetWin = LookupWindow(ctx, devId, "remote_open", windowHwnd); if (targetWin.rc != 0) return WindowRpcErrorJson(id, devId, targetWin.rc, targetWin.err); if (!targetWin.found) return WindowNotFoundErrorJson(id, windowHwnd, targetWin.truncated); const WindowEntry& we = targetWin.entry; if (we.flags & WINDOWINFO_MINIMIZED) return BuildError(id, -32009, "Window hwnd=" + std::to_string(windowHwnd) + " is minimized; restore it before opening a window-targeted session"); if (we.right <= we.left || we.bottom <= we.top) return BuildError(id, -32009, "Window hwnd=" + std::to_string(windowHwnd) + " has an empty rect; window capture is not usable"); } else if (hasRegion) { std::vector wins; std::string werr; const int rc = FetchWindowInfo(ctx, devId, "remote_open", 0, wins, werr, nullptr, &targetWin.desktop); if (rc != 0) return WindowRpcErrorJson(id, devId, rc, werr); if (!targetWin.desktop.valid) return BuildError(id, -32005, "region target requires a newer Windows client: its window info response " "does not carry the virtual desktop rect"); const WindowDesktopRect& d = targetWin.desktop; effectiveRegion.left = requestedRegion.left > d.left ? requestedRegion.left : d.left; effectiveRegion.top = requestedRegion.top > d.top ? requestedRegion.top : d.top; effectiveRegion.right = requestedRegion.right < d.left + d.width ? requestedRegion.right : (d.left + d.width); effectiveRegion.bottom = requestedRegion.bottom < d.top + d.height ? requestedRegion.bottom : (d.top + d.height); if (effectiveRegion.right <= effectiveRegion.left || effectiveRegion.bottom <= effectiveRegion.top) return BuildError(id, -32009, "region lies outside the virtual desktop; nothing to capture"); } // 多显示器门:截图与注入必须共用同一坐标系。Windows 新客户端(CLIENT_CAP_VIRTUAL_DESKTOP) // 会按 COMMAND_SCREEN_SPY 参数 buffer[11](wire 索引 12)抓整个虚拟桌面,可放行; // 老 Windows 客户端只能抓单块屏,N>1 时归一化坐标会系统性偏移,拒绝并提示升级。 // 非 Windows(如 Linux)不要求该能力位:其截屏取整个 X root // (linux/ScreenHandler.h 用 XDisplayWidth/Height),注入用 root 绝对坐标, // 多输出下天然同源。无冒号(老客户端格式)无法判定,放行不拦。 // 窗口目标不依赖虚拟桌面抓屏(帧来自目标窗口),不受此门限制。 if (!hasWindow) { CString res = ctx->GetAdditionalData(RES_RESOLUTION); int colon = res.Find(':'); if (colon > 0) { int monitorCount = atoi(res.Left(colon)); if (monitorCount > 1 && IsWindowsClient(ctx) && !ctx->SupportsVirtualDesktop()) return BuildError(id, -32005, "Multi-monitor hosts require a Windows client with virtual desktop capture (upgrade the client): monitor count " + std::to_string(monitorCount)); } } // 远程控制复用 Web 的隐藏屏幕子连接(COMMAND_SCREEN_SPY → CScreenSpyDlg → RegisterScreenContext)。 // 该路径依赖 Web 远程服务已启动(WebSvrPort>0,默认开启);未启动时子连接无法建立/注册。 if (!WebService().IsRunning()) return BuildError(id, -32005, "Remote control requires the Web remote service (WebSvrPort) to be enabled"); // 与人类远程桌面观看互斥:已有屏幕子连接(web 观看)→ 拒绝,避免向人类正在看的画面注入。 if (WebService().HasActiveSession(devId)) return BuildError(id, -32003, BusyMessage( "Device busy: a remote desktop session is already active for this host", devId)); int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; std::string sessionId = GenerateRandomToken(); if (!mcp.BeginScreenCtrlOpen(devId, sessionId)) return BuildError(id, -32003, BusyMessage( "Device busy: a remote control session is already active for this host", devId)); // 失败清理:会话 + 隐藏对话框 + web-triggered 标记(StartRemoteDesktop 先置标记再发送)。 auto abortOpen = [&]() { mcp.CloseScreenCtrlSession(devId, sessionId); if (parent) parent->CloseWebRemoteDesktopByClientID(devId); WebService().ClearWebTriggered(devId); }; // 建立隐藏屏幕子连接(发 COMMAND_SCREEN_SPY、标记 web-triggered)。 // 整屏目标额外要求抓整个虚拟桌面,保证截图与注入坐标系一致;窗口目标把 HWND 放进 // token [4..11],客户端进入窗口捕获(DWM 可见边框 + 窗口原点作为注入原点)。 if (!WebService().StartRemoteDesktop(devId, ctx->SupportsVirtualDesktop(), windowHwnd)) { mcp.CloseScreenCtrlSession(devId, sessionId); // StartRemoteDesktop 先置 web-triggered 再 Send2Client,发送失败需一并清理, // 否则该设备残留 web-triggered 标记、后续人类 web 观看会误走隐藏会话路径。 WebService().ClearWebTriggered(devId); return BuildError(id, -32004, "Failed to start remote desktop session"); } // 轮询等待子连接就绪(HasActiveSession)+ 分辨率到达(TOKEN_BITMAPINFO → NotifyResolutionChange)。 // 屏幕子连接的注册/分辨率由 CScreenSpyDlg 完成,无 McpServer 回调,故用轮询(open 低频)。 int screenW = 0, screenH = 0; context* subCtx = nullptr; auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); bool ready = false; while (std::chrono::steady_clock::now() < deadline) { if (WebService().HasActiveSession(devId) && WebService().GetScreenSize(devId, screenW, screenH)) { subCtx = WebService().GetScreenContext(devId); ready = (subCtx != nullptr); break; } if (McpCallCancelled()) break; // 按「没就绪」走下面的清理与超时分支 std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (!ready) { abortOpen(); return BuildError(id, -32001, "Timeout waiting for screen sub-connection / resolution"); } // region 目标:客户端 ROI 坐标是「缩放后的整帧」坐标,与服务端拿到的 screenW/H 同口径, // 所以直接把物理矩形按虚拟桌面比例换算成 ROI 下发,客户端裁掉其余部分。 // 必须等新分辨率到达后才算就绪:否则紧随其后的注入仍会被旧 ROI/全屏解释。 if (hasRegion) { const WindowDesktopRect& d = targetWin.desktop; auto toSend = [](int p, int origin, int len, int sendLen) -> int { if (len <= 0 || sendLen <= 0) return 0; int val = (int)((double)(p - origin) * (double)sendLen / (double)len + 0.5); return val < 0 ? 0 : (val > sendLen ? sendLen : val); }; int rx = toSend(effectiveRegion.left, d.left, d.width, screenW); int ry = toSend(effectiveRegion.top, d.top, d.height, screenH); int rx2 = toSend(effectiveRegion.right, d.left, d.width, screenW); int ry2 = toSend(effectiveRegion.bottom, d.top, d.height, screenH); int rw = rx2 - rx, rh = ry2 - ry; if (rw < 1) rw = 1; if (rh < 1) rh = 1; if (rw > screenW) rw = screenW; if (rh > screenH) rh = screenH; if (rx > screenW - rw) rx = screenW - rw; if (ry > screenH - rh) ry = screenH - rh; if (rx < 0) rx = 0; if (ry < 0) ry = 0; if (rx != 0 || ry != 0 || rw != screenW || rh != screenH) { BYTE roiBuf[1 + sizeof(RECT)] = {}; roiBuf[0] = COMMAND_SCREEN_ROI; RECT roi = { rx, ry, rx + rw, ry + rh }; memcpy(roiBuf + 1, &roi, sizeof(roi)); if (!subCtx->Send2Client(roiBuf, (int)sizeof(roiBuf))) { abortOpen(); return BuildError(id, -32004, "Failed to send region target to host"); } bool roiReady = false; while (std::chrono::steady_clock::now() < deadline) { int w2 = 0, h2 = 0; if (WebService().HasActiveSession(devId) && WebService().GetScreenSize(devId, w2, h2) && w2 == rw && h2 == rh) { roiReady = true; break; } if (McpCallCancelled() || !WebService().HasActiveSession(devId)) break; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (!roiReady) { abortOpen(); return BuildError(id, -32001, "Timeout waiting for the host to switch capture to the requested region"); } screenW = rw; screenH = rh; } } if (!mcp.MarkScreenCtrlReady(devId, sessionId, subCtx, screenW, screenH, hasWindow || hasRegion)) { // 并发 remote_close 已关掉会话:放弃本次 open(子连接已由 close 关闭)。 return BuildError(id, -32002, "Remote control session was closed concurrently: " + sessionId); } const char* targetKind = hasWindow ? "window" : (hasRegion ? "region" : "screen"); // 审计:打开会话(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " remote-open: session " + sessionId + " (" + std::to_string(screenW) + "x" + std::to_string(screenH) + ")" + " target=" + targetKind; if (hasWindow) { text += " window=" + std::to_string(windowHwnd); } else if (hasRegion) { text += " region=(" + std::to_string(effectiveRegion.left) + "," + std::to_string(effectiveRegion.top) + ")-(" + std::to_string(effectiveRegion.right) + "," + std::to_string(effectiveRegion.bottom) + ")"; } parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["session_id"] = sessionId; structuredContent["target"] = targetKind; structuredContent["screen_w"] = screenW; structuredContent["screen_h"] = screenH; if (hasWindow) { structuredContent["window_hwnd"] = windowHwnd; } else if (hasRegion) { Json::Value region(Json::objectValue); region["x"] = effectiveRegion.left; region["y"] = effectiveRegion.top; region["width"] = effectiveRegion.right - effectiveRegion.left; region["height"] = effectiveRegion.bottom - effectiveRegion.top; structuredContent["region"] = region; } result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = sessionId; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call:remote_close(关闭控制会话;幂等,session_id 不匹配报错) std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); if (!mcp.IsRemoteControlEnabled() || mcp.IsReadonly()) return BuildError(id, -32006, "Remote control is disabled: requires McpRemoteControl=1 and McpReadonly=0"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); // 关闭前记下是否锁定着对端键鼠:CloseScreenCtrlSession 会强制补发 block=false, // 审计里必须能看出「这次关闭顺带解了锁」(P10-C)。 const bool wasBlocked = mcp.IsScreenCtrlBlocked(devId, sessionId); int r = mcp.CloseScreenCtrlSession(devId, sessionId); if (r == 2) return BuildError(id, -32002, "Remote control session_id mismatch: " + sessionId); // 仅当确实关闭了 MCP 会话(r==0)时才关闭隐藏屏幕子连接;r==1(幂等,会话已不存在, // 如已被 idle 回收)时不得误关人类正在观看的 web 会话(CloseWebRemoteDesktopByClientID // 会关掉该设备任一 IsWebSession 的对话框)。 if (r == 0) { // 关闭隐藏屏幕子连接(幂等):WM_CLOSE → CScreenSpyDlg 析构 → UnregisterScreenContext。 if (parent) parent->CloseWebRemoteDesktopByClientID(devId); WebService().ClearWebTriggered(devId); } // 审计:关闭会话(不可关闭)。 if (parent) { std::string text = "host " + std::to_string(devId) + " remote-close: session " + sessionId; if (wasBlocked && r == 0) text += " (input lock forced off)"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["closed"] = true; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"closed"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P5:remote_keyboard(键盘注入,key_down / key_up / key_press / type)===== // 键名 → 虚拟键码(对齐 Windows VK_* 去掉前缀,见设计 §4.3)。 // 支持:单字符 A-Z/0-9、F1-F24、命名键、修饰键。未知返回 0(VK 0 非真实键)。 static int MapKeyNameToVk(const std::string& nameIn) { std::string n; for (char c : nameIn) n += (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c; if (n.size() == 1) { unsigned char c = (unsigned char)n[0]; if (c >= 'A' && c <= 'Z') return c; // 'A'..'Z' == VK_A..VK_Z if (c >= '0' && c <= '9') return c; // '0'..'9' == VK_0..VK_9 return 0; // 标点等请走 type } // F1..F24 if (n.size() >= 2 && n.size() <= 3 && n[0] == 'F') { int fnum = atoi(n.c_str() + 1); if (fnum >= 1 && fnum <= 24) return VK_F1 + (fnum - 1); return 0; } struct Named { const char* name; int vk; }; static const Named kNames[] = { {"ENTER", VK_RETURN}, {"RETURN", VK_RETURN}, {"TAB", VK_TAB}, {"SPACE", VK_SPACE}, {"ESC", VK_ESCAPE}, {"ESCAPE", VK_ESCAPE}, {"BACKSPACE", VK_BACK}, {"DELETE", VK_DELETE}, {"DEL", VK_DELETE}, {"INSERT", VK_INSERT}, {"INS", VK_INSERT}, {"HOME", VK_HOME}, {"END", VK_END}, {"PAGEUP", VK_PRIOR}, {"PRIOR", VK_PRIOR}, {"PAGEDOWN", VK_NEXT}, {"NEXT", VK_NEXT}, {"LEFT", VK_LEFT}, {"RIGHT", VK_RIGHT}, {"UP", VK_UP}, {"DOWN", VK_DOWN}, {"CAPSLOCK", VK_CAPITAL}, {"CAPITAL", VK_CAPITAL}, {"NUMLOCK", VK_NUMLOCK}, {"SCROLLLOCK", VK_SCROLL}, {"PRINTSCREEN", VK_SNAPSHOT}, {"SNAPSHOT", VK_SNAPSHOT}, {"PAUSE", VK_PAUSE}, {"APPS", VK_APPS}, {"CONTEXTMENU", VK_APPS}, {"CTRL", VK_CONTROL}, {"CONTROL", VK_CONTROL}, {"ALT", VK_MENU}, {"MENU", VK_MENU}, {"SHIFT", VK_SHIFT}, {"WIN", VK_LWIN}, {"WINDOWS", VK_LWIN}, {"CMD", VK_LWIN}, {"SUPER", VK_LWIN}, }; for (const Named& e : kNames) if (n == e.name) return e.vk; return 0; } // 是否修饰键(modifiers 白名单:CTRL/ALT/SHIFT/WIN) static bool IsModifierVk(int vk) { return vk == VK_CONTROL || vk == VK_MENU || vk == VK_SHIFT || vk == VK_LWIN || vk == VK_RWIN; } // 解析可选 modifiers 数组(JSON 字符串数组)→ 修饰键 VK 序列。非法返回 false 并填 err。 static bool ParseModifiers(const Json::Value& args, std::vector& out, std::string& err) { out.clear(); if (!args.isMember("modifiers")) return true; const Json::Value& mods = args["modifiers"]; if (mods.isNull()) return true; if (!mods.isArray()) { err = "modifiers must be an array of strings"; return false; } for (const auto& m : mods) { if (out.size() >= 8) { err = "too many modifiers (max 8)"; return false; } int vk = MapKeyNameToVk(m.asString()); if (vk == 0 || !IsModifierVk(vk)) { err = "invalid modifier: " + (m.isString() ? m.asString() : std::string("(non-string)")); return false; } out.push_back(vk); } return true; } // 是否纯 ASCII(type 走物理键事件,只能可靠注入 ASCII/ANSI;见设计 §6.4) static bool IsAscii(const std::string& s) { for (unsigned char c : s) if (c >= 0x80) return false; return true; } // type:逐字符 VkKeyScanA 映射为「(Shift↓)字符↓ 字符↑(Shift↑)」,回车/制表符映射为按键。 // 注:VkKeyScanA 在服务端按服务端线程键盘布局解析字符→虚拟键;仅限 ASCII(0..127)时 // 各布局的字母/数字/常用标点虚拟键一致,跨布局差异可忽略(非 ASCII 一律走剪贴板)。 static void BuildTypeBatch(const std::string& text, std::vector& batch) { for (unsigned char ch : text) { if (ch == '\r' || ch == '\n') { batch.push_back(BuildKeyMsg64(VK_RETURN, true, false)); batch.push_back(BuildKeyMsg64(VK_RETURN, false, false)); continue; } if (ch == '\t') { batch.push_back(BuildKeyMsg64(VK_TAB, true, false)); batch.push_back(BuildKeyMsg64(VK_TAB, false, false)); continue; } SHORT scan = VkKeyScanA((char)ch); if (scan == -1) continue; // 无法映射(控制字符等)→ 跳过 int vk = scan & 0xFF; bool needShift = (scan >> 8) & 1; if (needShift) batch.push_back(BuildKeyMsg64(VK_SHIFT, true, false)); batch.push_back(BuildKeyMsg64(vk, true, false)); batch.push_back(BuildKeyMsg64(vk, false, false)); if (needShift) batch.push_back(BuildKeyMsg64(VK_SHIFT, false, false)); } } Json::Value BuildRemoteKeyboardInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value act(Json::objectValue); act["type"] = "string"; act["description"] = u8"动作:key_down / key_up / key_press / type"; props["action"] = act; Json::Value key(Json::objectValue); key["type"] = "string"; key["description"] = u8"按键(key_down/key_up/key_press 用):Windows 虚拟键名(如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN)或单个字母/数字"; props["key"] = key; Json::Value text(Json::objectValue); text["type"] = "string"; text["description"] = u8"文本(type 用,仅 ASCII;非 ASCII 请走 remote_clipboard + Ctrl+V)"; props["text"] = text; Json::Value mods(Json::objectValue); mods["type"] = "array"; Json::Value modItem(Json::objectValue); modItem["type"] = "string"; mods["items"] = modItem; mods["description"] = u8"修饰键(可选):CTRL/ALT/SHIFT/WIN"; props["modifiers"] = mods; Json::Value expect(Json::objectValue); Json::Value expectTypes(Json::arrayValue); expectTypes.append("integer"); expectTypes.append("string"); expect["type"] = expectTypes; expect["description"] = u8"可选:注入前先确认目标窗口仍在当前可见窗口列表中(整数或 0x 前缀字符串)。" u8"顺带默认回报前台窗口;仅新 Windows 客户端支持(否则 -32005)。"; props["expect_hwnd"] = expect; Json::Value requireFg(Json::objectValue); requireFg["type"] = "boolean"; requireFg["description"] = u8"可选:配合 expect_hwnd,要求该窗口已是前台,否则不发注入并返回 -32000。默认 false"; props["require_foreground"] = requireFg; Json::Value reportFg(Json::objectValue); reportFg["type"] = "boolean"; reportFg["description"] = u8"可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true"; props["report_foreground"] = reportFg; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); required.append("action"); schema["required"] = required; // 描述里写明「type 用 text、按键动作用 key」,但 schema 只要求 id/session_id/action, // 漏字段要到 handler 才报错。条件必填让模型在发参数前就看到。 AppendConditionalRequired(schema, "action", { "type" }, { "text" }); AppendConditionalRequired(schema, "action", { "key_down", "key_up", "key_press" }, { "key" }); return schema; } Json::Value BuildRemoteKeyboardOutputSchema() { Json::Value props(Json::objectValue); Json::Value windowProp(Json::objectValue); windowProp["type"] = "object"; windowProp["description"] = u8"expect_hwnd 时注入前的目标窗口快照"; props["expectedWindow"] = windowProp; Json::Value fgProp(Json::objectValue); // report_foreground 时若系统没有可枚举的前台窗口,foreground 为 null。 Json::Value fgTypes(Json::arrayValue); fgTypes.append("object"); fgTypes.append("null"); fgProp["type"] = fgTypes; fgProp["description"] = u8"注入后的前台窗口(report_foreground 时返回;无前台窗口为 null)"; props["foreground"] = fgProp; Json::Value fgErr(Json::objectValue); fgErr["type"] = "string"; fgErr["description"] = u8"前台回报失败的原因(注入本身已成功)"; props["foregroundError"] = fgErr; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // 下发一批输入事件:每条 MSG64 单独一包([COMMAND_SCREEN_CONTROL][MSG64])。 // 协议上本可一包多条,但 Linux 客户端(ScreenHandler::OnReceive)只处理包内第一条, // 多消息批量会让 key_press 只剩按下(触发键盘自动重复)、click 只剩按下、type 只打出 // 首字符。按消息拆包对 Windows 客户端完全等价(它本来就一次处理一条),且新老客户端 // 行为一致,故不改客户端。任一条发送失败即返回 false。 static bool SendScreenCtrlEvents(context* subCtx, const std::vector& batch) { std::vector packet(1 + sizeof(MSG64)); packet[0] = COMMAND_SCREEN_CONTROL; for (size_t i = 0; i < batch.size(); ++i) { memcpy(packet.data() + 1, &batch[i], sizeof(MSG64)); if (!subCtx->Send2Client(packet.data(), (ULONG)packet.size())) return false; } return true; } // ===== 输入注入的窗口校验(expect_hwnd / require_foreground / report_foreground)===== // // 键鼠注入走屏幕子连接,窗口信息走主连接 RPC,两条链路互不占用,可安全地一前一后。 // 这些辅助只在调用方显式要求时才发 RPC:注入本身不能因为「查不到前台窗口」而失败。 // 解析可选 hwnd(非零整数,或 "0x..." / 十进制字符串)。 static bool GetOptionalWindowArg(const Json::Value& args, const char* key, uint32_t& out, bool& present, std::string& err) { present = false; out = 0; if (!args.isMember(key) || args[key].isNull()) return true; const Json::Value& v = args[key]; uint64_t val = 0; if (v.isNumeric()) { if (v.isDouble()) { double d = v.asDouble(); if (d < 1.0 || d > 4294967295.0 || d != (double)(uint64_t)d) { err = std::string("Invalid ") + key + ": expected a non-zero integer window handle"; return false; } val = (uint64_t)d; } else { Json::Int64 n = v.asInt64(); if (n <= 0) { err = std::string("Invalid ") + key + ": expected a non-zero window handle"; return false; } val = (uint64_t)n; } } else if (v.isString()) { const std::string s = Trim(v.asString()); char* end = nullptr; if (s.size() > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) val = strtoull(s.c_str() + 2, &end, 16); else val = strtoull(s.c_str(), &end, 10); if (end == s.c_str() || *end != '\0') { err = std::string("Invalid ") + key + ": expected a decimal integer or 0x-prefixed hex"; return false; } } else { err = std::string("Invalid ") + key + ": expected an integer or string window handle"; return false; } if (val == 0 || val > 0xFFFFFFFFull) { err = std::string("Invalid ") + key + ": window handle out of range"; return false; } out = (uint32_t)val; present = true; return true; } static bool GetOptionalBoolArg(const Json::Value& args, const char* key, bool& out, std::string& err) { out = false; if (!args.isMember(key) || args[key].isNull()) return true; if (!args[key].isBool()) { err = std::string("Invalid ") + key + ": expected a boolean"; return false; } out = args[key].asBool(); return true; } // 按 hwnd 在最新可见窗口列表里查找(只发一次窗口信息 RPC)。 static WindowLookup LookupWindow(context* ctx, uint64_t devId, const char* tool, uint32_t hwnd) { WindowLookup w; std::vector wins; w.rc = FetchWindowInfo(ctx, devId, tool, 0, wins, w.err, &w.truncated, &w.desktop); if (w.rc != 0) { w.truncated = false; return w; } for (const WindowEntry& e : wins) { if (e.hwnd == hwnd) { w.found = true; w.foreground = (e.flags & WINDOWINFO_FOREGROUND) != 0; w.entry = e; w.json = WindowEntryToJson(e); break; } } return w; } // 窗口信息 RPC 失败 → 序列化的 JSON-RPC 错误(与 get_foreground_window 同一错误口径)。 static std::string WindowRpcErrorJson(const Json::Value& id, uint64_t devId, int rc, const std::string& err) { if (rc == 1) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); if (rc == 4) return BuildError(id, -32005, "Host does not support window info (old client)"); return BuildError(id, rc == 2 ? -32001 : -32000, "Window check failed: " + err); } // expect_hwnd 在窗口列表里没命中:列表被单包上限截断时不能说"窗口不存在", // 只能说明它没出现在返回的这一批里。 static std::string WindowNotFoundErrorJson(const Json::Value& id, uint32_t hwnd, bool truncated) { const std::string win = "Window hwnd=" + std::to_string(hwnd); if (truncated) return BuildError(id, -32009, win + " is not in the returned window list, and that list was " "truncated at 96 windows (the host has more visible windows), " "so the window may still exist; verify with host_inspect " "or use the foreground window"); return BuildError(id, -32009, win + " is not in the current visible window list " "(hidden, closed, or not a visible top-level window)"); } // 注入后回报前台窗口。失败只写 foregroundError:注入已经发生,不能因此把工具判失败。 static void AppendForegroundReport(Json::Value& structuredContent, context* ctx, uint64_t devId, const char* tool) { Sleep(150); std::vector wins; std::string ferr; int rc = FetchWindowInfo(ctx, devId, tool, 0, wins, ferr); if (rc != 0) { structuredContent["foregroundError"] = ferr; return; } for (const WindowEntry& e : wins) { if (e.flags & WINDOWINFO_FOREGROUND) { structuredContent["foreground"] = WindowEntryToJson(e); return; } } structuredContent["foreground"] = Json::Value(Json::nullValue); } // tools/call:remote_keyboard(键盘注入;成功返回空对象) std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); std::string action = GetStringArg(args, "action"); if (action.empty()) return BuildError(id, -32602, "Missing required parameter: action"); std::string keyName = GetStringArg(args, "key"); std::string text = GetStringArg(args, "text"); std::vector mods; { std::string mErr; if (!ParseModifiers(args, mods, mErr)) return BuildError(id, -32602, mErr); } // 组装注入批次(按发送顺序) std::vector batch; if (action == "type") { // Android 没有文本注入:type 发的是物理键事件,字符 'v' 会变成 VK_V(本客户端 // 映射为「粘贴」),其余字符无动作。整条拒绝,别让调用方以为文本被敲进去了。 if (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK") return BuildError(id, -32005, "Android clients cannot type text; " "use remote_clipboard + key=V, or the global-action keys (ESC/HOME/APPS/PRINTSCREEN)"); if (text.empty()) return BuildError(id, -32602, "Missing required parameter: text"); if (!IsAscii(text)) return BuildError(id, -32602, "text must be ASCII; non-ASCII text requires remote_clipboard + Ctrl+V"); if (text.size() > 1024) return BuildError(id, -32602, "text too long (max 1024 bytes); use remote_clipboard + Ctrl+V for long text"); BuildTypeBatch(text, batch); } else if (action == "key_down" || action == "key_up" || action == "key_press") { if (keyName.empty()) return BuildError(id, -32602, "Missing required parameter: key"); int keyVk = MapKeyNameToVk(keyName); if (keyVk == 0) return BuildError(id, -32602, "Unknown key: " + keyName); // key=V 的粘贴映射只有新版 APK 才有;老 APK 收到 VK_V 不会动作 if (keyVk == 'V' && ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" && !ctx->SupportsScreenClipboard()) return BuildError(id, -32005, "Android client is too old for key=V paste: the APK has no paste mapping, " "upgrade the client first"); bool doDown = (action != "key_up"); bool doUp = (action != "key_down"); if (doDown) { for (int m : mods) batch.push_back(BuildKeyMsg64(m, true, false)); batch.push_back(BuildKeyMsg64(keyVk, true, false)); } if (doUp) { batch.push_back(BuildKeyMsg64(keyVk, false, false)); for (auto it = mods.rbegin(); it != mods.rend(); ++it) batch.push_back(BuildKeyMsg64(*it, false, false)); } } else { return BuildError(id, -32602, "Unknown action: " + action); } if (batch.empty()) return BuildError(id, -32602, "No key events generated"); // ---- expect_hwnd / require_foreground:注入前核对目标窗口(可选,走窗口信息 RPC)---- uint32_t expectHwnd = 0; bool hasExpect = false, requireForeground = false, reportForeground = false; { std::string oerr; if (!GetOptionalWindowArg(args, "expect_hwnd", expectHwnd, hasExpect, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "require_foreground", requireForeground, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "report_foreground", reportForeground, oerr)) return BuildError(id, -32602, oerr); if (requireForeground && !hasExpect) return BuildError(id, -32602, "require_foreground requires expect_hwnd"); if ((hasExpect || reportForeground) && !ctx->SupportsWindowInfo()) return BuildError(id, -32005, "expect_hwnd/report_foreground require window info capability, " "which this host does not support (newer Windows clients only)"); // 未显式指定 report_foreground 时,只要给了 expect_hwnd 就默认回报前台窗口。 if (!args.isMember("report_foreground") || args["report_foreground"].isNull()) reportForeground = hasExpect; } // 校验 session_id/busy 并置 busy(注入期间 close/sweep/断线不擦会话,镜像终端 busy 模式)。 context* subCtx = nullptr; int screenW = 0, screenH = 0; int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH); if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session"); if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId); // 窗口核对放在会话校验之后:session_id 无效时应当先报会话错误,不白跑一次 RPC; // busy 已置上,窗口不满足时必须先释放再返回。 WindowLookup expectWin; if (hasExpect) { expectWin = LookupWindow(ctx, devId, "remote_keyboard", expectHwnd); std::string winErr; if (expectWin.rc != 0) winErr = WindowRpcErrorJson(id, devId, expectWin.rc, expectWin.err); else if (!expectWin.found) winErr = WindowNotFoundErrorJson(id, expectHwnd, expectWin.truncated); else if (requireForeground && !expectWin.foreground) winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(expectHwnd) + " is not the foreground window; activate it first " "(host_control_window / operate_window action=activate)"); if (!winErr.empty()) { mcp.EndScreenCtrlAction(devId, sessionId); return winErr; } } bool ok = SendScreenCtrlEvents(subCtx, batch); mcp.EndScreenCtrlAction(devId, sessionId); if (!ok) return BuildError(id, -32004, "Failed to send keyboard injection"); // 审计(不可关闭) if (parent) { std::string audit = "host " + std::to_string(devId) + " remote-keyboard: session " + sessionId + " action=" + action; if (action == "type") audit += " text=" + text; else audit += " key=" + keyName; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); if (hasExpect) structuredContent["expectedWindow"] = expectWin.json; if (reportForeground) AppendForegroundReport(structuredContent, ctx, devId, "remote_keyboard"); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"ok"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P5:remote_mouse(鼠标注入,move/down/up/click/right_click/middle_click/drag/scroll)===== // 读取归一化坐标(0..1 浮点,接受 JSON number 或数字字符串),越界钳到 [0,1]。 static bool GetNormCoord(const Json::Value& args, const char* key, double& out, std::string& err) { if (!args.isMember(key)) { err = std::string("Missing required parameter: ") + key; return false; } const Json::Value& v = args[key]; if (v.isNumeric()) { out = v.asDouble(); } else if (v.isString()) { const std::string s = v.asString(); if (s.empty()) { err = std::string("Invalid ") + key + ": expected a number in 0..1"; return false; } char* end = nullptr; double d = strtod(s.c_str(), &end); if (end == s.c_str() || *end != '\0') { err = std::string("Invalid ") + key + ": expected a number in 0..1"; return false; } out = d; } else { err = std::string("Invalid ") + key + ": expected a number in 0..1"; return false; } if (out != out) { // NaN(如字符串 "nan")会绕过钳制并令 (int)(n*screen) 未定义行为 err = std::string("Invalid ") + key + ": not a finite number"; return false; } if (out < 0.0) out = 0.0; if (out > 1.0) out = 1.0; return true; } // button 字符串 → 0=左/1=中/2=右;空或 left 默认左。 static bool ParseButton(const std::string& s, int& out) { if (s.empty() || s == "left") { out = 0; return true; } if (s == "middle") { out = 1; return true; } if (s == "right") { out = 2; return true; } return false; } // button → 按下/抬起消息 + 按下 wParam(对齐 WebService::HandleMouse)。 static void ButtonMessages(int button, UINT& downMsg, UINT& upMsg, uint64_t& downWParam) { if (button == 1) { downMsg = WM_MBUTTONDOWN; upMsg = WM_MBUTTONUP; downWParam = MK_MBUTTON; } else if (button == 2) { downMsg = WM_RBUTTONDOWN; upMsg = WM_RBUTTONUP; downWParam = MK_RBUTTON; } else { downMsg = WM_LBUTTONDOWN; upMsg = WM_LBUTTONUP; downWParam = MK_LBUTTON; } } Json::Value BuildRemoteMouseInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value act(Json::objectValue); act["type"] = "string"; act["description"] = u8"动作:move / down / up / click / right_click / middle_click / drag / scroll"; Json::Value actEnum(Json::arrayValue); actEnum.append("move"); actEnum.append("down"); actEnum.append("up"); actEnum.append("click"); actEnum.append("right_click"); actEnum.append("middle_click"); actEnum.append("drag"); actEnum.append("scroll"); act["enum"] = actEnum; props["action"] = act; Json::Value xProp(Json::objectValue); xProp["type"] = "number"; xProp["description"] = u8"归一化 X 坐标(0=屏幕最左,1=最右);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=左边缘,1=右边缘"; props["x"] = xProp; Json::Value yProp(Json::objectValue); yProp["type"] = "number"; yProp["description"] = u8"归一化 Y 坐标(0=屏幕最上,1=最下);给了 window_hwnd 时改为相对「窗口与虚拟桌面的交集」(窗口完整可见时即窗口),0=上边缘,1=下边缘"; props["y"] = yProp; Json::Value x2Prop(Json::objectValue); x2Prop["type"] = "number"; x2Prop["description"] = u8"拖拽终点 X(仅 drag;坐标基准与 x 相同)"; props["x2"] = x2Prop; Json::Value y2Prop(Json::objectValue); y2Prop["type"] = "number"; y2Prop["description"] = u8"拖拽终点 Y(仅 drag;坐标基准与 y 相同)"; props["y2"] = y2Prop; Json::Value btn(Json::objectValue); btn["type"] = "string"; btn["description"] = u8"按键:left / middle / right(默认 left)"; Json::Value btnEnum(Json::arrayValue); btnEnum.append("left"); btnEnum.append("middle"); btnEnum.append("right"); btn["enum"] = btnEnum; props["button"] = btn; Json::Value clk(Json::objectValue); clk["type"] = "integer"; clk["description"] = u8"点击次数 1/2/3(仅 click,默认 1)"; props["clicks"] = clk; Json::Value del(Json::objectValue); del["type"] = "integer"; del["description"] = u8"滚动量(仅 scroll;正=向下滚,负=向上滚,与 Web 控制台一致;仅垂直滚轮,忽略 button)"; props["delta"] = del; Json::Value expect(Json::objectValue); Json::Value expectTypes(Json::arrayValue); expectTypes.append("integer"); expectTypes.append("string"); expect["type"] = expectTypes; expect["description"] = u8"可选:注入前先确认目标窗口仍在当前可见窗口列表中(整数或 0x 前缀字符串)。" u8"顺带默认回报前台窗口;仅新 Windows 客户端支持(否则 -32005)。"; props["expect_hwnd"] = expect; Json::Value requireFg(Json::objectValue); requireFg["type"] = "boolean"; requireFg["description"] = u8"可选:配合 expect_hwnd,要求该窗口已是前台,否则不发注入并返回 -32000。默认 false"; props["require_foreground"] = requireFg; Json::Value reportFg(Json::objectValue); reportFg["type"] = "boolean"; reportFg["description"] = u8"可选:注入后回报前台窗口(structuredContent.foreground)。给了 expect_hwnd 时默认 true"; props["report_foreground"] = reportFg; Json::Value winHwnd(Json::objectValue); Json::Value winHwndTypes(Json::arrayValue); winHwndTypes.append("integer"); winHwndTypes.append("string"); winHwnd["type"] = winHwndTypes; winHwnd["description"] = u8"可选:以该窗口为坐标基准(整数或 0x 前缀字符串)。给定后 x/y(及 drag 的 x2/y2)" u8"变为相对「窗口与虚拟桌面的交集」的归一化坐标(窗口完整可见时即窗口本身)," u8"服务端用该交集与虚拟桌面矩形换算成屏幕坐标,可直接用 get_screenshot mode=window 图上的比例点。" u8"默认要求该窗口是前台(可用 require_foreground=false 显式关闭;与 expect_hwnd 同时给出时" u8"须指向同一窗口);窗口不存在/最小化/完全移出虚拟桌面时报错。" u8"仅新 Windows 客户端支持(窗口信息 RPC 需带虚拟桌面矩形),否则 -32005。" u8"会话本身已只推窗口/区域(remote_open 的 window_hwnd/region)时不要再传:坐标本来就相对目标帧。"; props["window_hwnd"] = winHwnd; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); required.append("action"); required.append("x"); required.append("y"); schema["required"] = required; // drag 的终点坐标 x2/y2 在描述里标了「仅 drag」,schema 里补成条件必填。 AppendConditionalRequired(schema, "action", { "drag" }, { "x2", "y2" }); return schema; } Json::Value BuildRemoteMouseOutputSchema() { Json::Value props(Json::objectValue); Json::Value windowProp(Json::objectValue); windowProp["type"] = "object"; windowProp["description"] = u8"expect_hwnd 时注入前的目标窗口快照"; props["expectedWindow"] = windowProp; Json::Value fgProp(Json::objectValue); // report_foreground 时若系统没有可枚举的前台窗口,foreground 为 null。 Json::Value fgTypes(Json::arrayValue); fgTypes.append("object"); fgTypes.append("null"); fgProp["type"] = fgTypes; fgProp["description"] = u8"注入后的前台窗口(report_foreground 时返回;无前台窗口为 null)"; props["foreground"] = fgProp; Json::Value fgErr(Json::objectValue); fgErr["type"] = "string"; fgErr["description"] = u8"前台回报失败的原因(注入本身已成功)"; props["foregroundError"] = fgErr; Json::Value coordWin(Json::objectValue); coordWin["type"] = "object"; coordWin["description"] = u8"window_hwnd 时命中的窗口原始快照(left/top/right/bottom/width/height,未裁剪);实际归一化基准是 resolved.basis(窗口与虚拟桌面的交集)"; props["coordinateWindow"] = coordWin; Json::Value resolved(Json::objectValue); resolved["type"] = "object"; resolved["description"] = u8"window_hwnd 时换算后的发送帧归一化坐标(frame_x/frame_y,drag 另有 frame_x2/frame_y2);basis 为实际坐标基准矩形 left/top/right/bottom(窗口与虚拟桌面的交集,与 get_screenshot mode=window 的源矩形一致)"; props["resolved"] = resolved; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // tools/call:remote_mouse(鼠标注入;归一化坐标 → 发送帧像素) std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); std::string action = GetStringArg(args, "action"); if (action.empty()) return BuildError(id, -32602, "Missing required parameter: action"); // ---- 纯参数解析(不依赖会话分辨率;BeginScreenCtrlAction 之后再无提前返回)---- bool knownAction = action == "move" || action == "down" || action == "up" || action == "click" || action == "right_click" || action == "middle_click" || action == "drag" || action == "scroll"; if (!knownAction) return BuildError(id, -32602, "Unknown action: " + action); int button = 0; std::string buttonStr = GetStringArg(args, "button"); if (!ParseButton(buttonStr, button)) return BuildError(id, -32602, "Invalid button: " + buttonStr + " (expected left/middle/right)"); int clicks = 1; if (args.isMember("clicks")) { if (!GetIntArg(args, "clicks", clicks)) return BuildError(id, -32602, "clicks must be an integer 1..3"); if (clicks < 1 || clicks > 3) return BuildError(id, -32602, "clicks must be 1, 2 or 3"); } int delta = 0; if (args.isMember("delta") && !GetIntArg(args, "delta", delta)) return BuildError(id, -32602, "delta must be an integer"); int notches = 0; // scroll 实际注入的滚动档数(= clamp(delta, -10, 10)),审计用 double nx = 0, ny = 0, nx2 = 0, ny2 = 0; std::string coordErr; if (!GetNormCoord(args, "x", nx, coordErr)) return BuildError(id, -32602, coordErr); if (!GetNormCoord(args, "y", ny, coordErr)) return BuildError(id, -32602, coordErr); if (action == "drag") { if (!GetNormCoord(args, "x2", nx2, coordErr)) return BuildError(id, -32602, coordErr); if (!GetNormCoord(args, "y2", ny2, coordErr)) return BuildError(id, -32602, coordErr); } // ---- expect_hwnd / window_hwnd / require_foreground:注入前核对目标窗口(可选,走窗口信息 RPC)---- uint32_t expectHwnd = 0; bool hasExpect = false, requireForeground = false, reportForeground = false; uint32_t windowHwnd = 0; bool hasWindowFrame = false; { std::string oerr; if (!GetOptionalWindowArg(args, "expect_hwnd", expectHwnd, hasExpect, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalWindowArg(args, "window_hwnd", windowHwnd, hasWindowFrame, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "require_foreground", requireForeground, oerr)) return BuildError(id, -32602, oerr); if (!GetOptionalBoolArg(args, "report_foreground", reportForeground, oerr)) return BuildError(id, -32602, oerr); if (hasWindowFrame && hasExpect && windowHwnd != expectHwnd) return BuildError(id, -32602, "window_hwnd and expect_hwnd must refer to the same window"); // window_hwnd 的点击只有落在该窗口上才有意义(否则会点到它上面的窗口): // 调用方未显式关闭时默认要求前台。 if (hasWindowFrame && (!args.isMember("require_foreground") || args["require_foreground"].isNull())) requireForeground = true; if (requireForeground && !hasExpect && !hasWindowFrame) return BuildError(id, -32602, "require_foreground requires expect_hwnd or window_hwnd"); if ((hasExpect || hasWindowFrame || reportForeground) && !ctx->SupportsWindowInfo()) return BuildError(id, -32005, "expect_hwnd/window_hwnd/report_foreground require window info capability, " "which this host does not support (newer Windows clients only)"); if (!args.isMember("report_foreground") || args["report_foreground"].isNull()) reportForeground = hasExpect; } const bool needWindowLookup = hasExpect || hasWindowFrame; const uint32_t targetHwnd = hasWindowFrame ? windowHwnd : expectHwnd; WindowLookup expectWin; // 校验 session_id/busy 并置 busy,同时取抓屏帧尺寸(screenW/H>0 由会话就绪保证)。 context* subCtx = nullptr; int screenW = 0, screenH = 0; int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH); if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session"); if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId); // 窗口核对放在会话校验之后:session_id 无效时应当先报会话错误,不白跑一次 RPC; // busy 已置上,窗口不满足时必须先释放再返回。 // 会话已只推窗口/区域时,x/y 本来就相对目标帧;window_hwnd 的基准是整虚拟桌面, // 再换算会二次偏移。须先释放 busy 再返回。 if (hasWindowFrame && mcp.IsScreenCtrlTargeted(devId, sessionId)) { mcp.EndScreenCtrlAction(devId, sessionId); return BuildError(id, -32602, "window_hwnd is redundant for a window/region-targeted session: " "x/y are already 0..1 relative to the streamed frame"); } // 目标窗口可能在会话期间被拖动/缩放:客户端会原地重建并按新尺寸重发 TOKEN_BITMAPINFO, // 用服务端刚收到的最新帧尺寸覆盖 open 时的快照,避免坐标继续按旧比例换算。 if (mcp.IsScreenCtrlTargeted(devId, sessionId)) { int latestW = 0, latestH = 0; if (WebService().GetScreenSize(devId, latestW, latestH)) { screenW = latestW; screenH = latestH; } } // 窗口与虚拟桌面的交集:get_screenshot mode=window 的源矩形也是这个交集, // window_hwnd 比例点按同一交集换算,截图被裁掉的部分不会让点击整体偏移。 int clipL = 0, clipT = 0, clipR = 0, clipB = 0; bool clipEmpty = false; if (needWindowLookup) { expectWin = LookupWindow(ctx, devId, "remote_mouse", targetHwnd); if (expectWin.rc == 0 && expectWin.found && hasWindowFrame && expectWin.desktop.valid) { const WindowEntry& we = expectWin.entry; const WindowDesktopRect& de = expectWin.desktop; clipL = we.left > de.left ? we.left : de.left; clipT = we.top > de.top ? we.top : de.top; clipR = we.right < de.left + de.width ? we.right : de.left + de.width; clipB = we.bottom < de.top + de.height ? we.bottom : de.top + de.height; clipEmpty = (clipR <= clipL || clipB <= clipT); } std::string winErr; if (expectWin.rc != 0) winErr = WindowRpcErrorJson(id, devId, expectWin.rc, expectWin.err); else if (!expectWin.found) winErr = WindowNotFoundErrorJson(id, targetHwnd, expectWin.truncated); else if (hasWindowFrame && (expectWin.entry.flags & WINDOWINFO_MINIMIZED)) winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + " is minimized; restore it before using window-relative coordinates"); else if (hasWindowFrame && (expectWin.entry.right <= expectWin.entry.left || expectWin.entry.bottom <= expectWin.entry.top)) winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + " has an empty rect; window-relative coordinates are not usable"); else if (hasWindowFrame && !expectWin.desktop.valid) winErr = BuildError(id, -32005, "window_hwnd requires a newer Windows client: its window info response " "does not carry the virtual desktop rect"); else if (hasWindowFrame && clipEmpty) winErr = BuildError(id, -32009, "Window hwnd=" + std::to_string(targetHwnd) + " lies outside the virtual desktop; window-relative coordinates are not usable"); else if (requireForeground && !expectWin.foreground) winErr = BuildError(id, -32000, "Window hwnd=" + std::to_string(targetHwnd) + " is not the foreground window; activate it first " "(host_control_window / operate_window action=activate)"); if (!winErr.empty()) { mcp.EndScreenCtrlAction(devId, sessionId); return winErr; } } // 坐标基准:默认整屏/整虚拟桌面;给了 window_hwnd 时是窗口内归一化坐标,先换算成 // 虚拟桌面物理点,再按虚拟桌面矩形归一化到抓屏帧。基准矩形取「窗口矩形 ∩ 虚拟桌面」, // 与 get_screenshot mode=window 的源矩形完全一致,截图上的比例点可直接对应。 double fx = nx, fy = ny, fx2 = nx2, fy2 = ny2; if (hasWindowFrame) { const WindowDesktopRect& d = expectWin.desktop; auto toFrameNorm = [](double n, int lo, int hi, int dlo, int dlen) -> double { if (hi <= lo || dlen <= 0) return 0.0; double p = (double)lo + n * (double)(hi - lo); double f = (p - (double)dlo) / (double)dlen; return f < 0.0 ? 0.0 : (f > 1.0 ? 1.0 : f); }; fx = toFrameNorm(nx, clipL, clipR, d.left, d.width); fy = toFrameNorm(ny, clipT, clipB, d.top, d.height); if (action == "drag") { fx2 = toFrameNorm(nx2, clipL, clipR, d.left, d.width); fy2 = toFrameNorm(ny2, clipT, clipB, d.top, d.height); } } // 归一化坐标 → 发送帧像素(round + clamp 到 [0, screen-1];客户端 PointConversion 再换算为物理坐标) auto toPxX = [&](double n) -> int { int p = (int)(n * screenW + 0.5); return p < 0 ? 0 : (p > screenW - 1 ? screenW - 1 : p); }; auto toPxY = [&](double n) -> int { int p = (int)(n * screenH + 0.5); return p < 0 ? 0 : (p > screenH - 1 ? screenH - 1 : p); }; int px = toPxX(fx), py = toPxY(fy); int px2 = 0, py2 = 0; UINT downMsg, upMsg; uint64_t downWParam; ButtonMessages(button, downMsg, upMsg, downWParam); // 组装注入批次(按发送顺序;每个 MSG64 由客户端 ProcessCommand 分发到 SendInput) std::vector batch; if (action == "move") { batch.push_back(BuildMouseMsg64(px, py, WM_MOUSEMOVE, 0)); } else if (action == "down") { batch.push_back(BuildMouseMsg64(px, py, downMsg, downWParam)); } else if (action == "up") { batch.push_back(BuildMouseMsg64(px, py, upMsg, 0)); } else if (action == "click" || action == "right_click" || action == "middle_click") { int b = (action == "right_click") ? 2 : (action == "middle_click" ? 1 : button); UINT dMsg, uMsg; uint64_t dW; ButtonMessages(b, dMsg, uMsg, dW); for (int i = 0; i < clicks; ++i) { batch.push_back(BuildMouseMsg64(px, py, dMsg, dW)); batch.push_back(BuildMouseMsg64(px, py, uMsg, 0)); } } else if (action == "drag") { px2 = toPxX(fx2); py2 = toPxY(fy2); batch.push_back(BuildMouseMsg64(px, py, downMsg, downWParam)); batch.push_back(BuildMouseMsg64(px2, py2, WM_MOUSEMOVE, 0)); batch.push_back(BuildMouseMsg64(px2, py2, upMsg, 0)); } else if (action == "scroll") { // delta 正=向下滚(与 Web 控制台一致);WM_MOUSEWHEEL 负值=向下滚,故取反。 // 客户端对 WM_MOUSEWHEEL 会先 SetCursorPos(x,y) 再 MOUSEEVENTF_WHEEL,单条消息即可定位+滚动。 notches = delta; if (notches > 10) notches = 10; if (notches < -10) notches = -10; short wheelDelta = (short)(-notches * 120); batch.push_back(BuildMouseMsg64(px, py, WM_MOUSEWHEEL, MAKEWPARAM(0, wheelDelta))); } bool ok = SendScreenCtrlEvents(subCtx, batch); mcp.EndScreenCtrlAction(devId, sessionId); if (!ok) return BuildError(id, -32004, "Failed to send mouse injection"); // 审计(不可关闭;含归一化坐标与换算后的帧像素) if (parent) { std::string audit = "host " + std::to_string(devId) + " remote-mouse: session " + sessionId + " action=" + action; char cbuf[96]; sprintf(cbuf, " norm=(%.3f,%.3f) px=(%d,%d)", nx, ny, px, py); audit += cbuf; if (hasWindowFrame) { sprintf(cbuf, " window=%u frame=(%.4f,%.4f)", windowHwnd, fx, fy); audit += cbuf; } if (action == "drag") { sprintf(cbuf, " -> norm2=(%.3f,%.3f) px2=(%d,%d)", nx2, ny2, px2, py2); audit += cbuf; } if (action == "scroll") audit += " notches=" + std::to_string(notches); if (action == "click" || action == "right_click" || action == "middle_click") audit += " clicks=" + std::to_string(clicks); parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); if (hasExpect) structuredContent["expectedWindow"] = expectWin.json; if (hasWindowFrame) { structuredContent["coordinateWindow"] = expectWin.json; Json::Value resolved(Json::objectValue); resolved["frame_x"] = fx; resolved["frame_y"] = fy; if (action == "drag") { resolved["frame_x2"] = fx2; resolved["frame_y2"] = fy2; } // 实际坐标基准(窗口 ∩ 虚拟桌面);coordinateWindow 是未裁剪的窗口矩形, // 窗口部分移出虚拟桌面时两者不同,调用方核对换算用它。 Json::Value basis(Json::objectValue); basis["left"] = clipL; basis["top"] = clipT; basis["right"] = clipR; basis["bottom"] = clipB; resolved["basis"] = basis; structuredContent["resolved"] = resolved; } if (reportForeground) AppendForegroundReport(structuredContent, ctx, devId, "remote_mouse"); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"ok"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P5:remote_clipboard(写远程剪贴板,UTF-8 → GBK 直发,见设计 §6.4)===== Json::Value BuildRemoteClipboardInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value text(Json::objectValue); text["type"] = "string"; text["description"] = u8"要写入剪贴板的文本(UTF-8;非 GBK 字符如 emoji 会丢失)"; props["text"] = text; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); required.append("text"); schema["required"] = required; return schema; } Json::Value BuildRemoteClipboardOutputSchema() { Json::Value props(Json::objectValue); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // tools/call:remote_clipboard(写远程剪贴板;成功返回空对象) std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); // 老 APK 的屏幕子连接没有 COMMAND_SCREEN_SET_CLIPBOARD 分支,包会被静默丢弃; // 用它声明的能力位提前拒绝,避免调用方把「已下发」当成「已写入」。 if (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" && !ctx->SupportsScreenClipboard()) return BuildError(id, -32005, "Android client is too old for remote_clipboard: " "the APK has no clipboard handler, upgrade the client first"); std::string text = GetStringArg(args, "text"); if (text.empty()) return BuildError(id, -32602, "Missing required parameter: text"); if (text.size() > 262144) // 256 KB 上限(CF_TEXT 单包,防内存/传输失控) return BuildError(id, -32602, "text too long (max 262144 bytes)"); // UTF-8 → GBK:客户端 UpdateClientClipboard 以 CF_TEXT(ANSI/GBK)落剪贴板(设计 §6.4)。 // 非 GBK 字符(emoji 等)在此被替换为 '?',MVP 已知限制。 std::string ansi = ToAnsi(text, 936); // 校验 session_id/busy 并置 busy,取屏幕子连接(注入与剪贴板共用同一子连接串行化)。 context* subCtx = nullptr; int screenW = 0, screenH = 0; int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH); if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session"); if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId); // 组包 [COMMAND_SCREEN_SET_CLIPBOARD][GBK text],经屏幕子连接发送(客户端自行补 '\0')。 const int len = (int)(1 + ansi.size()); std::vector packet((size_t)len); packet[0] = COMMAND_SCREEN_SET_CLIPBOARD; memcpy(packet.data() + 1, ansi.data(), ansi.size()); bool ok = subCtx->Send2Client(packet.data(), (ULONG)len) != FALSE; mcp.EndScreenCtrlAction(devId, sessionId); if (!ok) return BuildError(id, -32004, "Failed to send clipboard text"); // 审计(不可关闭;记字节数,不落全文以免审计日志膨胀) if (parent) { std::string audit = "host " + std::to_string(devId) + " remote-clipboard: session " + sessionId + " input_bytes=" + std::to_string(text.size()); parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); result["structuredContent"] = Json::Value(Json::objectValue); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"ok"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== 锁屏:remote_lock_screen(COMMAND_SCREEN_CTRL_ALT_DEL)===== // // Ctrl+Alt+Del 这个「安全注意序列」在客户端一直没有实现(docs/Mcp_Next_Plan.md), // 服务端也就没有发送入口。Android 把它映射成系统的锁屏(GLOBAL_ACTION_LOCK_SCREEN), // 这是目前唯一有意义的语义:主控在自动化结束后把远端手机锁上,避免停在桌面。 // 报文只有 1 字节 [COMMAND_SCREEN_CTRL_ALT_DEL],和 MFC 端其它屏幕命令一样走子连接。 // 没有回执:客户端投递到主线程执行 performGlobalAction,成功与否只能看对端屏幕。 Json::Value BuildRemoteLockScreenInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); schema["required"] = required; return schema; } Json::Value BuildRemoteLockScreenOutputSchema() { Json::Value props(Json::objectValue); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // tools/call:remote_lock_screen(锁屏;成功返回空对象) std::string BuildRemoteLockScreen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); // 目前只有 Android 客户端处理 COMMAND_SCREEN_CTRL_ALT_DEL;Windows/Linux 收到也是丢弃。 if (ctx->GetAdditionalData(RES_CLIENT_TYPE) != "APK") return BuildError(id, -32005, "remote_lock_screen is only supported on Android hosts"); // 老 APK 没有该分支,包会被静默丢弃;用能力位提前拒绝,别假报成功。 if (!ctx->SupportsLockScreen()) return BuildError(id, -32005, "Android client is too old for remote_lock_screen: " "the APK has no lock-screen handler, upgrade the client first"); // 校验 session_id/busy 并置 busy,取屏幕子连接(与注入/剪贴板共用同一子连接串行化)。 context* subCtx = nullptr; int screenW = 0, screenH = 0; int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH); if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session"); if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId); BYTE packet[1] = { (BYTE)COMMAND_SCREEN_CTRL_ALT_DEL }; bool ok = subCtx->Send2Client(packet, sizeof(packet)) != FALSE; mcp.EndScreenCtrlAction(devId, sessionId); if (!ok) return BuildError(id, -32004, "Failed to send lock-screen command"); if (parent) { std::string audit = "host " + std::to_string(devId) + " remote-lock-screen: session " + sessionId; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value result(Json::objectValue); result["structuredContent"] = Json::Value(Json::objectValue); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"ok"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P10-C:remote_block_input(锁定/解除对端键鼠;零客户端改动)===== // // 报文与 MFC 端 IDM_BLOCK_INPUT 完全一致:[COMMAND_SCREEN_BLOCK_INPUT][0|1](2 字节, // 见 client/ScreenManager.cpp:1198)。客户端把 byte[1] 存进 m_bIsBlockInput 并调用 // BlockInput(),此后真人的键鼠到不了桌面——这是「把人锁在电脑外」的能力,故门控紧跟 // remote_open(McpRemoteControl=1 且 McpReadonly=0),且三条解除路径缺一不可: // 1) 工具显式 block=false; // 2) 超过 max_block_ms 由看门狗自动解除(下一次结果里以 auto_unblocked 上报); // 3) remote_close / idle 回收前强制补发 block=false(见 CloseScreenCtrlSession 等)。 // 子连接彻底断开(客户端掉线)时服务端已无从下发,只能指望客户端进程退出—— // BlockInput 在调用线程退出时自动解除,这是既有局限,工具描述里写明。 // 锁定报文(2 字节):byte[1] = 1 锁定 / 0 解除。与 MFC 端 bToken 逐字节一致。 static bool SendScreenBlockInput(context* subCtx, bool block) { if (!subCtx) return false; BYTE packet[2]; packet[0] = (BYTE)COMMAND_SCREEN_BLOCK_INPUT; packet[1] = block ? 1 : 0; return subCtx->Send2Client(packet, sizeof(packet)) != FALSE; } const int kBlockInputDefaultMaxMs = 300000; // 默认 5 分钟自动解除 const int kBlockInputMinMs = 1000; const int kBlockInputMaxMs = 3600000; // 1 小时上限:再长就该用别的方式 Json::Value BuildRemoteBlockInputInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value sid(Json::objectValue); sid["type"] = "string"; sid["description"] = u8"remote_open 返回的 session_id"; props["session_id"] = sid; Json::Value block(Json::objectValue); block["type"] = "boolean"; block["description"] = u8"true=锁定对端键鼠,false=解除。必填(没有默认值,避免误锁)"; props["block"] = block; Json::Value maxMs(Json::objectValue); maxMs["type"] = "integer"; maxMs["description"] = u8"锁定自动解除期限(毫秒),仅 block=true 时有效;默认 300000,范围 1000..3600000。" u8"到期由服务端强制解除并记入下一次结果的 auto_unblocked"; props["max_block_ms"] = maxMs; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("session_id"); required.append("block"); schema["required"] = required; return schema; } Json::Value BuildRemoteBlockInputOutputSchema() { Json::Value props(Json::objectValue); Json::Value blocked(Json::objectValue); blocked["type"] = "boolean"; blocked["description"] = u8"本次调用后的锁定状态"; props["blocked"] = blocked; Json::Value maxMs(Json::objectValue); maxMs["type"] = "integer"; maxMs["description"] = u8"本次锁定的自动解除期限(毫秒);blocked=false 时为 0(无待解除的锁定)"; props["max_block_ms"] = maxMs; Json::Value autoUnblocked(Json::objectValue); autoUnblocked["type"] = "boolean"; autoUnblocked["description"] = u8"上一次锁定是否因超过 max_block_ms 被服务端自动解除(本次调用取走该通知)"; props["auto_unblocked"] = autoUnblocked; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("blocked"); required.append("max_block_ms"); required.append("auto_unblocked"); schema["required"] = required; return schema; } // tools/call:remote_block_input(锁定/解除对端键鼠) std::string BuildRemoteBlockInput(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec); uint64_t devId = 0; context* ctx = nullptr; std::string errJson; if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; // 平台门:Windows 用 BlockInput();Android 新版用无障碍全屏 overlay 吃掉本机触摸 // (CLIENT_CAP_PRIVACY_OVERLAY);Linux/macOS 与老 APK 根本没有 COMMAND_SCREEN_BLOCK_INPUT // 分支(静默忽略),服务端不做「发了就算成功」的假动作——直接按能力限制拒绝。 if (!IsWindowsClient(ctx)) { if (ctx->GetAdditionalData(RES_CLIENT_TYPE) != "APK") return BuildError(id, -32005, "remote_block_input is only supported on Windows and Android hosts"); if (!ctx->SupportsPrivacyOverlay()) return BuildError(id, -32005, "Android client is too old for remote_block_input: " "the APK has no input-block overlay, upgrade the client first"); } std::string sessionId = GetStringArg(args, "session_id"); if (sessionId.empty()) return BuildError(id, -32602, "Missing required parameter: session_id"); // block 必须显式给:缺省按 true 会「默默锁住」对端,缺省按 false 又会让模型以为锁上了。 if (!args.isMember("block")) return BuildError(id, -32602, "Missing required parameter: block"); const Json::Value& blockArg = args["block"]; bool block = false; if (blockArg.isBool()) { block = blockArg.asBool(); } else if (blockArg.isNumeric()) { block = blockArg.asInt() != 0; } else if (blockArg.isString()) { const std::string s = blockArg.asString(); if (s == "true" || s == "1") block = true; else if (s == "false" || s == "0") block = false; else return BuildError(id, -32602, "Invalid parameter 'block': expected true or false"); } else { return BuildError(id, -32602, "Invalid parameter 'block': expected true or false"); } int maxBlockMs = kBlockInputDefaultMaxMs; if (args.isMember("max_block_ms")) { if (!GetIntArg(args, "max_block_ms", maxBlockMs)) return BuildError(id, -32602, "max_block_ms must be an integer"); if (maxBlockMs < kBlockInputMinMs || maxBlockMs > kBlockInputMaxMs) return BuildError(id, -32602, "max_block_ms out of range (1000..3600000)"); } context* subCtx = nullptr; int screenW = 0, screenH = 0; int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH); if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session"); if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId); // 先发报文再改状态:发不出去就不能声称锁上了(状态保持原样,看门狗仍按旧期限兜底)。 const bool ok = SendScreenBlockInput(subCtx, block); bool autoUnblocked = false; bool stateOk = false; if (ok) stateOk = mcp.ScreenCtrlSetBlock(devId, sessionId, block, maxBlockMs, autoUnblocked); mcp.EndScreenCtrlAction(devId, sessionId); if (!ok) return BuildError(id, -32004, "Failed to send block-input command"); if (!stateOk) return BuildError(id, -32002, "Remote control session was closed concurrently: " + sessionId); // 审计(不可关闭):锁定/解锁都是安全事件,记期限与自动解除标记。 if (parent) { std::string audit = "host " + std::to_string(devId) + " remote-block-input: session " + sessionId; audit += block ? (" block=true max_ms=" + std::to_string(maxBlockMs)) : std::string(" block=false"); if (autoUnblocked) audit += " (previous block auto-released)"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } Json::Value structured(Json::objectValue); structured["blocked"] = block; structured["max_block_ms"] = block ? maxBlockMs : 0; structured["auto_unblocked"] = autoUnblocked; Json::Value result(Json::objectValue); result["structuredContent"] = structured; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; std::string text = block ? "blocked" : "unblocked"; if (autoUnblocked) text += " (previous block had auto-released)"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P6:download_file 辅助 ===== // SHA-256 摘要转小写 hex(32 字节 → 64 字符) std::string Sha256Hex(const uint8_t* b, size_t n) { static const char hex[] = "0123456789abcdef"; std::string out; out.reserve(n * 2); for (size_t i = 0; i < n; ++i) { out += hex[b[i] >> 4]; out += hex[b[i] & 0xF]; } return out; } // 逐层创建目录(Windows 盘符路径;失败返回 false)。 bool EnsureDirA(const std::string& path) { std::string current; for (size_t i = 0; i < path.size(); ++i) { current += path[i]; if (path[i] == '\\' || path[i] == '/' || i + 1 == path.size()) { if (current.size() == 2 && current[1] == ':') continue; // 跳过盘符 "C:" if (GetFileAttributesA(current.c_str()) == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryA(current.c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) { return false; } } } } return GetFileAttributesA(path.c_str()) != INVALID_FILE_ATTRIBUTES; } // 把 UTF-8 local_dir 转为 ANSI 绝对路径(结尾 '\'),并创建目录。失败返回 false 并写 err。 bool NormalizeLocalDir(const std::string& utf8, std::string& ansiOut, std::string& err) { if (utf8.empty()) { err = "Missing required parameter: local_dir"; return false; } std::string ansi = ToAnsi(utf8, CP_ACP); if (ansi.empty()) { err = "Invalid local_dir encoding"; return false; } char full[MAX_PATH]; DWORD n = GetFullPathNameA(ansi.c_str(), MAX_PATH, full, nullptr); if (n == 0 || n >= MAX_PATH) { err = "Invalid local_dir: " + utf8; return false; } std::string dir = full; while (!dir.empty() && (dir.back() == '\\' || dir.back() == '/')) dir.pop_back(); if (dir.size() == 2 && dir[1] == ':') { err = "Invalid local_dir: " + utf8; return false; } if (!EnsureDirA(dir)) { err = "Failed to create local_dir: " + utf8; return false; } ansiOut = dir + "\\"; return true; } // 防路径穿越:fullPath 规范化后必须位于 baseDir 内(含 baseDir 本身)。 bool PathWithinDirA(const std::string& baseDir, const std::string& fullPath) { char baseFull[MAX_PATH], pathFull[MAX_PATH]; if (!GetFullPathNameA(baseDir.c_str(), MAX_PATH, baseFull, nullptr)) return false; if (!GetFullPathNameA(fullPath.c_str(), MAX_PATH, pathFull, nullptr)) return false; for (char* p = baseFull; *p; ++p) { if (*p == '/') *p = '\\'; else if (*p >= 'A' && *p <= 'Z') *p = (char)(*p - 'A' + 'a'); } for (char* p = pathFull; *p; ++p) { if (*p == '/') *p = '\\'; else if (*p >= 'A' && *p <= 'Z') *p = (char)(*p - 'A' + 'a'); } size_t bl = strlen(baseFull); while (bl > 0 && baseFull[bl - 1] == '\\') --bl; if (bl == 0) return true; // 根目录 if (strncmp(pathFull, baseFull, bl) != 0) return false; return pathFull[bl] == '\\' || pathFull[bl] == '\0'; } Json::Value BuildDownloadFileInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value rp(Json::objectValue); rp["type"] = "string"; rp["description"] = u8"远程绝对路径(文件或目录;目录递归下载)。Windows 主机用 C:\\Users\\foo\\Pictures,Linux/macOS 主机用 /home/user/data 这类绝对 POSIX 路径"; props["remote_path"] = rp; Json::Value ld(Json::objectValue); ld["type"] = "string"; ld["description"] = u8"主控本机保存目录(不存在则自动创建),如 C:\\Downloads"; props["local_dir"] = ld; Json::Value ow(Json::objectValue); ow["type"] = "boolean"; ow["description"] = u8"是否覆盖已存在的同名文件;默认 false(跳过并计入 skipped)"; props["overwrite"] = ow; Json::Value to(Json::objectValue); to["type"] = "integer"; to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时)"; props["timeout_ms"] = to; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("remote_path"); required.append("local_dir"); schema["required"] = required; return schema; } Json::Value BuildDownloadFileOutputSchema() { Json::Value props(Json::objectValue); Json::Value filesProp(Json::objectValue); filesProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; itemProps["path"] = pathProp; Json::Value sizeProp(Json::objectValue); sizeProp["type"] = "integer"; itemProps["size"] = sizeProp; Json::Value shaProp(Json::objectValue); shaProp["type"] = "string"; itemProps["sha256"] = shaProp; items["properties"] = itemProps; filesProp["items"] = items; props["files"] = filesProp; Json::Value tb(Json::objectValue); tb["type"] = "integer"; props["total_bytes"] = tb; Json::Value sk(Json::objectValue); sk["type"] = "integer"; props["skipped"] = sk; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // 词法检查路径是否含 ".." 段(定义在下方 upload_file 辅助区;download_file 先用)。 static bool HasDotDotSegment(const std::string& path); // tools/call:download_file(下载远程文件/目录到本机,V2 协议) std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { // 分派门控(独立开关 McpFileTransfer,不要求 McpReadonly=0):即便绕过 tools/list 直调也拒绝。 if (!CMcpServer::Instance().IsFileTransferEnabled()) return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 目标端类型决定 remote_path 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。 // LNX/MAC 走 common/FileManager.h 里同一套 CMD_DOWN_FILES_V2(V2 发送器)。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool posixTarget = (clientType == "LNX" || clientType == "MAC"); // 客户端须支持 V2 文件传输(否则 CMD_DOWN_FILES_V2 会被静默忽略 → 超时)。 if (!ctx->SupportsFileV2()) return BuildError(id, -32006, "Host does not support V2 file transfer"); std::string remotePathUtf8 = GetStringArg(args, "remote_path"); if (remotePathUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: remote_path"); std::string localDirUtf8 = GetStringArg(args, "local_dir"); if (localDirUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: local_dir"); bool overwrite = false; if (args.isMember("overwrite") && args["overwrite"].isBool()) overwrite = args["overwrite"].asBool(); int timeoutMs = 600000; if (args.isMember("timeout_ms")) { int v = 0; if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000) return BuildError(id, -32602, "timeout_ms must be in range 1..3600000"); timeoutMs = v; } // 本机保存目录:UTF-8 → ANSI 绝对路径(结尾 '\'),并创建。 std::string localDirAnsi; if (!NormalizeLocalDir(localDirUtf8, localDirAnsi, err)) return BuildError(id, -32602, err); // 远程路径:UTF-8 → 客户端 ANSI(Windows=936,与 list_files 一致)。 std::string remotePathAnsi = ToAnsi(remotePathUtf8, 936); if (remotePathAnsi.empty()) return BuildError(id, -32602, "Invalid remote_path encoding"); // POSIX 端 WinPathToLinux 会把 "C:\x" 去盘符改写成 "/x",静默落到别处, // 所以非 Windows 目标必须先按 POSIX 形态校验(\ 会被客户端归一化成 /,语义会漂)。 if (posixTarget) { if (remotePathAnsi[0] != '/') return BuildError(id, -32602, "remote_path must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/file.txt"); if (remotePathAnsi.find('\\') != std::string::npos) return BuildError(id, -32602, "remote_path must not contain backslashes on Linux/macOS hosts; use '/'"); if (HasDotDotSegment(remotePathAnsi)) return BuildError(id, -32602, "remote_path must not contain '..' path segments"); } CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginFileTransferPending(devId, "download_file", localDirAnsi, remotePathAnsi, overwrite)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearFileTransfer(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector files; int skipped = 0, error = 0; DWORD errorDetail = 0; bool ok = mcp.WaitFileTransferDone(devId, timeoutMs, files, skipped, error, &errorDetail); mcp.ClearFileTransfer(devId); // 擦会话 + CancelIO 子链接 if (ok) { uint64_t totalBytes = 0; for (auto& f : files) totalBytes += f.size; // 审计(不可关闭;只记路径与字节数,不落文件内容) if (parent) { std::string audit = "host " + std::to_string(devId) + " download_file: " + remotePathUtf8 + " -> " + localDirUtf8 + " (" + std::to_string(files.size()) + " files, " + std::to_string(totalBytes) + " bytes, skipped " + std::to_string(skipped) + ")"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); Json::Value filesArr(Json::arrayValue); for (auto& f : files) { Json::Value fo(Json::objectValue); fo["path"] = ToUtf8(f.path.c_str(), CP_ACP); fo["size"] = (Json::UInt64)f.size; fo["sha256"] = f.sha256; filesArr.append(fo); } structuredContent["files"] = filesArr; structuredContent["total_bytes"] = (Json::UInt64)totalBytes; structuredContent["skipped"] = skipped; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"下载完成:") + std::to_string(files.size()) + u8" 个文件(" + std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个。"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // 失败:删除已落盘的半成品文件(跳过的文件是既有的,不删)。 for (auto& f : files) { if (!f.path.empty()) DeleteFileA(f.path.c_str()); } if (parent) { std::string audit = "host " + std::to_string(devId) + " download_file FAILED (error " + std::to_string(error) + "): " + remotePathUtf8 + " -> " + localDirUtf8; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } // 新客户端在建立传输子链接之前就回报「远端路径不可用」(TOKEN_DOWNLOAD_ERROR): // 1005=不存在、1006=拒绝访问、1007=其他。直接给可分支的错误码,不再等停滞看门狗。 if (error == 1005 || error == 1006 || error == 1007) { std::string detail = " (win32=" + std::to_string((int)errorDetail) + ")"; if (error == 1005) return BuildError(id, -32009, "Remote path does not exist: " + remotePathUtf8 + detail); if (error == 1006) return BuildError(id, -32010, "Access denied to remote path: " + remotePathUtf8 + detail); return BuildError(id, -32000, "Client could not queue the download of " + remotePathUtf8 + detail); } const char* msg = (error == 1002) ? "Timeout waiting for file transfer" : (error == 1004) ? "File transfer stalled: no data received for 60s " "(the remote path is probably missing or inaccessible; " "verify it with list_files first)" : (error == 1001) ? "Path traversal detected in received path" : (error == 1003) ? "Connection lost: the transfer sub-connection closed" : (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed" : "File transfer failed"; return BuildError(id, -32001, msg); } // ===== P0-3:read_file(复用 download_file 的 V2 接收端,读后即删临时文件) ===== // 拒绝下载的体积门槛:2MB 以上的文件先落盘再读没有意义,直接让调用方改用 download_file。 static const uint64_t kReadFileSizeGate = 2 * 1024 * 1024; static const int kReadFileDefaultMaxBytes = 262144; // 单次返回的文本字节上限 static const int kReadFileDefaultLimit = 2000; // 单次返回的最大行数 static const int kReadFileTimeoutMs = 120000; // 2MB 文件在这个时间内收不完就算失败 // read_file 的两种「不该下载」结局(文件传输会话的 error 值,这里映射成 -32602)。 static const int kFileXferTooLarge = 1008; // 首包 fileSize > maxFileBytes static const int kFileXferPathIsDir = 1009; // 路径是目录 / 命中多个文件 // 服务端临时根目录:%APPDATA%\\mcp\tmp(用户可写,不依赖安装目录权限)。 static bool GetMcpTmpRootA(std::string& out) { char appdata[MAX_PATH] = { 0 }; if (FAILED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, appdata))) return false; std::string root = std::string(appdata) + "\\" BRAND_DATA_FOLDER "\\mcp\\tmp"; if (!EnsureDirA(root)) return false; out = root; return true; } // 递归删一颗小目录树(read_file 的临时目录里正常只有一个文件)。 static void DeleteTreeA(const std::string& dir) { WIN32_FIND_DATAA fd; HANDLE h = FindFirstFileA((dir + "\\*").c_str(), &fd); if (h != INVALID_HANDLE_VALUE) { do { if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; std::string p = dir + "\\" + fd.cFileName; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) RemoveDirectoryA(p.c_str()); else DeleteTreeA(p); } else { DeleteFileA(p.c_str()); } } while (FindNextFileA(h, &fd)); FindClose(h); } RemoveDirectoryA(dir.c_str()); } // RAII:成功、超时、取消、异常四条路径都靠析构清理临时文件(评审要求)。 struct McpScopedTmpDir { std::string dir; explicit McpScopedTmpDir(std::string d) : dir(std::move(d)) {} ~McpScopedTmpDir() { if (!dir.empty()) DeleteTreeA(dir); } McpScopedTmpDir(const McpScopedTmpDir&) = delete; McpScopedTmpDir& operator=(const McpScopedTmpDir&) = delete; }; static bool IsValidUtf8(const std::string& s) { if (s.empty()) return true; return MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), (int)s.size(), nullptr, 0) > 0; } // 按指定代码页把定长字节转成 UTF-8(不依赖 NUL 结尾,容忍文件里的 0x00)。 static std::string BytesToUtf8(const char* data, int len, UINT cp) { if (len <= 0) return std::string(); int wlen = MultiByteToWideChar(cp, 0, data, len, nullptr, 0); if (wlen <= 0) return std::string(); std::wstring w((size_t)wlen, L'\0'); MultiByteToWideChar(cp, 0, data, len, &w[0], wlen); int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), wlen, nullptr, 0, nullptr, nullptr); if (n <= 0) return std::string(); std::string out((size_t)n, '\0'); WideCharToMultiByte(CP_UTF8, 0, w.data(), wlen, &out[0], n, nullptr, nullptr); return out; } // UTF-16(BOM 已剥离)→ UTF-8。手工拼 wchar:实测 MultiByteToWideChar(1200) 在本机直接返回 0。 static std::string Utf16ToUtf8(const char* data, int len, bool bigEndian) { if (len < 2) return std::string(); const int n = len / 2; std::wstring w((size_t)n, L'\0'); for (int i = 0; i < n; ++i) { const unsigned char lo = (unsigned char)data[2 * i]; const unsigned char hi = (unsigned char)data[2 * i + 1]; w[(size_t)i] = bigEndian ? (wchar_t)((lo << 8) | hi) : (wchar_t)((hi << 8) | lo); } int m = WideCharToMultiByte(CP_UTF8, 0, w.data(), n, nullptr, 0, nullptr, nullptr); if (m <= 0) return std::string(); std::string out((size_t)m, '\0'); WideCharToMultiByte(CP_UTF8, 0, w.data(), n, &out[0], m, nullptr, nullptr); return out; } static std::string Latin1ToUtf8(const std::string& s) { std::string out; out.reserve(s.size()); for (size_t i = 0; i < s.size(); ++i) { unsigned char c = (unsigned char)s[i]; if (c < 0x80) out += (char)c; else { out += (char)(0xC0 | (c >> 6)); out += (char)(0x80 | (c & 0x3F)); } } return out; } // 解码:BOM → UTF-8 合法性 → GBK 回退(auto);也接受显式 utf-8 / gbk / latin1。 static bool DecodeFileText(const std::string& raw, const std::string& requested, std::string& utf8Out, std::string& encodingOut, std::string& err) { const std::string enc = ToLowerAscii(requested.empty() ? "auto" : requested); const unsigned char* b = (const unsigned char*)raw.data(); auto stripUtf8Bom = [&]() { if (raw.size() >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) return raw.substr(3); return raw; }; if (enc == "auto") { if (raw.size() >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { utf8Out = raw.substr(3); encodingOut = "utf-8"; } else if (raw.size() >= 2 && b[0] == 0xFF && b[1] == 0xFE) { utf8Out = Utf16ToUtf8(raw.data() + 2, (int)raw.size() - 2, false); // UTF-16LE encodingOut = "utf-16le"; } else if (raw.size() >= 2 && b[0] == 0xFE && b[1] == 0xFF) { utf8Out = Utf16ToUtf8(raw.data() + 2, (int)raw.size() - 2, true); // UTF-16BE encodingOut = "utf-16be"; } else if (IsValidUtf8(raw)) { utf8Out = raw; encodingOut = "utf-8"; } else { utf8Out = BytesToUtf8(raw.data(), (int)raw.size(), 936); // CP936 = GBK encodingOut = "gbk"; } return true; } if (enc == "utf-8" || enc == "utf8") { utf8Out = stripUtf8Bom(); encodingOut = "utf-8"; return true; } if (enc == "gbk" || enc == "gb18030") { utf8Out = BytesToUtf8(raw.data(), (int)raw.size(), enc == "gb18030" ? 54936 : 936); encodingOut = enc; return true; } if (enc == "latin1" || enc == "iso-8859-1") { utf8Out = Latin1ToUtf8(raw); encodingOut = "latin1"; return true; } err = "Unsupported encoding: " + requested + " (use auto / utf-8 / gbk / latin1)"; return false; } // 行尾风格:crlf / lf / cr / mixed / none。 static std::string DetectEol(const std::string& t) { size_t crlf = 0, lf = 0, cr = 0; for (size_t i = 0; i < t.size(); ++i) { if (t[i] == '\r') { if (i + 1 < t.size() && t[i + 1] == '\n') { ++crlf; ++i; } else ++cr; } else if (t[i] == '\n') { ++lf; } } if (crlf + lf + cr == 0) return "none"; if (crlf && !lf && !cr) return "crlf"; if (lf && !crlf && !cr) return "lf"; if (cr && !crlf && !lf) return "cr"; return "mixed"; } // 统一成 '\n'(行号计算与返回文本都用它,避免把 CRLF 当两个字符算)。 static std::string NormalizeEol(const std::string& t) { std::string out; out.reserve(t.size()); for (size_t i = 0; i < t.size(); ++i) { if (t[i] == '\r') { if (i + 1 < t.size() && t[i + 1] == '\n') ++i; out += '\n'; } else { out += t[i]; } } return out; } // 按 '\n' 切行;末尾换行不额外产生一个空行(与 Get-Content / readlines 一致)。 static std::vector SplitTextLines(const std::string& t) { std::vector lines; if (t.empty()) return lines; size_t start = 0; while (start < t.size()) { size_t nl = t.find('\n', start); if (nl == std::string::npos) { lines.push_back(t.substr(start)); break; } lines.push_back(t.substr(start, nl - start)); start = nl + 1; } return lines; } Json::Value BuildReadFileInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)"; props["path"] = pathProp; Json::Value off(Json::objectValue); off["type"] = "integer"; off["description"] = u8"起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0"; props["offset"] = off; Json::Value lim(Json::objectValue); lim["type"] = "integer"; lim["description"] = u8"最多返回的行数(1..200000,默认 2000)"; props["limit"] = lim; Json::Value enc(Json::objectValue); enc["type"] = "string"; enc["description"] = u8"auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1"; props["encoding"] = enc; Json::Value mb(Json::objectValue); mb["type"] = "integer"; mb["description"] = u8"本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断"; props["max_bytes"] = mb; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("path"); schema["required"] = required; return schema; } Json::Value BuildReadFileOutputSchema() { Json::Value props(Json::objectValue); auto strProp = [&](const char* k, const char* d) { Json::Value p(Json::objectValue); p["type"] = "string"; p["description"] = d; props[k] = p; }; auto intProp = [&](const char* k, const char* d) { Json::Value p(Json::objectValue); p["type"] = "integer"; p["description"] = d; props[k] = p; }; strProp("path", u8"远程路径(原样回传)"); intProp("size", u8"文件总字节数"); strProp("encoding", u8"实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1"); strProp("eol", u8"行尾风格:crlf / lf / cr / mixed / none"); intProp("lines_total", u8"文件总行数(末尾换行不计空行)"); intProp("offset", u8"本次实际起始行(负数已换算成绝对行号)"); intProp("lines_returned", u8"本次返回的行数"); Json::Value tr(Json::objectValue); tr["type"] = "boolean"; tr["description"] = u8"true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读"; props["truncated"] = tr; strProp("text", u8"文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)"); strProp("sha256", u8"整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对"); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("path"); required.append("size"); required.append("encoding"); required.append("eol"); required.append("lines_total"); required.append("offset"); required.append("lines_returned"); required.append("truncated"); required.append("text"); required.append("sha256"); schema["required"] = required; return schema; } // tools/call:read_file(复用 download_file 的 V2 接收通道把文件拉到临时目录,读完即删) std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); // 读远端只读,不要求关闭 McpReadonly;但同样受 McpFileTransfer 总开关约束。 if (!mcp.IsFileTransferEnabled()) return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool posixTarget = (clientType == "LNX" || clientType == "MAC"); if (!ctx->SupportsFileV2()) return BuildError(id, -32006, "Host does not support V2 file transfer"); std::string pathUtf8 = GetStringArg(args, "path"); if (pathUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: path"); int offset = 0; if (args.isMember("offset") && !GetIntArg(args, "offset", offset)) return BuildError(id, -32602, "offset must be an integer"); if (offset < -100000000 || offset > 100000000) return BuildError(id, -32602, "offset out of range"); int limit = kReadFileDefaultLimit; if (args.isMember("limit")) { int v = 0; if (!GetIntArg(args, "limit", v) || v < 1 || v > 200000) return BuildError(id, -32602, "limit must be in range 1..200000"); limit = v; } int maxBytes = kReadFileDefaultMaxBytes; if (args.isMember("max_bytes")) { int v = 0; if (!GetIntArg(args, "max_bytes", v) || v < 1024 || v > 2 * 1024 * 1024) return BuildError(id, -32602, "max_bytes must be in range 1024..2097152"); maxBytes = v; } const std::string encodingArg = GetStringArg(args, "encoding"); { // 先验证编码名:写错时不要白跑一次下载。 std::string probeUtf8, probeEnc; if (!DecodeFileText(std::string(), encodingArg, probeUtf8, probeEnc, err)) return BuildError(id, -32602, err); } std::string remotePathAnsi = ToAnsi(pathUtf8, 936); if (remotePathAnsi.empty()) return BuildError(id, -32602, "Invalid path encoding"); if (posixTarget) { if (remotePathAnsi[0] != '/') return BuildError(id, -32602, "path must be an absolute POSIX path for Linux/macOS hosts, e.g. /etc/app.conf"); if (remotePathAnsi.find('\\') != std::string::npos) return BuildError(id, -32602, "path must not contain backslashes on Linux/macOS hosts; use '/'"); if (HasDotDotSegment(remotePathAnsi)) return BuildError(id, -32602, "path must not contain '..' path segments"); } // 临时目录:%APPDATA%\\mcp\tmp\\\(每次调用独立,防并发互踩) std::string root; if (!GetMcpTmpRootA(root)) return BuildError(id, -32000, "Failed to create the MCP temp directory"); std::string tmpDir = root + "\\" + std::to_string(devId) + "\\" + GenerateRandomToken(); if (!EnsureDirA(tmpDir)) return BuildError(id, -32000, "Failed to create the MCP temp directory"); McpScopedTmpDir cleanup(tmpDir); std::string localDirAnsi = tmpDir + "\\"; if (!mcp.BeginFileTransferPending(devId, "read_file", localDirAnsi, remotePathAnsi, true, kReadFileSizeGate)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearFileTransfer(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector files; int skipped = 0, error = 0; DWORD errorDetail = 0; const bool ok = mcp.WaitFileTransferDone(devId, kReadFileTimeoutMs, files, skipped, error, &errorDetail); mcp.ClearFileTransfer(devId); // 擦会话 + CancelIO 子链接(临时文件由 RAII 清理) if (!ok) { if (parent) { std::string audit = "host " + std::to_string(devId) + " read_file FAILED (error " + std::to_string(error) + "): " + pathUtf8; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } // 两类「不该下载」的结局在首包就被拒收(没有落盘),给参数字典级错误码。 if (error == kFileXferTooLarge) return BuildError(id, -32602, "File is larger than 2MB: use download_file to fetch it (" + pathUtf8 + ")"); if (error == kFileXferPathIsDir) return BuildError(id, -32602, "Not a single regular file (directory or multiple matches): " + pathUtf8 + " — use list_files / search_file to pick a specific file"); if (error == 1005 || error == 1006 || error == 1007) { std::string detail = " (win32=" + std::to_string((int)errorDetail) + ")"; if (error == 1005) return BuildError(id, -32009, "Remote path does not exist: " + pathUtf8 + detail); if (error == 1006) return BuildError(id, -32010, "Access denied to remote path: " + pathUtf8 + detail); return BuildError(id, -32000, "Client could not queue the download of " + pathUtf8 + detail); } const char* msg = (error == 1002) ? "Timeout waiting for the file transfer" : (error == 1004) ? "File transfer stalled: no data received for 60s " "(the remote path is probably missing or inaccessible; " "verify it with list_files first)" : (error == 1001) ? "Path traversal detected in received path" : (error == 1003) ? "Connection lost: the transfer sub-connection closed" : (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed" : "File transfer failed"; return BuildError(id, -32001, msg); } if (files.size() != 1) return BuildError(id, -32602, "Expected exactly one file, got " + std::to_string(files.size()) + " (path must be a single regular file): " + pathUtf8); const FileTransferEntry& entry = files[0]; std::ifstream in(entry.path.c_str(), std::ios::binary); if (!in) return BuildError(id, -32000, "Failed to read the downloaded temp file"); std::string raw((std::istreambuf_iterator(in)), std::istreambuf_iterator()); in.close(); std::string utf8, encoding; if (!DecodeFileText(raw, encodingArg, utf8, encoding, err)) return BuildError(id, -32602, err); const std::string eol = DetectEol(utf8); const std::string normalized = NormalizeEol(utf8); const std::vector lines = SplitTextLines(normalized); const long long total = (long long)lines.size(); long long start = (offset >= 0) ? (long long)offset : total + (long long)offset; if (start < 0) start = 0; if (start > total) start = total; std::string text; long long count = 0; bool capHit = false; for (long long i = start; i < total && count < limit; ++i) { const std::string& ln = lines[(size_t)i]; const size_t add = ln.size() + (text.empty() ? 0 : 1); if (text.size() + add > (size_t)maxBytes) { if (text.empty()) { // 单行就超过上限:按字节硬切,回退到 UTF-8 字符边界,保证有内容返回 size_t cut = (size_t)maxBytes; while (cut > 0 && cut < ln.size() && ((unsigned char)ln[cut] & 0xC0) == 0x80) --cut; text = ln.substr(0, cut); count = 1; } capHit = true; break; } if (!text.empty()) text += '\n'; text += ln; ++count; } const bool moreLines = (start + count < total); const bool truncated = capHit || moreLines; const int linesReturned = (int)SplitTextLines(text).size(); if (parent) { // 审计:只记路径/大小/范围,不落文件内容。 std::string audit = "host " + std::to_string(devId) + " read_file: " + pathUtf8 + " (" + std::to_string(raw.size()) + " bytes, lines " + std::to_string(start) + "+" + std::to_string(count) + "/" + std::to_string(total) + ", " + encoding + ")"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } Json::Value structuredContent(Json::objectValue); structuredContent["path"] = pathUtf8; structuredContent["size"] = (Json::UInt64)raw.size(); structuredContent["encoding"] = encoding; structuredContent["eol"] = eol; structuredContent["lines_total"] = (Json::UInt64)total; structuredContent["offset"] = (Json::Int64)start; structuredContent["lines_returned"] = linesReturned; structuredContent["truncated"] = truncated; structuredContent["text"] = text; structuredContent["sha256"] = entry.sha256; Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; // 文本块 = 一行元信息 + 正文:只读 content 的客户端也能看到截断/编码,不至于默默漏读。 { std::string head = "[read_file] " + pathUtf8 + " | " + std::to_string(raw.size()) + " bytes | " + encoding + " | " + eol + " | lines " + std::to_string(start) + "-" + std::to_string(start + count) + " of " + std::to_string(total) + " | truncated=" + (truncated ? "true" : "false") + " | sha256=" + entry.sha256; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = head + "\n" + text; content.append(item); result["content"] = content; } result["isError"] = false; // 正文已在 content 里,别再让 BuildResult 追加一份 JSON 文本块(256KB 文本会被复制两遍)。 SetStructuredTextPayload(result, Json::Value(Json::objectValue)); return BuildResult(id, result); } // ===== P1-2:http_probe(在被管主机上请求私有网段 HTTP 地址) ===== // // 客户端没有 HTTP 命令,故复用持久终端的 shell 通道:Windows 用 PowerShell + HttpWebRequest, // Linux 用 curl。两者都只打印 ASCII 标记行 + base64 负载,服务端解析成结构化结果。 // 用 HttpWebRequest 而不是 Invoke-WebRequest:只有它能拿到原始响应字节(-UseBasicParsing 的 // Content 会被字符集解码),也能在读满 max_bytes 后主动断开,不把整个大响应拉回来。 // // 安全边界全部硬编码(不可配置,见 docs/Mcp_Tool_Optimization_Plan.md P1-2): // - 只允许 http/https;只接受 IP 字面量(外加 localhost)。域名校验在服务端没有意义 // (被管主机上的 DNS 结果才算数),私网/回环外的地址一律拒绝,避免把主机当代理用。 // - 不跟随重定向:3xx 原样返回,Location 留在 headers 里。 // - 响应体最多返回 max_bytes(默认与上限都是 64KB),超出置 truncated=true。 static const int kHttpProbeDefaultTimeoutMs = 10000; static const int kHttpProbeMinTimeoutMs = 1000; static const int kHttpProbeMaxTimeoutMs = 60000; static const int kHttpProbeDefaultMaxBytes = 65536; static const int kHttpProbeMaxUrlBytes = 1024; static const int kHttpProbeMaxHeaderBlob = 512; // headers 序列化后("Name: value\n")的上限 static const int kHttpProbeMaxBodyBytes = 2048; // 请求体上限(命令要挤进 cmd 的 8191 字符) static const int kHttpProbeCmdLineBudget = 7800; // cmd.exe 单行输入上限约 8191,留余量 static const int kHttpProbeWaitMarginMs = 20000; // 工具等待 = timeout_ms + 这段(shell 启动开销) static const int kHttpProbeMaxOutputBytes = 1024 * 1024; static const int kHttpProbeChunkChars = 56; // 负载按行分块:标记 + 56 < 80 列,避开 PTY 折行 static const char* const kHttpProbeStatusMarker = "__YAMA_HTTP_STATUS__"; static const char* const kHttpProbeErrMarker = "__YAMA_HTTP_ERR__"; static const char* const kHttpProbeErrStartMarker = "__YAMA_HTTP_ERRS__"; static const char* const kHttpProbeErrChunkMarker = "__YAMA_HTTP_E__"; static const char* const kHttpProbeErrEndMarker = "__YAMA_HTTP_ERRE__"; static const char* const kHttpProbeTruncMarker = "__YAMA_HTTP_TRUNC__"; static const char* const kHttpProbeElapsedMarker = "__YAMA_HTTP_ELAPSED__"; // 负载必须分块:ConPTY 是 80 列屏幕渲染流,超宽行在折行处会把边界字符重复一次, // 单行 base64 会被污染成乱码。分块后每行(标记 + 56 字符)都短于 80 列,不会被折行。 // 长度行给出解码后的字节数,服务端据此校验是否有字符丢失。 static const char* const kHttpProbeHdrLenMarker = "__YAMA_HTTP_HLEN__"; static const char* const kHttpProbeHdrStartMarker = "__YAMA_HTTP_HS__"; static const char* const kHttpProbeHdrChunkMarker = "__YAMA_HTTP_H__"; static const char* const kHttpProbeHdrEndMarker = "__YAMA_HTTP_HE__"; static const char* const kHttpProbeBodyLenMarker = "__YAMA_HTTP_BLEN__"; static const char* const kHttpProbeBodyStartMarker= "__YAMA_HTTP_BS__"; static const char* const kHttpProbeBodyChunkMarker= "__YAMA_HTTP_B__"; static const char* const kHttpProbeBodyEndMarker = "__YAMA_HTTP_BE__"; static const char* const kHttpProbeRcMarker = "__YAMA_HTTP_RC__"; static const char* const kHttpProbeSizeMarker = "__YAMA_HTTP_SIZE__"; static int HttpProbeB64Value(unsigned char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+') return 62; if (c == '/') return 63; return -1; } // 宽容的 base64 解码:跳过空白与其它非字母表字符(ConPTY 会按屏宽给长行插换行)。 static std::string HttpProbeB64Decode(const std::string& in) { std::string out; out.reserve(in.size() * 3 / 4 + 3); int val = 0, valb = -8; for (unsigned char c : in) { if (c == '=') break; int d = HttpProbeB64Value(c); if (d < 0) continue; val = (val << 6) + d; valb += 6; if (valb >= 0) { out.push_back((char)((val >> valb) & 0xFF)); valb -= 8; } } return out; } // 跳过空白(含折行)后读一个十进制整数;没有数字返回 0。 static int HttpProbeReadInt(const std::string& s, size_t& i) { while (i < s.size() && (s[i] == '\r' || s[i] == '\n' || s[i] == ' ' || s[i] == '\t')) ++i; bool neg = false; if (i < s.size() && s[i] == '-') { neg = true; ++i; } int v = 0; bool any = false; while (i < s.size() && s[i] >= '0' && s[i] <= '9') { if (v < 100000000) v = v * 10 + (s[i] - '0'); ++i; any = true; } return any ? (neg ? -v : v) : 0; } static bool HttpProbeParseIpv4(const std::string& s, unsigned out[4]) { int part = 0, digits = 0; unsigned val = 0; for (char ch : s) { if (ch >= '0' && ch <= '9') { val = val * 10 + (unsigned)(ch - '0'); if (++digits > 3) return false; } else if (ch == '.' && part < 3 && digits > 0) { out[part++] = val; val = 0; digits = 0; } else { return false; } } if (part != 3 || digits == 0) return false; out[3] = val; for (int i = 0; i < 4; ++i) if (out[i] > 255) return false; return true; } // URL 白名单校验。只收 scheme + IP 字面量(或 localhost),私网/回环之外一律拒绝。 static bool HttpProbeCheckUrl(const std::string& url, std::string& err) { if (url.empty()) { err = "Missing required parameter: url"; return false; } if ((int)url.size() > kHttpProbeMaxUrlBytes) { err = "url is too long (max " + std::to_string(kHttpProbeMaxUrlBytes) + " bytes)"; return false; } if (ContainsControlChar(url) || url.find(' ') != std::string::npos) { err = "Invalid URL: contains whitespace or control characters"; return false; } size_t p = url.find("://"); if (p == std::string::npos) { err = "Invalid URL: expected http://[:port][/path]"; return false; } std::string scheme = url.substr(0, p); if (_stricmp(scheme.c_str(), "http") != 0 && _stricmp(scheme.c_str(), "https") != 0) { err = "Invalid URL: only http and https are allowed"; return false; } size_t a = p + 3; size_t e = url.find_first_of("/?#", a); std::string authority = url.substr(a, e == std::string::npos ? std::string::npos : e - a); if (authority.empty()) { err = "Invalid URL: missing host"; return false; } if (authority.find('@') != std::string::npos) { err = "Invalid URL: userinfo (user:pass@) is not allowed"; return false; } std::string host, portStr; if (authority[0] == '[') { size_t rb = authority.find(']'); if (rb == std::string::npos) { err = "Invalid URL: malformed IPv6 literal"; return false; } host = authority.substr(1, rb - 1); if (rb + 1 < authority.size()) { if (authority[rb + 1] != ':') { err = "Invalid URL: malformed authority"; return false; } portStr = authority.substr(rb + 2); } } else { size_t c = authority.rfind(':'); if (c != std::string::npos) { host = authority.substr(0, c); portStr = authority.substr(c + 1); } else { host = authority; } } if (host.empty()) { err = "Invalid URL: missing host"; return false; } if (!portStr.empty()) { bool digits = portStr.size() <= 5; for (char ch : portStr) if (ch < '0' || ch > '9') digits = false; if (!digits) { err = "Invalid URL: port must be numeric (1-65535)"; return false; } int port = atoi(portStr.c_str()); if (port < 1 || port > 65535) { err = "Invalid URL: port must be 1-65535"; return false; } } if (_stricmp(host.c_str(), "localhost") == 0) return true; if (host == "::1" || host == "0:0:0:0:0:0:0:1") return true; unsigned o[4] = { 0, 0, 0, 0 }; if (HttpProbeParseIpv4(host, o) && (o[0] == 127 || o[0] == 10 || (o[0] == 172 && o[1] >= 16 && o[1] <= 31) || (o[0] == 192 && o[1] == 168))) return true; err = "Refused URL: only private/loopback IP literals are allowed " "(127.0.0.0/8, ::1, 10/8, 172.16/12, 192.168/16) or localhost — got host '" + host + "'"; return false; } // headers 对象 → "Name: value\n" 序列化(同时做注入校验)。 static bool HttpProbeBuildHeaderBlob(const Json::Value& headers, std::string& blob, std::string& err) { blob.clear(); if (headers.isNull()) return true; if (!headers.isObject()) { err = "headers must be an object mapping header names to string values"; return false; } for (const std::string& k : headers.getMemberNames()) { if (!headers[k].isString()) { err = "headers." + k + " must be a string"; return false; } if (k.empty() || k.size() > 64) { err = "Invalid header name: " + k; return false; } for (char ch : k) { const bool alphaNum = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); if (!alphaNum && ch != '-' && ch != '_') { err = "Invalid header name: " + k; return false; } } if (_stricmp(k.c_str(), "Content-Length") == 0) { err = "Invalid header: Content-Length is set by the tool, do not pass it"; return false; } std::string v = headers[k].asString(); if (v.size() > 256) { err = "Header value too long: " + k; return false; } for (char ch : v) { if ((unsigned char)ch < 0x20 && ch != '\t') { err = "Invalid header value for " + k + ": contains control characters"; return false; } } blob += k + ": " + v + "\n"; if ((int)blob.size() > kHttpProbeMaxHeaderBlob) { err = "headers are too large (max " + std::to_string(kHttpProbeMaxHeaderBlob) + " bytes after serialization)"; return false; } } return true; } // POSIX 单引号转义:' → '\'',其余原样。 static std::string HttpProbeShellQuote(const std::string& s) { std::string out = "'"; for (char c : s) { if (c == '\'') out += "'\\''"; else out += c; } out += "'"; return out; } // Windows 命令:powershell -Command "<内联脚本>"。脚本里只出现单引号,值一律 base64, // 因此 cmd 的双引号包裹不需要再转义;整行长度受 kHttpProbeCmdLineBudget 约束。 static std::string BuildHttpProbeWindowsCommand(const std::string& url, const std::string& method, const std::string& headerBlob, const std::string& body, int timeoutMs, int maxBytes) { using httplib::detail::base64_encode; const std::string st = kHttpProbeStatusMarker; const std::string hlen = kHttpProbeHdrLenMarker; const std::string hs = kHttpProbeHdrStartMarker; const std::string hc = kHttpProbeHdrChunkMarker; const std::string he = kHttpProbeHdrEndMarker; const std::string tr = kHttpProbeTruncMarker; const std::string el = kHttpProbeElapsedMarker; const std::string blen = kHttpProbeBodyLenMarker; const std::string bs = kHttpProbeBodyStartMarker; const std::string bc = kHttpProbeBodyChunkMarker; const std::string be = kHttpProbeBodyEndMarker; const std::string er = kHttpProbeErrMarker; const std::string ers = kHttpProbeErrStartMarker; const std::string ec = kHttpProbeErrChunkMarker; const std::string ere = kHttpProbeErrEndMarker; const std::string chunk = std::to_string(kHttpProbeChunkChars); std::string s; s += "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';"; s += "try{[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12}catch{};"; s += "$u=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64_encode(url) + "'));"; s += "$hx=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64_encode(headerBlob) + "'));"; s += "$y=[Convert]::FromBase64String('" + base64_encode(body) + "');"; s += "$sw=[Diagnostics.Stopwatch]::StartNew();"; s += "try{"; s += "$r=[Net.HttpWebRequest]::Create($u);"; s += "$r.Method='" + method + "';$r.Timeout=" + std::to_string(timeoutMs) + ";"; s += "$r.ReadWriteTimeout=" + std::to_string(timeoutMs) + ";$r.AllowAutoRedirect=$false;"; s += "foreach($l in $hx.Split([char]10)){if($l.Length -gt 0){$i=$l.IndexOf(':');if($i -gt 0){"; s += "$k=$l.Substring(0,$i);$v=$l.Substring($i+1).Trim();"; // 受限头(.NET 不接受 Headers.Add)里常用的三个走专用属性;其余受限头由框架报错。 s += "if($k -ieq 'Content-Type'){$r.ContentType=$v}else{if($k -ieq 'Host'){$r.Host=$v}else{"; s += "if($k -ieq 'Accept'){$r.Accept=$v}else{if($k -ieq 'User-Agent'){$r.UserAgent=$v}else{"; s += "if($k -ieq 'Referer'){$r.Referer=$v}else{$r.Headers.Add($k,$v)}}}}}}}};"; s += "if($y.Length -gt 0){$r.ContentLength=$y.Length;if($null -eq $r.ContentType){$r.ContentType='application/octet-stream'};"; s += "$q=$r.GetRequestStream();$q.Write($y,0,$y.Length);$q.Close()};"; s += "try{$p=$r.GetResponse()}catch [Net.WebException] {$p=$_.Exception.Response;if($null -eq $p){throw}};"; s += "$gs=$p.GetResponseStream();$ms=New-Object IO.MemoryStream;$bf=New-Object byte[] 8192;$tr=0;"; s += "while($true){$n=$gs.Read($bf,0,$bf.Length);if($n -le 0){break};"; s += "$left=" + std::to_string(maxBytes) + "-$ms.Length;"; s += "if($n -gt $left){$ms.Write($bf,0,[int]$left);$tr=1;break};$ms.Write($bf,0,$n)};"; s += "$gs.Close();"; s += "$hl='';foreach($k in $p.Headers.AllKeys){$hl=$hl+$k+': '+$p.Headers[$k]+[char]10};"; s += "$hb=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($hl));"; s += "$bb=[Convert]::ToBase64String($ms.ToArray());"; s += "[Console]::Out.WriteLine('" + st + "'+[int]$p.StatusCode);"; s += "[Console]::Out.WriteLine('" + hlen + "'+[Text.Encoding]::UTF8.GetByteCount($hl));"; s += "[Console]::Out.WriteLine('" + hs + "');"; s += "for($i=0;$i -lt $hb.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + hc + "'+$hb.Substring($i,[Math]::Min(" + chunk + ",$hb.Length-$i)))};"; s += "[Console]::Out.WriteLine('" + he + "');"; s += "[Console]::Out.WriteLine('" + tr + "'+$tr);"; s += "[Console]::Out.WriteLine('" + el + "'+[int]$sw.ElapsedMilliseconds);"; s += "[Console]::Out.WriteLine('" + blen + "'+$ms.Length);"; s += "[Console]::Out.WriteLine('" + bs + "');"; s += "for($i=0;$i -lt $bb.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + bc + "'+$bb.Substring($i,[Math]::Min(" + chunk + ",$bb.Length-$i)))};"; s += "[Console]::Out.WriteLine('" + be + "');"; s += "try{$p.Close()}catch{}"; s += "}catch{$em=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($_.Exception.Message));"; s += "[Console]::Out.WriteLine('" + er + "'+[Text.Encoding]::UTF8.GetByteCount($_.Exception.Message));"; s += "[Console]::Out.WriteLine('" + ers + "');"; s += "for($i=0;$i -lt $em.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + ec + "'+$em.Substring($i,[Math]::Min(" + chunk + ",$em.Length-$i)))};"; s += "[Console]::Out.WriteLine('" + ere + "')}"; return "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"" + s + "\""; } // POSIX 命令:curl 写临时文件,再按行分块打印标记 + base64。所有值走单引号转义。 static std::string BuildHttpProbePosixCommand(const std::string& nonce, const std::string& url, const std::string& method, const std::string& headerBlob, const std::string& body, int timeoutMs, int maxBytes) { using httplib::detail::base64_encode; const std::string base = "/tmp/.yama_hp_" + nonce; const std::string req = base + ".req"; const std::string resp = base + ".resp"; const std::string hdr = base + ".hdr"; const std::string bdy = base + ".body"; const int secs = (timeoutMs + 999) / 1000; const std::string chunk = std::to_string(kHttpProbeChunkChars); std::string cmd; if (!body.empty()) cmd += "printf %s '" + base64_encode(body) + "' | base64 -d > " + req + " ; "; // --max-filesize 只是防止被巨大响应拖死(16MB 安全阀);返回给调用方的仍是最多 max_bytes。 cmd += "curl -sS -m " + std::to_string(secs) + " --max-filesize 16777216" + " -X " + HttpProbeShellQuote(method) + " -D " + hdr + " -o " + resp; { size_t i = 0; while (i < headerBlob.size()) { size_t j = headerBlob.find('\n', i); if (j == std::string::npos) j = headerBlob.size(); std::string line = headerBlob.substr(i, j - i); if (!line.empty()) cmd += " -H " + HttpProbeShellQuote(line); i = j + 1; } } if (!body.empty()) cmd += " --data-binary @" + req; cmd += " -w '" + std::string(kHttpProbeStatusMarker) + "%{http_code}\\n' " + HttpProbeShellQuote(url); cmd += " ; __hp_rc=$?"; cmd += " ; head -c " + std::to_string(maxBytes) + " " + resp + " > " + bdy + " 2>/dev/null"; cmd += " ; echo '" + std::string(kHttpProbeHdrLenMarker) + "'$(wc -c < " + hdr + " 2>/dev/null)"; cmd += " ; echo '" + std::string(kHttpProbeHdrStartMarker) + "'"; cmd += " ; base64 -w " + chunk + " < " + hdr + " 2>/dev/null"; cmd += " ; echo '" + std::string(kHttpProbeHdrEndMarker) + "'"; cmd += " ; echo '" + std::string(kHttpProbeBodyLenMarker) + "'$(wc -c < " + bdy + " 2>/dev/null)"; cmd += " ; echo '" + std::string(kHttpProbeBodyStartMarker) + "'"; cmd += " ; base64 -w " + chunk + " < " + bdy + " 2>/dev/null"; cmd += " ; echo '" + std::string(kHttpProbeBodyEndMarker) + "'"; cmd += " ; echo '" + std::string(kHttpProbeRcMarker) + "'$__hp_rc"; cmd += " ; echo '" + std::string(kHttpProbeSizeMarker) + "'$(wc -c < " + resp + " 2>/dev/null)"; cmd += " ; rm -f " + req + " " + resp + " " + hdr + " " + bdy; return cmd; } struct HttpProbeParsed { bool hasStatus = false; int status = 0; int rc = 0; long long size = -1; bool truncated = false; int elapsedMs = 0; std::string headerBlob; std::string body; std::string error; }; static std::string HttpProbeSnippet(const std::string& out) { std::string t = Trim(out); if (t.size() > 400) t = "..." + t.substr(t.size() - 400); return t.empty() ? std::string("(empty output)") : t; } // 收集 LEN/START/CHUNK/END 四个标记之间的分块 base64 并解码。 // Windows 的每行带 chunk 前缀;POSIX 用 `base64 -w 56` 折行,行内只有 base64 字符。 // 长度行给出解码后的字节数,用于发现折行/清洗造成的字符丢失(PTY 曾把边界字符重复)。 static bool HttpProbeCollectPayload(const std::string& out, size_t from, const char* lenMarker, const char* startMarker, const char* chunkMarker, const char* endMarker, std::string& decoded) { decoded.clear(); const size_t lp = out.find(lenMarker, from); if (lp == std::string::npos) return false; size_t lj = lp + strlen(lenMarker); const int declared = HttpProbeReadInt(out, lj); const size_t sp = out.find(startMarker, lp); if (sp == std::string::npos) return false; const size_t spEnd = sp + strlen(startMarker); const size_t ep = out.find(endMarker, spEnd); if (ep == std::string::npos) return false; const size_t cm = strlen(chunkMarker); std::string b64; size_t i = spEnd; while (i < ep) { size_t e = out.find('\n', i); if (e == std::string::npos || e > ep) e = ep; std::string line = out.substr(i, e - i); i = (e < ep) ? e + 1 : ep; if (!line.empty() && line.back() == '\r') line.pop_back(); size_t b = line.find_first_not_of(' '); line = (b == std::string::npos) ? std::string() : line.substr(b); if (line.empty()) continue; if (line.compare(0, cm, chunkMarker) == 0) b64 += line.substr(cm); else b64 += line; // POSIX 的裸 base64 行 } decoded = HttpProbeB64Decode(b64); return declared >= 0 && (long long)decoded.size() == (long long)declared; } // Windows:tail = 最后一个 STATUS 标记之后(回显里也可能有标记,最后一个是真实输出)。 // 若有更晚的 ERR 标记则按错误处理。 static bool ParseHttpProbeWindowsOutput(const std::string& out, HttpProbeParsed& p) { const size_t st = out.rfind(kHttpProbeStatusMarker); const size_t er = out.rfind(kHttpProbeErrMarker); if (st == std::string::npos && er == std::string::npos) return false; if (er != std::string::npos && (st == std::string::npos || er > st)) { if (!HttpProbeCollectPayload(out, er, kHttpProbeErrMarker, kHttpProbeErrStartMarker, kHttpProbeErrChunkMarker, kHttpProbeErrEndMarker, p.error)) p.error = "request failed on host (error detail was corrupted or truncated)"; else if (p.error.empty()) p.error = "request failed on host (no error detail)"; return true; } size_t i = st + strlen(kHttpProbeStatusMarker); p.status = HttpProbeReadInt(out, i); p.hasStatus = true; size_t tp = out.find(kHttpProbeTruncMarker, i); if (tp != std::string::npos) { size_t j = tp + strlen(kHttpProbeTruncMarker); p.truncated = HttpProbeReadInt(out, j) != 0; } size_t ep = out.find(kHttpProbeElapsedMarker, i); if (ep != std::string::npos) { size_t j = ep + strlen(kHttpProbeElapsedMarker); p.elapsedMs = HttpProbeReadInt(out, j); } if (!HttpProbeCollectPayload(out, i, kHttpProbeHdrLenMarker, kHttpProbeHdrStartMarker, kHttpProbeHdrChunkMarker, kHttpProbeHdrEndMarker, p.headerBlob)) { p.error = "host output was corrupted or truncated (response headers)"; return true; } if (!HttpProbeCollectPayload(out, i, kHttpProbeBodyLenMarker, kHttpProbeBodyStartMarker, kHttpProbeBodyChunkMarker, kHttpProbeBodyEndMarker, p.body)) { p.error = "host output was corrupted or truncated (response body)"; return true; } return true; } // POSIX:curl -w 打 STATUS,随后 HLEN/HS/HE、BLEN/BS/BE、RC、SIZE 各标记行。 static bool ParseHttpProbePosixOutput(const std::string& out, int maxBytes, HttpProbeParsed& p) { const size_t st = out.rfind(kHttpProbeStatusMarker); if (st == std::string::npos) return false; size_t i = st + strlen(kHttpProbeStatusMarker); p.status = HttpProbeReadInt(out, i); p.hasStatus = true; size_t rp = out.find(kHttpProbeRcMarker, i); if (rp != std::string::npos) { size_t j = rp + strlen(kHttpProbeRcMarker); p.rc = HttpProbeReadInt(out, j); } size_t zp = out.find(kHttpProbeSizeMarker, i); if (zp != std::string::npos) { size_t j = zp + strlen(kHttpProbeSizeMarker); int v = HttpProbeReadInt(out, j); if (v > 0) p.size = v; } p.truncated = (p.rc == 63) || (p.size > (long long)maxBytes); if (p.status == 0) { std::string detail; std::istringstream iss(out); std::string line; while (std::getline(iss, line)) { if (line.find("curl:") != std::string::npos) { detail = Trim(line); break; } } if (detail.empty()) detail = HttpProbeSnippet(out); p.error = "curl failed (exit " + std::to_string(p.rc) + "): " + detail; return true; } if (!HttpProbeCollectPayload(out, i, kHttpProbeHdrLenMarker, kHttpProbeHdrStartMarker, kHttpProbeHdrChunkMarker, kHttpProbeHdrEndMarker, p.headerBlob)) { p.error = "host output was corrupted or truncated (response headers)"; return true; } if (!HttpProbeCollectPayload(out, i, kHttpProbeBodyLenMarker, kHttpProbeBodyStartMarker, kHttpProbeBodyChunkMarker, kHttpProbeBodyEndMarker, p.body)) { p.error = "host output was corrupted or truncated (response body)"; return true; } return true; } static void ParseHttpProbeHeaders(const std::string& blob, Json::Value& hdrs) { hdrs = Json::Value(Json::objectValue); std::istringstream iss(blob); std::string line, lastKey; while (std::getline(iss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (line.empty()) continue; if (line[0] == ' ' || line[0] == '\t') { // 折行续接 if (!lastKey.empty()) hdrs[lastKey] = hdrs[lastKey].asString() + " " + Trim(line); continue; } if (line.compare(0, 5, "HTTP/") == 0) continue; // curl -D 的状态行 size_t c = line.find(':'); if (c == std::string::npos) continue; std::string k = Trim(line.substr(0, c)); std::string v = Trim(line.substr(c + 1)); if (k.empty()) continue; if (hdrs.isMember(k)) hdrs[k] = hdrs[k].asString() + ", " + v; else hdrs[k] = v; lastKey = k; } } Json::Value BuildHttpProbeInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value urlProp(Json::objectValue); urlProp["type"] = "string"; urlProp["description"] = u8"要请求的地址:http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径,如 http://127.0.0.1:8003/health"; props["url"] = urlProp; Json::Value mProp(Json::objectValue); mProp["type"] = "string"; mProp["enum"] = Json::Value(Json::arrayValue); for (const char* m : { "GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS" }) mProp["enum"].append(m); mProp["description"] = u8"HTTP 方法,默认 GET"; props["method"] = mProp; Json::Value hProp(Json::objectValue); hProp["type"] = "object"; Json::Value hAdd(Json::objectValue); hAdd["type"] = "string"; hProp["additionalProperties"] = hAdd; hProp["description"] = u8"请求头(对象,名→值都是字符串),如 {\"Authorization\":\"Bearer x\"};序列化后上限 512 字节,不接受 Content-Length;Windows 上少数受限头(如 Connection、Expect、Range)会被系统拒收,Accept/User-Agent/Referer 已单独支持"; props["headers"] = hProp; Json::Value bProp(Json::objectValue); bProp["type"] = "string"; bProp["description"] = u8"请求体(可选,≤2048 字节),按 UTF-8 发送;POST/PUT/PATCH 时常用"; props["body"] = bProp; Json::Value tProp(Json::objectValue); tProp["type"] = "integer"; tProp["description"] = u8"请求超时毫秒数(默认 10000,范围 1000-60000);工具等待 = 该值 + 20 秒(含 shell 启动)"; props["timeout_ms"] = tProp; Json::Value mbProp(Json::objectValue); mbProp["type"] = "integer"; mbProp["description"] = u8"响应体最多返回的字节数(默认 65536,范围 1-65536),超出置 truncated=true"; props["max_bytes"] = mbProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("url"); schema["required"] = required; return schema; } Json::Value BuildHttpProbeOutputSchema() { Json::Value props(Json::objectValue); Json::Value statusProp(Json::objectValue); statusProp["type"] = "integer"; statusProp["description"] = u8"HTTP 状态码"; props["status"] = statusProp; Json::Value okProp(Json::objectValue); okProp["type"] = "boolean"; okProp["description"] = u8"true = 2xx/3xx;3xx 未跟随重定向"; props["ok"] = okProp; Json::Value headersProp(Json::objectValue); headersProp["type"] = "object"; headersProp["description"] = u8"响应头(名→值;同名多值用逗号拼接)"; props["headers"] = headersProp; Json::Value bodyProp(Json::objectValue); bodyProp["type"] = "string"; bodyProp["description"] = u8"响应体(响应体是合法 UTF-8 时才填;否则为空,看 body_base64)"; props["body"] = bodyProp; Json::Value encProp(Json::objectValue); encProp["type"] = "string"; encProp["description"] = u8"body 的编码:utf-8 或 base64"; props["body_encoding"] = encProp; Json::Value b64Prop(Json::objectValue); b64Prop["type"] = "string"; b64Prop["description"] = u8"响应体的 base64(仅 body_encoding=base64 时提供,非 UTF-8 的二进制响应)"; props["body_base64"] = b64Prop; Json::Value bytesProp(Json::objectValue); bytesProp["type"] = "integer"; bytesProp["description"] = u8"本次返回的响应体字节数(被截断时即 max_bytes 内实际读到的)"; props["body_bytes"] = bytesProp; Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; truncProp["description"] = u8"true = 响应体超过 max_bytes,只返回了前缀"; props["truncated"] = truncProp; Json::Value elProp(Json::objectValue); elProp["type"] = "integer"; elProp["description"] = u8"请求耗时毫秒(Windows 在 PowerShell 内计时;Linux 为服务端整轮计时)"; props["elapsed_ms"] = elProp; Json::Value urlProp(Json::objectValue); urlProp["type"] = "string"; urlProp["description"] = u8"回显请求的 url"; props["url"] = urlProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); for (const char* k : { "status", "ok", "headers", "body", "body_encoding", "body_bytes", "truncated", "elapsed_ms", "url" }) required.append(k); schema["required"] = required; return schema; } // tools/call:http_probe(在被管主机上请求私有网段 HTTP 地址;复用持久终端会话) std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.IsTerminalEnabled() || mcp.IsReadonly()) return BuildError(id, -32006, "http_probe is disabled: requires McpTerminal=1 and McpReadonly=0"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "http_probe is only supported on Windows and Linux hosts"); const bool posix = (clientType == "LNX"); std::string url = Trim(GetStringArg(args, "url")); std::string method = Trim(GetStringArg(args, "method")); if (method.empty()) method = "GET"; for (char& c : method) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); static const char* const kAllowedMethods[] = { "GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS" }; bool methodOk = false; for (const char* m : kAllowedMethods) if (method == m) methodOk = true; if (!methodOk) return BuildError(id, -32602, "Invalid method: " + method + " (allowed: GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS)"); if (!HttpProbeCheckUrl(url, err)) return BuildError(id, -32602, err); std::string headerBlob; if (!HttpProbeBuildHeaderBlob(args["headers"], headerBlob, err)) return BuildError(id, -32602, err); std::string body; if (args.isMember("body") && !args["body"].isNull()) { if (!args["body"].isString()) return BuildError(id, -32602, "body must be a string"); body = args["body"].asString(); } if ((int)body.size() > kHttpProbeMaxBodyBytes) return BuildError(id, -32602, "body is too large (max " + std::to_string(kHttpProbeMaxBodyBytes) + " bytes)"); int timeoutMs = kHttpProbeDefaultTimeoutMs; int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0) { if (v < kHttpProbeMinTimeoutMs || v > kHttpProbeMaxTimeoutMs) return BuildError(id, -32602, "timeout_ms must be between " + std::to_string(kHttpProbeMinTimeoutMs) + " and " + std::to_string(kHttpProbeMaxTimeoutMs)); timeoutMs = v; } int maxBytes = kHttpProbeDefaultMaxBytes; if (GetIntArg(args, "max_bytes", v) && v > 0) { if (v > kHttpProbeDefaultMaxBytes) return BuildError(id, -32602, "max_bytes must be between 1 and " + std::to_string(kHttpProbeDefaultMaxBytes)); maxBytes = v; } mcp.SweepIdleTerminals(kTermIdleTimeoutSec); std::string sessionId; bool reused = true; int openOrReuse = mcp.OpenOrReuseTermSession(devId, sessionId, reused); if (openOrReuse != 0) return BuildError(id, -32003, "Device busy: a terminal session for this host is still starting"); if (!reused) { BYTE openCmd = COMMAND_SHELL; if (!ctx->Send2Client(&openCmd, 1)) { mcp.ClearTermPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } context* openSubCtx = nullptr; bool openPty = false; // 冷启动可能比 ToolTimeoutMs 慢(客户端要先拉起 shell/PTY),用探测超时 + 余量兜住。 const int probeWaitMs = timeoutMs + kHttpProbeWaitMarginMs; const int toolWaitMs = mcp.ToolTimeoutMs(); const int openWaitMs = probeWaitMs > toolWaitMs ? probeWaitMs : toolWaitMs; if (!mcp.WaitTerminalReady(devId, openSubCtx, openPty, openWaitMs)) return BuildError(id, -32001, "Timeout waiting for shell to start"); } auto sessionErr = [&](int code) -> std::string { std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId); if (!destroyed.empty()) return BuildError(id, -32002, destroyed); if (code == 4) return BuildError(id, -32003, "Device busy: another command is running in this host's terminal session"); if (code == 6) return BuildError(id, -32003, "Device busy: the previous terminal command's output is not fully drained; " "call terminal_exec with only session_id to collect it first"); if (code == 7) return BuildError(id, -32002, "Terminal session is idle: no command is running"); return BuildError(id, -32002, "Terminal session is not ready: " + sessionId); }; std::string nonce = GenerateRandomToken().substr(0, 8); std::string command = posix ? BuildHttpProbePosixCommand(nonce, url, method, headerBlob, body, timeoutMs, maxBytes) : BuildHttpProbeWindowsCommand(url, method, headerBlob, body, timeoutMs, maxBytes); if ((int)command.size() > kHttpProbeCmdLineBudget) return BuildError(id, -32602, "Request too large for the host shell: command would be " + std::to_string(command.size()) + " chars, limit is " + std::to_string(kHttpProbeCmdLineBudget) + " (shorten url/headers/body)"); context* subCtx = nullptr; bool isPty = false; // POSIX 端没有可靠的进程内计时(curl 拿不到),用服务端整轮耗时兜底。 const auto t0 = std::chrono::steady_clock::now(); int begin = mcp.BeginTermCommand(devId, sessionId, "http_probe " + method + " " + url, nonce, subCtx, isPty); if (begin != 0) return sessionErr(begin); if (posix && isPty) mcp.WaitTerminalBootstrap(devId, 2000); std::string cmdLine, sentLine; // 同 terminal_exec:等提示符期间 shell 可能已退出,子连接指针可能已被连接池复用。 if (mcp.IsTermSubCtxLive(devId, sessionId, subCtx)) SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine); // 审计:请求的目标(不可关闭;不带 body/headers,避免泄露凭据)。 if (parent) { std::string text = "host " + std::to_string(devId) + " http-probe: " + method + " " + url; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(text, 936).c_str()), (LPARAM)new CString(_TR("MCP命令执行"))); } const int waitMs = timeoutMs + kHttpProbeWaitMarginMs; std::vector all; bool done = false, closed = false, chunkTruncated = false; size_t dropped = 0; int exitCode = -1; int wr = mcp.WaitTermCommand(devId, sessionId, all, done, exitCode, closed, chunkTruncated, dropped, isPty, nonce, kHttpProbeMaxOutputBytes, waitMs, false); if (wr == 2) return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed"); if (wr != 0 && wr != 1) return sessionErr(wr); // 交付上限 1MB,正常一次取完;万一还没结束就继续轮询(与 terminal_exec 的超时语义一致)。 int polls = 0; while (!done && polls < 200) { std::vector more; wr = mcp.WaitTermCommand(devId, sessionId, more, done, exitCode, closed, chunkTruncated, dropped, isPty, nonce, kHttpProbeMaxOutputBytes, waitMs, true); if (wr == 2) return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed"); if (wr != 0 && wr != 1) return sessionErr(wr); all.insert(all.end(), more.begin(), more.end()); ++polls; } if (!done) return BuildError(id, -32001, "Timeout waiting for http_probe result; the request is still running in terminal session " + sessionId + " (call terminal_exec with only session_id to collect the tail)"); // 写前校验发现子连接已断(shell 退出)时会跳过下发,这里必然没有输出:报会话结束的墓碑文案, // 比让解析器报「host 输出异常」清楚。 if (closed && all.empty()) { std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId); return BuildError(id, -32002, destroyed.empty() ? "Terminal session ended before the probe could run; call terminal_open again" : destroyed); } // 本工具隐式创建的会话用完即关:留着会让后续 exec_command 被 -32003「终端会话已存在」 // 挡到空闲回收为止。命令未结束时(上面的超时分支)保持会话,便于调用方轮询。 if (!reused) mcp.CloseTermSession(devId, sessionId); std::string out = CleanTerminalOutput(all, (posix || isPty) ? CP_UTF8 : 936, isPty, cmdLine, sentLine, nonce); HttpProbeParsed p; bool parsed = posix ? ParseHttpProbePosixOutput(out, maxBytes, p) : ParseHttpProbeWindowsOutput(out, p); if (!parsed || (!p.hasStatus && p.error.empty())) return BuildError(id, -32001, "http_probe failed: unexpected output from host: " + HttpProbeSnippet(out)); if (!p.error.empty()) return BuildError(id, -32001, "http_probe failed: " + p.error); if (posix) { p.elapsedMs = (int)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); } if (p.elapsedMs <= 0) p.elapsedMs = 0; const std::string& rawBody = p.body; Json::Value hdrs(Json::objectValue); ParseHttpProbeHeaders(p.headerBlob, hdrs); const bool bodyUtf8 = IsValidUtf8(rawBody); Json::Value sc(Json::objectValue); sc["status"] = p.status; sc["ok"] = (p.status >= 200 && p.status < 400); sc["headers"] = hdrs; sc["body"] = bodyUtf8 ? rawBody : std::string(); sc["body_encoding"] = bodyUtf8 ? "utf-8" : "base64"; if (!bodyUtf8) sc["body_base64"] = httplib::detail::base64_encode(rawBody); sc["body_bytes"] = (Json::UInt64)rawBody.size(); sc["truncated"] = p.truncated; sc["elapsed_ms"] = p.elapsedMs; sc["url"] = url; Json::Value result(Json::objectValue); result["structuredContent"] = sc; std::string head = "[http_probe] " + method + " " + url + " -> " + std::to_string(p.status) + " | " + std::to_string(rawBody.size()) + " bytes" + (p.truncated ? " (truncated)" : "") + " | " + std::to_string(p.elapsedMs) + " ms"; // 响应头也写进 text:只读 content 文本的客户端看不到 structuredContent.headers, // 而 Location/Set-Cookie/Content-Type 正是判断重定向与鉴权状态要用的。整体限长 // (单个值也限长),完整响应头仍在 structuredContent.headers 里。 const size_t kMaxHeaderTextBytes = 4096; const size_t kMaxHeaderLineBytes = 1200; std::string headerText; for (const std::string& key : hdrs.getMemberNames()) { if (headerText.size() >= kMaxHeaderTextBytes) { headerText += "(truncated; full response headers are in structuredContent.headers)\n"; break; } std::string line = key + ": " + hdrs[key].asString(); if (line.size() > kMaxHeaderLineBytes) { // 按字节截断可能切在多字节 UTF-8 字符中间:回退到该字符的首字节。 size_t cut = kMaxHeaderLineBytes; while (cut > 0 && ((unsigned char)line[cut] & 0xC0) == 0x80) --cut; line = line.substr(0, cut) + "..."; } headerText += line + "\n"; } std::string text = head; if (!headerText.empty()) text += "\nheaders:\n" + headerText; if (!rawBody.empty()) text += "\nbody:\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString()); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; // 正文已在 content 里,避免再把整份 JSON 追加一遍(响应体可能 64KB)。 SetStructuredTextPayload(result, Json::Value(Json::objectValue)); return BuildResult(id, result); } // ===== P2:upload_file 辅助 ===== // ASCII 小写(GBK 双字节首字节 0x81..0xFE 不含 A-Z,安全);Windows 路径名不区分大小写。 static std::string AsciiLower(std::string s) { for (char& c : s) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); return s; } // 词法检查路径是否含 ".." 段(防上传目标逃逸到预期目录之外)。 static bool HasDotDotSegment(const std::string& path) { size_t i = 0; while (i < path.size()) { size_t j = path.find_first_of("\\/", i); if (j == std::string::npos) j = path.size(); size_t n = j - i; if (n == 2 && path[i] == '.' && path[i + 1] == '.') return true; i = j + 1; } return false; } // 递归收集本机目录下的文件与目录项(目录在前、子项随后,供 FileBatchTransferWorkerV2 发送)。 // 与 common/file_upload.cpp 的 ExpandDirectory 同构(该函数未在 file_upload.h 导出,故本地实现)。 static void CollectLocalFiles(const std::string& dir, std::vector& out) { std::string searchPath = dir + "\\*"; WIN32_FIND_DATAA fd; HANDLE hFind = FindFirstFileA(searchPath.c_str(), &fd); if (hFind == INVALID_HANDLE_VALUE) return; do { if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue; std::string fullPath = dir + "\\" + fd.cFileName; out.push_back(fullPath); // 文件与目录都加入 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) CollectLocalFiles(fullPath, out); // 递归(目录项先于其子文件) } while (FindNextFileA(hFind, &fd)); FindClose(hFind); } // upload_file 无头发送回调数据 struct UploadCallbackData { CMy2015RemoteDlg* parent; uint64_t clientID; DWORD deadline = 0; // 整体传输截止(GetTickCount 毫秒;0=不限) bool timedOut = false; bool failed = false; // 任一 Send2Client 失败或客户端离线 // P11:进度与取消(worker 的每次分块回调都会经过这里) uint64_t totalBytes = 0; // 待发送的数据字节总数(进度分母) uint64_t bytesSent = 0; // 已发出的数据字节数(进度分子) bool cancelled = false; // 调用被取消 → 中止发送(worker 以非 0 返回) }; // upload_file 无头发送回调(镜像 GUI SendFileChunkToClientV2,去掉 dlg 进度)。 static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) { UploadCallbackData* cb = (UploadCallbackData*)user; if (!cb || !cb->parent) return false; if (McpCallCancelled()) { // P11:取消 → 停止发送 cb->cancelled = true; cb->failed = true; return false; } if (cb->deadline && (int)(GetTickCount() - cb->deadline) >= 0) { // 整体超时(DWORD 回绕安全) cb->timedOut = true; cb->failed = true; return false; } context* ctx = cb->parent->FindHost(cb->clientID); if (!ctx) { cb->failed = true; return false; } BOOL sent = ctx->Send2Client(data, size); if (!sent) cb->failed = true; else if (chunk && chunk->dataLength) { cb->bytesSent += chunk->dataLength; // 进度按 1s 节流(EmitProgress 内部),大文件每片都会回调到这里。 if (cb->totalBytes > 0) McpCallProgress((double)cb->bytesSent, (double)cb->totalBytes); else McpCallProgress((double)cb->bytesSent); } return sent != FALSE; } // 列远程目录一层,返回顶层名集合(小写原始 ANSI;客户端 ANSI=936 与主控本地名同编码)。 // 复用 list_files 的 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST 链路。 static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId, const std::string& remoteDirAnsi, std::set& names, bool foldCase = true) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_files", remoteDirAnsi)) return false; context* ctx = FindMainContext(parent, devId); if (!ctx) { mcp.ClearPending(devId); return false; } BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return false; } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return false; // upload_file 的 overwrite=false 判定:远程目录尚未创建(2/3)→ 视为「无同名项」, // 不能因为新客户端开始报错就让「上传到新目录」失败;其他失败(如拒绝访问)仍按失败处理。 if (!data.empty() && data[0] == TOKEN_FILE_LIST_ERROR) { DWORD e = ReadWin32Payload(data); return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND; } // TOKEN_FILE_LIST 布局:[token:1][attr:1][name\0][sizeHigh:4][sizeLow:4][ft:8]... if (data.size() < 2) return true; // 空目录 → 无顶层名 const char* p = (const char*)data.data(); size_t len = data.size(); size_t off = 1; // 跳过 token 字节 while (off + 1 <= len) { off += 1; // attr const char* name = p + off; size_t nlen = BoundedStrlen(name, len - off); if (nlen == 0 || nlen >= len - off) break; // 空记录/越界 = 尾部零填充 off += nlen + 1; if (off + 16 > len) break; off += 16; // sizeHigh/sizeLow/ft(8) names.insert(foldCase ? AsciiLower(std::string(name, nlen)) : std::string(name, nlen)); } return true; } Json::Value BuildUploadFileInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id,取 list_hosts 返回的 id 字段"; props["id"] = idProp; Json::Value lp(Json::objectValue); lp["type"] = "string"; lp["description"] = u8"主控本机文件或目录的绝对路径(目录递归上传),如 C:\\Users\\foo\\Pictures"; props["local_path"] = lp; Json::Value rd(Json::objectValue); rd["type"] = "string"; rd["description"] = u8"远程主机的保存目录(不存在则自动创建)。Windows 主机如 C:\\uploads,Linux/macOS 主机用 /home/user/uploads 这类绝对 POSIX 路径"; props["remote_dir"] = rd; Json::Value ow(Json::objectValue); ow["type"] = "boolean"; ow["description"] = u8"是否覆盖 remote_dir 下已存在的同名顶层文件/目录;默认 false(跳过并计入 skipped)"; props["overwrite"] = ow; Json::Value to(Json::objectValue); to["type"] = "integer"; to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时)"; props["timeout_ms"] = to; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("local_path"); required.append("remote_dir"); schema["required"] = required; return schema; } Json::Value BuildUploadFileOutputSchema() { Json::Value props(Json::objectValue); Json::Value filesProp(Json::objectValue); filesProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; itemProps["path"] = pathProp; Json::Value sizeProp(Json::objectValue); sizeProp["type"] = "integer"; itemProps["size"] = sizeProp; Json::Value shaProp(Json::objectValue); shaProp["type"] = "string"; itemProps["sha256"] = shaProp; items["properties"] = itemProps; filesProp["items"] = items; props["files"] = filesProp; Json::Value tb(Json::objectValue); tb["type"] = "integer"; props["total_bytes"] = tb; Json::Value sk(Json::objectValue); sk["type"] = "integer"; props["skipped"] = sk; Json::Value ra(Json::objectValue); ra["type"] = "boolean"; props["receiver_ack"] = ra; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // tools/call:upload_file(上传主控本机文件/目录到远程主机,V2 协议,主连接发送) std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { // 分派门控(McpFileTransfer=1 且 McpReadonly=0):即便绕过 tools/list 直调也拒绝。 if (!CMcpServer::Instance().IsFileTransferEnabled()) return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1"); if (CMcpServer::Instance().IsReadonly()) return BuildError(id, -32006, "upload_file is disabled in read-only mode: requires McpReadonly=0"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 目标端类型决定 remote_dir 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。 // POSIX 接收端(common/FileTransferV2.h)按包里的 name 派生落盘路径,不需要专门指令。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); const bool posixTarget = (clientType == "LNX" || clientType == "MAC"); const bool dstAcks = ctx->SupportsC2CRecvAck(); // 目前仅 Linux 接收端会回执 if (!ctx->SupportsFileV2()) return BuildError(id, -32006, "Host does not support V2 file transfer"); std::string localPathUtf8 = GetStringArg(args, "local_path"); if (localPathUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: local_path"); std::string remoteDirUtf8 = GetStringArg(args, "remote_dir"); if (remoteDirUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: remote_dir"); bool overwrite = false; if (args.isMember("overwrite") && args["overwrite"].isBool()) overwrite = args["overwrite"].asBool(); int timeoutMs = 600000; if (args.isMember("timeout_ms")) { int v = 0; if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000) return BuildError(id, -32602, "timeout_ms must be in range 1..3600000"); timeoutMs = v; } // 主控本机路径:UTF-8 → 主控 ANSI,去尾斜杠。 std::string localPathAnsi = ToAnsi(localPathUtf8, CP_ACP); if (localPathAnsi.empty()) return BuildError(id, -32602, "Invalid local_path encoding"); while (!localPathAnsi.empty() && (localPathAnsi.back() == '\\' || localPathAnsi.back() == '/')) localPathAnsi.pop_back(); DWORD attr = GetFileAttributesA(localPathAnsi.c_str()); if (attr == INVALID_FILE_ATTRIBUTES) return BuildError(id, -32602, "local_path not found: " + localPathUtf8); // 收集本机文件 + 目录项(目录在前、子项随后),镜像 ExpandDirectories 的顺序语义。 std::vector files; files.push_back(localPathAnsi); if (attr & FILE_ATTRIBUTE_DIRECTORY) CollectLocalFiles(localPathAnsi, files); // 远程保存目录:UTF-8 → 客户端 ANSI(936),去尾部分隔符。 std::string remoteDirAnsi = ToAnsi(remoteDirUtf8, 936); if (remoteDirAnsi.empty()) return BuildError(id, -32602, "Invalid remote_dir encoding"); if (posixTarget) { // 只接受绝对 POSIX 路径(单独的 "/" 也是合法目标)。 while (remoteDirAnsi.size() > 1 && remoteDirAnsi.back() == '/') remoteDirAnsi.pop_back(); if (remoteDirAnsi[0] != '/') return BuildError(id, -32602, "remote_dir must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/uploads"); if (remoteDirAnsi.find('\\') != std::string::npos) return BuildError(id, -32602, "remote_dir must not contain backslashes on Linux/macOS hosts; use '/'"); if (HasDotDotSegment(remoteDirAnsi)) return BuildError(id, -32602, "remote_dir must not contain '..' path segments"); } else { while (!remoteDirAnsi.empty() && (remoteDirAnsi.back() == '\\' || remoteDirAnsi.back() == '/')) remoteDirAnsi.pop_back(); if (remoteDirAnsi.empty()) return BuildError(id, -32602, "Invalid remote_dir: " + remoteDirUtf8); if (HasDotDotSegment(remoteDirAnsi)) return BuildError(id, -32602, "remote_dir must not contain '..' path segments"); } // 拼接前缀:Windows 用 '\';POSIX 用 '/'(根目录不再重复补分隔符)。 // relPath 里的 '\' 由接收端归一化成 '/',两条路都能落对。 std::string targetDir = posixTarget ? (remoteDirAnsi == "/" ? "/" : remoteDirAnsi + "/") : (remoteDirAnsi + "\\"); // overwrite=false:预检 remote_dir 一层,跳过已存在的同名顶层项(单文件精确、目录整体跳过)。 int skipped = 0; std::vector sendFiles; if (!overwrite) { std::set existing; if (!ListRemoteTopLevelNames(parent, devId, remoteDirAnsi, existing)) return BuildError(id, -32001, "Failed to list remote_dir for overwrite check"); std::string rootDir = GetCommonRoot(files); for (const std::string& f : files) { DWORD a = GetFileAttributesA(f.c_str()); bool isDir = (a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY)); std::string rel = GetRelativePath(rootDir, f); size_t sep = rel.find_first_of("\\/"); std::string top = (sep == std::string::npos) ? rel : rel.substr(0, sep); if (existing.count(AsciiLower(top))) { if (!isDir) skipped++; // 目录项不计入 skipped(与 download 一致) continue; } sendFiles.push_back(f); } } else { sendFiles = files; } // 全部被跳过:直接返回成功(不发起传输)。 if (sendFiles.empty()) { Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["files"] = Json::Value(Json::arrayValue); structuredContent["total_bytes"] = (Json::UInt64)0; structuredContent["skipped"] = skipped; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"上传完成:所有文件均已存在,跳过 ") + std::to_string(skipped) + u8" 个。"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } TransferOptionsV2 opts; opts.transferID = GenerateTransferID(); // 先定下来:会话要用它匹配 POSIX 目标端回执 opts.srcClientID = 0; // 主控端 opts.dstClientID = devId; opts.enableResume = false; CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginFileUpload(devId, opts.transferID)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); std::string hash = GetPwdHash(); std::string hmac = GetHMAC(100); UploadCallbackData cbData; cbData.parent = parent; cbData.clientID = devId; cbData.deadline = GetTickCount() + (DWORD)timeoutMs; // DWORD 回绕由回调的 (int) 差值判断吸收 // 进度分母:待发送文件的数据字节总数(目录项不计)。取不到属性时保持 0 → 只报已发字节数。 for (const std::string& f : sendFiles) { WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad) && !(fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) cbData.totalBytes += (((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow); } // 空文件:worker 对 0 字节文件不发数据块,只发 COMMAND_FILE_COMPLETE_V2,而完成包没有路径字段, // POSIX 接收端无从创建文件(会「回执成功但文件不存在」)。这里替 POSIX 目标端补一个长度 0 的 // 收尾块(名字拼法与 worker 一致),接收端据此建空文件;随后 worker 的完成包只会被去重。 // Windows 目标端维持原行为不动。 std::string xferRoot = GetCommonRoot(sendFiles); if (posixTarget) { for (size_t i = 0; i < sendFiles.size(); ++i) { DWORD a = GetFileAttributesA(sendFiles[i].c_str()); if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) continue; WIN32_FILE_ATTRIBUTE_DATA fad; if (!GetFileAttributesExA(sendFiles[i].c_str(), GetFileExInfoStandard, &fad)) continue; if ((((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow) != 0) continue; std::string name = targetDir + GetRelativePath(xferRoot, sendFiles[i]); size_t packetSize = sizeof(FileChunkPacketV2) + name.size(); std::vector packet(packetSize); auto* pkt = (FileChunkPacketV2*)packet.data(); pkt->cmd = COMMAND_SEND_FILE_V2; pkt->transferID = opts.transferID; pkt->srcClientID = 0; pkt->dstClientID = devId; pkt->fileIndex = (uint32_t)i; pkt->totalFiles = (uint32_t)sendFiles.size(); pkt->fileSize = 0; pkt->offset = 0; pkt->dataLength = 0; pkt->nameLength = (uint32_t)name.size(); pkt->flags = FFV2_LAST_CHUNK; pkt->checksum = 0; memset(pkt->reserved, 0, sizeof(pkt->reserved)); if (!name.empty()) memcpy(packet.data() + sizeof(FileChunkPacketV2), name.data(), name.size()); UploadSendChunkHeadless(&cbData, pkt, packet.data(), (int)packetSize); } } // 同步驱动发送(走主连接);无外来流,无需 WaitFileTransferDone / 收包计数。 int result = FileBatchTransferWorkerV2(sendFiles, targetDir, &cbData, UploadSendChunkHeadless, nullptr, hash, hmac, opts); bool clientOnline = (FindMainContext(parent, devId) != nullptr); bool ok = (result == 0) && !cbData.failed && clientOnline; // POSIX 目标端回执:接收端写完最后一包才回(Windows 客户端从不回,dstAcks 为 false)。 // 回执可能在上面的同步发送过程中就已到达并 latch 进会话,这里的等待通常立即返回。 CMcpServer::C2CResult ack; if (ok && dstAcks) mcp.WaitC2CReceiver(devId, 5000, ack); mcp.ClearFileTransfer(devId); // 计算已发送文件(远程完整路径 = targetDir + relPath)与字节数;目录项不计入 files。 std::string outRoot = xferRoot; std::vector outFiles; uint64_t totalBytes = 0; for (const std::string& f : sendFiles) { DWORD a = GetFileAttributesA(f.c_str()); if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) continue; std::string rel = GetRelativePath(outRoot, f); FileTransferEntry e; e.path = targetDir + rel; if (posixTarget) { for (char& c : e.path) if (c == '\\') c = '/'; // relPath 是 Windows 分隔符 } WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) e.size = ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow; // §7.5:V2 无接收方→发送方 ACK,发送方自算 SHA-256 未由 worker 回传;P2 留空(延后 P3)。 e.sha256 = ""; totalBytes += e.size; outFiles.push_back(std::move(e)); } // 目标端回了回执但失败:发送端的「全部发出」不算完成,按目标端写入失败上报。 // 与 copy_files_c2c 的 -32011 同义(那两个 -32009/-32010 是发送端路径语义)。 if (ok && ack.recvAck && ack.recvStatus != (uint32_t)FEV2_OK) { const char* why = "write failed"; if (ack.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied"; else if (ack.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory"; else if (ack.recvStatus == (uint32_t)FEV2_DISK_FULL) why = "no space left on device"; return BuildError(id, -32011, std::string("Destination host failed to write the files: ") + why + " (status=" + std::to_string(ack.recvStatus) + ", errno=" + std::to_string(ack.recvErrno) + ", files=" + std::to_string(ack.recvFileCount) + ")"); } // 声明了会回执却不回:目标端可能中途掉线,发送端的「已发出」不能当成落盘成功。 // 例外:整包没有字节(全是空文件)——接收端无从回执。 if (ok && dstAcks && !ack.recvAck && totalBytes != 0) return BuildError(id, -32001, "Upload finished sending but the destination did not confirm " "the write (verify with list_files on the target host)"); if (ok) { if (parent) { std::string audit = "host " + std::to_string(devId) + " upload_file: " + localPathUtf8 + " -> " + remoteDirUtf8 + " (" + std::to_string(outFiles.size()) + " files, " + std::to_string(totalBytes) + " bytes, skipped " + std::to_string(skipped) + ")"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); Json::Value filesArr(Json::arrayValue); for (auto& f : outFiles) { Json::Value fo(Json::objectValue); fo["path"] = ToUtf8(f.path.c_str(), 936); fo["size"] = (Json::UInt64)f.size; fo["sha256"] = f.sha256; filesArr.append(fo); } structuredContent["files"] = filesArr; structuredContent["total_bytes"] = (Json::UInt64)totalBytes; structuredContent["skipped"] = skipped; // receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执); // Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。 structuredContent["receiver_ack"] = ack.recvAck; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"上传完成:") + std::to_string(outFiles.size()) + u8" 个文件(" + std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个" + (ack.recvAck ? u8";目标端已确认写入。" : u8"。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } if (parent) { std::string audit = "host " + std::to_string(devId) + " upload_file FAILED: " + localPathUtf8 + " -> " + remoteDirUtf8; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } const char* msg = cbData.timedOut ? "Timeout waiting for upload to complete" : "Upload failed (target offline or send error)"; return BuildError(id, -32001, msg); } // ========== C2C 文件传输:copy_files_c2c ========== Json::Value BuildCopyFilesC2CInputSchema() { Json::Value props(Json::objectValue); Json::Value src(Json::objectValue); src["type"] = "string"; src["description"] = u8"源主机 id(文件从这里发出),取 list_hosts 返回的 id"; props["src_id"] = src; Json::Value dst(Json::objectValue); dst["type"] = "string"; dst["description"] = u8"目标主机 id(文件落在这里),同上"; props["dst_id"] = dst; Json::Value paths(Json::objectValue); paths["type"] = "array"; Json::Value pathItems(Json::objectValue); pathItems["type"] = "string"; paths["items"] = pathItems; paths["description"] = u8"源主机上的绝对路径列表(文件或目录;目录递归发送,保留相对目录结构)"; props["paths"] = paths; Json::Value dir(Json::objectValue); dir["type"] = "string"; dir["description"] = u8"目标主机保存目录(绝对路径,不存在自动创建):Windows 目标如 D:\\Incoming,Linux/macOS 目标如 /home/user/incoming"; props["dst_dir"] = dir; Json::Value to(Json::objectValue); to["type"] = "integer"; to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时);超时不代表传输失败"; props["timeout_ms"] = to; Json::Value ow(Json::objectValue); ow["type"] = "boolean"; ow["description"] = u8"目标目录已存在同名顶层项时是否覆盖重传。默认 false:跳过并计入 skipped(不发起传输)。" u8"目标端收包是无条件覆盖写,所以默认 false 才能避免重复调用时全量重发。"; props["overwrite"] = ow; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("src_id"); required.append("dst_id"); required.append("paths"); required.append("dst_dir"); schema["required"] = required; return schema; } Json::Value BuildCopyFilesC2COutputSchema() { Json::Value props(Json::objectValue); Json::Value s1(Json::objectValue); s1["type"] = "string"; props["transfer_id"] = s1; Json::Value s2(Json::objectValue); s2["type"] = "string"; props["src_id"] = s2; Json::Value s3(Json::objectValue); s3["type"] = "string"; props["dst_id"] = s3; Json::Value s4(Json::objectValue); s4["type"] = "string"; props["dst_dir"] = s4; Json::Value s5(Json::objectValue); s5["type"] = "integer"; props["file_count"] = s5; Json::Value s6(Json::objectValue); s6["type"] = "integer"; props["total_bytes"] = s6; Json::Value s7(Json::objectValue); s7["type"] = "boolean"; props["receiver_ack"] = s7; Json::Value s8(Json::objectValue); s8["type"] = "integer"; props["skipped"] = s8; Json::Value s9(Json::objectValue); s9["type"] = "boolean"; props["skip_check_failed"] = s9; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // 取一个十进制主机 id 字符串字段(src_id / dst_id),与 ParseHostIdArg 同规则但不绑定 "id" 键。 static bool ParseIdField(const Json::Value& args, const char* key, uint64_t& out, std::string& err) { std::string s = GetStringArg(args, key); if (s.empty()) { err = std::string("Missing required parameter: ") + key; return false; } for (char c : s) { if (c < '0' || c > '9') { err = std::string("Invalid ") + key + ": expected a decimal host id string"; return false; } } out = strtoull(s.c_str(), nullptr, 10); if (out == 0) { err = std::string("Invalid ") + key + ": host id must be non-zero"; return false; } return true; } // tools/call:copy_files_c2c(源主机 → 目标主机直接传文件;服务端只做中继,不落盘) // 报文:COMMAND_C2C_SEND_FILES(服务端 → 源主机主连接)→ 源端自开子连接上行 // → 服务端 COMMAND_SEND_FILE_V2 转发分支按 dstClientID 中继到目标主机主连接 // → 源端 TOKEN_C2C_SEND_RESULT 回传结果(本线程等的就是它)。 std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.IsFileTransferEnabled()) return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1"); if (mcp.IsReadonly()) return BuildError(id, -32006, "copy_files_c2c is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); uint64_t srcId = 0, dstId = 0; std::string err; if (!ParseIdField(args, "src_id", srcId, err)) return BuildError(id, -32602, err); if (!ParseIdField(args, "dst_id", dstId, err)) return BuildError(id, -32602, err); if (srcId == dstId) return BuildError(id, -32602, "src_id and dst_id must be different hosts"); context* srcCtx = FindMainContext(parent, srcId); if (!srcCtx) return BuildError(id, -32002, "Source host not found or offline: " + std::to_string(srcId)); context* dstCtx = FindMainContext(parent, dstId); if (!dstCtx) return BuildError(id, -32002, "Destination host not found or offline: " + std::to_string(dstId)); // 发送逻辑只在 Windows 客户端实现(client/KernelManager.cpp);目标端只按 V2 收包,无新能力位要求。 CString srcType = srcCtx->GetAdditionalData(RES_CLIENT_TYPE); if (srcType == "LNX" || srcType == "MAC") return BuildError(id, -32005, "copy_files_c2c requires a Windows source host"); if (!srcCtx->SupportsFileV2()) return BuildError(id, -32006, "Source host does not support V2 file transfer"); if (!srcCtx->SupportsC2CPaths()) return BuildError(id, -32005, "Source host client is too old: upgrade it to a build that supports copy_files_c2c"); if (!dstCtx->SupportsFileV2()) return BuildError(id, -32006, "Destination host does not support V2 file transfer"); // 目标端可以是 Windows,也可以是 Linux/macOS:dst_dir 由源端原样拼进每个块的 name 字段 // (纯字符串拼接,不经 Windows 路径 API),所以 Windows 目标吃绝对 Windows 路径, // POSIX 目标吃绝对 POSIX 路径——接收端会把 '\' 归一化成 '/' 后按绝对路径落盘 // (common/FileTransferV2.h:224)。形态在下面按 dstType 分别校验。 CString dstType = dstCtx->GetAdditionalData(RES_CLIENT_TYPE); const bool posixDst = (dstType == "LNX" || dstType == "MAC"); // 目标端是否会回落盘回执(目前只有新 Linux 客户端声明)。不会回的(Windows/老客户端) // 不等回执,避免每次传输都白等几秒。 const bool dstAcks = dstCtx->SupportsC2CRecvAck(); std::string dstDirUtf8 = GetStringArg(args, "dst_dir"); if (dstDirUtf8.empty()) return BuildError(id, -32602, "Missing required parameter: dst_dir"); const Json::Value& paths = args["paths"]; if (!paths.isArray() || paths.size() == 0) return BuildError(id, -32602, "Missing or invalid parameter: paths (non-empty string array)"); int timeoutMs = 600000; if (args.isMember("timeout_ms")) { int v = 0; if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000) return BuildError(id, -32602, "timeout_ms must be in range 1..3600000"); timeoutMs = v; } // 目标目录:UTF-8 → 目标端 ANSI(936),去尾斜杠后统一补一个分隔符(作 targetDir 前缀, // 源端是 targetDir + 相对路径的裸拼接,前缀必须以分隔符结尾)。 if (dstDirUtf8.find('\0') != std::string::npos) // 报文是 NUL 分隔的,内嵌 NUL 会截断并注入后续字段 return BuildError(id, -32602, "Invalid dst_dir: embedded NUL"); std::string dstDirAnsi; if (posixDst) { // 精确转换:CP936 表示不了字符(emoji/西里尔等)直接拒绝,而不是悄悄变成 '?' // 把文件写进另一个目录。 if (!Utf8ToCpExact(dstDirUtf8, 936, dstDirAnsi) || dstDirAnsi.empty()) return BuildError(id, -32602, "Invalid dst_dir encoding (must be representable in CP936): " + dstDirUtf8); } else { dstDirAnsi = ToAnsi(dstDirUtf8, 936); if (dstDirAnsi.empty()) return BuildError(id, -32602, "Invalid dst_dir encoding"); } while (!dstDirAnsi.empty() && (dstDirAnsi.back() == '\\' || dstDirAnsi.back() == '/')) dstDirAnsi.pop_back(); if (dstDirAnsi.empty() || HasDotDotSegment(dstDirAnsi)) return BuildError(id, -32602, "Invalid dst_dir: " + dstDirUtf8); // 不带尾分隔符的形态,供 overwrite=false 的目录列举使用:客户端拼 "%s\*.*", // 带尾分隔符会拼成 "C:\\*.*" 导致 FindFirstFile 失败(与 search_file 同一处坑)。 const std::string dstDirListAnsi = dstDirAnsi; if (posixDst) { // POSIX 目标:接收端把 '\' 当分隔符归一化,接 C:\x 会落成 /C:/x 之类;只收 '/' 根路径。 if (dstDirAnsi[0] != '/' || dstDirAnsi.find('\\') != std::string::npos) return BuildError(id, -32602, "Invalid dst_dir for a Linux/macOS destination: use an " "absolute POSIX path such as /home/user/incoming"); dstDirAnsi += "/"; } else { dstDirAnsi += "\\"; } std::vector pathAnsi; for (unsigned int i = 0; i < paths.size(); ++i) { if (!paths[i].isString()) return BuildError(id, -32602, "paths must be an array of strings"); const std::string u8 = paths[i].asString(); if (u8.find('\0') != std::string::npos) return BuildError(id, -32602, "Invalid path: embedded NUL"); std::string ansi = ToAnsi(u8, 936); if (ansi.empty()) return BuildError(id, -32602, "Invalid path encoding: " + u8); if (HasDotDotSegment(ansi)) return BuildError(id, -32602, "paths must not contain '..' segments: " + u8); pathAnsi.push_back(ansi); } // ===== overwrite=false:先列目标目录一层,跳过已存在的同名顶层项 ===== // 目标端收包是无条件覆盖写,服务端不预检的话每次调用都会把整份文件重发一遍 // (实测同一份 11 MB 日志连传两次都重写,且两次返回值完全相同,调用方无从分辨)。 // 预检只在 overwrite=false 时做;目标目录尚不存在时 ListRemoteTopLevelNames 返回空集, // 正好等价于「无同名项」。预检本身失败(主机忙/超时/拒绝访问)不回错误,退回全发并 // 置 skip_check_failed=true——不能让「检查失败」把一次本该成功的传输挡掉。 const bool overwrite = (args.isMember("overwrite") && args["overwrite"].isBool()) ? args["overwrite"].asBool() : false; int skipped = 0; bool skipCheckFailed = false; std::vector sendPathAnsi; if (overwrite) { sendPathAnsi = pathAnsi; } else { std::set existing; // POSIX 目标区分大小写,Windows 目标不区分(与目标文件系统语义一致)。 if (!ListRemoteTopLevelNames(parent, dstId, dstDirListAnsi, existing, !posixDst)) { skipCheckFailed = true; sendPathAnsi = pathAnsi; } else { for (unsigned int i = 0; i < paths.size(); ++i) { const std::string u8 = paths[i].asString(); const size_t sep = u8.find_last_of("\\/"); const std::string base = (sep == std::string::npos) ? u8 : u8.substr(sep + 1); const std::string key = posixDst ? base : AsciiLower(base); if (!base.empty() && existing.count(key)) { ++skipped; continue; } sendPathAnsi.push_back(pathAnsi[i]); } } } // 全部被跳过:直接返回成功,不发起传输。 if (sendPathAnsi.empty()) { Json::Value result(Json::objectValue); Json::Value sc(Json::objectValue); sc["transfer_id"] = std::string(); sc["src_id"] = std::to_string(srcId); sc["dst_id"] = std::to_string(dstId); sc["dst_dir"] = dstDirUtf8; sc["file_count"] = (Json::UInt)0; sc["total_bytes"] = (Json::UInt64)0; sc["receiver_ack"] = false; sc["skipped"] = skipped; sc["skip_check_failed"] = false; result["structuredContent"] = sc; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"C2C 未传输:") + std::to_string(skipped) + u8" 个顶层项在目标目录中已存在(overwrite=false),全部跳过。"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } const uint64_t transferID = GenerateTransferID(); if (!mcp.BeginC2CTransfer(srcId, dstId, transferID)) return BuildError(id, -32003, "Device busy: source or destination host already has a transfer in flight"); // 组包:[C2CSendFilesPacket][dstDir\0][path1\0]...[pathN\0][\0] C2CSendFilesPacket hdr = {}; hdr.cmd = (uint8_t)COMMAND_C2C_SEND_FILES; hdr.transferID = transferID; hdr.srcClientID = srcId; hdr.dstClientID = dstId; hdr.flags = 0; strncpy_s(hdr.hash, sizeof(hdr.hash), GetPwdHash().c_str(), _TRUNCATE); strncpy_s(hdr.hmac, sizeof(hdr.hmac), GetHMAC(100).c_str(), _TRUNCATE); std::vector pkt; pkt.reserve(sizeof(hdr) + dstDirAnsi.size() + 2); pkt.insert(pkt.end(), (const BYTE*)&hdr, (const BYTE*)&hdr + sizeof(hdr)); pkt.insert(pkt.end(), dstDirAnsi.begin(), dstDirAnsi.end()); pkt.push_back(0); for (const std::string& p : sendPathAnsi) { pkt.insert(pkt.end(), p.begin(), p.end()); pkt.push_back(0); } pkt.push_back(0); if (!srcCtx->Send2Client(pkt.data(), (ULONG)pkt.size())) { mcp.ClearFileTransfer(srcId); return BuildError(id, -32004, "Failed to send command to source host"); } CMcpServer::C2CResult r; bool ok = mcp.WaitC2CDone(srcId, timeoutMs, r); // 源端说「全部发出」后再等目标端回执:只有声明 CLIENT_CAP_C2C_RECV_ACK 的端会回, // 其余(Windows 目标、老 Linux 客户端、macOS)什么都不发,直接跳过等待。 if (ok && dstAcks) mcp.WaitC2CReceiver(srcId, 5000, r); mcp.ClearFileTransfer(srcId); if (!ok) { // 1002 = 工具线程等超时(源端可能仍在发),其余是源端主动回报的失败。 if (r.error == 1002) return BuildError(id, -32001, "Timeout waiting for the source host to finish sending (transfer may still be running; verify the destination with list_files)"); if (r.status == (uint32_t)FEV2_FILE_NOT_FOUND || r.status == (uint32_t)FEV2_ACCESS_DENIED) { const bool denied = (r.win32err == 5) || (r.status == (uint32_t)FEV2_ACCESS_DENIED); std::string msg = denied ? "Source path access denied (win32=" + std::to_string(r.win32err) + ")" : "Source path not found or inaccessible (win32=" + std::to_string(r.win32err) + ")"; return BuildError(id, denied ? -32010 : -32009, msg); } std::string msg = "C2C transfer failed on the source host (status=" + std::to_string(r.status) + ", win32=" + std::to_string(r.win32err) + ", worker_rc=" + std::to_string((int)r.workerRc) + ")"; return BuildError(id, -32000, msg); } // 目标端回了回执但失败:源端的「全部发出」不算完成,按目标端写入失败上报。 if (r.recvAck && r.recvStatus != (uint32_t)FEV2_OK) { const char* why = "write failed"; if (r.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied"; else if (r.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory"; else if (r.recvStatus == (uint32_t)FEV2_DISK_FULL) why = "no space left on device"; return BuildError(id, -32011, std::string("Destination host failed to write the files: ") + why + " (status=" + std::to_string(r.recvStatus) + ", errno=" + std::to_string(r.recvErrno) + ", files=" + std::to_string(r.recvFileCount) + ")"); } // 声明了会回执却不回:目标端可能中途掉线或包被丢弃,源端的「已发出」不能当成落盘成功。 // 例外:整包没有字节(paths 全是空文件)——客户端不为空文件发任何数据块,也就无从回执。 if (dstAcks && !r.recvAck && r.totalBytes != 0) return BuildError(id, -32001, "Source finished sending but the destination did not confirm " "the write (verify with list_files on the destination host)"); // 审计(不可关闭;只记主机 id、目录与字节数,不落文件名以外的内容) if (parent) { std::string audit = "host " + std::to_string(srcId) + " -> host " + std::to_string(dstId) + " copy_files_c2c: " + dstDirUtf8 + " (" + std::to_string(r.fileCount) + " files, " + std::to_string(r.totalBytes) + " bytes)"; parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP文件传输"))); } Json::Value result(Json::objectValue); Json::Value sc(Json::objectValue); sc["transfer_id"] = std::to_string(transferID); sc["src_id"] = std::to_string(srcId); sc["dst_id"] = std::to_string(dstId); sc["dst_dir"] = dstDirUtf8; sc["file_count"] = (Json::UInt)r.fileCount; sc["total_bytes"] = (Json::UInt64)r.totalBytes; // receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执); // Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。 sc["receiver_ack"] = r.recvAck; sc["skipped"] = skipped; sc["skip_check_failed"] = skipCheckFailed; result["structuredContent"] = sc; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"C2C 发送完成:") + std::to_string(r.fileCount) + u8" 个文件(" + std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8 + (skipped ? (std::string(u8";另有 ") + std::to_string(skipped) + u8" 个已存在被跳过") : std::string()) + (skipCheckFailed ? std::string(u8";未能预检目标目录(主机忙或超时),本次按全量发送") : std::string()) + (r.recvAck ? u8"。目标端已确认写入。" : u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ========== P7:设备管理控制 ========== // kill_process:主连接 COMMAND_SYSTEM → 系统子连接 TOKEN_PSLIST(就绪)→ COMMAND_KILLPROCESS // → 补发 COMMAND_PSLIST → 第二个 TOKEN_PSLIST(确认)。payload 与 SystemDlg::OnPlistKill 一致。 std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); // macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL)分支, // 但没有对应能力位的老构建收到 COMMAND_SYSTEM 只打一行日志 → 刷新永远等不到,故按位拒绝。 if (clientType == "MAC" && !ctx->SupportsProcess()) return BuildError(id, -32005, "macOS client is too old for kill_process: " "it does not declare CLIENT_CAP_PROCESS; upgrade the client first"); if (clientType == "APK") return BuildError(id, -32005, "kill_process is only supported on Windows, Linux and macOS hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "kill_process is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsManageEnabled()) return BuildError(id, -32006, "kill_process is disabled: management operations are off (set McpManage=1 to enable)"); const Json::Value& pids = args["pids"]; if (!pids.isArray() || pids.size() == 0) return BuildError(id, -32602, "Missing or invalid parameter: pids (non-empty integer array)"); std::vector pidList; std::vector followUp; followUp.push_back((BYTE)COMMAND_KILLPROCESS); for (unsigned int i = 0; i < pids.size(); ++i) { uint64_t pid = 0; if (!ReadUInt64(pids[i], pid) || pid == 0) return BuildError(id, -32602, "pids must be non-zero integers"); pidList.push_back(pid); DWORD d = (DWORD)pid; followUp.push_back((BYTE)(d & 0xFF)); followUp.push_back((BYTE)((d >> 8) & 0xFF)); followUp.push_back((BYTE)((d >> 16) & 0xFF)); followUp.push_back((BYTE)((d >> 24) & 0xFF)); } // ===== dry_run(§5.5):只取一次进程列表校验目标,不下发任何终止命令 ===== // MFC 侧不弹窗:挂起用「非写工具」的名称登记,TOKEN_PSLIST 首包会让 OnSystemReady // 返回 false,由 TakeMainResponse + CancelIO 收走子链接。目标全部不存在时按 -32009 报错, // 与 kill_network_connection 的 dry_run 口径一致。 bool dryRun = false; if (args.isMember("dry_run")) { if (!args["dry_run"].isBool()) return BuildError(id, -32602, "dry_run must be a boolean"); dryRun = args["dry_run"].asBool(); } if (dryRun) { if (!mcp.BeginPending(devId, "kill_process/dryrun")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SYSTEM; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for process list (dry run)"); UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value procs = ParseProcessList(data, cp); Json::Value targets(Json::arrayValue); Json::Value missing(Json::arrayValue); for (size_t i = 0; i < pidList.size(); ++i) { bool found = false; for (unsigned int j = 0; j < procs.size(); ++j) { if (procs[j]["pid"].asUInt64() == pidList[i]) { Json::Value t(Json::objectValue); t["pid"] = (Json::UInt64)pidList[i]; t["name"] = procs[j]["name"]; t["path"] = procs[j]["path"]; targets.append(t); found = true; break; } } if (!found) missing.append((Json::UInt64)pidList[i]); } AuditManageAction(parent, devId, "kill_process", "pids=" + std::to_string(pidList.size()) + " result=dry_run"); if (targets.empty()) return BuildError(id, -32009, "No matching process for any requested pid (dry run)"); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; structuredContent["dry_run"] = true; structuredContent["targets"] = targets; structuredContent["missing"] = missing; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"试运行:将终止 ") + std::to_string(targets.size()) + u8" 个进程(未发送任何命令)" + (missing.empty() ? std::string() : std::string(u8";") + std::to_string(missing.size()) + u8" 个 PID 已不存在,已列入 missing") ; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } if (!mcp.BeginPendingFollowUp(devId, "kill_process", followUp)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SYSTEM; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for process list after kill"); UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; Json::Value procs = ParseProcessList(data, cp); Json::Value remaining(Json::arrayValue); std::string detail = "pids="; for (size_t i = 0; i < pidList.size(); ++i) { if (i) detail += ","; detail += std::to_string(pidList[i]); bool stillAlive = false; for (unsigned int j = 0; j < procs.size(); ++j) { if (procs[j]["pid"].asUInt64() == pidList[i]) { stillAlive = true; break; } } if (stillAlive) remaining.append((Json::UInt64)pidList[i]); } AuditManageAction(parent, devId, "kill_process", detail); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["remaining"] = remaining; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = remaining.empty() ? std::string(u8"目标进程已全部终止。") : std::string(u8"仍有 ") + std::to_string((int)remaining.size()) + std::string(u8" 个进程存活(见 remaining)。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // operate_window:主连接 COMMAND_WSLIST → 窗口子连接 TOKEN_WSLIST(就绪)→ CMD_WINDOW_CLOSE // (close 客户端自动回 TOKEN_WSLIST)或 CMD_WINDOW_TEST(test 补发 COMMAND_WSLIST 索取)。 // 20 字节零填充 buffer 复刻 SystemDlg::OnWlistClose/OnWlistHide/Recover/Max/Min(hwnd 为 DWORD)。 std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "operate_window is only supported on Windows hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "operate_window is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsManageEnabled()) return BuildError(id, -32006, "operate_window is disabled: management operations are off (set McpManage=1 to enable)"); uint64_t hwnd = 0; if (!ReadUInt64Arg(args, "hwnd", hwnd) || hwnd == 0) return BuildError(id, -32602, "Missing or invalid parameter: hwnd (non-zero window handle)"); std::string action = Trim(GetStringArg(args, "action")); BYTE lpMsgBuf[20] = { 0 }; DWORD h = (DWORD)hwnd; if (action == "close") { lpMsgBuf[0] = CMD_WINDOW_CLOSE; memcpy(lpMsgBuf + 1, &h, sizeof(DWORD)); } else { DWORD dHow; if (action == "hide") dHow = SW_HIDE; // 0 else if (action == "show") dHow = SW_NORMAL; // 1 else if (action == "restore") dHow = SW_NORMAL; // 1 else if (action == "maximize") dHow = SW_MAXIMIZE; // 3 else if (action == "minimize") dHow = SW_MINIMIZE; // 6 else if (action == "activate") { // 后台窗口仅 ShowWindow 不会升到前台:依赖新客户端的激活实现。 if (!ctx->SupportsWindowInfo()) return BuildError(id, -32005, "activate requires a newer client (window info capability); use show instead"); dHow = CMD_WINDOW_ACTIVATE_FLAG; } else return BuildError(id, -32602, "Invalid action: " + action + " (expect close|show|hide|minimize|maximize|restore|activate)"); lpMsgBuf[0] = CMD_WINDOW_TEST; memcpy(lpMsgBuf + 1, &h, sizeof(DWORD)); memcpy(lpMsgBuf + 1 + sizeof(DWORD), &dHow, sizeof(DWORD)); } std::vector followUp(lpMsgBuf, lpMsgBuf + sizeof(lpMsgBuf)); // ===== dry_run(§5.5):只取一次窗口列表校验 hwnd,不下发任何窗口命令 ===== // 与 kill_process 的 dry_run 同构:用非写工具名登记,首包直接由 TakeMainResponse 收走。 bool dryRun = false; if (args.isMember("dry_run")) { if (!args["dry_run"].isBool()) return BuildError(id, -32602, "dry_run must be a boolean"); dryRun = args["dry_run"].asBool(); } if (dryRun) { if (!mcp.BeginPending(devId, "operate_window/dryrun")) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_WSLIST; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for window list (dry run)"); // 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP),与 list_windows 同口径。 Json::Value windows = ParseWindowList(data, GetClientEncoding(ctx)); Json::Value target(Json::objectValue); for (unsigned int i = 0; i < windows.size(); ++i) { if (windows[i]["hwnd"].asUInt64() == hwnd) { target = windows[i]; break; } } AuditManageAction(parent, devId, "operate_window", "action=" + action + " hwnd=" + std::to_string(hwnd) + " result=dry_run"); if (target.isNull() || !target.isObject()) return BuildError(id, -32009, "Window hwnd=" + std::to_string(hwnd) + " is not in the current visible window list (dry run)"); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; structuredContent["dry_run"] = true; structuredContent["action"] = action; structuredContent["window"] = target; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"试运行:将对窗口「") + target["title"].asString() + u8"」执行 " + action + u8"(未发送任何命令)"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } if (!mcp.BeginPendingFollowUp(devId, "operate_window", followUp)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_WSLIST; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for window operation"); AuditManageAction(parent, devId, "operate_window", "action=" + action + " hwnd=" + std::to_string(hwnd)); if (action == "activate") { Sleep(300); // 给客户端激活线程 / 系统前台切换留出时间 std::vector wins; std::string ferr; bool winTruncated = false; int rc = FetchWindowInfo(ctx, devId, "operate_window", 0, wins, ferr, &winTruncated); if (rc == 1) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); const WindowEntry* target = nullptr; if (rc == 0) { for (const WindowEntry& e : wins) { if (e.hwnd == (uint32_t)hwnd) { target = &e; break; } } } bool isForeground = target && (target->flags & WINDOWINFO_FOREGROUND) != 0; // 列表被 96 条上限截断时,没找到目标只是"没看到",不能断言窗口不存在。 const bool listIncomplete = (rc == 0 && winTruncated); std::string state = (rc != 0) ? "unknown" : (!target ? (listIncomplete ? "unknown" : "missing") : (isForeground ? "foreground" : "background")); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = isForeground; structuredContent["action"] = action; structuredContent["state"] = state; structuredContent["window"] = target ? WindowEntryToJson(*target) : Json::Value(Json::nullValue); if (rc != 0) structuredContent["verifyError"] = ferr; else if (listIncomplete) structuredContent["truncated"] = true; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; if (isForeground) item["text"] = u8"窗口已激活并成为前台窗口(复核 GetForegroundWindow 一致)"; else if (rc != 0) item["text"] = u8"窗口操作已下发,但前台复核失败:" + ferr; else if (!target && listIncomplete) item["text"] = u8"窗口操作已下发,但复核用的窗口列表被单次上限截断(可见窗口超过 96 个)," u8"目标不在返回的这一批里,无法确认是否已到前台"; else if (!target) item["text"] = u8"窗口操作已下发,但复核时目标窗口不在可见窗口列表中(可能已关闭或已隐藏)"; else item["text"] = u8"窗口操作已下发,但目标窗口仍未成为前台窗口(可能被系统前台锁定策略拦下,可重试)"; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"已下发窗口操作:") + action; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // control_service:主连接 COMMAND_SERVICES → 服务子连接 TOKEN_SERVERLIST(就绪)→ // COMMAND_SERVICECONFIG → 客户端写后自动 SendServicesList(确认,无需补发)。 std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "control_service is only supported on Windows hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "control_service is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsManageEnabled()) return BuildError(id, -32006, "control_service is disabled: management operations are off (set McpManage=1 to enable)"); std::string serviceName = Trim(GetStringArg(args, "service_name")); if (serviceName.empty()) return BuildError(id, -32602, "Missing required parameter: service_name"); std::string action = Trim(GetStringArg(args, "action")); BYTE bCmd; if (action == "start") bCmd = 1; else if (action == "stop") bCmd = 2; else if (action == "set_auto") bCmd = 3; else if (action == "set_manual") bCmd = 4; else return BuildError(id, -32602, "Invalid action: " + action + " (expect start|stop|set_auto|set_manual)"); // 服务名来自 Windows A 接口(GBK/936),下发前转 ANSI。payload 与 MachineDlg 一致: // [COMMAND_SERVICECONFIG:1][bCmd:1][serviceName\0]。 std::string ansiName = ToAnsi(serviceName, 936); std::vector followUp; followUp.reserve(2 + ansiName.size() + 1); followUp.push_back((BYTE)COMMAND_SERVICECONFIG); followUp.push_back(bCmd); followUp.insert(followUp.end(), ansiName.begin(), ansiName.end()); followUp.push_back(0); if (!mcp.BeginPendingFollowUp(devId, "control_service", followUp)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SERVICES; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector data; if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for service operation"); AuditManageAction(parent, devId, "control_service", "service=" + serviceName + " action=" + action); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"已下发服务操作:") + action + std::string(u8" ") + serviceName; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // power_action:主连接 TOKEN_MACHINE_MANAGE,发完即走(无响应);主机立即离线。 // power_action 的结果验证(§5.4):电源命令是「发完即走、无响应」,服务端唯一能观察到的 // 事实是主连接在不在线。wait=true 时先等主机下线(连接消失),再等它重新上线(重启后客户端 // 用同一个 id 重连)。两个阶段各自以 wait_ms 为上界;等不到不是错误,交给调用方判断。 static bool WaitHostOnlineState(CMy2015RemoteDlg* parent, uint64_t devId, bool wantOnline, int timeoutMs) { const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); while (true) { if ((FindMainContext(parent, devId) != nullptr) == wantOnline) return true; if (McpCallCancelled()) return false; // 取消后按「没等到」返回,由调用方如实回报 const auto now = std::chrono::steady_clock::now(); if (now >= deadline) return false; std::this_thread::sleep_for(std::chrono::milliseconds(200)); } } std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "power_action is only supported on Windows hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "power_action is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsManageEnabled()) return BuildError(id, -32006, "power_action is disabled: management operations are off (set McpManage=1 to enable)"); std::string action = Trim(GetStringArg(args, "action")); BYTE type; if (action == "logout") type = MACHINE_LOGOUT; else if (action == "shutdown") type = MACHINE_SHUTDOWN; else if (action == "reboot") type = MACHINE_REBOOT; else return BuildError(id, -32602, "Invalid action: " + action + " (expect logout|shutdown|reboot)"); // 结果验证参数(§5.4):wait 默认 false(保持「发完即走」的旧行为与旧耗时)。 // wait_ms 即使 wait=false 也校验,避免调用方以为传了有效值、实际被静默忽略。 bool wait = false; if (args.isMember("wait")) { if (!args["wait"].isBool()) return BuildError(id, -32602, "wait must be a boolean"); wait = args["wait"].asBool(); } int waitMs = 60000; if (args.isMember("wait_ms")) { int v = 0; if (!GetIntArg(args, "wait_ms", v) || v < 1000 || v > 600000) return BuildError(id, -32602, "wait_ms must be in range 1000..600000"); waitMs = v; } // 主连接、发完即走、无响应(客户端 KernelManager 只校验 ulLength>1 并读 szBuffer[1])。 BYTE token[2] = { (BYTE)TOKEN_MACHINE_MANAGE, type }; if (!ctx->Send2Client(token, 2)) return BuildError(id, -32004, "Failed to send command to host"); bool wentOffline = false; bool cameBack = false; long long elapsedMs = 0; if (wait) { const auto t0 = std::chrono::steady_clock::now(); wentOffline = WaitHostOnlineState(parent, devId, false, waitMs); if (wentOffline) cameBack = WaitHostOnlineState(parent, devId, true, waitMs); elapsedMs = (long long)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); } AuditManageAction(parent, devId, "power_action", "action=" + action + (wait ? " wait=1" : "") + (wait ? (wentOffline ? (cameBack ? " went_offline=1 came_back=1" : " went_offline=1 came_back=0") : " went_offline=0") : "")); // 取消优先于「没等到」:命令已经发出去了,不能伪装成「主机没反应」。用 -32800 说明是 // 调用方自己取消了等待,正文里点明命令可能已生效(重试前先读一次在线列表)。 // 已经看到下线的(wentOffline)继续按成功回报——那是真实发生的事实。 if (wait && !wentOffline && McpCallCancelled()) return BuildError(id, kErrCancelled, "Cancelled while waiting for the host to go offline; the power command " "was already sent, so check the host list before retrying"); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; structuredContent["sent"] = true; structuredContent["went_offline"] = wentOffline; structuredContent["came_back"] = cameBack; structuredContent["elapsed_ms"] = (Json::Int64)elapsedMs; result["structuredContent"] = structuredContent; std::string text = std::string(u8"已下发电源操作:") + action; if (!wait) { text += u8"(未等待结果;要确认主机真的下线/回线请传 wait=true)"; } else if (!wentOffline) { text += std::string(u8";在 ") + std::to_string(waitMs) + u8" ms 内主机仍在在线列表里——命令可能没有生效" u8"(客户端无管理员权限时关机/重启会被拒绝),也可能还在关机流程中。"; } else if (!cameBack) { text += std::string(u8";主机已下线(") + std::to_string(elapsedMs) + std::string(u8" ms),但未在 ") + std::to_string(waitMs) + u8" ms 内重新上线(注销不会自动回线;关机后需人工开机)。"; } else { text += std::string(u8";主机已下线并重新上线,共耗时 ") + std::to_string(elapsedMs) + u8" ms。"; } Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== 卸载主机:uninstall_host(TOKEN_UNINSTALL,单字节,无回执)===== // // 与主控在线列表右键「卸载主机」完全相同:单字节 TOKEN_UNINSTALL 走主连接。Windows // 客户端一直有该分支(回 BYE、退出、self_del),Android 新版映射为「拉起系统卸载 // 确认框」,Linux/macOS 没有分支。老 APK 收到也是静默丢弃,所以 Android 必须先有 // CLIENT_CAP_UNINSTALL 才放行;Windows 没有能力位体系,按平台直接允许。 // 结果验证同 power_action:wait=true 等主机从在线列表消失(卸载后不会回线)。 Json::Value BuildUninstallHostInputSchema() { Json::Value props(Json::objectValue); AddIdRequiredProp(props); Json::Value waitProp(Json::objectValue); waitProp["type"] = "boolean"; waitProp["description"] = u8"true 时等主机从在线列表消失再返回(默认 false,发完即走)。卸载后主机不会回线。"; props["wait"] = waitProp; Json::Value waitMsProp(Json::objectValue); waitMsProp["type"] = "integer"; waitMsProp["minimum"] = 1000; waitMsProp["maximum"] = 600000; waitMsProp["description"] = u8"wait=true 时的最长等待(毫秒,默认 30000)"; props["wait_ms"] = waitMsProp; return FinalizeIdSchema(props, {}); } // 输出:ok/sent 只代表命令写进了 socket;wait=true 时用在线列表观察 went_offline。 Json::Value BuildUninstallHostOutputSchema() { Json::Value props(Json::objectValue); Json::Value ok(Json::objectValue); ok["type"] = "boolean"; ok["description"] = u8"命令已下发(不代表已经卸载)"; props["ok"] = ok; Json::Value sent(Json::objectValue); sent["type"] = "boolean"; sent["description"] = u8"命令已送达主机"; props["sent"] = sent; Json::Value off(Json::objectValue); off["type"] = "boolean"; off["description"] = u8"主机是否已从在线列表消失(wait=true 时观察到的;wait=false 恒为 false)"; props["went_offline"] = off; Json::Value elapsed(Json::objectValue); elapsed["type"] = "integer"; elapsed["description"] = u8"本次等待实际耗时(毫秒;wait=false 时为 0)"; props["elapsed_ms"] = elapsed; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } std::string BuildUninstallHost(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC") return BuildError(id, -32005, "uninstall_host is not supported on Linux/macOS hosts: " "the client has no TOKEN_UNINSTALL handler"); if (clientType == "APK" && !ctx->SupportsUninstall()) return BuildError(id, -32005, "Android client is too old for uninstall_host: " "the APK has no TOKEN_UNINSTALL handler, upgrade the client first"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "uninstall_host is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsManageEnabled()) return BuildError(id, -32006, "uninstall_host is disabled: management operations are off (set McpManage=1 to enable)"); bool wait = false; if (args.isMember("wait")) { if (!args["wait"].isBool()) return BuildError(id, -32602, "wait must be a boolean"); wait = args["wait"].asBool(); } int waitMs = 30000; if (args.isMember("wait_ms")) { int v = 0; if (!GetIntArg(args, "wait_ms", v) || v < 1000 || v > 600000) return BuildError(id, -32602, "wait_ms must be in range 1000..600000"); waitMs = v; } BYTE token = (BYTE)TOKEN_UNINSTALL; if (!ctx->Send2Client(&token, sizeof(token))) return BuildError(id, -32004, "Failed to send uninstall command to host"); bool wentOffline = false; long long elapsedMs = 0; if (wait) { const auto t0 = std::chrono::steady_clock::now(); wentOffline = WaitHostOnlineState(parent, devId, false, waitMs); elapsedMs = (long long)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); } AuditManageAction(parent, devId, "uninstall_host", std::string("wait=") + (wait ? "1" : "0") + (wait ? (wentOffline ? " went_offline=1" : " went_offline=0") : "")); if (wait && !wentOffline && McpCallCancelled()) return BuildError(id, kErrCancelled, "Cancelled while waiting for the host to go offline; the uninstall command " "was already sent, so check the host list before retrying"); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; structuredContent["sent"] = true; structuredContent["went_offline"] = wentOffline; structuredContent["elapsed_ms"] = (Json::Int64)elapsedMs; result["structuredContent"] = structuredContent; std::string text = std::string(u8"已下发卸载命令"); if (!wait) { text += u8"(未等待结果;要确认主机真的下线请传 wait=true)"; } else if (!wentOffline) { text += std::string(u8";在 ") + std::to_string(waitMs) + u8" ms 内主机仍在在线列表里——命令可能没有生效,或 Android 端在等人工点确认框。"; } else { text += std::string(u8";主机已从在线列表下线(") + std::to_string(elapsedMs) + u8" ms)。"; } Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== B1:主机库元数据(备注 / 关注等级)===== // // 写的是服务端本机的 _ClientList(MAP_NOTE / MAP_LEVEL),只影响主控端自己的展示: // 不向客户端下发任何命令,也不改远端状态。所以门控只要 McpReadonly=0(这不是对设备的 // 操作,不要求 McpManage),审计仍走 AuditManageAction(只记字节数,绝不记备注内容)。 // 在线与离线(历史记录)主机都能写:id 在主机库里存在即可。 static bool HostStoreHas(CMy2015RemoteDlg* parent, uint64_t devId) { if (!parent || !parent->m_ClientMap) return false; EnterCriticalSection(&parent->m_cs); bool exists = parent->m_ClientMap->Exists(devId); LeaveCriticalSection(&parent->m_cs); return exists; } // 备注/关注等级改完,UI 行要重绘才能立刻看到。MCP 线程不能直接碰 CListCtrl, // 用 LVM_REDRAWITEMS 投递到列表控件(回到 UI 线程处理,触发 LVN_GETDISPINFO 重取文本)。 static void PostRepaintHostRow(CMy2015RemoteDlg* parent, uint64_t devId) { if (!parent || !parent->m_CList_Online.GetSafeHwnd()) return; int row = -1; EnterCriticalSection(&parent->m_cs); auto it = parent->m_ClientIndex.find(devId); if (it != parent->m_ClientIndex.end()) { for (size_t fi = 0; fi < parent->m_FilteredIndices.size(); ++fi) { if (parent->m_FilteredIndices[fi] == it->second) { row = (int)fi; break; } } } LeaveCriticalSection(&parent->m_cs); if (row >= 0) parent->m_CList_Online.PostMessage(LVM_REDRAWITEMS, (WPARAM)row, (LPARAM)row); } std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); if (!args.isMember("remark") || !args["remark"].isString()) return BuildError(id, -32602, "Missing required parameter: remark (string; empty string clears the remark)"); const std::string remarkU8 = args["remark"].asString(); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "host_set_remark is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!HostStoreHas(parent, devId)) return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId)); // 主机库的备注列是 char Note[64](_ClientValue),存的是 GBK。严格转换:不可表示 // 的字符(emoji、ö 等)直接报错,而不是静默变成 '?';长度按 GBK 字节算,留 1 字节 NUL。 std::string remarkGbk; if (!Utf8ToCpExact(remarkU8, 936, remarkGbk)) return BuildError(id, -32602, "Remark contains characters that GBK (client ANSI) cannot represent"); if (remarkGbk.size() >= 64) return BuildError(id, -32602, "Remark too long: " + std::to_string(remarkGbk.size()) + " GBK bytes (max 63)"); EnterCriticalSection(&parent->m_cs); parent->m_ClientMap->SetClientMapData(devId, MAP_NOTE, remarkGbk.c_str()); parent->m_ClientMap->SaveToFile(GetDbPath()); LeaveCriticalSection(&parent->m_cs); PostRepaintHostRow(parent, devId); AuditManageAction(parent, devId, "host_set_remark", std::string("remark ") + (remarkGbk.empty() ? "cleared" : "set") + " bytes=" + std::to_string(remarkGbk.size())); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["id"] = std::to_string(devId); structuredContent["remark"] = remarkU8; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = remarkGbk.empty() ? std::string(u8"已清除该主机的备注。") : std::string(u8"已更新该主机的备注(") + std::to_string(remarkGbk.size()) + std::string(u8" 字节)。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); int level = -1; if (!GetIntArg(args, "level", level)) return BuildError(id, -32602, "Missing required parameter: level (integer 0-3)"); if (level < 0 || level > 3) return BuildError(id, -32602, "Invalid level: " + std::to_string(level) + " (expect 0-3)"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, "host_set_watch_level is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!HostStoreHas(parent, devId)) return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId)); EnterCriticalSection(&parent->m_cs); parent->m_ClientMap->SetClientMapInteger(devId, MAP_LEVEL, level); parent->m_ClientMap->SaveToFile(GetDbPath()); LeaveCriticalSection(&parent->m_cs); PostRepaintHostRow(parent, devId); AuditManageAction(parent, devId, "host_set_watch_level", "level=" + std::to_string(level)); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["id"] = std::to_string(devId); structuredContent["level"] = level; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"关注等级已设为 ") + std::to_string(level) + std::string(u8"(0=无、1=蓝字、2=红字、3=红底)。"); content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== N3:get_keylog ===== // // 复用客户端既有键盘记录链路:主连接下发 COMMAND_KEYBOARD → 客户端新建子连接并回 // TOKEN_KEYBOARD_START(就绪)→ 之后客户端每约 1 秒推一包 TOKEN_KEYBOARD_DATA // (击键文本,客户端编码)。服务端在窗口期内累积,到时间/字节上限即关闭子连接 // (关连接就是让客户端停止记录,与 MFC 关对话框同一路径)。 // 隐私:击键内容只进本次响应;审计日志只有 tool/耗时/字节数(CALL_OK 那一行)。 std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.IsKeylogEnabled()) return BuildError(id, -32006, "Keyboard log is disabled (McpKeylog=0)"); uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); int durationMs = 4000; // 采集窗口:默认 4s,1-15s GetIntArg(args, "duration_ms", durationMs); if (durationMs < 1000) durationMs = 1000; if (durationMs > 15000) durationMs = 15000; int maxBytes = 64 * 1024; // 返回上限:默认 64 KiB,1-256 KiB GetIntArg(args, "max_bytes", maxBytes); if (maxBytes < 1024) maxBytes = 1024; if (maxBytes > 256 * 1024) maxBytes = 256 * 1024; // 两个写动作在开会话之前就要判定完:否则先下发 COMMAND_KEYBOARD、建好子连接, // 再因为参数/权限问题返回错误,客户端那边已经弹起记录了。 bool setOffline = false; const bool wantSetOffline = args.isMember("set_offline"); if (wantSetOffline) { if (!args["set_offline"].isBool()) return BuildError(id, -32602, "set_offline must be a boolean"); setOffline = args["set_offline"].asBool(); } bool wantClear = false; if (args.isMember("clear")) { if (!args["clear"].isBool()) return BuildError(id, -32602, "clear must be a boolean"); wantClear = args["clear"].asBool(); // clear=false 视为不要求 } if ((wantSetOffline || wantClear) && mcp.IsReadonly()) return BuildError(id, -32006, "clear / set_offline change client state: set McpReadonly=0 to use them"); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "get_keylog is only supported on Windows hosts"); if (!mcp.BeginKeylogSession(devId, "get_keylog", ctx)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_KEYBOARD; if (!ctx->Send2Client(&cmd, 1)) { mcp.EndManagedSession(devId, false, false); return BuildError(id, -32004, "Failed to send command to host"); } // 等子连接就绪包(TOKEN_KEYBOARD_START)。客户端建连很快,给 10s 余量。 std::vector ready; context* sub = nullptr; std::string clientErr; CMcpServer::ManagedWaitResult wr = mcp.WaitManagedPacket( devId, (BYTE)TOKEN_KEYBOARD_START, ready, sub, 10000, clientErr); if (wr != CMcpServer::ManagedWaitResult::Ok) { mcp.EndManagedSession(devId, sub != nullptr, wr == CMcpServer::ManagedWaitResult::Timeout); if (wr == CMcpServer::ManagedWaitResult::ClientError) return BuildError(id, -32004, "Client error: " + clientErr); if (wr == CMcpServer::ManagedWaitResult::Closed) return BuildError(id, -32002, "Sub-connection closed before keyboard log started"); return BuildError(id, -32001, "Timeout waiting for keyboard log sub-connection"); } // 通知「窗口已打开」:客户端 `WaitForDialogOpen` 收到 COMMAND_NEXT 立即返回, // 不再空等 8s。本工具不开 UI,这一步只是让客户端线程别阻塞。 if (sub) { BYTE next = COMMAND_NEXT; sub->Send2Client(&next, 1); } // 就绪包格式 [TOKEN_KEYBOARD_START, offline, WORD caps, TextReplace...](client/ // KeyboardManager.cpp:162-169):byte 1 是客户端常驻记录开关的现值。老客户端也带 // 这一字节;长度不足视为没上报,响应里就不出 offlineRecord。 const bool haveOfflineFlag = ready.size() >= 2; const bool offlineRecord = haveOfflineFlag && ready[1] != 0; // Ok 一定带 subCtx(OnManagedSubPacket 先绑连接再置 hasResponse)。真为空说明状态机 // 出了问题:宁可报错,也不能让写动作被静默跳过、却回一份「已经清过」的结果。 if (!sub) { mcp.EndManagedSession(devId, false, false); return BuildError(id, -32004, "Keyboard sub-connection not bound"); } // 写动作在采集窗口之前下发(与 MFC 的 CKeyBoardDlg 同一组命令、同一条子连接)。 // 二者都没有回执,Send2Client 只表示写进了 socket;失败就中止本次会话,别让模型 // 以为「清过了」而拿到一份其实没清的记录。 if (wantClear) { BYTE b = COMMAND_KEYBOARD_CLEAR; if (!sub->Send2Client(&b, 1)) { mcp.EndManagedSession(devId, true, false); return BuildError(id, -32004, "Failed to send clear to host"); } } if (wantSetOffline) { BYTE b[2] = { COMMAND_KEYBOARD_OFFLINE, (BYTE)(setOffline ? 1 : 0) }; if (!sub->Send2Client(b, sizeof(b))) { mcp.EndManagedSession(devId, true, false); return BuildError(id, -32004, "Failed to send set_offline to host"); } } if (wantClear || wantSetOffline) { std::string detail = std::string("clear=") + (wantClear ? "1" : "0") + " set_offline=" + (wantSetOffline ? (setOffline ? "1" : "0") : "-"); AuditManageAction(parent, devId, "get_keylog", detail); } std::string collected; bool truncated = false; auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(durationMs); for (;;) { auto now = std::chrono::steady_clock::now(); if (now >= deadline) break; int remain = (int)std::chrono::duration_cast( deadline - now).count(); std::string chunk; bool chunkTrunc = false; CMcpServer::KeylogWaitResult r = mcp.WaitKeylogData(devId, chunk, remain > 0 ? remain : 1, chunkTrunc); if (chunkTrunc) truncated = true; if (!chunk.empty()) { if (collected.size() + chunk.size() > (size_t)maxBytes) { collected.append(chunk, 0, (size_t)maxBytes - collected.size()); truncated = true; break; } collected += chunk; if (collected.size() >= (size_t)maxBytes) { truncated = true; break; } } if (r == CMcpServer::KeylogWaitResult::Closed) break; } // 关子连接 = 让客户端停止键盘记录(与 MFC 关闭对话框同路径)。 mcp.EndManagedSession(devId, true, false); // 编码:主连接的代码页(老客户端 GBK,新客户端可能 UTF-8)。 // 去掉夹带的 NUL,避免截断转换;按行切分并去掉行尾 '\r'。 std::string raw; raw.reserve(collected.size()); for (char c : collected) if (c != '\0') raw.push_back(c); std::string utf8 = ToUtf8(raw.c_str(), GetClientEncoding(ctx)); Json::Value lines(Json::arrayValue); size_t pos = 0; std::string joined; while (pos < utf8.size()) { size_t nl = utf8.find('\n', pos); std::string line = (nl == std::string::npos) ? utf8.substr(pos) : utf8.substr(pos, nl - pos); if (!line.empty() && line[line.size() - 1] == '\r') line.erase(line.size() - 1); if (!line.empty()) { lines.append(line); if (joined.size() < 16 * 1024) joined += line + "\n"; } if (nl == std::string::npos) break; pos = nl + 1; } Json::Value structuredContent(Json::objectValue); structuredContent["id"] = std::to_string(devId); structuredContent["duration_ms"] = durationMs; structuredContent["bytes"] = (Json::Int)collected.size(); structuredContent["lines"] = lines; structuredContent["lineCount"] = (int)lines.size(); structuredContent["truncated"] = truncated; if (haveOfflineFlag) structuredContent["offlineRecord"] = offlineRecord; Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; // 行内容已随正文外露(joined 最多 16 KB),正文外只补元数据,不再重复整份行记录。 Json::Value textPayload(Json::objectValue); textPayload["id"] = std::to_string(devId); textPayload["duration_ms"] = durationMs; textPayload["bytes"] = (Json::Int)collected.size(); textPayload["lineCount"] = (int)lines.size(); textPayload["truncated"] = truncated; SetStructuredTextPayload(result, textPayload); Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; std::string text = std::string(u8"键盘记录 ") + std::to_string(durationMs / 1000) + std::string(u8" 秒:收到 ") + std::to_string(collected.size()) + std::string(u8" 字节、") + std::to_string(lines.size()) + std::string(u8" 行"); text += truncated ? std::string(u8"(已到上限,后续内容未取)。") : std::string(u8"。"); if (!joined.empty()) text += "\n" + joined; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== B2:search_file(远程文件搜索,仅 Windows)===== // // 链路:主连接 COMMAND_LIST_DRIVE → 子连接回 TOKEN_DRIVE_LIST(OnDriveList 转下发) // → 子连接 COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST → TOKEN_SEARCH_FILE_FINISH。 // // 协议来自 client/FileManager.cpp(COMMAND_LIST_DRIVE → LoopFileManager → 这个 CFileManager), // 不是 client/file/FileManager.cpp(那是 SimplePlugins 版,走 COMMAND_FILE_MANAGER_PLUGIN, // MCP 的 list_files 不走那条链路)。客户端工程是 MultiByte,全部字段都是 ANSI(GBK): // * 请求 = [COMMAND_SEARCH_FILE][根目录 \0][模式 \0](两个 NUL 结尾的字符串,无定长结构)。 // 模式里没有 * / ? 时客户端自动包成 "*模式*",即「子串、不区分大小写」; // 含通配符则按通配符匹配(WildcardMatch)。 // * 结果 = [TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 \0][sizeHi:4][sizeLo:4][FILETIME:8] }*, // 一个包里可以有多条(客户端按 64KB 批量发),attr = dwFileAttributes & 0x10 → 0 或 16。 // * 客户端行为:总是递归(深度 32、最多 10000 条),跳过隐藏+系统目录与重解析点; // COMMAND_FILES_SEARCH_STOP 只置 m_bSearching=false,搜索线程随后自然结束并发 FINISH。 // ~CFileManager 会 m_bSearching=false + WaitForSingleObject(5000) 再离开,所以即使连接 // 在搜索中途断开,旧版这个管理器也不会 UAF;我们仍然只在 FINISH 后关连接,保持保守。 // // 协议上限约束:客户端用 char[MAX_PATH] 缓冲拼路径(ExpandEnvironmentStrings/wsprintf), // 服务端把 path/pattern 限在 200 字节 GBK 内,给客户端留余量(见 kSearchMaxPathBytes)。 namespace { // 客户端 SearchFilesRecursive 的 strPath[MAX_PATH]/szFullPath[MAX_PATH] 都要再拼子路径。 const size_t kSearchMaxPathBytes = 200; const size_t kSearchMaxPatternBytes = 200; // 去掉末尾的 '\' 或 '/'("C:\" 保留成 "C:",比较时再容忍这种差异)。 std::string StripTrailingSlashes(std::string s) { while (s.size() > 2 && (s.back() == '\\' || s.back() == '/')) s.pop_back(); if (s.size() == 3 && s[1] == ':' && (s[2] == '\\' || s[2] == '/')) s.pop_back(); // "C:\" → "C:" return s; } // Windows 路径比较:ASCII 不区分大小写(GBK 双字节按原字节比,中文本就无大小写)。 bool EqualsPathNoCase(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); ++i) { char ca = a[i], cb = b[i]; if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a'); if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a'); if (ca != cb) return false; } return true; } std::string FormatFileTimeLocal(const FILETIME& ftIn) { if (ftIn.dwLowDateTime == 0 && ftIn.dwHighDateTime == 0) return ""; FILETIME local; if (!FileTimeToLocalFileTime(&ftIn, &local)) return ""; SYSTEMTIME st; if (!FileTimeToSystemTime(&local, &st)) return ""; char buf[32]; _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); return buf; } // 一个 TOKEN_SEARCH_FILE_LIST 包里有多条记录(客户端按 64KB 批量发)。 // 客户端用 LocalReAlloc(LMEM_ZEROINIT) 扩缓冲,包尾可能带 0 填充;读到空路径即视为结束。 void AppendSearchRecords(const std::vector& pkt, Json::Value& out) { if (pkt.size() < 2) return; const size_t len = pkt.size(); size_t off = 1; // 跳过 token 字节 while (off + 1 <= len) { const BYTE attr = pkt[off]; ++off; std::string path; // GBK 原始字节 bool terminated = false; while (off < len) { const char ch = (char)pkt[off++]; if (ch == 0) { terminated = true; break; } path.push_back(ch); } if (!terminated || off + 16 > len) return; // 尾部截断/零填充 if (path.empty()) return; // LocalSize 的零填充 DWORD sizeHi = 0, sizeLo = 0; memcpy(&sizeHi, pkt.data() + off, 4); memcpy(&sizeLo, pkt.data() + off + 4, 4); off += 8; FILETIME ft; memcpy(&ft, pkt.data() + off, sizeof(ft)); off += 8; size_t slash = path.find_last_of("\\/"); const std::string name = (slash == std::string::npos) ? path : path.substr(slash + 1); Json::Value rec(Json::objectValue); rec["path"] = ToUtf8(path.c_str(), 936); rec["name"] = ToUtf8(name.c_str(), 936); rec["dir"] = (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; rec["size"] = (Json::UInt64)(((uint64_t)sizeHi << 32) | sizeLo); std::string modified = FormatFileTimeLocal(ft); if (!modified.empty()) rec["modified"] = modified; out.append(rec); } } } // namespace Json::Value BuildSearchFileInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(Windows 客户端)。"; props["id"] = idProp; Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"搜索的根目录,例如 C:\\Users 或 D:\\Data(必须是完整路径)。"; props["path"] = pathProp; Json::Value patProp(Json::objectValue); patProp["type"] = "string"; patProp["description"] = u8"文件名匹配串(不区分大小写),例如 report、.log、setup.exe;不含通配符时按子串匹配,含 * 或 ? 时按通配符匹配(如 *.log)。"; props["pattern"] = patProp; Json::Value recProp(Json::objectValue); recProp["type"] = "boolean"; recProp["description"] = u8"是否包含子目录,默认 true。客户端只支持递归搜索,传 false 时由服务端过滤出根目录下的直接子项(搜索耗时不变)。"; props["recursive"] = recProp; Json::Value toProp(Json::objectValue); toProp["type"] = "integer"; toProp["description"] = u8"搜索时限(毫秒),默认 20000,范围 1000-120000。到时限会通知客户端停止搜索,返回已收到的部分结果(finished=false)。"; props["timeout_ms"] = toProp; // ===== C4:结果侧过滤 ===== Json::Value minProp(Json::objectValue); minProp["type"] = "integer"; minProp["description"] = u8"只保留大小不小于该字节数的条目。目录项也会参与比较(客户端上报的目录 size 恒为 0),只想看文件时用 min_size=1。"; props["min_size"] = minProp; Json::Value maxProp(Json::objectValue); maxProp["type"] = "integer"; maxProp["description"] = u8"只保留不大于该字节数的条目。与 min_size 同时给出时区间取交集。"; props["max_size"] = maxProp; Json::Value maProp(Json::objectValue); maProp["type"] = "string"; maProp["description"] = u8"只保留修改时间晚于该时刻的条目,格式 YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS(主机本地时间)。只给日期时按「该日 00:00:00 之后」理解。"; props["modified_after"] = maProp; Json::Value nameOnlyProp(Json::objectValue); nameOnlyProp["type"] = "boolean"; nameOnlyProp["description"] = u8"true 时每条只返回 path 与 name,省略 dir/size/modified,用于结果集很大时省流量。默认 false。"; props["name_only"] = nameOnlyProp; AppendPagingProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("path"); required.append("pattern"); schema["required"] = required; return schema; } Json::Value BuildSearchFileOutputSchema() { Json::Value props(Json::objectValue); Json::Value filesProp(Json::objectValue); filesProp["type"] = "array"; Json::Value items(Json::objectValue); items["type"] = "object"; Json::Value itemProps(Json::objectValue); for (const char* f : { "path", "name", "modified" }) { Json::Value s(Json::objectValue); s["type"] = "string"; itemProps[f] = s; } Json::Value dirProp(Json::objectValue); dirProp["type"] = "boolean"; itemProps["dir"] = dirProp; Json::Value sizeProp(Json::objectValue); sizeProp["type"] = "integer"; itemProps["size"] = sizeProp; items["properties"] = itemProps; filesProp["items"] = items; props["files"] = filesProp; Json::Value finProp(Json::objectValue); finProp["type"] = "boolean"; props["finished"] = finProp; Json::Value truncProp(Json::objectValue); truncProp["type"] = "boolean"; props["truncated"] = truncProp; // 分页字段:BuildSearchFile 一直会带 total/totalAll/offset/limit/hasMore, // schema 补齐后客户端按输出契约取值才不会扑空。 AppendPageOutputProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 该协议只在 Windows 客户端的 CFileManager 里实现(请求体是两个 GBK C 串)。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, "search_file is only supported on Windows hosts"); std::string path = Trim(GetStringArg(args, "path")); std::string pattern = Trim(GetStringArg(args, "pattern")); if (path.empty()) return BuildError(id, -32602, "Missing required parameter: path (e.g. C:\\\\Users)"); if (pattern.empty()) return BuildError(id, -32602, "Missing required parameter: pattern (file name substring)"); // 客户端枚举用的是 wsprintf("%s\\*.*"):根目录带尾部反斜杠会拼成 "C:\\*.*", // FindFirstFile 直接失败,搜索秒回 0 条。统一去尾斜杠("C:\" → "C:",客户端拼回 "C:\*.*"), // 顺便把分隔符统一成反斜杠(记录里的全路径也是反斜杠拼的)。 for (char& c : path) if (c == '/') c = '\\'; path = StripTrailingSlashes(path); if (path.empty() || path == "\\") return BuildError(id, -32602, "Invalid path: expected a directory such as C:\\ or C:\\Users"); bool recursive = true; if (args.isMember("recursive") && args["recursive"].isBool()) recursive = args["recursive"].asBool(); int timeoutMs = 20000; int v = 0; if (GetIntArg(args, "timeout_ms", v)) { if (v < 1000) v = 1000; if (v > 120000) v = 120000; timeoutMs = v; } // ===== C4:结果侧过滤参数(全部在服务端做,客户端仍只做「按名字匹配 + 递归」)===== // 读可选的字节数参数:0=未给出;1=已给出;-1=非法(负数/非数字)。 auto readSizeArg = [](const Json::Value& a, const char* key, uint64_t& out) -> int { if (!a.isMember(key)) return 0; const Json::Value& val = a[key]; if (val.isNumeric() && val.asDouble() < 0) return -1; if (!ReadUInt64(val, out)) return -1; return 1; }; uint64_t minSize = 0, maxSize = 0; int hasMinSize = readSizeArg(args, "min_size", minSize); int hasMaxSize = readSizeArg(args, "max_size", maxSize); if (hasMinSize < 0) return BuildError(id, -32602, "min_size must be a non-negative integer (bytes)"); if (hasMaxSize < 0) return BuildError(id, -32602, "max_size must be a non-negative integer (bytes)"); if (hasMinSize == 1 && hasMaxSize == 1 && minSize > maxSize) return BuildError(id, -32602, "min_size must not be greater than max_size"); // 客户端 modified 是固定宽度的 "YYYY-MM-DD HH:MM:SS",所以边界值可直接按字典序比较。 std::string modifiedAfter; if (args.isMember("modified_after")) { if (!args["modified_after"].isString()) return BuildError(id, -32602, "modified_after must be a string"); modifiedAfter = Trim(args["modified_after"].asString()); if (!modifiedAfter.empty()) { bool shaped = (modifiedAfter.size() == 10 || modifiedAfter.size() == 19); for (size_t i = 0; shaped && i < modifiedAfter.size(); ++i) { const char c = modifiedAfter[i]; if (i == 4 || i == 7) shaped = (c == '-'); else if (i == 10) shaped = (c == ' '); else if (i == 13 || i == 16) shaped = (c == ':'); // 19 位形式才有 else shaped = (c >= '0' && c <= '9'); } if (!shaped) return BuildError(id, -32602, "modified_after must look like YYYY-MM-DD or YYYY-MM-DD HH:MM:SS"); } } bool nameOnly = args.isMember("name_only") && args["name_only"].isBool() && args["name_only"].asBool(); const bool hasResultFilter = hasMinSize == 1 || hasMaxSize == 1 || !modifiedAfter.empty() || nameOnly; std::string ansiPath, ansiPattern; if (!Utf8ToCpExact(path, 936, ansiPath)) return BuildError(id, -32602, "path cannot be encoded in the client's ANSI code page (GBK); use ASCII-safe paths"); if (!Utf8ToCpExact(pattern, 936, ansiPattern)) return BuildError(id, -32602, "pattern cannot be encoded in the client's ANSI code page (GBK)"); if (ansiPath.size() > kSearchMaxPathBytes) return BuildError(id, -32602, "path too long (max " + std::to_string(kSearchMaxPathBytes) + " bytes in GBK)"); if (ansiPattern.size() > kSearchMaxPatternBytes) return BuildError(id, -32602, "pattern too long (max " + std::to_string(kSearchMaxPatternBytes) + " bytes in GBK)"); // 请求体 = [根目录 \0][模式 \0](OnDriveList 前面再加 COMMAND_SEARCH_FILE)。 std::string payload; payload.reserve(ansiPath.size() + ansiPattern.size() + 2); payload.append(ansiPath); payload.push_back('\0'); payload.append(ansiPattern); payload.push_back('\0'); CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "search_file", payload)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } std::vector> packets; bool finished = false, truncated = false; context* subCtx = nullptr; if (!mcp.WaitSearchFile(devId, packets, finished, truncated, subCtx, timeoutMs)) { mcp.ClearPending(devId); return BuildError(id, -32001, "Timeout waiting for the file manager session"); } if (!finished) { if (!subCtx) { // 客户端连文件管理器子连接都没建起来(离线/拒绝/过载),不是「搜索慢」。 mcp.ClearPending(devId); return BuildError(id, -32001, "Timeout waiting for the file manager session"); } // 到时限:让客户端停搜(客户端搜索线程下一次循环即退出,随后回 FINISH),再给 5s 收尾。 // 收不到 FINISH 也照样返回部分结果;子连接留给 FINISH 分支关闭。 mcp.StopSearchFile(devId); std::vector> more; bool finished2 = false, truncated2 = truncated; context* subCtx2 = nullptr; if (mcp.WaitSearchFile(devId, more, finished2, truncated2, subCtx2, 5000)) { packets.insert(packets.end(), more.begin(), more.end()); finished = finished2; truncated = truncated || truncated2; } } mcp.ClearPending(devId); Json::Value all(Json::arrayValue); for (const auto& pkt : packets) AppendSearchRecords(pkt, all); // 客户端只有递归搜索(深度 32),非递归请求在这里按「父目录 == 根目录」服务端过滤。 if (!recursive) { Json::Value filtered(Json::arrayValue); const std::string root = StripTrailingSlashes(path); for (const Json::Value& rec : all) { std::string p = rec["path"].asString(); size_t slash = p.find_last_of("\\/"); if (slash == std::string::npos) continue; if (EqualsPathNoCase(StripTrailingSlashes(p.substr(0, slash)), root)) filtered.append(rec); } all = filtered; } // C4:结果侧过滤。注意它发生在收集之后——客户端的 5000 条 / 4 MB 收集上限 // 仍在过滤之前生效,命中太多时该 truncated 还是会 truncated。 const int collected = (int)all.size(); if (hasResultFilter) { Json::Value filtered(Json::arrayValue); for (const Json::Value& rec : all) { if (hasMinSize == 1 || hasMaxSize == 1) { uint64_t sz = rec["size"].asUInt64(); if (hasMinSize == 1 && sz < minSize) continue; if (hasMaxSize == 1 && sz > maxSize) continue; } if (!modifiedAfter.empty()) { std::string m = JsonStrField(rec, "modified"); if (m.empty() || m <= modifiedAfter) continue; // 字典序即时间序(格式固定) } if (nameOnly) { Json::Value slim(Json::objectValue); slim["path"] = rec["path"]; slim["name"] = rec["name"]; filtered.append(slim); } else { filtered.append(rec); } } all = filtered; } PageWindow page = ResolvePageWindow(args); Json::Value pageItems; ApplyPageWindow(all, page, pageItems); if (hasResultFilter) page.totalAll = collected; // total 是命中数,totalAll 是过滤前条数 Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["files"] = pageItems; structuredContent["finished"] = finished; structuredContent["truncated"] = truncated; WritePageFields(structuredContent, page); result["structuredContent"] = structuredContent; std::string text = PageSummary(page, u8"个匹配项"); if (hasResultFilter) text += std::string(u8"过滤前共 ") + std::to_string(collected) + std::string(u8" 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)。"); if (!finished) text += u8" 搜索在时限内未完成,以上为已收到的部分结果(可加大 timeout_ms 重试)。"; if (truncated) text += u8" 命中数超过服务端收集上限(5000 条 / 4 MB),后续匹配已停止收集,请缩小 path 或 pattern 再搜。"; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)===== // // 链路: // 主连接 COMMAND_LIST_DRIVE → 子连接首包 TOKEN_DRIVE_LIST(OnDriveList 转下发写命令) // → 子连接回 TOKEN_DELETE_FINISH / TOKEN_RENAME_FINISH / TOKEN_CREATEFOLDER_FINISH // (TakeFileOpFinish 转入复核:在同一子连接上补发 COMMAND_LIST_FILES 列父目录) // → TOKEN_FILE_LIST(MessageHandle 现有分支投递数据并 CancelIO 收尾) // // 为什么必须复核:客户端四个写命令都是「做完就无条件 SendToken」,DeleteFile / MoveFile / // MakeSureDirectoryPathExists 的返回值一概不看(也没有错误包)。所以完成包只证明「命令到了」, // 不证明「做成了」。复核复用同一条已开的子连接再列一次父目录,代价只有一次往返。 // // 编码:路径按客户端 ANSI(GBK) 上线(CFileManager 走 A 接口),UTF-8 → GBK 严格转换, // 转不了直接 -32602(同 search_file),不做「转不了就传原样」的猜测。 namespace { // 客户端用 char[MAX_PATH] 缓冲拼路径(ExpandPath / wsprintf "%s\\*.*"), // 与 search_file 同一约束:单条路径限 200 字节 GBK,给「父目录 + 反斜杠 + 文件名」留余量。 const size_t kFileOpMaxPathBytes = 200; bool IsFileWriteToolName(const std::string& tool) { return tool == "delete_path" || tool == "move_path" || tool == "create_folder"; } inline bool IsAsciiLetter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } // 规范化 UTF-8 路径:去掉 \\?\ 前缀、分隔符统一 '\'、折叠 . 与 ..、去掉尾部分隔符。 // 只接受绝对路径(盘符 / UNC / 卷根相对):相对路径由目标机的当前目录解析,服务端既没法 // 校验保护目录,也就算不出复核用的父目录。折叠 .. 是为了保护判定不被人为的 "C:\x\..\Windows" 绕过。 bool NormalizePathUtf8(const std::string& raw, std::string& out) { std::string in = raw; if (in.rfind("\\\\?\\", 0) == 0 || in.rfind("\\\\.\\", 0) == 0) in = in.substr(4); for (char& c : in) if (c == '/') c = '\\'; // 前缀:盘符 "X:"、UNC 的 "\\server\share",或卷根相对("\Windows\..." → 前缀为空) std::string prefix; size_t i = 0; if (in.size() >= 2 && IsAsciiLetter(in[0]) && in[1] == ':') { prefix = in.substr(0, 2); i = 2; } else if (in.rfind("\\\\", 0) == 0) { const size_t a = in.find('\\', 2); if (a == std::string::npos) return false; // "\\" 或 "\\server" const size_t b = in.find('\\', a + 1); prefix = (b == std::string::npos) ? in : in.substr(0, b); i = prefix.size(); } else if (!in.empty() && in[0] == '\\') { i = 1; } else { return false; // 相对路径 } std::vector segs; while (i <= in.size()) { size_t j = in.find('\\', i); if (j == std::string::npos) j = in.size(); const std::string seg = in.substr(i, j - i); if (!seg.empty() && seg != ".") { if (seg == "..") { if (segs.empty()) return false; // 试图越过根 segs.pop_back(); } else { segs.push_back(seg); } } i = j + 1; } out = prefix; for (const std::string& s : segs) { out += '\\'; out += s; } return !out.empty(); } // 盘符根 / 卷根 / 共享根(C:、\、\\server\share):任何写操作都不能拿它当目标。 bool IsPathRoot(const std::string& p) { if (p.size() == 2 && IsAsciiLetter(p[0]) && p[1] == ':') return true; if (p.empty() || p.find_first_not_of('\\') == std::string::npos) return true; if (p.rfind("\\\\", 0) == 0) { const size_t a = p.find('\\', 2); if (a == std::string::npos) return true; // \\server return p.find('\\', a + 1) == std::string::npos; // \\server\share } return false; } std::string UpperAscii(std::string s) { for (char& c : s) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); return s; } // 系统目录保护。删除/改名是「毁灭」,不允许落在这些位置;建目录不受限(安装前建目录是正经用法)。 // 按整段比较:C:\Windows.old 不算 C:\Windows,C:\Program Files (x86) 单独一条。 // 带子树的是「整棵都不能动」;kProtectedExact 只挡目录本身(C:\Users\bob\... 仍是合法目标)。 const char* const kProtectedTree[] = { "\\WINDOWS", "\\PROGRAM FILES", "\\PROGRAM FILES (X86)", "\\PROGRAMDATA", "\\SYSTEM VOLUME INFORMATION", "\\$RECYCLE.BIN", }; const char* const kProtectedExact[] = { "\\USERS", "\\PERFLOGS", "\\RECOVERY" }; // 入参必须是 NormalizePathUtf8 的结果。 bool IsProtectedSystemPath(const std::string& normalized) { const std::string up = UpperAscii(normalized); size_t i = 0; if (up.size() >= 2 && IsAsciiLetter(up[0]) && up[1] == ':') { i = 2; } else if (up.rfind("\\\\", 0) == 0) { const size_t a = up.find('\\', 2); if (a == std::string::npos) return true; // 只有服务器名 const size_t b = up.find('\\', a + 1); if (b == std::string::npos) return true; // 共享根本身 i = b; } const std::string rel = up.substr(i); for (const char* p : kProtectedTree) { const std::string tree = p; if (rel == tree || rel.rfind(tree + "\\", 0) == 0) return true; } for (const char* p : kProtectedExact) { if (rel == std::string(p)) return true; } return false; } // 校验一条写操作目标路径,产出上线用的 GBK 字节、复核用的父目录与末段名字。 // protectSystemDirs=true:目标本身落在系统目录内就拒绝(删除、改名的来源); // false:只拒绝根路径(改名的去向、建目录——写到 Program Files 与 upload_file 同权限,不额外收紧)。 bool PrepareFileOpPath(const std::string& raw, bool protectSystemDirs, bool needParent, const std::string& tool, std::string& normalized, std::string& ansi, std::string& parentAnsi, std::string& leafUtf8, std::string& err) { const std::string trimmed = Trim(raw); if (trimmed.empty()) { err = tool + ": missing or empty path"; return false; } // 客户端会对路径做 ExpandEnvironmentStrings:%SystemRoot%\System32 之类的写法在服务端 // 看起来不在保护目录里,到目标机却会展开过去。服务端无从预知目标机环境,一律拒绝。 if (trimmed.find('%') != std::string::npos) { err = tool + ": path must not contain environment variables (%VAR%): the client expands " "them and the server cannot validate the real target. Resolve the variable first"; return false; } if (!NormalizePathUtf8(trimmed, normalized)) { err = tool + ": invalid path (expected an absolute path such as C:\\\\Temp\\\\work): " + trimmed; return false; } if (IsPathRoot(normalized)) { err = tool + ": refusing to operate on a drive root or share root: " + normalized; return false; } if (protectSystemDirs && IsProtectedSystemPath(normalized)) { err = tool + ": refusing to modify a protected system location: " + normalized + " (Windows, Program Files, ProgramData, $Recycle.Bin and their subtrees are off " "limits; use exec_command if you really need to touch them)"; return false; } if (!Utf8ToCpExact(normalized, 936, ansi)) { err = tool + ": path cannot be encoded in the client's ANSI code page (GBK): " + normalized; return false; } if (ansi.size() > kFileOpMaxPathBytes) { err = tool + ": path too long (max " + std::to_string(kFileOpMaxPathBytes) + " bytes in GBK): " + normalized; return false; } if (!needParent) return true; const size_t slash = normalized.find_last_of('\\'); if (slash == std::string::npos) { err = tool + ": cannot derive a parent directory from " + normalized; return false; } leafUtf8 = normalized.substr(slash + 1); // 父目录一定比整条路径短,前面已确认整条能转 GBK;这里再转一次是因为要单独上线。 if (leafUtf8.empty() || !Utf8ToCpExact(normalized.substr(0, slash), 936, parentAnsi)) { err = tool + ": cannot derive a parent directory from " + normalized; return false; } return true; } // 复核结果:在 TOKEN_FILE_LIST 里找末段名字。 enum class ListingLookup { Unknown, Present, Absent }; ListingLookup LookupInListing(const std::vector& data, const std::string& leafUtf8, bool& isDir) { isDir = false; if (data.empty()) return ListingLookup::Unknown; if (data[0] == TOKEN_FILE_LIST_ERROR) { // 新客户端的结构化失败:[token][win32err:4]。只有「不存在」能当否定结论; // 拒绝访问说明复核本身没做成,不能据此判定操作失败。 const DWORD e = ReadWin32Payload(data); if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return ListingLookup::Absent; return ListingLookup::Unknown; } if (data[0] != TOKEN_FILE_LIST) return ListingLookup::Unknown; // 复核要扫全整个列表(list_files 自己也已整目录解析;这里上限只为兜底)。 const Json::Value items = ParseFileList(data, 1000000, 936); for (unsigned int i = 0; i < items.size(); ++i) { const std::string name = JsonStrField(items[i], "name"); if (EqualsPathNoCase(name, leafUtf8)) { isDir = items[i]["isDir"].asBool(); return ListingLookup::Present; } } return ListingLookup::Absent; } // want:0=期望目标不存在(删除);1=期望存在(改名目标);2=期望存在且是目录(建目录)。 // 返回 1=确认生效,0=确认未生效,-1=无法确认(不谎报 false)。 int ResolveFileOpVerified(ListingLookup lk, bool isDir, int want) { if (lk == ListingLookup::Unknown) return -1; if (lk == ListingLookup::Absent) return want == 0 ? 1 : 0; if (want == 0) return 0; // 还在 if (want == 2) return isDir ? 1 : 0; // 同名文件挡着,目录没建成 return 1; } struct FileOpWait { bool acked = false; // 收到客户端完成包(命令已送达) bool dataIsListing = false; // 最终拿到的是复核列表(false = 完成包本身) std::vector data; }; // 等两阶段收尾。返回 false = 连完成包都没等到(超时/断线),调用方按 -32001 处理。 // phase 1 超时是特例:命令已送到客户端、只是复核没回来——结果未知,不算失败。 bool WaitFileOp(CMcpServer& mcp, uint64_t devId, FileOpWait& out) { int phase = 0; if (!mcp.WaitPendingWrite(devId, out.data, mcp.ToolTimeoutMs(), &phase)) { out.acked = (phase == 1); out.dataIsListing = false; return out.acked; } out.acked = true; out.dataIsListing = (phase == 1); return true; } // 门控 + 平台检查。返回空串 = 放行;否则是完整的错误响应。 std::string GateFileWriteTool(const Json::Value& id, const std::string& tool, const Json::Value& args, CMy2015RemoteDlg* parent, uint64_t& devId, context*& ctx) { std::string err; if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err); ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); // 这几个命令只在 Windows 客户端的 CFileManager 里实现(GBK + A 接口);LNX/MAC 的 // FileManager.h 虽然也有同名分支,但收包按 GBK→UTF-8 解,和 list_files 的 UTF-8 口径 // 不一致,非 ASCII 路径会互相打脸,暂不开放。 const CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") return BuildError(id, -32005, tool + " is only supported on Windows hosts"); CMcpServer& mcp = CMcpServer::Instance(); if (mcp.IsReadonly()) return BuildError(id, -32006, tool + " is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); if (!mcp.IsFileWriteEnabled()) return BuildError(id, -32006, tool + " is disabled: file writes are off (set McpFileWrite=1 to enable)"); return std::string(); } // 开子连接 + 两阶段等待。返回空串 = 结果在 out 里;否则是完整的错误响应。 std::string RunFileOp(const Json::Value& id, const std::string& tool, context* ctx, uint64_t devId, const std::vector& followUp, const std::string& verifyPathAnsi, FileOpWait& out) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPendingFileOp(devId, tool, followUp, verifyPathAnsi)) return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return BuildError(id, -32004, "Failed to send command to host"); } if (!WaitFileOp(mcp, devId, out)) return BuildError(id, -32001, "Timeout waiting for the client to acknowledge " + tool + " (the command may still be executed later; re-check with list_files)"); return std::string(); } // 统一输出:{..., ok, verified:true|false|null} + 一句可读摘要。 // 复核通过时的文案必须只描述「复核看到的状态」,不能写成「已完成删除」:客户端对不存在的 // 目标也会回完成包,而复核只能看到「现在没有这个名字」,两者无法区分(见 delete_path 描述)。 std::string BuildFileOpResult(const Json::Value& id, Json::Value structured, const std::string& confirmedText, const std::string& failedHint, const FileOpWait& w, int verified) { structured["ok"] = w.acked; if (verified == 1) structured["verified"] = true; else if (verified == 0) structured["verified"] = false; else structured["verified"] = Json::Value(Json::nullValue); std::string text; if (verified == 1) { text = std::string(u8"复核通过:") + confirmedText; } else if (verified == 0) { text = std::string(u8"命令已送达客户端,但复核显示未生效:") + failedHint; } else { text = std::string(u8"命令已送达客户端(已收到完成包),但复核没能完成" u8"(列目录超时或断线),结果未知;请用 list_files 再确认一次。"); } Json::Value result(Json::objectValue); result["structuredContent"] = structured; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = text; content.append(item); result["content"] = content; // verified=false 是「确认没成」→ 调用失败;null 只是「不知道」,不判失败。 result["isError"] = (verified == 0); return BuildResult(id, result); } // 三个写工具共享的路径字段 schema void AppendFileOpResultProps(Json::Value& props) { Json::Value okProp(Json::objectValue); okProp["type"] = "boolean"; okProp["description"] = u8"命令已送达客户端并收到完成回包。客户端的完成包是无条件回包,不代表操作成功。"; props["ok"] = okProp; Json::Value verProp(Json::objectValue); // 三态:true / false / null。声明成 ["boolean","null"],别让严格校验的客户端 // 把「复核没做成」误判成 schema 违规。 Json::Value verType(Json::arrayValue); verType.append("boolean"); verType.append("null"); verProp["type"] = verType; verProp["description"] = u8"复核结果:true=确认已生效,false=确认未生效,null=复核没做成(结果未知)。"; props["verified"] = verProp; } } // namespace Json::Value BuildDeletePathInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(Windows 客户端)。"; props["id"] = idProp; Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"要删除的绝对路径(文件或目录),例如 C:\\Temp\\old.log;不能含 %VAR%,不能是盘符根。"; props["path"] = pathProp; Json::Value recProp(Json::objectValue); recProp["type"] = "boolean"; recProp["description"] = u8"true=按目录递归删除(COMMAND_DELETE_DIRECTORY,连同子目录内容一起删);默认 false=按单个文件删除。目标其实是目录却传 false 时,客户端 DeleteFile 会失败(复核会返回 verified=false)。"; props["recursive"] = recProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("path"); schema["required"] = required; return schema; } Json::Value BuildDeletePathOutputSchema() { Json::Value props(Json::objectValue); AppendFileOpResultProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildMovePathInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(Windows 客户端)。"; props["id"] = idProp; Json::Value fromProp(Json::objectValue); fromProp["type"] = "string"; fromProp["description"] = u8"原来的绝对路径(文件或目录),例如 C:\\Temp\\a.txt。"; props["from"] = fromProp; Json::Value toProp(Json::objectValue); toProp["type"] = "string"; toProp["description"] = u8"新的完整路径(含新名字),例如 C:\\Temp\\b.txt;必须在同一卷内。"; props["to"] = toProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("from"); required.append("to"); schema["required"] = required; return schema; } Json::Value BuildMovePathOutputSchema() { Json::Value props(Json::objectValue); AppendFileOpResultProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildCreateFolderInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(Windows 客户端)。"; props["id"] = idProp; Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; pathProp["description"] = u8"要创建的目录绝对路径,例如 C:\\Temp\\report\\2026;缺失的中间层会一并创建。"; props["path"] = pathProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("path"); schema["required"] = required; return schema; } Json::Value BuildCreateFolderOutputSchema() { Json::Value props(Json::objectValue); AppendFileOpResultProps(props); Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { const std::string tool = "delete_path"; uint64_t devId = 0; context* ctx = nullptr; std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx); if (!err.empty()) return err; const bool recursive = args.isMember("recursive") && args["recursive"].isBool() && args["recursive"].asBool(); std::string normalized, ansi, parentAnsi, leafUtf8; if (!PrepareFileOpPath(GetStringArg(args, "path"), true, true, tool, normalized, ansi, parentAnsi, leafUtf8, err)) return BuildError(id, -32602, err); // 递归删除走 COMMAND_DELETE_DIRECTORY(客户端 DeleteDirectory 会先清子项再删目录)。 // path 后必须补 '\0':客户端按 C 串取路径。 std::vector followUp; followUp.reserve(2 + ansi.size()); followUp.push_back(recursive ? (BYTE)COMMAND_DELETE_DIRECTORY : (BYTE)COMMAND_DELETE_FILE); followUp.insert(followUp.end(), ansi.begin(), ansi.end()); followUp.push_back(0); FileOpWait w; err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w); if (!err.empty()) return err; AuditManageAction(parent, devId, tool, std::string("path=") + normalized + (recursive ? " recursive=1" : " recursive=0")); int verified = -1; if (w.dataIsListing) { bool isDir = false; // isDir 是 LookupInListing 的出参,必须先单独调用:写成 // ResolveFileOpVerified(LookupInListing(..., isDir), isDir, ...) 会读到未赋值的 false // (实参求值顺序未指定,MSVC 从右往左先算 isDir)。 const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir); verified = ResolveFileOpVerified(lk, isDir, 0); } Json::Value sc(Json::objectValue); sc["id"] = std::to_string(devId); sc["path"] = normalized; sc["recursive"] = recursive; return BuildFileOpResult(id, sc, u8"\"" + normalized + u8"\" 已不在父目录列表里" u8"(目标本来就不存在时也是这个结果——客户端不回错误包)。", u8"目标仍在(只读文件、被占用或权限不足都会静默失败;" u8"也可能是 recursive=false 落在了目录上:" + normalized + u8")。", w, verified); } std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { const std::string tool = "move_path"; uint64_t devId = 0; context* ctx = nullptr; std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx); if (!err.empty()) return err; // 来源按「会被拿走」对待,受系统目录保护;去向只拒绝根路径(写入 Program Files 的权限 // 与 upload_file 相同,不额外收紧)。 std::string fromNorm, fromAnsi, ignored1, ignored2; if (!PrepareFileOpPath(GetStringArg(args, "from"), true, false, tool, fromNorm, fromAnsi, ignored1, ignored2, err)) return BuildError(id, -32602, err); std::string toNorm, toAnsi, toParentAnsi, toLeafUtf8; if (!PrepareFileOpPath(GetStringArg(args, "to"), false, true, tool, toNorm, toAnsi, toParentAnsi, toLeafUtf8, err)) return BuildError(id, -32602, err); if (EqualsPathNoCase(fromNorm, toNorm)) return BuildError(id, -32602, "move_path: from and to are the same path: " + fromNorm); // 请求体 = [from\0][to\0](首字节是命令)。客户端用 ::MoveFile,同卷内文件与目录都能搬。 std::vector followUp; followUp.reserve(3 + fromAnsi.size() + toAnsi.size()); followUp.push_back((BYTE)COMMAND_RENAME_FILE); followUp.insert(followUp.end(), fromAnsi.begin(), fromAnsi.end()); followUp.push_back(0); followUp.insert(followUp.end(), toAnsi.begin(), toAnsi.end()); followUp.push_back(0); FileOpWait w; err = RunFileOp(id, tool, ctx, devId, followUp, toParentAnsi, w); if (!err.empty()) return err; AuditManageAction(parent, devId, tool, "from=" + fromNorm + " to=" + toNorm); int verified = -1; if (w.dataIsListing) { bool isDir = false; // 同 delete_path:先调用再取值,别把出参和调用写进同一句实参表。 const ListingLookup lk = LookupInListing(w.data, toLeafUtf8, isDir); verified = ResolveFileOpVerified(lk, isDir, 1); } Json::Value sc(Json::objectValue); sc["id"] = std::to_string(devId); sc["from"] = fromNorm; sc["to"] = toNorm; return BuildFileOpResult(id, sc, u8"\"" + toNorm + u8"\" 已出现在父目录列表里(原路径 \"" + fromNorm + u8"\" 是否已消失不在复核范围内)。", u8"新名字没有出现在目标目录里(目标已存在、跨卷、只读或被占用都会" u8"让 ::MoveFile 静默失败):\"" + toNorm + u8"\"。", w, verified); } std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { const std::string tool = "create_folder"; uint64_t devId = 0; context* ctx = nullptr; std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx); if (!err.empty()) return err; std::string normalized, ansi, parentAnsi, leafUtf8; if (!PrepareFileOpPath(GetStringArg(args, "path"), false, true, tool, normalized, ansi, parentAnsi, leafUtf8, err)) return BuildError(id, -32602, err); // 结尾必须补一个 '\\':客户端 CFileManager::CreateFolder 直接把这段字节丢给 // MakeSureDirectoryPathExists,而它是「路径里每个以反斜杠结尾的片段都要存在」的语义 // ——不带尾部反斜杠时最后一级被当成文件名,压根不会被创建(MFC 的 OnRemoteNewfolder // 也是拼 m_Remote_Path + name + "\\")。delete 恰好相反:RemoveDirectory 不接受尾部 // 反斜杠,所以那边保持去掉分隔符的写法。 std::vector followUp; followUp.reserve(3 + ansi.size()); followUp.push_back((BYTE)COMMAND_CREATE_FOLDER); followUp.insert(followUp.end(), ansi.begin(), ansi.end()); followUp.push_back('\\'); followUp.push_back(0); FileOpWait w; err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w); if (!err.empty()) return err; AuditManageAction(parent, devId, tool, "path=" + normalized); int verified = -1; if (w.dataIsListing) { bool isDir = false; // 这一处最要命:want=2 会读 isDir,写成一行时 isDir 永远是初始的 false, // 于是「建目录」永远自评「未生效」(同 delete_path 的注释)。 const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir); verified = ResolveFileOpVerified(lk, isDir, 2); } Json::Value sc(Json::objectValue); sc["id"] = std::to_string(devId); sc["path"] = normalized; return BuildFileOpResult(id, sc, u8"\"" + normalized + u8"\" 已存在且确实是目录。", u8"复核时没看到这个目录,或同名条目是文件而不是目录(权限不足、" u8"路径被占用等都会静默失败):\"" + normalized + u8"\"。", w, verified); } // ===== B1:主机库元数据 schema ===== Json::Value BuildHostSetRemarkInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(list_hosts 返回的十进制字符串)。"; props["id"] = idProp; Json::Value remarkProp(Json::objectValue); remarkProp["type"] = "string"; remarkProp["description"] = u8"备注文本(UTF-8);空字符串表示清除备注;GBK 编码后最长 63 字节。"; props["remark"] = remarkProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("remark"); schema["required"] = required; return schema; } Json::Value BuildHostSetRemarkOutputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; props["id"] = idProp; Json::Value remarkProp(Json::objectValue); remarkProp["type"] = "string"; props["remark"] = remarkProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } Json::Value BuildHostSetWatchLevelInputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; idProp["description"] = u8"主机 id(在线或离线历史记录均可)。"; props["id"] = idProp; Json::Value levelProp(Json::objectValue); levelProp["type"] = "integer"; levelProp["minimum"] = 0; levelProp["maximum"] = 3; levelProp["description"] = u8"关注等级:0=无、1=蓝字、2=红字、3=红底(服务端在线列表现色)。"; props["level"] = levelProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; Json::Value required(Json::arrayValue); required.append("id"); required.append("level"); schema["required"] = required; return schema; } Json::Value BuildHostSetWatchLevelOutputSchema() { Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); idProp["type"] = "string"; props["id"] = idProp; Json::Value levelProp(Json::objectValue); levelProp["type"] = "integer"; props["level"] = levelProp; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; return schema; } // ===== N2:批量只读调用(ids[]) ===== // // 只读工具支持一次传多个主机 id(args.ids),服务端逐个调用单机实现并把结果汇总到 // structuredContent.results。写操作工具一律不支持批量(避免一次误操作波及多台)。 // 每个 id 的单机结果仍带各自的 limit/offset/total/hasMore —— 分页是「每台主机各自的」。 static const size_t kBatchMaxIds = 50; // 批量整体时限:50 台 × 单机 20s 最坏能拖到 1000s,远超 MCP 客户端自身的工具超时。 // 到了时限就不再对剩余 id 下发(标 skipped),保证响应在客户端放弃之前返回。 // 注意:时限只在「下一台开始前」检查,正在跑的那一台仍会跑完它自己的超时, // 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。 static const long long kBatchDeadlineMs = 50000; // IsBatchReadOnlyTool 定义在 McpInternal.cpp:tools/list 要用它补 outputSchema, // tools/call 要用它做批量入口判定,两处必须共用同一份清单,故不再在此重复定义。 // ===== 平台门禁:调用前拦掉「该客户端根本没实现」的组合 ===== // // 判据来自各平台客户端对相应 COMMAND_ 的处理实现,不能看「是否引用了常量」: // - 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 会校验两边一致。 // // 这里只做平台级粗筛。能力位门槛(SCREEN_PREVIEW / V2 / C2C_PATHS)仍留在各工具内部, // 因为像「Linux 这台机器有没有 X11 桌面」只有运行时才知道。 enum : uint8_t { kPlatWin = 1, kPlatLnx = 2, kPlatMac = 4, kPlatApk = 8, }; struct ToolPlatform { const char* name; uint8_t mask; }; // mask 为 0 或表里查不到 = 不限制。新增工具忘了登记时按放行处理(宁可漏拦,不可误拒), // 遗漏由 check_platform_table.py 的工具数比对发现。 const ToolPlatform kToolPlatforms[] = { // ---- win+lnx+mac+apk ---- 只读写服务端本地数据,与客户端平台无关 // P1-1:主机列表三合一。旧名保留为别名(不进 tools/list,也不进平台表)。 { "list_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "get_host_detail", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "get_audit_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "get_server_status", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "mcp_list_sessions", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "host_set_remark", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "host_set_watch_level", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, // 生成客户端只在服务端本机写文件,不触达任何主机;平台表按「全平台」登记, // 门禁因入参没有 id 而直接放行(与其它服务端本地工具相同)。 { "build_client", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, // ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输 { "list_processes", kPlatWin|kPlatLnx|kPlatMac }, { "list_files", kPlatWin|kPlatLnx|kPlatMac }, // Android 客户端同样实现了 COMMAND_QUERY_LOG → TOKEN_REPORT_LOG 子连接上报 { "get_client_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "download_file", kPlatWin|kPlatLnx|kPlatMac }, { "read_file", kPlatWin|kPlatLnx|kPlatMac }, { "upload_file", kPlatWin|kPlatLnx|kPlatMac }, // ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项 // Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen // macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW // 的前提是登录时已授予录屏权限),与 Linux 一样回 BGRX 由服务端编码 { "get_screenshot", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, // 窗口信息 RPC 只在 Windows 客户端实现(CLIENT_CAP_WINDOW_INFO) { "get_foreground_window", kPlatWin }, // Android 客户端把注入翻译成触摸手势 / 全局动作(android/.../ControlService.kt), // 剪贴板走 CaptureService.onClipboardText;window_hwnd/region 目标仍只有 Windows 支持 { "remote_open", kPlatWin|kPlatLnx|kPlatApk }, { "remote_close", kPlatWin|kPlatLnx|kPlatApk }, { "remote_keyboard", kPlatWin|kPlatLnx|kPlatApk }, { "remote_mouse", kPlatWin|kPlatLnx|kPlatApk }, { "remote_clipboard", kPlatWin|kPlatLnx|kPlatApk }, // COMMAND_SCREEN_CTRL_ALT_DEL:只有 Android 客户端实现(映射为系统锁屏) { "remote_lock_screen", kPlatApk }, // macOS 客户端同样是完整 PTY(common/PTYHandler.h,zsh/bash),新版声明 // CLIENT_CAP_TERMINAL;老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented, // 工具内部按能力位提前拒绝(McpServer.cpp 的 SupportsTerminal 判定)。 // Android 新版复用 common/PTYHandler.h(/system/bin/sh),同样声明 CLIENT_CAP_TERMINAL { "exec_command", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "terminal_open", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "terminal_exec", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "terminal_close", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, // macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL), // 新版声明 CLIENT_CAP_PROCESS;老构建按能力位提前拒绝。 { "kill_process", kPlatWin|kPlatLnx|kPlatMac }, // http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl)。 // macOS 终端已开放,但这里的 POSIX 命令用了 `base64 -w`(GNU 专有),BSD base64 // 没有这个开关,头和体都会解不出来——等换成两平台通用的折行写法再放行。 // Android 的 toybox 不保证有 curl/base64,故仍只标 win/lnx。 { "http_probe", kPlatWin|kPlatLnx }, // ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action // list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上 // (McpServer.cpp:2931 的 Send2Client),而 Linux/macOS 主循环只处理 COMMAND_SYSTEM // (起 SystemManager 子连接),WSLIST 只在子连接里处理 —— 走不到,实测 Linux 上 // 直接超时 -32001。Windows 是在主循环里处理的(client/KernelManager.cpp:1491)。 // 注意别被 linux/SystemManager.h:38 和 macos/SystemManager.mm:39 的 case 骗到, // 那是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。 { "list_windows", kPlatWin }, // Linux 客户端已实现 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY(linux/LinuxActivityHistory.h, // 有桌面走 X11 窗口采样,无桌面走 last + shell 历史),Android 复用同一套采样机、 // 前台应用由无障碍服务提供,与 Windows 同为主连接 RPC // macOS 是 macos/ActivityHistory.mm(CGWindowList 前台窗口采样,同样主连接一次性快照) { "get_activity_history", kPlatWin|kPlatLnx|kPlatMac|kPlatApk }, { "list_services", kPlatWin }, { "get_keylog", kPlatWin }, { "list_registry", kPlatWin }, { "remote_block_input", kPlatWin|kPlatApk }, // 两端并集。方向性差异由 CollectTargetReqs 精确处理:源端必须 win,目标端 win/lnx/mac { "copy_files_c2c", kPlatWin|kPlatLnx|kPlatMac }, { "operate_window", kPlatWin }, { "control_service", kPlatWin }, { "power_action", kPlatWin }, // TOKEN_UNINSTALL:Windows 客户端一直有该分支;Android 新版映射为系统卸载框 { "uninstall_host", kPlatWin|kPlatApk }, { "search_file", kPlatWin }, { "delete_path", kPlatWin }, { "move_path", kPlatWin }, { "create_folder", kPlatWin }, { "list_network_connections", kPlatWin }, { "kill_network_connection", kPlatWin }, // P2-1:10 个 host_list_* / host_get_hosts_file 合并为 host_inspect。 // 旧名是别名(不进 tools/list,也不进平台表);它们的目标 builder 自己会 // ResolveHost(requireWindows=true),所以别名仍然拿得到 -32005。 { "host_inspect", kPlatWin }, { "host_control_process", kPlatWin }, { "host_control_window", kPlatWin }, { "host_control_service", kPlatWin }, { "host_control_task", kPlatWin }, { "chat_open", kPlatWin|kPlatApk }, { "chat_send", kPlatWin|kPlatApk }, { "chat_wait", kPlatWin|kPlatApk }, { "chat_close", kPlatWin|kPlatApk }, }; // 未知的 clientType 一律按 Windows:EXE/DLL/MEXE/SC/MDLL 都走这个分支, // 将来新增平台在没有明确登记前也不会被误拦。 uint8_t CurrentClientPlatform(context* ctx) { CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE); if (t == "LNX") return kPlatLnx; if (t == "MAC") return kPlatMac; if (t == "APK") return kPlatApk; return kPlatWin; } const char* PlatformName(uint8_t p) { switch (p) { case kPlatLnx: return "lnx"; case kPlatMac: return "mac"; case kPlatApk: return "apk"; default: return "win"; } } std::string PlatformNames(uint8_t mask) { std::string s; if (mask & kPlatWin) s += "win "; if (mask & kPlatLnx) s += "lnx "; if (mask & kPlatMac) s += "mac "; if (mask & kPlatApk) s += "apk "; if (!s.empty()) s.pop_back(); return s; } // 一台主机 + 它在这个工具里被允许的平台集合。 struct TargetReq { uint64_t id; uint8_t mask; }; bool AddIdReq(const Json::Value& args, const char* key, uint8_t mask, std::vector& reqs) { if (!args[key].isString()) return false; const std::string sid = args[key].asString(); if (sid.empty() || sid.find_first_not_of("0123456789") != std::string::npos) return false; reqs.push_back({ strtoull(sid.c_str(), nullptr, 10), mask }); return true; } // 取出这个工具真正要操作的主机,以及每台主机各自的平台要求。 // 绝大多数工具只有一个目标、用统一的 defaultMask;copy_files_c2c 是唯一的 // 非对称工具,源端和目标端的平台要求不同,必须分开查: // src_id —— 只有 Windows 实现了 C2C 发送逻辑(client/KernelManager.cpp) // dst_id —— 只需 CLIENT_CAP_V2 收包,Windows / Linux / macOS 都行 // 反过来 Linux → Windows 不支持:POSIX 客户端没有 C2C_PATHS 发送实现。 // 返回 false = 这个工具不针对某台主机(服务端本地工具),不需要门禁。 bool CollectTargetReqs(const std::string& toolName, const Json::Value& args, uint8_t defaultMask, std::vector& reqs) { // 多主机工具必须先判断:它的 schema 里没有 "id",但调用方可以多塞一个 id 进来。 // 若先走 ParseHostIdArg,就只会检查那一台主机,真正的 src_id / dst_id 反而漏过去。 if (toolName == "copy_files_c2c") { AddIdReq(args, "src_id", kPlatWin, reqs); AddIdReq(args, "dst_id", kPlatWin|kPlatLnx|kPlatMac, reqs); return !reqs.empty(); } uint64_t devId = 0; std::string err; if (!ParseHostIdArg(args, devId, err)) return false; // 无 id:服务端本地工具 reqs.push_back({ devId, defaultMask }); return true; } // 返回空串 = 放行;非空 = 可直接作为 tools/call 结果返回的错误 JSON。 // 主机不存在/离线时跳过该 id,把 -32002 留给工具自己报,避免同一问题出现两种错误码。 std::string CheckToolPlatform(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent) { if (!CMcpServer::Instance().IsPlatformGuardEnabled()) return ""; uint8_t mask = 0; for (const ToolPlatform& e : kToolPlatforms) { if (toolName == e.name) { mask = e.mask; break; } } if (mask == 0) return ""; std::vector reqs; if (!CollectTargetReqs(toolName, args, mask, reqs)) return ""; // 无 id:服务端本地工具 for (const TargetReq& req : reqs) { context* ctx = FindMainContext(parent, req.id); if (!ctx) continue; const uint8_t cur = CurrentClientPlatform(ctx); if (req.mask & cur) continue; CString ct = ctx->GetAdditionalData(RES_CLIENT_TYPE); std::string msg; msg += std::string(u8"该主机平台是 "); msg += PlatformName(cur); msg += std::string(u8"(clientType="); msg += std::string((LPCSTR)ct); msg += std::string(u8"),"); msg += toolName; msg += std::string(u8" 在此主机上仅支持 "); msg += PlatformNames(req.mask); msg += std::string(u8"。按 instructions 第 5 节换用该平台支持的等价工具。"); return BuildError(id, -32005, msg); } return ""; } // 单主机分派:批量路径复用它,保证批量与单机走同一套实现。 std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent); Json::Value MakeBatchErrorEntry(const std::string& hostId, int code, const std::string& msg) { Json::Value entry(Json::objectValue); entry["id"] = hostId; entry["ok"] = false; Json::Value err(Json::objectValue); err["code"] = code; err["message"] = msg; entry["error"] = err; return entry; } // 批量整体时限用尽后,剩余 id 的占位结果:明确标 skipped(未下发), // 与「试过但失败」区分开,避免调用方误以为这些都是主机侧错误。 Json::Value MakeBatchSkippedEntry(const std::string& hostId) { Json::Value entry = MakeBatchErrorEntry(hostId, -32001, "Batch deadline exceeded (" + std::to_string(kBatchDeadlineMs / 1000) + " s): not attempted"); entry["skipped"] = true; return entry; } std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent) { const Json::Value& ids = args["ids"]; if (ids.size() > kBatchMaxIds) { return BuildError(id, -32602, "Too many ids: " + std::to_string(ids.size()) + " (max " + std::to_string(kBatchMaxIds) + " per batch)"); } Json::Value results(Json::arrayValue); int okCount = 0, failCount = 0, skipCount = 0; std::string failLines; const auto batchDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(kBatchDeadlineMs); bool deadlineHit = false; for (const Json::Value& v : ids) { std::string hostId; if (v.isString()) hostId = v.asString(); else if (v.isNumeric()) hostId = std::to_string(v.asUInt64()); if (!IsDigits(hostId)) { results.append(MakeBatchErrorEntry(hostId, -32602, "Invalid id: expected a decimal host id string")); ++failCount; if (failLines.size() < 1200) failLines += "\n - " + (hostId.empty() ? std::string("(empty)") : hostId) + ": Invalid id: expected a decimal host id string"; continue; } // 整体时限:一旦命中,后面所有 id 都不再下发(只记 skipped,不等待)。 if (deadlineHit || std::chrono::steady_clock::now() >= batchDeadline) { deadlineHit = true; results.append(MakeBatchSkippedEntry(hostId)); ++skipCount; continue; } Json::Value oneArgs = args; oneArgs.removeMember("ids"); oneArgs["id"] = hostId; std::string raw = DispatchSingleHostTool(id, toolName, oneArgs, parent); Json::Value parsed; Json::CharReaderBuilder rb; std::string parseErrs; std::istringstream iss(raw); if (!Json::parseFromStream(rb, iss, &parsed, &parseErrs) || !parsed.isObject()) { results.append(MakeBatchErrorEntry(hostId, -32603, "Internal error: failed to parse host result")); ++failCount; continue; } if (parsed.isMember("error")) { Json::Value entry = MakeBatchErrorEntry(hostId, -32603, ""); entry["error"] = parsed["error"]; results.append(entry); ++failCount; std::string msg = JsonStrField(parsed["error"], "message"); if (failLines.size() < 1200) failLines += "\n - " + hostId + ": " + msg; continue; } const Json::Value& r = parsed["result"]; bool isError = r.isMember("isError") && r["isError"].isBool() && r["isError"].asBool(); Json::Value entry(Json::objectValue); entry["id"] = hostId; entry["ok"] = !isError; if (r.isMember("structuredContent")) entry["data"] = r["structuredContent"]; std::string firstText; if (r.isMember("content") && r["content"].isArray() && !r["content"].empty()) firstText = JsonStrField(r["content"][0], "text"); if (!firstText.empty()) entry["text"] = firstText; results.append(entry); if (isError) { ++failCount; if (failLines.size() < 1200) failLines += "\n - " + hostId + ": " + firstText; } else { ++okCount; } } Json::Value structuredContent(Json::objectValue); structuredContent["tool"] = toolName; structuredContent["total"] = (int)ids.size(); structuredContent["succeeded"] = okCount; structuredContent["failed"] = failCount; structuredContent["skipped"] = skipCount; structuredContent["results"] = results; Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"批量调用 ") + toolName + std::string(u8":共 ") + std::to_string(ids.size()) + std::string(u8" 台,成功 ") + std::to_string(okCount) + std::string(u8" 台,失败 ") + std::to_string(failCount) + std::string(u8" 台") + (skipCount > 0 ? std::string(u8",超时跳过 ") + std::to_string(skipCount) + std::string(u8" 台") : std::string()) + std::string(u8"。") + failLines; content.append(item); result["content"] = content; result["isError"] = false; return BuildResult(id, result); } // tools/call 分派 std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) { const Json::Value& id = root["id"]; Json::Value params = root.isMember("params") ? root["params"] : Json::Value(Json::objectValue); std::string toolName; if (params.isObject() && params.isMember("name") && params["name"].isString()) { toolName = params["name"].asString(); } const Json::Value args = GetCallArguments(params); // N2:带 ids[] 即走批量只读路径。 if (args.isObject() && args.isMember("ids") && args["ids"].isArray()) { if (!IsBatchReadOnlyTool(toolName)) { return BuildError(id, -32602, "Batch calls are only supported for read-only tools, and " + toolName + " is not one of them."); } return BuildBatchCall(id, toolName, args, parent); } return DispatchSingleHostTool(id, toolName, args, parent); } std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent) { // 平台门禁:放在所有分派之前,批量路径也会经过这里(BuildBatchCall 循环调用本函数), // 所以不需要在批量入口重复一次。主机不存在/离线时放行,让各工具自己报 -32002。 { std::string platErr = CheckToolPlatform(id, toolName, args, parent); if (!platErr.empty()) return platErr; } // P2-2:两对控制工具合并后的动作路由。tools/list 里随 McpMachine 只出现一套名字, // 但两套名字都能调用:host_control_window 的 close/show 没有主机管理实现,转给主连接版 // operate_window;host_control_service 的 set_auto/set_manual 转给 control_service。 // 两者都先过主机管理总开关(与其它 host_* 一致),旧实现再各自复核 McpManage/McpReadonly。 if (toolName == "host_control_window" || toolName == "host_control_service") { if (!McpServer().IsMachineEnabled()) return BuildError(id, -32006, "Host management tools are disabled (set McpMachine=1 to enable)"); std::string action = ToLowerAscii(Trim(GetStringArg(args, "action"))); if (toolName == "host_control_window" && (action == "close" || action == "show")) return BuildOperateWindow(id, args, parent); if (toolName == "host_control_service") { if (action == "set_auto" || action == "set_manual") { // control_service 不支持 dry_run:与其假装试运行,不如明确拒绝。 if (args.isMember("dry_run")) { if (!args["dry_run"].isBool()) return BuildError(id, -32602, "dry_run must be a boolean"); if (args["dry_run"].asBool()) return BuildError(id, -32602, "dry_run is not supported for set_auto/set_manual"); } Json::Value a(args); if (!a.isMember("service_name") && a.isMember("name")) a["service_name"] = args["name"]; return BuildControlService(id, a, parent); } // 旧的 control_service 参数名 service_name 在这里同样可用。 if (!args.isMember("name") && args.isMember("service_name")) { Json::Value a(args); a["name"] = args["service_name"]; return McpMachine::Call(id, toolName, a, parent); } } } // P8:连接管理 / 主机管理工具族(独立分发;门控在 McpMachine::Call 内复核)。 if (McpMachine::Handles(toolName)) return McpMachine::Call(id, toolName, args, parent); // P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。 if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent); // 生成客户端(独立开关 McpBuild + !McpReadonly;门控在 Call 内复核)。 if (McpBuildClient::Handles(toolName)) return McpBuildClient::Call(id, toolName, args, parent); // P1-1:list_hosts 与三个旧别名共用一个 handler;list_all_hosts 默认为「在线 + 离线」。 if (toolName == "list_hosts") return BuildListHosts(id, args, parent, false); if (toolName == "list_online_hosts") return BuildListHosts(id, args, parent, false); if (toolName == "search_hosts") return BuildListHosts(id, args, parent, false); if (toolName == "list_all_hosts") return BuildListHosts(id, args, parent, true); if (toolName == "get_host_detail") return BuildGetHostDetail(id, args, parent); if (toolName == "list_processes") return BuildListProcesses(id, args, parent); if (toolName == "list_windows") return BuildListWindows(id, args, parent); if (toolName == "get_activity_history") return BuildGetActivityHistory(id, args, parent); if (toolName == "get_screenshot") return BuildGetScreenshot(id, args, parent); if (toolName == "get_foreground_window") return BuildGetForegroundWindow(id, args, parent); if (toolName == "list_files") return BuildListFiles(id, args, parent); if (toolName == "list_services") return BuildListServices(id, args, parent); if (toolName == "get_client_log") return BuildGetClientLog(id, args, parent); if (toolName == "get_keylog") return BuildGetKeylog(id, args, parent); if (toolName == "get_audit_log") return BuildGetAuditLog(id, args, parent); if (toolName == "get_server_status") return BuildGetServerStatus(id, parent); // P11:服务端自身会话的观测 / 取消(无主机、纯本地;不受功能开关与只读限制)。 if (toolName == "mcp_list_sessions") return BuildMcpListSessions(id, args); if (toolName == "mcp_cancel_session") return BuildMcpCancelSession(id, args); if (toolName == "list_registry") return BuildListRegistry(id, args, parent); if (toolName == "exec_command") return BuildExecCommand(id, args, parent); if (toolName == "terminal_open") return BuildTerminalOpen(id, args, parent); if (toolName == "terminal_exec") return BuildTerminalExec(id, args, parent); if (toolName == "terminal_close") return BuildTerminalClose(id, args, parent); if (toolName == "remote_open") return BuildRemoteOpen(id, args, parent); if (toolName == "remote_close") return BuildRemoteClose(id, args, parent); if (toolName == "remote_keyboard") return BuildRemoteKeyboard(id, args, parent); if (toolName == "remote_mouse") return BuildRemoteMouse(id, args, parent); if (toolName == "remote_clipboard") return BuildRemoteClipboard(id, args, parent); if (toolName == "remote_lock_screen") return BuildRemoteLockScreen(id, args, parent); if (toolName == "remote_block_input") return BuildRemoteBlockInput(id, args, parent); if (toolName == "download_file") return BuildDownloadFile(id, args, parent); if (toolName == "read_file") return BuildReadFile(id, args, parent); if (toolName == "http_probe") return BuildHttpProbe(id, args, parent); if (toolName == "upload_file") return BuildUploadFile(id, args, parent); if (toolName == "copy_files_c2c") return BuildCopyFilesC2C(id, args, parent); if (toolName == "kill_process") return BuildKillProcess(id, args, parent); if (toolName == "operate_window") return BuildOperateWindow(id, args, parent); if (toolName == "control_service") return BuildControlService(id, args, parent); if (toolName == "power_action") return BuildPowerAction(id, args, parent); if (toolName == "uninstall_host") return BuildUninstallHost(id, args, parent); if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent); if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent); if (toolName == "search_file") return BuildSearchFile(id, args, parent); if (toolName == "delete_path") return BuildDeletePath(id, args, parent); if (toolName == "move_path") return BuildMovePath(id, args, parent); if (toolName == "create_folder") return BuildCreateFolder(id, args, parent); return BuildError(id, -32602, "Unknown tool: " + (toolName.empty() ? std::string("(empty)") : toolName)); } } // namespace // ===== P3:exec_command 哨兵检测与终端会话 ===== // 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。哨兵后紧跟退出码数字(可带负号)。 // // ConPTY 会把输入整行回显进输出流,因此「哨兵必须独占行首」这条旧规则反而会把真实哨兵 // 排除掉(命令最后一行没有换行时哨兵会接在其后),再往前命中回显里的 &&/|| 片段,得到 // 错误的退出码(评审 P3,`ver` → exit_code=1)。现在两种哨兵形态都能安全地不依赖行首: // - 新形态(ConPTY):回显文本里是字面 "%errorlevel%",不是数字,天然不可能命中; // - 老形态(非 PTY):回显由客户端按写入长度跳过,且回显中的片段在真实哨兵之前。 // 故从后往前找第一个「标记 + 数字」即可。 static bool FindSentinel(const std::vector& buf, const std::string& nonce, size_t& pos, int& exitCode) { std::string marker = "__MCP_DONE_" + nonce + "__"; if (marker.size() + 1 > buf.size()) return false; std::string s((const char*)buf.data(), buf.size()); size_t from = std::string::npos; while (true) { size_t p = s.rfind(marker, from); if (p == std::string::npos) return false; size_t q = p + marker.size(); bool neg = false; if (q < s.size() && s[q] == '-') { neg = true; ++q; } size_t digits = q; long long v = 0; while (q < s.size() && s[q] >= '0' && s[q] <= '9' && q - digits < 9) { v = v * 10 + (s[q] - '0'); ++q; } if (q > digits) { exitCode = (int)(neg ? -v : v); pos = p; return true; } if (p == 0) return false; from = p - 1; } } bool CMcpServer::IsTermPending(uint64_t device_id) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); return it != m_TermSessions.end() && !it->second.started; } void CMcpServer::RegisterTerminalContext(uint64_t device_id, context* subCtx, bool isPty) { { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end() || it->second.started) return; // 没有等它的会话 TermSession& s = it->second; s.started = true; s.subCtx = subCtx; s.isPty = isPty; m_TermContextToDevice[subCtx] = device_id; } // 关键步骤:告知客户端「启动 shell 输出回流」。客户端读线程靠 COMMAND_NEXT 才启动, // 漏发会导致 shell 在跑但输出永不送回。PTY 还要先告知初始 80x24,否则 TUI 尺寸错乱。 if (isPty) { BYTE resizeBuf[5]; resizeBuf[0] = CMD_TERMINAL_RESIZE; *(short*)(resizeBuf + 1) = (short)80; *(short*)(resizeBuf + 3) = (short)24; subCtx->Send2Client(resizeBuf, 5); } BYTE startCmd = COMMAND_NEXT; subCtx->Send2Client(&startCmd, 1); m_TermCv.notify_all(); } bool CMcpServer::IsTerminalContext(context* subCtx) { std::lock_guard lk(m_TermMutex); return m_TermContextToDevice.find(subCtx) != m_TermContextToDevice.end(); } bool CMcpServer::IsTermSubCtxLive(uint64_t device_id, const std::string& sessionId, context* subCtx) { if (!subCtx) return false; std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return false; const TermSession& s = it->second; // OnTerminalClosed 置 closed 的同时把 subCtx 置空:closed 即「这个指针已交还连接池」。 if (s.closed || s.subCtx != subCtx) return false; if (!sessionId.empty() && (!s.persistent || s.sessionId != sessionId)) return false; return true; } void CMcpServer::OnTerminalData(context* subCtx, const BYTE* data, ULONG len) { std::lock_guard lk(m_TermMutex); auto it = m_TermContextToDevice.find(subCtx); if (it == m_TermContextToDevice.end()) return; auto sit = m_TermSessions.find(it->second); if (sit == m_TermSessions.end()) return; TermSession& s = sit->second; if (s.done || s.closed) return; // 已结束,忽略迟到数据 s.data.insert(s.data.end(), data, data + len); // 硬上限(P0-2):轮询设计下命令输出可能堆到 MB 级。超限时丢弃最旧字节(含未交付的), // delivered/sentPos 同步前移,丢弃量如实记进 droppedBytes。哨兵在尾部,不受丢弃影响。 if ((int)s.data.size() > kTermMaxDataBytes) { size_t excess = s.data.size() - (size_t)kTermMaxDataBytes; s.data.erase(s.data.begin(), s.data.begin() + excess); s.droppedBytes += excess; s.delivered = s.delivered > excess ? s.delivered - excess : 0; s.sentPos = s.sentPos > excess ? s.sentPos - excess : 0; } // 第一屏输出到达 = shell 已接管终端(见 WaitTerminalBootstrap)。BeginTermCommand 会清 // data,故就绪态需要单独记一个旗标,跨命令保持。 s.sawOutput = true; if (FindSentinel(s.data, s.nonce, s.sentPos, s.exitCode)) { s.done = true; } m_TermCv.notify_all(); // 唤醒 WaitTerminalBootstrap / WaitTerminalDone } void CMcpServer::OnTerminalClosed(context* subCtx) { std::lock_guard lk(m_TermMutex); auto it = m_TermContextToDevice.find(subCtx); if (it == m_TermContextToDevice.end()) return; auto sit = m_TermSessions.find(it->second); if (sit == m_TermSessions.end()) return; TermSession& s = sit->second; // 子连接已断,OfflineProc 随后会把它归还连接池:会话里不能再留这个指针,否则等待线程 // 醒来(或后续轮询)会对已回收、甚至已被新连接复用的 context 误 CancelIO;路由也必须 // 立刻摘掉,否则迟到的清理会按旧指针误删新连接的表项。 m_TermContextToDevice.erase(it); s.subCtx = nullptr; s.closed = true; if (s.persistent && !s.busy && s.started) { // 空闲持久会话:shell 已退、无等待线程会清理,直接擦会话(子连接已死,无需 CancelIO)。 m_TermSessions.erase(sit); } m_TermCv.notify_all(); // busy 场景唤醒等待线程交付剩余输出后由其清理;一次性 exec 路径不变 } bool CMcpServer::BeginTermPending(uint64_t device_id, const std::string& command, const std::string& nonce) { std::lock_guard lk(m_TermMutex); if (m_TermSessions.find(device_id) != m_TermSessions.end()) return false; // 已有会话 TermSession s; s.command = command; s.nonce = nonce; m_TermSessions[device_id] = std::move(s); return true; } bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& isPty, int timeoutMs) { std::unique_lock lk(m_TermMutex); // 谓词每次重新查表:等待期间 OnTerminalClosed(子连接断开)可能擦会话或置 closed, // 缓存的迭代器会悬空。会话消失也算「结束等待」,由下面统一判失败。 auto ready = [&] { auto jt = m_TermSessions.find(device_id); return jt == m_TermSessions.end() || jt->second.started || jt->second.closed; }; bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), ready); auto it = m_TermSessions.find(device_id); if (!signaled || it == m_TermSessions.end() || !it->second.started || it->second.closed || !it->second.subCtx) { // 放弃:迟到的 shell 子连接就绪包(TOKEN_SHELL_START/TOKEN_TERMINAL_START)不能弹终端窗口。 // 失败原因可能是超时,也可能是子连接刚建立就断开(OnTerminalClosed 已置空 subCtx): // 绝不能把空指针或已回收的 context 交给调用方。 MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SHELL_START, (BYTE)TOKEN_TERMINAL_START }); if (it != m_TermSessions.end()) { // 会话要么未就绪、要么子连接已断,都不可再用;清理掉避免占着该主机的终端槽。 if (it->second.subCtx) m_TermContextToDevice.erase(it->second.subCtx); m_TermSessions.erase(it); } return false; } subCtx = it->second.subCtx; isPty = it->second.isPty; 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); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) { closed = true; // 会话已不在(被取消/回收):子连接去向未知,调用方不能再去碰这个指针 return false; } bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), [&] { return it->second.done || it->second.closed; }); if (!signaled) { // 超时/取消 → 清理(含路由表) closed = it->second.closed; // 照实回报:closed 时子连接指针已置空、可能已被连接池复用 if (it->second.subCtx) m_TermContextToDevice.erase(it->second.subCtx); m_TermSessions.erase(it); return false; } TermSession s = it->second; // 拷贝出,避免擦除后悬空 m_TermContextToDevice.erase(s.subCtx); m_TermSessions.erase(it); closed = s.closed; exitCode = s.exitCode; if (s.done && s.sentPos <= s.data.size()) out.assign(s.data.begin(), s.data.begin() + s.sentPos); // 截断到哨兵前 else out = s.data; // 进程退出无哨兵:返回已收集的原始输出 return true; } void CMcpServer::ClearTermPending(uint64_t device_id) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it != m_TermSessions.end()) m_TermSessions.erase(it); } // ===== P4:持久远程终端(状态机方法)===== bool CMcpServer::BeginTermOpen(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_TermMutex); if (m_TermSessions.find(device_id) != m_TermSessions.end()) return false; // 单设备单终端 TermSession s; s.sessionId = sessionId; s.persistent = true; s.lastActiveAt = time(nullptr); m_TermSessions[device_id] = std::move(s); return true; } int CMcpServer::OpenOrReuseTermSession(uint64_t device_id, std::string& sessionId, bool& reused) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it != m_TermSessions.end()) { TermSession& s = it->second; // 已有一条在用的持久会话:直接复用(忙不忙由 BeginTermCommand 判断)。 if (s.persistent && s.started && !s.closed) { sessionId = s.sessionId; reused = true; return 0; } // 有 open 正在建立 / 一次性 exec_command 在跑:单设备单终端,报忙。 return 2; } TermSession s; s.sessionId = GenerateRandomToken(); s.persistent = true; s.lastActiveAt = time(nullptr); sessionId = s.sessionId; m_TermSessions[device_id] = std::move(s); reused = false; return 0; } int CMcpServer::ReuseTermSession(uint64_t device_id, std::string& sessionId, bool& isPty) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return 2; TermSession& s = it->second; if (!s.persistent || !s.started || s.closed) return 2; sessionId = s.sessionId; isPty = s.isPty; return 0; } // 墓碑:记下会话被销毁的原因,供后续 terminal_exec 给出可区分文案。 // 调用方必须持有 m_TermMutex。会话不存在时记录是为了让「上一次超时后用户重试」能看懂。 void CMcpServer::MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId, const std::string& reason) { if (sessionId.empty()) return; TermDestroyedInfo info; info.sessionId = sessionId; info.reason = reason; info.expiry = std::chrono::steady_clock::now() + std::chrono::seconds(kTermTombstoneSec); m_TermDestroyed[device_id] = std::move(info); // 顺手清理过期项(条目极少,线性清一遍即可) auto now = std::chrono::steady_clock::now(); for (auto it = m_TermDestroyed.begin(); it != m_TermDestroyed.end(); ) { if (it->second.expiry <= now) it = m_TermDestroyed.erase(it); else ++it; } } std::string CMcpServer::DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_TermMutex); auto it = m_TermDestroyed.find(device_id); if (it == m_TermDestroyed.end()) return ""; if (std::chrono::steady_clock::now() >= it->second.expiry) { m_TermDestroyed.erase(it); return ""; } if (it->second.sessionId != sessionId) return ""; // 是「id 写错」,不是「已销毁」 return it->second.reason; } int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId, const std::string& command, const std::string& nonce, context*& subCtx, bool& isPty) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return 1; // 不存在(含已销毁) TermSession& s = it->second; if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配 if (!s.started) return 3; // 未就绪 if (s.closed) return 5; // 已关闭 // 上一条命令已结束但输出还没取完:data 即将被清空,必须先轮询取走,否则静默丢输出。 // 这个状态同时满足 busy(取完才复位),所以必须排在 busy 之前,否则会误报「另一条命令在跑」。 if (s.done && s.delivered < s.sentPos) return 6; if (s.busy) return 4; // 已有命令在飞 s.busy = true; s.busySince = std::chrono::steady_clock::now(); s.command = command; s.nonce = nonce; s.data.clear(); s.sentPos = 0; s.delivered = 0; s.droppedBytes = 0; s.exitCode = -1; s.done = false; s.closed = false; s.lastActiveAt = time(nullptr); subCtx = s.subCtx; isPty = s.isPty; return 0; } int CMcpServer::PeekTermSession(uint64_t device_id, const std::string& sessionId, bool& isPty) { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return 1; TermSession& s = it->second; if (!s.persistent || s.sessionId != sessionId) return 2; if (!s.started) return 3; if (s.closed) return 5; if (s.done && s.delivered < s.sentPos) return 6; // 与 BeginTermCommand 的顺序保持一致 if (s.busy) return 4; isPty = s.isPty; return 0; } // 交付窗口的截断点:优先回退到窗口内最后一个换行——UTF-8 与 GBK 的换行字节都不会出现在 // 多字节字符内部,按行截断既不会切坏编码,模型读起来也完整。4KB 内找不到换行就直接硬切。 static size_t ChooseDeliverEnd(const std::vector& data, size_t start, size_t end) { if (end <= start) return end; size_t floorPos = end > start + 4096 ? end - 4096 : start; for (size_t i = end; i > floorPos; --i) if (data[i - 1] == '\n') return i; return end; } int CMcpServer::WaitTermCommand(uint64_t device_id, const std::string& sessionId, std::vector& out, bool& done, int& exitCode, bool& closed, bool& truncated, size_t& droppedBytes, bool& isPty, std::string& nonce, int maxOutputBytes, int timeoutMs, bool pollMode) { std::unique_lock lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return 3; if (!it->second.persistent) return 3; if (it->second.sessionId != sessionId) return 4; if (!it->second.started) return 3; if (pollMode && !it->second.busy && !it->second.done && !it->second.closed) return 7; // 没有在跑的命令:轮询只会空等到超时,直接告诉调用方用错 isPty = it->second.isPty; nonce = it->second.nonce; ++it->second.waiters; // terminal_close 靠它判断 closed 之后有没有人负责收尾 // 谓词每次都重新查表:等待期间会话可能被 terminal_close / busy 兜底回收擦掉。 const std::string sid = sessionId; auto ended = [&] { auto jt = m_TermSessions.find(device_id); if (jt == m_TermSessions.end() || jt->second.sessionId != sid) return true; return jt->second.done || jt->second.closed; }; bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), ended); it = m_TermSessions.find(device_id); if (it == m_TermSessions.end() || it->second.sessionId != sid) { // 等待期间会话被销毁(关闭 / 长时间在飞的兜底回收);墓碑里有原因。 done = true; closed = true; exitCode = -1; return 3; } TermSession& s = it->second; if (!signaled && McpCallCancelled()) { // 取消:处理线程已经走了,不会再有人来轮询,照旧销毁(shell 一并结束)。 context* subCtx = s.subCtx; MarkTermDestroyedLocked(device_id, s.sessionId, "Terminal session was destroyed because the request was cancelled; call terminal_open again"); if (subCtx) m_TermContextToDevice.erase(subCtx); m_TermSessions.erase(it); lk.unlock(); if (subCtx) subCtx->CancelIO(); return 2; } closed = s.closed; done = s.done || s.closed; droppedBytes = s.droppedBytes; // 交付窗口:done 时截止到哨兵(不含哨兵),否则到当前缓冲末尾。 size_t end = s.data.size(); if (s.done && s.sentPos <= s.data.size()) end = s.sentPos; if (s.delivered > end) s.delivered = end; // 防御:游标只前进不后退 size_t deliverEnd = end; if (end - s.delivered > (size_t)maxOutputBytes) { deliverEnd = s.delivered + (size_t)maxOutputBytes; deliverEnd = ChooseDeliverEnd(s.data, s.delivered, deliverEnd); truncated = true; } out.assign(s.data.begin() + s.delivered, s.data.begin() + deliverEnd); s.delivered = deliverEnd; if (s.closed) { // shell 进程退出(或运行中被 terminal_close)→ 交付剩余输出后清理会话+路由 if (s.delivered < end) { // 本块被 maxOutputBytes 截断:会话与缓冲都保留(已 closed,pollMode 仍允许继续调用), // 由后续轮询把尾巴取完再清理。若在这里直接擦会话,未交付的输出会静默丢失。 // 但远端 shell 必须现在就结束(terminal_close 场景),否则它会一直跑到 1 小时兜底; // 缓冲已收在 s.data 里,CancelIO 不影响后续轮询。 context* subCtx = s.subCtx; if (subCtx) { m_TermContextToDevice.erase(subCtx); s.subCtx = nullptr; } --s.waiters; if (subCtx) { lk.unlock(); subCtx->CancelIO(); } return 0; } context* subCtx = s.subCtx; exitCode = -1; MarkTermDestroyedLocked(device_id, s.sessionId, "Terminal session ended: the shell process exited; call terminal_open again"); if (subCtx) m_TermContextToDevice.erase(subCtx); m_TermSessions.erase(it); if (subCtx) { lk.unlock(); subCtx->CancelIO(); // 对称注销:已退出的子连接无害,运行中被 close 的由这里结束 shell } return 0; } if (s.done) { // 哨兵命中:输出取完才复位 busy,否则下一条命令会清掉未交付的输出 exitCode = s.exitCode; if (s.delivered >= end) { s.busy = false; s.lastActiveAt = time(nullptr); // idle 语义是「距上次活动」,避免刚完成就被回收 } --s.waiters; return 0; } // 超时:命令仍在远端运行。会话保持 busy、不销毁,调用方继续轮询(P0-2)。 s.lastActiveAt = time(nullptr); --s.waiters; return 1; } int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionId) { context* subCtx = nullptr; { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return 1; // 不存在(幂等) TermSession& s = it->second; if (!s.persistent || s.sessionId != sessionId) return 2; // token 不匹配 if (s.busy && s.waiters > 0) { // 有等待线程:置 closed 唤醒它,由其交付剩余输出后清理(避免双重擦除)。 s.closed = true; MarkTermDestroyedLocked(device_id, sessionId, "Terminal session was closed by terminal_close while a command was running"); m_TermCv.notify_all(); return 0; } // 空闲,或 busy 但已无等待线程(调用方超时走人,只可能靠轮询):立刻收尾。 // 后者若沿用「置 closed 等别人清理」,远端 shell 会一直跑到 1 小时 busy 兜底, // 期间该主机的终端全部返回 busy。 subCtx = s.subCtx; MarkTermDestroyedLocked(device_id, sessionId, s.busy ? "Terminal session was closed by terminal_close while a command was running" : "Terminal session was closed by terminal_close"); if (subCtx) m_TermContextToDevice.erase(subCtx); m_TermSessions.erase(it); } if (subCtx) subCtx->CancelIO(); // 锁外取消 IO,触发客户端 shell 退出 return 0; } int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) { time_t now = time(nullptr); std::vector toCancel; { std::lock_guard lk(m_TermMutex); const auto steadyNow = std::chrono::steady_clock::now(); for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) { TermSession& s = it->second; // started 条件不能省:尚未 START 的会话可能正被 WaitTerminalReady 等着, // 回收它会把自己的新会话暴露给等待线程(抢到/被误删),等它自己的超时分支清理。 const bool idle = s.persistent && s.started && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec; // busy 兜底(P0-2):超时轮询下会话一直 busy,调用方若再也不回来,该主机的终端槽 // 会永远返回 -32003。跑满 1 小时强制回收(等待函数会重新查表,不会悬空)。 const bool overdue = s.persistent && s.busy && steadyNow - s.busySince > std::chrono::seconds(kTermBusyMaxSec); if (idle || overdue) { if (s.subCtx) { m_TermContextToDevice.erase(s.subCtx); toCancel.push_back(s.subCtx); } MarkTermDestroyedLocked(it->first, s.sessionId, overdue ? "Terminal session was reclaimed after the command ran longer than " + std::to_string(kTermBusyMaxSec) + "s; call terminal_open again" : "Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec) + "s of inactivity; call terminal_open again"); it = m_TermSessions.erase(it); } else { ++it; } } } for (context* c : toCancel) if (c) c->CancelIO(); // 锁外 CancelIO return (int)toCancel.size(); } // ===== P5:MCP 远程控制(状态机方法)===== bool CMcpServer::IsScreenCtrlContext(context* subCtx) { std::lock_guard lk(m_ScreenCtrlMutex); return m_ScreenCtrlContextToDevice.find(subCtx) != m_ScreenCtrlContextToDevice.end(); } bool CMcpServer::BeginScreenCtrlOpen(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_ScreenCtrlMutex); if (m_ScreenCtrlSessions.find(device_id) != m_ScreenCtrlSessions.end()) return false; // 单设备单会话 ScreenCtrlSession s; s.sessionId = sessionId; s.lastActiveAt = time(nullptr); m_ScreenCtrlSessions[device_id] = std::move(s); // 双向互斥(方向二):标记该设备屏幕子连接归 MCP 会话独占,人类 Web 观看期间被拒绝 // (HandleConnect 查 IsMcpTriggered)。会话擦除点(CloseScreenCtrlSession / // SweepIdleScreenCtrl / OnScreenControlClosed / EndScreenCtrlAction)同步 ClearMcpTriggered。 WebService().SetMcpTriggered(device_id); return true; } bool CMcpServer::MarkScreenCtrlReady(uint64_t device_id, const std::string& sessionId, context* subCtx, int screenW, int screenH, bool targeted) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it == m_ScreenCtrlSessions.end() || it->second.sessionId != sessionId) return false; ScreenCtrlSession& s = it->second; s.subCtx = subCtx; s.started = true; s.screenW = screenW; s.screenH = screenH; s.targeted = targeted; s.lastActiveAt = time(nullptr); m_ScreenCtrlContextToDevice[subCtx] = device_id; return true; } bool CMcpServer::IsScreenCtrlTargeted(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it == m_ScreenCtrlSessions.end() || it->second.sessionId != sessionId) return false; return it->second.targeted; } int CMcpServer::CloseScreenCtrlSession(uint64_t device_id, const std::string& sessionId) { context* unblockCtx = nullptr; int rc = 1; { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it != m_ScreenCtrlSessions.end()) { if (it->second.sessionId != sessionId) { rc = 2; // token 不匹配 } else { rc = 0; ScreenCtrlSession& s = it->second; // 关会话前必须解除键鼠锁定:子连接一断,服务端就再没有下发通道, // 客户端进程还活着的话人会被锁在电脑外(P10-C)。 if (s.inputBlocked && s.subCtx) unblockCtx = s.subCtx; if (s.busy) { // 注入在飞:置 closed 交注入线程收尾,避免与注入并发擦会话(镜像终端 busy 模式)。 s.closed = true; } else { if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx); m_ScreenCtrlSessions.erase(it); WebService().ClearMcpTriggered(device_id); } } } } // 锁外发(Send2Client 持该上下文的 SendLock,不在 MCP 锁内做 socket 发送)。 if (unblockCtx) SendScreenBlockInput(unblockCtx, false); return rc; } int CMcpServer::SweepIdleScreenCtrl(time_t idleTimeoutSec) { time_t now = time(nullptr); std::vector toClose; struct Blocked { uint64_t devId; std::string sessionId; context* subCtx; }; std::vector toUnblock; { std::lock_guard lk(m_ScreenCtrlMutex); for (auto it = m_ScreenCtrlSessions.begin(); it != m_ScreenCtrlSessions.end(); ) { ScreenCtrlSession& s = it->second; if (!s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) { // 回收前强制解除键鼠锁定(P10-C):下面就要关子连接了,之后无从下发。 if (s.inputBlocked && s.subCtx) toUnblock.push_back({ it->first, s.sessionId, s.subCtx }); if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx); uint64_t devId = it->first; toClose.push_back(devId); it = m_ScreenCtrlSessions.erase(it); WebService().ClearMcpTriggered(devId); // 锁内清除,避免与并发 remote_open 竞态 } else { ++it; } } } // 锁外解锁,且必须排在关对话框之前:先让客户端丢掉锁定,再拆子连接。 for (const Blocked& b : toUnblock) { SendScreenBlockInput(b.subCtx, false); // 审计(不可关闭):闲置回收顺带解了锁,人类看不到这一步,必须留痕。 if (m_parent) { std::string audit = "host " + std::to_string(b.devId) + " remote-block-input: session " + b.sessionId + " input lock forced off by idle reclaim"; m_parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } } // 锁外关闭隐藏对话框(WM_CLOSE → CScreenSpyDlg 析构 → UnregisterScreenContext)。 for (uint64_t devId : toClose) { if (m_parent) m_parent->CloseWebRemoteDesktopByClientID(devId); WebService().ClearWebTriggered(devId); } return (int)toClose.size(); } void CMcpServer::OnScreenControlClosed(context* subCtx) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlContextToDevice.find(subCtx); if (it == m_ScreenCtrlContextToDevice.end()) return; auto sit = m_ScreenCtrlSessions.find(it->second); if (sit == m_ScreenCtrlSessions.end()) { // 路由在但会话已擦(防御) m_ScreenCtrlContextToDevice.erase(it); return; } if (sit->second.busy) { // 注入在飞:不擦会话(注入线程仍持 subCtx),仅置 closed,由 EndScreenCtrlAction 收尾。 sit->second.closed = true; } else { uint64_t devId = it->second; m_ScreenCtrlSessions.erase(sit); m_ScreenCtrlContextToDevice.erase(it); WebService().ClearMcpTriggered(devId); } } int CMcpServer::BeginScreenCtrlAction(uint64_t device_id, const std::string& sessionId, context*& subCtx, int& screenW, int& screenH) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it == m_ScreenCtrlSessions.end()) return 1; // 会话不存在 ScreenCtrlSession& s = it->second; if (s.sessionId != sessionId) return 1; // token 不匹配 if (!s.started) return 1; // 未就绪 if (s.busy) return 2; // 已有注入在飞 if (s.closed) return 1; // 子连接已断 s.busy = true; s.lastActiveAt = time(nullptr); subCtx = s.subCtx; screenW = s.screenW; screenH = s.screenH; return 0; } void CMcpServer::EndScreenCtrlAction(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it == m_ScreenCtrlSessions.end()) return; if (it->second.sessionId != sessionId) return; it->second.busy = false; it->second.lastActiveAt = time(nullptr); if (it->second.closed) { // 注入期间子连接已断:擦会话+路由 if (it->second.subCtx) m_ScreenCtrlContextToDevice.erase(it->second.subCtx); m_ScreenCtrlSessions.erase(it); WebService().ClearMcpTriggered(device_id); } } // ===== P10-C:键鼠锁定的状态维护与自动解除 ===== bool CMcpServer::ScreenCtrlSetBlock(uint64_t device_id, const std::string& sessionId, bool block, int maxBlockMs, bool& autoUnblocked) { autoUnblocked = false; std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it == m_ScreenCtrlSessions.end() || it->second.sessionId != sessionId) return false; ScreenCtrlSession& s = it->second; // 上一次锁定被看门狗自动解除的通知:随本次结果取走(每条 remote_block_input 都能看到)。 autoUnblocked = s.blockAutoReleased; s.blockAutoReleased = false; s.inputBlocked = block; s.blockUntil = block ? std::chrono::steady_clock::now() + std::chrono::milliseconds(maxBlockMs) : std::chrono::steady_clock::time_point{}; return true; } bool CMcpServer::IsScreenCtrlBlocked(uint64_t device_id, const std::string& sessionId) { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); return it != m_ScreenCtrlSessions.end() && it->second.sessionId == sessionId && it->second.inputBlocked; } // 扫一遍会话,把超过 blockUntil 的锁定解除。busy 的会话本轮跳过(下一轮再试,注入都很短); // 发送失败(多半是子连接已断)时保持锁定并把期限推后 5 秒,避免每 500ms 空转打已死的连接。 void CMcpServer::WatchdogScreenBlock() { struct Hit { uint64_t devId; std::string sessionId; context* subCtx; }; std::vector hits; { std::lock_guard lk(m_ScreenCtrlMutex); auto now = std::chrono::steady_clock::now(); for (auto& kv : m_ScreenCtrlSessions) { ScreenCtrlSession& s = kv.second; if (!s.inputBlocked || s.busy || s.closed || !s.started || !s.subCtx) continue; if (now < s.blockUntil) continue; s.busy = true; // 占位:注入 / close 会等这次解锁收尾 s.lastActiveAt = time(nullptr); hits.push_back({ kv.first, s.sessionId, s.subCtx }); } } for (const Hit& h : hits) { const bool ok = SendScreenBlockInput(h.subCtx, false); // 锁外发送 bool erased = false; { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(h.devId); if (it != m_ScreenCtrlSessions.end() && it->second.sessionId == h.sessionId) { ScreenCtrlSession& s = it->second; if (ok) { s.inputBlocked = false; s.blockAutoReleased = true; // 等下一次 remote_block_input 上报 s.blockUntil = std::chrono::steady_clock::time_point{}; } else { s.blockUntil = std::chrono::steady_clock::now() + std::chrono::seconds(5); } s.busy = false; s.lastActiveAt = time(nullptr); if (s.closed) { // 占位期间子连接断了:擦会话(镜像 EndScreenCtrlAction) if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx); m_ScreenCtrlSessions.erase(it); WebService().ClearMcpTriggered(h.devId); erased = true; } } } // 审计(不可关闭):自动解除是人类看不见的安全事件,必须留痕。 if (ok && !erased && m_parent) { std::string audit = "host " + std::to_string(h.devId) + " remote-block-input: session " + h.sessionId + " auto-unblocked (max_block_ms elapsed)"; m_parent->PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(ToAnsi(audit, 936).c_str()), (LPARAM)new CString(_TR("MCP远程控制"))); } } } void CMcpServer::BlockWatchdogLoop() { // 100ms 切片:Stop 时最多等一个切片,不拖慢退出。 while (!m_blockStop.load()) { for (int i = 0; i < 5 && !m_blockStop.load(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(100)); if (m_blockStop.load()) break; WatchdogScreenBlock(); } } ////////////////////////////////////////////////////////////////////////// // CMcpServer Implementation ////////////////////////////////////////////////////////////////////////// CMcpServer& CMcpServer::Instance() { static CMcpServer instance; return instance; } CMcpServer::CMcpServer() { m_server.Post("/mcp", [this](const httplib::Request& req, httplib::Response& res) { HandleMcp(req, res); }); } CMcpServer::~CMcpServer() { Stop(); // 兜底:确保监听线程 join,避免 std::thread 析构触发 terminate } bool CMcpServer::Start(const std::string& bind, int port) { if (m_running.load()) return true; // 已在运行 // ===== 传输层加固(A1)===== // httplib 默认:请求体不限长(SIZE_MAX)、读写超时各 5s、线程池 max(8, 核数-1)。 // 1) 请求体上限 2 MB:本服务只收 JSON-RPC 参数(文件内容走子连接分块,不进 HTTP body), // 2 MB 足够 chat_send(4 KB)/remote_clipboard 文本,又能挡住超大 body 打爆内存。 // 2) 读超时 15s:经 frp 隧道上传参数时单次 recv 不至于 5s 就被掐断。 // 3) 写超时 60s:get_screenshot 的大图 base64 或慢链路下,5s 会把半个响应写断。 // 4) 线程池显式 32:chat_wait(最长 55s)/批量只读会长时间占线程,默认 8~15 个不够; // 每个线程约 1 MB 栈,32 个约 32 MB,可接受。 m_server.set_payload_max_length(2 * 1024 * 1024); m_server.set_read_timeout(15, 0); m_server.set_write_timeout(60, 0); m_server.new_task_queue = []() { return new httplib::ThreadPool(32); }; m_bind = bind; m_port = port; // HTTPS 时 httplib 只监听回环内部端口,对外端口由 McpTlsProxy 占据。 const bool https = m_httpsEnabled; const int backendPort = (https && m_internalPort > 0) ? m_internalPort : (https ? port + 1 : port); // 只在 HTTPS 下记住内部端口:明文模式下把它写成 port,会让「先明文启动、再改 HTTPS // 重启」这条路径拿到 backendPort == port,后端和前端抢同一个端口、MCP 直接起不来。 if (https) m_internalPort = backendPort; const std::string backendBind = https ? "127.0.0.1" : bind; m_thread = std::thread([this, backendBind, backendPort]() { m_server.listen(backendBind, backendPort); }); // 给 listen 一点时间绑定端口;httplib::Server::is_running() 在 listen 内部置位。 std::this_thread::sleep_for(std::chrono::milliseconds(100)); m_running.store(m_server.is_running()); if (!m_running.load()) return false; if (https) { // fail-closed:TLS 前端起不来(证书/私钥坏、端口被占)就整体停掉, // 绝不让 MCP 以「以为在跑 HTTPS 其实没在监听」的状态存在。 if (!m_tlsProxy.Start(bind, port, backendPort, m_certPath, m_keyPath)) { Mprintf("[MCP] HTTPS front-end failed to start; MCP server disabled\n"); m_server.stop(); if (m_thread.joinable()) m_thread.join(); m_running.store(false); return false; } } // 键鼠锁定看门狗(P10-C):remote_block_input 的 auto-unblock 期限靠它兑现。 // 防御:上一次 Start 没 Stop 就再 Start(正常路径由顶部 m_running 拦下)时先收掉旧线程, // 必须先置停止位再 join,否则旧线程永远不退出。 if (m_blockThread.joinable()) { m_blockStop.store(true); m_blockThread.join(); } m_blockStop.store(false); m_blockThread = std::thread([this]() { BlockWatchdogLoop(); }); return true; } void CMcpServer::Stop() { // P11:先取消所有在飞调用——长任务(下载 / 搜索 / 挂起等待)的等待循环会在 ≤1s // 内退出并走超时清理路径,不给 Stop 留下还在用连接、还在改表的工具线程。 CancelCalls(0, std::string()); // 再停看门狗:它会对屏幕子连接发报文,必须在后端服务拆除之前停止。 m_blockStop.store(true); if (m_blockThread.joinable()) m_blockThread.join(); // 再停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。 m_tlsProxy.Stop(); m_server.stop(); if (m_thread.joinable()) { m_thread.join(); } m_running.store(false); } // get_server_status:各类在飞会话 + 当前被封禁的来源 IP 计数。 // 每类只取自己的锁且立刻释放,不跨锁持有一致性(这些数字只作观测用)。 void CMcpServer::GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl, int& fileXfer, int& chat, int& blockedIps) { { std::lock_guard lk(m_PendingMutex); pending = (int)m_Pending.size(); } { std::lock_guard lk(m_TermMutex); terminal = (int)m_TermSessions.size(); } { std::lock_guard lk(m_ScreenCtrlMutex); screenCtrl = (int)m_ScreenCtrlSessions.size(); } { std::lock_guard lk(m_FileXferMutex); fileXfer = (int)m_FileXferSessions.size(); } { std::lock_guard lk(m_ChatMutex); chat = (int)m_ChatSessions.size(); } blockedIps = 0; auto now = std::chrono::steady_clock::now(); std::lock_guard lk(m_AuthMutex); for (const auto& kv : m_AuthFails) { if (kv.second.blockedUntil > now) blockedIps++; } } // ===== P11:在飞调用登记 / 取消 / 会话快照 ===== // // 三张表各自持锁、只读遍历,绝不嵌套(与 GetRuntimeCounters 同一约定):调用方拿到的 // 是「大致同一时刻」的快照,仅用于观测与取消,不用来同步。 namespace { long long ElapsedMsSince(std::chrono::steady_clock::time_point tp) { if (tp.time_since_epoch().count() == 0) return -1; return (long long)std::chrono::duration_cast( std::chrono::steady_clock::now() - tp).count(); } long long IdleMsSince(time_t t) { if (t <= 0) return -1; return (long long)(time(NULL) - t) * 1000; } } // namespace std::shared_ptr CMcpServer::BeginCall(const std::string& idKey, const std::string& idText, const std::string& tool, uint64_t device, const std::string& sessionId) { auto call = std::make_shared(); call->idKey = idKey; call->idText = idText; call->tool = tool; call->device = device; call->sessionId = sessionId; call->startedAt = std::chrono::steady_clock::now(); std::lock_guard lk(m_CallMutex); m_Calls.push_back(call); return call; } void CMcpServer::EndCall(const std::shared_ptr& call) { if (!call) return; std::lock_guard lk(m_CallMutex); for (auto it = m_Calls.begin(); it != m_Calls.end(); ++it) { if (*it == call) { m_Calls.erase(it); return; } } } bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) { std::lock_guard lk(m_CallMutex); // 取消工具自己也是一次在飞调用;request_id 指到自己时不能把自己算成「被取消」。 const McpCallContext* self = CurrentMcpCall().get(); // 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。 for (const auto& c : m_Calls) { if (c.get() == self) continue; if (c->idKey == idKey) { c->cancelled.store(true); return true; } } // 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来, // 而原调用用的是数字 id —— 这是同一意图,容忍。 if (!idText.empty()) { for (const auto& c : m_Calls) { if (c.get() == self) continue; if (c->idText == idText) { c->cancelled.store(true); return true; } } } return false; } int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) { int n = 0; std::lock_guard lk(m_CallMutex); const McpCallContext* self = CurrentMcpCall().get(); for (const auto& c : m_Calls) { if (c.get() == self) continue; // 不把取消工具自身计入 cancelled if (device != 0 && c->device != device) continue; if (!sessionId.empty() && c->sessionId != sessionId) continue; c->cancelled.store(true); ++n; } return n; } std::vector CMcpServer::ListSessions() { std::vector out; { std::lock_guard lk(m_CallMutex); for (const auto& c : m_Calls) { SessionSnapshot s; s.device = c->device; s.kind = "call"; s.tool = c->tool; s.sessionId = c->sessionId; s.idKey = c->idKey; s.requestId = c->idText; s.busy = true; s.elapsedMs = ElapsedMsSince(c->startedAt); out.push_back(s); } } { std::lock_guard lk(m_PendingMutex); for (const auto& kv : m_Pending) { SessionSnapshot s; s.device = kv.first; s.kind = "pending"; s.tool = kv.second.tool; s.busy = true; s.elapsedMs = ElapsedMsSince(kv.second.startedAt); out.push_back(s); } } { std::lock_guard lk(m_TermMutex); for (const auto& kv : m_TermSessions) { const TermSession& t = kv.second; SessionSnapshot s; s.device = kv.first; s.kind = "terminal"; s.tool = t.persistent ? "terminal" : "exec_command"; s.sessionId = t.sessionId; s.busy = t.busy || !t.started; s.elapsedMs = ElapsedMsSince(t.startedAt); s.idleMs = IdleMsSince(t.lastActiveAt); out.push_back(s); } } { std::lock_guard lk(m_ScreenCtrlMutex); for (const auto& kv : m_ScreenCtrlSessions) { const ScreenCtrlSession& c = kv.second; SessionSnapshot s; s.device = kv.first; s.kind = "remote_control"; s.tool = "remote_control"; s.sessionId = c.sessionId; s.busy = c.busy || !c.started; s.elapsedMs = ElapsedMsSince(c.startedAt); s.idleMs = IdleMsSince(c.lastActiveAt); out.push_back(s); } } { std::lock_guard lk(m_FileXferMutex); for (const auto& kv : m_FileXferSessions) { const FileTransferSession& f = kv.second; SessionSnapshot s; s.device = kv.first; s.kind = "file_transfer"; s.tool = f.tool; s.busy = true; // 文件传输会话在表里就是「在飞」,结束时删除 s.elapsedMs = ElapsedMsSince(f.startedAt); s.idleMs = ElapsedMsSince(f.lastDataAt); out.push_back(s); } } { std::lock_guard lk(m_ChatMutex); for (const auto& kv : m_ChatSessions) { const ChatSession& c = *kv.second; SessionSnapshot s; s.device = kv.first; s.kind = "chat"; s.tool = "chat"; s.sessionId = c.sessionId; s.busy = c.sendBusy || c.waitBusy || !c.started; s.elapsedMs = ElapsedMsSince(c.startedAt); s.idleMs = IdleMsSince(c.lastActiveAt); out.push_back(s); } } return out; } // -32003 文案后缀:优先报「正在跑的长任务」(调用 / 挂起 / 文件传输),其次报持久会话。 std::string CMcpServer::DescribeBusy(uint64_t device_id) { auto describe = [](const std::string& tool, long long ms) { std::string s = " (tool=" + (tool.empty() ? std::string("?") : tool); if (ms >= 0) s += ", elapsed=" + std::to_string(ms / 1000) + "s"; return s + ")"; }; { std::lock_guard lk(m_CallMutex); const McpCallContext* self = CurrentMcpCall().get(); for (const auto& c : m_Calls) { if (c.get() == self) continue; // 发起 -32003 的就是这次调用,不能算「占用者」 if (c->device == device_id) return describe(c->tool + (c->sessionId.empty() ? "" : " session_id=" + c->sessionId), ElapsedMsSince(c->startedAt)); } } { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it != m_Pending.end()) return describe(it->second.tool, ElapsedMsSince(it->second.startedAt)); } { std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it != m_FileXferSessions.end()) return describe(it->second.tool, ElapsedMsSince(it->second.startedAt)); } { std::lock_guard lk(m_TermMutex); auto it = m_TermSessions.find(device_id); if (it != m_TermSessions.end() && it->second.busy) return describe(TerminalLabel(it->second.sessionId), ElapsedMsSince(it->second.startedAt)); } { std::lock_guard lk(m_ScreenCtrlMutex); auto it = m_ScreenCtrlSessions.find(device_id); if (it != m_ScreenCtrlSessions.end() && it->second.busy) return describe("remote_control", ElapsedMsSince(it->second.startedAt)); } { std::lock_guard lk(m_ChatMutex); auto it = m_ChatSessions.find(device_id); if (it != m_ChatSessions.end() && (it->second->sendBusy || it->second->waitBusy)) return describe("chat", ElapsedMsSince(it->second->startedAt)); } return std::string(); } // -32003 的正文:通用句 + 「谁占着这台主机、已持续多久」。McpMachine.cpp 也用它。 std::string BusyMessage(const std::string& base, uint64_t devId) { const std::string who = CMcpServer::Instance().DescribeBusy(devId); return who.empty() ? base : base + who; } // ===== 鉴权加固(N4)===== // 两件事: // 1) 同一 IP 在 60 s 内鉴权失败 10 次 → 封禁 15 min(封禁期内直接 429,不比对 token)。 // 正常客户端只有在 token 配错时才会连续 401,10 次足够覆盖改配置重试;爆破工具一分钟 // 就能打出上千次,阈值远在安全侧。例外:环回来源(frp 隧道)只记账不封禁,见 // IsProxySourceAddress——封 127.0.0.1 会误伤隧道后面所有客户端。 // 2) 所有鉴权失败与工具调用写入 \logs\mcp_audit.log。审计只含时间/IP/UA/工具名/ // 耗时/字节数等元数据——绝不写 token、Authorization 头、请求参数或返回正文。 namespace { const int kAuthWindowSec = 60; const int kAuthMaxFailures = 10; const int kAuthBlockSec = 900; const size_t kAuthMapMax = 1024; // 跟踪表上限,防止被扫描器撑爆内存 const long long kAuditMaxBytes = 5LL * 1024 * 1024; std::string AuditStamp() { SYSTEMTIME st; GetLocalTime(&st); char buf[32]; _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d.%03d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); return buf; } // 经本机代理转发的请求源地址恒为环回:内置 frpc 把 MCP 端口映射出去时是「本机连本机」, // 且这条转发没开 Proxy Protocol(httplib 不解析),所以远端客户端的真实 IP 拿不到。 // 这类来源一律不封禁——封 127.0.0.1 等于把经隧道连进来的所有客户端(含用户自己)一起封掉, // 而攻击者要过 token 这一关本来也过不去。失败照样计数并写审计,便于事后发现扫描。 bool IsProxySourceAddress(const std::string& ip) { return ip == "127.0.0.1" || ip == "::1" || ip == "::ffff:127.0.0.1"; } // 头部值可能很长且含引号/控制字符:压成单行并截断,避免破坏日志行结构。 std::string SanitizeHeaderValue(const std::string& s, size_t maxLen = 120) { std::string out; for (char c : s) { if (out.size() >= maxLen) break; out += (c < 0x20 || c == 0x7f || c == '"') ? '_' : c; } return out; } } // namespace void CMcpServer::AppendAuditFile(const std::string& line) { static std::mutex s_mutex; static std::string s_path; static bool s_init = false; std::lock_guard lk(s_mutex); if (!s_init) { char exe[MAX_PATH] = {0}; if (GetModuleFileNameA(NULL, exe, MAX_PATH) == 0) return; std::string dir(exe); size_t pos = dir.find_last_of("\\/"); if (pos == std::string::npos) return; dir.resize(pos); std::string logDir = dir + "\\logs"; CreateDirectoryA(logDir.c_str(), NULL); // 已存在时失败,忽略 s_path = logDir + "\\mcp_audit.log"; s_init = true; } // 超限滚动一代(mcp_audit.log → mcp_audit.log.1),避免无限增长。 WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExA(s_path.c_str(), GetFileExInfoStandard, &fad)) { long long size = ((long long)fad.nFileSizeHigh << 32) | fad.nFileSizeLow; if (size > kAuditMaxBytes) { std::string old = s_path + ".1"; DeleteFileA(old.c_str()); MoveFileA(s_path.c_str(), old.c_str()); } } FILE* f = nullptr; if (fopen_s(&f, s_path.c_str(), "ab") != 0 || !f) return; fputs(line.c_str(), f); fputc('\n', f); fclose(f); } void CMcpServer::AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail) { std::string line = AuditStamp(); line += ' '; line += event; line += " ip="; line += ip.empty() ? std::string("-") : ip; if (!detail.empty()) { line += ' '; line += detail; } AppendAuditFile(line); } bool CMcpServer::IsAuthBlocked(const std::string& ip) { auto now = std::chrono::steady_clock::now(); std::lock_guard lk(m_AuthMutex); auto it = m_AuthFails.find(ip); if (it == m_AuthFails.end()) return false; if (it->second.blockedUntil > now) return true; // 封禁已到期、且失败窗口也已过期 → 清掉,防止表无限增长 if (now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec)) m_AuthFails.erase(it); return false; } bool CMcpServer::RecordAuthFailure(const std::string& ip) { auto now = std::chrono::steady_clock::now(); std::lock_guard lk(m_AuthMutex); if (m_AuthFails.size() >= kAuthMapMax) { // 表满:先清扫彻底过期的项;仍然满就不再新增(宁可少统计也不无限增长) for (auto it = m_AuthFails.begin(); it != m_AuthFails.end(); ) { bool stale = it->second.blockedUntil <= now && now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec); if (stale) it = m_AuthFails.erase(it); else ++it; } if (m_AuthFails.size() >= kAuthMapMax) return false; } AuthFailRecord& r = m_AuthFails[ip]; if (r.count == 0 || now - r.windowStart > std::chrono::seconds(kAuthWindowSec)) { r.count = 1; r.windowStart = now; return false; } r.count++; if (r.count >= kAuthMaxFailures && r.blockedUntil <= now) { r.blockedUntil = now + std::chrono::seconds(kAuthBlockSec); return true; } return false; } void CMcpServer::ClearAuthFailures(const std::string& ip) { std::lock_guard lk(m_AuthMutex); m_AuthFails.erase(ip); } void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) { // 注意:这里不预置 Content-Type —— set_content / set_chunked_content_provider 各自 // 会写,预置会让 SSE 响应带上两个 Content-Type(application/json 在前)。 const std::string clientIp = req.remote_addr; // 环回来源(本机 / frp 隧道)不参与封禁,理由见 IsProxySourceAddress。 const bool proxySource = IsProxySourceAddress(clientIp); // 封禁期内直接拒绝:不比对 token,也不解析请求体 if (!proxySource && IsAuthBlocked(clientIp)) { res.status = 429; res.set_header("Retry-After", std::to_string(kAuthBlockSec)); res.set_content(BuildError(Json::nullValue, -32000, "Too many failed authentication attempts"), "application/json"); return; } // 静态 token 校验:Authorization: Bearer (Start 前经 SetToken 保证非空) if (req.get_header_value("Authorization") != ("Bearer " + m_token)) { bool blocked = RecordAuthFailure(clientIp); std::string ua = SanitizeHeaderValue(req.get_header_value("User-Agent")); AuditMcpEvent("AUTH_FAIL", clientIp, "ua=\"" + ua + "\" bytes=" + std::to_string(req.body.size()) + " blocked=" + (blocked ? "1" : "0")); if (blocked) { AuditMcpEvent("AUTH_BLOCK", clientIp, "window=" + std::to_string(kAuthWindowSec) + "s fail=" + std::to_string(kAuthMaxFailures) + " block=" + std::to_string(kAuthBlockSec) + "s" + (proxySource ? " scope=proxy-source-exempt" : "")); if (!proxySource) { res.status = 429; res.set_header("Retry-After", std::to_string(kAuthBlockSec)); res.set_content(BuildError(Json::nullValue, -32000, "Too many failed authentication attempts"), "application/json"); return; } } res.status = 401; res.set_content(BuildError(Json::nullValue, -32000, "Unauthorized"), "application/json"); return; } ClearAuthFailures(clientIp); // 解析 JSON-RPC 请求体 Json::Value root; Json::CharReaderBuilder rbuilder; std::string errs; std::istringstream iss(req.body); if (!Json::parseFromStream(rbuilder, iss, &root, &errs) || !root.isObject()) { res.set_content(BuildError(Json::nullValue, -32700, "Parse error"), "application/json"); return; } // 通知(无 id)→ 不返回 JSON-RPC 响应(如 notifications/initialized) if (!root.isMember("id")) { // P11:notifications/cancelled → 置对应在飞调用的取消位。工具层的等待循环会在 // ≤1s 内退出并走既有的超时清理路径(不发多余报文、不留下悬空挂起项), // 该请求自己的 SSE 流(若有)随即以 -32800 结束。 const Json::Value& m = root["method"]; if (m.isString() && m.asString() == "notifications/cancelled") { const Json::Value& params = root["params"]; if (params.isObject() && params.isMember("requestId")) { const Json::Value& rid = params["requestId"]; const bool hit = CancelCallById(JsonToString(rid), McpRequestIdText(rid)); AuditMcpEvent("NOTIFY_CANCEL", clientIp, "requestId=" + SanitizeHeaderValue(McpRequestIdText(rid), 64) + " hit=" + (hit ? "1" : "0")); } } res.status = 202; res.set_content("", "application/json"); return; } // 结构校验:缺 method if (!root.isMember("method") || !root["method"].isString()) { res.set_content(BuildError(root["id"], -32600, "Invalid Request"), "application/json"); return; } std::string method = root["method"].asString(); if (method == "initialize") { res.set_content(BuildInitializeResult(root["id"]), "application/json"); return; } if (method == "ping") { res.set_content(BuildPingResult(root["id"]), "application/json"); return; } if (method == "tools/list") { res.set_content(BuildToolsListResult(root["id"]), "application/json"); return; } if (method == "tools/call") { const Json::Value params = root.isMember("params") ? root["params"] : Json::Value(Json::objectValue); std::string toolName; if (params.isObject() && params.isMember("name") && params["name"].isString()) toolName = params["name"].asString(); // 登记在飞调用:devId / session_id 只用于观测与 mcp_cancel_session, // 解析不出来(非主机工具、参数非法)就按 0 / 空处理,不影响工具自身的行为。 const Json::Value args = GetCallArguments(params); uint64_t devId = 0; std::string ignored; ParseHostIdArg(args, devId, ignored); std::string sessionId; if (args.isObject() && args.isMember("session_id") && args["session_id"].isString()) sessionId = args["session_id"].asString(); auto call = BeginCall(JsonToString(root["id"]), McpRequestIdText(root["id"]), toolName, devId, sessionId); // _meta.progressToken(MCP 2025-06-18):字符串或整数,原样回显。 if (params.isObject() && params.isMember("_meta") && params["_meta"].isObject() && params["_meta"].isMember("progressToken")) { const Json::Value& tok = params["_meta"]["progressToken"]; if (tok.isString() || tok.isInt() || tok.isUInt() || tok.isInt64() || tok.isUInt64()) { call->hasProgressToken = true; call->progressTokenJson = JsonToString(tok); } } // 审计一条 tools/call 结果(SSE 路径的工具线程与普通路径共用同一份判定)。 auto auditResult = [this, clientIp, toolName](const std::string& resp, long long ms) { // 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判) bool failed = false; int errCode = 0; std::string errMsg; { Json::Value parsed; Json::CharReaderBuilder rb; std::string perrs; std::istringstream pis(resp); if (Json::parseFromStream(rb, pis, &parsed, &perrs) && parsed.isObject() && parsed.isMember("error")) { failed = true; const Json::Value& err = parsed["error"]; if (err.isObject()) { if (err["code"].isInt()) errCode = err["code"].asInt(); if (err["message"].isString()) errMsg = err["message"].asString(); } } } // 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行 auto oneLine = [](std::string v) { for (char& c : v) if ((unsigned char)c < 0x20) c = ' '; return v; }; const std::string toolTag = "tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName); AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp, toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); // 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED, // 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含 // 调用参数或用户输入,可以直接落盘。 if (errCode == -32006) AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg)); }; // 取消后的收尾:工具因取消而失败时,把错误统一改写成 -32800,让调用方知道 // 「这是自己取消的」而不是主机故障;已经拿到成功结果就照实返回。 auto finalize = [id = root["id"], call](std::string resp) { if (!call->IsCancelled()) return resp; Json::Value parsed; Json::CharReaderBuilder rb; std::string perrs; std::istringstream pis(resp); if (!Json::parseFromStream(rb, pis, &parsed, &perrs) || !parsed.isObject() || !parsed.isMember("error")) return resp; return BuildError(id, kErrCancelled, "Request cancelled: the in-flight work was aborted and cleaned up"); }; if (call->hasProgressToken) { // 带 _meta.progressToken:按 MCP Streamable HTTP 的要求以 text/event-stream // 回应同一个 POST。工具在独立线程执行,进度通知与最终响应都从这个流写出。 auto ch = std::make_shared(); ch->call = call; call->channel = ch; const Json::Value rootCopy = root; // 请求体在栈上,工具线程必须持有副本 std::thread([this, rootCopy, call, ch, clientIp, toolName, auditResult, finalize]() { McpCallScope scope(call); auto t0 = std::chrono::steady_clock::now(); std::string resp = finalize(BuildToolsCall(rootCopy, m_parent)); const long long ms = (long long)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); auditResult(resp, ms); EndCall(call); ch->Finish(resp); // 最后一步:置 finished 并唤醒 provider 线程写出最终响应 }).detach(); res.status = 200; res.set_chunked_content_provider( "text/event-stream", [ch](size_t, httplib::DataSink& sink) { return ch->Pump(sink); }); return; } auto t0 = std::chrono::steady_clock::now(); std::string resp; { McpCallScope scope(call); // 让工具实现里的 McpCallCancelled() 生效 resp = BuildToolsCall(root, m_parent); } const long long ms = (long long)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); resp = finalize(std::move(resp)); EndCall(call); auditResult(resp, ms); res.set_content(resp, "application/json"); return; } // 未实现的方法 res.set_content(BuildError(root["id"], -32601, "Method not found"), "application/json"); } // ===== P2b 挂起请求注册表实现 ===== bool CMcpServer::IsPending(uint64_t device_id) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; // P8:主机管理/连接管理会话的响应包走 OnManagedSubPacket,不归 MFC 的 // TOKEN_PSLIST/TOKEN_WSLIST/SERVERLIST/DRIVE_LIST 分支消费(否则会抢走 UI 包)。 return it->second.kind == PendingKind::Generic || it->second.kind == PendingKind::FollowUp; } void CMcpServer::TakeMainResponse(uint64_t device_id, const BYTE* data, ULONG len) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) { Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d: no pending (late/dropped)\n", device_id, (int)len); return; } // 已超时清理 → 迟到数据,丢弃 if (it->second.kind != PendingKind::Generic && it->second.kind != PendingKind::FollowUp) return; // P8 会话:不接管 Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d done\n", device_id, (int)len); it->second.data.assign(data, data + len); it->second.done = true; m_PendingCv.notify_one(); } bool CMcpServer::BeginPending(uint64_t device_id, const std::string& tool) { if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2) std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙 PendingRequest r; r.tool = tool; m_Pending[device_id] = std::move(r); return true; } bool CMcpServer::BeginPendingFileOp(uint64_t device_id, const std::string& tool, const std::vector& followUp, const std::string& verifyPath) { if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2) std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙 PendingRequest r; r.tool = tool; r.kind = PendingKind::FollowUp; // IsPending 认这个 kind,TOKEN_DRIVE_LIST 才会交给 OnDriveList r.followUp = followUp; r.verifyPath = verifyPath; m_Pending[device_id] = std::move(r); return true; } CMcpServer::FileOpAck CMcpServer::TakeFileOpFinish(uint64_t device_id, context* subCtx, const BYTE* data, ULONG len) { std::vector listCmd; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return FileOpAck::NotMine; // 已超时清理 → 迟到包 if (!IsFileWriteToolName(it->second.tool)) return FileOpAck::NotMine; // 别的写工具不会发这些 token if (it->second.phase == 0 && !it->second.verifyPath.empty()) { // phase 0 → 1:完成包不代表成功,先在同一子连接上补一次列目录复核。 // 不投递完成包、也不置 done:工具线程继续在同一超时窗口内等复核结果。 it->second.phase = 1; it->second.data.clear(); it->second.done = false; listCmd.push_back((BYTE)COMMAND_LIST_FILES); listCmd.insert(listCmd.end(), it->second.verifyPath.begin(), it->second.verifyPath.end()); listCmd.push_back(0); // 客户端按 C 串取路径 } else { // 没有复核目标(或伪造的第二次完成包):直接投递,让工具线程收尾。 it->second.data.assign(data, data + len); it->second.done = true; m_PendingCv.notify_one(); return FileOpAck::CloseSub; } } if (!subCtx->Send2Client(listCmd.data(), (ULONG)listCmd.size())) { // 复核下发失败:别把工具线程挂到超时,直接把完成包投递过去, // 工具会看到「不是列表包」→ verified=null(结果未知),如实上报。 Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: send verify listing failed\n", (unsigned long long)device_id); std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return FileOpAck::CloseSub; it->second.data.assign(data, data + len); it->second.done = true; m_PendingCv.notify_one(); return FileOpAck::CloseSub; } Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: ack ok -> verify listing (%d bytes)\n", (unsigned long long)device_id, (int)listCmd.size()); return FileOpAck::KeepSub; // 等 TOKEN_FILE_LIST;该分支投递数据后 CancelIO 收尾 } bool CMcpServer::WaitPending(uint64_t device_id, std::vector& out, int timeoutMs) { std::unique_lock lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; // 500ms 一片地等:取消后最多一个切片就落到下面的超时分支,仍由本线程清理 map。 const bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), [&] { return it->second.done; }); if (!signaled || it->second.data.empty()) { // 放弃:客户端可能在我们返回后才把应答首包发上来,登记吸收,别让它弹 MFC 窗口。 MarkLateFirstPacketForTool(device_id, it->second.tool); m_Pending.erase(it); // 超时/空数据 → 清理 return false; } out = std::move(it->second.data); m_Pending.erase(it); return true; } void CMcpServer::ClearPending(uint64_t device_id) { std::lock_guard lk(m_PendingMutex); m_Pending.erase(device_id); } // ===== 迟到首包吸收 ===== // 工具放弃后 5 分钟内到达的「应答首包」只吸收一次;过期即失效(不长期压制人工操作)。 static const int kFirstPacketMarkMs = 5 * 60 * 1000; void CMcpServer::MarkLateFirstPacket(uint64_t device_id, std::initializer_list tokens) { if (tokens.size() == 0) return; const auto now = std::chrono::steady_clock::now(); std::lock_guard lk(m_FirstPacketMutex); for (auto it = m_FirstPacketMarks.begin(); it != m_FirstPacketMarks.end();) { if (it->second.expiry <= now) it = m_FirstPacketMarks.erase(it); else ++it; } FirstPacketMark mk; mk.tokens.insert(tokens.begin(), tokens.end()); mk.expiry = now + std::chrono::milliseconds(kFirstPacketMarkMs); m_FirstPacketMarks[device_id] = std::move(mk); } // 工具 → 应答首包 token。只有「子连接第一个包会弹 MFC 窗口」的工具需要登记。 void CMcpServer::MarkLateFirstPacketForTool(uint64_t device_id, const std::string& tool) { if (tool == "list_files" || tool == "download_file" || tool == "read_file" || tool == "upload_file" || tool == "search_file" || IsFileWriteToolName(tool)) MarkLateFirstPacket(device_id, { (BYTE)TOKEN_DRIVE_LIST }); else if (tool == "list_registry") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REGEDIT }); else if (tool == "list_services" || tool == "control_service") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SERVERLIST }); else if (tool == "list_processes" || tool == "kill_process") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_PSLIST }); else if (tool == "list_windows" || tool == "operate_window") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_WSLIST }); else if (tool == "get_client_log") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REPORT_LOG }); else if (tool == "get_activity_history") MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REPORT_ACTIVITY }); } bool CMcpServer::TakeToolFirstPacket(uint64_t device_id, BYTE token) { std::lock_guard lk(m_FirstPacketMutex); auto it = m_FirstPacketMarks.find(device_id); if (it == m_FirstPacketMarks.end()) return false; if (it->second.expiry <= std::chrono::steady_clock::now()) { m_FirstPacketMarks.erase(it); return false; } if (it->second.tokens.find(token) == it->second.tokens.end()) return false; // 不是该工具的应答首包 m_FirstPacketMarks.erase(it); // 一次性消费 Mprintf("[MCP] absorb late first token=%d dev=%llu (tool gave up earlier)\n", (int)token, (unsigned long long)device_id); return true; } // ===== P2c:list_files / get_screenshot 扩展 ===== bool CMcpServer::BeginPending(uint64_t device_id, const std::string& tool, const std::string& path) { if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2) std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙 PendingRequest r; r.tool = tool; r.path = path; m_Pending[device_id] = std::move(r); return true; } uint16_t CMcpServer::NextPreviewReqId() { uint16_t v = m_PreviewReqId.fetch_add(1, std::memory_order_relaxed); if (v == 0) v = m_PreviewReqId.fetch_add(1, std::memory_order_relaxed); // 跳过 0 return v; } void CMcpServer::SetPendingReqId(uint64_t device_id, uint16_t reqId) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it != m_Pending.end()) it->second.expectedReqId = reqId; } bool CMcpServer::TakePreviewResponse(uint64_t device_id, uint16_t reqId, const BYTE* data, ULONG len) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; // 已超时清理 → 迟到数据,回落 MFC if (it->second.tool != "get_screenshot") return false; if (it->second.expectedReqId == 0 || it->second.expectedReqId != reqId) return false; // 过期/他途响应 it->second.data.assign(data, data + len); it->second.done = true; m_PendingCv.notify_one(); return true; } bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) { std::string path; bool listDrives = true; bool searchFile = false; bool fileOp = false; std::vector fileOpFollowUp; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return true; // 已超时清理 → 调用方 CancelIO 收尾 path = it->second.path; if (IsFileWriteToolName(it->second.tool)) { // P10-B:文件写工具。子连接就绪即下发写命令(path 对这些工具无意义, // payload 已整条存在 followUp 里),保持子连接等 TOKEN_*_FINISH。 fileOp = true; it->second.subCtx = subCtx; // 超时 CancelIO / 阶段判断用 it->second.followUpSent = true; fileOpFollowUp = it->second.followUp; } else if (it->second.tool == "search_file") { // B2:path 里装的是 [根目录 \0][模式 \0](含 NUL,不能用 C 字符串接口处理)。 searchFile = true; it->second.subCtx = subCtx; // 超时停搜 / 收尾要用 } else { // 列盘一律用空 path 表示:Windows 的 "."、"/"、"\\" 已在 BuildListFiles 归一化成 // 空串;POSIX 上 "/" 与 "." 是真实目录,必须按目录下发。这里不再自行判魔法路径, // 免得两个地方口径不一致。 listDrives = path.empty(); if (listDrives) { it->second.data.assign(buf, buf + len); it->second.done = true; m_PendingCv.notify_one(); return true; // 只列盘 → 调用方用完即关 } } } if (fileOp) { // 锁外下发写命令。发送失败不额外处理:工具线程会在超时后按 -32001 收尾并 CancelIO。 if (!subCtx->Send2Client(fileOpFollowUp.data(), (ULONG)fileOpFollowUp.size())) Mprintf("[MCP-P10B] OnDriveList: send file-op command failed (dev=%llu, %d bytes)\n", (unsigned long long)device_id, (int)fileOpFollowUp.size()); return false; // 保持子连接,等完成包 } if (searchFile) { // 文件搜索:子链接已就绪,下发 COMMAND_SEARCH_FILE + FILESEARCH 结构体。 // 与 MFC 文件管理器 OnBtnSearch 的打包方式一致(命令字节后紧跟整个结构体)。 std::vector pkt; pkt.reserve(1 + path.size()); pkt.push_back((BYTE)COMMAND_SEARCH_FILE); pkt.insert(pkt.end(), path.begin(), path.end()); subCtx->Send2Client(pkt.data(), (ULONG)pkt.size()); return false; // 保持子链接,等 N 个结果包 + FINISH } // 列目录:锁外下发 COMMAND_LIST_FILES + path,子链接保持,等 TOKEN_FILE_LIST。 // path 已在 BuildListFiles 按客户端 ANSI 转好(OnDriveList 无需再转),结尾 '\0' // 与 FileManagerDlg 的 PacketSize=len+2 一致。 std::vector pkt; pkt.reserve(1 + path.size() + 1); pkt.push_back((BYTE)COMMAND_LIST_FILES); pkt.insert(pkt.end(), path.begin(), path.end()); pkt.push_back(0); subCtx->Send2Client(pkt.data(), (ULONG)pkt.size()); return false; // 继续等 TOKEN_FILE_LIST,调用方不 CancelIO } // ===== B2:search_file ===== namespace { // 收集上限:单次搜索最多记住 5000 条 / 4 MB 原始包,超过就让客户端停搜。 // 这是保护服务端内存(整盘搜索能命中几十万条),不是业务上限。 const size_t kSearchMaxRecords = 5000; const size_t kSearchMaxBytes = 4 * 1024 * 1024; } bool CMcpServer::OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) { bool needStop = false; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end() || it->second.tool != "search_file") return false; PendingRequest& p = it->second; // 身份校验:只认登记过的那条子连接。旧搜索(已放弃)的尾包一律不受理, // 由调用方原地丢弃——但调用方绝不能因此关连接(见 2015RemoteDlg.cpp 的注释)。 if (p.subCtx != subCtx) return false; if (p.searchRecords.size() >= kSearchMaxRecords || p.searchBytes + len > kSearchMaxBytes) { p.searchTruncated = true; if (!p.searchStopSent) { p.searchStopSent = true; needStop = true; } } else { p.searchRecords.emplace_back(buf, buf + len); p.searchBytes += len; } } if (needStop && subCtx) { BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP; subCtx->Send2Client(&stop, 1); } return true; // 命中挂起 → 本包由 MCP 消费(不论是否因超限被丢弃) } void CMcpServer::FinishSearchFile(uint64_t device_id, context* subCtx) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end() || it->second.tool != "search_file") return; if (it->second.subCtx != subCtx) return; // 别的子连接的 FINISH,与当前搜索无关 it->second.searchFinished = true; m_PendingCv.notify_all(); } bool CMcpServer::WaitSearchFile(uint64_t device_id, std::vector>& records, bool& finished, bool& truncated, context*& subCtx, int timeoutMs) { std::unique_lock lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end() || it->second.tool != "search_file") return false; // 取消(search_file 120s 上限)后仍然把已收记录带出去:调用方会去停搜并返回部分结果。 WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), [&] { return it->second.searchFinished; }); records.swap(it->second.searchRecords); it->second.searchRecords.clear(); it->second.searchBytes = 0; finished = it->second.searchFinished; truncated = it->second.searchTruncated; subCtx = it->second.subCtx; return true; } void CMcpServer::StopSearchFile(uint64_t device_id) { context* subCtx = nullptr; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end() || it->second.tool != "search_file") return; if (it->second.searchStopSent) return; it->second.searchStopSent = true; subCtx = it->second.subCtx; } if (subCtx) { BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP; subCtx->Send2Client(&stop, 1); } } // ===== P3:list_registry 扩展 ===== bool CMcpServer::OnRegeditReady(uint64_t device_id, context* subCtx) { std::string rootAndPath; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; // 无挂起 → 回落 MFC if (it->second.tool != "list_registry") return false; rootAndPath = it->second.path; // [rootToken:1][相对子键路径...] } if (rootAndPath.empty()) return false; // 不应发生:list_registry 必有 rootToken BYTE rootToken = (BYTE)rootAndPath[0]; std::string relPath = rootAndPath.substr(1); // 下发 COMMAND_REG_FIND:布局与 RegisterDlg::OnTvnSelchangedTree 一致 // [COMMAND_REG_FIND][rootToken][relPath...]['\0']。子链接保持,等 TOKEN_REG_PATH + KEY。 std::vector pkt; pkt.reserve(2 + relPath.size() + 1); pkt.push_back((BYTE)COMMAND_REG_FIND); pkt.push_back(rootToken); pkt.insert(pkt.end(), relPath.begin(), relPath.end()); pkt.push_back(0); subCtx->Send2Client(pkt.data(), (ULONG)pkt.size()); return true; // 接管子链接,不打开 MFC 对话框 } void CMcpServer::TakeRegPath(uint64_t device_id, const BYTE* data, ULONG len) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return; // 已超时清理 → 迟到数据丢弃 if (it->second.tool != "list_registry") return; it->second.regPath.assign(data, data + len); it->second.pathDone = true; if (it->second.keyDone) { it->second.done = true; m_PendingCv.notify_one(); } } void CMcpServer::TakeRegKey(uint64_t device_id, const BYTE* data, ULONG len) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return; if (it->second.tool != "list_registry") return; it->second.regKey.assign(data, data + len); it->second.keyDone = true; if (it->second.pathDone) { it->second.done = true; m_PendingCv.notify_one(); } } // 工具默认等待超时([settings] McpToolTimeoutMs)。仅在启动初始化阶段调用,无并发写。 void CMcpServer::SetToolTimeoutMs(int ms) { if (ms < 1000) ms = 1000; // 下限:短于一秒的等待几乎必然误判超时 if (ms > 600000) ms = 600000; // 上限:与 exec_command timeout_ms 同界 m_toolTimeoutMs = ms; } void CMcpServer::TakeRegError(uint64_t device_id, const BYTE* data, ULONG len) { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return; // 已超时清理 → 迟到数据丢弃 if (it->second.tool != "list_registry") return; // 失败时客户端只发这一包(不会有 PATH/KEY),故一次置满三个标志。 it->second.regPath.assign(data, data + len); it->second.pathDone = true; it->second.keyDone = true; it->second.done = true; m_PendingCv.notify_one(); } bool CMcpServer::WaitPendingRegistry(uint64_t device_id, std::vector& subkeys, std::vector& values, int timeoutMs) { std::unique_lock lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), [&] { return it->second.done; }); if (!signaled) { MarkLateFirstPacketForTool(device_id, it->second.tool); // 放弃后的 TOKEN_REGEDIT 不弹注册表窗口 m_Pending.erase(it); // 超时/取消 → 清理 return false; } subkeys = std::move(it->second.regPath); values = std::move(it->second.regKey); m_Pending.erase(it); return true; } // ===== P7:设备管理控制(写工具接管)===== bool CMcpServer::BeginPendingFollowUp(uint64_t device_id, const std::string& tool, const std::vector& followUp) { if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2) std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙 PendingRequest r; r.tool = tool; r.kind = PendingKind::FollowUp; r.followUp = followUp; m_Pending[device_id] = std::move(r); return true; } bool CMcpServer::OnSystemReady(uint64_t device_id, context* subCtx) { std::string tool; std::vector followUp; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) { Mprintf("[MCP-P7] OnSystemReady dev=%llu: no pending\n", device_id); return false; } // 无挂起 → 回落 MFC tool = it->second.tool; if (tool != "kill_process" && tool != "operate_window") { Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s: not write tool\n", device_id, tool.c_str()); return false; } if (it->second.followUpSent) { Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s: CONFIRM token -> TakeMainResponse\n", device_id, tool.c_str()); return false; } // 确认包 → TakeMainResponse followUp = it->second.followUp; it->second.subCtx = subCtx; it->second.followUpSent = true; } // 锁外下发写命令;kill/test 需补发刷新命令索取新列表(close/control_service 客户端自动回)。 BOOL b1 = subCtx->Send2Client(followUp.data(), (ULONG)followUp.size()); BYTE refresh = 0; if (tool == "kill_process") { refresh = (BYTE)COMMAND_PSLIST; } else if (!followUp.empty() && followUp[0] == CMD_WINDOW_TEST) { refresh = (BYTE)COMMAND_WSLIST; } if (refresh) { // followUp 与 refresh 是两次独立 Send2Client,各自 PostQueuedCompletionStatus(IOWrite), // worker 会对同一 OutCompressedBuffer 并发发起 WSASend,造成竞态/丢包。用 WaitSendIdle // 确定性等首个包真正发完再发刷新包(比 MFC 的 Sleep(100) 盲等更稳)。 subCtx->WaitSendIdle(2000); BOOL b2 = subCtx->Send2Client(&refresh, 1); Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s READY: followUpSend=%d refreshSend=%d refresh=%d\n", device_id, tool.c_str(), b1 ? 1 : 0, b2 ? 1 : 0, (int)refresh); } return true; // 已接管,不 CancelIO } bool CMcpServer::OnServiceReady(uint64_t device_id, context* subCtx) { std::vector followUp; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; if (it->second.tool != "control_service") return false; if (it->second.followUpSent) return false; // 确认包 → 调用方 TakeMainResponse followUp = it->second.followUp; it->second.subCtx = subCtx; it->second.followUpSent = true; } subCtx->Send2Client(followUp.data(), (ULONG)followUp.size()); return true; // 客户端写后自动回,无需补发 } bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector& out, int timeoutMs, int* phaseOut) { context* subCtx = nullptr; std::unique_lock lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) { if (phaseOut) *phaseOut = 0; return false; } if (phaseOut) *phaseOut = it->second.phase; bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), [&] { return it->second.done; }); // 超时/空数据时把「放弃那一刻所处的阶段」带出去:P10-B 的 phase 1 表示完成包已到、 // 只是复核列目录没回来(命令已送达),与 phase 0 的「连回包都没有」不是一回事。 if (phaseOut) *phaseOut = it->second.phase; if (!signaled || it->second.data.empty()) { subCtx = it->second.subCtx; Mprintf("[MCP-P7] WaitPendingWrite dev=%llu TIMEOUT: signaled=%d dataEmpty=%d subCtx=%p\n", device_id, signaled ? 1 : 0, it->second.data.empty() ? 1 : 0, (void*)subCtx); MarkLateFirstPacketForTool(device_id, it->second.tool); // 就绪包迟到 → 吸收,不弹进程/服务窗口 m_Pending.erase(it); // 超时/空数据 → 清理 lk.unlock(); if (subCtx) subCtx->CancelIO(); // 锁外关子连接,防孤儿子连接 return false; } out = std::move(it->second.data); Mprintf("[MCP-P7] WaitPendingWrite dev=%llu OK len=%d\n", device_id, (int)out.size()); m_Pending.erase(it); return true; } void CMcpServer::OnManageSubClosed(context* subCtx) { std::lock_guard lk(m_PendingMutex); // 只匹配「已接管、等确认包」的写工具子连接(read 工具从不存 subCtx,天然不命中)。 // 扫描而非按 device_id 查找,避免依赖断线后 GetClientID 是否仍有效。 for (auto& kv : m_Pending) { if (kv.second.subCtx == subCtx) { // P8 会话由 OnManagedContextClosed 处理(这里若清 subCtx 会让其无法按指针反查设备)。 if (kv.second.kind == PendingKind::Machine || kv.second.kind == PendingKind::ConnMgr) continue; Mprintf("[MCP-P7] OnManageSubClosed subCtx=%p tool=%s: sub-conn closed before confirm\n", (void*)subCtx, kv.second.tool.c_str()); kv.second.subCtx = nullptr; // 断线后子连接已死/将回收,超时路径不得再 CancelIO kv.second.done = true; // 唤醒等待线程(WaitPendingWrite 见 data 空 → 返回失败) m_PendingCv.notify_all(); break; } } } // rand_s:Windows CRT 加密安全随机源(基于系统 CSPRNG)。其声明需在 前 // 定义 _CRT_RAND_S;为避免依赖 PCH 的包含顺序,这里手动声明其导出原型(errno_t == int)。 extern "C" int __cdecl rand_s(unsigned int* randomValue); std::string GenerateRandomToken() { static const char hex[] = "0123456789abcdef"; std::string out; out.reserve(32); for (int i = 0; i < 16; ++i) { unsigned int v = 0; if (rand_s(&v) != 0) { // rand_s 失败(罕见):退化为时间 + 地址熵,保证仍返回非空 token。 v = (unsigned int)(GetTickCount() ^ (ULONG_PTR)&out); } out.push_back(hex[(v >> 4) & 0xF]); out.push_back(hex[v & 0xF]); } return out; } // ===== P6:download_file 文件传输会话(状态机方法)===== // 停滞看门狗:超过这么久没收到任何传输包即判失败(远程路径不存在时客户端不发包)。 // 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。 static const int kFileXferStallMs = 60000; // read_file 复用 download_file 的 V2 接收通道:这四处包处理按「下载类工具」放行。 static bool IsFileXferDownloadTool(const std::string& tool) { return tool == "download_file" || tool == "read_file"; } bool CMcpServer::IsFileTransferPending(uint64_t device_id) { std::lock_guard lk(m_FileXferMutex); return m_FileXferSessions.find(device_id) != m_FileXferSessions.end(); } bool CMcpServer::IsC2CTransferPending(uint64_t src_id, uint64_t dst_id) { std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(src_id); return it != m_FileXferSessions.end() && it->second.tool == "copy_files_c2c" && it->second.dstClientID == dst_id; } bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string& tool, const std::string& localDir, const std::string& remotePath, bool overwrite, uint64_t maxFileBytes) { // 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。 { std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; } std::lock_guard lk(m_FileXferMutex); if (m_FileXferSessions.find(device_id) != m_FileXferSessions.end()) return false; // 单设备单传输 FileTransferSession s; s.tool = tool; s.localDir = localDir; s.remotePath = remotePath; s.overwrite = overwrite; s.maxFileBytes = maxFileBytes; s.startAt = time(nullptr); s.lastDataAt = std::chrono::steady_clock::now(); m_FileXferSessions[device_id] = std::move(s); return true; } bool CMcpServer::BeginFileUpload(uint64_t device_id, uint64_t transfer_id) { // 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。 { std::lock_guard lk(m_PendingMutex); if (m_Pending.find(device_id) != m_Pending.end()) return false; } std::lock_guard lk(m_FileXferMutex); if (m_FileXferSessions.find(device_id) != m_FileXferSessions.end()) return false; // 单设备单传输 FileTransferSession s; s.tool = "upload_file"; s.dstClientID = device_id; // 目标端 = 会话宿主,回执按 dstClientID + transferID 匹配 s.transferID = transfer_id; s.startAt = time(nullptr); s.lastDataAt = std::chrono::steady_clock::now(); m_FileXferSessions[device_id] = std::move(s); return true; } // ===== C2C 文件传输(copy_files_c2c)===== // 源客户端收到 COMMAND_C2C_SEND_FILES 后自己开子连接上行,数据包由服务端的 // COMMAND_SEND_FILE_V2 转发分支(dstClientID != 0)原样中继到目标客户端主连接, // 服务端不落盘、不解析文件内容;本会话只用来「等源端回传结果 + 单设备单传输互斥」。 bool CMcpServer::BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id) { if (src_id == 0 || src_id == dst_id) return false; { // 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。 std::lock_guard lk(m_PendingMutex); if (m_Pending.find(src_id) != m_Pending.end()) return false; if (m_Pending.find(dst_id) != m_Pending.end()) return false; } std::lock_guard lk(m_FileXferMutex); if (m_FileXferSessions.find(src_id) != m_FileXferSessions.end()) return false; // 单设备单传输 if (m_FileXferSessions.find(dst_id) != m_FileXferSessions.end()) return false; // 目标端另有在飞传输 FileTransferSession s; s.tool = "copy_files_c2c"; s.dstClientID = dst_id; s.transferID = transfer_id; s.startAt = time(nullptr); s.lastDataAt = std::chrono::steady_clock::now(); m_FileXferSessions[src_id] = std::move(s); return true; } void CMcpServer::OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len) { if (len < sizeof(C2CSendResultPacket)) return; const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf; std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(src_id); if (it == m_FileXferSessions.end() || it->second.tool != "copy_files_c2c") return; FileTransferSession& s = it->second; if (s.c2cResult || res->transferID != s.transferID) return; // 首个结果为准,旧传输的迟到包忽略 s.c2cResult = true; s.c2cStatus = res->status; s.c2cWin32 = res->win32err; s.c2cWorkerRc = res->workerRc; s.c2cFileCount = res->fileCount; s.c2cBytes = res->totalBytes; s.done = true; s.error = (res->status == (uint32_t)FEV2_OK && res->workerRc == 0) ? 0 : (int)(res->status ? res->status : 1001); m_FileXferCv.notify_all(); } void CMcpServer::OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len) { if (len < sizeof(C2CSendResultPacket)) return; const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf; if (res->cmd != TOKEN_C2C_RECV_RESULT || res->dstClientID != dst_id) return; // 身份自洽性 std::lock_guard lk(m_FileXferMutex); // copy_files_c2c:目标端在服务端没有会话条目(BeginC2CTransfer 只登记源端),只能反查; // upload_file:会话键就是目标端本身。两者都用 dstClientID + transferID 定位。 for (auto& kv : m_FileXferSessions) { FileTransferSession& s = kv.second; if (s.tool != "copy_files_c2c" && s.tool != "upload_file") continue; if (s.dstClientID != dst_id || s.transferID != res->transferID) continue; if (s.recvAck) return; // 重复回执只认第一包 s.recvAck = true; s.recvStatus = res->status; s.recvErrno = res->win32err; // 176 里放的是 errno s.recvFileCount = res->fileCount; s.recvBytes = res->totalBytes; m_FileXferCv.notify_all(); return; } } bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) { std::unique_lock lk(m_FileXferMutex); auto it = m_FileXferSessions.find(src_id); if (it == m_FileXferSessions.end()) { out.error = 1002; return false; } // 只有总超时,没有停滞看门狗:源端全程只在最后回一包结果,中途长时间无包是正常的 // (大文件传输),按「无数据即停滞」判会误杀。 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); bool signaled = false; while (true) { auto slice = std::chrono::milliseconds(500); auto now = std::chrono::steady_clock::now(); if (now + slice > deadline) slice = std::chrono::duration_cast(deadline - now); if (slice.count() <= 0) break; // 总超时 if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) { signaled = true; break; } if (McpCallCancelled()) break; // P11:取消按「未收到结果」收尾 } FileTransferSession& s = it->second; out.status = s.c2cStatus; out.win32err = s.c2cWin32; out.workerRc = s.c2cWorkerRc; out.fileCount = s.c2cFileCount; out.totalBytes = s.c2cBytes; if (!signaled && !s.done) { out.error = 1002; return false; } // 超时:传输可能仍在继续 out.error = s.error; return s.c2cResult && s.error == 0; } bool CMcpServer::WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out) { std::unique_lock lk(m_FileXferMutex); auto it = m_FileXferSessions.find(src_id); if (it == m_FileXferSessions.end()) return false; // 会话已收尾:按「无回执」处理 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); while (!it->second.recvAck) { auto slice = std::chrono::milliseconds(250); auto now = std::chrono::steady_clock::now(); if (now + slice > deadline) slice = std::chrono::duration_cast(deadline - now); if (slice.count() <= 0) break; // 超时:老客户端/Windows 目标根本不回执 m_FileXferCv.wait_for(lk, slice); if (McpCallCancelled()) break; } FileTransferSession& s = it->second; out.recvAck = s.recvAck; out.recvStatus = s.recvStatus; out.recvErrno = s.recvErrno; out.recvFileCount = s.recvFileCount; out.recvBytes = s.recvBytes; return s.recvAck; } bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) { std::string localDir, remotePath; { std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end() || !IsFileXferDownloadTool(it->second.tool)) return false; // 会话已清理 → 调用方 CancelIO 收尾 FileTransferSession& s = it->second; if (s.fmSubCtx != nullptr) return true; // 已下发过,防重复 s.fmSubCtx = fmSubCtx; m_FileXferContextToDevice[fmSubCtx] = device_id; // OfflineProc 反查用 localDir = s.localDir; remotePath = s.remotePath; } // 锁外组包下发(Send2Client 异步投递,子链接保持到 ClearFileTransfer 收尾,见 §13 F3)。 // 布局与 FileManagerDlg::OnTransferV2ToLocal 一致:[cmd][targetDir\0][remotePath\0][\0] std::vector pkt; pkt.reserve(1 + localDir.size() + 1 + remotePath.size() + 2); pkt.push_back((BYTE)CMD_DOWN_FILES_V2); pkt.insert(pkt.end(), localDir.begin(), localDir.end()); pkt.push_back(0); pkt.insert(pkt.end(), remotePath.begin(), remotePath.end()); pkt.push_back(0); pkt.push_back(0); fmSubCtx->Send2Client(pkt.data(), (ULONG)pkt.size()); Mprintf("[MCP] download_file: 下发 CMD_DOWN_FILES_V2 remote=%s\n", remotePath.c_str()); return true; } void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const BYTE* buf, ULONG len) { if (len < (ULONG)sizeof(FileChunkPacketV2)) return; const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)buf; if (pkt->nameLength > (uint64_t)(len - sizeof(FileChunkPacketV2))) return; // 畸形包:名字越界 // 与 FileManagerDlg.cpp 落盘同款参数(镜像其 GetPwdHash()/GetHMAC(100))。 std::string hash = GetPwdHash(), hmac = GetHMAC(100); std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end()) return; FileTransferSession& s = it->second; if (!IsFileXferDownloadTool(s.tool)) return; if (s.done) return; // 已出错/完成,丢弃迟到包 s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命 s.bytesReceived += pkt->dataLength; // P11:进度通知的兜底量(文件数未知时用) if (s.streamSubCtx == nullptr) { s.streamSubCtx = streamSubCtx; m_FileXferContextToDevice[streamSubCtx] = device_id; // OfflineProc 反查用 } if (s.transferID == 0) { s.transferID = pkt->transferID; s.totalFiles = pkt->totalFiles; } uint32_t fileIndex = pkt->fileIndex; std::string fileName((char*)(pkt + 1), pkt->nameLength); // ANSI = localDir + relPath // read_file 只收单个普通文件:目录项与超大文件在首包就拒收(不落盘、不建目录)。 if (s.tool == "read_file") { if (pkt->flags & FFV2_DIRECTORY) { s.error = kFileXferPathIsDir; s.done = true; m_FileXferCv.notify_one(); return; } if (pkt->offset == 0) { if (s.maxFileBytes > 0 && pkt->fileSize > s.maxFileBytes) { s.error = kFileXferTooLarge; s.done = true; m_FileXferCv.notify_one(); return; } if (!s.fileEntries.empty() && s.fileEntries.find(fileIndex) == s.fileEntries.end()) { s.error = kFileXferPathIsDir; // 一个路径命中多个文件,read_file 不接受 s.done = true; m_FileXferCv.notify_one(); return; } } } // 目录项:只建目录(RecvFileChunkV2 会 mkdir),不参与 files 输出(见 §13 F4)。 // 与文件项一样先做路径穿越校验(F5):目录项的 filename 同样可能越界(如远程目录名含 ..)。 if (pkt->flags & FFV2_DIRECTORY) { if (!PathWithinDirA(s.localDir, fileName)) { s.error = 1001; s.done = true; m_FileXferCv.notify_one(); return; } s.directoryCount++; RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0); // 目录项不发 COMPLETE 包,而条目顺序由客户端决定(目录可能排在最后,如空子目录), // 完成判定必须在每一类条目定案后都做:文件数 + 目录数覆盖 totalFiles 即完成(F4)。 if (s.totalFiles > 0 && s.filesDone + s.directoryCount >= s.totalFiles) { s.done = true; m_FileXferCv.notify_one(); } return; } if (pkt->offset == 0) { // 路径穿越校验(F5):规范化后必须在 localDir 内。 if (!PathWithinDirA(s.localDir, fileName)) { s.error = 1001; s.done = true; m_FileXferCv.notify_one(); return; } // overwrite=false 且同名已存在 → 跳过该文件(丢弃其后续分块,不落盘)。 if (!s.overwrite && GetFileAttributesA(fileName.c_str()) != INVALID_FILE_ATTRIBUTES) { s.skipIndexes.insert(fileIndex); FileTransferEntry e; e.path = fileName; e.size = pkt->fileSize; s.skipped.push_back(std::move(e)); return; } // 记录文件条目(size 已知;sha256 待 COMPLETE 包回填)。 FileTransferEntry e; e.path = fileName; e.size = pkt->fileSize; s.fileEntries[fileIndex] = std::move(e); } else { if (s.skipIndexes.count(fileIndex)) return; // 已跳过的文件,丢弃后续分块 } int n = RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0); if (n) { s.error = n; s.done = true; m_FileXferCv.notify_one(); } } void CMcpServer::OnDownloadError(uint64_t device_id, context* fmSubCtx, const BYTE* buf, ULONG len) { // [TOKEN_DOWNLOAD_ERROR][win32err:4 LE]:客户端在 FileManager 子连接上直接回报 // 「远端路径全部不存在/不可访问」,此时传输子连接还没建立,不会再有 chunk 到达。 DWORD win32err = 0; if (len >= 1 + sizeof(DWORD)) memcpy(&win32err, buf + 1, sizeof(DWORD)); std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end()) return; FileTransferSession& s = it->second; if (!IsFileXferDownloadTool(s.tool)) return; if (s.fmSubCtx != fmSubCtx) return; // 非本会话的子连接 → 忽略 if (s.done) return; // 已出错/完成,丢弃迟到包 s.error = (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND) ? 1005 : (win32err == ERROR_ACCESS_DENIED) ? 1006 : 1007; s.errorDetail = win32err; // 供 BuildDownloadFile 在文案里带出 win32 码 s.done = true; m_FileXferCv.notify_one(); // 不 CancelIO:由 ClearFileTransfer 统一收尾 } void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len) { if (len < (ULONG)sizeof(FileCompletePacketV2)) return; const FileCompletePacketV2* pkt = (const FileCompletePacketV2*)buf; std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end()) return; FileTransferSession& s = it->second; if (!IsFileXferDownloadTool(s.tool)) return; if (s.done) return; s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命 uint32_t fileIndex = pkt->fileIndex; if (s.skipIndexes.count(fileIndex)) { s.filesDone++; // 跳过的文件:不校验,直接计数 } else { bool verifyOk = HandleFileCompleteV2((const char*)buf, len, 0); auto fe = s.fileEntries.find(fileIndex); if (fe != s.fileEntries.end()) fe->second.sha256 = Sha256Hex(pkt->sha256, 32); if (!verifyOk) { s.error = FEV2_HASH_MISMATCH; s.done = true; m_FileXferCv.notify_one(); return; } s.filesDone++; } // 完成判定:目录不发 COMPLETE 包,故 filesDone 达 totalFiles - directoryCount 即完成(F4)。 uint32_t expectedFiles = (s.totalFiles > s.directoryCount) ? (s.totalFiles - s.directoryCount) : 0; if (s.filesDone >= expectedFiles) { s.done = true; m_FileXferCv.notify_one(); } } bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs, std::vector& files, int& skipped, int& error, DWORD* errorDetail) { if (errorDetail) *errorDetail = 0; std::unique_lock lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end()) { error = 1002; return false; } // 分段等待 + 停滞看门狗:远程路径不存在时客户端一个包都不发,只靠总超时(默认 600s) // 会把整台主机的单飞互斥占满 10 分钟(评审 P2)。改为「N 秒没有任何数据就判停滞」, // 大文件正常传输时每个 chunk 都会续命,不受影响。 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); bool signaled = false; while (true) { auto slice = std::chrono::milliseconds(500); auto now = std::chrono::steady_clock::now(); if (now + slice > deadline) slice = std::chrono::duration_cast(deadline - now); if (slice.count() <= 0) break; // 总超时 if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) { signaled = true; break; } // 进度:已落盘文件数 / 期望文件数(总量未知时退回已收字节数)。 // EmitProgress 内部按 1s 节流,这里每片(500ms)报一次不会把流刷爆。 { const uint32_t expectedNow = (it->second.totalFiles > it->second.directoryCount) ? (it->second.totalFiles - it->second.directoryCount) : 0; if (expectedNow > 0) McpCallProgress((double)it->second.filesDone, (double)expectedNow); else McpCallProgress((double)it->second.bytesReceived); } if (McpCallCancelled()) break; // 取消 → 下面按超时(1002)收尾 if (std::chrono::steady_clock::now() - it->second.lastDataAt >= std::chrono::milliseconds(kFileXferStallMs)) { it->second.error = 1004; // 停滞 it->second.done = true; break; } } FileTransferSession& s = it->second; if (!signaled && !s.done) s.error = 1002; // 总超时 error = s.error; if (errorDetail) *errorDetail = s.errorDetail; // 复制已见文件(成功=完整文件;失败=供调用方删半成品)。跳过的既有文件不在此列。 for (auto& kv : s.fileEntries) files.push_back(kv.second); skipped = (int)s.skipped.size(); const bool ok = s.done && s.error == 0; // 放弃的文件工具:迟到的 TOKEN_DRIVE_LIST(文件管理器子链接首包)不能弹文件管理器窗口。 if (!ok) MarkLateFirstPacketForTool(device_id, s.tool); return ok; } void CMcpServer::ClearFileTransfer(uint64_t device_id) { FileTransferSession s; bool found = false; { std::lock_guard lk(m_FileXferMutex); auto it = m_FileXferSessions.find(device_id); if (it != m_FileXferSessions.end()) { s = std::move(it->second); m_FileXferSessions.erase(it); found = true; } // 反查表按 context* 键,必须随会话一起擦,否则连接池复用同一指针后会被误转成断线事件。 if (s.fmSubCtx) m_FileXferContextToDevice.erase(s.fmSubCtx); if (s.streamSubCtx) m_FileXferContextToDevice.erase(s.streamSubCtx); } if (!found) return; // 锁外关闭两条子链接(CancelIO 触发客户端断开,停掉仍在飞的流式数据)。 if (s.fmSubCtx) s.fmSubCtx->CancelIO(); if (s.streamSubCtx) s.streamSubCtx->CancelIO(); } void CMcpServer::OnFileTransferContextClosed(context* subCtx) { std::lock_guard lk(m_FileXferMutex); auto mapIt = m_FileXferContextToDevice.find(subCtx); if (mapIt == m_FileXferContextToDevice.end()) return; // 不是文件传输子链接 uint64_t device_id = mapIt->second; m_FileXferContextToDevice.erase(mapIt); auto it = m_FileXferSessions.find(device_id); if (it == m_FileXferSessions.end()) return; FileTransferSession& s = it->second; // 无论如何先清裸指针:此后工具线程的 ClearFileTransfer 绝不能再对这条已回收的连接 CancelIO。 bool wasStream = (s.streamSubCtx == subCtx); if (s.fmSubCtx == subCtx) s.fmSubCtx = nullptr; if (s.streamSubCtx == subCtx) s.streamSubCtx = nullptr; // 流式子链接承载数据,它断了传输就不可能完成 → 立即判失败并唤醒工具线程(不用等 timeout)。 // 文件管理器子链接只用来下发命令,断开不代表传输失败,清指针即可。 if (wasStream && !s.done) { s.error = 1003; // 断线 s.done = true; m_FileXferCv.notify_all(); } }