Feature: Make Linux a copy_files_c2c destination

The C2C file transfer tool required both ends to be Windows clients. A Linux
client can already land the files: the Windows source worker builds every
entry name by plain string concatenation of dst_dir and the relative path, so
a POSIX dst_dir such as /tmp/recv arrives as "/tmp/recv\sub\file", which the
POSIX receiver normalizes to "/" and writes below an absolute path. What was
missing was the server gate and any way to tell whether the writes succeeded.

The server now accepts LNX/MAC destinations instead of rejecting them, and
validates dst_dir by destination type: an absolute Windows path for Windows
targets, an absolute POSIX path without backslashes for POSIX targets. The
paths and dst_dir arguments also reject embedded NULs, and a POSIX dst_dir is
converted to CP936 exactly so unencodable characters fail loudly instead of
silently becoming '?'.

To make receiver_ack meaningful, a Linux client that receives a C2C transfer
now reports what it wrote. It tracks the outcome per transferID, counting a
directory entry, the last chunk of a file and the completion packet of an
empty file as the three ways an item is settled, with done sets so that
source retries and the trailing completion packet never double count. When
every item is settled it sends one C2CSendResultPacket back on its main
connection under the new TOKEN_C2C_RECV_RESULT (176), with the first errno in
the win32err field and the mapped FEV2_* status. A dedicated token is used
instead of reusing 175 because a host can be the destination of one transfer
while being the source of another, and a destination result must never latch
the source side's done flag.

The server waits up to five seconds for that acknowledgement after the source
reports success, and only for destinations advertising the new
CLIENT_CAP_C2C_RECV_ACK capability bit (Linux only, macOS reports nothing).
A failed acknowledgement becomes -32011 with the status, errno and received
file count; a missing acknowledgement stays an error only for transfers that
actually moved bytes, since a transfer of empty files alone gives the
receiver nothing to learn totalFiles from. Windows destinations are unchanged
and skip the wait entirely.

Verified on the debug instance: Windows to Linux (WSL Ubuntu 24.04) with
subdirectories, an empty directory, a Chinese file name and a 3 MB binary
lands with matching SHA-256 and receiver_ack true; a Windows-style dst_dir
returns -32602; an unwritable POSIX destination returns -32011; the existing
Windows to Windows cases still pass with receiver_ack false and the same
latency.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-27 19:22:12 +01:00
1 parent 4c0e86dcc5
commit 4146c73657
11 files changed
+384 -48

No files matched your search

+110 -16
View File
@@ -1778,7 +1778,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"在两个在线 Windows 主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建)。返回 transfer_id/file_count/total_bytes;receiver_ack 恒为 false —— V2 没有目标端回执,目标端校验失败只记在目标机日志里,需要确证请用 list_files 复核。";
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["inputSchema"] = BuildCopyFilesC2CInputSchema();
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
tools.append(tool);
@@ -5117,7 +5117,7 @@ Json::Value BuildCopyFilesC2CInputSchema() {
Json::Value dir(Json::objectValue);
dir["type"] = "string";
dir["description"] = u8"目标主机保存目录(绝对路径,不存在自动创建),如 D:\\Incoming";
dir["description"] = u8"目标主机保存目录(绝对路径,不存在自动创建):Windows 目标如 D:\\Incoming,Linux/macOS 目标如 /home/user/incoming";
props["dst_dir"] = dir;
Json::Value to(Json::objectValue);
@@ -5203,13 +5203,15 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
return BuildError(id, -32005, "Source host client is too old: upgrade it to a build that supports copy_files_c2c");
if (!dstCtx->SupportsFileV2())
return BuildError(id, -32006, "Destination host does not support V2 file transfer");
// 目标端也必须是 Windows:dst_dir 由源端拼进每个块的 name 字段(绝对 Windows 路径),
// 非 Windows 接收端拿不到 COMMAND_C2C_PREPARE 设置的目标目录,会把 C:\x\y 去盘符后
// 当绝对路径写(common/FileTransferV2.h:224)——落到 /x/y 并要求 root 权限。
// 目标端可以是 Windows,也可以是 Linux/macOS:dst_dir 由源端原样拼进每个块的 name 字段
// (纯字符串拼接,不经 Windows 路径 API),所以 Windows 目标吃绝对 Windows 路径,
// POSIX 目标吃绝对 POSIX 路径——接收端会把 '\' 归一化成 '/' 后按绝对路径落盘
// (common/FileTransferV2.h:224)。形态在下面按 dstType 分别校验。
CString dstType = dstCtx->GetAdditionalData(RES_CLIENT_TYPE);
if (dstType == "LNX" || dstType == "MAC")
return BuildError(id, -32005, "copy_files_c2c requires a Windows destination host: "
"non-Windows clients cannot honour dst_dir yet");
const bool posixDst = (dstType == "LNX" || dstType == "MAC");
// 目标端是否会回落盘回执(目前只有新 Linux 客户端声明)。不会回的(Windows/老客户端)
// 不等回执,避免每次传输都白等几秒。
const bool dstAcks = dstCtx->SupportsC2CRecvAck();
std::string dstDirUtf8 = GetStringArg(args, "dst_dir");
if (dstDirUtf8.empty())
@@ -5227,21 +5229,43 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
timeoutMs = v;
}
// 目标目录:UTF-8 → 目标端 ANSI(936),去尾斜杠后统一补一个 '\'(作 targetDir 前缀)。
std::string dstDirAnsi = ToAnsi(dstDirUtf8, 936);
if (dstDirAnsi.empty())
return BuildError(id, -32602, "Invalid dst_dir encoding");
// 目标目录:UTF-8 → 目标端 ANSI(936),去尾斜杠后统一补一个分隔符(作 targetDir 前缀,
// 源端是 targetDir + 相对路径的裸拼接,前缀必须以分隔符结尾)。
if (dstDirUtf8.find('\0') != std::string::npos) // 报文是 NUL 分隔的,内嵌 NUL 会截断并注入后续字段
return BuildError(id, -32602, "Invalid dst_dir: embedded NUL");
std::string dstDirAnsi;
if (posixDst) {
// 精确转换:CP936 表示不了字符(emoji/西里尔等)直接拒绝,而不是悄悄变成 '?'
// 把文件写进另一个目录。
if (!Utf8ToCpExact(dstDirUtf8, 936, dstDirAnsi) || dstDirAnsi.empty())
return BuildError(id, -32602, "Invalid dst_dir encoding (must be representable in CP936): "
+ dstDirUtf8);
} else {
dstDirAnsi = ToAnsi(dstDirUtf8, 936);
if (dstDirAnsi.empty())
return BuildError(id, -32602, "Invalid dst_dir encoding");
}
while (!dstDirAnsi.empty() && (dstDirAnsi.back() == '\\' || dstDirAnsi.back() == '/'))
dstDirAnsi.pop_back();
if (dstDirAnsi.empty() || HasDotDotSegment(dstDirAnsi))
return BuildError(id, -32602, "Invalid dst_dir: " + dstDirUtf8);
dstDirAnsi += "\\";
if (posixDst) {
// POSIX 目标:接收端把 '\' 当分隔符归一化,接 C:\x 会落成 /C:/x 之类;只收 '/' 根路径。
if (dstDirAnsi[0] != '/' || dstDirAnsi.find('\\') != std::string::npos)
return BuildError(id, -32602, "Invalid dst_dir for a Linux/macOS destination: use an "
"absolute POSIX path such as /home/user/incoming");
dstDirAnsi += "/";
} else {
dstDirAnsi += "\\";
}
std::vector<std::string> pathAnsi;
for (unsigned int i = 0; i < paths.size(); ++i) {
if (!paths[i].isString())
return BuildError(id, -32602, "paths must be an array of strings");
const std::string u8 = paths[i].asString();
if (u8.find('\0') != std::string::npos)
return BuildError(id, -32602, "Invalid path: embedded NUL");
std::string ansi = ToAnsi(u8, 936);
if (ansi.empty())
return BuildError(id, -32602, "Invalid path encoding: " + u8);
@@ -5282,6 +5306,11 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
CMcpServer::C2CResult r;
bool ok = mcp.WaitC2CDone(srcId, timeoutMs, r);
// 源端说「全部发出」后再等目标端回执:只有声明 CLIENT_CAP_C2C_RECV_ACK 的端会回,
// 其余(Windows 目标、老 Linux 客户端、macOS)什么都不发,直接跳过等待。
if (ok && dstAcks) mcp.WaitC2CReceiver(srcId, 5000, r);
mcp.ClearFileTransfer(srcId);
if (!ok) {
@@ -5302,6 +5331,24 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
return BuildError(id, -32000, msg);
}
// 目标端回了回执但失败:源端的「全部发出」不算完成,按目标端写入失败上报。
if (r.recvAck && r.recvStatus != (uint32_t)FEV2_OK) {
const char* why = "write failed";
if (r.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied";
else if (r.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory";
else if (r.recvStatus == (uint32_t)FEV2_DISK_FULL) why = "no space left on device";
return BuildError(id, -32011, std::string("Destination host failed to write the files: ") + why
+ " (status=" + std::to_string(r.recvStatus)
+ ", errno=" + std::to_string(r.recvErrno)
+ ", files=" + std::to_string(r.recvFileCount) + ")");
}
// 声明了会回执却不回:目标端可能中途掉线或包被丢弃,源端的「已发出」不能当成落盘成功。
// 例外:整包没有字节(paths 全是空文件)——客户端不为空文件发任何数据块,也就无从回执。
if (dstAcks && !r.recvAck && r.totalBytes != 0)
return BuildError(id, -32001, "Source finished sending but the destination did not confirm "
"the write (verify with list_files on the destination host)");
// 审计(不可关闭;只记主机 id、目录与字节数,不落文件名以外的内容)
if (parent) {
std::string audit = "host " + std::to_string(srcId) + " -> host " + std::to_string(dstId)
@@ -5320,8 +5367,9 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
sc["dst_dir"] = dstDirUtf8;
sc["file_count"] = (Json::UInt)r.fileCount;
sc["total_bytes"] = (Json::UInt64)r.totalBytes;
// V2 没有「目标端已校验」的回执回到服务端:目标端校验失败只记在目标主机日志里。
sc["receiver_ack"] = false;
// receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执);
// Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。
sc["receiver_ack"] = r.recvAck;
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
@@ -5329,7 +5377,8 @@ 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
+ u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。";
+ (r.recvAck ? u8"。目标端已确认写入。"
: u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。");
content.append(item);
result["content"] = content;
result["isError"] = false;
@@ -8077,6 +8126,28 @@ void CMcpServer::OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len) {
m_FileXferCv.notify_all();
}
void CMcpServer::OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len) {
if (len < sizeof(C2CSendResultPacket)) return;
const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf;
if (res->cmd != TOKEN_C2C_RECV_RESULT || res->dstClientID != dst_id) return; // 身份自洽性
std::lock_guard<std::mutex> lk(m_FileXferMutex);
// 目标端在服务端没有自己的会话条目(BeginC2CTransfer 只登记源端),只能按 dstClientID + transferID 反查。
for (auto& kv : m_FileXferSessions) {
FileTransferSession& s = kv.second;
if (s.tool != "copy_files_c2c" || s.dstClientID != dst_id
|| s.transferID != res->transferID) continue;
if (s.recvAck) return; // 重复回执只认第一包
s.recvAck = true;
s.recvStatus = res->status;
s.recvErrno = res->win32err; // 176 里放的是 errno
s.recvFileCount = res->fileCount;
s.recvBytes = res->totalBytes;
m_FileXferCv.notify_all();
return;
}
}
bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) {
std::unique_lock<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
@@ -8108,6 +8179,29 @@ bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) {
return s.c2cResult && s.error == 0;
}
bool CMcpServer::WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out) {
std::unique_lock<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
if (it == m_FileXferSessions.end()) return false; // 会话已收尾:按「无回执」处理
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (!it->second.recvAck) {
auto slice = std::chrono::milliseconds(250);
auto now = std::chrono::steady_clock::now();
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
if (slice.count() <= 0) break; // 超时:老客户端/Windows 目标根本不回执
m_FileXferCv.wait_for(lk, slice);
}
FileTransferSession& s = it->second;
out.recvAck = s.recvAck;
out.recvStatus = s.recvStatus;
out.recvErrno = s.recvErrno;
out.recvFileCount = s.recvFileCount;
out.recvBytes = s.recvBytes;
return s.recvAck;
}
bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) {
std::string localDir, remotePath;
{