diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index 104e949..221f692 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -2432,6 +2432,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog() McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0); // N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。 McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0); + // 工具默认等待超时(ini-only 键,无设置界面):默认 20000ms,clamp 在 SetToolTimeoutMs 内。 + McpServer().SetToolTimeoutMs(THIS_CFG.GetInt("settings", "McpToolTimeoutMs", 20000)); if (!McpServer().Start(mcpBind, mcpPort)) { Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort); } else { @@ -6873,6 +6875,26 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) ContextObject->CancelIO(); // 无论是否命中,用完即关(无 MFC 对话框接管此子链接) break; } + case TOKEN_FILE_LIST_ERROR: { // 列目录失败(新客户端)【MCP 结构化失败】 + // [token][win32err:4]。与 TOKEN_FILE_LIST 同构:命中则当作响应投递(由 BuildListFiles + // 转译成 -32009/-32010),否则是迟到的孤儿包;两种情况都关子链接。 + uint64_t devId = ContextObject->GetClientID(); + if (McpServer().IsPending(devId)) { + McpServer().TakeMainResponse(devId, szBuffer, len); + } + ContextObject->CancelIO(); + break; + } + case TOKEN_DOWNLOAD_ERROR: { // download_file 无可用文件(新客户端)【MCP 结构化失败】 + // 客户端在「传输子链接还没建立」时就在文件管理器子连接上回报,故此处不 CancelIO: + // 该子链接由 ClearFileTransfer 统一收尾(避免与 tool 线程的 CancelIO 竞争)。 + uint64_t devId = ContextObject->GetClientID(); + if (McpServer().IsFileTransferPending(devId)) { + McpServer().OnDownloadError(devId, ContextObject, szBuffer, len); + } + // 未命中(工具线程已放弃 / MFC 手动下载不会发此 token)→ 忽略,等 ClearFileTransfer。 + break; + } case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】 // 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索 // (工具线程已超时返回部分结果)的尾包,原地丢弃即可。 @@ -6996,6 +7018,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) ContextObject->CancelIO(); // 值包为最后包,无论命中与否用完即关 break; } + case TOKEN_REG_ERROR: { // 注册表打开失败(新客户端)【MCP 结构化失败】 + // 失败时客户端只发这一包(不会有 TOKEN_REG_PATH/KEY),TakeRegError 一次置满三个标志。 + uint64_t devId = ContextObject->GetClientID(); + if (McpServer().IsPending(devId)) { + McpServer().TakeRegError(devId, szBuffer, len); + } + ContextObject->CancelIO(); // 这一包即最后包 + break; + } case TOKEN_SERVERLIST: { // 服务管理【x】 // P3:MCP 挂起时接管。服务列表为一次性子链接回传(CServicesManager 构造即发), // 取走即 CancelIO 关子链接(无 MFC 对话框续用该子链接)。 @@ -7012,6 +7043,17 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) g_2015RemoteDlg->SendMessage(WM_OPENSERVICESDIALOG, 0, (LPARAM)ContextObject); break; } + case TOKEN_SERVICE_ERROR: { // 服务枚举失败(新客户端)【MCP 结构化失败】 + // 典型:客户端未提权,OpenSCManager 失败(win32=5)。命中则当作响应投递(由 + // BuildListServices 立即返回 -32010),不再等 20s 超时。MFC 服务管理对话框有自己的 + // OnReceive,不会走到这里;到达此处的孤儿包直接丢弃并关子链接。 + uint64_t devId = ContextObject->GetClientID(); + if (McpServer().IsPending(devId)) { + McpServer().TakeMainResponse(devId, szBuffer, len); + } + ContextObject->CancelIO(); + break; + } case TOKEN_CONNECTION_LIST: { // 连接管理【x】 g_2015RemoteDlg->SendMessage(WM_OPENCONNECTIONDIALOG, 0, (LPARAM)ContextObject); break; diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 604a71c..839f0b0 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -39,8 +39,8 @@ using namespace McpInternal; namespace { -// P2b 工具等待响应的超时(ms)。MCP 一次性请求:等待子连接回传进程/窗口列表。 -static const int kMcpToolTimeoutMs = 20000; +// P2b 工具等待响应的超时(ms)改为运行期可配:CMcpServer::ToolTimeoutMs(),默认 20000, +// 由 settings.ini 的 [settings] McpToolTimeoutMs 覆盖(见 2015RemoteDlg 的 MCP 初始化块)。 // initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo) std::string BuildInitializeResult(const Json::Value& id) { @@ -2149,7 +2149,7 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for process list"); // 进程名/路径编码按 clientType 判定:Windows 走 A 接口(QueryFullProcessImageNameA 等) @@ -2203,7 +2203,7 @@ std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for window list"); // 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP)。 @@ -2253,7 +2253,7 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for activity history"); // data[0]=token,其后为客户端 ActivityHistory::Dump() 的 UTF-8 纯文本 @@ -2332,7 +2332,7 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C parent->SendScreenPreviewRequest(ctx, reqId, maxWidth, quality); std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for screenshot"); // data = [ScreenPreviewRspHeader][JPEG] @@ -2372,6 +2372,28 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C 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) std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { @@ -2407,15 +2429,20 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20 } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + 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); if (listDrives) { drives = ParseDriveList(data, cp); } else { - // 客户端侧先按 500 条截断(避免子连接包过大),服务端再按 limit/offset 取窗口。 + // 服务端按 500 条截断(避免子连接/JSON 过大),再按 limit/offset 取窗口。 files = ParseFileList(data, 500, cp); } @@ -2469,9 +2496,14 @@ std::string BuildListServices(const Json::Value& id, const Json::Value& args, CM } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + 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); @@ -2544,9 +2576,14 @@ std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CM } std::vector subkeys, values; - if (!mcp.WaitPendingRegistry(devId, subkeys, values, kMcpToolTimeoutMs)) + 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); @@ -2804,7 +2841,7 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy if (!IsCommandAllowed(command, whitelist)) return BuildError(id, -32007, "Command not allowed by whitelist: " + command); - int timeoutMs = kMcpToolTimeoutMs; + int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; @@ -2901,7 +2938,7 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for client log"); // data[0]=token,其后为 Logger 内存 ring buffer 的日志文本(无 '\0' 终止)。 @@ -3288,7 +3325,7 @@ std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CM if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson)) return errJson; - int timeoutMs = kMcpToolTimeoutMs; + int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; @@ -3357,7 +3394,7 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM return BuildError(id, -32008, "Command contains & or | or a newline (breaks output capture); run chained/piped commands as separate terminal_exec calls"); - int timeoutMs = kMcpToolTimeoutMs; + int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; @@ -3599,7 +3636,8 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2 // 多显示器门(§7.2 / §12.1):Observe 抓主屏,Act 注入在虚拟桌面空间,两者仅单显示器时 // 重合。客户端心跳 RES_RESOLUTION = "N:W*H"(N=显示器数);N>1 时归一化坐标会系统性 - // 偏移,阶段一直接拒绝(-32008)。无冒号(老客户端格式)则无法判定,放行不拦。 + // 偏移,阶段一直接拒绝。这是能力限制(改参数也修不好),故报 -32005 而非参数校验错误 -32008。 + // 无冒号(老客户端格式)则无法判定,放行不拦。 { CString res = ctx->GetAdditionalData(RES_RESOLUTION); int colon = res.Find(':'); @@ -3607,7 +3645,7 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2 CString countStr = res.Left(colon); int monitorCount = atoi(countStr); if (monitorCount > 1) - return BuildError(id, -32008, + return BuildError(id, -32005, "Multi-monitor hosts are not supported yet (phase 1): monitor count " + std::to_string(monitorCount)); } @@ -3623,7 +3661,7 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2 if (WebService().HasActiveSession(devId)) return BuildError(id, -32003, "Device busy: a remote desktop session is already active for this host"); - int timeoutMs = kMcpToolTimeoutMs; + int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); int v = 0; if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v; @@ -4573,7 +4611,8 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM std::vector files; int skipped = 0, error = 0; - bool ok = mcp.WaitFileTransferDone(devId, timeoutMs, files, skipped, error); + DWORD errorDetail = 0; + bool ok = mcp.WaitFileTransferDone(devId, timeoutMs, files, skipped, error, &errorDetail); mcp.ClearFileTransfer(devId); // 擦会话 + CancelIO 子链接 if (ok) { @@ -4629,6 +4668,17 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM (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; " @@ -4715,7 +4765,13 @@ static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId, BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return false; } std::vector data; - if (!mcp.WaitPending(devId, data, kMcpToolTimeoutMs)) return false; + 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(); @@ -5058,7 +5114,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy } std::vector data; - if (!mcp.WaitPendingWrite(devId, data, kMcpToolTimeoutMs)) + 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; @@ -5155,7 +5211,7 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C } std::vector data; - if (!mcp.WaitPendingWrite(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for window operation"); AuditManageAction(parent, devId, "operate_window", @@ -5232,7 +5288,7 @@ std::string BuildControlService(const Json::Value& id, const Json::Value& args, } std::vector data; - if (!mcp.WaitPendingWrite(devId, data, kMcpToolTimeoutMs)) + if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs())) return BuildError(id, -32001, "Timeout waiting for service operation"); AuditManageAction(parent, devId, "control_service", @@ -7394,6 +7450,26 @@ void CMcpServer::TakeRegKey(uint64_t device_id, const BYTE* data, ULONG len) { } } +// 工具默认等待超时([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); @@ -7700,6 +7776,27 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const } } +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 (s.tool != "download_file") 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; @@ -7738,7 +7835,9 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len } bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs, - std::vector& files, int& skipped, int& error) { + 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; } @@ -7769,6 +7868,7 @@ bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs, 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(); diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 9e1b692..f7590a6 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -139,6 +139,10 @@ public: // MessageHandle(TOKEN_REG_PATH / TOKEN_REG_KEY) 调用:两包都到齐后置 done 并唤醒等待者。 void TakeRegPath(uint64_t device_id, const BYTE* data, ULONG len); void TakeRegKey(uint64_t device_id, const BYTE* data, ULONG len); + // MessageHandle(TOKEN_REG_ERROR) 调用:键打不开(不存在/拒绝访问)。失败时客户端只发这一包, + // 故一次置满 pathDone/keyDone/done,让 WaitPendingRegistry 立即返回;错误包原样存进 regPath, + // 由 BuildListRegistry 读首字节转译成 -32009/-32010。 + void TakeRegError(uint64_t device_id, const BYTE* data, ULONG len); // 工具线程:等待注册表两包(子键 + 值);成功返回 true 并把两包分别写入 out,超时返回 false。 bool WaitPendingRegistry(uint64_t device_id, std::vector& subkeys, @@ -272,6 +276,11 @@ public: // COMMAND_SEND_FILE_V2:解析 chunk,路径校验 + overwrite 判定 + 落盘(RecvFileChunkV2)。 void OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const BYTE* buf, ULONG len); + // TOKEN_DOWNLOAD_ERROR:客户端在建立传输子链接之前就判定「无可传输文件」(远端路径不存在/ + // 不可访问)。置会话 error=1005(不存在)/1006(拒绝访问)/1007(其他)并唤醒等待线程。 + // 不在此 CancelIO:文件管理器子链接由 ClearFileTransfer 统一收尾。 + void OnDownloadError(uint64_t device_id, context* fmSubCtx, const BYTE* buf, ULONG len); + // COMMAND_FILE_COMPLETE_V2:SHA-256 校验(HandleFileCompleteV2)+ 完成判定。 void OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len); @@ -279,7 +288,8 @@ public: // 无论成败,files 都会返回已见文件的落盘路径(成功=完整文件,失败=供调用方删半成品)。 // 调用方随后必须调 ClearFileTransfer 收尾(擦会话 + CancelIO 子链接)。 bool WaitFileTransferDone(uint64_t device_id, int timeoutMs, - std::vector& files, int& skipped, int& error); + std::vector& files, int& skipped, int& error, + DWORD* errorDetail = nullptr); // 收尾:擦会话 + 锁外 CancelIO 文件管理器/流式两条子链接(幂等)。 void ClearFileTransfer(uint64_t device_id); @@ -348,6 +358,12 @@ public: void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; } bool IsKeylogEnabled() const { return m_keylogEnabled; } + // ===== 工具默认等待超时([settings] McpToolTimeoutMs,ini-only 键)===== + // 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 120000]。 + // 改动需重启服务端生效(与其它 Mcp* 开关一致)。 + void SetToolTimeoutMs(int ms); + int ToolTimeoutMs() const { return m_toolTimeoutMs; } + bool BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx); enum class KeylogWaitResult { Ok, Timeout, Closed }; @@ -607,7 +623,9 @@ private: uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包) uint32_t filesDone = 0; // 已完成的文件数(含跳过的) bool done = false; // 全部完成或出错 - int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;1004=停滞(看门狗) + int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线; + // 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败 + DWORD errorDetail = 0; // error=1005/1006/1007 时的 win32 码(原样带进文案,便于分支/排查) std::map fileEntries; // fileIndex → {path,size,sha256} std::set skipIndexes; // overwrite=false 跳过的 fileIndex std::vector skipped; // 跳过的文件(供输出) @@ -669,6 +687,7 @@ private: bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具) bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务) bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog) + int m_toolTimeoutMs = 20000; // 工具默认等待超时(McpToolTimeoutMs,见 SetToolTimeoutMs) }; // 全局访问器(仿 WebService(),见 WebService.h 末尾) diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 index 97c31d2..1e9ce54 100644 --- a/tools/mcp_smoke.ps1 +++ b/tools/mcp_smoke.ps1 @@ -250,6 +250,31 @@ if (-not $SkipHost) { Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1) } +# ===== 4b. 结构化失败(新客户端:TOKEN_*_ERROR → -32009/-32010) ===== +# 老客户端没有这些回报包,对应工具会退化成「成功 + 空列表」或超时—— +# 所以这三条只对「新客户端」成立;失败时先确认目标机客户端是否已升级。 +if (-not $SkipHost -and $drive) { + Write-Host "`n[4b] 结构化失败" + $ghostDir = $drive.TrimEnd('\') + '\mcp_smoke_no_such_dir_xyz' + $lf = Rpc '' $null 'list_files' @{ id = $HostId; path = $ghostDir } + Check 'list_files 不存在路径返回 -32009' ` + ($lf.error -and [int]$lf.error.code -eq -32009) ([string]$lf.error.message) + + $lr = Rpc '' $null 'list_registry' @{ id = $HostId; path = 'HKEY_LOCAL_MACHINE\SOFTWARE\MCPSmokeNoSuchKey_xyz' } + Check 'list_registry 不存在键返回 -32009' ` + ($lr.error -and [int]$lr.error.code -eq -32009) ([string]$lr.error.message) + + if (@($tools | Where-Object { $_.name -eq 'download_file' }).Count -gt 0) { + $dlDir = Join-Path $env:TEMP 'mcp_smoke_dl' + $dl = Rpc '' $null 'download_file' @{ id = $HostId; remote_path = ($ghostDir + '\a.txt'); local_dir = $dlDir } + Check 'download_file 不存在路径返回 -32009' ` + ($dl.error -and [int]$dl.error.code -eq -32009) ([string]$dl.error.message) + Remove-Item -LiteralPath $dlDir -Recurse -Force -ErrorAction SilentlyContinue + } else { + Write-Host " download_file 未开启(McpFileTransfer),跳过下载负例。" -ForegroundColor Yellow + } +} + # ===== 5. 策略拒绝(-32006) ===== # 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。 # 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。