Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they need. Reusing McpFileTransfer would have been wrong: uploading overwrites a file, deleting destroys a tree, and an operator who wants one may well not want the other. McpFileWrite is therefore a separate key, off by default, wired the way every other switch is - read from settings.ini at startup, reported as get_server_status.switches.file_write, and exposed with its own checkbox in the MCP settings dialog. The tools additionally require readonly to be off: a read-only server has no business modifying a host. No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY, COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows file manager. The chain reuses the file-manager sub-connection and adds a phase - the main connection asks for the drive list, the sub-connection's first packet hands it to OnDriveList which sends the write command, and the client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1, where the tool sends COMMAND_LIST_FILES for the parent so the ack and the confirmation share one timeout. Only the IO thread touches the sub-connection; the tool thread just waits on the shared condvar, which keeps the sub-connection's lifetime out of its reach. The confirmation exists because the client answers unconditionally: it ignores the return values of DeleteFile, MoveFile and MakeSureDirectoryPathExists and there is no error token. ok therefore only means "the command arrived", and verified is the real answer - true when the parent listing shows the expected post-state, false when it shows the opposite, null when the listing itself did not come back (timeout or disconnect), since reporting that as false would be a lie. Linux, macOS and Android hosts are refused outright: those clients decode these paths as GBK while the server speaks UTF-8 to them for list_files, so a non-ASCII path would corrupt rather than fail. Paths are validated as UTF-8, converted to GBK exactly once, and reject %VAR%, relative paths, drive and share roots, and - for delete_path and for move_path's source - the Windows, Program Files, ProgramData, $Recycle.Bin and System Volume Information trees. create_folder gets no system-directory ban, because writing there is the same permission upload_file already has. Two defects surfaced while exercising this against a real client: create_folder's wire path has to end with a backslash, because MakeSureDirectoryPathExists treats a non-terminated last component as a file name and only creates the intermediate levels; and ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the lookup ever set it - argument evaluation order is unspecified and MSVC evaluates right to left - so every create_folder reported verified=false even when the directory existed. Verified on a Debug x64 build against a Windows client over MCP: nested create_folder, upload, rename, delete, delete a tree, the failure shapes (delete with recursive=false on a directory, create_folder onto an existing file name, delete of a non-existent target) and every refusal (drive root, C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to, offline host, non-numeric id), with a Chinese-named directory created, renamed and deleted end to end; no file-manager window appeared in the server process during any of it. The smoke test gained section [4c], opt-in through -FileWriteDir, which asserts verified and never ok and walks a sandbox through the same path; two runs passed 69 checks with the sandbox removed afterwards. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
bb55f52b29
commit
27b5431130
7 files changed
+933
-13
No files matched your search
@@ -2421,6 +2421,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
McpServer().SetRemoteControlEnabled(THIS_CFG.GetInt("settings", "McpRemoteControl", 0) != 0);
|
||||
// 文件传输开关:默认关;仅 download_file 门控(不要求只读关)。
|
||||
McpServer().SetFileTransferEnabled(THIS_CFG.GetInt("settings", "McpFileTransfer", 0) != 0);
|
||||
// P10-B 文件写入开关:默认关;delete_path / move_path / create_folder 需要它且只读关。
|
||||
McpServer().SetFileWriteEnabled(THIS_CFG.GetInt("settings", "McpFileWrite", 0) != 0);
|
||||
// P7 管理控制开关:默认关;要求只读关(McpReadonly=0)才生效(工具列表/分派双重门控)。
|
||||
McpServer().SetManageEnabled(THIS_CFG.GetInt("settings", "McpManage", 0) != 0);
|
||||
// P8 主机管理 / 连接管理工具族:总开关默认关(关闭时 16 个工具都不可见)。
|
||||
@@ -7029,6 +7031,19 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
case TOKEN_DELETE_FINISH: // 文件写操作完成回包【P10-B】
|
||||
case TOKEN_RENAME_FINISH:
|
||||
case TOKEN_CREATEFOLDER_FINISH: {
|
||||
// 客户端对四个写命令都是「做完就无条件回包」,这些 token 正常只在 FileManagerDlg
|
||||
// 的 hDlg 路径里消费;MCP 的文件管理器子连接 hDlg 为 NULL,包会落在这里。
|
||||
// KeepSub = 已转入复核、在同一子连接上补发了 COMMAND_LIST_FILES,留给 TOKEN_FILE_LIST
|
||||
// 分支投递数据并 CancelIO;其余(与本请求无关的迟到包 / 复核下发失败)关掉子连接。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
if (McpServer().TakeFileOpFinish(devId, ContextObject, szBuffer, len)
|
||||
!= CMcpServer::FileOpAck::KeepSub)
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
case TOKEN_DOWNLOAD_ERROR: { // download_file 无可用文件(新客户端)【MCP 结构化失败】
|
||||
// 客户端在「传输子链接还没建立」时就在文件管理器子连接上回报,故此处不 CancelIO:
|
||||
// 该子链接由 ClearFileTransfer 统一收尾(避免与 tool 线程的 CancelIO 竞争)。
|
||||
|
||||
@@ -395,6 +395,10 @@ const ToolHints kToolHints[] = {
|
||||
{ "list_registry", true, false, true, true },
|
||||
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
|
||||
{ "search_file", true, false, true, true },
|
||||
// --- 文件系统写操作(McpFileWrite)---
|
||||
{ "delete_path", false, true, false, true },
|
||||
{ "move_path", false, true, false, true },
|
||||
{ "create_folder", false, false, true, true }, // 已存在时同样成功
|
||||
{ "list_network_connections", true, false, true, true },
|
||||
{ "host_list_processes", true, false, true, true },
|
||||
{ "host_list_windows", true, false, true, true },
|
||||
|
||||
@@ -56,7 +56,7 @@ const char* kServerInstructions =
|
||||
u8"\n"
|
||||
u8"2) 工具的可见性与开关\n"
|
||||
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
|
||||
u8"文件传输(file_transfer)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
|
||||
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
|
||||
u8"远程交谈(chat)各有独立开关。工具不在列表里就是不可用,直接调用返回 -32006;"
|
||||
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
|
||||
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;"
|
||||
@@ -84,6 +84,9 @@ const char* kServerInstructions =
|
||||
u8"主机可能在你操作期间掉线。\n"
|
||||
u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条,"
|
||||
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ download_file 取回、upload_file 送到目标。"
|
||||
u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关),"
|
||||
u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、"
|
||||
u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。"
|
||||
u8"列表结果按 limit/offset 分页,total 是命中数、totalAll 是过滤前的总数。\n"
|
||||
u8"进程排查:host_list_processes 或 list_processes 定位,kill_process 结束。这类动作没有真实回执,"
|
||||
u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n"
|
||||
@@ -1505,6 +1508,17 @@ Json::Value BuildSearchFileInputSchema();
|
||||
Json::Value BuildSearchFileOutputSchema();
|
||||
std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
|
||||
// ===== P10-B 前置声明(文件系统写操作,定义见「tools/call 分派」前)=====
|
||||
Json::Value BuildDeletePathInputSchema();
|
||||
Json::Value BuildDeletePathOutputSchema();
|
||||
Json::Value BuildMovePathInputSchema();
|
||||
Json::Value BuildMovePathOutputSchema();
|
||||
Json::Value BuildCreateFolderInputSchema();
|
||||
Json::Value BuildCreateFolderOutputSchema();
|
||||
std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
|
||||
// tools/list
|
||||
std::string BuildToolsListResult(const Json::Value& id) {
|
||||
Json::Value result(Json::objectValue);
|
||||
@@ -1970,6 +1984,36 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
tools.append(tool);
|
||||
}
|
||||
|
||||
// 18d) 文件系统写操作(P10-B:delete_path / move_path / create_folder)。
|
||||
// 独立开关 McpFileWrite(默认关)且要求 McpReadonly=0:上传是「覆盖」,删除是
|
||||
// 「毁灭」,风险等级不同,必须能分别关掉。关闭时不追加任何工具。
|
||||
if (CMcpServer::Instance().IsFileWriteEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "delete_path";
|
||||
tool["description"] = u8"删除指定主机(仅 Windows)上的文件或目录。recursive=false(默认)删除单个文件;recursive=true 递归删除整个目录及其全部内容——没有回收站,不可恢复。path 必须是绝对路径(C:\\... 或 \\\\server\\share\\...),不接受相对路径,也不接受含 %VAR% 环境变量的路径(客户端会展开,服务端无法校验真实目标)。服务端一律拒绝盘符/共享根,以及系统目录(Windows、Program Files、Program Files (x86)、ProgramData、$Recycle.Bin、System Volume Information)及其子树——需要清理这些位置请改用 exec_command 或逐项确认。客户端对删除命令无条件回完成包(根本不看 DeleteFile 的返回值),所以 ok 只代表命令已送达;真正的结果看 verified:true=复核确认目标已不在,false=复核确认目标还在(只读文件会静默失败,被占用/权限不足同理),null=复核没做成(列目录超时或断线),此时请自己用 list_files 再确认。注意目标本来就不存在时客户端同样回完成包、复核也只能看到「现在没有这个名字」,所以会表现为 verified=true——动手前最好先 list_files 确认目标确实存在。";
|
||||
tool["inputSchema"] = BuildDeletePathInputSchema();
|
||||
tool["outputSchema"] = BuildDeletePathOutputSchema();
|
||||
tools.append(tool);
|
||||
}
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "move_path";
|
||||
tool["description"] = u8"重命名或移动指定主机(仅 Windows)上的文件或目录:把 from 改成 to,to 必须是完整的新路径(含新名字)。客户端用 ::MoveFile,只能在同一卷内移动;跨盘请改用 download_file + upload_file。目录也支持(同一卷内整体移动)。from 不能是盘符/共享根或系统目录(Windows、Program Files、ProgramData 等),to 只拒绝根路径;from 与 to 都必须是不含 %VAR% 的绝对路径。ok 只代表命令已送达(客户端无条件回完成包),verified=true 表示复核确认 to 已出现在父目录里,false 表示没出现(目标已存在、跨卷、只读或被占用),null 表示复核没做成。";
|
||||
tool["inputSchema"] = BuildMovePathInputSchema();
|
||||
tool["outputSchema"] = BuildMovePathOutputSchema();
|
||||
tools.append(tool);
|
||||
}
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "create_folder";
|
||||
tool["description"] = u8"在指定主机(仅 Windows)上创建目录。客户端用 MakeSureDirectoryPathExists,会连同缺失的中间层一起建(C:\\a\\b\\c 会把 a、b 也建出来),目录已存在时同样算成功。path 若误带上了文件名,就会建出一个同名目录——本工具不会创建文件,也不会覆盖同名文件(那种情况 verified=false)。path 必须是绝对路径,不能含 %VAR%,不能是盘符/共享根。ok 只代表命令已送达,verified=true 表示复核确认该目录已存在且确实是目录,false 表示复核时没看到它(权限不足、被同名文件占用等),null 表示复核没做成。";
|
||||
tool["inputSchema"] = BuildCreateFolderInputSchema();
|
||||
tool["outputSchema"] = BuildCreateFolderOutputSchema();
|
||||
tools.append(tool);
|
||||
}
|
||||
}
|
||||
|
||||
// 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection /
|
||||
// host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine /
|
||||
// McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。
|
||||
@@ -3309,6 +3353,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
||||
switches["terminal"] = srv.IsTerminalEnabled();
|
||||
switches["remote_control"] = srv.IsRemoteControlEnabled();
|
||||
switches["file_transfer"] = srv.IsFileTransferEnabled();
|
||||
switches["file_write"] = srv.IsFileWriteEnabled();
|
||||
switches["manage"] = srv.IsManageEnabled();
|
||||
switches["machine"] = srv.IsMachineEnabled();
|
||||
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
|
||||
@@ -6759,6 +6804,593 @@ std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
|
||||
//
|
||||
// 链路:
|
||||
// 主连接 COMMAND_LIST_DRIVE → 子连接首包 TOKEN_DRIVE_LIST(OnDriveList 转下发写命令)
|
||||
// → 子连接回 TOKEN_DELETE_FINISH / TOKEN_RENAME_FINISH / TOKEN_CREATEFOLDER_FINISH
|
||||
// (TakeFileOpFinish 转入复核:在同一子连接上补发 COMMAND_LIST_FILES 列父目录)
|
||||
// → TOKEN_FILE_LIST(MessageHandle 现有分支投递数据并 CancelIO 收尾)
|
||||
//
|
||||
// 为什么必须复核:客户端四个写命令都是「做完就无条件 SendToken」,DeleteFile / MoveFile /
|
||||
// MakeSureDirectoryPathExists 的返回值一概不看(也没有错误包)。所以完成包只证明「命令到了」,
|
||||
// 不证明「做成了」。复核复用同一条已开的子连接再列一次父目录,代价只有一次往返。
|
||||
//
|
||||
// 编码:路径按客户端 ANSI(GBK) 上线(CFileManager 走 A 接口),UTF-8 → GBK 严格转换,
|
||||
// 转不了直接 -32602(同 search_file),不做「转不了就传原样」的猜测。
|
||||
namespace {
|
||||
|
||||
// 客户端用 char[MAX_PATH] 缓冲拼路径(ExpandPath / wsprintf "%s\\*.*"),
|
||||
// 与 search_file 同一约束:单条路径限 200 字节 GBK,给「父目录 + 反斜杠 + 文件名」留余量。
|
||||
const size_t kFileOpMaxPathBytes = 200;
|
||||
|
||||
bool IsFileWriteToolName(const std::string& tool) {
|
||||
return tool == "delete_path" || tool == "move_path" || tool == "create_folder";
|
||||
}
|
||||
|
||||
inline bool IsAsciiLetter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
|
||||
|
||||
// 规范化 UTF-8 路径:去掉 \\?\ 前缀、分隔符统一 '\'、折叠 . 与 ..、去掉尾部分隔符。
|
||||
// 只接受绝对路径(盘符 / UNC / 卷根相对):相对路径由目标机的当前目录解析,服务端既没法
|
||||
// 校验保护目录,也就算不出复核用的父目录。折叠 .. 是为了保护判定不被人为的 "C:\x\..\Windows" 绕过。
|
||||
bool NormalizePathUtf8(const std::string& raw, std::string& out) {
|
||||
std::string in = raw;
|
||||
if (in.rfind("\\\\?\\", 0) == 0 || in.rfind("\\\\.\\", 0) == 0) in = in.substr(4);
|
||||
for (char& c : in) if (c == '/') c = '\\';
|
||||
|
||||
// 前缀:盘符 "X:"、UNC 的 "\\server\share",或卷根相对("\Windows\..." → 前缀为空)
|
||||
std::string prefix;
|
||||
size_t i = 0;
|
||||
if (in.size() >= 2 && IsAsciiLetter(in[0]) && in[1] == ':') {
|
||||
prefix = in.substr(0, 2);
|
||||
i = 2;
|
||||
} else if (in.rfind("\\\\", 0) == 0) {
|
||||
const size_t a = in.find('\\', 2);
|
||||
if (a == std::string::npos) return false; // "\\" 或 "\\server"
|
||||
const size_t b = in.find('\\', a + 1);
|
||||
prefix = (b == std::string::npos) ? in : in.substr(0, b);
|
||||
i = prefix.size();
|
||||
} else if (!in.empty() && in[0] == '\\') {
|
||||
i = 1;
|
||||
} else {
|
||||
return false; // 相对路径
|
||||
}
|
||||
|
||||
std::vector<std::string> segs;
|
||||
while (i <= in.size()) {
|
||||
size_t j = in.find('\\', i);
|
||||
if (j == std::string::npos) j = in.size();
|
||||
const std::string seg = in.substr(i, j - i);
|
||||
if (!seg.empty() && seg != ".") {
|
||||
if (seg == "..") {
|
||||
if (segs.empty()) return false; // 试图越过根
|
||||
segs.pop_back();
|
||||
} else {
|
||||
segs.push_back(seg);
|
||||
}
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
|
||||
out = prefix;
|
||||
for (const std::string& s : segs) {
|
||||
out += '\\';
|
||||
out += s;
|
||||
}
|
||||
return !out.empty();
|
||||
}
|
||||
|
||||
// 盘符根 / 卷根 / 共享根(C:、\、\\server\share):任何写操作都不能拿它当目标。
|
||||
bool IsPathRoot(const std::string& p) {
|
||||
if (p.size() == 2 && IsAsciiLetter(p[0]) && p[1] == ':') return true;
|
||||
if (p.empty() || p.find_first_not_of('\\') == std::string::npos) return true;
|
||||
if (p.rfind("\\\\", 0) == 0) {
|
||||
const size_t a = p.find('\\', 2);
|
||||
if (a == std::string::npos) return true; // \\server
|
||||
return p.find('\\', a + 1) == std::string::npos; // \\server\share
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string UpperAscii(std::string s) {
|
||||
for (char& c : s) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A');
|
||||
return s;
|
||||
}
|
||||
|
||||
// 系统目录保护。删除/改名是「毁灭」,不允许落在这些位置;建目录不受限(安装前建目录是正经用法)。
|
||||
// 按整段比较:C:\Windows.old 不算 C:\Windows,C:\Program Files (x86) 单独一条。
|
||||
// 带子树的是「整棵都不能动」;kProtectedExact 只挡目录本身(C:\Users\bob\... 仍是合法目标)。
|
||||
const char* const kProtectedTree[] = {
|
||||
"\\WINDOWS", "\\PROGRAM FILES", "\\PROGRAM FILES (X86)", "\\PROGRAMDATA",
|
||||
"\\SYSTEM VOLUME INFORMATION", "\\$RECYCLE.BIN",
|
||||
};
|
||||
const char* const kProtectedExact[] = { "\\USERS", "\\PERFLOGS", "\\RECOVERY" };
|
||||
|
||||
// 入参必须是 NormalizePathUtf8 的结果。
|
||||
bool IsProtectedSystemPath(const std::string& normalized) {
|
||||
const std::string up = UpperAscii(normalized);
|
||||
size_t i = 0;
|
||||
if (up.size() >= 2 && IsAsciiLetter(up[0]) && up[1] == ':') {
|
||||
i = 2;
|
||||
} else if (up.rfind("\\\\", 0) == 0) {
|
||||
const size_t a = up.find('\\', 2);
|
||||
if (a == std::string::npos) return true; // 只有服务器名
|
||||
const size_t b = up.find('\\', a + 1);
|
||||
if (b == std::string::npos) return true; // 共享根本身
|
||||
i = b;
|
||||
}
|
||||
const std::string rel = up.substr(i);
|
||||
for (const char* p : kProtectedTree) {
|
||||
const std::string tree = p;
|
||||
if (rel == tree || rel.rfind(tree + "\\", 0) == 0) return true;
|
||||
}
|
||||
for (const char* p : kProtectedExact) {
|
||||
if (rel == std::string(p)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 校验一条写操作目标路径,产出上线用的 GBK 字节、复核用的父目录与末段名字。
|
||||
// protectSystemDirs=true:目标本身落在系统目录内就拒绝(删除、改名的来源);
|
||||
// false:只拒绝根路径(改名的去向、建目录——写到 Program Files 与 upload_file 同权限,不额外收紧)。
|
||||
bool PrepareFileOpPath(const std::string& raw, bool protectSystemDirs, bool needParent,
|
||||
const std::string& tool, std::string& normalized,
|
||||
std::string& ansi, std::string& parentAnsi, std::string& leafUtf8,
|
||||
std::string& err) {
|
||||
const std::string trimmed = Trim(raw);
|
||||
if (trimmed.empty()) {
|
||||
err = tool + ": missing or empty path";
|
||||
return false;
|
||||
}
|
||||
// 客户端会对路径做 ExpandEnvironmentStrings:%SystemRoot%\System32 之类的写法在服务端
|
||||
// 看起来不在保护目录里,到目标机却会展开过去。服务端无从预知目标机环境,一律拒绝。
|
||||
if (trimmed.find('%') != std::string::npos) {
|
||||
err = tool + ": path must not contain environment variables (%VAR%): the client expands "
|
||||
"them and the server cannot validate the real target. Resolve the variable first";
|
||||
return false;
|
||||
}
|
||||
if (!NormalizePathUtf8(trimmed, normalized)) {
|
||||
err = tool + ": invalid path (expected an absolute path such as C:\\\\Temp\\\\work): " + trimmed;
|
||||
return false;
|
||||
}
|
||||
if (IsPathRoot(normalized)) {
|
||||
err = tool + ": refusing to operate on a drive root or share root: " + normalized;
|
||||
return false;
|
||||
}
|
||||
if (protectSystemDirs && IsProtectedSystemPath(normalized)) {
|
||||
err = tool + ": refusing to modify a protected system location: " + normalized +
|
||||
" (Windows, Program Files, ProgramData, $Recycle.Bin and their subtrees are off "
|
||||
"limits; use exec_command if you really need to touch them)";
|
||||
return false;
|
||||
}
|
||||
if (!Utf8ToCpExact(normalized, 936, ansi)) {
|
||||
err = tool + ": path cannot be encoded in the client's ANSI code page (GBK): " + normalized;
|
||||
return false;
|
||||
}
|
||||
if (ansi.size() > kFileOpMaxPathBytes) {
|
||||
err = tool + ": path too long (max " + std::to_string(kFileOpMaxPathBytes) +
|
||||
" bytes in GBK): " + normalized;
|
||||
return false;
|
||||
}
|
||||
if (!needParent) return true;
|
||||
|
||||
const size_t slash = normalized.find_last_of('\\');
|
||||
if (slash == std::string::npos) {
|
||||
err = tool + ": cannot derive a parent directory from " + normalized;
|
||||
return false;
|
||||
}
|
||||
leafUtf8 = normalized.substr(slash + 1);
|
||||
// 父目录一定比整条路径短,前面已确认整条能转 GBK;这里再转一次是因为要单独上线。
|
||||
if (leafUtf8.empty() || !Utf8ToCpExact(normalized.substr(0, slash), 936, parentAnsi)) {
|
||||
err = tool + ": cannot derive a parent directory from " + normalized;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 复核结果:在 TOKEN_FILE_LIST 里找末段名字。
|
||||
enum class ListingLookup { Unknown, Present, Absent };
|
||||
|
||||
ListingLookup LookupInListing(const std::vector<BYTE>& data, const std::string& leafUtf8, bool& isDir) {
|
||||
isDir = false;
|
||||
if (data.empty()) return ListingLookup::Unknown;
|
||||
if (data[0] == TOKEN_FILE_LIST_ERROR) {
|
||||
// 新客户端的结构化失败:[token][win32err:4]。只有「不存在」能当否定结论;
|
||||
// 拒绝访问说明复核本身没做成,不能据此判定操作失败。
|
||||
const DWORD e = ReadWin32Payload(data);
|
||||
if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return ListingLookup::Absent;
|
||||
return ListingLookup::Unknown;
|
||||
}
|
||||
if (data[0] != TOKEN_FILE_LIST) return ListingLookup::Unknown;
|
||||
// 不在服务端截断:默认那 500 条是给界面用的窗口,这里要扫全(大小仍由客户端单包上限约束)。
|
||||
const Json::Value items = ParseFileList(data, 1000000, 936);
|
||||
for (unsigned int i = 0; i < items.size(); ++i) {
|
||||
const std::string name = JsonStrField(items[i], "name");
|
||||
if (EqualsPathNoCase(name, leafUtf8)) {
|
||||
isDir = items[i]["isDir"].asBool();
|
||||
return ListingLookup::Present;
|
||||
}
|
||||
}
|
||||
return ListingLookup::Absent;
|
||||
}
|
||||
|
||||
// want:0=期望目标不存在(删除);1=期望存在(改名目标);2=期望存在且是目录(建目录)。
|
||||
// 返回 1=确认生效,0=确认未生效,-1=无法确认(不谎报 false)。
|
||||
int ResolveFileOpVerified(ListingLookup lk, bool isDir, int want) {
|
||||
if (lk == ListingLookup::Unknown) return -1;
|
||||
if (lk == ListingLookup::Absent) return want == 0 ? 1 : 0;
|
||||
if (want == 0) return 0; // 还在
|
||||
if (want == 2) return isDir ? 1 : 0; // 同名文件挡着,目录没建成
|
||||
return 1;
|
||||
}
|
||||
|
||||
struct FileOpWait {
|
||||
bool acked = false; // 收到客户端完成包(命令已送达)
|
||||
bool dataIsListing = false; // 最终拿到的是复核列表(false = 完成包本身)
|
||||
std::vector<BYTE> data;
|
||||
};
|
||||
|
||||
// 等两阶段收尾。返回 false = 连完成包都没等到(超时/断线),调用方按 -32001 处理。
|
||||
// phase 1 超时是特例:命令已送到客户端、只是复核没回来——结果未知,不算失败。
|
||||
bool WaitFileOp(CMcpServer& mcp, uint64_t devId, FileOpWait& out) {
|
||||
int phase = 0;
|
||||
if (!mcp.WaitPendingWrite(devId, out.data, mcp.ToolTimeoutMs(), &phase)) {
|
||||
out.acked = (phase == 1);
|
||||
out.dataIsListing = false;
|
||||
return out.acked;
|
||||
}
|
||||
out.acked = true;
|
||||
out.dataIsListing = (phase == 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 门控 + 平台检查。返回空串 = 放行;否则是完整的错误响应。
|
||||
std::string GateFileWriteTool(const Json::Value& id, const std::string& tool, const Json::Value& args,
|
||||
CMy2015RemoteDlg* parent, uint64_t& devId, context*& ctx) {
|
||||
std::string err;
|
||||
if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err);
|
||||
ctx = FindMainContext(parent, devId);
|
||||
if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
// 这几个命令只在 Windows 客户端的 CFileManager 里实现(GBK + A 接口);LNX/MAC 的
|
||||
// FileManager.h 虽然也有同名分支,但收包按 GBK→UTF-8 解,和 list_files 的 UTF-8 口径
|
||||
// 不一致,非 ASCII 路径会互相打脸,暂不开放。
|
||||
const CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
|
||||
return BuildError(id, -32005, tool + " is only supported on Windows hosts");
|
||||
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (mcp.IsReadonly())
|
||||
return BuildError(id, -32006, tool + " is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
|
||||
if (!mcp.IsFileWriteEnabled())
|
||||
return BuildError(id, -32006, tool + " is disabled: file writes are off (set McpFileWrite=1 to enable)");
|
||||
return std::string();
|
||||
}
|
||||
|
||||
// 开子连接 + 两阶段等待。返回空串 = 结果在 out 里;否则是完整的错误响应。
|
||||
std::string RunFileOp(const Json::Value& id, const std::string& tool, context* ctx, uint64_t devId,
|
||||
const std::vector<BYTE>& followUp, const std::string& verifyPathAnsi,
|
||||
FileOpWait& out) {
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (!mcp.BeginPendingFileOp(devId, tool, followUp, verifyPathAnsi))
|
||||
return BuildError(id, -32003, "Device busy: another request is pending for this host");
|
||||
|
||||
BYTE cmd = COMMAND_LIST_DRIVE;
|
||||
if (!ctx->Send2Client(&cmd, 1)) {
|
||||
mcp.ClearPending(devId);
|
||||
return BuildError(id, -32004, "Failed to send command to host");
|
||||
}
|
||||
if (!WaitFileOp(mcp, devId, out))
|
||||
return BuildError(id, -32001,
|
||||
"Timeout waiting for the client to acknowledge " + tool +
|
||||
" (the command may still be executed later; re-check with list_files)");
|
||||
return std::string();
|
||||
}
|
||||
|
||||
// 统一输出:{..., ok, verified:true|false|null} + 一句可读摘要。
|
||||
// 复核通过时的文案必须只描述「复核看到的状态」,不能写成「已完成删除」:客户端对不存在的
|
||||
// 目标也会回完成包,而复核只能看到「现在没有这个名字」,两者无法区分(见 delete_path 描述)。
|
||||
std::string BuildFileOpResult(const Json::Value& id, Json::Value structured,
|
||||
const std::string& confirmedText,
|
||||
const std::string& failedHint, const FileOpWait& w, int verified) {
|
||||
structured["ok"] = w.acked;
|
||||
if (verified == 1) structured["verified"] = true;
|
||||
else if (verified == 0) structured["verified"] = false;
|
||||
else structured["verified"] = Json::Value(Json::nullValue);
|
||||
|
||||
std::string text;
|
||||
if (verified == 1) {
|
||||
text = std::string(u8"复核通过:") + confirmedText;
|
||||
} else if (verified == 0) {
|
||||
text = std::string(u8"命令已送达客户端,但复核显示未生效:") + failedHint;
|
||||
} else {
|
||||
text = std::string(u8"命令已送达客户端(已收到完成包),但复核没能完成"
|
||||
u8"(列目录超时或断线),结果未知;请用 list_files 再确认一次。");
|
||||
}
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
result["structuredContent"] = structured;
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
// verified=false 是「确认没成」→ 调用失败;null 只是「不知道」,不判失败。
|
||||
result["isError"] = (verified == 0);
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
// 三个写工具共享的路径字段 schema
|
||||
void AppendFileOpResultProps(Json::Value& props) {
|
||||
Json::Value okProp(Json::objectValue);
|
||||
okProp["type"] = "boolean";
|
||||
okProp["description"] = u8"命令已送达客户端并收到完成回包。客户端的完成包是无条件回包,不代表操作成功。";
|
||||
props["ok"] = okProp;
|
||||
Json::Value verProp(Json::objectValue);
|
||||
// 三态:true / false / null。声明成 ["boolean","null"],别让严格校验的客户端
|
||||
// 把「复核没做成」误判成 schema 违规。
|
||||
Json::Value verType(Json::arrayValue);
|
||||
verType.append("boolean");
|
||||
verType.append("null");
|
||||
verProp["type"] = verType;
|
||||
verProp["description"] = u8"复核结果:true=确认已生效,false=确认未生效,null=复核没做成(结果未知)。";
|
||||
props["verified"] = verProp;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Json::Value BuildDeletePathInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value idProp(Json::objectValue);
|
||||
idProp["type"] = "string";
|
||||
idProp["description"] = u8"主机 id(Windows 客户端)。";
|
||||
props["id"] = idProp;
|
||||
Json::Value pathProp(Json::objectValue);
|
||||
pathProp["type"] = "string";
|
||||
pathProp["description"] = u8"要删除的绝对路径(文件或目录),例如 C:\\Temp\\old.log;不能含 %VAR%,不能是盘符根。";
|
||||
props["path"] = pathProp;
|
||||
Json::Value recProp(Json::objectValue);
|
||||
recProp["type"] = "boolean";
|
||||
recProp["description"] = u8"true=按目录递归删除(COMMAND_DELETE_DIRECTORY,连同子目录内容一起删);默认 false=按单个文件删除。目标其实是目录却传 false 时,客户端 DeleteFile 会失败(复核会返回 verified=false)。";
|
||||
props["recursive"] = recProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
required.append("path");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildDeletePathOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
AppendFileOpResultProps(props);
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildMovePathInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value idProp(Json::objectValue);
|
||||
idProp["type"] = "string";
|
||||
idProp["description"] = u8"主机 id(Windows 客户端)。";
|
||||
props["id"] = idProp;
|
||||
Json::Value fromProp(Json::objectValue);
|
||||
fromProp["type"] = "string";
|
||||
fromProp["description"] = u8"原来的绝对路径(文件或目录),例如 C:\\Temp\\a.txt。";
|
||||
props["from"] = fromProp;
|
||||
Json::Value toProp(Json::objectValue);
|
||||
toProp["type"] = "string";
|
||||
toProp["description"] = u8"新的完整路径(含新名字),例如 C:\\Temp\\b.txt;必须在同一卷内。";
|
||||
props["to"] = toProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
required.append("from");
|
||||
required.append("to");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildMovePathOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
AppendFileOpResultProps(props);
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildCreateFolderInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value idProp(Json::objectValue);
|
||||
idProp["type"] = "string";
|
||||
idProp["description"] = u8"主机 id(Windows 客户端)。";
|
||||
props["id"] = idProp;
|
||||
Json::Value pathProp(Json::objectValue);
|
||||
pathProp["type"] = "string";
|
||||
pathProp["description"] = u8"要创建的目录绝对路径,例如 C:\\Temp\\report\\2026;缺失的中间层会一并创建。";
|
||||
props["path"] = pathProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
required.append("path");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildCreateFolderOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
AppendFileOpResultProps(props);
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
return schema;
|
||||
}
|
||||
|
||||
std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
const std::string tool = "delete_path";
|
||||
uint64_t devId = 0;
|
||||
context* ctx = nullptr;
|
||||
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
const bool recursive = args.isMember("recursive") && args["recursive"].isBool() &&
|
||||
args["recursive"].asBool();
|
||||
|
||||
std::string normalized, ansi, parentAnsi, leafUtf8;
|
||||
if (!PrepareFileOpPath(GetStringArg(args, "path"), true, true, tool,
|
||||
normalized, ansi, parentAnsi, leafUtf8, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
// 递归删除走 COMMAND_DELETE_DIRECTORY(客户端 DeleteDirectory 会先清子项再删目录)。
|
||||
// path 后必须补 '\0':客户端按 C 串取路径。
|
||||
std::vector<BYTE> followUp;
|
||||
followUp.reserve(2 + ansi.size());
|
||||
followUp.push_back(recursive ? (BYTE)COMMAND_DELETE_DIRECTORY : (BYTE)COMMAND_DELETE_FILE);
|
||||
followUp.insert(followUp.end(), ansi.begin(), ansi.end());
|
||||
followUp.push_back(0);
|
||||
|
||||
FileOpWait w;
|
||||
err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
AuditManageAction(parent, devId, tool,
|
||||
std::string("path=") + normalized + (recursive ? " recursive=1" : " recursive=0"));
|
||||
int verified = -1;
|
||||
if (w.dataIsListing) {
|
||||
bool isDir = false;
|
||||
// isDir 是 LookupInListing 的出参,必须先单独调用:写成
|
||||
// ResolveFileOpVerified(LookupInListing(..., isDir), isDir, ...) 会读到未赋值的 false
|
||||
// (实参求值顺序未指定,MSVC 从右往左先算 isDir)。
|
||||
const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir);
|
||||
verified = ResolveFileOpVerified(lk, isDir, 0);
|
||||
}
|
||||
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["id"] = std::to_string(devId);
|
||||
sc["path"] = normalized;
|
||||
sc["recursive"] = recursive;
|
||||
return BuildFileOpResult(id, sc,
|
||||
u8"\"" + normalized + u8"\" 已不在父目录列表里"
|
||||
u8"(目标本来就不存在时也是这个结果——客户端不回错误包)。",
|
||||
u8"目标仍在(只读文件、被占用或权限不足都会静默失败;"
|
||||
u8"也可能是 recursive=false 落在了目录上:" + normalized + u8")。",
|
||||
w, verified);
|
||||
}
|
||||
|
||||
std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
const std::string tool = "move_path";
|
||||
uint64_t devId = 0;
|
||||
context* ctx = nullptr;
|
||||
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
// 来源按「会被拿走」对待,受系统目录保护;去向只拒绝根路径(写入 Program Files 的权限
|
||||
// 与 upload_file 相同,不额外收紧)。
|
||||
std::string fromNorm, fromAnsi, ignored1, ignored2;
|
||||
if (!PrepareFileOpPath(GetStringArg(args, "from"), true, false, tool,
|
||||
fromNorm, fromAnsi, ignored1, ignored2, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
std::string toNorm, toAnsi, toParentAnsi, toLeafUtf8;
|
||||
if (!PrepareFileOpPath(GetStringArg(args, "to"), false, true, tool,
|
||||
toNorm, toAnsi, toParentAnsi, toLeafUtf8, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
if (EqualsPathNoCase(fromNorm, toNorm))
|
||||
return BuildError(id, -32602, "move_path: from and to are the same path: " + fromNorm);
|
||||
|
||||
// 请求体 = [from\0][to\0](首字节是命令)。客户端用 ::MoveFile,同卷内文件与目录都能搬。
|
||||
std::vector<BYTE> followUp;
|
||||
followUp.reserve(3 + fromAnsi.size() + toAnsi.size());
|
||||
followUp.push_back((BYTE)COMMAND_RENAME_FILE);
|
||||
followUp.insert(followUp.end(), fromAnsi.begin(), fromAnsi.end());
|
||||
followUp.push_back(0);
|
||||
followUp.insert(followUp.end(), toAnsi.begin(), toAnsi.end());
|
||||
followUp.push_back(0);
|
||||
|
||||
FileOpWait w;
|
||||
err = RunFileOp(id, tool, ctx, devId, followUp, toParentAnsi, w);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
AuditManageAction(parent, devId, tool, "from=" + fromNorm + " to=" + toNorm);
|
||||
int verified = -1;
|
||||
if (w.dataIsListing) {
|
||||
bool isDir = false;
|
||||
// 同 delete_path:先调用再取值,别把出参和调用写进同一句实参表。
|
||||
const ListingLookup lk = LookupInListing(w.data, toLeafUtf8, isDir);
|
||||
verified = ResolveFileOpVerified(lk, isDir, 1);
|
||||
}
|
||||
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["id"] = std::to_string(devId);
|
||||
sc["from"] = fromNorm;
|
||||
sc["to"] = toNorm;
|
||||
return BuildFileOpResult(id, sc,
|
||||
u8"\"" + toNorm + u8"\" 已出现在父目录列表里(原路径 \""
|
||||
+ fromNorm + u8"\" 是否已消失不在复核范围内)。",
|
||||
u8"新名字没有出现在目标目录里(目标已存在、跨卷、只读或被占用都会"
|
||||
u8"让 ::MoveFile 静默失败):\"" + toNorm + u8"\"。",
|
||||
w, verified);
|
||||
}
|
||||
|
||||
std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
const std::string tool = "create_folder";
|
||||
uint64_t devId = 0;
|
||||
context* ctx = nullptr;
|
||||
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
std::string normalized, ansi, parentAnsi, leafUtf8;
|
||||
if (!PrepareFileOpPath(GetStringArg(args, "path"), false, true, tool,
|
||||
normalized, ansi, parentAnsi, leafUtf8, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
// 结尾必须补一个 '\\':客户端 CFileManager::CreateFolder 直接把这段字节丢给
|
||||
// MakeSureDirectoryPathExists,而它是「路径里每个以反斜杠结尾的片段都要存在」的语义
|
||||
// ——不带尾部反斜杠时最后一级被当成文件名,压根不会被创建(MFC 的 OnRemoteNewfolder
|
||||
// 也是拼 m_Remote_Path + name + "\\")。delete 恰好相反:RemoveDirectory 不接受尾部
|
||||
// 反斜杠,所以那边保持去掉分隔符的写法。
|
||||
std::vector<BYTE> followUp;
|
||||
followUp.reserve(3 + ansi.size());
|
||||
followUp.push_back((BYTE)COMMAND_CREATE_FOLDER);
|
||||
followUp.insert(followUp.end(), ansi.begin(), ansi.end());
|
||||
followUp.push_back('\\');
|
||||
followUp.push_back(0);
|
||||
|
||||
FileOpWait w;
|
||||
err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w);
|
||||
if (!err.empty()) return err;
|
||||
|
||||
AuditManageAction(parent, devId, tool, "path=" + normalized);
|
||||
int verified = -1;
|
||||
if (w.dataIsListing) {
|
||||
bool isDir = false;
|
||||
// 这一处最要命:want=2 会读 isDir,写成一行时 isDir 永远是初始的 false,
|
||||
// 于是「建目录」永远自评「未生效」(同 delete_path 的注释)。
|
||||
const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir);
|
||||
verified = ResolveFileOpVerified(lk, isDir, 2);
|
||||
}
|
||||
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["id"] = std::to_string(devId);
|
||||
sc["path"] = normalized;
|
||||
return BuildFileOpResult(id, sc,
|
||||
u8"\"" + normalized + u8"\" 已存在且确实是目录。",
|
||||
u8"复核时没看到这个目录,或同名条目是文件而不是目录(权限不足、"
|
||||
u8"路径被占用等都会静默失败):\"" + normalized + u8"\"。",
|
||||
w, verified);
|
||||
}
|
||||
|
||||
// ===== B1:主机库元数据 schema =====
|
||||
Json::Value BuildHostSetRemarkInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -7064,6 +7696,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent);
|
||||
if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent);
|
||||
if (toolName == "search_file") return BuildSearchFile(id, args, parent);
|
||||
if (toolName == "delete_path") return BuildDeletePath(id, args, parent);
|
||||
if (toolName == "move_path") return BuildMovePath(id, args, parent);
|
||||
if (toolName == "create_folder") return BuildCreateFolder(id, args, parent);
|
||||
|
||||
return BuildError(id, -32602,
|
||||
"Unknown tool: " + (toolName.empty() ? std::string("(empty)") : toolName));
|
||||
@@ -7942,6 +8577,65 @@ bool CMcpServer::BeginPending(uint64_t device_id, const std::string& tool) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CMcpServer::BeginPendingFileOp(uint64_t device_id, const std::string& tool,
|
||||
const std::vector<BYTE>& followUp,
|
||||
const std::string& verifyPath) {
|
||||
if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2)
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
|
||||
PendingRequest r;
|
||||
r.tool = tool;
|
||||
r.kind = PendingKind::FollowUp; // IsPending 认这个 kind,TOKEN_DRIVE_LIST 才会交给 OnDriveList
|
||||
r.followUp = followUp;
|
||||
r.verifyPath = verifyPath;
|
||||
m_Pending[device_id] = std::move(r);
|
||||
return true;
|
||||
}
|
||||
|
||||
CMcpServer::FileOpAck CMcpServer::TakeFileOpFinish(uint64_t device_id, context* subCtx,
|
||||
const BYTE* data, ULONG len) {
|
||||
std::vector<BYTE> listCmd;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end()) return FileOpAck::NotMine; // 已超时清理 → 迟到包
|
||||
if (!IsFileWriteToolName(it->second.tool)) return FileOpAck::NotMine; // 别的写工具不会发这些 token
|
||||
if (it->second.phase == 0 && !it->second.verifyPath.empty()) {
|
||||
// phase 0 → 1:完成包不代表成功,先在同一子连接上补一次列目录复核。
|
||||
// 不投递完成包、也不置 done:工具线程继续在同一超时窗口内等复核结果。
|
||||
it->second.phase = 1;
|
||||
it->second.data.clear();
|
||||
it->second.done = false;
|
||||
listCmd.push_back((BYTE)COMMAND_LIST_FILES);
|
||||
listCmd.insert(listCmd.end(), it->second.verifyPath.begin(), it->second.verifyPath.end());
|
||||
listCmd.push_back(0); // 客户端按 C 串取路径
|
||||
} else {
|
||||
// 没有复核目标(或伪造的第二次完成包):直接投递,让工具线程收尾。
|
||||
it->second.data.assign(data, data + len);
|
||||
it->second.done = true;
|
||||
m_PendingCv.notify_one();
|
||||
return FileOpAck::CloseSub;
|
||||
}
|
||||
}
|
||||
|
||||
if (!subCtx->Send2Client(listCmd.data(), (ULONG)listCmd.size())) {
|
||||
// 复核下发失败:别把工具线程挂到超时,直接把完成包投递过去,
|
||||
// 工具会看到「不是列表包」→ verified=null(结果未知),如实上报。
|
||||
Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: send verify listing failed\n",
|
||||
(unsigned long long)device_id);
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end()) return FileOpAck::CloseSub;
|
||||
it->second.data.assign(data, data + len);
|
||||
it->second.done = true;
|
||||
m_PendingCv.notify_one();
|
||||
return FileOpAck::CloseSub;
|
||||
}
|
||||
Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: ack ok -> verify listing (%d bytes)\n",
|
||||
(unsigned long long)device_id, (int)listCmd.size());
|
||||
return FileOpAck::KeepSub; // 等 TOKEN_FILE_LIST;该分支投递数据后 CancelIO 收尾
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitPending(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs) {
|
||||
std::unique_lock<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
@@ -7985,7 +8679,8 @@ void CMcpServer::MarkLateFirstPacket(uint64_t device_id, std::initializer_list<B
|
||||
|
||||
// 工具 → 应答首包 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")
|
||||
if (tool == "list_files" || tool == "download_file" || tool == "upload_file" || tool == "search_file" ||
|
||||
IsFileWriteToolName(tool))
|
||||
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_DRIVE_LIST });
|
||||
else if (tool == "list_registry")
|
||||
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REGEDIT });
|
||||
@@ -8054,12 +8749,21 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu
|
||||
std::string path;
|
||||
bool listDrives = true;
|
||||
bool searchFile = false;
|
||||
bool fileOp = false;
|
||||
std::vector<BYTE> fileOpFollowUp;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end()) return true; // 已超时清理 → 调用方 CancelIO 收尾
|
||||
path = it->second.path;
|
||||
if (it->second.tool == "search_file") {
|
||||
if (IsFileWriteToolName(it->second.tool)) {
|
||||
// P10-B:文件写工具。子连接就绪即下发写命令(path 对这些工具无意义,
|
||||
// payload 已整条存在 followUp 里),保持子连接等 TOKEN_*_FINISH。
|
||||
fileOp = true;
|
||||
it->second.subCtx = subCtx; // 超时 CancelIO / 阶段判断用
|
||||
it->second.followUpSent = true;
|
||||
fileOpFollowUp = it->second.followUp;
|
||||
} else if (it->second.tool == "search_file") {
|
||||
// B2:path 里装的是 [根目录 \0][模式 \0](含 NUL,不能用 C 字符串接口处理)。
|
||||
searchFile = true;
|
||||
it->second.subCtx = subCtx; // 超时停搜 / 收尾要用
|
||||
@@ -8074,6 +8778,14 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu
|
||||
}
|
||||
}
|
||||
|
||||
if (fileOp) {
|
||||
// 锁外下发写命令。发送失败不额外处理:工具线程会在超时后按 -32001 收尾并 CancelIO。
|
||||
if (!subCtx->Send2Client(fileOpFollowUp.data(), (ULONG)fileOpFollowUp.size()))
|
||||
Mprintf("[MCP-P10B] OnDriveList: send file-op command failed (dev=%llu, %d bytes)\n",
|
||||
(unsigned long long)device_id, (int)fileOpFollowUp.size());
|
||||
return false; // 保持子连接,等完成包
|
||||
}
|
||||
|
||||
if (searchFile) {
|
||||
// 文件搜索:子链接已就绪,下发 COMMAND_SEARCH_FILE + FILESEARCH 结构体。
|
||||
// 与 MFC 文件管理器 OnBtnSearch 的打包方式一致(命令字节后紧跟整个结构体)。
|
||||
@@ -8335,14 +9047,22 @@ bool CMcpServer::OnServiceReady(uint64_t device_id, context* subCtx) {
|
||||
return true; // 客户端写后自动回,无需补发
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs) {
|
||||
bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs,
|
||||
int* phaseOut) {
|
||||
context* subCtx = nullptr;
|
||||
std::unique_lock<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end()) return false;
|
||||
if (it == m_Pending.end()) {
|
||||
if (phaseOut) *phaseOut = 0;
|
||||
return false;
|
||||
}
|
||||
if (phaseOut) *phaseOut = it->second.phase;
|
||||
|
||||
bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
// 超时/空数据时把「放弃那一刻所处的阶段」带出去:P10-B 的 phase 1 表示完成包已到、
|
||||
// 只是复核列目录没回来(命令已送达),与 phase 0 的「连回包都没有」不是一回事。
|
||||
if (phaseOut) *phaseOut = it->second.phase;
|
||||
if (!signaled || it->second.data.empty()) {
|
||||
subCtx = it->second.subCtx;
|
||||
Mprintf("[MCP-P7] WaitPendingWrite dev=%llu TIMEOUT: signaled=%d dataEmpty=%d subCtx=%p\n",
|
||||
|
||||
@@ -270,6 +270,12 @@ public:
|
||||
void SetFileTransferEnabled(bool enabled) { m_fileTransferEnabled = enabled; }
|
||||
bool IsFileTransferEnabled() const { return m_fileTransferEnabled; }
|
||||
|
||||
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
|
||||
// 独立开关 McpFileWrite(默认关),并要求 McpReadonly=0。不复用 McpFileTransfer:
|
||||
// 上传是「覆盖」,删除是「毁灭」,风险等级不同,必须能分别关掉。
|
||||
void SetFileWriteEnabled(bool enabled) { m_fileWriteEnabled = enabled; }
|
||||
bool IsFileWriteEnabled() const { return m_fileWriteEnabled; }
|
||||
|
||||
// 该 host 是否有进行中的文件传输会话(MessageHandle 分派守卫)。
|
||||
bool IsFileTransferPending(uint64_t device_id);
|
||||
|
||||
@@ -377,7 +383,28 @@ public:
|
||||
bool OnServiceReady(uint64_t device_id, context* subCtx);
|
||||
|
||||
// 工具线程:等待写确认包(第二个同 token 包);超时/空数据清挂起并 CancelIO 子连接。
|
||||
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs);
|
||||
// phaseOut(可空):返回超时/成功那一刻所处的阶段(见 P10-B 的 phase),供调用方区分
|
||||
// 「连完成包都没收到」与「完成包已到、复核没回来」。
|
||||
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs,
|
||||
int* phaseOut = nullptr);
|
||||
|
||||
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
|
||||
// 链路与 P7 同构(主连接 COMMAND_LIST_DRIVE → 子连接首包 TOKEN_DRIVE_LIST → 同一子连接
|
||||
// 上发写命令 → 等 TOKEN_*_FINISH),但多一个阶段:客户端的完成包是无条件回包
|
||||
// (忽略 DeleteFile/MoveFile/MakeSureDirectoryPathExists 的返回值),所以收到后不直接
|
||||
// 收尾,而在同一子连接上补发一次 COMMAND_LIST_FILES 复核(phase 0 = 等完成包,
|
||||
// phase 1 = 等复核列目录,两阶段共用一个超时)。
|
||||
//
|
||||
// verifyPath 是复核要列的父目录(客户端 ANSI/GBK,空 = 不复核,直接投递完成包)。
|
||||
bool BeginPendingFileOp(uint64_t device_id, const std::string& tool,
|
||||
const std::vector<BYTE>& followUp, const std::string& verifyPath);
|
||||
|
||||
// MessageHandle(TOKEN_DELETE_FINISH / TOKEN_RENAME_FINISH / TOKEN_CREATEFOLDER_FINISH) 调用。
|
||||
// NotMine 与本请求无关(迟到的孤儿包)→ 调用方 CancelIO 收尾;
|
||||
// KeepSub 已转入 phase 1、在同一子连接上补发了列目录 → 调用方不关子连接;
|
||||
// CloseSub 已投递最终数据(无复核目标 / 复核包发不出去)→ 调用方 CancelIO 收尾。
|
||||
enum class FileOpAck { NotMine, KeepSub, CloseSub };
|
||||
FileOpAck TakeFileOpFinish(uint64_t device_id, context* subCtx, const BYTE* data, ULONG len);
|
||||
|
||||
// ===== 迟到首包吸收(工具放弃后不再弹出 MFC 对话框)=====
|
||||
// 工具超时/失败清掉挂起后,客户端仍可能才把应答首包发上来(列盘、服务列表、注册表、
|
||||
@@ -602,6 +629,9 @@ private:
|
||||
std::vector<std::vector<BYTE>> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包
|
||||
size_t searchBytes = 0;
|
||||
bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH
|
||||
// ===== P10-B:文件写工具(delete_path / move_path / create_folder)=====
|
||||
int phase = 0; // 0=等 TOKEN_*_FINISH;1=等复核用的 TOKEN_FILE_LIST
|
||||
std::string verifyPath; // phase 1 要列的父目录(客户端 ANSI/GBK)
|
||||
bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP
|
||||
bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃
|
||||
};
|
||||
@@ -778,6 +808,7 @@ private:
|
||||
bool m_terminalEnabled = false; // 持久终端开关(默认关;要求 m_readonly=false)
|
||||
bool m_remoteControlEnabled = false; // 远程控制开关(默认关;要求 m_readonly=false)
|
||||
bool m_fileTransferEnabled = false; // 文件传输开关(默认关;download_file)
|
||||
bool m_fileWriteEnabled = false; // P10-B 文件写入开关(默认关;要求 m_readonly=false)
|
||||
bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false)
|
||||
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
|
||||
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
|
||||
|
||||
@@ -162,6 +162,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnFileTransfer.Create(_TR("启用文件传输(download_file)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_FILETRANSFER);
|
||||
m_btnFileWrite.Create(_TR("启用文件写入(删除/改名/建目录,不可恢复)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_FILEWRITE);
|
||||
m_btnManage.Create(_TR("启用管理操作(进程/窗口/服务/电源)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_MANAGE);
|
||||
@@ -207,6 +210,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnTerminal.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnFileTransfer.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnFileWrite.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnManage.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
@@ -228,6 +232,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
int terminal = THIS_CFG.GetInt("settings", "McpTerminal", 0);
|
||||
int remoteControl = THIS_CFG.GetInt("settings", "McpRemoteControl", 0);
|
||||
int fileTransfer = THIS_CFG.GetInt("settings", "McpFileTransfer", 0);
|
||||
int fileWrite = THIS_CFG.GetInt("settings", "McpFileWrite", 0);
|
||||
int manage = THIS_CFG.GetInt("settings", "McpManage", 0);
|
||||
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
|
||||
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
|
||||
@@ -250,6 +255,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnTerminal.SetCheck(terminal ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnRemoteControl.SetCheck(remoteControl ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnFileTransfer.SetCheck(fileTransfer ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnFileWrite.SetCheck(fileWrite ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnManage.SetCheck(manage ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
|
||||
@@ -323,6 +329,7 @@ void CMcpSettingsDlg::OnOK()
|
||||
bool terminal = (m_btnTerminal.GetCheck() == BST_CHECKED);
|
||||
bool remoteControl = (m_btnRemoteControl.GetCheck() == BST_CHECKED);
|
||||
bool fileTransfer = (m_btnFileTransfer.GetCheck() == BST_CHECKED);
|
||||
bool fileWrite = (m_btnFileWrite.GetCheck() == BST_CHECKED);
|
||||
bool manage = (m_btnManage.GetCheck() == BST_CHECKED);
|
||||
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
|
||||
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
|
||||
@@ -384,6 +391,7 @@ void CMcpSettingsDlg::OnOK()
|
||||
THIS_CFG.SetInt("settings", "McpTerminal", terminal ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpRemoteControl", remoteControl ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpFileTransfer", fileTransfer ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpFileWrite", fileWrite ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpManage", manage ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
|
||||
@@ -398,8 +406,9 @@ void CMcpSettingsDlg::OnOK()
|
||||
|
||||
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
|
||||
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
|
||||
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
|
||||
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/文件写入/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("持久终端、远程控制、管理操作与文件写入仅在只读模式关闭时生效。") + _T("\r\n") +
|
||||
_TR("文件写入包含删除(不可恢复)、改名与建目录;删除会拒绝盘符根与系统目录。") + _T("\r\n") +
|
||||
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
|
||||
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
|
||||
@@ -463,6 +472,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
||||
m_btnFileTransfer.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
m_btnFileWrite.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
m_btnManage.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ private:
|
||||
IDC_MCP_KEY = 1017, // 私钥路径编辑框(PKCS#8)
|
||||
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
|
||||
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
|
||||
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
|
||||
};
|
||||
|
||||
CButton m_btnEnable;
|
||||
@@ -54,6 +55,7 @@ private:
|
||||
CButton m_btnTerminal;
|
||||
CButton m_btnRemoteControl;
|
||||
CButton m_btnFileTransfer;
|
||||
CButton m_btnFileWrite;
|
||||
CButton m_btnManage;
|
||||
CButton m_btnMachine;
|
||||
CButton m_btnMachineDangerous;
|
||||
|
||||
+141
-5
@@ -1,10 +1,14 @@
|
||||
<#
|
||||
服务端 MCP 只读冒烟测试。
|
||||
服务端 MCP 冒烟测试。
|
||||
|
||||
只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
|
||||
默认只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
|
||||
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
|
||||
确认 MCP 链路与改动前相比没有回归。
|
||||
|
||||
唯一会写目标机的部分是 [4c] 文件写入,且必须显式给 -FileWriteDir 才会跑:
|
||||
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
|
||||
后整棵删掉,不碰沙箱以外的任何东西。
|
||||
|
||||
用法:
|
||||
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
|
||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
||||
@@ -21,6 +25,11 @@
|
||||
10000 条上限,测出来的是「部分结果」而不是功能是否可用。
|
||||
-AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言
|
||||
-32006 拒绝会写一条 CALL_DENIED。
|
||||
-FileWriteDir 可选,跑 delete_path / move_path / create_folder 的目标机目录
|
||||
(必须已存在且可写,如 C:\Users\Public 或 C:\Temp)。脚本只在其下
|
||||
新建 mcp_smoke_xxxx 沙箱并在结束时删掉它。不指定就跳过这一节。
|
||||
注意 upload_file 的 local_path 指的是服务端本机路径,所以这一节要求
|
||||
冒烟脚本与服务端在同一台机器上(默认的 127.0.0.1 即如此)。
|
||||
|
||||
退出码:0 全部通过;1 有失败项。token 不会被打印。
|
||||
#>
|
||||
@@ -30,7 +39,8 @@ param(
|
||||
[string]$HostId = '',
|
||||
[switch]$SkipHost,
|
||||
[string]$SearchPath = '',
|
||||
[string]$AuditLog = ''
|
||||
[string]$AuditLog = '',
|
||||
[string]$FileWriteDir = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -242,10 +252,13 @@ if (-not $SkipHost) {
|
||||
$pname = [string]$firstProc.name
|
||||
$byName = Rpc '' $null 'list_processes' @{ id = $HostId; name = $pname; limit = 100 }
|
||||
$bn = $byName.result.structuredContent
|
||||
# totalAll 是「过滤前的总数」,两次调用之间目标机的进程本来就会增减(实测差过 1),
|
||||
# 所以留一点余量:要断言的是「过滤没有把 totalAll 一起缩掉」,不是快照完全相等。
|
||||
$drift = [Math]::Abs([int]$bn.totalAll - [int]$ps.totalAll)
|
||||
Check 'list_processes name 过滤命中且 totalAll 不变' `
|
||||
($byName.error -eq $null -and [int]$bn.totalAll -eq [int]$ps.totalAll -and
|
||||
($byName.error -eq $null -and $drift -le 10 -and
|
||||
[int]$bn.total -gt 0 -and [int]$bn.total -le [int]$bn.totalAll) `
|
||||
("total=" + $bn.total + " totalAll=" + $bn.totalAll + " baseAll=" + $ps.totalAll)
|
||||
("total=" + $bn.total + " totalAll=" + $bn.totalAll + " baseAll=" + $ps.totalAll + " drift=" + $drift)
|
||||
$lower = $pname.ToLowerInvariant()
|
||||
Check 'list_processes name 过滤结果都含该名字' `
|
||||
(@($bn.processes | Where-Object { -not ([string]$_.name).ToLowerInvariant().Contains($lower) }).Count -eq 0)
|
||||
@@ -378,6 +391,129 @@ if (-not $SkipHost -and $drive) {
|
||||
}
|
||||
}
|
||||
|
||||
# ===== 4c. 文件写入(P10-B:delete_path / move_path / create_folder) =====
|
||||
# 客户端对删除文件/删除目录/建目录/改名四条命令都是「做完就无条件回完成包」,ok 只证明命令送达;真正的结论在
|
||||
# verified(true=复核看到状态变了,false=复核看到没变,null=复核没做成)。所以这一节只断言
|
||||
# verified,不看 ok。顺带覆盖两处只有真机才暴露的坑:建目录要在路径末尾补反斜杠,
|
||||
# 以及复核要读 LookupInListing 的 isDir 出参。
|
||||
function Detail($r) {
|
||||
if ($null -ne $r -and $null -ne $r.error) { return [string]$r.error.message }
|
||||
$c = @($r.result.content)
|
||||
if ($c.Count -gt 0) { return [string]$c[0].text }
|
||||
return ''
|
||||
}
|
||||
function ErrCode($r) {
|
||||
if ($null -eq $r -or $null -eq $r.error) { return 0 }
|
||||
return [int]$r.error.code
|
||||
}
|
||||
function OkVerified($r) {
|
||||
if ($null -eq $r -or $null -ne $r.error) { return $false }
|
||||
$s = $r.result.structuredContent
|
||||
return (($s.ok -eq $true) -and ($s.verified -eq $true))
|
||||
}
|
||||
function ListingNames([string]$path) {
|
||||
$r = Rpc '' $null 'list_files' @{ id = $HostId; path = $path; limit = 100 }
|
||||
if ($r.error) { return @() }
|
||||
return @($r.result.structuredContent.files | ForEach-Object { [string]$_.name })
|
||||
}
|
||||
|
||||
$writeTools = @($tools | Where-Object { $_.name -in @('delete_path', 'move_path', 'create_folder') })
|
||||
if ($writeTools.Count -lt 3) {
|
||||
Write-Host "`n[4c] 文件写入:工具未出现(McpFileWrite 关或 McpReadonly 开),跳过。" -ForegroundColor Yellow
|
||||
} elseif ($SkipHost -or -not $HostId) {
|
||||
Write-Host "`n[4c] 文件写入:没有在线主机,跳过。" -ForegroundColor Yellow
|
||||
} elseif (-not $FileWriteDir) {
|
||||
Write-Host "`n[4c] 文件写入:未给 -FileWriteDir,跳过(这一节会在目标机上建/删文件)。" -ForegroundColor Yellow
|
||||
} else {
|
||||
Write-Host "`n[4c] 文件写入 (根=$FileWriteDir)"
|
||||
$sandbox = $FileWriteDir.TrimEnd('\') + '\mcp_smoke_' + (Get-Random -Minimum 10000 -Maximum 99999)
|
||||
$uploadedName = ''
|
||||
try {
|
||||
# 一次建两层:既测「中间层一并创建」,也测路径末尾的反斜杠(少了它,客户端
|
||||
# MakeSureDirectoryPathExists 会把最后一级当成文件名,只建中间层)。
|
||||
$deep = $sandbox + '\sub\deep'
|
||||
$mk = Rpc '' $null 'create_folder' @{ id = $HostId; path = $deep }
|
||||
Check 'create_folder 建嵌套目录 verified=true' (OkVerified $mk) (Detail $mk)
|
||||
$names = ListingNames $sandbox
|
||||
Check 'create_folder 后父目录里能看到它' ($names -contains 'sub') ("names=" + ($names -join ','))
|
||||
|
||||
# upload_file 的返回值只有摘要,用列表复核它到底落没落盘
|
||||
$localFile = Join-Path $env:TEMP ('mcp_smoke_upload_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.txt')
|
||||
Set-Content -LiteralPath $localFile -Value 'mcp smoke' -Encoding ascii
|
||||
$uploadedName = [System.IO.Path]::GetFileName($localFile)
|
||||
$uploadOk = $false
|
||||
if (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
|
||||
$up = Rpc '' $null 'upload_file' @{ id = $HostId; local_path = $localFile; remote_dir = $sandbox }
|
||||
$uploadOk = ($null -eq $up.error)
|
||||
Check 'upload_file 正常返回' $uploadOk (Detail $up)
|
||||
} else {
|
||||
Write-Host " upload_file 未开启,跳过上传/改名/删文件三连。" -ForegroundColor Yellow
|
||||
}
|
||||
if ($uploadOk) {
|
||||
Check 'upload_file 后沙箱里能看到该文件' ((ListingNames $sandbox) -contains $uploadedName)
|
||||
|
||||
$renamed = $uploadedName -replace '\.txt$', '_renamed.txt'
|
||||
$mv = Rpc '' $null 'move_path' @{ id = $HostId; from = ($sandbox + '\' + $uploadedName); to = ($sandbox + '\' + $renamed) }
|
||||
Check 'move_path 改名 verified=true' (OkVerified $mv) (Detail $mv)
|
||||
$names = ListingNames $sandbox
|
||||
Check 'move_path 后新名字出现、旧名字消失' `
|
||||
(($names -contains $renamed) -and -not ($names -contains $uploadedName)) ("names=" + ($names -join ','))
|
||||
$uploadedName = $renamed
|
||||
|
||||
$rm = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\' + $renamed) }
|
||||
Check 'delete_path 删文件 verified=true' (OkVerified $rm) (Detail $rm)
|
||||
Check 'delete_path 后文件不在列表里' (-not ((ListingNames $sandbox) -contains $renamed))
|
||||
} elseif (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
|
||||
# 上传失败时改名/删文件没有对象,跳过而不是再报两条失败(upload_file 那条已经记了)
|
||||
Write-Host " 上一步 upload_file 失败,跳过改名/删文件。" -ForegroundColor Yellow
|
||||
}
|
||||
Remove-Item -LiteralPath $localFile -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# 非 ASCII 路径:服务端按 UTF-8 校验、只转一次 GBK,客户端再用 A 接口落盘
|
||||
$cnDir = $sandbox + '\中文目录'
|
||||
$cn = Rpc '' $null 'create_folder' @{ id = $HostId; path = $cnDir }
|
||||
Check 'create_folder 中文路径 verified=true' (OkVerified $cn) (Detail $cn)
|
||||
$cnRm = Rpc '' $null 'delete_path' @{ id = $HostId; path = $cnDir; recursive = $true }
|
||||
Check 'delete_path 中文路径 verified=true' (OkVerified $cnRm) (Detail $cnRm)
|
||||
|
||||
# recursive=false 落在目录上:客户端 DeleteFile 失败且不回错误包 → 复核必须说 false
|
||||
$mk2 = Rpc '' $null 'create_folder' @{ id = $HostId; path = ($sandbox + '\asdir') }
|
||||
if (OkVerified $mk2) {
|
||||
$bad = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\asdir') }
|
||||
Check 'delete_path 对目录用 recursive=false 时 verified=false' `
|
||||
(($null -eq $bad.error) -and ($bad.result.structuredContent.ok -eq $true) -and
|
||||
($bad.result.structuredContent.verified -eq $false)) (Detail $bad)
|
||||
}
|
||||
|
||||
# 越界与参数拒绝:全部发生在服务端,不该触达目标机
|
||||
$fwDrive = if ($drive) { $drive } else { $FileWriteDir.Substring(0, 2) }
|
||||
$fwRoot = $fwDrive.TrimEnd('\')
|
||||
$longPath = $sandbox + '\' + ('a' * 220)
|
||||
$cases = @(
|
||||
@{ name = '盘符根'; tool = 'delete_path'; args = @{ id = $HostId; path = $fwRoot }; code = -32602 }
|
||||
@{ name = '系统目录'; tool = 'delete_path'; args = @{ id = $HostId; path = ($fwRoot + '\Windows\Temp') }; code = -32602 }
|
||||
@{ name = '含 %VAR%'; tool = 'delete_path'; args = @{ id = $HostId; path = '%TEMP%\mcp_smoke_x' }; code = -32602 }
|
||||
@{ name = '相对路径'; tool = 'create_folder'; args = @{ id = $HostId; path = 'mcp_smoke_x' }; code = -32602 }
|
||||
@{ name = '超长路径'; tool = 'create_folder'; args = @{ id = $HostId; path = $longPath }; code = -32602 }
|
||||
@{ name = 'from 与 to 相同'; tool = 'move_path'; args = @{ id = $HostId; from = $deep; to = $deep.ToUpperInvariant() }; code = -32602 }
|
||||
@{ name = '主机不在线'; tool = 'create_folder'; args = @{ id = '1'; path = ($sandbox + '\x') }; code = -32002 }
|
||||
)
|
||||
foreach ($c in $cases) {
|
||||
$r = Rpc '' $null $c.tool $c.args
|
||||
Check ('参数被拒:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r)
|
||||
}
|
||||
|
||||
# 收尾:整棵删掉沙箱,并用父目录列表复核
|
||||
$rmAll = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
|
||||
Check 'delete_path 递归删沙箱 verified=true' (OkVerified $rmAll) (Detail $rmAll)
|
||||
$fwParent = $FileWriteDir.TrimEnd('\')
|
||||
Check '沙箱已不在父目录里' (-not ((ListingNames $fwParent) -contains [System.IO.Path]::GetFileName($sandbox)))
|
||||
} finally {
|
||||
# 中途失败时也要尽量不把沙箱留在目标机上(尽力而为,不再断言)
|
||||
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
|
||||
}
|
||||
}
|
||||
|
||||
# ===== 5. 策略拒绝(-32006) =====
|
||||
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
|
||||
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
|
||||
|
||||
Reference in new issue
Block a user