From 3a158a241cdb73cad545782320bd7f6c358a3c50 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Tue, 27 Oct 2026 20:39:22 +0100 Subject: [PATCH] Feature: Support upload_file and download_file on Linux and macOS hosts Both tools used to reject LNX/MAC targets outright. The server now gates on the target client type instead: a POSIX target must pass an absolute POSIX remote path without a backslash or a ".." segment (-32602 otherwise), while Windows targets keep their exact previous behaviour. upload_file needed no new client command; the POSIX receiver already handles COMMAND_SEND_FILE_V2 and derives the destination from the packet name. It now also reports a real receiver_ack: the upload session records dstClientID/transferID, and OnC2CRecvResult matches the 176 acknowledgement from Linux targets, so a destination write failure becomes -32011 and a missing ack (with bytes in flight) becomes -32001. download_file needed two pieces on the POSIX side, both shared by Linux and macOS through common/FileTransferV2.h: a FileCompletePacketV2 per file with a streaming SHA-256 (new self-contained common/sha256_posix.h, since BCrypt is Windows-only) so the server can count completed files and verify digests, and a TOKEN_DOWNLOAD_ERROR reply when the requested paths do not exist or are denied, which the server maps to -32009/-32010 within milliseconds instead of waiting for the stall watchdog. Zero-byte files were lost when uploading to POSIX targets because the worker sends no data chunk for them and the complete packet carries no path, so the receiver had nothing to create. The server now injects a zero-length final chunk for each empty file, only for POSIX targets; Windows targets keep their existing behaviour. Also fixes a download completion edge case found while testing: the client decides entry order, so a directory may arrive after all files (an empty subdirectory, for example), and the directory branch only completed when the directory count alone covered totalFiles. The check is now filesDone + directoryCount >= totalFiles. Verified end to end against a WSL Linux client and a Windows client: upload and download of a tree with a 3 MB binary, a Chinese filename, an empty file and an empty subdirectory all round-trip with matching SHA-256; the documented error paths (-32602, -32009, -32011, -32001) and the Windows upload/download/C2C regressions were exercised as well. Co-Authored-By: deepseek-flash --- common/FileTransferV2.h | 65 +++++++++++- common/sha256_posix.h | 148 ++++++++++++++++++++++++++ docs/Mcp_Design.md | 12 +++ docs/Mcp_FileTransfer_Design.md | 84 ++++++++++++++- linux/README.md | 2 +- server/2015Remote/McpServer.cpp | 181 +++++++++++++++++++++++++------- server/2015Remote/McpServer.h | 9 +- 7 files changed, 451 insertions(+), 50 deletions(-) create mode 100644 common/sha256_posix.h diff --git a/common/FileTransferV2.h b/common/FileTransferV2.h index 295fe72..988bd29 100644 --- a/common/FileTransferV2.h +++ b/common/FileTransferV2.h @@ -26,6 +26,8 @@ #include #include #include +#include +#include "sha256_posix.h" #include #include #include @@ -457,6 +459,32 @@ public: return p; } + // errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类 + // (McpServer::OnDownloadError: 2/3 -> 路径不存在,5 -> 拒绝访问,其余 -> 一般失败)。 + static uint32_t PosixErrnoToWin32(int e) + { + switch (e) { + case ENOENT: return 2; // ERROR_FILE_NOT_FOUND + case ENOTDIR: return 3; // ERROR_PATH_NOT_FOUND + case EACCES: + case EPERM: return 5; // ERROR_ACCESS_DENIED + default: return 2; + } + } + + // 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。 + // 走文件管理器子连接(服务端此时还在等第一批 chunk),让它立即失败而不是等停滞看门狗。 + // 与 Windows 客户端 CFileManager::SendDownloadError 等价。 + static void SendDownloadError(IOCPClient* client, uint32_t win32err) + { + if (client == nullptr) return; + if (win32err == 0) win32err = 2; // ERROR_FILE_NOT_FOUND + uint8_t pkt[1 + sizeof(uint32_t)] = { 0 }; + pkt[0] = (uint8_t)TOKEN_DOWNLOAD_ERROR; + memcpy(pkt + 1, &win32err, sizeof(uint32_t)); + client->Send2Server((char*)pkt, (ULONG)sizeof(pkt)); + } + // 处理 CMD_DOWN_FILES_V2 请求 - 上传文件到服务端 // 格式: [cmd:1][targetDir\0][file1\0][file2\0]...[\0] static void HandleDownFilesV2(const uint8_t* data, size_t len, IOCPClient* client, uint64_t myClientID) @@ -480,19 +508,22 @@ public: if (remotePaths.empty()) { Mprintf("[V2 Send] No files to send\n"); + SendDownloadError(client, 87); // ERROR_INVALID_PARAMETER(与 Windows 客户端一致) return; } // 收集所有文件 (展开目录) std::vector allFiles; std::vector rootCandidates; + int firstErrno = 0; // 首个失败的 errno(全部不存在时回报给服务端) for (const auto& remotePath : remotePaths) { std::string localPath = WinPathToLinux(remotePath); struct stat st; if (stat(localPath.c_str(), &st) != 0) { - Mprintf("[V2 Send] File not found: %s\n", localPath.c_str()); + if (firstErrno == 0) firstErrno = errno ? errno : ENOENT; + Mprintf("[V2 Send] File not found: %s (errno=%d)\n", localPath.c_str(), errno); continue; } @@ -513,7 +544,8 @@ public: } if (allFiles.empty()) { - Mprintf("[V2 Send] No files found\n"); + Mprintf("[V2 Send] No files found (errno=%d)\n", firstErrno); + SendDownloadError(client, PosixErrnoToWin32(firstErrno)); return; } @@ -628,6 +660,9 @@ public: uint64_t offset = 0; std::vector buffer; buffer.reserve(sizeof(FileChunkPacketV2) + targetNameGbk.length() + CHUNK_SIZE); + Sha256 hasher; // 流式 SHA-256:服务端落盘后会用它校验 + bool truncated = false; // 读失败/文件变短 → 不发完成包,避免谎报校验通过 + bool sendOk = true; while (offset < fileSize || (offset == 0 && fileSize == 0)) { size_t toRead = std::min(CHUNK_SIZE, (size_t)(fileSize - offset)); @@ -660,21 +695,26 @@ public: ssize_t n = read(fd, dataPtr, toRead); if (n < 0) { Mprintf("[V2 Send] read failed: errno=%d\n", errno); + truncated = true; break; } + hasher.update(dataPtr, (size_t)n); if ((size_t)n < toRead) { - // 文件读取不完整,调整包大小 + // 文件读取不完整(传输中被截断):调整包大小后作为末块发出, + // 但不发完成包 —— 服务端按原 fileSize 收不全,必须让它失败而不是校验通过。 toRead = n; pkt->dataLength = toRead; buffer.resize(sizeof(FileChunkPacketV2) + targetNameGbk.length() + toRead); isLast = true; pkt->flags |= FFV2_LAST_CHUNK; + truncated = true; } } // 发送 if (!client->Send2Server((char*)buffer.data(), (ULONG)buffer.size())) { Mprintf("[V2 Send] Send failed\n"); + sendOk = false; break; } @@ -682,12 +722,31 @@ public: // 空文件处理 if (fileSize == 0) break; + if (truncated) break; // 已按末块发出,不再续读 // 发送间隔 (避免发送过快) usleep(10000); // 10ms } close(fd); + + // 完成校验包:服务端凭它判定该文件结束并比对 SHA-256(目录项不发)。 + // 与 Windows 客户端 FileBatchTransferWorkerV2 的发送点一致;没有它 MCP + // download_file 的会话永远等不到 filesDone 达标。 + if (sendOk && !truncated) { + FileCompletePacketV2 cpkt; + memset(&cpkt, 0, sizeof(cpkt)); + cpkt.cmd = COMMAND_FILE_COMPLETE_V2; + cpkt.transferID = transferID; + cpkt.srcClientID = myClientID; + cpkt.dstClientID = 0; // 目标是主控端 + cpkt.fileIndex = fileIndex; + cpkt.fileSize = fileSize; + hasher.final(cpkt.sha256); + if (!client->Send2Server((char*)&cpkt, (ULONG)sizeof(cpkt))) { + Mprintf("[V2 Send] Send complete packet failed\n"); + } + } } Mprintf("[V2 Send] Transfer complete: transferID=%llu\n", transferID); diff --git a/common/sha256_posix.h b/common/sha256_posix.h new file mode 100644 index 0000000..f7c3906 --- /dev/null +++ b/common/sha256_posix.h @@ -0,0 +1,148 @@ +/** + * sha256_posix.h - 最小实现 SHA-256(POSIX 侧) + * + * 为什么不用现成的:Windows 侧的 SHA-256 走 BCrypt(common/VerifyV2.h), + * Linux/macOS 没有 BCrypt,也没有 OpenSSL 依赖,而 V2 文件发送要向服务端 + * 回报 FileCompletePacketV2.sha256,必须自己算。 + * + * 只实现 FileTransferV2 需要的流式接口(update/final),不做别的事。 + */ + +#pragma once + +#if defined(_WIN32) || defined(_WIN64) +#error "sha256_posix.h is POSIX-only; Windows uses BCrypt via VerifyV2.h." +#endif + +#include +#include +#include + +class Sha256 +{ +public: + Sha256() { reset(); } + + void reset() + { + static const uint32_t init[8] = { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + }; + memcpy(m_h, init, sizeof(m_h)); + m_bufLen = 0; + m_totalLen = 0; + } + + void update(const void* data, size_t len) + { + const uint8_t* p = (const uint8_t*)data; + m_totalLen += len; + + if (m_bufLen > 0) { + size_t take = 64 - m_bufLen; + if (take > len) take = len; + memcpy(m_buf + m_bufLen, p, take); + m_bufLen += take; + p += take; + len -= take; + if (m_bufLen == 64) { + transform(m_buf); + m_bufLen = 0; + } + } + while (len >= 64) { + transform(p); + p += 64; + len -= 64; + } + if (len > 0) { + memcpy(m_buf, p, len); + m_bufLen = len; + } + } + + // 输出 32 字节摘要;调用后对象可 reset() 复用(不自动 reset,避免隐式行为) + void final(uint8_t out[32]) + { + uint64_t bitLen = m_totalLen * 8; + + // 0x80 + 零填充 + 64 位长度,凑满整块 + uint8_t pad[72]; + memset(pad, 0, sizeof(pad)); + pad[0] = 0x80; + size_t padLen = (m_bufLen < 56) ? (56 - m_bufLen) : (120 - m_bufLen); + update(pad, padLen); + + uint8_t lenBytes[8]; + for (int i = 0; i < 8; ++i) { + lenBytes[i] = (uint8_t)(bitLen >> (56 - 8 * i)); + } + update(lenBytes, sizeof(lenBytes)); + + for (int i = 0; i < 8; ++i) { + out[4 * i] = (uint8_t)(m_h[i] >> 24); + out[4 * i + 1] = (uint8_t)(m_h[i] >> 16); + out[4 * i + 2] = (uint8_t)(m_h[i] >> 8); + out[4 * i + 3] = (uint8_t)(m_h[i]); + } + } + + static void hash(const void* data, size_t len, uint8_t out[32]) + { + Sha256 s; + s.update(data, len); + s.final(out); + } + +private: + static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } + + void transform(const uint8_t block[64]) + { + static const uint32_t K[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + }; + + uint32_t w[64]; + for (int i = 0; i < 16; ++i) { + w[i] = ((uint32_t)block[4 * i] << 24) | ((uint32_t)block[4 * i + 1] << 16) | + ((uint32_t)block[4 * i + 2] << 8) | (uint32_t)block[4 * i + 3]; + } + for (int i = 16; i < 64; ++i) { + uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + + uint32_t a = m_h[0], b = m_h[1], c = m_h[2], d = m_h[3]; + uint32_t e = m_h[4], f = m_h[5], g = m_h[6], h = m_h[7]; + + for (int i = 0; i < 64; ++i) { + uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + uint32_t ch = (e & f) ^ (~e & g); + uint32_t t1 = h + S1 + ch + K[i] + w[i]; + uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + uint32_t maj = (a & b) ^ (a & c) ^ (b & c); + uint32_t t2 = S0 + maj; + + h = g; g = f; f = e; e = d + t1; + d = c; c = b; b = a; a = t1 + t2; + } + + m_h[0] += a; m_h[1] += b; m_h[2] += c; m_h[3] += d; + m_h[4] += e; m_h[5] += f; m_h[6] += g; m_h[7] += h; + } + + uint32_t m_h[8]; + uint8_t m_buf[64]; + size_t m_bufLen; + uint64_t m_totalLen; +}; diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 209c843..f030724 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -685,6 +685,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机 | `-32008` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符 `&\|<>^` 或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符 | 按 `message` 修正参数后重试 | | `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 | | `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 | +| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 | - **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: `)区分开。 - **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。 @@ -846,3 +847,14 @@ Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` - `receiver_ack`:Linux 目标端落盘后会回一包 `TOKEN_C2C_RECV_RESULT=176`(能力位 `CLIENT_CAP_C2C_RECV_ACK=0x0010`),`true` 表示目标端确认写入、`total_bytes` 是实收值;写入失败统一 `-32011`(带 status/errno)。Windows/macOS 目标端不回执,仍为 `false`,需 `list_files` 复核。 - 实施中一个坑:服务端既有的 C2C 中继分支会在源端子连接上挂进度对话框,而 `NotifyProc` 对挂了 `hDlg` 的连接会把后续包交给对话框——源端最后那包结果就被当 V1 文件块吃掉,工具只能超时。现按「该 host 是否有 MCP 的 C2C 会话」跳过对话框,MFC 手动 C2C 不变。 - 协议细节、落盘路径语义(`dst_dir` + 相对公共父目录,Windows 与 POSIX 两种目标端)、回执与错误码映射(含 `-32011`)、限制与实测见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §14。 + +## 16. 增补(2026-10-27:`download_file` / `upload_file` 支持 Linux/macOS 主机) + +此前两个工具把 LNX/MAC 目标端直接拒掉(`-32005`)。现在放开,改动集中在服务端的路径门禁与 POSIX 接收端: + +- **`upload_file` 不需要客户端新指令**:Linux/macOS 的文件接收走 `common/FileTransferV2.h`,`dstClientID != 0` 的包按 C2C 语义落盘,目录由包里的 name 派生。服务端按 `RES_CLIENT_TYPE` 校验 `remote_dir`:POSIX 目标必须是绝对 `/…`、不含 `\`、不含 `..` 段(`-32602`);Windows 目标行为不变。 +- **`download_file`**:POSIX 文件管理器(`common/FileManager.h`)补齐两块——每个文件末尾发 `FileCompletePacketV2`(流式 SHA-256,新增 `common/sha256_posix.h`;读失败/截断不发,不谎报校验通过),以及下载失败时回 `TOKEN_DOWNLOAD_ERROR`(errno→win32,服务端转成 `-32009`/`-32010`,不用等停滞看门狗)。 +- **`upload_file` 的 `receiver_ack`**:Linux 目标端会回 `TOKEN_C2C_RECV_RESULT=176`,服务端在发送完成后等 ≤5 s,`true` 表示已确认写入;回执报错 `-32011`;声明会回执却不回(且传输含字节)`-32001`。Windows/macOS 目标端仍恒为 `false`。 +- **空文件**:worker 对 0 字节文件只发完成包(无路径字段),POSIX 接收端无从建文件。服务端只对 POSIX 目标补一个长度 0 的末块,接收端据此建空文件;Windows 目标的空文件仍不落地(V2 协议既有边界,未改)。 +- 顺带修掉一个下载完成判定的边界:条目顺序由客户端决定,目录可能排在文件之后(如空子目录),`OnFileChunkV2` 改为按 `filesDone + directoryCount >= totalFiles` 判完成,不再出现「文件全部收完还干等超时」。 +- 协议细节、POSIX 路径规则、错误码新语义与实测(含 3 MB 二进制、中文名、空文件、空目录的 SHA-256 往返)见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §15。 diff --git a/docs/Mcp_FileTransfer_Design.md b/docs/Mcp_FileTransfer_Design.md index 9c58861..1d74f19 100644 --- a/docs/Mcp_FileTransfer_Design.md +++ b/docs/Mcp_FileTransfer_Design.md @@ -175,7 +175,7 @@ MCP工具线程 服务端 MessageHandle - 发 `CMD_DOWN_FILES_V2` 前把 `local_dir` 规范化为绝对路径并 `CreateDirectory`;`targetDir` 用 ANSI(MBCS 构建本机路径)。 - 每收到一个 chunk,校验其 `filename` 规范化后**前缀必须在 `local_dir` 内**(防 `..` 穿越,呼应 `FILE_TRANSFER_V2.md §8.3` 已识别的风险);逃逸则置 `error` 并 `CancelIO`。 -- 编码:`remote_path` 走 UTF-8→ANSI(936)(Windows 客户端,复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。 +- 编码:`remote_path` 走 UTF-8→ANSI(936)(复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。POSIX 目标端的路径规则见 §15。 ### 6.5 超时与并发 @@ -248,7 +248,7 @@ MCP工具线程 主连接 (ctx→Send2Client) - V2 无接收方→发送方 ACK:客户端 `HandleFileCompleteV2` 校验失败只打日志(`RecvFileChunkV2` 返回 8,`KernelManager.cpp:1381` 不回传主控)。 - **P2 的 `output.files[].sha256` 恒为空串**:`FileBatchTransferWorkerV2` 内部会为每个文件自算 SHA-256 并写入 `COMMAND_FILE_COMPLETE_V2` 包发给客户端,但该值**不回传调用方**;服务端侧又无导出的 SHA-256 工具函数可自行复算。故 P2 输出不填 sha256(延后 P3:worker 回传哈希,或服务端引入 SHA-256 工具)。传输完整性仍依赖客户端本地 `HandleFileCompleteV2` 校验(与 GUI upload / C2C 同权,属 V2 协议既有边界,非 MCP 引入)。 -- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)。 +- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)——**Linux 目标端的 `receiver_ack` 已实现**,复用 §14 的 176 回执(见 §15),Windows 目标端仍为 `false`。 ### 7.6 overwrite 语义 @@ -309,6 +309,8 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm | (P2)`server/2015Remote/McpServer.h` | `FileTransferSession.tool` 增 `"upload_file"`;新增 `BeginFileUpload(id)`(单设备单传输互斥标记) | | (P2)`server/2015Remote/McpServer.cpp` | `upload_file` schema/实现:无头回调 `UploadSendChunkHeadless` + `CollectLocalFiles` 收集 + overwrite 预检(复用 `list_files` 链路)+ 驱动 `FileBatchTransferWorkerV2`(复用主连接,无子连接路由) | | (P2)`client/KernelManager.cpp` | `COMMAND_SEND_FILE_V2` 分支加懒初始化 `InitFileUpload`(`g_status` 由 0 置 1,见 §7.8) | +| (2026-10-27)`common/FileTransferV2.h` | POSIX 接收端:发送 `FileCompletePacketV2`(含流式 SHA-256)、下载失败回 `TOKEN_DOWNLOAD_ERROR`(errno→Win32 映射);见 §15 | +| (2026-10-27)`common/sha256_posix.h` | 新增:POSIX 侧最小流式 SHA-256(Windows 侧仍走 BCrypt,见 `common/VerifyV2.h`) | **客户端**:`UploadToRemoteV2` / `RecvFileChunkV2` / `FileBatchTransferWorkerV2` 均已存在、未改动;仅 `COMMAND_SEND_FILE_V2` 分支新增懒初始化(见 §7.8)。 @@ -517,3 +519,81 @@ TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端 | 只发一个空目录 | 目录包携带 `totalFiles` → 回执到达,`receiver_ack:true`、`file_count=0`,目录已创建 | | Windows → Windows 回归(原 c2c_test 用例) | 全部与改动前一致,`receiver_ack:false`,耗时 3.2 s(未增加等待) | | `upload_file`/`download_file`(`dstClientID=0`) | 不进回执分支(`FinishC2CItem` 首行即 `dstClientID==0` 返回),行为不变 | + +--- + +## 15. 增补(2026-10-27):`download_file` / `upload_file` 支持 Linux/macOS 主机 + +§6/§7 的原始实现只允许 Windows 目标端(LNX/MAC 直接 `-32005`)。本次打通: + +- **`upload_file`(主控 → 目标端)**:不需要客户端新指令。POSIX 接收端本来就实现了 `COMMAND_SEND_FILE_V2` + (`common/FileTransferV2.h`),`dstClientID != 0` 的包按 C2C 语义处理,目标目录由包里的 name 派生 + (§14.4 的 POSIX 规则)。服务端只放开门禁 + 按目标端类型校验 `remote_dir` 形态。 +- **`download_file`(目标端 → 主控)**:走客户端文件管理器子连接的 `CMD_DOWN_FILES_V2`,Linux/macOS 的 + 文件管理器在 `common/FileManager.h` 里(与 Windows `client/FileManager.cpp` 同构)。缺的两块在 POSIX 接收侧补齐: + +### 15.1 接收端改动(`common/FileTransferV2.h`,Linux 与 macOS 共用) + +1. **发送 `FileCompletePacketV2`**(`SendFilesV2` 每个文件末尾):`cmd(1) transferID(8) srcClientID(8) + dstClientID(8) fileIndex(4) fileSize(8) sha256(32)`,SHA-256 边读边算(新增 `common/sha256_posix.h`, + 自包含流式实现;Windows 侧继续用 BCrypt)。服务端 `OnFileCompleteV2` 凭它计 `filesDone` 并校验摘要—— + 没有它 MCP 的下载会话永远等不到完成判定。 + - 读失败 / 文件在传输中被截断(短读):仍把末块发出去,但**不发**完成包(不谎报校验通过),服务端按 + `fileSize` 收不全而失败。 + - 发送失败(`Send2Server` 返回 false)同样不发完成包。 +2. **下载失败回 `TOKEN_DOWNLOAD_ERROR`**:`[cmd:1][win32err:4 LE]`,与 Windows `CFileManager::SendDownloadError` + 一致。触发点:`remote_paths` 为空(win32 87)、所有路径 stat 失败 / 展开后无文件(首个 errno 映射 + `ENOENT/ENOTDIR→2/3`、`EACCES/EPERM→5`,其余→2)。服务端据此立即失败,不用等停滞看门狗。 + +### 15.2 服务端改动(`server/2015Remote/McpServer.cpp`) + +- `BuildDownloadFile` / `BuildUploadFile`:`RES_CLIENT_TYPE` 为 `LNX`/`MAC` 时按 POSIX 校验路径: + **必须以 `/` 开头、不得含 `\`(会被客户端 `WinPathToLinux` 归一化成 `/`,语义会漂)、不得含 `..` 段**, + 否则 `-32602` 并给出示例;`upload_file` 的 `remote_dir` 单独给 `/` 是合法的(写到根目录,通常因权限回 `-32011`)。 + Windows 目标端行为与之前逐字节一致。 +- `BeginFileUpload(device_id, transfer_id)` 现在登记 `dstClientID`/`transferID`,`OnC2CRecvResult` 同时匹配 + `copy_files_c2c` 与 `upload_file` 的会话(键分别是源端与目标端,都用 `dstClientID + transferID` 定位)。 + `upload_file` 因此也能拿到真实回执:Linux 目标端声明 `CLIENT_CAP_C2C_RECV_ACK`,发送完成后等 ≤5 s, + `receiver_ack` 参与输出。 +- **空文件(仅 POSIX 目标)**:`FileBatchTransferWorkerV2` 对 0 字节文件不发数据块,只发完成包,而完成包 + 没有路径字段,POSIX 接收端无从建文件(会「回执成功但文件不存在」)。服务端在驱动 worker 前,为每个 + 0 字节文件补一个长度 0 的 `FFV2_LAST_CHUNK` 块(名字拼法与 worker 一致:`targetDir + relPath`), + 接收端据此 `open(O_CREAT)`;随后 worker 的完成包只用于去重。**Windows 目标端不注入**——保持原有行为 + (Windows 目标端的空文件仍不会被创建,属 V2 协议既有边界,见 §14.6)。 +- 下载完成判定(F4 的补强):条目顺序由客户端决定,目录可能排在**最后**(如空子目录),所以 + `OnFileChunkV2` 的目录分支现在按 `filesDone + directoryCount >= totalFiles` 判完成。此前只比目录数, + 目录排在文件之后时整次下载会干等到超时(实测 4 个文件全部 COMPLETE 后仍卡 60 s)。 + +### 15.3 工具契约变化 + +| 工具 | 变化 | +|---|---| +| `download_file` | 支持 LNX/MAC 目标端(`remote_path` 用绝对 POSIX 路径);新增错误来源 `-32009`/`-32010`(来自客户端 `TOKEN_DOWNLOAD_ERROR`) | +| `upload_file` | 支持 LNX/MAC 目标端(`remote_dir` 用绝对 POSIX 路径);输出新增 `receiver_ack`(boolean);新增 `-32011`(目标端回执报写入失败)与 `-32001`(声明会回执却不回,且传输含字节) | + +`upload_file` 的错误补充(其余码与 §7.7 一致): + +| 码 | 触发 | +|---|---| +| `-32011` | 目标端回了 176 且 `status != 0`;文案带 status、首个 errno、实收文件数(13/1→权限、2→路径不存在、28→磁盘满) | +| `-32001` | 传输完成但支持回执的目标端在 5 s 内没有回执(目标端可能中途掉线);全 0 字节的传输不判失败(接收端学不到 `totalFiles`,无从回执) | + +`receiver_ack` 语义与 §14.5 一致:`true` 只可能来自 Linux 目标端;Windows 目标与 macOS 目标恒为 `false` +(macOS 编译侧 `macos/main.mm` 没有全局主连接句柄,本次未接线),要确证落盘请用 `list_files` 复核。 + +### 15.4 验证(Debug 实例 6543/6546,WSL Ubuntu 24.04 的 `linux/ghost` 以 yuan(1000) 运行) + +源目录含:`a.txt`(12 B)、`empty.txt`(0 B)、`sub/b.bin`(3 MB)、`emptydir/`、`中文名.txt`(14 B)。 + +| 用例 | 结果 | +|---|---| +| `upload_file` → `/tmp/yama_mcp/final` | 4 文件 + 空目录到位,SHA-256 全对(`ddda4069…`/`e3b0c442…`/`834dcf1d…`/`b2a71864…`),`receiver_ack:true`,`total_bytes=3145754` | +| 同上 `overwrite=false` 重传 | 全部跳过(`skipped=4`),不发包 | +| `download_file` 整目录 | 4 文件 + 空目录,SHA-256 全对,`total_bytes=3145754` | +| 单文件 / 单文件中文名 / 只含空子目录的目录 | 均成功(后者 0.2 s 级返回,不再等超时) | +| `download_file` 不存在的路径 | `-32009`(errno 2 → win32 2) | +| `remote_path` 给 `C:\tmp\x` 或含 `..` | `-32602` | +| `upload_file` 到 `/` 或 `/root/yama_x`(非 root) | `-32011`(errno 13/2) | +| Windows 目标端 `upload_file` / `download_file` / `copy_files_c2c` 回归 | 与改动前一致(Windows 目标的空文件仍不落地,`receiver_ack` 仍为 `false`) | + +注:WSL 重启后 Linux 客户端的 machine-id 会变,`id` 随之改变,测试脚本以运行时 `list_online_hosts` 为准。 diff --git a/linux/README.md b/linux/README.md index 9526452..92a8482 100644 --- a/linux/README.md +++ b/linux/README.md @@ -25,7 +25,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件 | 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 | | 守护进程 | daemonize() | Windows 服务 | ✅ 完整 | | 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux | -| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux | +| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) | | C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) | | 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 | diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index cb64154..011a1cf 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -1750,23 +1750,23 @@ std::string BuildToolsListResult(const Json::Value& id) { } } - // 16) download_file(P6:MCP 文件传输,仅 Windows,安全门:McpFileTransfer=1) + // 16) download_file(P6:MCP 文件传输,安全门:McpFileTransfer=1) // 独立开关(不要求 McpReadonly=0):下载是只读方向(主控落盘),风险可控。 if (CMcpServer::Instance().IsFileTransferEnabled()) { Json::Value tool(Json::objectValue); tool["name"] = "download_file"; - tool["description"] = u8"从指定在线 Windows 主机下载文件或目录到主控本机(V2 协议,逐文件 SHA-256 校验)。remote_path 为远程绝对路径(文件或目录,目录递归下载);local_dir 为本机保存目录;overwrite=false 时跳过已存在文件。返回 files[{path,size,sha256}] 与 total_bytes/skipped。"; + tool["description"] = u8"从指定在线主机下载文件或目录到主控本机(V2 协议,逐文件 SHA-256 校验)。支持 Windows 与 Linux/macOS 主机;remote_path 为远程绝对路径(文件或目录,目录递归下载),Windows 用 D:\\data\\a.txt 这类盘符路径,Linux/macOS 用 /home/user/a.txt 这类绝对 POSIX 路径;local_dir 为本机保存目录;overwrite=false 时跳过已存在文件。返回 files[{path,size,sha256}] 与 total_bytes/skipped。"; tool["inputSchema"] = BuildDownloadFileInputSchema(); tool["outputSchema"] = BuildDownloadFileOutputSchema(); tools.append(tool); } - // 17) upload_file(P2:MCP 文件上传,仅 Windows,安全门:McpFileTransfer=1 且 McpReadonly=0) + // 17) upload_file(P2:MCP 文件上传,安全门:McpFileTransfer=1 且 McpReadonly=0) // 写远程盘,故额外要求关闭只读(与 terminal_* / remote_* 一致)。 if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) { Json::Value tool(Json::objectValue); tool["name"] = "upload_file"; - tool["description"] = u8"把主控本机文件或目录上传到指定在线 Windows 主机的目录(V2 协议,主连接发送)。local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建);overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped;sha256 恒为空(V2 无接收方回执,完整性由客户端本地校验、失败仅记日志)。"; + tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。"; tool["inputSchema"] = BuildUploadFileInputSchema(); tool["outputSchema"] = BuildUploadFileOutputSchema(); tools.append(tool); @@ -4523,7 +4523,7 @@ Json::Value BuildDownloadFileInputSchema() { Json::Value rp(Json::objectValue); rp["type"] = "string"; - rp["description"] = u8"远程绝对路径(文件或目录;目录递归下载),如 C:\\Users\\foo\\Pictures"; + rp["description"] = u8"远程绝对路径(文件或目录;目录递归下载)。Windows 主机用 C:\\Users\\foo\\Pictures,Linux/macOS 主机用 /home/user/data 这类绝对 POSIX 路径"; props["remote_path"] = rp; Json::Value ld(Json::objectValue); @@ -4576,6 +4576,9 @@ Json::Value BuildDownloadFileOutputSchema() { return schema; } +// 词法检查路径是否含 ".." 段(定义在下方 upload_file 辅助区;download_file 先用)。 +static bool HasDotDotSegment(const std::string& path); + // tools/call:download_file(下载远程文件/目录到本机,V2 协议) std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { // 分派门控(独立开关 McpFileTransfer,不要求 McpReadonly=0):即便绕过 tools/list 直调也拒绝。 @@ -4591,10 +4594,10 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); - // 仅 Windows 客户端实现 CMD_DOWN_FILES_V2(client/FileManager.cpp),LNX/MAC 提前拒绝。 + // 目标端类型决定 remote_path 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。 + // LNX/MAC 走 common/FileManager.h 里同一套 CMD_DOWN_FILES_V2(V2 发送器)。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); - if (clientType == "LNX" || clientType == "MAC") - return BuildError(id, -32005, "download_file is only supported on Windows hosts"); + const bool posixTarget = (clientType == "LNX" || clientType == "MAC"); // 客户端须支持 V2 文件传输(否则 CMD_DOWN_FILES_V2 会被静默忽略 → 超时)。 if (!ctx->SupportsFileV2()) @@ -4630,6 +4633,17 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM if (remotePathAnsi.empty()) return BuildError(id, -32602, "Invalid remote_path encoding"); + // POSIX 端 WinPathToLinux 会把 "C:\x" 去盘符改写成 "/x",静默落到别处, + // 所以非 Windows 目标必须先按 POSIX 形态校验(\ 会被客户端归一化成 /,语义会漂)。 + if (posixTarget) { + if (remotePathAnsi[0] != '/') + return BuildError(id, -32602, "remote_path must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/file.txt"); + if (remotePathAnsi.find('\\') != std::string::npos) + return BuildError(id, -32602, "remote_path must not contain backslashes on Linux/macOS hosts; use '/'"); + if (HasDotDotSegment(remotePathAnsi)) + return BuildError(id, -32602, "remote_path must not contain '..' path segments"); + } + CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginFileTransferPending(devId, "download_file", localDirAnsi, remotePathAnsi, overwrite)) return BuildError(id, -32003, "Device busy: another request is pending for this host"); @@ -4835,7 +4849,7 @@ Json::Value BuildUploadFileInputSchema() { Json::Value rd(Json::objectValue); rd["type"] = "string"; - rd["description"] = u8"远程主机的保存目录(不存在则自动创建),如 C:\\uploads"; + rd["description"] = u8"远程主机的保存目录(不存在则自动创建)。Windows 主机如 C:\\uploads,Linux/macOS 主机用 /home/user/uploads 这类绝对 POSIX 路径"; props["remote_dir"] = rd; Json::Value ow(Json::objectValue); @@ -4876,6 +4890,7 @@ Json::Value BuildUploadFileOutputSchema() { Json::Value tb(Json::objectValue); tb["type"] = "integer"; props["total_bytes"] = tb; Json::Value sk(Json::objectValue); sk["type"] = "integer"; props["skipped"] = sk; + Json::Value ra(Json::objectValue); ra["type"] = "boolean"; props["receiver_ack"] = ra; Json::Value schema(Json::objectValue); schema["type"] = "object"; @@ -4900,10 +4915,11 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); - // 仅 Windows 客户端实现 V2 主连接接收链路(与 download_file 一致)。 + // 目标端类型决定 remote_dir 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。 + // POSIX 接收端(common/FileTransferV2.h)按包里的 name 派生落盘路径,不需要专门指令。 CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); - if (clientType == "LNX" || clientType == "MAC") - return BuildError(id, -32005, "upload_file is only supported on Windows hosts"); + const bool posixTarget = (clientType == "LNX" || clientType == "MAC"); + const bool dstAcks = ctx->SupportsC2CRecvAck(); // 目前仅 Linux 接收端会回执 if (!ctx->SupportsFileV2()) return BuildError(id, -32006, "Host does not support V2 file transfer"); @@ -4945,17 +4961,33 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 if (attr & FILE_ATTRIBUTE_DIRECTORY) CollectLocalFiles(localPathAnsi, files); - // 远程保存目录:UTF-8 → 客户端 ANSI(936),去尾斜杠 + 结尾 '\'(作 targetDir 前缀)。 + // 远程保存目录:UTF-8 → 客户端 ANSI(936),去尾部分隔符。 std::string remoteDirAnsi = ToAnsi(remoteDirUtf8, 936); if (remoteDirAnsi.empty()) return BuildError(id, -32602, "Invalid remote_dir encoding"); - while (!remoteDirAnsi.empty() && (remoteDirAnsi.back() == '\\' || remoteDirAnsi.back() == '/')) - remoteDirAnsi.pop_back(); - if (remoteDirAnsi.empty()) - return BuildError(id, -32602, "Invalid remote_dir: " + remoteDirUtf8); - if (HasDotDotSegment(remoteDirAnsi)) - return BuildError(id, -32602, "remote_dir must not contain '..' path segments"); - std::string targetDir = remoteDirAnsi + "\\"; + if (posixTarget) { + // 只接受绝对 POSIX 路径(单独的 "/" 也是合法目标)。 + while (remoteDirAnsi.size() > 1 && remoteDirAnsi.back() == '/') + remoteDirAnsi.pop_back(); + if (remoteDirAnsi[0] != '/') + return BuildError(id, -32602, "remote_dir must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/uploads"); + if (remoteDirAnsi.find('\\') != std::string::npos) + return BuildError(id, -32602, "remote_dir must not contain backslashes on Linux/macOS hosts; use '/'"); + if (HasDotDotSegment(remoteDirAnsi)) + return BuildError(id, -32602, "remote_dir must not contain '..' path segments"); + } else { + while (!remoteDirAnsi.empty() && (remoteDirAnsi.back() == '\\' || remoteDirAnsi.back() == '/')) + remoteDirAnsi.pop_back(); + if (remoteDirAnsi.empty()) + return BuildError(id, -32602, "Invalid remote_dir: " + remoteDirUtf8); + if (HasDotDotSegment(remoteDirAnsi)) + return BuildError(id, -32602, "remote_dir must not contain '..' path segments"); + } + // 拼接前缀:Windows 用 '\';POSIX 用 '/'(根目录不再重复补分隔符)。 + // relPath 里的 '\' 由接收端归一化成 '/',两条路都能落对。 + std::string targetDir = posixTarget + ? (remoteDirAnsi == "/" ? "/" : remoteDirAnsi + "/") + : (remoteDirAnsi + "\\"); // overwrite=false:预检 remote_dir 一层,跳过已存在的同名顶层项(单文件精确、目录整体跳过)。 int skipped = 0; @@ -4999,16 +5031,16 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 return BuildResult(id, result); } - CMcpServer& mcp = CMcpServer::Instance(); - if (!mcp.BeginFileUpload(devId)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); - TransferOptionsV2 opts; - opts.transferID = GenerateTransferID(); + opts.transferID = GenerateTransferID(); // 先定下来:会话要用它匹配 POSIX 目标端回执 opts.srcClientID = 0; // 主控端 opts.dstClientID = devId; opts.enableResume = false; + CMcpServer& mcp = CMcpServer::Instance(); + if (!mcp.BeginFileUpload(devId, opts.transferID)) + return BuildError(id, -32003, "Device busy: another request is pending for this host"); + std::string hash = GetPwdHash(); std::string hmac = GetHMAC(100); @@ -5016,16 +5048,57 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 cbData.parent = parent; cbData.clientID = devId; cbData.deadline = GetTickCount() + (DWORD)timeoutMs; // DWORD 回绕由回调的 (int) 差值判断吸收 + + // 空文件:worker 对 0 字节文件不发数据块,只发 COMMAND_FILE_COMPLETE_V2,而完成包没有路径字段, + // POSIX 接收端无从创建文件(会「回执成功但文件不存在」)。这里替 POSIX 目标端补一个长度 0 的 + // 收尾块(名字拼法与 worker 一致),接收端据此建空文件;随后 worker 的完成包只会被去重。 + // Windows 目标端维持原行为不动。 + std::string xferRoot = GetCommonRoot(sendFiles); + if (posixTarget) { + for (size_t i = 0; i < sendFiles.size(); ++i) { + DWORD a = GetFileAttributesA(sendFiles[i].c_str()); + if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) continue; + WIN32_FILE_ATTRIBUTE_DATA fad; + if (!GetFileAttributesExA(sendFiles[i].c_str(), GetFileExInfoStandard, &fad)) continue; + if ((((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow) != 0) continue; + + std::string name = targetDir + GetRelativePath(xferRoot, sendFiles[i]); + size_t packetSize = sizeof(FileChunkPacketV2) + name.size(); + std::vector packet(packetSize); + auto* pkt = (FileChunkPacketV2*)packet.data(); + pkt->cmd = COMMAND_SEND_FILE_V2; + pkt->transferID = opts.transferID; + pkt->srcClientID = 0; + pkt->dstClientID = devId; + pkt->fileIndex = (uint32_t)i; + pkt->totalFiles = (uint32_t)sendFiles.size(); + pkt->fileSize = 0; + pkt->offset = 0; + pkt->dataLength = 0; + pkt->nameLength = (uint32_t)name.size(); + pkt->flags = FFV2_LAST_CHUNK; + pkt->checksum = 0; + memset(pkt->reserved, 0, sizeof(pkt->reserved)); + if (!name.empty()) memcpy(packet.data() + sizeof(FileChunkPacketV2), name.data(), name.size()); + UploadSendChunkHeadless(&cbData, pkt, packet.data(), (int)packetSize); + } + } + // 同步驱动发送(走主连接);无外来流,无需 WaitFileTransferDone / 收包计数。 int result = FileBatchTransferWorkerV2(sendFiles, targetDir, &cbData, UploadSendChunkHeadless, nullptr, hash, hmac, opts); bool clientOnline = (FindMainContext(parent, devId) != nullptr); - mcp.ClearFileTransfer(devId); - bool ok = (result == 0) && !cbData.failed && clientOnline; + // POSIX 目标端回执:接收端写完最后一包才回(Windows 客户端从不回,dstAcks 为 false)。 + // 回执可能在上面的同步发送过程中就已到达并 latch 进会话,这里的等待通常立即返回。 + CMcpServer::C2CResult ack; + if (ok && dstAcks) mcp.WaitC2CReceiver(devId, 5000, ack); + + mcp.ClearFileTransfer(devId); + // 计算已发送文件(远程完整路径 = targetDir + relPath)与字节数;目录项不计入 files。 - std::string outRoot = GetCommonRoot(sendFiles); + std::string outRoot = xferRoot; std::vector outFiles; uint64_t totalBytes = 0; for (const std::string& f : sendFiles) { @@ -5034,6 +5107,9 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 std::string rel = GetRelativePath(outRoot, f); FileTransferEntry e; e.path = targetDir + rel; + if (posixTarget) { + for (char& c : e.path) if (c == '\\') c = '/'; // relPath 是 Windows 分隔符 + } WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) e.size = ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow; @@ -5043,6 +5119,25 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 outFiles.push_back(std::move(e)); } + // 目标端回了回执但失败:发送端的「全部发出」不算完成,按目标端写入失败上报。 + // 与 copy_files_c2c 的 -32011 同义(那两个 -32009/-32010 是发送端路径语义)。 + if (ok && ack.recvAck && ack.recvStatus != (uint32_t)FEV2_OK) { + const char* why = "write failed"; + if (ack.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied"; + else if (ack.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory"; + else if (ack.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(ack.recvStatus) + + ", errno=" + std::to_string(ack.recvErrno) + + ", files=" + std::to_string(ack.recvFileCount) + ")"); + } + + // 声明了会回执却不回:目标端可能中途掉线,发送端的「已发出」不能当成落盘成功。 + // 例外:整包没有字节(全是空文件)——接收端无从回执。 + if (ok && dstAcks && !ack.recvAck && totalBytes != 0) + return BuildError(id, -32001, "Upload finished sending but the destination did not confirm " + "the write (verify with list_files on the target host)"); + if (ok) { if (parent) { std::string audit = "host " + std::to_string(devId) + " upload_file: " @@ -5067,13 +5162,17 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 structuredContent["files"] = filesArr; structuredContent["total_bytes"] = (Json::UInt64)totalBytes; structuredContent["skipped"] = skipped; + // receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执); + // Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。 + structuredContent["receiver_ack"] = ack.recvAck; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; item["text"] = std::string(u8"上传完成:") + std::to_string(outFiles.size()) + u8" 个文件(" - + std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个。"; + + std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个" + + (ack.recvAck ? u8";目标端已确认写入。" : u8"。"); content.append(item); result["content"] = content; result["isError"] = false; @@ -8065,7 +8164,7 @@ bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string& return true; } -bool CMcpServer::BeginFileUpload(uint64_t device_id) { +bool CMcpServer::BeginFileUpload(uint64_t device_id, uint64_t transfer_id) { // 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。 { std::lock_guard lk(m_PendingMutex); @@ -8074,9 +8173,11 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) { std::lock_guard lk(m_FileXferMutex); if (m_FileXferSessions.find(device_id) != m_FileXferSessions.end()) return false; // 单设备单传输 FileTransferSession s; - s.tool = "upload_file"; - s.startAt = time(nullptr); - s.lastDataAt = std::chrono::steady_clock::now(); + s.tool = "upload_file"; + s.dstClientID = device_id; // 目标端 = 会话宿主,回执按 dstClientID + transferID 匹配 + s.transferID = transfer_id; + s.startAt = time(nullptr); + s.lastDataAt = std::chrono::steady_clock::now(); m_FileXferSessions[device_id] = std::move(s); return true; } @@ -8132,11 +8233,12 @@ void CMcpServer::OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len) { if (res->cmd != TOKEN_C2C_RECV_RESULT || res->dstClientID != dst_id) return; // 身份自洽性 std::lock_guard lk(m_FileXferMutex); - // 目标端在服务端没有自己的会话条目(BeginC2CTransfer 只登记源端),只能按 dstClientID + transferID 反查。 + // copy_files_c2c:目标端在服务端没有会话条目(BeginC2CTransfer 只登记源端),只能反查; + // upload_file:会话键就是目标端本身。两者都用 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.tool != "copy_files_c2c" && s.tool != "upload_file") continue; + if (s.dstClientID != dst_id || s.transferID != res->transferID) continue; if (s.recvAck) return; // 重复回执只认第一包 s.recvAck = true; s.recvStatus = res->status; @@ -8271,10 +8373,9 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const } s.directoryCount++; RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0); - // 纯目录树(空目录、只有子目录):期望文件数 = totalFiles - directoryCount = 0, - // 而客户端对目录项不发 COMPLETE 包,完成判定永远等不到 → 只能干等到超时。 - // 目录项数已覆盖全部条目时直接判完成(totalFiles 含目录项,见 F4)。 - if (s.totalFiles > 0 && s.directoryCount >= s.totalFiles) { + // 目录项不发 COMPLETE 包,而条目顺序由客户端决定(目录可能排在最后,如空子目录), + // 完成判定必须在每一类条目定案后都做:文件数 + 目录数覆盖 totalFiles 即完成(F4)。 + if (s.totalFiles > 0 && s.filesDone + s.directoryCount >= s.totalFiles) { s.done = true; m_FileXferCv.notify_one(); } diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index 2efb620..09fa41a 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -284,9 +284,10 @@ public: bool overwrite); // 登记上传会话(false = 该 host 已有文件会话或一次性挂起请求)。upload 走主连接、 - // 工具线程同步驱动 FileBatchTransferWorkerV2,会话仅为单设备单传输互斥标记 + // 工具线程同步驱动 FileBatchTransferWorkerV2。会话同时用于单设备单传输互斥与 + // POSIX 目标端回执匹配(登记 dstClientID/transferID,见 OnC2CRecvResult)。 // (无 fmSubCtx/streamSubCtx,ClearFileTransfer 对空指针安全)。 - bool BeginFileUpload(uint64_t device_id); + bool BeginFileUpload(uint64_t device_id, uint64_t transfer_id); // ===== C2C 文件传输(copy_files_c2c:源客户端 → 目标客户端,服务端只做中继)===== // 会话键控在「源」设备上:工具线程只等源客户端回传的 TOKEN_C2C_SEND_RESULT, @@ -314,8 +315,8 @@ public: void OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len); // TOKEN_C2C_RECV_RESULT:目标客户端(目前只有 Linux)回传落盘回执。 - // 目标端在服务端没有自己的会话条目(会话键在源端),所以按 dstClientID + transferID 反查; - // 回执可能早于源端结果到达,两条 latch 互相独立,这里绝不置 done。 + // 会话匹配按 dstClientID + transferID:copy_files_c2c 的会话键在源端、只能反查; + // upload_file 的会话键就是目标端本身。回执可能早于源端结果到达,绝不置 done。 void OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len); // 工具线程:等源客户端回传结果;true=全部发出(error=0)。调用方随后 ClearFileTransfer(src)。