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

+16
View File
@@ -5582,6 +5582,15 @@ BOOL CALLBACK CMy2015RemoteDlg::NotifyProc(CONTEXT_OBJECT* ContextObject)
int cmd = ContextObject->GetBYTE(0);
AUTO_TICK(50, std::to_string(cmd));
// 目标端的 C2C 落盘回执:必须在对话框分支之前截走——目标主机要是正开着远程屏幕/文件管理,
// 主连接上的包会被 hDlg->OnReceiveComplete 吃掉,MCP 侧就永远等不到回执(会被判成写入失败)。
if (cmd == TOKEN_C2C_RECV_RESULT) {
McpServer().OnC2CRecvResult(ContextObject->GetClientID(),
ContextObject->InDeCompressedBuffer.GetBuffer(),
ContextObject->InDeCompressedBuffer.GetBufferLen());
return TRUE;
}
DialogBase* Dlg = (DialogBase*)ContextObject->hDlg;
if (Dlg) {
if (!IsWindow(Dlg->GetSafeHwnd()) || Dlg->IsClosed())
@@ -7034,6 +7043,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
McpServer().OnC2CResult(ContextObject->GetClientID(), szBuffer, len);
break;
}
case TOKEN_C2C_RECV_RESULT: { // copy_files_c2c 目标端落盘回执
// 正常在 NotifyProc 里就截走了(避免被 hDlg 吃掉);这里兜住未运行/直投的路径。
Mprintf("[C2C] 收到目标端回执: dev=%llu len=%u\n",
(unsigned long long)ContextObject->GetClientID(), len);
McpServer().OnC2CRecvResult(ContextObject->GetClientID(), szBuffer, len);
break;
}
case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】
// 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索
// (工具线程已超时返回部分结果)的尾包,原地丢弃即可。
+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;
{
+21
View File
@@ -298,6 +298,12 @@ public:
int32_t workerRc = 0; // FileBatchTransferWorkerV2 返回值
uint32_t fileCount = 0;
uint64_t totalBytes = 0;
// 目标端回执(只有 POSIX 接收端会发;Windows 目标恒为 false)
bool recvAck = false; // 收到了目标端回执
uint32_t recvStatus = 0; // 回执 status(0=写入成功,FEV2_* = 失败原因)
DWORD recvErrno = 0; // 回执 win32err(POSIX 端放 errno)
uint32_t recvFileCount = 0; // 回执 fileCount(实收文件数)
uint64_t recvBytes = 0; // 回执 totalBytes(实收字节数)
};
// 登记 C2C 会话(false = 源设备已有文件会话/挂起请求,或源==目标)。
@@ -307,9 +313,18 @@ public:
// 无对应会话(迟到的结果、MFC 侧手写包)直接忽略。
void OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len);
// TOKEN_C2C_RECV_RESULT:目标客户端(目前只有 Linux)回传落盘回执。
// 目标端在服务端没有自己的会话条目(会话键在源端),所以按 dstClientID + transferID 反查;
// 回执可能早于源端结果到达,两条 latch 互相独立,这里绝不置 done。
void OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len);
// 工具线程:等源客户端回传结果;true=全部发出(error=0)。调用方随后 ClearFileTransfer(src)。
bool WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out);
// 工具线程:源端报告发出后再等目标端回执(仅声明 CLIENT_CAP_C2C_RECV_ACK 的端会回);
// true=收到回执(out.recvStatus 判断成败),false=没有回执(老客户端/超时)。
bool WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out);
// TOKEN_DRIVE_LIST:识别 download_file,存文件管理器子链接并下发 CMD_DOWN_FILES_V2。
// 返回 true=已接管(保持子链接,收尾由 ClearFileTransfer);false=会话已清理(调用方 CancelIO)。
bool OnDownloadDriveList(uint64_t device_id, context* fmSubCtx);
@@ -686,6 +701,12 @@ private:
int32_t c2cWorkerRc = 0; // 结果包 workerRc
uint32_t c2cFileCount = 0; // 结果包 fileCount
uint64_t c2cBytes = 0; // 结果包 totalBytes
// 目标端回执(POSIX 接收端写完最后一包后发的同一个 175 包,dstClientID = 自己)
bool recvAck = false; // 已收到目标端回执
uint32_t recvStatus = 0; // 回执 status(0=写入成功)
DWORD recvErrno = 0; // 回执 win32err(POSIX 端放 errno)
uint32_t recvFileCount = 0; // 回执 fileCount(实收文件数)
uint64_t recvBytes = 0; // 回执 totalBytes(实收字节数)
std::string localDir; // download:本机保存目录(ANSI,结尾 '\')
std::string remotePath; // 客户端远程路径(ANSI,发 CMD_DOWN_FILES_V2 用)
bool overwrite = false; // 是否覆盖已存在文件
+9
View File
@@ -89,6 +89,15 @@ public:
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_PATHS) != 0;
}
// 检查客户端作为 C2C 目标端时是否回落盘回执(TOKEN_C2C_RECV_RESULT)。
// 目前只有 Linux 客户端声明;没有此能力位的老客户端/Windows 端不回执,
// 服务端据此决定要不要等回执,避免给它们白等。
bool SupportsC2CRecvAck() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
if (caps.IsEmpty()) return false;
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_RECV_ACK) != 0;
}
// 检查客户端是否支持屏幕预览(双击主机时拉缩略图)。
bool SupportsScreenPreview() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);