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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-29 15:03:32 +01:00
1 parent cd10d0cc1b
commit 13c02fe50b
2 files changed
+184 -6

No files matched your search

+80 -4
View File
@@ -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<std::string>& names) {
std::set<std::string>& 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<std::string> sendPathAnsi;
if (overwrite) {
sendPathAnsi = pathAnsi;
} else {
std::set<std::string> 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);