From 3d388f8e45acc03682bd7e8c61faf64b9303305d Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Wed, 28 Oct 2026 20:11:42 +0100 Subject: [PATCH] Feature: Add remote_block_input to MCP remote control A GUI automation run is interrupted the moment a person at the host touches the mouse, and locking the host's keyboard and mouse is the standard answer. The client already implements COMMAND_SCREEN_BLOCK_INPUT and the MFC screen window already sends it, so the tool needs no client change: it puts the same two-byte packet [COMMAND_SCREEN_BLOCK_INPUT][0|1] on the hidden screen sub-connection that remote_open established. The gate is remote_open's own - McpRemoteControl=1 and McpReadonly=0 - because the ability to lock someone out deserves exactly the same door as the ability to drive their desktop, and Linux and Android clients are refused with -32005: they have no branch for this packet at all and would silently ignore it. Locking a host out is only acceptable if every way back in is closed, so the session now carries its own lock state and three paths release it. block=false releases it directly. block=true always carries a deadline (max_block_ms, default 300000, clamped to 1000..3600000) and a watchdog thread started with the MCP server sweeps every 500ms for expired locks, sends the release and records it; the next remote_block_input reports it as auto_unblocked so the model learns that its lock lapsed instead of assuming it is still held. remote_close and the idle reclaim both send block=false before they tear the sub-connection down, because once that connection is gone the server has no channel left and a live client process stays blocked - all three release paths write an audit line, since none of them is something a person can see. The send happens outside the MCP lock, and the watchdog takes the session's busy flag while it releases, so it cannot interleave with an injection or race a close; a failed send keeps the lock marked and retries five seconds later rather than hammering a dead connection every tick, and a session that dies under the watchdog is erased the same way an injection would erase it. Verified against a real Windows client over MCP on a Debug x64 build: block then unblock, block with a 1.5-2s deadline left to expire and reported back as auto_unblocked with the watchdog audit entry at the expected second, block with a ten-minute deadline then remote_close with "(input lock forced off)" in the audit, and the five refusals (missing block, non-boolean block, max_block_ms out of range, unknown session, offline host). The smoke test gained [4d] for those refusals; 54 checks pass. Two limits are worth stating plainly. BlockInput only works when the calling process is elevated (or UIAccess), the client ignores the API's return value, so on an ordinary client the lock silently does nothing and the tool can only promise that the command was delivered - both the tool description and the server instructions say so. And the idle-reclaim release, like the two verified paths, is only exercised at a 300s idle timeout; it shares the same send helper and was reviewed rather than timed out live. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash --- server/2015Remote/McpInternal.cpp | 5 +- server/2015Remote/McpServer.cpp | 362 ++++++++++++++++++++++++++++-- server/2015Remote/McpServer.h | 30 +++ tools/mcp_smoke.ps1 | 24 ++ 4 files changed, 406 insertions(+), 15 deletions(-) diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 7404c86..15097d9 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -370,7 +370,8 @@ struct ToolHints { bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机 }; -// 54 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。 +// 工具的语义登记表(全部工具,含开关门控后才会出现的)。新增工具必须在此登记 +// (漏登记 → 走默认 destructiveHint=true)。 const ToolHints kToolHints[] = { // --- 服务端本机只读 --- { "list_online_hosts", true, false, true, false }, @@ -421,6 +422,8 @@ const ToolHints kToolHints[] = { { "remote_keyboard", false, false, false, true }, { "remote_mouse", false, false, false, true }, { "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板 + // 锁定对端键鼠:不破坏数据,但会把真人挡在电脑外,按「可破坏且非幂等」登记。 + { "remote_block_input", false, true, false, true }, // --- 文件传输 --- { "upload_file", false, true, false, true }, // 覆盖/新增远端文件 { "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件 diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 4faac99..1cd8b78 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -91,7 +91,9 @@ const char* kServerInstructions = u8"进程排查:host_list_processes 或 list_processes 定位,kill_process 结束。这类动作没有真实回执," u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n" u8"GUI 自动化:remote_open 取得 session_id 与分辨率(screen_w/screen_h)→ get_screenshot 看画面 → " - u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。\n" + u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。" + u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(必须带 max_block_ms,到期自动解除;" + u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n" u8"命令执行:exec_command 一次性取输出;需要保持 cd 或环境变量时用 terminal_open + terminal_exec,用毕 terminal_close。\n" u8"\n" u8"5) 安全约定\n" @@ -1464,10 +1466,13 @@ 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(); @@ -1881,6 +1886,14 @@ std::string BuildToolsListResult(const Json::Value& id) { tool["outputSchema"] = BuildRemoteClipboardOutputSchema(); tools.append(tool); } + { + Json::Value tool(Json::objectValue); + tool["name"] = "remote_block_input"; + tool["description"] = u8"锁定或解除目标 Windows 主机的本机键鼠。做 GUI 自动化时先 block=true,真人碰一下鼠标就不会打断流程。必须带期限:max_block_ms(默认 300000 毫秒)到期由服务端自动解除,并在下一次调用结果的 auto_unblocked 里上报;remote_close 或会话闲置回收时服务端也会强制解除。两个限制:1) Windows 只在调用进程具备管理员权限(或 UIAccess)时才允许 BlockInput,普通权限的客户端会静默失败且不上报结果,所以本工具的成功只代表命令已送达、不保证真的锁住了——不要凭它断言对端已被锁;2) 若屏幕子连接因目标机断网被拆,服务端也再没有下发通道,只能等客户端进程退出(BlockInput 随调用线程结束自动释放)。仅 Windows 支持(Linux 客户端不处理该报文,直接报 -32005)。"; + tool["inputSchema"] = BuildRemoteBlockInputInputSchema(); + tool["outputSchema"] = BuildRemoteBlockInputOutputSchema(); + tools.append(tool); + } } // 16) download_file(P6:MCP 文件传输,安全门:McpFileTransfer=1) @@ -4035,6 +4048,10 @@ std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy 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); @@ -4051,6 +4068,7 @@ std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy // 审计:关闭会话(不可关闭)。 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远程控制"))); @@ -4708,6 +4726,186 @@ std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, 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_online_hosts / search_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; + + // Linux/Android 客户端根本没有 COMMAND_SCREEN_BLOCK_INPUT 分支(静默忽略),只做报文的 + // 服务端不做「发了就算成功」的假动作——直接报不支持(能力限制,非参数错误)。 + if (!IsWindowsClient(ctx)) + return BuildError(id, -32005, "remote_block_input is only supported on Windows hosts"); + + 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 字符) @@ -7686,6 +7884,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too 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_block_input") return BuildRemoteBlockInput(id, args, parent); if (toolName == "download_file") return BuildDownloadFile(id, args, parent); if (toolName == "upload_file") return BuildUploadFile(id, args, parent); if (toolName == "copy_files_c2c") return BuildCopyFilesC2C(id, args, parent); @@ -8069,29 +8268,49 @@ bool CMcpServer::MarkScreenCtrlReady(uint64_t device_id, const std::string& sess } int CMcpServer::CloseScreenCtrlSession(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 1; // 不存在(幂等) - if (it->second.sessionId != sessionId) return 2; // token 不匹配 - if (it->second.busy) { - // 注入在飞:置 closed 交注入线程收尾,避免与注入并发擦会话(镜像终端 busy 模式)。 - it->second.closed = true; - return 0; + 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); + } + } + } } - if (it->second.subCtx) m_ScreenCtrlContextToDevice.erase(it->second.subCtx); - m_ScreenCtrlSessions.erase(it); - WebService().ClearMcpTriggered(device_id); - return 0; + // 锁外发(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); @@ -8102,6 +8321,18 @@ int CMcpServer::SweepIdleScreenCtrl(time_t idleTimeoutSec) { } } } + // 锁外解锁,且必须排在关对话框之前:先让客户端丢掉锁定,再拆子连接。 + 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); @@ -8162,6 +8393,96 @@ void CMcpServer::EndScreenCtrlAction(uint64_t device_id, const std::string& sess } } +// ===== 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 ////////////////////////////////////////////////////////////////////////// @@ -8228,11 +8549,24 @@ bool CMcpServer::Start(const std::string& bind, int port) { 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() { - // 先停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。 + // 先停看门狗:它会对屏幕子连接发报文,必须在后端服务拆除之前停止。 + m_blockStop.store(true); + if (m_blockThread.joinable()) m_blockThread.join(); + // 再停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。 m_tlsProxy.Stop(); m_server.stop(); if (m_thread.joinable()) { diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index dec219e..d487f73 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -263,6 +263,28 @@ public: // 屏幕子连接断开(OfflineProc 调用):擦除该子连接对应的会话 + 路由(幂等)。 void OnScreenControlClosed(context* subCtx); + // ===== P10-C:键鼠锁定(remote_block_input)===== + // 锁定状态记在会话上,报文由调用方在锁外发([COMMAND_SCREEN_BLOCK_INPUT][0|1])。 + // 必须在 BeginScreenCtrlAction 之后调用(busy 期间会话不会被并发擦除,状态才有意义)。 + // block=true 时以 maxBlockMs 为自动解锁期限。autoUnblocked 输出「上一次锁定是否因 + // 超过 maxBlockMs 被服务端自动解除」(取走后清除),供工具结果标注。 + // 返回 false = 会话已不存在(防御;正常不会发生)。 + bool ScreenCtrlSetBlock(uint64_t device_id, const std::string& sessionId, bool block, + int maxBlockMs, bool& autoUnblocked); + + // 该会话此刻是否锁定着对端键鼠(仅审计用:remote_close 要能说明自己强制解了锁)。 + bool IsScreenCtrlBlocked(uint64_t device_id, const std::string& sessionId); + + // 键鼠锁定的强制解除:关闭会话 / idle 回收 / 超期自动解锁时必须先发 block=false, + // 否则客户端进程还活着就会一直 BlockInput(人进不来)。三处实现: + // 1) CloseScreenCtrlSession / SweepIdleScreenCtrl —— 擦会话前发(见 .cpp); + // 2) WatchdogScreenBlock —— 每 500ms 扫描超过 blockUntil 的会话; + // 3) OnScreenControlClosed —— 子连接已断,无从下发,只能靠客户端进程退出(既有局限)。 + // 另一个既有局限:Windows 要求调用进程有管理员权限(或 UIAccess)才允许 BlockInput, + // 客户端忽略返回值,低权限下会静默不生效——服务端无从得知,故工具结果只承诺「已送达」。 + void BlockWatchdogLoop(); + void WatchdogScreenBlock(); + // ===== P6:MCP 文件传输(download_file,V2 协议)===== // 下载走 CMD_DOWN_FILES_V2 → 客户端新开流式子连接回传 COMMAND_SEND_FILE_V2 / // COMMAND_FILE_COMPLETE_V2(dstClientID==0)。会话按 device_id 键控,单设备单传输; @@ -588,6 +610,9 @@ private: McpTlsProxy m_tlsProxy; // HTTPS 前端(仅在 m_httpsEnabled 时启动) std::thread m_thread; std::atomic m_running{false}; + // 键鼠锁定看门狗(P10-C):m_blockStop 置位后线程在下一次 100ms 切片退出。 + std::thread m_blockThread; + std::atomic m_blockStop{false}; std::string m_token; std::string m_bind; // Start 传入的监听地址 int m_port = 0; // Start 传入的监听端口 @@ -717,6 +742,11 @@ private: time_t lastActiveAt = 0; // idle 回收用(秒) int screenW = 0; // 物理捕获分辨率(来自 TOKEN_BITMAPINFO) int screenH = 0; + // P10-C 键鼠锁定:inputBlocked 是服务端认为的锁定状态(唯一真相,用于强制解锁); + // blockUntil 是自动解锁期限;blockAutoReleased 待下一次 remote_block_input 上报。 + bool inputBlocked = false; + std::chrono::steady_clock::time_point blockUntil{}; + bool blockAutoReleased = false; }; std::mutex m_ScreenCtrlMutex; std::map m_ScreenCtrlSessions; // device_id → 会话 diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 index ade0444..c64bca4 100644 --- a/tools/mcp_smoke.ps1 +++ b/tools/mcp_smoke.ps1 @@ -514,6 +514,30 @@ if ($writeTools.Count -lt 3) { } } +# ===== 4d. 键鼠锁定(P10-C:remote_block_input)参数校验 ===== +# 这里刻意不真的锁定对端:冒烟测试常常跑在操作者自己的电脑上(客户端与服务端同机), +# 真锁会把正在用电脑的人挡在外面。锁定 / 到期自动解除 / remote_close 强制解除只能人工旁观 +# 目标机来验证(见 docs/Mcp_Next_Plan.md §3.1),本节只覆盖服务端就能判定的拒绝分支。 +$blockTool = @($tools | Where-Object { $_.name -eq 'remote_block_input' }).Count -gt 0 +if (-not $blockTool) { + Write-Host "`n[4d] 键鼠锁定:remote_block_input 未出现(McpRemoteControl=0 或 McpReadonly=1),跳过。" -ForegroundColor Yellow +} elseif ($SkipHost -or -not $HostId) { + Write-Host "`n[4d] 键鼠锁定:没有在线主机,跳过。" -ForegroundColor Yellow +} else { + Write-Host "`n[4d] 键鼠锁定(参数校验)" + $blockCases = @( + @{ name = '缺 block'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such' }; code = -32602 } + @{ name = 'block 非布尔'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = 'maybe' }; code = -32602 } + @{ name = 'max_block_ms 越界'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true; max_block_ms = 500 }; code = -32602 } + @{ name = '会话不存在'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 } + @{ name = '主机不在线'; args = @{ id = '1'; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 } + ) + foreach ($c in $blockCases) { + $r = Rpc '' $null 'remote_block_input' $c.args + Check ('键鼠锁定:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r) + } +} + # ===== 5. 策略拒绝(-32006) ===== # 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。 # 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。