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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-27 20:39:22 +01:00
1 parent 4146c73657
commit 3a158a241c
7 files changed
+451 -50

No files matched your search

+62 -3
View File
@@ -26,6 +26,8 @@
#include <iconv.h>
#include <cstring>
#include <cctype>
#include <cerrno>
#include "sha256_posix.h"
#include <string>
#include <vector>
#include <map>
@@ -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<std::string> allFiles;
std::vector<std::string> 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<uint8_t> 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);