From 13c02fe50b1f66d952cd1e62149ad7ac039b72ab Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Thu, 29 Oct 2026 15:03:32 +0100 Subject: [PATCH] Feature: Skip already-present targets in copy_files_c2c The destination writes every chunk unconditionally, so a second call with the same arguments re-sent the whole file and returned exactly the same result as the first. Measured on an 11 MB log: the target's mtime moved and the entry count did not, and the caller had no way to tell a real transfer from a repeat. upload_file and download_file already answer this with overwrite/skipped; copy_files_c2c was the one that did not. The skip decision has to be made on the server, because the receiving end does not check whether the file exists. Before opening the transfer, a default call now lists one level of dst_dir through ListRemoteTopLevelNames - the helper upload_file already uses - and drops the paths whose basename is already there. If everything is dropped the call returns success without creating a transfer id at all, so no host is occupied and nothing is sent. overwrite=true restores the old unconditional behaviour. Name comparison follows the destination filesystem: folded on Windows, exact on POSIX. That needed a foldCase parameter on the helper, defaulted to true so upload_file keeps its behaviour. dst_dir is handed to the listing without its trailing separator, because the client concatenates "%s\*.*" and a trailing one produces "C://*.*", which FindFirstFile rejects. search_file hit the same thing. No protocol change and no client change: the packet layout, the receiver and both client platforms are untouched. Verified against a real server (build 2026-10-29 14:34:33) with a Windows 11 source and both an Ubuntu 24.04 and a Windows 11 destination. A second default call returns file_count=0, skipped=1, an empty transfer_id and skip_check_failed=false with the target's mtime unchanged; overwrite=true advances the mtime (1793276909 -> 1793281657) and reports skipped=0; a call into a non-existent directory creates it and lands the file flat; a Windows destination folds case, so a placeholder SETTINGS.INI makes a later settings.ini skip, while a POSIX destination leaves both files side by side. One documented case does not hold, and the expectation was mine rather than the code's. "Destination occupied by another tool" was supposed to fail the pre-check and still transfer with skip_check_failed=true, but BeginC2CTransfer consults the same m_Pending registry for src_id and dst_id, so the transfer is refused with -32003 before the fallback can carry it. The other door - a directory that can be written but not listed - showed the pre-check succeeding instead of failing: the Linux client reports EACCES as an empty directory rather than TOKEN_FILE_LIST_ERROR, so the call goes on to overwrite. skip_check_failed is therefore a timeout backstop that is hard to reach deliberately; the field stays, and 14.9.2 no longer claims that a busy host reaches the fallback. Section 14.9 of the design doc records the contract, those results, and one wrong turn worth keeping: an earlier round concluded that single-file C2C nested the whole absolute path under dst_dir, and added receiver-side hardening for it. The nesting came from the ad-hoc JSON-RPC test harness, which passed JSON on the command line where the shell folded \\ into \/ before Python parsed it, so the source client received a path with no backslashes left and its basename fallback - which looks for a backslash - returned the whole path. The same file sent through the real MCP client produces a clean basename. That hardening has been reverted; the defect was in the test, not the product. Co-Authored-By: deepseek-flash --- docs/Mcp_FileTransfer_Design.md | 106 +++++++++++++++++++++++++++++++- server/2015Remote/McpServer.cpp | 84 +++++++++++++++++++++++-- 2 files changed, 184 insertions(+), 6 deletions(-) diff --git a/docs/Mcp_FileTransfer_Design.md b/docs/Mcp_FileTransfer_Design.md index 1d74f19..a56d3ce 100644 --- a/docs/Mcp_FileTransfer_Design.md +++ b/docs/Mcp_FileTransfer_Design.md @@ -451,8 +451,8 @@ TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端 ### 14.5 工具契约 -入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)。 -出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`。 +入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)、`overwrite`(默认 `false`,见 §14.9)。 +出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`、`skipped`、`skip_check_failed`。 `receiver_ack` 三种取值: - `true` 且 `status==0`:目标端已确认全部条目落盘(`file_count`/`total_bytes` 是**目标端实收**值,与源端统计一致)。 @@ -597,3 +597,105 @@ TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端 | Windows 目标端 `upload_file` / `download_file` / `copy_files_c2c` 回归 | 与改动前一致(Windows 目标的空文件仍不落地,`receiver_ack` 仍为 `false`) | 注:WSL 重启后 Linux 客户端的 machine-id 会变,`id` 随之改变,测试脚本以运行时 `list_online_hosts` 为准。 + +### 14.9 增补(2026-10-29):`overwrite` 与 `skipped` + +#### 14.9.1 问题(实测) + +同一份文件连续 C2C 两次,目标端 mtime 从 `1793276750` 变为 `1793276909`(重写),大小不变、 +条目数不变 —— 即**每次都全量重发**。更麻烦的是两次返回值完全相同: + +``` +第一次: file_count=1, total_bytes=11595168, receiver_ack=true +第二次: file_count=1, total_bytes=11595168, receiver_ack=true +``` + +调用方无法分辨「这次真的传了」还是「跳过了」。`upload_file` / `download_file` 有 `overwrite` + +`skipped`,只有 C2C 缺这一对。 + +#### 14.9.2 做法(纯服务端,协议零改动) + +目标端收包是**无条件覆盖写**(`RecvFileChunkV2` 不判断是否存在),所以跳过只能在服务端做: +发起传输前先列一次目标目录,把重名的顶层项从 `paths` 里剔掉。协议、客户端一律不动。 + +- `overwrite=false`(默认)时,调用 `ListRemoteTopLevelNames`(`upload_file` 已在用的同一个 + helper,`McpServer.cpp`)列 `dst_dir` 一层; +- 逐个 `paths` 取 basename,与目标端已有名字比对:**Windows 目标不区分大小写,POSIX 目标区分** + (为此给 helper 加了 `foldCase` 参数,默认 `true` 保持 `upload_file` 行为不变); +- 命中的路径剔除并计入 `skipped`;全被剔除则直接返回成功,**不发起传输、不建 transferID**; +- 目标目录不存在时 helper 返回空集(`ERROR_FILE_NOT_FOUND`/`ERROR_PATH_NOT_FOUND` 视为空), + 正好等价于「无同名项」,不会挡住「传到新目录」; +- **预检失败不报错**:预检本身失败时退回「全量发送」,并置 `skip_check_failed=true`。 + 不能让一次检查失败把本该成功的传输挡掉——这是与 `upload_file` 不同的取舍 + (`upload_file` 在预检失败时直接 `-32001` 失败)。 + 注意这个 fallback 的**实际可达范围很窄**:目标主机被在飞传输或别的工具占用时,预检确实 + 失败,但紧接着的 `BeginC2CTransfer` 也查同一套 `m_Pending` / `m_FileXferSessions` 互斥, + 会直接返回 `-32003`,根本走不到「全量发送」那一步(见 §14.9.5)。真正能置位的只有 + 「列举超时或异常,而设备此刻空闲」。 + +`dst_dir` 传给 helper 时用**不带尾分隔符**的形态(`dstDirListAnsi`):客户端拼 `"%s\*.*"`, +带尾分隔符会拼成 `C://*.*` 让 `FindFirstFile` 失败,与 `search_file` 踩过的是同一个坑。 + +#### 14.9.3 契约 + +| 字段 | 语义 | +|---|---| +| `overwrite`(入参,bool,默认 false) | `false`:目标目录已有同名顶层项则跳过;`true`:维持旧行为,无条件重发 | +| `skipped`(出参,int) | 本次因已存在而跳过的顶层项数;`overwrite=true` 时恒为 0 | +| `skip_check_failed`(出参,bool) | `true` 表示没能预检目标目录(主机忙/超时/拒绝访问),本次按全量发送,`skipped` 不可信 | + +#### 14.9.4 验证 + +服务端重建并重启后(`exe_build_time=2026-10-29 14:34:33`,PID 12160)实测: + +| 用例 | 结果 | +|---|---| +| 1. 同一文件连传两次,第二次 `overwrite=false` | **通过**:`file_count=0`、`skipped=1`、`transfer_id=""`、`skip_check_failed=false`,目标端 mtime 不变 | +| 2. `overwrite=true` 重传 | **通过**:`file_count=1`、`skipped=0`,目标端 mtime `1793276909` → `1793281657`(推进 4748 s),条目数不变 | +| 3. 传到不存在的新目录 | **通过**:目录自动创建,单文件落成 `/`(如 `/home/shaun/c2c_probe3/settings.ini`) | +| 4. 目标主机被别的工具占住(在飞) | **不可按原描述构造**:返回 `-32003` 而不是「全量发送 + `skip_check_failed=true`」,详见 §14.9.5 | +| 5. Windows 目标 + 大小写不同的同名文件 | **通过**:目标 `C:\Temp\c2c_case5` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=1`、`file_count=0`、`transfer_id=""`,目录内仍只有 `SETTINGS.INI` | +| 6. Linux 目标 + `SETTINGS.INI` vs `settings.ini` | **通过**:目标 `/home/shaun/c2c_case6` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=0`、`file_count=1`,两个文件并存(23 B 与 1528 B) | + +用例 1、2、3 的目标端是 Ubuntu 24.04(`ubuntu-24` / `Ubuntu24`),源端是 Windows 11(`IOU-Station`); +用例 5 的目标端是 Windows 11(`MS084`)。 + +#### 14.9.5 用例 4 的期望不成立(实测) + +原用例假设「目标主机被别的工具占住 → 预检失败 → 仍能传完,`skip_check_failed=true`」。实测两条 +路径都走不到那个结果: + +- **占住目标**(后台 `download_file` 一份 17 MB 日志,随即发起 C2C):返回 + `-32003 Device busy: source or destination host already has a transfer in flight`。 + 原因是 `BeginC2CTransfer`(`McpServer.cpp`)除了查自己的 `m_FileXferSessions`,还查 + `src_id`/`dst_id` 的 `m_Pending`——与预检 `BeginPending` 的互斥条件是同一套。预检失败后 + 落到它这里仍然被拒,`skip_check_failed` 因此不可观测。 +- **让列举失败但写入成功**(`chmod 333`,可写不可读):预检**没有**失败。Linux 客户端把 + `EACCES` 当成「目录里没有条目」上报(不是 `TOKEN_FILE_LIST_ERROR`),服务端于是 + `skip_check_failed=false`、`skipped=0`,随后照常覆盖写,文件确实写进了 1528 字节。 + 即这一路是 **fail-open**:列不出来的目录,`overwrite=false` 不会保护其中已有的同名文件。 + +因此 `skip_check_failed` 现在只作为「列举超时/异常且设备空闲」的兜底存在,难以稳定构造, +字段保留。若要真正验证它,需要让 `WaitPending` 超时(例如临时挂起客户端进程),代价是可能 +把主机判成离线,本轮没有做。 + +#### 14.9.6 一次误报的复盘(重要,避免重犯) + +本轮曾判定「单文件 C2C 落盘会多出 `C:/…` 目录树,只有目录/多文件正常」,并据此在 +`common/FileTransferV2.h` 里加了一段接收端路径加固。**该结论是错的,加固已还原。** + +根因是自制的 JSON-RPC 直连测试脚本:为了绕过连接器缓存的 `tools/list`(它还没有 +`overwrite` 字段),脚本用命令行参数传 JSON,而**命令行传递层会把 `\\` 折成 `\/`**, +于是 Python 解析出来的路径已经是 `C://ProgramData//HTS//…`(双正斜杠)。源端拿到一条 +没有任何反斜杠的路径后,`GetRelativePath` 的 basename 兜底用 `find_last_of('\\')` 找分隔符, +找不到就把整条绝对路径当相对路径返回 —— 于是落盘成 `/C:/ProgramData/…`。 + +也就是说:**缺陷在测试工具里,不在产品里。** 同一个文件、同一个 `dst_dir`,用连接器 +(标准 JSON 转义)调用时源端发出的名字是干净的 `/home/shaun/c2c_probe3/settings.ini`。 + +教训: + +- 传含反斜杠的路径给自测脚本时,**必须走文件或 stdin,不要走命令行参数**; +- 判定「产品有 bug」之前,先用**真实 MCP 客户端**复现一次,别只信自建 harness; +- 中继侧/接收侧的日志只能证明「收到的字节是什么」,不能证明「上游是谁写坏的」。 + diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 85144a1..fd9bb52 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -2331,7 +2331,7 @@ std::string BuildToolsListResult(const Json::Value& id) { if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "copy_files_c2c"; - tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。返回 transfer_id/file_count/total_bytes/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。"; + tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。"; tool["inputSchema"] = BuildCopyFilesC2CInputSchema(); tool["outputSchema"] = BuildCopyFilesC2COutputSchema(); tools.append(tool); @@ -5854,7 +5854,8 @@ static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsign // 复用 list_files 的 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST 链路。 static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId, const std::string& remoteDirAnsi, - std::set& names) { + std::set& names, + bool foldCase = true) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_files", remoteDirAnsi)) return false; context* ctx = FindMainContext(parent, devId); @@ -5882,7 +5883,7 @@ static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId, off += nlen + 1; if (off + 16 > len) break; off += 16; // sizeHigh/sizeLow/ft(8) - names.insert(AsciiLower(std::string(name, nlen))); + names.insert(foldCase ? AsciiLower(std::string(name, nlen)) : std::string(name, nlen)); } return true; } @@ -6284,6 +6285,12 @@ Json::Value BuildCopyFilesC2CInputSchema() { to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时);超时不代表传输失败"; props["timeout_ms"] = to; + Json::Value ow(Json::objectValue); + ow["type"] = "boolean"; + ow["description"] = u8"目标目录已存在同名顶层项时是否覆盖重传。默认 false:跳过并计入 skipped(不发起传输)。" + u8"目标端收包是无条件覆盖写,所以默认 false 才能避免重复调用时全量重发。"; + props["overwrite"] = ow; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -6305,6 +6312,8 @@ Json::Value BuildCopyFilesC2COutputSchema() { Json::Value s5(Json::objectValue); s5["type"] = "integer"; props["file_count"] = s5; Json::Value s6(Json::objectValue); s6["type"] = "integer"; props["total_bytes"] = s6; Json::Value s7(Json::objectValue); s7["type"] = "boolean"; props["receiver_ack"] = s7; + Json::Value s8(Json::objectValue); s8["type"] = "integer"; props["skipped"] = s8; + Json::Value s9(Json::objectValue); s9["type"] = "boolean"; props["skip_check_failed"] = s9; Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -6408,6 +6417,9 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM dstDirAnsi.pop_back(); if (dstDirAnsi.empty() || HasDotDotSegment(dstDirAnsi)) return BuildError(id, -32602, "Invalid dst_dir: " + dstDirUtf8); + // 不带尾分隔符的形态,供 overwrite=false 的目录列举使用:客户端拼 "%s\*.*", + // 带尾分隔符会拼成 "C:\\*.*" 导致 FindFirstFile 失败(与 search_file 同一处坑)。 + const std::string dstDirListAnsi = dstDirAnsi; if (posixDst) { // POSIX 目标:接收端把 '\' 当分隔符归一化,接 C:\x 会落成 /C:/x 之类;只收 '/' 根路径。 if (dstDirAnsi[0] != '/' || dstDirAnsi.find('\\') != std::string::npos) @@ -6433,6 +6445,64 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM pathAnsi.push_back(ansi); } + // ===== overwrite=false:先列目标目录一层,跳过已存在的同名顶层项 ===== + // 目标端收包是无条件覆盖写,服务端不预检的话每次调用都会把整份文件重发一遍 + // (实测同一份 11 MB 日志连传两次都重写,且两次返回值完全相同,调用方无从分辨)。 + // 预检只在 overwrite=false 时做;目标目录尚不存在时 ListRemoteTopLevelNames 返回空集, + // 正好等价于「无同名项」。预检本身失败(主机忙/超时/拒绝访问)不回错误,退回全发并 + // 置 skip_check_failed=true——不能让「检查失败」把一次本该成功的传输挡掉。 + const bool overwrite = (args.isMember("overwrite") && args["overwrite"].isBool()) + ? args["overwrite"].asBool() : false; + + int skipped = 0; + bool skipCheckFailed = false; + std::vector sendPathAnsi; + if (overwrite) { + sendPathAnsi = pathAnsi; + } else { + std::set existing; + // POSIX 目标区分大小写,Windows 目标不区分(与目标文件系统语义一致)。 + if (!ListRemoteTopLevelNames(parent, dstId, dstDirListAnsi, existing, !posixDst)) { + skipCheckFailed = true; + sendPathAnsi = pathAnsi; + } else { + for (unsigned int i = 0; i < paths.size(); ++i) { + const std::string u8 = paths[i].asString(); + const size_t sep = u8.find_last_of("\\/"); + const std::string base = (sep == std::string::npos) ? u8 : u8.substr(sep + 1); + const std::string key = posixDst ? base : AsciiLower(base); + if (!base.empty() && existing.count(key)) { ++skipped; continue; } + sendPathAnsi.push_back(pathAnsi[i]); + } + } + } + + // 全部被跳过:直接返回成功,不发起传输。 + if (sendPathAnsi.empty()) { + Json::Value result(Json::objectValue); + Json::Value sc(Json::objectValue); + sc["transfer_id"] = std::string(); + sc["src_id"] = std::to_string(srcId); + sc["dst_id"] = std::to_string(dstId); + sc["dst_dir"] = dstDirUtf8; + sc["file_count"] = (Json::UInt)0; + sc["total_bytes"] = (Json::UInt64)0; + sc["receiver_ack"] = false; + sc["skipped"] = skipped; + sc["skip_check_failed"] = false; + result["structuredContent"] = sc; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"C2C 未传输:") + std::to_string(skipped) + + u8" 个顶层项在目标目录中已存在(overwrite=false),全部跳过。"; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); + } + const uint64_t transferID = GenerateTransferID(); if (!mcp.BeginC2CTransfer(srcId, dstId, transferID)) return BuildError(id, -32003, "Device busy: source or destination host already has a transfer in flight"); @@ -6452,7 +6522,7 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM pkt.insert(pkt.end(), (const BYTE*)&hdr, (const BYTE*)&hdr + sizeof(hdr)); pkt.insert(pkt.end(), dstDirAnsi.begin(), dstDirAnsi.end()); pkt.push_back(0); - for (const std::string& p : pathAnsi) { + for (const std::string& p : sendPathAnsi) { pkt.insert(pkt.end(), p.begin(), p.end()); pkt.push_back(0); } @@ -6529,6 +6599,8 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM // receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执); // Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。 sc["receiver_ack"] = r.recvAck; + sc["skipped"] = skipped; + sc["skip_check_failed"] = skipCheckFailed; result["structuredContent"] = sc; Json::Value content(Json::arrayValue); @@ -6536,6 +6608,10 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM item["type"] = "text"; item["text"] = std::string(u8"C2C 发送完成:") + std::to_string(r.fileCount) + u8" 个文件(" + std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8 + + (skipped ? (std::string(u8";另有 ") + std::to_string(skipped) + u8" 个已存在被跳过") + : std::string()) + + (skipCheckFailed ? std::string(u8";未能预检目标目录(主机忙或超时),本次按全量发送") + : std::string()) + (r.recvAck ? u8"。目标端已确认写入。" : u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。"); content.append(item);