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:
yuanyuanxianganddeepseek-flash committed 2026-10-28 21:25:46 +01:00
1 parent bb55f52b29
commit 27b5431130
7 files changed
+933 -13

No files matched your search

+725 -5
View File
@@ -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",