Feature: Add copy_files_c2c to transfer files between clients directly
Adds the 54th MCP tool, copy_files_c2c, which asks the source client to push a set of files straight to another online client. Previously the only way to move files between two clients was to download them to the server machine and upload them again, so the data crossed the wire twice and needed free disk on the server. With C2C the server only relays packets and never parses or stores the payload. Protocol. Two new ids in common/commands.h: COMMAND_C2C_SEND_FILES (174), carrying the destination directory followed by a NUL-separated path list, and TOKEN_C2C_SEND_RESULT (175), a fixed 45-byte result packet sent back over the same sub-connection the transfer used. Clients advertise support with the LOGIN_INFOR capability bit CLIENT_CAP_C2C_PATHS (0x0008), exposed server side as Context::SupportsC2CPaths(). File transfer V2 already knew how to push to dstClientID, so the destination side needed no change at all; existing V2 receive paths keep working, and older clients simply do not advertise the bit and are rejected with a clear error instead of hanging. Client. OnC2CSendFiles expands environment variables, collects directories recursively, opens its own sub-connection (with sub-connection auth), and runs FileBatchTransferWorkerV2 in a detached thread, then reports the result on that same connection. Every early exit now reports a structured failure rather than staying silent. The worker needs the process-level InitFileUpload call that the receive path performs lazily, and a source client may never have opened a file manager or received an upload, so the initialization is factored into EnsureV2TransferInited() and called from both paths. Server. copy_files_c2c mirrors the existing upload tool: gates, id parsing, capability checks, path validation, then a session keyed on the source host that WaitC2CDone polls until the result packet arrives. The C2C relay branch used to attach a CDlgFileSend progress dialog to the source's sub-connection; NotifyProc then routed every later packet on that connection to the dialog, which parsed the result packet as a V1 file chunk and dropped it, so the tool always timed out even though the files had arrived. IsC2CTransferPending() now suppresses dialog creation for MCP-driven transfers only, leaving manual Ctrl+V transfers untouched. Errors map to -32001 for a source-side transfer failure, -32010 for access denied, -32009 for a missing path and -32002 for an offline destination. Both hosts must be Windows: the destination is restricted too, because the source embeds dst_dir in each V2 chunk name as an absolute Windows path and only the Windows receiver applies it literally. A Linux or macOS receiver never gets a target directory here (the clipboard flow sets one with COMMAND_C2C_PREPARE, which this path does not send), so it would strip the drive letter and write under / instead. Supporting that needs a prepare packet carrying an explicit path plus an upgrade of those clients, so for now the tool rejects them with -32005 rather than writing somewhere wrong. Verified end to end on the Debug build: three files including a non-ASCII name, an empty directory and a 3 MB binary arrived with matching SHA-256 in 3.2 s, a non-existent destination directory was created, and the negative cases returned the documented codes. mcp_smoke.ps1 passes 41/41 with two new assertions and 27/27 in -SkipHost mode. Design notes, error table and limitations are in docs/Mcp_FileTransfer_Design.md section 14 and docs/Mcp_Design.md section 15. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
27d40f5678
commit
c271911fcb
12 files changed
+729
-11
No files matched your search
+183
-8
@@ -1512,14 +1512,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
|
||||
case COMMAND_SEND_FILE_V2: {
|
||||
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
|
||||
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit。
|
||||
static bool s_v2RecvInited = false;
|
||||
if (!s_v2RecvInited) {
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(*m_cfg, chunkKb, durMs);
|
||||
InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
|
||||
s_v2RecvInited = true;
|
||||
}
|
||||
EnsureV2TransferInited();
|
||||
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
|
||||
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
|
||||
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
|
||||
@@ -1563,6 +1556,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_C2C_SEND_FILES: {
|
||||
// C2C 按路径清单发送:服务端指定「源端路径 + 目标端目录」,见 OnC2CSendFiles。
|
||||
OnC2CSendFiles(szBuffer, ulLength);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_CLIPBOARD_V2: {
|
||||
// C2C 剪贴板请求:被请求发送剪贴板文件到另一个客户端
|
||||
ClipboardRequestV2* req = (ClipboardRequestV2*)szBuffer;
|
||||
@@ -1838,6 +1837,182 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
|
||||
// V2 文件传输模块是进程级的(InitFileUpload/UninitFileUpload 成对),发送与接收共用一次初始化:
|
||||
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit,也不会被发送/接收两个
|
||||
// 入口各自初始化一次(第二次 Init 会重置状态并泄漏前一次的上下文)。
|
||||
void CKernelManager::EnsureV2TransferInited()
|
||||
{
|
||||
static bool s_v2Inited = false;
|
||||
if (s_v2Inited) return;
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(*m_cfg, chunkKb, durMs);
|
||||
int rc = InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
|
||||
if (rc != 0) Mprintf("[V2] InitFileUpload 返回 %d,V2 文件传输可能不可用\n", rc);
|
||||
s_v2Inited = true;
|
||||
}
|
||||
|
||||
// 收集目录下的文件与子目录(语义同 CFileManager::CollectFilesRecursiveV2:
|
||||
// 目录本身先作为一条 V2 目录项,随后是子项)。无成员依赖,主连接侧直接复用。
|
||||
static void CollectFilesForC2C(const std::string& dirPath, std::vector<std::string>& files)
|
||||
{
|
||||
std::string dirEntry = dirPath;
|
||||
while (!dirEntry.empty() && (dirEntry.back() == '\\' || dirEntry.back() == '/'))
|
||||
dirEntry.pop_back();
|
||||
if (!dirEntry.empty()) files.push_back(dirEntry);
|
||||
|
||||
WIN32_FIND_DATAA wfd;
|
||||
HANDLE hFind = FindFirstFileA((dirPath + "*.*").c_str(), &wfd);
|
||||
if (hFind == INVALID_HANDLE_VALUE) return;
|
||||
do {
|
||||
if (wfd.cFileName[0] == '.') continue;
|
||||
std::string fullPath = dirPath + wfd.cFileName;
|
||||
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
|
||||
CollectFilesForC2C(fullPath + "\\", files);
|
||||
else
|
||||
files.push_back(fullPath);
|
||||
} while (FindNextFileA(hFind, &wfd));
|
||||
FindClose(hFind);
|
||||
}
|
||||
|
||||
// 展开 %VAR%(与 CFileManager 的静态 ExpandPath 同语义,展开失败返回原路径)
|
||||
static std::string ExpandPathForC2C(const char* path)
|
||||
{
|
||||
char szExpanded[MAX_PATH * 2] = { 0 };
|
||||
DWORD len = ExpandEnvironmentStringsA(path, szExpanded, (DWORD)sizeof(szExpanded));
|
||||
if (len > 0 && len < (DWORD)sizeof(szExpanded)) return szExpanded;
|
||||
return path;
|
||||
}
|
||||
|
||||
// C2C 按路径清单发送(服务端 → 源客户端)。
|
||||
// 包格式:[C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0](ANSI/936)。
|
||||
// 与 COMMAND_CLIPBOARD_V2 的差别只在文件来源:这里的路径由服务端指定,不取剪贴板/资源管理器选中项。
|
||||
// 数据由本端新开子连接上行,服务端按包内 dstClientID 原样中继到目标客户端的主连接。
|
||||
void CKernelManager::OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength < sizeof(C2CSendFilesPacket)) return;
|
||||
const C2CSendFilesPacket* req = (const C2CSendFilesPacket*)szBuffer;
|
||||
|
||||
const char* p = (const char*)szBuffer + sizeof(C2CSendFilesPacket);
|
||||
const char* end = (const char*)szBuffer + ulLength;
|
||||
std::string targetDir = (p < end) ? std::string(p) : std::string();
|
||||
p += targetDir.size() + 1;
|
||||
|
||||
std::vector<std::string> paths;
|
||||
while (p < end && *p != '\0') {
|
||||
paths.push_back(p);
|
||||
p += strlen(p) + 1;
|
||||
}
|
||||
|
||||
// 收包缓冲在 OnReceive 返回后即失效:先把要用的字段拷出来,线程里只用副本。
|
||||
const uint64_t transferID = req->transferID;
|
||||
const uint64_t dstClientID = req->dstClientID;
|
||||
std::string hash(req->hash, strnlen(req->hash, sizeof(req->hash)));
|
||||
std::string hmac(req->hmac, strnlen(req->hmac, sizeof(req->hmac)));
|
||||
|
||||
// 结果包(服务端 TOKEN_C2C_SEND_RESULT → MCP 等待线程)。任何早退都要回一包,
|
||||
// 否则服务端只能干等超时——这与 download_file 早期的「静默超时」是同一种毛病。
|
||||
auto sendResult = [&](uint32_t status, uint32_t win32err, int32_t workerRc,
|
||||
uint32_t fileCount, uint64_t totalBytes) {
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = status;
|
||||
res.win32err = win32err;
|
||||
res.workerRc = workerRc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
m_ClientObject->Send2Server((char*)&res, sizeof(res));
|
||||
};
|
||||
|
||||
// FileBatchTransferWorkerV2 依赖 g_status==1(InitFileUpload 已调用),否则直接返回 -1。
|
||||
// 源端可能从未打开过文件管理器、也从未接收过上传,所以这里必须显式初始化。
|
||||
EnsureV2TransferInited();
|
||||
|
||||
if (paths.empty() || targetDir.empty()) {
|
||||
Mprintf("[C2C] 路径清单发送请求非法: transferID=%llu, paths=%zu, targetDir=%s\n",
|
||||
transferID, paths.size(), targetDir.c_str());
|
||||
sendResult(FEV2_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集文件:展开环境变量、递归展开目录(目录项本身也发给目标端,用于建空目录)
|
||||
std::vector<std::string> allFiles;
|
||||
DWORD dwFirstErr = 0;
|
||||
for (const std::string& raw : paths) {
|
||||
std::string localPath = ExpandPathForC2C(raw.c_str());
|
||||
DWORD attrs = GetFileAttributesA(localPath.c_str());
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES) {
|
||||
if (dwFirstErr == 0) dwFirstErr = GetLastError();
|
||||
Mprintf("[C2C] 源路径不可访问: %s (win32=%lu)\n", localPath.c_str(), dwFirstErr);
|
||||
continue;
|
||||
}
|
||||
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
|
||||
std::string dirPath = localPath;
|
||||
if (dirPath.back() != '\\') dirPath += '\\';
|
||||
CollectFilesForC2C(dirPath, allFiles);
|
||||
} else {
|
||||
allFiles.push_back(localPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
sendResult(FEV2_FILE_NOT_FOUND,
|
||||
dwFirstErr ? dwFirstErr : (DWORD)ERROR_FILE_NOT_FOUND, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 统计(目录项不计入 fileCount/totalBytes)
|
||||
uint32_t fileCount = 0;
|
||||
uint64_t totalBytes = 0;
|
||||
for (const std::string& f : allFiles) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (!GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) continue;
|
||||
if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
|
||||
fileCount++;
|
||||
totalBytes += ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
|
||||
}
|
||||
|
||||
IOCPClient* pClient = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn);
|
||||
pClient->EnableSubConnAuth(); // V2 文件传输子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
if (!pClient->ConnectServer(m_ClientObject->ServerIP().c_str(), m_ClientObject->ServerPort())) {
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 连接服务器失败\n");
|
||||
sendResult(1001, 0, -1, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
TransferOptionsV2 opts;
|
||||
opts.transferID = transferID;
|
||||
opts.srcClientID = m_MyClientID;
|
||||
opts.dstClientID = dstClientID;
|
||||
opts.enableResume = false; // v1 不做断点续传:失败即整包重发(目标端状态按 transferID 索引)
|
||||
|
||||
std::thread([allFiles, targetDir, pClient, opts, hash, hmac,
|
||||
transferID, dstClientID, fileCount, totalBytes]() {
|
||||
int rc = FileBatchTransferWorkerV2(allFiles, targetDir, pClient,
|
||||
[](void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) -> bool {
|
||||
IOCPClient* client = (IOCPClient*)user;
|
||||
return client->Send2Server((char*)data, size) != FALSE;
|
||||
},
|
||||
nullptr, hash, hmac, opts);
|
||||
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = (rc == 0) ? (uint32_t)FEV2_OK : (uint32_t)1001;
|
||||
res.win32err = 0;
|
||||
res.workerRc = (int32_t)rc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
pClient->Send2Server((char*)&res, sizeof(res));
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 路径清单发送结束: transferID=%llu, %u 个文件, rc=%d\n",
|
||||
transferID, fileCount, rc);
|
||||
}).detach();
|
||||
}
|
||||
|
||||
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength > 8) {
|
||||
|
||||
Reference in new issue
Block a user