Compare commits
9
Commits
8f718d9b39
...
1c5fab1645
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c5fab1645 | ||
|
|
cc3e11d30d | ||
|
|
7c5bf3e73d | ||
|
|
929065e7be | ||
|
|
5ce453797c | ||
|
|
ae37e812ee | ||
|
|
d9a1a9ebcb | ||
|
|
16f23e164c | ||
|
|
39f0928de7 |
No files matched your search
@@ -465,7 +465,11 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
|
||||
|
||||
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer[0] == TOKEN_HEARTBEAT) return;
|
||||
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
|
||||
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
|
||||
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
|
||||
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
|
||||
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
|
||||
|
||||
if (ulLength == 1) {
|
||||
switch (szBuffer[0]) {
|
||||
|
||||
+13
-4
@@ -95,9 +95,12 @@ chat_close(id, sid)
|
||||
|
||||
## 5. 客户端怪癖与规避(协议不变)
|
||||
|
||||
1. **首字节 101 ('e') 被丢弃**:`client/ChatManager.cpp` 在任何长度判断之前执行
|
||||
`if (szBuffer[0] == TOKEN_HEARTBEAT) return;`。服务端在转换后的 GBK 首字节为
|
||||
101 时前置一个空格(显示上无感)。若客户端日后修复此行,可移除该规避。
|
||||
1. **首字节 101 ('e') 被丢弃(客户端已修)**:`client/ChatManager.cpp` 原在任何长度
|
||||
判断之前执行 `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`,而该通道承载自由文本,
|
||||
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
|
||||
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
|
||||
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
|
||||
空格好过静默丢消息。验证见本章末尾。
|
||||
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
|
||||
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
|
||||
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
|
||||
@@ -138,6 +141,12 @@ chat_close(id, sid)
|
||||
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
|
||||
逻辑不变。
|
||||
|
||||
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
|
||||
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
|
||||
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
|
||||
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
|
||||
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
|
||||
|
||||
## 6. 服务端状态机
|
||||
|
||||
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
|
||||
@@ -209,7 +218,7 @@ using ChatSessionPtr = std::shared_ptr<ChatSession>;
|
||||
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
|
||||
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
|
||||
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
|
||||
| 5 | 发送 `"echo test"`(首字节 'e') | 正常显示(前置空格规避生效) |
|
||||
| 5 | 发送 `"echo test"`(首字节 'e') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
|
||||
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
|
||||
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
|
||||
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
|
||||
|
||||
+98
-2
@@ -483,6 +483,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
|
||||
- `AUTH_BLOCK`:封禁生效。
|
||||
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
|
||||
- `CALL_DENIED`:被策略拒绝的调用(`-32006`)另记一条,含 `tool=` 与固定原因文本,见 §10.8。
|
||||
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
|
||||
|
||||
### 9.5 N5 列表输出治理
|
||||
@@ -517,7 +518,7 @@ httplib 默认值对 MCP 场景不合适,改为显式配置:
|
||||
- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。
|
||||
- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。
|
||||
- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。
|
||||
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log`),其余都会触达外部主机。
|
||||
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log` / `get_server_status`),其余都会触达外部主机。
|
||||
|
||||
### 10.3 A4 `get_host_detail` 字段补全
|
||||
|
||||
@@ -554,7 +555,7 @@ httplib 默认值对 MCP 场景不合适,改为显式配置:
|
||||
- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。
|
||||
- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。
|
||||
- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。
|
||||
- **已知风险(客户端既有缺陷,未修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath` 第 562 行、`szFullPath` 第 578 行),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**(本工具只是让它更容易被触发)。规避:只搜具体的中浅层目录,别从盘符根开始深搜。
|
||||
- **已知风险(客户端既有缺陷,仓库内已修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 曾用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath`、`szFullPath`),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**。源码已于 2026-10-25 修掉(commit 8f718d9,入口/逐条目长度预判);**已部署的老客户端仍带这个缺陷**,所以 `tools/mcp_smoke.ps1` 的搜索用例仍是 opt-in(`-SearchPath`)。
|
||||
- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。
|
||||
- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。
|
||||
|
||||
@@ -574,3 +575,98 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
|
||||
- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。
|
||||
- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。
|
||||
|
||||
### 10.8 D 批:拒绝也入审计
|
||||
|
||||
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
|
||||
|
||||
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
|
||||
```
|
||||
<时间> CALL_DENIED ip=<来源> tool=<工具名> reason=<固定英文原因>
|
||||
```
|
||||
同一调用仍会留下原有的 `CALL_FAIL` 行,所以 `CALL_FAIL` 的统计口径不变。
|
||||
- `reason` 全部是各分支写死的英文句子(如 `File transfer is disabled: requires McpFileTransfer=1`),不含调用参数或用户输入,落盘安全;审计依旧不记录 token、参数或返回正文。
|
||||
- 其他错误码(`-32602` 参数、`-32002` 主机离线、`-32001` 超时等)不额外记事件,靠 `CALL_FAIL` 行即可。
|
||||
- 验证(Debug 实例):把 `McpFileTransfer` 临时置 0 重启后调 `download_file`,审计立刻出现
|
||||
`CALL_FAIL ... tool=download_file ms=1 bytes=114` 紧跟 `CALL_DENIED ... reason=File transfer is disabled: requires McpFileTransfer=1`;恢复 `McpFileTransfer=1` 重启后同一调用恢复 `CALL_OK` 且无 `CALL_DENIED`。冒烟脚本 20/20 通过(未指定 `-SearchPath` 时跳过 2 个搜索用例)。
|
||||
|
||||
---
|
||||
|
||||
## 11. 增补(C 批:读侧增强,不改客户端)
|
||||
|
||||
### 11.1 C1 `get_audit_log` 分页与过滤
|
||||
|
||||
改动前每次调用都返回镜像里的全部条目(环形缓冲上限 1000 条),调用方没法只看关心的部分,日志一多就会把工具返回值撑大。
|
||||
|
||||
- 新增入参:`type`(类型列子串,不区分大小写,如 `MCP` 能匹配 `MCP命令执行`)、`keyword`(正文子串,不区分大小写)、`limit` / `offset`(沿用统一分页,默认 100、上限 1000)。
|
||||
- 过滤在分页之前生效:`total` 是命中条数、`totalAll` 是镜像里的全部条数;`hasMore` 针对命中的条目。摘要会补一句「过滤前共 N 条」,方便判断是不是过滤写错了。
|
||||
- 读取仍在 `m_cs` 临界区内完成(UI 线程会并发写入),过滤循环里先做 GBK→UTF-8 转换再比对,避免拿两种编码互相比。
|
||||
- outputSchema 补 `total/totalAll/offset/limit/hasMore`(与其它列表工具一致)。
|
||||
- 注意 `get_audit_log` 读的是**主界面消息镜像**,不是 `logs\mcp_audit.log`;两者的条目内容和保留策略都不同(前者是 1000 条环形缓冲,后者是 5 MB 文件滚动)。
|
||||
- 验证(Debug 实例):`limit=2` 两页分别返回第 1-2 / 3-4 条且 `hasMore=true`,`offset=999` 返回「offset 超出范围」;`type=mcp` 命中 `MCP命令执行`(大小写不敏感)、`type=提示` 命中「使用提示 / 提示信息」、`keyword=监听` 命中「监听端口: 6543成功」;冒烟脚本 23/23 通过(新增分页字段、条数上限、过滤未命中 3 项断言)。
|
||||
|
||||
### 11.2 C2 新工具 `get_server_status`
|
||||
|
||||
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
|
||||
|
||||
返回(`structuredContent.status`):
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `app_name` / `version` | 品牌名与 `BRAND_VERSION`(当前 1.4.1) |
|
||||
| `exe_build_time` | exe 文件的最后写入时间=链接时间(比 `__DATE__`/`__TIME__` 可靠,后者是编译单个 .cpp 的时间) |
|
||||
| `uptime_sec` | 进程已运行秒数(`GetProcessTimes` 的创建时间起算,不是开机时间,也不受 MCP 启停影响) |
|
||||
| `bind` / `port` | MCP 实际监听的地址与端口(`Start` 时记录,非从配置回读) |
|
||||
| `switches` | `readonly` / `terminal` / `remote_control` / `file_transfer` / `manage` / `machine` / `machine_dangerous` / `keylog` / `chat` |
|
||||
| `hosts` | `online` / `offline` 台数(与 `list_all_hosts` 同源) |
|
||||
| `sessions` | `pending`(一次性/管理/键盘记录挂起) / `terminal` / `remote_control` / `file_transfer` / `chat` 在飞会话数 |
|
||||
| `blocked_auth_ips` | 当前处于鉴权封禁期的来源 IP 数 |
|
||||
|
||||
- **不返回** token、`McpCmdWhitelist` 内容或任何配置原文;`switches` 只报布尔值。
|
||||
- `sessions` 各项各取各自的锁、取完即放,是「大致同一时刻」的估算值,不能当一致性快照用。
|
||||
- 工具注解登记为只读 + 非破坏性 + 幂等 + 不触达外部主机;`tools/list` 总数变为 53。
|
||||
- 验证(Debug 实例):返回 `Yama v1.4.1,已运行 17 秒,监听 127.0.0.1:6545;在线主机 1 台、离线 3160 台`;`terminal_open` 期间 `sessions.terminal=1`、`terminal_close` 后回到 0;冒烟脚本 26/26 通过(新增 3 项:正常返回、版本/端口/开关齐全、不含 token)。
|
||||
|
||||
### 11.3 C3 主机列表过滤:`list_online_hosts` / `list_all_hosts`
|
||||
|
||||
这两个工具原先只有分页,想找「某个分组」「某个平台」的主机只能翻页或改用 `search_hosts`(后者不支持 `client_type`,且对在线/离线的取舍规则不同)。
|
||||
|
||||
- 新增三个可选入参(两个工具共用同一套实现):`group` / `os` / `client_type`,均为子串匹配、ASCII 不区分大小写、AND 组合,口径与 `search_hosts` 一致。
|
||||
- 过滤在分页之前生效:`total` 为命中台数、`totalAll` 为过滤前总数(`list_online_hosts` 是全部在线数,`list_all_hosts` 是主机库总数);摘要改用「共 N 台主机匹配」并补一句过滤前规模,写错条件时一眼能看出来。
|
||||
- `list_all_hosts` 摘要里的在线/离线拆分也按命中条目统计。
|
||||
- **离线主机没有 `clientType`**(历史记录里不存这个字段),所以带 `client_type` 条件时离线主机不会命中——按平台筛历史主机用 `os`。
|
||||
- 验证(Debug 实例):`client_type=exe` 命中 1 台(`EXE`/`os=Windows 11`),`client_type=lnx` 命中 0 台但 `totalAll` 仍为 1;`list_all_hosts` 带 `group=default` 命中 3161 台并正确拆分在线 1 / 离线 3160,`os=zzz` 命中 0 台;冒烟脚本 28/28 通过(新增过滤未命中、totalAll 不变 2 项断言)。
|
||||
|
||||
### 11.4 C4 `search_file` 结果侧过滤
|
||||
|
||||
`search_file` 的搜索条件(根目录 + 通配模式)由客户端执行,改不动;但把匹配项拿回服务端后可以再筛一遍,省掉 AI 端逐条比对。
|
||||
|
||||
- 新增四个可选入参,**都在服务端对已收集的匹配项做过滤**,不减少客户端侧搜索耗时:
|
||||
- `min_size` / `max_size`:字节数,整数,闭区间;负数或非数字返回 `-32602`;两者都给出且 `min_size > max_size` 返回 `-32602`。
|
||||
- `modified_after`:接受 `YYYY-MM-DD`(当天 00:00:00 之后)或 `YYYY-MM-DD HH:MM:SS`;格式不符返回 `-32602`。客户端返回的 `modified` 是定宽 `"YYYY-MM-DD HH:MM:SS"`,可直接字典序比较,所以两种写法都合法(`"2026-01-01" <= "2026-01-01 08:00:00"`)。
|
||||
- `name_only`:布尔,命中项只保留 `path` / `name` 两个字段,适合只要文件清单时省 token。
|
||||
- 过滤在分页之前:`total` 为命中条数、`totalAll` 为过滤前条数;摘要补一句「过滤前共 N 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)」。
|
||||
- 过滤只看服务端已收到的条目,所以仍受 `max_results` / `timeout_ms` 截断:客户端没搜完时,过滤结果也是部分的(`truncated` / `finished` 字段照旧反映这一点)。
|
||||
- 验证(Debug 实例,根目录 `C:\Windows\Fonts`、`*.ttf`):基线 255 条;`min_size=1000000` → 39 条且 `totalAll=255`;`name_only=true` 每条只有 `path`/`name`;`modified_after=2026-01-01` → 165 条、`2026-06-03 00:00:00` → 130 条、`2027-01-01` → 0 条;`min_size=-5`、`min_size=10 & max_size=5`、`modified_after=2026/01/01`、`modified_after=2026-01-01 12:00` 均返回预期的 `-32602`。冒烟脚本 33/33 通过(新增 3 项:`min_size` 过滤后 `totalAll` 不变、`name_only` 精简字段、非法 `modified_after` 返回 `-32602`;后三项需带 `-SearchPath` 才执行)。
|
||||
|
||||
## 12. 错误码速查(E 批:冒烟与文档)
|
||||
|
||||
工具的失败分三类,AI 端应按 `code` 决定下一步,而不是读 `message` 文本。`message` 是给人看的英文说明,随实现变化,不作为契约。
|
||||
|
||||
| code | 含义 | 典型触发 | 建议动作 |
|
||||
|---|---|---|---|
|
||||
| `-32700` | Parse error | 请求体不是合法 JSON | 修正客户端序列化 |
|
||||
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
|
||||
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
|
||||
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
|
||||
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
|
||||
| `-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` 等) |
|
||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
||||
|
||||
- `-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 通过。
|
||||
@@ -394,3 +394,10 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
|
||||
| U7 | 实施验证发现:客户端主连接 `g_status==0`,`RecvFileChunkV2` 逐 chunk `return -1`(上传落盘 0 字节/截断) | 客户端 `COMMAND_SEND_FILE_V2` 分支加懒初始化(§7.8):`static` 一次 + 永久引用计数、析构不 `Uninit`;与 `FileManager.cpp:40` 参数一致,独立评审确认无稳定性风险 |
|
||||
|
||||
**判定**:7 项均已写入 §7 对应小节,无阻塞项,**定稿**。
|
||||
|
||||
### 13.2 实施后修复记录(2026-10-25)
|
||||
|
||||
| # | 问题 | 修复 |
|
||||
|---|---|---|
|
||||
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
|
||||
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
|
||||
@@ -5546,6 +5546,12 @@ BOOL CALLBACK CMy2015RemoteDlg::OfflineProc(CONTEXT_OBJECT* ContextObject)
|
||||
McpServer().OnManagedContextClosed(ContextObject);
|
||||
}
|
||||
|
||||
// MCP P6 文件传输的文件管理器/流式子连接断开:清反查表并置空裸指针,避免工具线程
|
||||
// 超时路径对连接池回收后的 context 误 CancelIO;流式子链接断开同时判传输失败。
|
||||
if (McpServer().IsRunning()) {
|
||||
McpServer().OnFileTransferContextClosed(ContextObject);
|
||||
}
|
||||
|
||||
// MCP P9 远程交谈:子连接(或主连接)断开时清路由/标记会话 closed 并唤醒 chat_wait。
|
||||
// 同样必须在 RemoveFromHostList 之前,避免连接池复用同一 context 指针后误路由。
|
||||
if (McpServer().IsRunning()) {
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
// → 双向文本 [CP936 字节][NUL],无 token 前缀
|
||||
// → 服务端 [COMMAND_CHAT_CLOSE=1] 关闭窗口
|
||||
//
|
||||
// 客户端怪癖(见 docs/Mcp_Chat_Design.md §4):
|
||||
// 1. ChatManager.cpp 在任何长度判断前丢弃首字节为 TOKEN_HEARTBEAT(101, 'e') 的包,
|
||||
// 故 GBK 首字节为 101 时前置一个空格。
|
||||
// 客户端怪癖(见 docs/Mcp_Chat_Design.md §5):
|
||||
// 1. 老客户端 ChatManager.cpp 在任何长度判断前丢弃首字节为 TOKEN_HEARTBEAT(101, 'e')
|
||||
// 的包,故 GBK 首字节为 101 时前置一个空格(新客户端已删掉那行守卫,空格只为兼容)。
|
||||
// 2. 窗口由子线程 CreateDialogParamA 创建,收到 [0] 后仍有约 150ms 建窗延迟;
|
||||
// 绑定后 1000ms 内不返回 chat_open,也不接受 chat_send。
|
||||
//
|
||||
@@ -419,8 +419,9 @@ static std::string BuildChatSend(const Json::Value& id, const Json::Value& args,
|
||||
" GBK bytes (limit " + std::to_string(kMaxSendBytes) + ")");
|
||||
}
|
||||
|
||||
// 客户端在长度判断之前丢弃首字节为 TOKEN_HEARTBEAT(101, 'e') 的包。
|
||||
// 前置一个空格规避,显示上无感(2026-10 客户端 ChatManager.cpp:281)。
|
||||
// 兼容老客户端:它们在任何长度判断之前丢弃首字节为 TOKEN_HEARTBEAT(101, 'e') 的包
|
||||
// (ChatManager::OnReceive 里照搬来的心跳守卫)。新客户端已删掉那行,这里保留前置空格
|
||||
// 是为了不区分客户端版本——多一个看不见的空格,好过老客户端静默丢消息。
|
||||
if ((BYTE)gbk[0] == (BYTE)TOKEN_HEARTBEAT) gbk.insert(gbk.begin(), ' ');
|
||||
|
||||
std::vector<char> packet(gbk.begin(), gbk.end());
|
||||
|
||||
@@ -323,7 +323,7 @@ struct ToolHints {
|
||||
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
|
||||
};
|
||||
|
||||
// 52 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
|
||||
// 53 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
|
||||
const ToolHints kToolHints[] = {
|
||||
// --- 服务端本机只读 ---
|
||||
{ "list_online_hosts", true, false, true, false },
|
||||
@@ -332,6 +332,7 @@ const ToolHints kToolHints[] = {
|
||||
{ "get_host_detail", true, false, true, false },
|
||||
{ "get_activity_history", true, false, true, false },
|
||||
{ "get_audit_log", true, false, true, false },
|
||||
{ "get_server_status", true, false, true, false },
|
||||
// --- 主机只读 ---
|
||||
{ "list_processes", true, false, true, true },
|
||||
{ "list_windows", true, false, true, true },
|
||||
|
||||
+467
-26
@@ -580,6 +580,53 @@ void CollectAllHosts(CMy2015RemoteDlg* parent, Json::Value& hosts,
|
||||
LeaveCriticalSection(&parent->m_cs);
|
||||
}
|
||||
|
||||
// ===== C3:list_online_hosts / list_all_hosts 的公共过滤 =====
|
||||
// 口径与 search_hosts 一致:条件都可选、AND 组合、子串匹配、ASCII 不区分大小写。
|
||||
// 只过滤已有字段,不额外拉取主机数据;离线主机没有 clientType(历史记录里不存),
|
||||
// 所以带 client_type 条件时离线主机不会命中——需要按平台筛历史主机请用 os。
|
||||
struct HostListFilter {
|
||||
std::string group;
|
||||
std::string os;
|
||||
std::string clientType;
|
||||
bool Any() const { return !group.empty() || !os.empty() || !clientType.empty(); }
|
||||
};
|
||||
|
||||
HostListFilter ReadHostListFilter(const Json::Value& args) {
|
||||
HostListFilter f;
|
||||
f.group = GetStringArg(args, "group");
|
||||
f.os = GetStringArg(args, "os");
|
||||
f.clientType = GetStringArg(args, "client_type");
|
||||
return f;
|
||||
}
|
||||
|
||||
void ApplyHostListFilter(const Json::Value& in, const HostListFilter& f, Json::Value& out) {
|
||||
out = Json::Value(Json::arrayValue);
|
||||
for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
|
||||
const Json::Value& h = in[i];
|
||||
if (!f.group.empty() && !ContainsCI(JsonStrField(h, "group"), f.group)) continue;
|
||||
if (!f.os.empty() && !ContainsCI(JsonStrField(h, "os"), f.os)) continue;
|
||||
if (!f.clientType.empty() && !ContainsCI(JsonStrField(h, "clientType"), f.clientType)) continue;
|
||||
out.append(h);
|
||||
}
|
||||
}
|
||||
|
||||
void AppendHostListFilterProps(Json::Value& props) {
|
||||
Json::Value groupProp(Json::objectValue);
|
||||
groupProp["type"] = "string";
|
||||
groupProp["description"] = u8"按分组过滤(子串,不区分大小写)。省略则不过滤。";
|
||||
props["group"] = groupProp;
|
||||
|
||||
Json::Value osProp(Json::objectValue);
|
||||
osProp["type"] = "string";
|
||||
osProp["description"] = u8"按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。";
|
||||
props["os"] = osProp;
|
||||
|
||||
Json::Value typeProp(Json::objectValue);
|
||||
typeProp["type"] = "string";
|
||||
typeProp["description"] = u8"按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。";
|
||||
props["client_type"] = typeProp;
|
||||
}
|
||||
|
||||
// ========== 工具 schema ==========
|
||||
|
||||
// 单台主机字段 schema(hosts 数组元素 / 单机详情共用的形状)
|
||||
@@ -698,6 +745,7 @@ Json::Value BuildListAllHostsInputSchema() {
|
||||
offlineProp["description"] = u8"是否包含离线主机(历史连接过、当前未连接的),默认 true";
|
||||
props["offline"] = offlineProp;
|
||||
|
||||
AppendHostListFilterProps(props);
|
||||
AppendPagingProps(props);
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -1122,6 +1170,7 @@ Json::Value BuildAuditLogOutputSchema() {
|
||||
items["properties"] = itemProps;
|
||||
entriesProp["items"] = items;
|
||||
props["entries"] = entriesProp;
|
||||
AppendPageOutputProps(props);
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
@@ -1132,6 +1181,36 @@ Json::Value BuildAuditLogOutputSchema() {
|
||||
return schema;
|
||||
}
|
||||
|
||||
// get_server_status 的 outputSchema(服务端自身状态;嵌套对象只声明类型,不逐字段展开)
|
||||
Json::Value BuildServerStatusOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
|
||||
const char* strFields[] = { "app_name", "version", "exe_build_time", "bind" };
|
||||
for (const char* f : strFields) {
|
||||
Json::Value s(Json::objectValue);
|
||||
s["type"] = "string";
|
||||
props[f] = s;
|
||||
}
|
||||
const char* intFields[] = { "uptime_sec", "port", "blocked_auth_ips" };
|
||||
for (const char* f : intFields) {
|
||||
Json::Value n(Json::objectValue);
|
||||
n["type"] = "integer";
|
||||
props[f] = n;
|
||||
}
|
||||
const char* objFields[] = { "switches", "hosts", "sessions" };
|
||||
for (const char* f : objFields) {
|
||||
Json::Value o(Json::objectValue);
|
||||
o["type"] = "object";
|
||||
props[f] = o;
|
||||
}
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
schema["required"] = Json::Value(Json::arrayValue);
|
||||
return schema;
|
||||
}
|
||||
|
||||
// get_screenshot 的 outputSchema(image 元数据;base64 数据在 content 的 image 块中)
|
||||
Json::Value BuildScreenshotOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -1334,11 +1413,12 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
tool["name"] = "list_online_hosts";
|
||||
// 说明文字为 UTF-8:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK,
|
||||
// 故用 u8 前缀确保输出到 JSON 的字节是 UTF-8。
|
||||
tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。结果按 limit/offset 分页(默认 100 条,上限 1000),total 为在线主机总数,hasMore 表示还有下一页。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。";
|
||||
tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。可选 group / os / client_type 三个过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写),过滤在分页之前生效:total 为命中台数,totalAll 为全部在线台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。";
|
||||
|
||||
Json::Value inputSchema(Json::objectValue);
|
||||
inputSchema["type"] = "object";
|
||||
Json::Value props(Json::objectValue);
|
||||
AppendHostListFilterProps(props);
|
||||
AppendPagingProps(props);
|
||||
inputSchema["properties"] = props;
|
||||
inputSchema["required"] = Json::Value(Json::arrayValue);
|
||||
@@ -1365,7 +1445,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "list_all_hosts";
|
||||
tool["description"] = u8"列出服务端已知的全部主机:在线主机(实时信息)与离线主机(历史连接过、当前未连接,来自主机列表记录)。在线主机字段同 list_online_hosts;离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。默认两类都返回;结果按 limit/offset 分页(默认 100 条,上限 1000),total 为总条数。";
|
||||
tool["description"] = u8"列出服务端已知的全部主机:在线主机(实时信息)与离线主机(历史连接过、当前未连接,来自主机列表记录)。在线主机字段同 list_online_hosts;离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。默认两类都返回;可选 group / os / client_type 过滤(AND 组合、子串匹配、ASCII 不区分大小写),过滤在分页之前生效:total 为命中台数,totalAll 为主机库总数。结果按 limit/offset 分页(默认 100 条,上限 1000)。";
|
||||
|
||||
tool["inputSchema"] = BuildListAllHostsInputSchema();
|
||||
tool["outputSchema"] = BuildHostOutputSchema();
|
||||
@@ -1528,7 +1608,34 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_audit_log";
|
||||
tool["description"] = u8"获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等)。返回列表内当前全部条目(最多 1000 条,新在前)。只读、纯内存。";
|
||||
tool["description"] = u8"获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。";
|
||||
|
||||
Json::Value inputSchema(Json::objectValue);
|
||||
inputSchema["type"] = "object";
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value typeProp(Json::objectValue);
|
||||
typeProp["type"] = "string";
|
||||
typeProp["description"] = u8"类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。";
|
||||
props["type"] = typeProp;
|
||||
Json::Value kwProp(Json::objectValue);
|
||||
kwProp["type"] = "string";
|
||||
kwProp["description"] = u8"正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。";
|
||||
props["keyword"] = kwProp;
|
||||
AppendPagingProps(props);
|
||||
inputSchema["properties"] = props;
|
||||
inputSchema["required"] = Json::Value(Json::arrayValue);
|
||||
tool["inputSchema"] = inputSchema;
|
||||
|
||||
tool["outputSchema"] = BuildAuditLogOutputSchema();
|
||||
|
||||
tools.append(tool);
|
||||
}
|
||||
|
||||
// 11b) get_server_status(服务端自身状态:版本/运行时长/开关/监听地址/计数,纯内存)
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_server_status";
|
||||
tool["description"] = u8"获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。";
|
||||
|
||||
Json::Value inputSchema(Json::objectValue);
|
||||
inputSchema["type"] = "object";
|
||||
@@ -1536,7 +1643,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
inputSchema["required"] = Json::Value(Json::arrayValue);
|
||||
tool["inputSchema"] = inputSchema;
|
||||
|
||||
tool["outputSchema"] = BuildAuditLogOutputSchema();
|
||||
tool["outputSchema"] = BuildServerStatusOutputSchema();
|
||||
|
||||
tools.append(tool);
|
||||
}
|
||||
@@ -1723,7 +1830,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "search_file";
|
||||
tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。注意:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,整盘/深目录搜索会栈溢出(Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程,Release 静默破坏栈)——请只搜具体的中浅层目录,不要从盘符根开始扫。";
|
||||
tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。可选 min_size / max_size(字节)与 modified_after(YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS)在服务端做结果侧过滤,name_only=true 只返回 path 与 name;这些过滤不减少客户端搜索耗时,total 为命中数、totalAll 为过滤前条数。注意:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,整盘/深目录搜索会栈溢出(Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程,Release 静默破坏栈)——请只搜具体的中浅层目录,不要从盘符根开始扫。";
|
||||
tool["inputSchema"] = BuildSearchFileInputSchema();
|
||||
tool["outputSchema"] = BuildSearchFileOutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -1752,9 +1859,15 @@ std::string BuildListOnlineHosts(const Json::Value& id, const Json::Value& args,
|
||||
Json::Value all(Json::arrayValue);
|
||||
CollectOnlineHosts(parent, all);
|
||||
|
||||
// 过滤在分页之前:total 是命中数,totalAll 是全部在线数(与 get_audit_log 同口径)。
|
||||
HostListFilter filter = ReadHostListFilter(args);
|
||||
Json::Value matched;
|
||||
ApplyHostListFilter(all, filter, matched);
|
||||
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
Json::Value hosts;
|
||||
ApplyPageWindow(all, page, hosts);
|
||||
ApplyPageWindow(matched, page, hosts);
|
||||
if (filter.Any()) page.totalAll = (int)all.size();
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
@@ -1762,10 +1875,14 @@ std::string BuildListOnlineHosts(const Json::Value& id, const Json::Value& args,
|
||||
WritePageFields(structuredContent, page);
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
std::string text = PageSummary(page, filter.Any() ? u8"台主机匹配" : u8"台主机在线");
|
||||
if (filter.Any())
|
||||
text += std::string(u8"在线共 ") + std::to_string((int)all.size()) + std::string(u8" 台。");
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = PageSummary(page, u8"台主机在线");
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
@@ -1781,14 +1898,20 @@ std::string BuildListAllHosts(const Json::Value& id, const Json::Value& args, CM
|
||||
Json::Value hosts(Json::arrayValue);
|
||||
CollectAllHosts(parent, hosts, includeOnline, includeOffline);
|
||||
|
||||
// 过滤先于统计与分页:total/totalAll 与摘要里的在线/离线数都按命中条目算。
|
||||
HostListFilter filter = ReadHostListFilter(args);
|
||||
Json::Value matched;
|
||||
ApplyHostListFilter(hosts, filter, matched);
|
||||
|
||||
int onlineCount = 0;
|
||||
for (unsigned int i = 0; i < hosts.size(); ++i) {
|
||||
if (hosts[i]["online"].asBool()) onlineCount++;
|
||||
for (unsigned int i = 0; i < matched.size(); ++i) {
|
||||
if (matched[i]["online"].asBool()) onlineCount++;
|
||||
}
|
||||
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
Json::Value pageItems;
|
||||
ApplyPageWindow(hosts, page, pageItems);
|
||||
ApplyPageWindow(matched, page, pageItems);
|
||||
if (filter.Any()) page.totalAll = (int)hosts.size();
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
@@ -1799,9 +1922,11 @@ std::string BuildListAllHosts(const Json::Value& id, const Json::Value& args, CM
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
std::string text = PageSummary(page, u8"台主机");
|
||||
std::string text = PageSummary(page, filter.Any() ? u8"台主机匹配" : u8"台主机");
|
||||
text += std::string(u8"其中在线 ") + std::to_string(onlineCount) +
|
||||
std::string(u8",离线 ") + std::to_string(page.total - onlineCount) + std::string(u8"。");
|
||||
if (filter.Any())
|
||||
text += std::string(u8"主机库共 ") + std::to_string((int)hosts.size()) + std::string(u8" 台。");
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
@@ -2700,33 +2825,154 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM
|
||||
}
|
||||
|
||||
// tools/call:get_audit_log(服务端本地消息日志,读取 UI 日志列表的线程安全镜像)
|
||||
std::string BuildGetAuditLog(const Json::Value& id, CMy2015RemoteDlg* parent) {
|
||||
Json::Value entries(Json::arrayValue);
|
||||
std::string BuildGetAuditLog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
std::string fType = GetStringArg(args, "type");
|
||||
std::string fKeyword = GetStringArg(args, "keyword");
|
||||
|
||||
Json::Value all(Json::arrayValue);
|
||||
int rawCount = 0;
|
||||
if (parent) {
|
||||
EnterCriticalSection(&parent->m_cs);
|
||||
// m_MessageLog 新在前、旧在后(与界面一致),直接顺序输出。
|
||||
// 镜像本身有 1000 条环形上限(MAX_MESSAGE_COUNT),过滤与分页都在内存里做,代价可忽略。
|
||||
for (const auto& e : parent->m_MessageLog) {
|
||||
std::string ty = ToUtf8(e.type.c_str(), 936);
|
||||
std::string tm = ToUtf8(e.time.c_str(), 936);
|
||||
std::string ms = ToUtf8(e.msg.c_str(), 936);
|
||||
rawCount++;
|
||||
if (!fType.empty() && !ContainsCI(ty, fType)) continue;
|
||||
if (!fKeyword.empty() && !ContainsCI(ms, fKeyword)) continue;
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = ToUtf8(e.type.c_str(), 936);
|
||||
item["time"] = ToUtf8(e.time.c_str(), 936);
|
||||
item["msg"] = ToUtf8(e.msg.c_str(), 936);
|
||||
entries.append(item);
|
||||
item["type"] = ty;
|
||||
item["time"] = tm;
|
||||
item["msg"] = ms;
|
||||
all.append(item);
|
||||
}
|
||||
LeaveCriticalSection(&parent->m_cs);
|
||||
}
|
||||
|
||||
int count = (int)entries.size();
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
Json::Value entries;
|
||||
ApplyPageWindow(all, page, entries);
|
||||
page.totalAll = rawCount; // 过滤前的总条数:total 是命中数,totalAll 是镜像里全部条数
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
structuredContent["entries"] = entries;
|
||||
WritePageFields(structuredContent, page);
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
std::string text = PageSummary(page, u8"条日志");
|
||||
if (!fType.empty() || !fKeyword.empty())
|
||||
text += std::string(u8"过滤前共 ") + std::to_string(rawCount) + std::string(u8" 条。");
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = count > 0 ? std::string(u8"共 ") + std::to_string(count) + std::string(u8" 条日志。")
|
||||
: std::string(u8"当前无日志。");
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
// tools/call:get_server_status(服务端自身状态:版本/构建时间/运行时长/开关/监听地址/计数)
|
||||
std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent) {
|
||||
CMcpServer& srv = CMcpServer::Instance();
|
||||
|
||||
Json::Value status(Json::objectValue);
|
||||
status["app_name"] = BRAND_APP_NAME;
|
||||
status["version"] = VERSION_STR;
|
||||
|
||||
// exe 的最后写入时间就是链接时间,比 __DATE__/__TIME__ 可靠(后者是编译本 .cpp 的时间)。
|
||||
{
|
||||
char exe[MAX_PATH] = { 0 };
|
||||
if (GetModuleFileNameA(NULL, exe, MAX_PATH) > 0) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (GetFileAttributesExA(exe, GetFileExInfoStandard, &fad)) {
|
||||
FILETIME local = fad.ftLastWriteTime;
|
||||
FileTimeToLocalFileTime(&fad.ftLastWriteTime, &local);
|
||||
SYSTEMTIME st = { 0 };
|
||||
if (FileTimeToSystemTime(&local, &st)) {
|
||||
char buf[32] = { 0 };
|
||||
wsprintfA(buf, "%04d-%02d-%02d %02d:%02d:%02d",
|
||||
(int)st.wYear, (int)st.wMonth, (int)st.wDay,
|
||||
(int)st.wHour, (int)st.wMinute, (int)st.wSecond);
|
||||
status["exe_build_time"] = buf;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 进程运行时长:从进程创建时间算起(不是系统开机时间,也不受 MCP 启停影响)。
|
||||
{
|
||||
FILETIME createTime, exitTime, kernelTime, userTime, nowFt;
|
||||
if (GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime)) {
|
||||
GetSystemTimeAsFileTime(&nowFt);
|
||||
ULARGE_INTEGER c, n;
|
||||
c.LowPart = createTime.dwLowDateTime; c.HighPart = createTime.dwHighDateTime;
|
||||
n.LowPart = nowFt.dwLowDateTime; n.HighPart = nowFt.dwHighDateTime;
|
||||
LONGLONG ticks100ns = (LONGLONG)(n.QuadPart - c.QuadPart);
|
||||
if (ticks100ns > 0) status["uptime_sec"] = (Json::Int64)(ticks100ns / 10000000LL);
|
||||
}
|
||||
}
|
||||
|
||||
status["bind"] = srv.GetBind();
|
||||
status["port"] = srv.GetPort();
|
||||
|
||||
// 开关只报「开/关」,不输出 token、白名单内容等敏感配置。
|
||||
Json::Value switches(Json::objectValue);
|
||||
switches["readonly"] = srv.IsReadonly();
|
||||
switches["terminal"] = srv.IsTerminalEnabled();
|
||||
switches["remote_control"] = srv.IsRemoteControlEnabled();
|
||||
switches["file_transfer"] = srv.IsFileTransferEnabled();
|
||||
switches["manage"] = srv.IsManageEnabled();
|
||||
switches["machine"] = srv.IsMachineEnabled();
|
||||
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
|
||||
switches["keylog"] = srv.IsKeylogEnabled();
|
||||
switches["chat"] = srv.IsChatEnabled();
|
||||
status["switches"] = switches;
|
||||
|
||||
int onlineCount = 0, offlineCount = 0;
|
||||
if (parent) {
|
||||
Json::Value all(Json::arrayValue);
|
||||
CollectAllHosts(parent, all, true, true);
|
||||
for (Json::Value::ArrayIndex i = 0; i < all.size(); ++i) {
|
||||
if (all[i]["online"].asBool()) onlineCount++;
|
||||
else offlineCount++;
|
||||
}
|
||||
}
|
||||
Json::Value hosts(Json::objectValue);
|
||||
hosts["online"] = onlineCount;
|
||||
hosts["offline"] = offlineCount;
|
||||
status["hosts"] = hosts;
|
||||
|
||||
int pending = 0, terminal = 0, screenCtrl = 0, fileXfer = 0, chat = 0, blockedIps = 0;
|
||||
srv.GetRuntimeCounters(pending, terminal, screenCtrl, fileXfer, chat, blockedIps);
|
||||
Json::Value sessions(Json::objectValue);
|
||||
sessions["pending"] = pending; // 一次性/管理/键盘记录挂起会话
|
||||
sessions["terminal"] = terminal;
|
||||
sessions["remote_control"] = screenCtrl;
|
||||
sessions["file_transfer"] = fileXfer;
|
||||
sessions["chat"] = chat;
|
||||
status["sessions"] = sessions;
|
||||
status["blocked_auth_ips"] = blockedIps;
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
structuredContent["status"] = status;
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
std::string text = std::string(BRAND_APP_NAME) + " v" + VERSION_STR +
|
||||
std::string(u8",已运行 ") + std::to_string((long long)status["uptime_sec"].asInt64()) +
|
||||
std::string(u8" 秒,监听 ") + srv.GetBind() + ":" + std::to_string(srv.GetPort()) +
|
||||
std::string(u8";在线主机 ") + std::to_string(onlineCount) +
|
||||
std::string(u8" 台、离线 ") + std::to_string(offlineCount) + std::string(u8" 台。");
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
@@ -4263,6 +4509,7 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
const char* msg = (error == 1002) ? "Timeout waiting for file transfer"
|
||||
: (error == 1001) ? "Path traversal detected in received path"
|
||||
: (error == 1003) ? "Connection lost: the transfer sub-connection closed"
|
||||
: (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed"
|
||||
: "File transfer failed";
|
||||
return BuildError(id, -32001, msg);
|
||||
@@ -5348,6 +5595,27 @@ Json::Value BuildSearchFileInputSchema() {
|
||||
toProp["description"] = u8"搜索时限(毫秒),默认 20000,范围 1000-120000。到时限会通知客户端停止搜索,返回已收到的部分结果(finished=false)。";
|
||||
props["timeout_ms"] = toProp;
|
||||
|
||||
// ===== C4:结果侧过滤 =====
|
||||
Json::Value minProp(Json::objectValue);
|
||||
minProp["type"] = "integer";
|
||||
minProp["description"] = u8"只保留大小不小于该字节数的条目。目录项也会参与比较(客户端上报的目录 size 恒为 0),只想看文件时用 min_size=1。";
|
||||
props["min_size"] = minProp;
|
||||
|
||||
Json::Value maxProp(Json::objectValue);
|
||||
maxProp["type"] = "integer";
|
||||
maxProp["description"] = u8"只保留不大于该字节数的条目。与 min_size 同时给出时区间取交集。";
|
||||
props["max_size"] = maxProp;
|
||||
|
||||
Json::Value maProp(Json::objectValue);
|
||||
maProp["type"] = "string";
|
||||
maProp["description"] = u8"只保留修改时间晚于该时刻的条目,格式 YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS(主机本地时间)。只给日期时按「该日 00:00:00 之后」理解。";
|
||||
props["modified_after"] = maProp;
|
||||
|
||||
Json::Value nameOnlyProp(Json::objectValue);
|
||||
nameOnlyProp["type"] = "boolean";
|
||||
nameOnlyProp["description"] = u8"true 时每条只返回 path 与 name,省略 dir/size/modified,用于结果集很大时省流量。默认 false。";
|
||||
props["name_only"] = nameOnlyProp;
|
||||
|
||||
AppendPagingProps(props);
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -5424,6 +5692,51 @@ std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2
|
||||
timeoutMs = v;
|
||||
}
|
||||
|
||||
// ===== C4:结果侧过滤参数(全部在服务端做,客户端仍只做「按名字匹配 + 递归」)=====
|
||||
// 读可选的字节数参数:0=未给出;1=已给出;-1=非法(负数/非数字)。
|
||||
auto readSizeArg = [](const Json::Value& a, const char* key, uint64_t& out) -> int {
|
||||
if (!a.isMember(key)) return 0;
|
||||
const Json::Value& val = a[key];
|
||||
if (val.isNumeric() && val.asDouble() < 0) return -1;
|
||||
if (!ReadUInt64(val, out)) return -1;
|
||||
return 1;
|
||||
};
|
||||
uint64_t minSize = 0, maxSize = 0;
|
||||
int hasMinSize = readSizeArg(args, "min_size", minSize);
|
||||
int hasMaxSize = readSizeArg(args, "max_size", maxSize);
|
||||
if (hasMinSize < 0)
|
||||
return BuildError(id, -32602, "min_size must be a non-negative integer (bytes)");
|
||||
if (hasMaxSize < 0)
|
||||
return BuildError(id, -32602, "max_size must be a non-negative integer (bytes)");
|
||||
if (hasMinSize == 1 && hasMaxSize == 1 && minSize > maxSize)
|
||||
return BuildError(id, -32602, "min_size must not be greater than max_size");
|
||||
|
||||
// 客户端 modified 是固定宽度的 "YYYY-MM-DD HH:MM:SS",所以边界值可直接按字典序比较。
|
||||
std::string modifiedAfter;
|
||||
if (args.isMember("modified_after")) {
|
||||
if (!args["modified_after"].isString())
|
||||
return BuildError(id, -32602, "modified_after must be a string");
|
||||
modifiedAfter = Trim(args["modified_after"].asString());
|
||||
if (!modifiedAfter.empty()) {
|
||||
bool shaped = (modifiedAfter.size() == 10 || modifiedAfter.size() == 19);
|
||||
for (size_t i = 0; shaped && i < modifiedAfter.size(); ++i) {
|
||||
const char c = modifiedAfter[i];
|
||||
if (i == 4 || i == 7) shaped = (c == '-');
|
||||
else if (i == 10) shaped = (c == ' ');
|
||||
else if (i == 13 || i == 16) shaped = (c == ':'); // 19 位形式才有
|
||||
else shaped = (c >= '0' && c <= '9');
|
||||
}
|
||||
if (!shaped)
|
||||
return BuildError(id, -32602,
|
||||
"modified_after must look like YYYY-MM-DD or YYYY-MM-DD HH:MM:SS");
|
||||
}
|
||||
}
|
||||
|
||||
bool nameOnly = args.isMember("name_only") && args["name_only"].isBool() &&
|
||||
args["name_only"].asBool();
|
||||
const bool hasResultFilter = hasMinSize == 1 || hasMaxSize == 1 ||
|
||||
!modifiedAfter.empty() || nameOnly;
|
||||
|
||||
std::string ansiPath, ansiPattern;
|
||||
if (!Utf8ToCpExact(path, 936, ansiPath))
|
||||
return BuildError(id, -32602,
|
||||
@@ -5501,9 +5814,37 @@ std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2
|
||||
all = filtered;
|
||||
}
|
||||
|
||||
// C4:结果侧过滤。注意它发生在收集之后——客户端的 5000 条 / 4 MB 收集上限
|
||||
// 仍在过滤之前生效,命中太多时该 truncated 还是会 truncated。
|
||||
const int collected = (int)all.size();
|
||||
if (hasResultFilter) {
|
||||
Json::Value filtered(Json::arrayValue);
|
||||
for (const Json::Value& rec : all) {
|
||||
if (hasMinSize == 1 || hasMaxSize == 1) {
|
||||
uint64_t sz = rec["size"].asUInt64();
|
||||
if (hasMinSize == 1 && sz < minSize) continue;
|
||||
if (hasMaxSize == 1 && sz > maxSize) continue;
|
||||
}
|
||||
if (!modifiedAfter.empty()) {
|
||||
std::string m = JsonStrField(rec, "modified");
|
||||
if (m.empty() || m <= modifiedAfter) continue; // 字典序即时间序(格式固定)
|
||||
}
|
||||
if (nameOnly) {
|
||||
Json::Value slim(Json::objectValue);
|
||||
slim["path"] = rec["path"];
|
||||
slim["name"] = rec["name"];
|
||||
filtered.append(slim);
|
||||
} else {
|
||||
filtered.append(rec);
|
||||
}
|
||||
}
|
||||
all = filtered;
|
||||
}
|
||||
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
Json::Value pageItems;
|
||||
ApplyPageWindow(all, page, pageItems);
|
||||
if (hasResultFilter) page.totalAll = collected; // total 是命中数,totalAll 是过滤前条数
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
@@ -5514,6 +5855,9 @@ std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
std::string text = PageSummary(page, u8"个匹配项");
|
||||
if (hasResultFilter)
|
||||
text += std::string(u8"过滤前共 ") + std::to_string(collected) +
|
||||
std::string(u8" 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)。");
|
||||
if (!finished)
|
||||
text += u8" 搜索在时限内未完成,以上为已收到的部分结果(可加大 timeout_ms 重试)。";
|
||||
if (truncated)
|
||||
@@ -5813,7 +6157,8 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
if (toolName == "list_services") return BuildListServices(id, args, parent);
|
||||
if (toolName == "get_client_log") return BuildGetClientLog(id, args, parent);
|
||||
if (toolName == "get_keylog") return BuildGetKeylog(id, args, parent);
|
||||
if (toolName == "get_audit_log") return BuildGetAuditLog(id, parent);
|
||||
if (toolName == "get_audit_log") return BuildGetAuditLog(id, args, parent);
|
||||
if (toolName == "get_server_status") return BuildGetServerStatus(id, parent);
|
||||
if (toolName == "list_registry") return BuildListRegistry(id, args, parent);
|
||||
if (toolName == "exec_command") return BuildExecCommand(id, args, parent);
|
||||
if (toolName == "terminal_open") return BuildTerminalOpen(id, args, parent);
|
||||
@@ -6279,6 +6624,9 @@ bool CMcpServer::Start(const std::string& bind, int port) {
|
||||
m_server.set_write_timeout(60, 0);
|
||||
m_server.new_task_queue = []() { return new httplib::ThreadPool(32); };
|
||||
|
||||
m_bind = bind;
|
||||
m_port = port;
|
||||
|
||||
m_thread = std::thread([this, bind, port]() {
|
||||
m_server.listen(bind, port);
|
||||
});
|
||||
@@ -6297,6 +6645,38 @@ void CMcpServer::Stop() {
|
||||
m_running.store(false);
|
||||
}
|
||||
|
||||
// get_server_status:各类在飞会话 + 当前被封禁的来源 IP 计数。
|
||||
// 每类只取自己的锁且立刻释放,不跨锁持有一致性(这些数字只作观测用)。
|
||||
void CMcpServer::GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
|
||||
int& fileXfer, int& chat, int& blockedIps) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
pending = (int)m_Pending.size();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
terminal = (int)m_TermSessions.size();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
|
||||
screenCtrl = (int)m_ScreenCtrlSessions.size();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_FileXferMutex);
|
||||
fileXfer = (int)m_FileXferSessions.size();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_ChatMutex);
|
||||
chat = (int)m_ChatSessions.size();
|
||||
}
|
||||
blockedIps = 0;
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
std::lock_guard<std::mutex> lk(m_AuthMutex);
|
||||
for (const auto& kv : m_AuthFails) {
|
||||
if (kv.second.blockedUntil > now) blockedIps++;
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 鉴权加固(N4)=====
|
||||
//
|
||||
// 两件事:
|
||||
@@ -6527,17 +6907,39 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res)
|
||||
|
||||
// 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判)
|
||||
bool failed = false;
|
||||
int errCode = 0;
|
||||
std::string errMsg;
|
||||
{
|
||||
Json::Value parsed;
|
||||
Json::CharReaderBuilder rb;
|
||||
std::string perrs;
|
||||
std::istringstream pis(resp);
|
||||
if (Json::parseFromStream(rb, pis, &parsed, &perrs))
|
||||
failed = parsed.isObject() && parsed.isMember("error");
|
||||
if (Json::parseFromStream(rb, pis, &parsed, &perrs) &&
|
||||
parsed.isObject() && parsed.isMember("error")) {
|
||||
failed = true;
|
||||
const Json::Value& err = parsed["error"];
|
||||
if (err.isObject()) {
|
||||
if (err["code"].isInt()) errCode = err["code"].asInt();
|
||||
if (err["message"].isString()) errMsg = err["message"].asString();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行
|
||||
auto oneLine = [](std::string v) {
|
||||
for (char& c : v)
|
||||
if ((unsigned char)c < 0x20) c = ' ';
|
||||
return v;
|
||||
};
|
||||
const std::string toolTag =
|
||||
"tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName);
|
||||
AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp,
|
||||
"tool=" + (toolName.empty() ? std::string("(empty)") : toolName) +
|
||||
" ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size()));
|
||||
toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size()));
|
||||
|
||||
// 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED,
|
||||
// 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含
|
||||
// 调用参数或用户输入,可以直接落盘。
|
||||
if (errCode == -32006)
|
||||
AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg));
|
||||
|
||||
res.set_content(resp, "application/json");
|
||||
return;
|
||||
@@ -7014,6 +7416,7 @@ bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) {
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.fmSubCtx != nullptr) return true; // 已下发过,防重复
|
||||
s.fmSubCtx = fmSubCtx;
|
||||
m_FileXferContextToDevice[fmSubCtx] = device_id; // OfflineProc 反查用
|
||||
localDir = s.localDir;
|
||||
remotePath = s.remotePath;
|
||||
}
|
||||
@@ -7048,7 +7451,10 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return; // 已出错/完成,丢弃迟到包
|
||||
|
||||
if (s.streamSubCtx == nullptr) s.streamSubCtx = streamSubCtx;
|
||||
if (s.streamSubCtx == nullptr) {
|
||||
s.streamSubCtx = streamSubCtx;
|
||||
m_FileXferContextToDevice[streamSubCtx] = device_id; // OfflineProc 反查用
|
||||
}
|
||||
if (s.transferID == 0) {
|
||||
s.transferID = pkt->transferID;
|
||||
s.totalFiles = pkt->totalFiles;
|
||||
@@ -7068,6 +7474,13 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
|
||||
}
|
||||
s.directoryCount++;
|
||||
RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0);
|
||||
// 纯目录树(空目录、只有子目录):期望文件数 = totalFiles - directoryCount = 0,
|
||||
// 而客户端对目录项不发 COMPLETE 包,完成判定永远等不到 → 只能干等到超时。
|
||||
// 目录项数已覆盖全部条目时直接判完成(totalFiles 含目录项,见 F4)。
|
||||
if (s.totalFiles > 0 && s.directoryCount >= s.totalFiles) {
|
||||
s.done = true;
|
||||
m_FileXferCv.notify_one();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7172,9 +7585,37 @@ void CMcpServer::ClearFileTransfer(uint64_t device_id) {
|
||||
m_FileXferSessions.erase(it);
|
||||
found = true;
|
||||
}
|
||||
// 反查表按 context* 键,必须随会话一起擦,否则连接池复用同一指针后会被误转成断线事件。
|
||||
if (s.fmSubCtx) m_FileXferContextToDevice.erase(s.fmSubCtx);
|
||||
if (s.streamSubCtx) m_FileXferContextToDevice.erase(s.streamSubCtx);
|
||||
}
|
||||
if (!found) return;
|
||||
// 锁外关闭两条子链接(CancelIO 触发客户端断开,停掉仍在飞的流式数据)。
|
||||
if (s.fmSubCtx) s.fmSubCtx->CancelIO();
|
||||
if (s.streamSubCtx) s.streamSubCtx->CancelIO();
|
||||
}
|
||||
|
||||
void CMcpServer::OnFileTransferContextClosed(context* subCtx) {
|
||||
std::lock_guard<std::mutex> lk(m_FileXferMutex);
|
||||
auto mapIt = m_FileXferContextToDevice.find(subCtx);
|
||||
if (mapIt == m_FileXferContextToDevice.end()) return; // 不是文件传输子链接
|
||||
uint64_t device_id = mapIt->second;
|
||||
m_FileXferContextToDevice.erase(mapIt);
|
||||
|
||||
auto it = m_FileXferSessions.find(device_id);
|
||||
if (it == m_FileXferSessions.end()) return;
|
||||
FileTransferSession& s = it->second;
|
||||
|
||||
// 无论如何先清裸指针:此后工具线程的 ClearFileTransfer 绝不能再对这条已回收的连接 CancelIO。
|
||||
bool wasStream = (s.streamSubCtx == subCtx);
|
||||
if (s.fmSubCtx == subCtx) s.fmSubCtx = nullptr;
|
||||
if (s.streamSubCtx == subCtx) s.streamSubCtx = nullptr;
|
||||
|
||||
// 流式子链接承载数据,它断了传输就不可能完成 → 立即判失败并唤醒工具线程(不用等 timeout)。
|
||||
// 文件管理器子链接只用来下发命令,断开不代表传输失败,清指针即可。
|
||||
if (wasStream && !s.done) {
|
||||
s.error = 1003; // 断线
|
||||
s.done = true;
|
||||
m_FileXferCv.notify_all();
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,11 @@ public:
|
||||
// 收尾:擦会话 + 锁外 CancelIO 文件管理器/流式两条子链接(幂等)。
|
||||
void ClearFileTransfer(uint64_t device_id);
|
||||
|
||||
// 文件传输子链接断开(OfflineProc 调用):清反查表 + 置空裸指针,避免工具线程超时路径
|
||||
// 对已回收(连接池复用)的 context 误 CancelIO。流式子链接断开 = 传输失败(1003);
|
||||
// 文件管理器子链接断开只是少了收尾对象,传输数据走流式子链接,不判失败。
|
||||
void OnFileTransferContextClosed(context* subCtx);
|
||||
|
||||
// ===== P7:设备管理控制(kill_process / operate_window / control_service / power_action)=====
|
||||
// 写工具复用 m_Pending 单飞行;followUp/followUpSent/subCtx 标记接管进度。
|
||||
// 「就绪 token」与「确认 token」是同一 token(客户端子连接构造即回一包,写后再回一包),
|
||||
@@ -414,6 +419,15 @@ public:
|
||||
bool IsReadonly() const { return m_readonly; }
|
||||
const std::string& GetCmdWhitelist() const { return m_cmdWhitelist; }
|
||||
|
||||
// 监听地址/端口(Start 时记录,供 get_server_status 报告)。
|
||||
const std::string& GetBind() const { return m_bind; }
|
||||
int GetPort() const { return m_port; }
|
||||
|
||||
// get_server_status:在飞会话与鉴权封禁计数。每类各取一次自己的锁,
|
||||
// 返回前全部释放——调用方拿到的是「大致同一时刻」的估算值,不用来同步。
|
||||
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
|
||||
int& fileXfer, int& chat, int& blockedIps);
|
||||
|
||||
private:
|
||||
CMcpServer();
|
||||
~CMcpServer();
|
||||
@@ -455,6 +469,8 @@ private:
|
||||
std::thread m_thread;
|
||||
std::atomic<bool> m_running{false};
|
||||
std::string m_token;
|
||||
std::string m_bind; // Start 传入的监听地址
|
||||
int m_port = 0; // Start 传入的监听端口
|
||||
CMy2015RemoteDlg* m_parent = nullptr;
|
||||
|
||||
// 挂起请求注册表(受 m_PendingMutex 保护,键 = device_id)。
|
||||
@@ -572,7 +588,7 @@ private:
|
||||
uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包)
|
||||
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
|
||||
bool done = false; // 全部完成或出错
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时
|
||||
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线
|
||||
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
|
||||
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
|
||||
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
|
||||
@@ -581,6 +597,8 @@ private:
|
||||
std::mutex m_FileXferMutex;
|
||||
std::condition_variable m_FileXferCv;
|
||||
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
|
||||
// 子连接反查(受 m_FileXferMutex 保护):OfflineProc 拿不到 device_id,只能按 context* 找会话。
|
||||
std::map<context*, uint64_t> m_FileXferContextToDevice;
|
||||
|
||||
// ===== P9:远程交谈(受 m_ChatMutex 保护;单设备单会话)=====
|
||||
// 用 shared_ptr 持有会话:chat_wait / chat_send 在工作线程里复制一份后,即使 map 条目
|
||||
|
||||
+85
-1
@@ -18,6 +18,8 @@
|
||||
-SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。
|
||||
不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,
|
||||
深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。
|
||||
-AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言
|
||||
-32006 拒绝会写一条 CALL_DENIED。
|
||||
|
||||
退出码:0 全部通过;1 有失败项。token 不会被打印。
|
||||
#>
|
||||
@@ -26,7 +28,8 @@ param(
|
||||
[string]$Token = $env:YAMA_MCP_TOKEN,
|
||||
[string]$HostId = '',
|
||||
[switch]$SkipHost,
|
||||
[string]$SearchPath = ''
|
||||
[string]$SearchPath = '',
|
||||
[string]$AuditLog = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -119,6 +122,24 @@ $ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
|
||||
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
|
||||
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
|
||||
|
||||
# ===== 2b. 协议层错误码 =====
|
||||
Write-Host "`n[2b] 协议层错误码"
|
||||
$um = Rpc 'bogus/method' @{} $null $null
|
||||
Check '未知 method 返回 -32601' ([int]$um.error.code -eq -32601) ([string]$um.error.code)
|
||||
$ut = Rpc '' $null 'no_such_tool' @{}
|
||||
Check '未知工具返回 -32602' ([int]$ut.error.code -eq -32602) ([string]$ut.error.code)
|
||||
$mi = Rpc '' $null 'get_host_detail' @{}
|
||||
Check '缺少必填参数返回 -32602' ([int]$mi.error.code -eq -32602) ([string]$mi.error.message)
|
||||
|
||||
# ===== 2c. 批量入口上限 =====
|
||||
$ids51 = (1..51 | ForEach-Object { '"99999999999999' + $_ + '"' }) -join ','
|
||||
# Rpc 会把 ids 数组重新序列化,这里直接发原始请求体,避免 51 个 id 走两层转换
|
||||
$raw51 = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_processes","arguments":{"ids":[' +
|
||||
$ids51 + ']}}}'
|
||||
$r51 = Send-Raw $raw51 $Token
|
||||
$j51 = $r51.Body | ConvertFrom-Json
|
||||
Check '批量 51 个 id 返回 -32602' ([int]$j51.error.code -eq -32602) ([string]$j51.error.message)
|
||||
|
||||
# ===== 3. 服务端本机只读工具 =====
|
||||
Write-Host "`n[3] 服务端本机工具"
|
||||
$online = Rpc '' $null 'list_online_hosts' @{ limit = 100 }
|
||||
@@ -126,6 +147,10 @@ $sc = $online.result.structuredContent
|
||||
Check 'list_online_hosts 带分页字段' (HasPaging $sc)
|
||||
Check 'list_online_hosts 每条都有 id/online' (@($sc.hosts | Where-Object { -not $_.id -or $_.online -ne $true }).Count -eq 0)
|
||||
|
||||
$noMatch = Rpc '' $null 'list_online_hosts' @{ group = 'zzz-no-such-group' }
|
||||
Check 'list_online_hosts 过滤未命中返回 0 条' ($noMatch.error -eq $null -and [int]$noMatch.result.structuredContent.total -eq 0)
|
||||
Check 'list_online_hosts 过滤后 totalAll 仍是全部在线数' ([int]$noMatch.result.structuredContent.totalAll -eq [int]$sc.totalAll)
|
||||
|
||||
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
|
||||
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
|
||||
|
||||
@@ -134,6 +159,19 @@ Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found
|
||||
|
||||
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
|
||||
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
|
||||
Check 'get_audit_log 带分页字段' (HasPaging $audit.result.structuredContent)
|
||||
Check 'get_audit_log 条数不超过 limit' (@($audit.result.structuredContent.entries).Count -le 5)
|
||||
$auditFiltered = Rpc '' $null 'get_audit_log' @{ type = 'zzz-no-such-type'; limit = 5 }
|
||||
Check 'get_audit_log 过滤未命中返回 0 条' ($auditFiltered.error -eq $null -and @($auditFiltered.result.structuredContent.entries).Count -eq 0)
|
||||
|
||||
$status = Rpc '' $null 'get_server_status' @{}
|
||||
$st = $status.result.structuredContent.status
|
||||
Check 'get_server_status 正常返回' ($status.error -eq $null -and $null -ne $st)
|
||||
$basePort = 6544
|
||||
if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
|
||||
Check 'get_server_status 版本/端口/开关齐全' `
|
||||
([string]$st.version -ne '' -and [int]$st.port -eq $basePort -and $null -ne $st.switches -and $null -ne $st.sessions)
|
||||
Check 'get_server_status 不含 token' (($st | ConvertTo-Json -Depth 6) -notmatch '(?i)token')
|
||||
|
||||
if (-not $HostId) {
|
||||
$first = @($sc.hosts)[0]
|
||||
@@ -183,6 +221,23 @@ if (-not $SkipHost) {
|
||||
} else {
|
||||
Check 'search_file 带 finished/truncated 字段' (($null -ne $ss.finished) -and ($null -ne $ss.truncated))
|
||||
Check 'search_file 命中项字段完整' (@($ss.files | Where-Object { -not $_.path -or $null -eq $_.size }).Count -eq 0)
|
||||
|
||||
# C4:结果侧过滤(大小 / 修改时间 / 精简字段),全部在服务端做
|
||||
$base0 = [int]$ss.totalAll
|
||||
$big = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||||
limit = 3; timeout_ms = 5000; min_size = 1073741824 }
|
||||
$bs = $big.result.structuredContent
|
||||
Check 'search_file min_size 过滤后 totalAll 不变' `
|
||||
($big.error -eq $null -and [int]$bs.totalAll -eq $base0 -and [int]$bs.total -le $base0)
|
||||
$slim = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||||
limit = 3; timeout_ms = 5000; name_only = $true }
|
||||
$sl = @($slim.result.structuredContent.files)
|
||||
Check 'search_file name_only 只返回 path/name' `
|
||||
($slim.error -eq $null -and @($sl | Where-Object { $_.size -or $_.modified -or $_.dir }).Count -eq 0)
|
||||
$bad = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||||
modified_after = '2026/01/01' }
|
||||
Check 'search_file 非法 modified_after 返回 -32602' `
|
||||
($bad.error -and [int]$bad.error.code -eq -32602)
|
||||
}
|
||||
} else {
|
||||
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow
|
||||
@@ -195,6 +250,35 @@ if (-not $SkipHost) {
|
||||
Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1)
|
||||
}
|
||||
|
||||
# ===== 5. 策略拒绝(-32006) =====
|
||||
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
|
||||
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
|
||||
Write-Host "`n[5] 策略拒绝"
|
||||
$gateMap = @(
|
||||
@{ swName = 'keylog'; tool = 'get_keylog'; args = @{} }
|
||||
@{ swName = 'chat'; tool = 'chat_open'; args = @{} }
|
||||
@{ swName = 'terminal'; tool = 'terminal_open'; args = @{} }
|
||||
@{ swName = 'remote_control'; tool = 'get_screenshot'; args = @{} }
|
||||
)
|
||||
$offGate = $null
|
||||
foreach ($g in $gateMap) {
|
||||
if ($null -ne $st.switches -and $st.switches.PSObject.Properties.Name -contains $g.swName -and
|
||||
$st.switches.($g.swName) -eq $false) { $offGate = $g; break }
|
||||
}
|
||||
if ($offGate) {
|
||||
$args5 = @{}
|
||||
if ($HostId) { $args5['id'] = $HostId }
|
||||
foreach ($k in $offGate.args.Keys) { $args5[$k] = $offGate.args[$k] }
|
||||
$refused = Rpc '' $null $offGate.tool $args5
|
||||
Check ("关闭 " + $offGate.swName + " 后 " + $offGate.tool + " 返回 -32006") ([int]$refused.error.code -eq -32006) ([string]$refused.error.message)
|
||||
if ($AuditLog) {
|
||||
$tail = Get-Content -LiteralPath $AuditLog -Tail 20 -ErrorAction SilentlyContinue
|
||||
Check '拒绝记录进审计日志(CALL_DENIED)' (@($tail | Where-Object { $_ -match 'CALL_DENIED' }).Count -gt 0)
|
||||
}
|
||||
} else {
|
||||
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# ===== 汇总 =====
|
||||
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
|
||||
if ($script:fail -gt 0) {
|
||||
|
||||
Reference in new issue
Block a user