Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4cb34fea9 | ||
|
|
1456882f16 | ||
|
|
3b1626f415 | ||
|
|
315a0855dc | ||
|
|
eaa10cc7d3 |
No files matched your search
+36
-6
@@ -438,8 +438,7 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
|
||||
|
||||
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
|
||||
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
|
||||
BYTE bToken = TOKEN_FILE_LIST;
|
||||
return Send(&bToken, 1);
|
||||
return SendListError(ERROR_INVALID_NAME);
|
||||
}
|
||||
|
||||
UINT nRet = 0;
|
||||
@@ -461,8 +460,8 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
|
||||
hFile = FindFirstFile(strPath, &FindFileData);
|
||||
|
||||
if (hFile == INVALID_HANDLE_VALUE) {
|
||||
BYTE bToken = TOKEN_FILE_LIST;
|
||||
return Send(&bToken, 1);
|
||||
// 路径不存在/不可访问:回结构化失败(TOKEN_FILE_LIST_ERROR),不再和「空目录」混为一包。
|
||||
return SendListError(GetLastError());
|
||||
}
|
||||
|
||||
*lpList = TOKEN_FILE_LIST;
|
||||
@@ -850,6 +849,32 @@ int CFileManager::SendToken(BYTE bToken)
|
||||
return Send(&bToken, 1);
|
||||
}
|
||||
|
||||
// 列目录失败的结构化回报:[TOKEN_FILE_LIST_ERROR:1][win32err:4 LE]。
|
||||
// 服务端(MCP list_files)据此返回「路径不存在/权限不足」,而不是一个空列表。
|
||||
// 随后再补一个老的 1 字节 TOKEN_FILE_LIST:老服务端不认识新 token,仍按「空目录」处理,
|
||||
// 行为与改动前完全一致。
|
||||
UINT CFileManager::SendListError(DWORD dwErr)
|
||||
{
|
||||
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_FILE_LIST_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
int n = Send(pkt, (UINT)sizeof(pkt));
|
||||
SendToken(TOKEN_FILE_LIST);
|
||||
return n > 0 ? (UINT)n : 0;
|
||||
}
|
||||
|
||||
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
|
||||
// 走文件管理器子连接(传输子连接此时尚未建立),服务端立即失败而不是等停滞看门狗。
|
||||
void CFileManager::SendDownloadError(DWORD dwErr)
|
||||
{
|
||||
if (dwErr == 0) dwErr = ERROR_FILE_NOT_FOUND;
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_DOWNLOAD_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
m_ClientObject->Send2Server((char*)pkt, (UINT)sizeof(pkt));
|
||||
}
|
||||
|
||||
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
|
||||
{
|
||||
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\') {
|
||||
@@ -1144,19 +1169,23 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
|
||||
|
||||
if (remotePaths.empty()) {
|
||||
Mprintf("[V2] 没有要传输的文件\n");
|
||||
SendDownloadError(ERROR_INVALID_PARAMETER);
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集所有文件(展开目录)
|
||||
std::vector<std::string> allFiles;
|
||||
std::vector<std::string> rootCandidates; // 用于计算公共根目录
|
||||
DWORD dwFirstErr = 0; // 首个失败的 win32 码(全部不存在时回传)
|
||||
|
||||
for (const auto& remotePath : remotePaths) {
|
||||
std::string localPath = ExpandPath(remotePath.c_str());
|
||||
|
||||
DWORD attrs = GetFileAttributesA(localPath.c_str());
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES)
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES) {
|
||||
if (dwFirstErr == 0) dwFirstErr = GetLastError();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
|
||||
// 目录:递归收集
|
||||
@@ -1175,7 +1204,8 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
Mprintf("[V2] 没有找到可传输的文件\n");
|
||||
Mprintf("[V2] 没有找到可传输的文件 (win32=%lu)\n", dwFirstErr);
|
||||
SendDownloadError(dwFirstErr);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ private:
|
||||
void CreateFolder(LPBYTE lpBuffer);
|
||||
void Rename(LPBYTE lpBuffer);
|
||||
int SendToken(BYTE bToken);
|
||||
UINT SendListError(DWORD dwErr); // 列目录失败的结构化回报(TOKEN_FILE_LIST_ERROR + win32 码)
|
||||
void SendDownloadError(DWORD dwErr); // 下载无可用文件的结构化回报(TOKEN_DOWNLOAD_ERROR + win32 码)
|
||||
|
||||
void CreateLocalRecvFile(LPBYTE lpBuffer);
|
||||
void SetTransferMode(LPBYTE lpBuffer);
|
||||
|
||||
@@ -57,6 +57,22 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
|
||||
// 子键包(TOKEN_REG_PATH):无子键时也回传空包,保证服务端(含 MCP 无头查询)
|
||||
// 能确定性收齐 PATH+KEY 两包,无需靠超时猜测是否有第二包。
|
||||
char *szBuffer= Opt.FindPath();
|
||||
// 键打不开(不存在 / 路径不存在 / 拒绝访问 …):回结构化错误包。此前这种情况与
|
||||
// 「空键」同为 NULL,服务端只能回一个空列表,调用方无法区分。
|
||||
LSTATUS st = Opt.GetLastOpenStatus();
|
||||
if (st != ERROR_SUCCESS) {
|
||||
BYTE pkt[1 + sizeof(LSTATUS)] = { 0 };
|
||||
pkt[0] = TOKEN_REG_ERROR;
|
||||
memcpy(pkt + 1, &st, sizeof(LSTATUS));
|
||||
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
|
||||
// 老服务端不认识 TOKEN_REG_ERROR:补上原来的两个空包,仍按「空键」处理,行为不变。
|
||||
char empty[1 + sizeof(REGMSG)] = { 0 };
|
||||
empty[0] = TOKEN_REG_PATH;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
empty[0] = TOKEN_REG_KEY;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
return;
|
||||
}
|
||||
if(szBuffer!=NULL) {
|
||||
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
|
||||
//目录下的目录
|
||||
|
||||
@@ -60,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
|
||||
}
|
||||
|
||||
ZeroMemory(KeyPath,MAX_PATH);
|
||||
m_lastOpenStatus = ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
RegisterOperation::~RegisterOperation()
|
||||
@@ -73,7 +74,8 @@ char* RegisterOperation::FindPath()
|
||||
char *szBuffer=NULL;
|
||||
HKEY hKey; //注册表返回句柄
|
||||
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
|
||||
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
|
||||
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
|
||||
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
|
||||
DWORD dwIndex=0,NameCount,NameMaxLen;
|
||||
DWORD KeySize,KeyCount,KeyMaxLen,MaxDataLen;
|
||||
//这就是枚举了
|
||||
@@ -127,7 +129,8 @@ char* RegisterOperation::FindKey()
|
||||
|
||||
char *szBuffer=NULL;
|
||||
HKEY hKey; //注册表返回句柄
|
||||
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
|
||||
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
|
||||
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
|
||||
DWORD dwIndex=0,NameSize,NameCount,NameMaxLen,Type;
|
||||
DWORD KeyCount,KeyMaxLen,DataSize,MaxDataLen;
|
||||
//这就是枚举了
|
||||
|
||||
@@ -19,6 +19,11 @@ public:
|
||||
char KeyPath[MAX_PATH];
|
||||
void SetPath(char *szPath);
|
||||
char* FindKey();
|
||||
// 最近一次 RegOpenKeyEx 的状态:区分「键打不开」(不存在/拒绝访问)与「键为空」
|
||||
// (后者返回 NULL 但状态是 ERROR_SUCCESS)。
|
||||
LSTATUS GetLastOpenStatus() const { return m_lastOpenStatus; }
|
||||
private:
|
||||
LSTATUS m_lastOpenStatus;
|
||||
};
|
||||
|
||||
#endif // !defined(AFX_REGISTEROPERATION_H__BB4F3ED1_FA98_4BA4_97D6_A78E683131CC__INCLUDED_)
|
||||
@@ -24,11 +24,20 @@ CServicesManager::~CServicesManager()
|
||||
|
||||
VOID CServicesManager::SendServicesList()
|
||||
{
|
||||
LPBYTE szBuffer = GetServicesList();
|
||||
DWORD dwErr = 0;
|
||||
LPBYTE szBuffer = GetServicesList(&dwErr);
|
||||
if (szBuffer == NULL) {
|
||||
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
|
||||
Mprintf("Get service list failed[IP: %s][win32=%lu]\n", m_ClientObject->GetPublicIP().c_str(), dwErr);
|
||||
// 结构化失败回报:MCP 端据此立即返回「权限不足/SCM 打不开」,不必等 20s 超时。
|
||||
// 老服务端不认识 TOKEN_SERVICE_ERROR,走 default 分支丢弃,随后仍按原样收到 ClientMsg。
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_SERVICE_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
|
||||
// 保留原有弹窗消息:老服务端与 MFC 服务管理器(新 token 由对话框忽略)行为不变。
|
||||
char buf[128];
|
||||
sprintf_s(buf, "Get service list failed[IP: %s]", m_ClientObject->GetPublicIP().c_str());
|
||||
Mprintf("%s\n", buf);
|
||||
ClientMsg msg("服务管理", buf);
|
||||
m_ClientObject->Send2Server((char*)&msg, sizeof(msg));
|
||||
return;
|
||||
@@ -42,7 +51,7 @@ VOID CServicesManager::SendServicesList()
|
||||
#define skCrypt(p) p
|
||||
#endif
|
||||
|
||||
LPBYTE CServicesManager::GetServicesList()
|
||||
LPBYTE CServicesManager::GetServicesList(DWORD* err)
|
||||
{
|
||||
LPENUM_SERVICE_STATUS ServicesStatus = NULL;
|
||||
LPQUERY_SERVICE_CONFIG ServicesInfor = NULL;
|
||||
@@ -52,12 +61,14 @@ LPBYTE CServicesManager::GetServicesList()
|
||||
DWORD dwLength = 0;
|
||||
DWORD dwOffset = 0;
|
||||
if((m_hscManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS))==NULL) {
|
||||
if (err) *err = GetLastError(); // 典型 5=拒绝访问(未提权)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ServicesStatus = (LPENUM_SERVICE_STATUS) LocalAlloc(LPTR,64*1024);
|
||||
|
||||
if (ServicesStatus==NULL) {
|
||||
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
|
||||
CloseServiceHandle(m_hscManager);
|
||||
return NULL;
|
||||
}
|
||||
@@ -75,8 +86,10 @@ LPBYTE CServicesManager::GetServicesList()
|
||||
&dwResumeHandle);
|
||||
|
||||
szBuffer = (LPBYTE)LocalAlloc(LPTR, MAX_PATH);
|
||||
if (szBuffer == NULL)
|
||||
if (szBuffer == NULL) {
|
||||
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
|
||||
return NULL;
|
||||
}
|
||||
szBuffer[0] = TOKEN_SERVERLIST;
|
||||
dwOffset = 1;
|
||||
for (unsigned long i = 0; i < dwServicesCount; ++i) { // Display The Services,显示所有的服务
|
||||
|
||||
@@ -20,7 +20,7 @@ public:
|
||||
CServicesManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CServicesManager();
|
||||
VOID SendServicesList();
|
||||
LPBYTE GetServicesList();
|
||||
LPBYTE GetServicesList(DWORD* err = NULL);
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
void ServicesConfig(PBYTE szBuffer, ULONG ulLength);
|
||||
SC_HANDLE m_hscManager;
|
||||
|
||||
@@ -330,6 +330,13 @@ enum {
|
||||
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
|
||||
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
|
||||
|
||||
// MCP 结构化失败回报(客户端 → 服务端,仅失败分支发送;成功路径报文不变)。
|
||||
// 170-198 是当前未占用的字节值,显式赋值避免后续插入重编号。
|
||||
TOKEN_SERVICE_ERROR = 170, // [token:1][win32err:4 LE] 服务枚举失败(典型:OpenSCManager 权限不足)
|
||||
TOKEN_FILE_LIST_ERROR = 171, // [token:1][win32err:4 LE] 文件列表失败(典型:路径不存在/非法)
|
||||
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
|
||||
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
|
||||
|
||||
TOKEN_DECRYPT = 199,
|
||||
TOKEN_REGEDIT = 200, // 注册表
|
||||
COMMAND_REG_FIND, // 注册表 管理标识
|
||||
|
||||
+32
-4
@@ -259,6 +259,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
|
||||
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
|
||||
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
||||
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
||||
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
|
||||
|
||||
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
|
||||
|
||||
@@ -492,7 +493,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
|
||||
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
|
||||
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
|
||||
- `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。
|
||||
- `list_files` 仍受服务端 `ParseFileList` 的 500 条硬限制(`total=500` 且原目录确有更多条目时表示截断,不是服务端分页)。客户端侧不截断、按需扩缓冲一次性回全量;本轮未加 `truncated` 标记(要加得改服务端 `ParseFileList` 的调用约定),仍靠「`total=500` 且 `hasMore`」判断。
|
||||
|
||||
---
|
||||
|
||||
@@ -663,10 +664,37 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
|
||||
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open` | 等前一个结束或先 `*_close` |
|
||||
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
|
||||
| `-32005` | Not supported on this host | 需要 Windows 的工具用在 LNX/MAC/APK 主机上 | 换 Windows 主机,或改用跨平台只读工具(`list_files` 等) |
|
||||
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
|
||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
||||
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
|
||||
| `-32008` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符 `&\|<>^` 或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符 | 按 `message` 修正参数后重试 |
|
||||
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
|
||||
| `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
|
||||
|
||||
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
|
||||
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
|
||||
- **工具放弃后的「迟到首包」一律吸收,不会弹 MFC 窗口**:文件/服务/注册表/进程/日志/终端这几族的子连接都是「建成即发首包」。工具超时清理挂起后,客户端可能才把首包发上来,此时没有挂起会话,`MessageHandle` 只能把它当成人手点击,于是弹出文件管理器/服务管理器/注册表/进程管理器/日志/终端窗口(构造超时场景时实测出现过文件管理器窗口)。现在各等待函数在**放弃分支**登记「设备 → 该工具的首包 token」(`CMcpServer::MarkLateFirstPacketForTool`),包到达时 `TakeToolFirstPacket` 一次性吸收并关子连接:`list_files`/`download_file`/`upload_file`/`search_file` → `TOKEN_DRIVE_LIST`;`list_services`/`control_service` → `TOKEN_SERVERLIST`;`list_registry` → `TOKEN_REGEDIT`;`list_processes`/`kill_process` → `TOKEN_PSLIST`;`list_windows`/`operate_window` → `TOKEN_WSLIST`;`get_client_log` → `TOKEN_REPORT_LOG`;`get_activity_history` → `TOKEN_REPORT_ACTIVITY`(主连接,只丢包不关连接);`exec_command`/`terminal_open` → `TOKEN_SHELL_START` + `TOKEN_TERMINAL_START`。成功路径不登记,命中即消费,标记 5 分钟后过期。**已知代价**:同一主机在工具超时后 5 分钟内手动点开对应窗口,可能被这枚标记吞掉一次(再点即可)——比误弹窗口更可接受。
|
||||
- **MCP 工具在飞时不弹客户端的老式提示框**:新客户端在失败分支同时发结构化 token 和老的 `ClientMsg`(只为兼容老服务端),后者会 `PostMessageA(WM_SHOWERRORMSG)` 在服务端 UI 上弹框。`TOKEN_CLIENT_MSG` 分支现在发现该设备有挂起请求/文件传输时就只记日志不弹框。实测 `list_services`(未提权)时客户端子连接已被服务端关掉,`ClientMsg` 根本发不出来,这条属兜底。
|
||||
- **`download_file` 有停滞看门狗兜底**:60 秒没收到任何数据即失败,返回 `-32001` 且文案带 `File transfer stalled: no data received for 60s ...`。新客户端的 `TOKEN_DOWNLOAD_ERROR` 让这条路基本不再触发,看门狗只用来兜住「客户端卡住/老客户端」。
|
||||
|
||||
- `-32006` 会额外在审计日志里记一条 `CALL_DENIED`(§10.8),其余错误只体现在 `CALL_FAIL` 行。
|
||||
- 批量调用(带 `ids[]`)**整体不报错**:每个 id 的结果单独带 `error`,顶层用 `succeeded` / `failed` / `skipped` 汇总;只有整批请求本身非法(超过 50 个 id、写操作传 `ids`)才返回顶层 `-32602`。
|
||||
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
|
||||
- 本次验证(Debug 实例,`McpKeylog` 临时置 0):`get_keylog` 返回 `-32006`,`Bin\logs\mcp_audit.log` 末尾出现 `CALL_DENIED ... tool=get_keylog reason=Keyboard log is disabled (McpKeylog=0)`;此时冒烟 34/34 通过。恢复开关后 `-32006` 与审计两条转为跳过,32/32 通过;带 `-SearchPath` 时 37/37 通过。
|
||||
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)、`-32009`(新客户端的 `list_files`/`list_registry`/`download_file` 不存在路径负例)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
|
||||
- 本次验证(Debug 实例):冒烟 **40/40 通过**(原 37 项 + 3 条 `-32009` 负例);`-32010` 由 `list_services`(未提权客户端,win32=5)、`list_files "C:\System Volume Information"`、`list_registry "HKLM\SAM\SAM\Domains\Account"` 三条实测覆盖。
|
||||
|
||||
### 12.1 命令哨兵与输出清洗(测试报告 P1/P3/P4 的修复)
|
||||
|
||||
`exec_command` 与 `terminal_exec` 都靠哨兵判断「命令已执行完、退出码是多少」。哨兵有两种形态:
|
||||
|
||||
| 客户端 | 下发内容 | 退出码 |
|
||||
|---|---|---|
|
||||
| ConPTY(`is_pty=true`,新版 Windows 客户端) | 第一行 `@echo off & <cmd>`;第二行单独 `echo __MCP_DONE_<nonce>__%errorlevel%` | 命令的真实退出码 |
|
||||
| 老 ShellManager 管道(`is_pty=false`) | 单行 `<cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1` | 仅 0 / 非 0 |
|
||||
|
||||
**为什么 PTY 要分两行下发**:`rem hello`、`cmd /c exit 0`、`if`、`for` 这类「吞行」命令会把同一行里的 `&& echo 哨兵` 一起吞掉(`rem`/`cmd /c` 把行内剩余文本当作自己的参数),哨兵永不出现,于是必然超时并销毁会话。哨兵独立成行后由 shell 自己执行,不再受命令行影响。老客户端只能维持单行形态:`client/ShellManager.cpp` 按「写入字节数」跳过回显,多写一行会吃掉上一行的输出。
|
||||
|
||||
**为什么用 `%errorlevel%`**:ConPTY 会把输入整行回显进输出流(80 列会折行)。回显文本里是字面 `%errorlevel%` 而不是数字,而 `FindSentinel` 只认「标记 + 数字」,折行回显再也不可能被误判成哨兵(评审 P3:`ver` 曾因回显里的 `__1` 被判成 `exit_code=1`),同时还能拿到真实退出码(如 `nosuchcmd` 的 9009)。
|
||||
|
||||
**输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。
|
||||
|
||||
**已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。
|
||||
@@ -295,10 +295,8 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
|
||||
| -32002 | 设备/会话不存在 | `id` 无在线主机、`session_id` 不存在或不匹配 |
|
||||
| -32003 | 设备/会话忙 | 已有控制会话、人类远程桌面占用、`get_screenshot` 在飞 |
|
||||
| -32004 | 发送失败 | 注入命令发送失败 |
|
||||
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act) |
|
||||
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act)/ **多显示器主机(阶段一)** |
|
||||
| -32006 | 被开关禁用 | `McpRemoteControl=0` 或 `McpReadonly=1` |
|
||||
| -32008 | 非法/被拒参数 | 多显示器未支持时的 `remote_open` 降级拒绝(阶段一) |
|
||||
|
||||
---
|
||||
|
||||
## 11. 配置项
|
||||
@@ -317,7 +315,7 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
|
||||
|
||||
### 12.1 阶段一(本期)
|
||||
|
||||
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32008`)。
|
||||
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32005`,能力限制而非参数错误)。
|
||||
- 注入基于**绝对坐标** `SendInput`,要求客户端处于可注入的桌面会话(已登录、非锁屏/非 UAC 安全桌面);锁屏/UAC 提示场景注入无效(客户端 `SendInput` 限制),设计文档记录为已知限制。
|
||||
- **代聊实验使能项**:窗口抓屏(`COMMAND_SCREEN_WINDOW`)、UTF-8 剪贴板、窗口聚焦随阶段一落地(§17)。
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# YAMA MCP 服务测试报告
|
||||
|
||||
- 日期:2026-10-25(两轮:本机回环 + 虚拟机复测)
|
||||
- 环境:
|
||||
- 第1轮:Debug 服务端 `Yama_x64d.exe` + 本机被控端 `ghost.exe`(Windows 11,双显示器)
|
||||
- 第2轮:同一 Debug 服务端 + VirtualBox 虚拟机被控端(`DESKTOP-A55C0OI`,Windows 10 19045,单显示器 1718x920,clientType=MDLL)+ 重启后的本机被控端
|
||||
- 配置:`Bin\settings.ini`(McpEnabled=1,McpPort=6545,McpBind=127.0.0.1,McpReadonly=0,全部 `Mcp*` 开关开启)
|
||||
- 方法:Python 直连 `http://127.0.0.1:6545/mcp`(JSON-RPC 2.0),辅以 `tools/mcp_smoke.ps1`、审计日志、`get_client_log`、代码审读交叉验证
|
||||
- 敏感操作约束:删除类操作仅针对本次自建的临时文件/目录(本机 `%TEMP%\yama_mcp_test`、VM 同名目录),测试后已全部清理
|
||||
|
||||
---
|
||||
|
||||
## 0. 复核与处置(同日二次复核)
|
||||
|
||||
复核方式:逐条回到源码确认现象与根因,再在 Debug 实例(`Bin\Yama_x64d.exe` + 本机 `ghost.exe`,Windows 11 双屏 ConPTY 客户端)上端到端复现与验证修复。复核用的客户端配置临时改为直连本机(`x64\Debug\settings.ini`:`master=127.0.0.1`、`ghost=6543`、`UseFrp=0`,原文件备份为 `settings.ini.bak_mcptest`);修复后在 Debug 实例上 `tools/mcp_smoke.ps1 -SearchPath C:\Windows\Fonts` **37/37 通过**。
|
||||
|
||||
| 编号 | 复核结论 | 处置 | 验证证据(修复后实测) |
|
||||
|---|---|---|---|
|
||||
| P1 | 属实 | **已修**。ConPTY 下哨兵改为独立一行(`@echo off & <cmd>` + 单独 `echo __MCP_DONE_<nonce>__%errorlevel%`);会话因超时被销毁后留 600s 墓碑,报错文案区分「被销毁」与「id 写错」。老客户端(非 PTY)保持单行 `&&` 形态,行为不变。 | `rem hello` → exit 0(原 100% 超时);`cmd /c exit 0` → exit 0;`cmd /c echo abc` → `abc`。超时路径:`ping -n 40` 配 `timeout_ms=3000` → `-32001`,随后同一 session → `-32002 "Terminal session was destroyed after this command timed out (waited 3000 ms); call terminal_open again"`;假 id → `-32002 "Terminal session not found: <id> (call terminal_open first)"`;销毁后 `terminal_open` 立即成功 |
|
||||
| P2 | 属实(结论成立),但「10 个纯本地 DB 读取」的**表述有误**——被挡的是经主连接向目标机取数据的远程机器管理工具(`host_list_processes/windows/network_state/scheduled_tasks/services/…`、`host_get_hosts_file` 等,都走 `BeginPending`),属 single-flight 设计;纯服务端本地工具(`get_server_status`、`get_audit_log`、`host_set_remark` 等)不受影响 | **已修**(选了「快速失败」):文件传输加 60s 停滞看门狗,`timeout_ms` 内只要持续有数据就不受影响;默认超时保持 600s(避免误杀大文件)。互斥豁免未做——远程工具之间互斥本身就是有意的。 | 不存在路径 `C:/no_such_dir_zzz_mcp` → **60096ms** 失败,`-32001 "File transfer stalled: no data received for 60s (the remote path is probably missing or inaccessible; verify it with list_files first)"`(原为 `ms=600004`);挂起期间 `get_server_status` 2120ms OK、`get_audit_log` 20ms OK,远程 `list_files` 仍 `-32003`;失败后主机立刻释放,冒烟脚本随即 37/37 通过。**2026-10-25 二次修**:新客户端在建立传输子链接前就回 `TOKEN_DOWNLOAD_ERROR`(173),`download_file` 不存在路径现在 **0.07s → `-32009`**(`Remote path does not exist: ... (win32=3)`),60s 停滞看门狗降级为兜底 |
|
||||
| P3 | 属实 | **已修**。`%errorlevel%` 在回显文本里是字面模板而非数字,`FindSentinel` 改为「从后往前找第一个『标记+数字』」,不再依赖行首。 | `ver` → exit 0(原 1);`nosuchcmd_zzz` → 9009;`cmd /c exit 0` → 0;`set NOVAR` → 1 |
|
||||
| P4 | 属实 | **已修**。清洗改为三段:删到「命令行回显」结束(顺带清掉 shell 启动画面/提示符)→ 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 的收尾(会残留 `\`)。设计见 `docs/Mcp_Design.md` §12.1。 | 上述命令的 stdout 全部无 `@echo off`、无 `__MCP_DONE_*`、无提示符/空行;`type` 报错文本无残留反斜杠 |
|
||||
| P5 | 属实 | **已修**(`McpInternal.cpp` 注解表 `get_activity_history` → `openWorld=true`,附代码注释说明它经 `COMMAND_QUERY_ACTIVITY` 触达远程主机) | 代码审查 + 与 §10.2 口径一致 |
|
||||
| P6 | 属实(`OpenSCManager` 权限不足,客户端失败分支回普通消息包) | **已修**:新增 `TOKEN_SERVICE_ERROR`(170),客户端 `SendServicesList` 失败时回 `[170][win32:4]`(并保留原 `ClientMsg`,老服务端行为不变);服务端转译成 `-32010`,文案点明需要管理员权限 | 非提权客户端 `list_services` → **268ms `-32010`**(`Failed to enumerate services: access denied (win32=5). service enumeration requires the client to run elevated (administrator)`;原为 20s `-32001`) |
|
||||
| P7 | 属实 | **已修**(文档):`docs/Mcp_Design.md` §12 补齐 `-32007`/`-32008`/`-32009` 并注明 `-32008` 的四类语义 | 文档核对 |
|
||||
| P8 | 属实 | **已修**:新增 `TOKEN_FILE_LIST_ERROR`(171) / `TOKEN_REG_ERROR`(172),客户端失败分支回 `[token][win32/lstatus:4]`;服务端按 `2/3 → -32009`、`5 → -32010` 转译,空目录/空键仍返回成功空列表 | `list_files C:\no_such_dir_xyz` → **0.22s `-32009`**、`list_files C:\System Volume Information` → **0.06s `-32010 (win32=5)`**;`list_registry HKLM\Software\NoSuchKeyXYZ` → **0.10s `-32009`**、`HKLM\SAM\SAM\Domains\Account` → **0.08s `-32010`**;空目录/正常目录/正常键返回不变 |
|
||||
|
||||
**结论**:报告的问题清单与根因分析全部成立(仅 P2 有一处表述需要更正);P1/P3/P4(同一处哨兵机制)与 P5/P7、P2 的「长时间锁定」已在服务端修复并端到端验证,P6/P8 已在放开「客户端可小改」后按结构化失败回报修复(见上表,均为亚秒级返回)。
|
||||
|
||||
---
|
||||
|
||||
53 个工具全部可达,冒烟脚本 32/32 通过。功能面整体质量良好;VM 复测轮验证了第1轮受条件所限未能覆盖的远程控制族(11/11)、跨机文件往返、真实 kill 目标校验,并把第1轮两大疑难问题(exec_command 超时、list_services 超时)推进到根因定性。
|
||||
|
||||
最终问题清单:**2 个高优先级**(哨兵机制对吞行命令必然超时并销毁会话;download_file 失败路径长时间锁定主机)、**3 个中优先级**(exit_code 不可靠、stdout 内部实现泄漏、get_activity_history 注解错误)、**3 个低优先级**(list_services 权限失败无解释、错误码缺漏/-32008 复用、路径类工具静默空结果)。每条问题的逐条复核结论、处置与修复后实测证据见 §0。
|
||||
|
||||
## 2. 问题清单
|
||||
|
||||
### P1(高):哨兵机制——「吞行」命令 100% 超时,且销毁持久会话
|
||||
|
||||
哨兵方案:发送 `@echo off & <cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1`,服务端扫描输出定位哨兵取退出码(`McpServer.cpp:2721/3027` 发送、`FindSentinel :6195` 匹配)。
|
||||
|
||||
缺陷:**任何会消费行内剩余文本的命令都会把哨兵一起「吞掉」**,导致哨兵永远不出现:
|
||||
|
||||
| 命令 | 结果 | 机制 |
|
||||
|---|---|---|
|
||||
| `rem hello` | 超时 | `rem` 把整行剩余部分当注释,`&& echo 哨兵` 不执行 |
|
||||
| `cmd /c exit 0` | 超时(2/2 会话复现) | `cmd /c` 把 `&& echo 哨兵` 一并传给子进程,子进程 `exit` 即退 |
|
||||
| `if`/`for` 同理 | 预期同 | 同类吞行语句 |
|
||||
|
||||
后果链:20s 等待 → `-32001 Timeout waiting for command output`;**持久终端路径上 `WaitTermCommand` 超时直接销毁会话**(`McpServer.cpp:6400` 附近),后续所有 `terminal_exec` 报 `-32002 "Terminal session not found, not ready, or busy"`——报错文案无法区分「会话已被超时销毁」与「id 写错」。
|
||||
|
||||
- 正常对照:`whoami` 35/35 成功(62-217ms)、`set NOVAR`(失败有哨兵)正确返回 exit=1、`cmd /c echo abc`/`cmd /c ver`(子进程有输出)成功。
|
||||
- 建议:
|
||||
1. 哨兵改为独立行下发(先发命令行,再单独发 `echo __MCP_DONE_...__0 || echo ...` 第二行,或用 `(%cmd%) & (echo sentinel)` 子shell包裹);
|
||||
2. 会话被超时销毁后,`terminal_exec` 对该 session_id 返回专门的错误文案(如 "session destroyed after timeout; re-open");
|
||||
3. 文档标注 `exec_command`/`terminal_exec` 不支持 `rem`、`cmd /c` 等吞行命令。
|
||||
|
||||
**复核(2026-10-25)**:属实。已按建议 1、2 修复并验证(PTY 下哨兵独立成行;超时销毁会话留墓碑 + 专用文案),文档见 `docs/Mcp_Design.md` §12.1。老客户端(非 PTY)仍为单行形态,故「吞行命令」限制只适用于老客户端。
|
||||
|
||||
### P2(高):`download_file` 对不存在路径无快速失败,默认 600 秒锁定整台主机
|
||||
|
||||
- 不存在的远程路径会等满默认 `timeout_ms=600000`(实测审计日志 `ms=600004`),期间该主机**所有**远程机器管理工具 `-32003`(single-flight 跨工具互斥),含 `host_list_processes/windows/network_state/scheduled_tasks/services`、`host_get_hosts_file` 等**经主连接向目标机取数据**的工具。一次误路径 = 10 分钟整机不可管理。(初版报告把这批工具写成「10 个纯本地 DB 读取」,属表述错误:它们都要触达目标主机,被互斥挡住是设计;纯服务端本地工具如 `get_server_status` / `get_audit_log` / `host_set_remark` 不受影响,二次复核已实测确认。)
|
||||
- **timeout_ms 参数本身工作正常**(显式 8000 → 实测 8031ms 终止),问题是默认值过长 + 缺路径检测。
|
||||
- 建议任选:客户端枚举路径时快速失败(最优);或下调默认超时(如 60s);或本地读取类工具豁免 BeginPending 互斥。
|
||||
|
||||
### P3(中):`exit_code` 不可靠(哨兵匹配到回显模板)
|
||||
|
||||
- `ver`(成功命令)返回 `exit_code=1`。根因:ConPTY 80 列回显折行使**回显的命令模板**中 `|| echo __MCP_DONE_<nonce>__1` 片段落到行首,`FindSentinel`(`McpServer.cpp:6195`)要求哨兵前是 `\n`/`\r`,于是 rfind 命中的是回显片段而非真实执行的哨兵。
|
||||
- 影响:依赖 exit_code 的自动化会把成功当失败。与 P1 同根(哨兵与回显混在同一输出流)。
|
||||
- 建议:随 P1 一起修(独立行哨兵可同时解决);短期可在 FindSentinel 中排除与已发送命令行重叠的匹配位置。
|
||||
|
||||
**复核(2026-10-25)**:属实。已随 P1 修复:`%errorlevel%` 回显是字面模板、`FindSentinel` 改为从后往前找「标记+数字」,实测 `ver`→0、`nosuchcmd_zzz`→9009。
|
||||
|
||||
### P4(中):`stdout` 泄漏内部实现(回显命令行 + 哨兵文本)
|
||||
|
||||
- `terminal_exec`/`exec_command` 返回的 stdout 中可见 `@echo off & ...` 命令回显、`__MCP_DONE_<nonce>__0/1` 哨兵字样(多例复现,如 `cmd /c echo abc` 的 stdout 含 `__0 || echo __MCP_DONE_2c0fbce0__1\nabc`)。
|
||||
- 原因:ConPTY 回显折行后 `StripEchoedCommand` 的整行匹配失效;哨兵截断点之后的清洗也不覆盖片段。
|
||||
- 影响:输出不可直接展示给最终用户;nonce 泄漏无安全风险(一次性),但属于实现细节泄漏。
|
||||
- 建议:清洗逻辑改为「剔除从行首到哨兵行之前的全部回显块」,而非精确整行匹配。
|
||||
|
||||
**复核(2026-10-25)**:属实。已修:删到命令行回显结束 → 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 收尾会残留 `\` 的问题。设计见 `docs/Mcp_Design.md` §12.1。
|
||||
|
||||
### P5(中):`get_activity_history` 注解登记错误
|
||||
|
||||
- `McpInternal.cpp:333` 登记 `openWorldHint=false`,但该工具经 `ctx->Send2Client(COMMAND_QUERY_ACTIVITY)` 触达远程主机(`McpServer.cpp:2249`),与代码注释及 `docs/Mcp_Design.md` §10.2 口径矛盾。一行修复。
|
||||
|
||||
**复核(2026-10-25)**:属实,已改 `openWorld=true` 并加注释说明理由。
|
||||
|
||||
### P6(低):`list_services` 在非提权被控端上 20s 超时且无解释
|
||||
|
||||
- 第1轮本机被控端(非提权):3/3 超时。客户端日志定位根因:`ServicesManager.cpp:31 Get service list failed`——`OpenSCManager(SC_MANAGER_ALL_ACCESS)` 权限不足,失败分支回传普通消息包而非 `TOKEN_SERVERLIST`,服务端等满 20s。
|
||||
- 第2轮 VM 被控端(权限足够):**成功**(服务列表正常返回)——反证根因即权限。
|
||||
- 建议:客户端失败分支回传带失败标记的 `TOKEN_SERVERLIST`,服务端转译为 `-32005`/明确错误文本;文档标注需要管理员权限。
|
||||
|
||||
**复核(2026-10-25)**:属实(`OpenSCManager` 权限不足 → 客户端失败分支回普通消息包,服务端只能等到超时)。修它要改客户端,按「暂不动客户端」原则搁置。
|
||||
|
||||
### P7(低):错误码表缺 -32007/-32008/-32009,且 -32008 复用多种语义
|
||||
|
||||
- `docs/Mcp_Design.md` §12 只登记到 -32006。-32008 同时用于:元字符、`&|`/控制字符、老客户端格式、多显示器不支持(4 处)。后者语义近 `-32005 Not supported`。
|
||||
|
||||
**复核(2026-10-25)**:属实。`docs/Mcp_Design.md` §12 已补齐 `-32007`/`-32008`/`-32009`,`-32008` 行内注明其四类语义(修正参数 vs 能力限制的处理方式不同)。
|
||||
|
||||
### P8(低):路径类工具对不存在路径静默返回空
|
||||
|
||||
- `list_registry`(注册表,两轮均复现)与 `list_files`(文件列表)对不存在的路径均返回空列表 + `isError:false`,无法区分「为空」与「不存在」。建议返回错误或加 `exists:false`。
|
||||
|
||||
**复核(2026-10-25)**:属实,但服务端拿到的响应与「空目录/空键」完全一致,无法在服务端区分;需客户端回报错误码 → 按「暂不动客户端」原则搁置。
|
||||
|
||||
### 观察项(不计入问题)
|
||||
|
||||
- `host_list_network_state` 的 state 为本地化文本("连接"),按 `ESTABLISHED` 过滤会失配;`kill_network_connection` 内部已归一化(stateName=ESTABLISHED, killable:true),dry_run 对真实四元组校验通过。
|
||||
- `remote_open` 双显示器拒绝(-32008)文案清晰、即时;VM 单屏下全链路正常。
|
||||
- 第1轮 exec_command 11/12 超时在两台被控端重启后均未复现(VM 5/5、重启后本机 5/5+30/30 连发通过);当时环境长时间运行+大量会话开关,疑与资源/状态积累有关,未能复现定位。鉴于 P1/P3 已证哨兵机制脆弱,建议优先落实哨兵改造后观察。
|
||||
|
||||
## 3. 通过项(摘要)
|
||||
|
||||
| 领域 | 结果 |
|
||||
|---|---|
|
||||
| 传输层 | 401/413/404、-32700/-32600/-32601、ping、status 不泄露 token —— 全过 |
|
||||
| 冒烟脚本 | 32/32 PASS |
|
||||
| 主机列表/分页/过滤 | 分页 clamp、越界、group/os/client_type、totalAll 保留 —— 全过 |
|
||||
| 批量工具 | ids>51 拒、写工具拒批量 —— 全过 |
|
||||
| exec 安全门 | 白名单+词边界(`dir` 过/`dirx` 拒/`echo` 拒)、`&`/CRLF -32008、空命令 -32602 —— 全过 |
|
||||
| 文件传输 V2 | 上传 11 项(中文文件名、1MB SHA-256、620 文件递归、overwrite 跳过)、下载 SHA-256、**跨机往返(本机↔VM)SHA 一致** —— 全过 |
|
||||
| search_file | min_size/name_only/子串/非法时间 -32602 —— 全过 |
|
||||
| 服务端本机工具 | audit 分页+过滤、status 一致性、`host_set_remark` GBK 边界(63B 过/66B 拒/emoji 拒)—— 全过 |
|
||||
| 只读主机工具(双端) | get_screenshot(JPEG magic 双端过)、get_keylog、list_registry 子键、list_windows、get_activity_history —— 全过 |
|
||||
| **remote 控制族(VM,第2轮新增)** | open→mouse(move/click/scroll)→keyboard(type/key_press)→clipboard→close→幂等→死会话拒绝 —— **11/11** |
|
||||
| chat(双端) | 本机 6/6 + VM 4/4(open/send/wait timed_out/close)—— 全过 |
|
||||
| 终端持久会话 | open/exec/close 生命周期、echo/whoami/cmd /c echo 等有输出命令 —— 全过(异常见 P1/P3/P4) |
|
||||
| 写工具 | watch_level 1↔0 往返、非法值拒绝 —— 过 |
|
||||
| kill_network_connection | dry_run 假四元组 -32009、**真实四元组校验通过**(VM 实测)—— 过 |
|
||||
|
||||
## 4. 修复优先级建议
|
||||
|
||||
1. **哨兵改造**(P1/P3/P4 同根一次修):独立行哨兵 + 回显块整体剔除 + 超时销毁会话的专用错误文案;
|
||||
2. P2:download 快速失败或默认超时下调 + 本地读取豁免互斥;
|
||||
3. P5:一行注解修复;
|
||||
4. P6:客户端服务枚举失败结构化回传;
|
||||
5. P7/P8 随批次顺手处理。
|
||||
|
||||
**复核后状态**:1 → 已修(§0 P1/P3/P4);2 → 已修「停滞 60s 快速失败」,默认超时未下调、互斥豁免未做(远程工具互斥是有意设计,本地工具本就不受限);3 → 已修;4 → 已修(`TOKEN_SERVICE_ERROR` → `-32010`);5 → P7 已修(文档),P8 已修(`TOKEN_FILE_LIST_ERROR`/`TOKEN_REG_ERROR` → `-32009`/`-32010`)。
|
||||
|
||||
## 附录 A:错误码实测一览
|
||||
|
||||
| 码 | 场景 | 实测 |
|
||||
|---|---|---|
|
||||
| -32001 | 等待超时 | 吞行命令、非提权 list_services、download 600s/8s 均复现(复核后:吞行命令不再超时;download 停滞 60s 即失败并说明原因) |
|
||||
| -32002 | 离线/不存在 | 不存在 id 复现;会话销毁后 terminal_exec 文案混用(见 P1)→ 复核后已拆成「被超时销毁」与「id 写错」两种文案 |
|
||||
| -32003 | 单设备互斥 | 挂起期间跨工具复现(含远程机器管理工具;**纯服务端本地工具不受影响**,复核已实测) |
|
||||
| -32005 | 不支持 | 代码审查确认(无 LNX/MAC 主机可测) |
|
||||
| -32006 | 策略拒绝 | 冒烟历史覆盖(McpKeylog=0 → CALL_DENIED) |
|
||||
| -32007 | 白名单拒绝 | `echo`/`set` 复现 |
|
||||
| -32008 | 元字符/&\|/老格式/多显示器 | 双屏 `remote_open`、`dir & whoami` 复现 |
|
||||
| -32009 | kill 目标不存在 | dry_run 复现;真实四元组通过 |
|
||||
| -32602 | 参数错误 | 备注 66B、level=99、非法时间等复现 |
|
||||
|
||||
## 附录 B:审计日志行为
|
||||
|
||||
- `CALL_OK`/`CALL_FAIL` 含 `tool= ms= bytes=`;600s 挂起精确记录 `ms=600004`;`get_audit_log` 过滤与实际一致。
|
||||
|
||||
## 附录 C:测试残留与清理
|
||||
|
||||
- 全部测试数据(本机 `%TEMP%\yama_mcp_test\src|vm_target|dl_vm` 与 VM 同名目录)测试后已删除/验证删除。
|
||||
- `settings.ini` 未做修改(本轮未动开关),第1轮已恢复备份。
|
||||
- VM 会话中因超时被销毁的终端已随服务端状态清理;我启动的本机 ghost.exe 已关闭,Debug 服务端保持用户启动状态。
|
||||
@@ -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 {
|
||||
@@ -5944,11 +5946,16 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// 只取首条全量,取走即 CancelIO 关子链接,停止后续增量推送(与 MFC 日志对话框
|
||||
// 持续接收增量的路径区分开)。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId)) {
|
||||
McpServer().TakeMainResponse(devId, szBuffer, len);
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // get_client_log 已放弃后的迟到日志子链接:不弹日志窗口
|
||||
break;
|
||||
}
|
||||
std::string logText((char*)(szBuffer + 1), len > 1 ? len - 1 : 0);
|
||||
if (!ContextObject->hDlg) {
|
||||
// 对话框尚未打开:用 SendMessage 同步打开并显示初始全量日志
|
||||
@@ -5966,10 +5973,12 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// P2b:MCP 挂起时接管。历史活动为「主连接 RPC」(无子链接),响应回主 context,
|
||||
// 不能 CancelIO(会断开主连接),仅同步拷贝后 break。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId)) {
|
||||
McpServer().TakeMainResponse(devId, ContextObject->GetBuffer(0), ContextObject->GetBufferLength());
|
||||
break;
|
||||
}
|
||||
if (mcpLate) break; // get_activity_history 已放弃后的迟到包:主连接,不能 CancelIO,直接丢弃
|
||||
// 一次性快照:直接打开“历史活动”对话框展示,不占用 hDlg(避免与运行日志对话框冲突)
|
||||
std::string text((char*)(szBuffer + 1), len > 1 ? len - 1 : 0);
|
||||
CActivityDialog* dlg = new CActivityDialog(this, ContextObject->GetServer(), ContextObject);
|
||||
@@ -5980,6 +5989,17 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
break;
|
||||
}
|
||||
case TOKEN_CLIENT_MSG: {
|
||||
// MCP 工具在飞时不弹客户端的老式提示框:新客户端在失败分支同时发结构化 token(已能
|
||||
// 让工具立即返回错误)和老 ClientMsg(只为兼容老服务端),后者会让 MCP 调用在服务端
|
||||
// UI 上弹一个模态框。有挂起请求说明这次失败已经由工具结果解释,直接丢弃并记日志。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
if (McpServer().IsRunning() &&
|
||||
(McpServer().IsPending(devId) || McpServer().IsFileTransferPending(devId))) {
|
||||
ClientMsg *msg =(ClientMsg*)ContextObject->InDeCompressedBuffer.GetBuffer(0);
|
||||
Mprintf("[MCP] suppress client popup dev=%llu title=%.31s text=%.512s\n",
|
||||
(unsigned long long)devId, msg->title, msg->text);
|
||||
break;
|
||||
}
|
||||
ClientMsg *msg =(ClientMsg*)ContextObject->InDeCompressedBuffer.GetBuffer(0);
|
||||
PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(_L(msg->text)), (LPARAM)new CString(_L(msg->title)));
|
||||
break;
|
||||
@@ -6846,6 +6866,9 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// P2c:MCP 挂起时接管。列盘 = 取走数据后用完即关;列目录 = 转向下发
|
||||
// COMMAND_LIST_FILES、等 TOKEN_FILE_LIST(此时不关子链接,交给 TOKEN_FILE_LIST 分支收尾)。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
// 先取「迟到首包」标记(成功路径同样消费,不留残留):工具超时后客户端才连上来的
|
||||
// 文件管理器子链接与本包,绝不能当成人手点击去弹文件管理器窗口。
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId)) {
|
||||
if (McpServer().OnDriveList(devId, ContextObject, szBuffer, len))
|
||||
ContextObject->CancelIO(); // 只列盘 → 用完即关一次性子链接
|
||||
@@ -6858,6 +6881,10 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // 工具已放弃后的迟到包:关子链接,不弹窗
|
||||
break;
|
||||
}
|
||||
ContextObject->EnableZstdContext(6);
|
||||
g_2015RemoteDlg->SendMessage(WM_OPENFILEMANAGERDIALOG, 0, (LPARAM)ContextObject);
|
||||
break;
|
||||
@@ -6873,6 +6900,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 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索
|
||||
// (工具线程已超时返回部分结果)的尾包,原地丢弃即可。
|
||||
@@ -6905,10 +6952,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
break;
|
||||
}
|
||||
// MCP exec_command 触发的 shell 子上下文:交给 McpServer 接管(老 cmd 管道,GBK)。
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsTermPending(devId)) {
|
||||
McpServer().RegisterTerminalContext(devId, ContextObject, /*isPty*/false);
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // 终端工具已放弃后的迟到 shell 子链接:不弹终端窗口
|
||||
break;
|
||||
}
|
||||
g_2015RemoteDlg->SendMessage(WM_OPENSHELLDIALOG, 0, (LPARAM)ContextObject);
|
||||
break;
|
||||
}
|
||||
@@ -6920,10 +6972,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
break;
|
||||
}
|
||||
// MCP exec_command 触发的 PTY 子上下文:交给 McpServer 接管(ConPTY,UTF-8)。
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsTermPending(devId)) {
|
||||
McpServer().RegisterTerminalContext(devId, ContextObject, /*isPty*/true);
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // 终端工具已放弃后的迟到 PTY 子链接:不弹终端窗口
|
||||
break;
|
||||
}
|
||||
|
||||
// 三个前置条件,缺任何一个都回退到经典终端,并把原因贴到信息列表。
|
||||
// SYSTEM 场景:WebView2 不支持 LocalSystem token,会出现"窗口能弹但页面空白",
|
||||
@@ -6954,6 +7011,7 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// OnSystemReady 命中就绪包时接管子连接并下发写命令(返回 true、不 CancelIO),
|
||||
// 命中确认包或只读工具时返回 false,走 TakeMainResponse + CancelIO 收尾。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId)) {
|
||||
if (McpServer().OnSystemReady(devId, ContextObject))
|
||||
break;
|
||||
@@ -6961,6 +7019,10 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->CancelIO(); // 用完即关,避免子链接泄漏(仿 WebService 终端关闭)
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // 进程/窗口工具已放弃后的迟到包:不弹进程管理器
|
||||
break;
|
||||
}
|
||||
g_2015RemoteDlg->SendMessage(WM_OPENSYSTEMDIALOG, 0, (LPARAM)ContextObject);
|
||||
break;
|
||||
}
|
||||
@@ -6972,8 +7034,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// P3:MCP 挂起时接管。TOKEN_REGEDIT 是客户端子链接构造即发(CRegisterManager 构造),
|
||||
// 命中则下发 COMMAND_REG_FIND 并保持子链接(等 TOKEN_REG_PATH/KEY),不打开 MFC 对话框。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId) && McpServer().OnRegeditReady(devId, ContextObject))
|
||||
break;
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // list_registry 已放弃后的迟到子链接:不弹注册表窗口
|
||||
break;
|
||||
}
|
||||
g_2015RemoteDlg->SendMessage(WM_OPENREGISTERDIALOG, 0, (LPARAM)ContextObject);
|
||||
break;
|
||||
}
|
||||
@@ -6996,12 +7063,22 @@ 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 对话框续用该子链接)。
|
||||
// P7:control_service 的就绪/确认是同一 token,OnServiceReady 命中就绪包时接管并下发
|
||||
// COMMAND_SERVICECONFIG(返回 true、不 CancelIO),确认包走 TakeMainResponse 收尾。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
|
||||
if (McpServer().IsPending(devId)) {
|
||||
if (McpServer().OnServiceReady(devId, ContextObject))
|
||||
break;
|
||||
@@ -7009,9 +7086,24 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
if (mcpLate) {
|
||||
ContextObject->CancelIO(); // 服务工具已放弃后的迟到包:不弹服务管理器
|
||||
break;
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -330,7 +330,9 @@ const ToolHints kToolHints[] = {
|
||||
{ "search_hosts", true, false, true, false },
|
||||
{ "list_all_hosts", true, false, true, false },
|
||||
{ "get_host_detail", true, false, true, false },
|
||||
{ "get_activity_history", true, false, true, false },
|
||||
// get_activity_history 虽不含主机 id 之外的写操作,但要经主连接向目标主机发
|
||||
// COMMAND_QUERY_ACTIVITY 取数据(McpServer.cpp:2249),属触达外部主机 → openWorld=true。
|
||||
{ "get_activity_history", true, false, true, true },
|
||||
{ "get_audit_log", true, false, true, false },
|
||||
{ "get_server_status", true, false, true, false },
|
||||
// --- 主机只读 ---
|
||||
|
||||
+447
-88
@@ -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) {
|
||||
@@ -1122,7 +1122,7 @@ Json::Value BuildExecCommandOutputSchema() {
|
||||
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -2149,7 +2149,7 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C
|
||||
}
|
||||
|
||||
std::vector<BYTE> 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<BYTE> 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<BYTE> 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<BYTE> 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<BYTE>& 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<BYTE> 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<BYTE> 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<BYTE> 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);
|
||||
|
||||
@@ -2624,24 +2661,139 @@ static std::string StripAnsi(const std::string& s) {
|
||||
++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/ESC
|
||||
} 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 把整行输入回显造成的噪声:echoedLine 是发送的哨兵命令行(含唯一 nonce),
|
||||
// 输出里若出现该行(连同其后换行)则整行剔除。非 PTY 老 ShellManager 已自行跳回显,
|
||||
// 找不到该行即无操作。echoedLine 含随机 nonce,命令真实输出不可能恰好相同。
|
||||
static std::string StripEchoedCommand(const std::string& s, const std::string& echoedLine) {
|
||||
if (echoedLine.empty() || s.empty()) return s;
|
||||
size_t p = s.find(echoedLine);
|
||||
if (p == std::string::npos) return s;
|
||||
size_t q = p + echoedLine.size();
|
||||
if (q < s.size() && s[q] == '\n') ++q; // CRLF 已归一为 \n
|
||||
return s.substr(0, p) + s.substr(q);
|
||||
// 去掉 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):
|
||||
// - 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, const std::string& command, const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
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, const std::string& command,
|
||||
const std::string& nonce, std::string& cmdLine, std::string& sentLine) {
|
||||
BuildSentinelLines(isPty, command, nonce, cmdLine, sentLine);
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string 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 里会绕过
|
||||
@@ -2689,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;
|
||||
|
||||
@@ -2712,15 +2864,10 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
|
||||
// 编码:ConPTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
// 哨兵命令行:@echo off 仅 ConPTY 需要(抑制回显噪声);老 ShellManager 已自行跳过回显,
|
||||
// 加 @echo off 反而破坏其回显跳过逻辑。&&/|| 取命令真实退出码(%errorlevel% 在复合句中
|
||||
// 是解析期展开、已过期,故用控制操作符)。哨兵为随机串,命令输出不可能恰好包含。
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
// 哨兵形态见 BuildSentinelLines:PTY 下命令与哨兵分两行下发(吞行命令不再超时),
|
||||
// 老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。
|
||||
std::string cmdLine, sentLine;
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -2740,7 +2887,7 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, line);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
|
||||
@@ -2791,7 +2938,7 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM
|
||||
}
|
||||
|
||||
std::vector<BYTE> 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' 终止)。
|
||||
@@ -2983,6 +3130,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
||||
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
|
||||
|
||||
// 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 LNX/MAC。
|
||||
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
|
||||
@@ -3016,24 +3164,19 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
|
||||
return true;
|
||||
}
|
||||
|
||||
// 发送哨兵命令行(复用 exec_command 的编码/哨兵逻辑);返回所发送的完整命令行,
|
||||
// 发送哨兵命令行(复用 exec_command 的哨兵逻辑);回传所发送的两行,
|
||||
// 供调用方剔除 ConPTY 把输入整行回显造成的噪声。cp 由 isPty 决定。
|
||||
static std::string SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce) {
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
return line;
|
||||
static void SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
}
|
||||
|
||||
// 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 →
|
||||
// 去 ConPTY 回显命令行 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
const std::string& echoedLine) {
|
||||
// 去输入回显 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp, bool isPty,
|
||||
const std::string& cmdLine, const std::string& sentLine,
|
||||
const std::string& nonce) {
|
||||
std::string stdoutStr;
|
||||
if (!raw.empty()) {
|
||||
std::string rawStr((const char*)raw.data(), raw.size());
|
||||
@@ -3041,7 +3184,7 @@ static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, echoedLine);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
return stdoutStr;
|
||||
@@ -3124,7 +3267,7 @@ Json::Value BuildTerminalExecOutputSchema() {
|
||||
props["stdout"] = stdoutProp;
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
@@ -3182,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;
|
||||
|
||||
@@ -3251,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;
|
||||
|
||||
@@ -3259,10 +3402,25 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
context* subCtx = nullptr;
|
||||
bool isPty = false;
|
||||
if (!mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty))
|
||||
return BuildError(id, -32002, "Terminal session not found, not ready, or busy: " + sessionId);
|
||||
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
|
||||
if (begin != 0) {
|
||||
// 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。
|
||||
std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId);
|
||||
if (!destroyed.empty())
|
||||
return BuildError(id, -32002, destroyed);
|
||||
if (begin == 4)
|
||||
return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session");
|
||||
if (begin == 2)
|
||||
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
|
||||
if (begin == 3)
|
||||
return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId);
|
||||
if (begin == 5)
|
||||
return BuildError(id, -32002, "Terminal session is already closing: " + sessionId);
|
||||
return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)");
|
||||
}
|
||||
|
||||
std::string sentLine = SendTerminalCommandLine(subCtx, isPty, command, nonce);
|
||||
std::string cmdLine, sentLine;
|
||||
SendTerminalCommandLine(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -3276,7 +3434,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
subCtx->CancelIO();
|
||||
}
|
||||
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, sentLine);
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, isPty, cmdLine, sentLine,
|
||||
nonce);
|
||||
|
||||
// 审计:命令执行(不可关闭)。
|
||||
if (parent) {
|
||||
@@ -3477,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(':');
|
||||
@@ -3485,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));
|
||||
}
|
||||
@@ -3501,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;
|
||||
|
||||
@@ -4451,7 +4611,8 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
std::vector<FileTransferEntry> 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) {
|
||||
@@ -4507,7 +4668,21 @@ 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; "
|
||||
"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"
|
||||
@@ -4590,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<BYTE> 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();
|
||||
@@ -4933,7 +5114,7 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
||||
}
|
||||
|
||||
std::vector<BYTE> 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;
|
||||
@@ -5030,7 +5211,7 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C
|
||||
}
|
||||
|
||||
std::vector<BYTE> 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",
|
||||
@@ -5107,7 +5288,7 @@ std::string BuildControlService(const Json::Value& id, const Json::Value& args,
|
||||
}
|
||||
|
||||
std::vector<BYTE> 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",
|
||||
@@ -6187,11 +6368,14 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
|
||||
// ===== P3:exec_command 哨兵检测与终端会话 =====
|
||||
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。真实哨兵由 echo 单独输出、独占
|
||||
// 一行(前面是 \n 或缓冲区开头);而 ConPTY 会把整条命令行回显进输出流,哨兵字样嵌在
|
||||
// "&& echo ... || echo ..." 里、前面是空格。据此从后往前找「行首命中」,排除回显行误判:
|
||||
// 否则回显包先于命令输出单独到达时,rfind 会命中回显里的 __1 提前结束、截断真实输出。
|
||||
// 老 ShellManager 已自行跳过回显,输出里只有真实哨兵(仍为行首)。命中 __0 → exit 0;__1 → exit 1。
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。哨兵后紧跟退出码数字(可带负号)。
|
||||
//
|
||||
// ConPTY 会把输入整行回显进输出流,因此「哨兵必须独占行首」这条旧规则反而会把真实哨兵
|
||||
// 排除掉(命令最后一行没有换行时哨兵会接在其后),再往前命中回显里的 &&/|| 片段,得到
|
||||
// 错误的退出码(评审 P3,`ver` → exit_code=1)。现在两种哨兵形态都能安全地不依赖行首:
|
||||
// - 新形态(ConPTY):回显文本里是字面 "%errorlevel%",不是数字,天然不可能命中;
|
||||
// - 老形态(非 PTY):回显由客户端按写入长度跳过,且回显中的片段在真实哨兵之前。
|
||||
// 故从后往前找第一个「标记 + 数字」即可。
|
||||
static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
size_t& pos, int& exitCode) {
|
||||
std::string marker = "__MCP_DONE_" + nonce + "__";
|
||||
@@ -6201,11 +6385,17 @@ static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
while (true) {
|
||||
size_t p = s.rfind(marker, from);
|
||||
if (p == std::string::npos) return false;
|
||||
bool lineStart = (p == 0) || (s[p - 1] == '\n') || (s[p - 1] == '\r');
|
||||
size_t digitPos = p + marker.size();
|
||||
if (lineStart && digitPos < s.size() &&
|
||||
(s[digitPos] == '0' || s[digitPos] == '1')) {
|
||||
exitCode = (s[digitPos] == '0') ? 0 : 1;
|
||||
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;
|
||||
}
|
||||
@@ -6301,6 +6491,8 @@ bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& i
|
||||
bool signaled = m_TermCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.started; });
|
||||
if (!signaled) {
|
||||
// 放弃:迟到的 shell 子连接就绪包(TOKEN_SHELL_START/TOKEN_TERMINAL_START)不能弹终端窗口。
|
||||
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SHELL_START, (BYTE)TOKEN_TERMINAL_START });
|
||||
m_TermSessions.erase(it); // 超时 → 清理
|
||||
return false;
|
||||
}
|
||||
@@ -6356,17 +6548,47 @@ bool CMcpServer::BeginTermOpen(uint64_t device_id, const std::string& sessionId)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty) {
|
||||
// 墓碑:记下会话被销毁的原因,供后续 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<std::mutex> 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<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermSessions.find(device_id);
|
||||
if (it == m_TermSessions.end()) return false;
|
||||
if (it == m_TermSessions.end()) return 1; // 不存在(含已销毁)
|
||||
TermSession& s = it->second;
|
||||
if (!s.persistent || s.sessionId != sessionId) return false; // 非持久或 token 不匹配
|
||||
if (!s.started) return false; // 未就绪
|
||||
if (s.busy) return false; // 已有命令在飞
|
||||
if (s.closed) return false; // 已关闭
|
||||
if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配
|
||||
if (!s.started) return 3; // 未就绪
|
||||
if (s.busy) return 4; // 已有命令在飞
|
||||
if (s.closed) return 5; // 已关闭
|
||||
s.busy = true;
|
||||
s.command = command;
|
||||
s.nonce = nonce;
|
||||
@@ -6378,7 +6600,7 @@ bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& session
|
||||
s.lastActiveAt = time(nullptr);
|
||||
subCtx = s.subCtx;
|
||||
isPty = s.isPty;
|
||||
return true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
@@ -6392,6 +6614,9 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
|
||||
if (!signaled) { // 超时 → 清理会话+路由(调用方负责 CancelIO)
|
||||
context* subCtx = it->second.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session was destroyed after this command timed out (waited "
|
||||
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return false;
|
||||
@@ -6402,6 +6627,8 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
out = it->second.data;
|
||||
exitCode = -1;
|
||||
closed = true;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session ended: the shell process exited; call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return true;
|
||||
@@ -6429,10 +6656,13 @@ int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionI
|
||||
if (s.busy) {
|
||||
// 有命令在飞:置 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;
|
||||
}
|
||||
subCtx = s.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, sessionId, "Terminal session was closed by terminal_close");
|
||||
m_TermContextToDevice.erase(s.subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
}
|
||||
@@ -6449,6 +6679,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
|
||||
TermSession& s = it->second;
|
||||
if (s.persistent && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
|
||||
if (s.subCtx) { m_TermContextToDevice.erase(s.subCtx); toCancel.push_back(s.subCtx); }
|
||||
MarkTermDestroyedLocked(it->first, s.sessionId,
|
||||
"Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec)
|
||||
+ "s of inactivity; call terminal_open again");
|
||||
it = m_TermSessions.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
@@ -6989,6 +7222,8 @@ bool CMcpServer::WaitPending(uint64_t device_id, std::vector<BYTE>& out, int tim
|
||||
bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
if (!signaled || it->second.data.empty()) {
|
||||
// 放弃:客户端可能在我们返回后才把应答首包发上来,登记吸收,别让它弹 MFC 窗口。
|
||||
MarkLateFirstPacketForTool(device_id, it->second.tool);
|
||||
m_Pending.erase(it); // 超时/空数据 → 清理
|
||||
return false;
|
||||
}
|
||||
@@ -7002,6 +7237,54 @@ void CMcpServer::ClearPending(uint64_t device_id) {
|
||||
m_Pending.erase(device_id);
|
||||
}
|
||||
|
||||
// ===== 迟到首包吸收 =====
|
||||
// 工具放弃后 5 分钟内到达的「应答首包」只吸收一次;过期即失效(不长期压制人工操作)。
|
||||
static const int kFirstPacketMarkMs = 5 * 60 * 1000;
|
||||
|
||||
void CMcpServer::MarkLateFirstPacket(uint64_t device_id, std::initializer_list<BYTE> tokens) {
|
||||
if (tokens.size() == 0) return;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
std::lock_guard<std::mutex> 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 == "upload_file" || tool == "search_file")
|
||||
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<std::mutex> 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) {
|
||||
@@ -7219,6 +7502,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<std::mutex> 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<BYTE>& subkeys,
|
||||
std::vector<BYTE>& values, int timeoutMs) {
|
||||
std::unique_lock<std::mutex> lk(m_PendingMutex);
|
||||
@@ -7228,6 +7531,7 @@ bool CMcpServer::WaitPendingRegistry(uint64_t device_id, std::vector<BYTE>& subk
|
||||
bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
if (!signaled) {
|
||||
MarkLateFirstPacketForTool(device_id, it->second.tool); // 放弃后的 TOKEN_REGEDIT 不弹注册表窗口
|
||||
m_Pending.erase(it); // 超时 → 清理
|
||||
return false;
|
||||
}
|
||||
@@ -7315,6 +7619,7 @@ bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, in
|
||||
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(); // 锁外关子连接,防孤儿子连接
|
||||
@@ -7366,6 +7671,10 @@ std::string GenerateRandomToken() {
|
||||
|
||||
// ===== P6:download_file 文件传输会话(状态机方法)=====
|
||||
|
||||
// 停滞看门狗:超过这么久没收到任何传输包即判失败(远程路径不存在时客户端不发包)。
|
||||
// 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。
|
||||
static const int kFileXferStallMs = 60000;
|
||||
|
||||
bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
|
||||
std::lock_guard<std::mutex> lk(m_FileXferMutex);
|
||||
return m_FileXferSessions.find(device_id) != m_FileXferSessions.end();
|
||||
@@ -7387,6 +7696,7 @@ bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string&
|
||||
s.remotePath = remotePath;
|
||||
s.overwrite = overwrite;
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7402,6 +7712,7 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) {
|
||||
FileTransferSession s;
|
||||
s.tool = "upload_file";
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7450,6 +7761,7 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return; // 已出错/完成,丢弃迟到包
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
if (s.streamSubCtx == nullptr) {
|
||||
s.streamSubCtx = streamSubCtx;
|
||||
@@ -7518,6 +7830,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<std::mutex> 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;
|
||||
@@ -7528,6 +7861,7 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return;
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
uint32_t fileIndex = pkt->fileIndex;
|
||||
|
||||
@@ -7555,23 +7889,48 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs,
|
||||
std::vector<FileTransferEntry>& files, int& skipped, int& error) {
|
||||
std::vector<FileTransferEntry>& files, int& skipped, int& error,
|
||||
DWORD* errorDetail) {
|
||||
if (errorDetail) *errorDetail = 0;
|
||||
std::unique_lock<std::mutex> lk(m_FileXferMutex);
|
||||
auto it = m_FileXferSessions.find(device_id);
|
||||
if (it == m_FileXferSessions.end()) { error = 1002; return false; }
|
||||
|
||||
bool signaled = m_FileXferCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
// 分段等待 + 停滞看门狗:远程路径不存在时客户端一个包都不发,只靠总超时(默认 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<std::chrono::milliseconds>(deadline - now);
|
||||
if (slice.count() <= 0) break; // 总超时
|
||||
if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) {
|
||||
signaled = true;
|
||||
break;
|
||||
}
|
||||
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.error = 1002; // 超时
|
||||
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();
|
||||
|
||||
return signaled && s.error == 0;
|
||||
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) {
|
||||
|
||||
@@ -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<BYTE>& subkeys,
|
||||
@@ -186,10 +190,16 @@ public:
|
||||
// 登记持久终端挂起(复用单设备单终端约束;sessionId 由调用方生成)。
|
||||
bool BeginTermOpen(uint64_t device_id, const std::string& sessionId);
|
||||
|
||||
// 复位单条命令字段并置 busy;输出 subCtx/isPty。false = 不存在/不匹配/未就绪/忙碌/已关。
|
||||
bool BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty);
|
||||
// 复位单条命令字段并置 busy;输出 subCtx/isPty。
|
||||
// 返回:0=ok;1=会话不存在;2=sessionId 不匹配;3=未就绪;4=忙(另一条命令在飞);
|
||||
// 5=shell 已退出。1/2 之外的原因由 DescribeTermDestroyed 提供可读文案。
|
||||
int BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty);
|
||||
|
||||
// 若该设备上的持久终端最近被销毁(超时/退出/关闭),返回可读原因(英文,含时间);
|
||||
// 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。
|
||||
std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);
|
||||
|
||||
// 等待本条命令完成(done || closed || 超时)。done=保持会话;closed/超时=清理会话+路由。
|
||||
bool WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out, int& exitCode,
|
||||
@@ -266,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);
|
||||
|
||||
@@ -273,7 +288,8 @@ public:
|
||||
// 无论成败,files 都会返回已见文件的落盘路径(成功=完整文件,失败=供调用方删半成品)。
|
||||
// 调用方随后必须调 ClearFileTransfer 收尾(擦会话 + CancelIO 子链接)。
|
||||
bool WaitFileTransferDone(uint64_t device_id, int timeoutMs,
|
||||
std::vector<FileTransferEntry>& files, int& skipped, int& error);
|
||||
std::vector<FileTransferEntry>& files, int& skipped, int& error,
|
||||
DWORD* errorDetail = nullptr);
|
||||
|
||||
// 收尾:擦会话 + 锁外 CancelIO 文件管理器/流式两条子链接(幂等)。
|
||||
void ClearFileTransfer(uint64_t device_id);
|
||||
@@ -306,6 +322,15 @@ public:
|
||||
// 工具线程:等待写确认包(第二个同 token 包);超时/空数据清挂起并 CancelIO 子连接。
|
||||
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs);
|
||||
|
||||
// ===== 迟到首包吸收(工具放弃后不再弹出 MFC 对话框)=====
|
||||
// 工具超时/失败清掉挂起后,客户端仍可能才把应答首包发上来(列盘、服务列表、注册表、
|
||||
// 进程列表、终端都是「子连接建成即发」)。那时已无挂起会话,MessageHandle 会把它当成
|
||||
// 人手点击而打开文件管理器/服务管理器/注册表/进程窗口/日志/终端窗口。
|
||||
// 工具放弃时按设备登记该工具的应答首包 token;包到达时一次性吸收(调用方关子连接、
|
||||
// 不弹窗)。命中即消费,过期即失效,绝不长期压制人工操作。
|
||||
// MessageHandle 各对话框分支开头调用(早于挂起判断:成功路径同样消费,不留残留)。
|
||||
bool TakeToolFirstPacket(uint64_t device_id, BYTE token);
|
||||
|
||||
// OfflineProc 调用:接管的子连接断开时清挂起(置 done 并清 subCtx,唤醒等待线程)。
|
||||
// 不擦表(由 WaitPendingWrite 持有迭代器时自行擦除,防迭代器失效);清 subCtx 使
|
||||
// 超时路径不会对已回收(连接池复用)的 context 误 CancelIO。
|
||||
@@ -342,6 +367,12 @@ public:
|
||||
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
|
||||
bool IsKeylogEnabled() const { return m_keylogEnabled; }
|
||||
|
||||
// ===== 工具默认等待超时([settings] McpToolTimeoutMs,ini-only 键)=====
|
||||
// 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 600000]。
|
||||
// 改动需重启服务端生效(与其它 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 };
|
||||
@@ -437,6 +468,10 @@ private:
|
||||
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
|
||||
void HandleMcp(const httplib::Request& req, httplib::Response& res);
|
||||
|
||||
// 记一条「持久终端已销毁」墓碑(调用方须持有 m_TermMutex)。
|
||||
void MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& reason);
|
||||
|
||||
// ===== 鉴权加固 =====
|
||||
// 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。
|
||||
bool IsAuthBlocked(const std::string& ip);
|
||||
@@ -528,6 +563,17 @@ private:
|
||||
// 清理过期墓碑(持 m_PendingMutex 调用)。
|
||||
void PruneOrphanMarksLocked(std::chrono::steady_clock::time_point now);
|
||||
|
||||
// ===== 迟到首包吸收(受 m_FirstPacketMutex 保护,独立锁避免与挂起/传输表形成锁序)=====
|
||||
// 等待函数在「超时/失败」分支调用:登记该工具放弃后可能迟到的应答首包 token。
|
||||
struct FirstPacketMark {
|
||||
std::set<BYTE> tokens;
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
std::mutex m_FirstPacketMutex;
|
||||
std::map<uint64_t, FirstPacketMark> m_FirstPacketMarks;
|
||||
void MarkLateFirstPacket(uint64_t device_id, std::initializer_list<BYTE> tokens);
|
||||
void MarkLateFirstPacketForTool(uint64_t device_id, const std::string& tool);
|
||||
|
||||
// 路由表大小(已绑定 + 已吸收的子连接数)。MessageHandle 每个包都会调用
|
||||
// OnManagedSubPacket,若无会话在飞则用它无锁快速返回,避免音频/屏幕等高频
|
||||
// 子连接逐包争用 m_PendingMutex。只在持锁时更新(store)。
|
||||
@@ -559,6 +605,15 @@ private:
|
||||
std::condition_variable m_TermCv;
|
||||
std::map<uint64_t, TermSession> m_TermSessions; // device_id → 会话
|
||||
std::map<context*, uint64_t> m_TermContextToDevice; // subCtx → device_id(顶部路由)
|
||||
// 最近一次持久终端被销毁的原因(device → 信息)。终端因超时/退出/关闭被清理后,后续
|
||||
// terminal_exec 无法区分「会话被超时销毁」与「session_id 写错」,只能报同一句
|
||||
// "not found"(评审 P1)。留一条短墓碑,让错误文案能说清是哪种情况。
|
||||
struct TermDestroyedInfo {
|
||||
std::string sessionId;
|
||||
std::string reason; // 英文短句,直接拼进 -32002 文案
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
std::map<uint64_t, TermDestroyedInfo> m_TermDestroyed; // device_id → 墓碑(10 分钟内有效)
|
||||
|
||||
// ===== P5:远程控制会话(受 m_ScreenCtrlMutex 保护;单设备单会话)=====
|
||||
struct ScreenCtrlSession {
|
||||
@@ -588,11 +643,16 @@ private:
|
||||
uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包)
|
||||
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
|
||||
bool done = false; // 全部完成或出错
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;
|
||||
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败
|
||||
DWORD errorDetail = 0; // error=1005/1006/1007 时的 win32 码(原样带进文案,便于分支/排查)
|
||||
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
|
||||
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
|
||||
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
|
||||
time_t startAt = 0;
|
||||
// 停滞看门狗:最后一次收到数据的时间。远程路径不存在时客户端一个包都不发,
|
||||
// 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。
|
||||
std::chrono::steady_clock::time_point lastDataAt;
|
||||
};
|
||||
std::mutex m_FileXferMutex;
|
||||
std::condition_variable m_FileXferCv;
|
||||
@@ -647,6 +707,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 末尾)
|
||||
|
||||
@@ -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 再挑一个关着的功能。
|
||||
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
|
||||
|
||||
Reference in new issue
Block a user