diff --git a/server/2015Remote/2015Remote_vs2015.vcxproj b/server/2015Remote/2015Remote_vs2015.vcxproj
index 4644000..9ff093a 100644
--- a/server/2015Remote/2015Remote_vs2015.vcxproj
+++ b/server/2015Remote/2015Remote_vs2015.vcxproj
@@ -361,6 +361,7 @@
+
@@ -478,6 +479,7 @@
+
diff --git a/server/2015Remote/2015Remote_vs2015.vcxproj.filters b/server/2015Remote/2015Remote_vs2015.vcxproj.filters
index f2038a3..916a21b 100644
--- a/server/2015Remote/2015Remote_vs2015.vcxproj.filters
+++ b/server/2015Remote/2015Remote_vs2015.vcxproj.filters
@@ -22,6 +22,7 @@
+
@@ -163,6 +164,7 @@
+
diff --git a/server/2015Remote/FilePreview.cpp b/server/2015Remote/FilePreview.cpp
new file mode 100644
index 0000000..02f1bd5
--- /dev/null
+++ b/server/2015Remote/FilePreview.cpp
@@ -0,0 +1,1147 @@
+// FilePreview.cpp — 文件管理器双击预览的实现(缓存/索引/设备闸门/接收钩子)
+#include "StdAfx.h"
+#include "FilePreview.h"
+
+#include "LangManager.h"
+#include "2015Remote.h" // THIS_CFG / GetThisCfg()
+
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+
+#pragma comment(lib, "bcrypt.lib")
+
+namespace
+{
+const int kStallSeconds = 15;
+const int kTotalSeconds = 120;
+const int kFinishedKeepSec = 60;
+const int kTombstoneSeconds = 24 * 60 * 60;
+const char kEmptySha256[] = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+std::string AsStd(const CString& s) { return std::string((LPCSTR)s); }
+
+std::string ToLowerAscii(std::string s)
+{
+ for (char& c : s) {
+ if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
+ }
+ return s;
+}
+
+std::string BaseNameOf(const std::string& path)
+{
+ size_t pos = path.find_last_of("\\/");
+ return pos == std::string::npos ? path : path.substr(pos + 1);
+}
+
+bool StartsWithNoCase(const std::string& s, const std::string& prefix)
+{
+ if (s.size() < prefix.size()) return false;
+ return _strnicmp(s.c_str(), prefix.c_str(), prefix.size()) == 0;
+}
+} // namespace
+
+// ============================================================================
+// DeviceTransferGate
+// ============================================================================
+DeviceTransferGate& DeviceTransferGate::Instance()
+{
+ static DeviceTransferGate* g = new DeviceTransferGate();
+ return *g;
+}
+
+bool DeviceTransferGate::TryClaim(uint64_t key, uint64_t owner)
+{
+ std::lock_guard lk(m_mtx);
+ if (m_owner.find(key) != m_owner.end()) return false;
+ m_owner[key] = owner;
+ return true;
+}
+
+bool DeviceTransferGate::TryClaimPair(uint64_t a, uint64_t b, uint64_t owner)
+{
+ std::lock_guard lk(m_mtx);
+ if (a == b) {
+ if (m_owner.find(a) != m_owner.end()) return false;
+ m_owner[a] = owner;
+ return true;
+ }
+ if (m_owner.find(a) != m_owner.end() || m_owner.find(b) != m_owner.end())
+ return false;
+ m_owner[a] = owner;
+ m_owner[b] = owner;
+ return true;
+}
+
+void DeviceTransferGate::Release(uint64_t key, uint64_t owner)
+{
+ std::lock_guard lk(m_mtx);
+ auto it = m_owner.find(key);
+ if (it != m_owner.end() && it->second == owner)
+ m_owner.erase(it);
+}
+
+void DeviceTransferGate::ReleasePair(uint64_t a, uint64_t b, uint64_t owner)
+{
+ std::lock_guard lk(m_mtx);
+ auto it = m_owner.find(a);
+ if (it != m_owner.end() && it->second == owner) m_owner.erase(it);
+ it = m_owner.find(b);
+ if (it != m_owner.end() && it->second == owner) m_owner.erase(it);
+}
+
+bool DeviceTransferGate::IsBusy(uint64_t key) const
+{
+ std::lock_guard lk(m_mtx);
+ return m_owner.find(key) != m_owner.end();
+}
+
+// ============================================================================
+// CFilePreviewMgr
+// ============================================================================
+CFilePreviewMgr& CFilePreviewMgr::Instance()
+{
+ // 故意不析构:看门狗线程在进程退出期间不应访问已销毁的 static 对象。
+ static CFilePreviewMgr* g = new CFilePreviewMgr();
+ return *g;
+}
+
+CFilePreviewMgr::CFilePreviewMgr()
+{
+ std::thread([this]() { WatchdogLoop(); }).detach();
+}
+
+CFilePreviewMgr::PrepareResult CFilePreviewMgr::Prepare(
+ uint64_t clientID, const std::string& clientKey,
+ const std::string& remotePath, const std::string& basename,
+ uint64_t size, uint64_t mtimeMs, const std::string& sha256,
+ HWND notifyHwnd, std::string& outPath, std::string& error)
+{
+ outPath.clear();
+ error.clear();
+
+ std::string root = RootDir();
+ if (root.empty()) {
+ error = AsStd(_TR("无法创建预览缓存目录"));
+ return PrepareError;
+ }
+ std::string clientDir = ClientDir(clientKey);
+ if (clientDir.empty() || !EnsureDirA(clientDir)) {
+ error = AsStd(_TR("无法创建预览缓存目录"));
+ return PrepareError;
+ }
+
+ std::vector index;
+ LoadIndex(clientDir, index);
+
+ Meta hit;
+ bool found = false;
+ if (!sha256.empty())
+ found = FindBySha(index, sha256, hit);
+ if (!found)
+ found = FindByPath(index, remotePath, size, mtimeMs, hit);
+
+ if (found) {
+ std::string localPath = clientDir + "\\" + hit.localName;
+ if (VerifyLocalFile(localPath, hit.size, hit.sha256)) {
+ uint64_t now = (uint64_t)time(nullptr);
+ for (auto& m : index) {
+ if (m.remotePath == hit.remotePath && m.localName == hit.localName)
+ m.lastUsed = now;
+ }
+ SaveIndex(clientDir, index);
+ outPath = localPath;
+ return PrepareCached;
+ }
+ }
+
+ // 0 字节文件不走 V2(Windows 发送器不会发任何 chunk)。
+ if (size == 0) {
+ std::string sha = kEmptySha256;
+ std::string localName = MakeLocalName(sha, basename, index, remotePath);
+ std::string localPath = clientDir + "\\" + localName;
+ if (!WriteEmptyFile(localPath)) {
+ error = AsStd(_TR("无法写入预览缓存文件"));
+ return PrepareError;
+ }
+ Meta m;
+ m.remotePath = remotePath;
+ m.size = 0;
+ m.mtimeMs = mtimeMs;
+ m.sha256 = sha;
+ m.localName = localName;
+ m.lastUsed = (uint64_t)time(nullptr);
+ bool replaced = false;
+ for (auto& e : index) {
+ if (e.remotePath == remotePath) { e = m; replaced = true; break; }
+ }
+ if (!replaced) index.push_back(m);
+ SaveIndex(clientDir, index);
+ EnforceCacheLimits(clientDir, index);
+ outPath = localPath;
+ return PrepareCached;
+ }
+
+ uint64_t reqId = 0;
+ {
+ BYTE b[8] = {};
+ if (BCryptGenRandom(NULL, b, sizeof(b), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) {
+ error = AsStd(_TR("无法生成预览请求 ID"));
+ return PrepareError;
+ }
+ memcpy(&reqId, b, sizeof(reqId));
+ if (reqId == 0) reqId = 1;
+ }
+
+ uint64_t gateKey = clientID ? clientID : (Fnv1a64(clientKey) | 0x8000000000000000ULL);
+ if (!DeviceTransferGate::Instance().TryClaim(gateKey, reqId)) {
+ error = AsStd(_TR("正在预览另一个文件,请稍候"));
+ return PrepareError;
+ }
+
+ std::string tempDir = clientDir + "\\.tmp\\" + RandomHex(16) + "\\";
+ if (!EnsureDirA(tempDir)) {
+ DeviceTransferGate::Instance().Release(gateKey, reqId);
+ error = AsStd(_TR("无法创建预览缓存目录"));
+ return PrepareError;
+ }
+
+ Request req;
+ req.id = reqId;
+ req.gateKey = gateKey;
+ req.clientID = clientID;
+ req.size = size;
+ req.mtimeMs = mtimeMs;
+ req.clientKey = clientKey;
+ req.clientDir = clientDir;
+ req.remotePath = remotePath;
+ req.basename = basename;
+ req.sha256 = sha256;
+ req.tempDir = tempDir;
+ req.notifyHwnd = notifyHwnd;
+ req.state = Request::WaitFirst;
+ req.startAt = req.lastDataAt = std::chrono::steady_clock::now();
+
+ {
+ std::lock_guard lk(m_mtx);
+ m_reqs.push_back(req);
+ }
+
+ outPath = tempDir;
+ Mprintf("[Preview] transfer start client=%llu temp=%s\n",
+ (unsigned long long)clientID, tempDir.c_str());
+ return PrepareTransfer;
+}
+
+void CFilePreviewMgr::CancelForHwnd(HWND hwnd)
+{
+ std::lock_guard lk(m_mtx);
+ std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
+ for (auto& req : m_reqs) {
+ if (req.notifyHwnd != hwnd) continue;
+ if (req.state == Request::Done || req.state == Request::Failed ||
+ req.state == Request::Abandoned)
+ continue;
+ req.state = Request::Abandoned;
+ req.lastDataAt = now;
+ DeviceTransferGate::Instance().Release(req.gateKey, req.id);
+ if (req.progressHwnd && ::IsWindow(req.progressHwnd))
+ ::PostMessage(req.progressHwnd, WM_CLOSE, 0, 0);
+ TombstoneLocked(req.tempDir);
+ RemoveTempDir(req.tempDir);
+ req.ctx = nullptr;
+ req.recvName.clear();
+ }
+}
+
+bool CFilePreviewMgr::ObserveChunk(CONTEXT_OBJECT* ctx, const FileChunkPacketV2* pkt,
+ const char* name, ULONG len, uint64_t* transferID)
+{
+ if (!ctx || !pkt || !name || !transferID) return true;
+ *transferID = pkt->transferID;
+
+ // 包里的 filename 不是 NUL 结尾的 C 字符串,必须按 nameLength 截断;
+ // 直接用 strlen/隐式 std::string 会读到相邻内存,把合法文件名误判成越界。
+ size_t maxName = (len > sizeof(FileChunkPacketV2))
+ ? (size_t)(len - sizeof(FileChunkPacketV2)) : 0;
+ size_t nameLen = (pkt->nameLength <= maxName) ? (size_t)pkt->nameLength : maxName;
+ std::string safeName(name, nameLen);
+
+ std::lock_guard lk(m_mtx);
+
+ Request* req = FindByTransferLocked(ctx, pkt->transferID);
+ if (req) {
+ if (req->state == Request::Failed || req->state == Request::Abandoned ||
+ req->state == Request::Done)
+ return false; // 迟到/已失败:调用方取消连接,不能变回普通下载
+ if (!IsSingleFileUnder(req->tempDir, safeName)) {
+ FailLocked(*req, AsStd(_TR("预览文件名越界")));
+ return false;
+ }
+ req->lastDataAt = std::chrono::steady_clock::now();
+ return true;
+ }
+
+ req = FindByPrefixLocked(safeName);
+ if (!req) {
+ // 非预览传输:静默放行(每个 chunk 都会走到这里,不能打印)。
+ return !IsTombstonedLocked(safeName);
+ }
+ if (req->state != Request::WaitFirst) {
+ Mprintf("[Preview] observe unexpected state=%d name=%s\n",
+ (int)req->state, safeName.c_str());
+ return false;
+ }
+
+ if (!IsSingleFileUnder(req->tempDir, safeName)) {
+ Mprintf("[Preview] observe path reject temp=%s name=%s\n",
+ req->tempDir.c_str(), safeName.c_str());
+ FailLocked(*req, AsStd(_TR("预览文件名越界")));
+ return false;
+ }
+ if (pkt->totalFiles != 1 || (pkt->flags & FFV2_DIRECTORY) ||
+ pkt->fileSize > FILE_PREVIEW_MAX_BYTES) {
+ Mprintf("[Preview] observe gate reject total=%u flags=%u size=%llu\n",
+ (unsigned)pkt->totalFiles, (unsigned)pkt->flags,
+ (unsigned long long)pkt->fileSize);
+ FailLocked(*req, AsStd(_TR("文件较大或不支持预览")));
+ return false;
+ }
+
+ req->ctx = ctx;
+ req->transferID = pkt->transferID;
+ req->recvName = safeName;
+ req->state = Request::Transferring;
+ req->startAt = req->lastDataAt = std::chrono::steady_clock::now();
+ *transferID = pkt->transferID;
+ Mprintf("[Preview] first chunk tid=%llu name=%s size=%llu\n",
+ (unsigned long long)pkt->transferID, safeName.c_str(),
+ (unsigned long long)pkt->fileSize);
+ return true;
+}
+
+void CFilePreviewMgr::BindProgressWindow(CONTEXT_OBJECT* ctx, HWND hwnd)
+{
+ std::lock_guard lk(m_mtx);
+ for (auto& req : m_reqs) {
+ if (req.ctx == ctx && req.state == Request::Transferring) {
+ req.progressHwnd = hwnd;
+ return;
+ }
+ }
+}
+
+void CFilePreviewMgr::OnComplete(CONTEXT_OBJECT* ctx, const FileCompletePacketV2* pkt, bool verifyOk)
+{
+ if (!ctx || !pkt) return;
+ std::lock_guard lk(m_mtx);
+
+ Request* req = FindByTransferLocked(ctx, pkt->transferID);
+ if (!req || req->state != Request::Transferring)
+ return;
+
+ if (!verifyOk) {
+ FailLocked(*req, AsStd(_TR("预览文件校验失败")));
+ return;
+ }
+
+ std::string packetSha = HexLower(pkt->sha256, sizeof(pkt->sha256));
+ if (!req->sha256.empty() && _stricmp(req->sha256.c_str(), packetSha.c_str()) != 0) {
+ FailLocked(*req, AsStd(_TR("文件在传输过程中发生变化,请重试")));
+ return;
+ }
+
+ req->state = Request::Done;
+ req->lastDataAt = std::chrono::steady_clock::now();
+ DeviceTransferGate::Instance().Release(req->gateKey, req->id);
+ if (req->progressHwnd && ::IsWindow(req->progressHwnd))
+ ::PostMessage(req->progressHwnd, WM_CLOSE, 0, 0);
+
+ FinalizeJob job;
+ job.requestID = req->id;
+ job.clientDir = req->clientDir;
+ job.remotePath = req->remotePath;
+ job.basename = req->basename;
+ job.tempDir = req->tempDir;
+ job.recvName = req->recvName;
+ job.size = req->size;
+ job.mtimeMs = req->mtimeMs;
+ job.requestedSha = req->sha256;
+ job.packetSha = packetSha;
+ job.notifyHwnd = req->notifyHwnd;
+
+ std::thread([job]() { FinalizeThread(job); }).detach();
+ Mprintf("[Preview] complete tid=%llu verify=%d sha=%s\n",
+ (unsigned long long)pkt->transferID, (int)verifyOk, packetSha.c_str());
+}
+
+void CFilePreviewMgr::FailLocked(Request& req, const std::string& message)
+{
+ if (req.state == Request::Done || req.state == Request::Failed ||
+ req.state == Request::Abandoned)
+ return;
+ req.state = Request::Failed;
+ req.lastDataAt = std::chrono::steady_clock::now();
+ DeviceTransferGate::Instance().Release(req.gateKey, req.id);
+ if (req.progressHwnd && ::IsWindow(req.progressHwnd))
+ ::PostMessage(req.progressHwnd, WM_CLOSE, 0, 0);
+ PostResultLocked(req, false, std::string(), message);
+ TombstoneLocked(req.tempDir);
+ RemoveTempDir(req.tempDir);
+ req.ctx = nullptr;
+ req.recvName.clear();
+}
+
+void CFilePreviewMgr::PostResultLocked(const Request& req, bool ok,
+ const std::string& localPath,
+ const std::string& message)
+{
+ Result* r = new Result();
+ r->ok = ok;
+ r->localPath = localPath;
+ r->remotePath = req.remotePath;
+ r->message = message;
+ r->size = req.size;
+ r->sha256 = req.sha256;
+ PostResult(req.notifyHwnd, r);
+}
+
+void CFilePreviewMgr::PostResult(HWND hwnd, Result* r)
+{
+ if (!r) return;
+ if (hwnd && ::IsWindow(hwnd)) {
+ if (!::PostMessage(hwnd, WM_PREVIEW_RESULT, 0, (LPARAM)r))
+ delete r;
+ } else {
+ delete r;
+ }
+}
+
+void CFilePreviewMgr::TombstoneLocked(const std::string& tempDir)
+{
+ if (tempDir.empty()) return;
+ m_tombstones[tempDir] = std::chrono::steady_clock::now() +
+ std::chrono::seconds(kTombstoneSeconds);
+}
+
+bool CFilePreviewMgr::IsTombstonedLocked(const std::string& name) const
+{
+ for (const auto& kv : m_tombstones) {
+ if (StartsWithNoCase(name, kv.first) && name.size() > kv.first.size())
+ return true;
+ }
+ return false;
+}
+
+CFilePreviewMgr::Request* CFilePreviewMgr::FindByTransferLocked(CONTEXT_OBJECT* ctx, uint64_t transferID)
+{
+ if (transferID == 0) return nullptr;
+ for (auto& req : m_reqs) {
+ if (req.ctx == ctx && req.transferID == transferID)
+ return &req;
+ }
+ return nullptr;
+}
+
+CFilePreviewMgr::Request* CFilePreviewMgr::FindByPrefixLocked(const std::string& name)
+{
+ for (auto& req : m_reqs) {
+ if (req.state != Request::WaitFirst) continue;
+ if (StartsWithNoCase(name, req.tempDir) && name.size() > req.tempDir.size())
+ return &req;
+ }
+ return nullptr;
+}
+
+void CFilePreviewMgr::CleanupRequestLocked(Request& req)
+{
+ RemoveTempDir(req.tempDir);
+ req.ctx = nullptr;
+ req.recvName.clear();
+}
+
+void CFilePreviewMgr::WatchdogLoop()
+{
+ for (;;) {
+ ::Sleep(1000);
+ std::lock_guard lk(m_mtx);
+ auto now = std::chrono::steady_clock::now();
+ CheckTimeoutsLocked(now);
+
+ for (auto it = m_tombstones.begin(); it != m_tombstones.end(); ) {
+ if (it->second <= now) it = m_tombstones.erase(it);
+ else ++it;
+ }
+
+ for (auto it = m_reqs.begin(); it != m_reqs.end(); ) {
+ bool finished = (it->state == Request::Done || it->state == Request::Failed ||
+ it->state == Request::Abandoned);
+ if (finished && now - it->lastDataAt > std::chrono::seconds(kFinishedKeepSec))
+ it = m_reqs.erase(it);
+ else
+ ++it;
+ }
+ }
+}
+
+void CFilePreviewMgr::CheckTimeoutsLocked(std::chrono::steady_clock::time_point now)
+{
+ for (auto& req : m_reqs) {
+ if (req.state != Request::WaitFirst && req.state != Request::Transferring)
+ continue;
+ bool stalled = now - req.lastDataAt > std::chrono::seconds(kStallSeconds);
+ bool tooLong = now - req.startAt > std::chrono::seconds(kTotalSeconds);
+ if (stalled || tooLong) {
+ FailLocked(req, AsStd(stalled ? _TR("预览传输停滞,已取消")
+ : _TR("预览传输超时,已取消")));
+ }
+ }
+}
+
+void CFilePreviewMgr::FinalizeThread(FinalizeJob job)
+{
+ if (job.recvName.empty() || job.packetSha.empty()) {
+ Result* r = new Result();
+ r->ok = false;
+ r->remotePath = job.remotePath;
+ r->size = job.size;
+ r->sha256 = job.packetSha;
+ r->message = AsStd(_TR("预览文件校验失败"));
+ PostResult(job.notifyHwnd, r);
+ RemoveTempDir(job.tempDir);
+ return;
+ }
+
+ std::vector index;
+ LoadIndex(job.clientDir, index);
+
+ // 内容去重:同 sha 的已有缓存(P1 传输完成后也能复用)直接改用它的 localName。
+ Meta sameSha;
+ std::string localName;
+ if (FindBySha(index, job.packetSha, sameSha)) {
+ std::string existing = job.clientDir + "\\" + sameSha.localName;
+ if (VerifyLocalFile(existing, sameSha.size, job.packetSha)) {
+ localName = sameSha.localName;
+ }
+ }
+ if (localName.empty())
+ localName = MakeLocalName(job.packetSha, job.basename, index, job.remotePath);
+
+ std::string finalPath = job.clientDir + "\\" + localName;
+ bool moved = false;
+ if (_stricmp(job.recvName.c_str(), finalPath.c_str()) == 0) {
+ moved = true;
+ } else if (GetFileAttributesA(finalPath.c_str()) != INVALID_FILE_ATTRIBUTES) {
+ // 目标已存在:同内容则删临时文件,不同内容则换一个名字。
+ if (VerifyLocalFile(finalPath, job.size, job.packetSha)) {
+ DeleteFileA(job.recvName.c_str());
+ moved = true;
+ } else {
+ localName = MakeLocalName(job.packetSha, job.basename, index,
+ job.remotePath + "#dup");
+ finalPath = job.clientDir + "\\" + localName;
+ moved = MoveOrCopy(job.recvName, finalPath);
+ }
+ } else {
+ moved = MoveOrCopy(job.recvName, finalPath);
+ }
+
+ if (!moved) {
+ Result* r = new Result();
+ r->ok = false;
+ r->remotePath = job.remotePath;
+ r->size = job.size;
+ r->sha256 = job.packetSha;
+ r->message = AsStd(_TR("无法写入预览缓存文件"));
+ PostResult(job.notifyHwnd, r);
+ RemoveTempDir(job.tempDir);
+ return;
+ }
+
+ Meta m;
+ m.remotePath = job.remotePath;
+ m.size = job.size;
+ m.mtimeMs = job.mtimeMs;
+ m.sha256 = job.packetSha;
+ m.localName = localName;
+ m.lastUsed = (uint64_t)time(nullptr);
+ bool replaced = false;
+ for (auto& e : index) {
+ if (e.remotePath == job.remotePath) { e = m; replaced = true; break; }
+ }
+ if (!replaced) index.push_back(m);
+ SaveIndex(job.clientDir, index);
+ EnforceCacheLimits(job.clientDir, index);
+ RemoveTempDir(job.tempDir);
+
+ Result* r = new Result();
+ r->ok = true;
+ r->localPath = finalPath;
+ r->remotePath = job.remotePath;
+ r->size = job.size;
+ r->sha256 = job.packetSha;
+ PostResult(job.notifyHwnd, r);
+}
+
+// ============================================================================
+// 缓存/索引
+// ============================================================================
+std::string CFilePreviewMgr::RootDir()
+{
+ static std::mutex mtx;
+ static std::string cached;
+ std::lock_guard lk(mtx);
+ if (!cached.empty()) return cached;
+
+ std::vector candidates;
+ wchar_t exe[MAX_PATH] = {};
+ if (GetModuleFileNameW(NULL, exe, MAX_PATH)) {
+ std::wstring dir(exe);
+ size_t pos = dir.find_last_of(L"\\/");
+ if (pos != std::wstring::npos) dir.resize(pos);
+ candidates.push_back(dir + L"\\Preview");
+ }
+ wchar_t tmp[MAX_PATH] = {};
+ if (GetEnvironmentVariableW(L"TEMP", tmp, MAX_PATH))
+ candidates.push_back(std::wstring(tmp) + L"\\YAMA\\Preview");
+ wchar_t pd[MAX_PATH] = {};
+ if (GetEnvironmentVariableW(L"ProgramData", pd, MAX_PATH))
+ candidates.push_back(std::wstring(pd) + L"\\YAMA\\Preview");
+
+ for (const auto& c : candidates) {
+ if (!IsGbkRepresentable(c)) continue;
+ int rc = SHCreateDirectoryExW(NULL, c.c_str(), NULL);
+ if (rc == ERROR_SUCCESS || rc == ERROR_ALREADY_EXISTS || rc == ERROR_FILE_EXISTS) {
+ cached = WideToGbk(c);
+ return cached;
+ }
+ }
+ return std::string();
+}
+
+std::string CFilePreviewMgr::ClientDir(const std::string& clientKey)
+{
+ std::string root = RootDir();
+ if (root.empty()) return std::string();
+ std::string key;
+ for (char c : clientKey) {
+ if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') || c == '_' || c == '-')
+ key += c;
+ else
+ key += '_';
+ }
+ if (key.empty()) key = "unknown";
+ return root + "\\" + key;
+}
+
+std::string CFilePreviewMgr::IndexPath(const std::string& clientDir)
+{
+ return clientDir + "\\index.txt";
+}
+
+bool CFilePreviewMgr::EnsureDirA(const std::string& dir)
+{
+ if (dir.empty()) return false;
+ int rc = SHCreateDirectoryExA(NULL, dir.c_str(), NULL);
+ return rc == ERROR_SUCCESS || rc == ERROR_ALREADY_EXISTS || rc == ERROR_FILE_EXISTS;
+}
+
+bool CFilePreviewMgr::LoadIndex(const std::string& clientDir, std::vector& out)
+{
+ out.clear();
+ std::ifstream f(IndexPath(clientDir).c_str(), std::ios::binary);
+ if (!f) return false;
+
+ std::string line;
+ while (std::getline(f, line)) {
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (line.empty() || line[0] == '#') continue;
+ std::vector parts;
+ size_t pos = 0;
+ while (pos <= line.size()) {
+ size_t next = line.find('\t', pos);
+ if (next == std::string::npos) { parts.push_back(line.substr(pos)); break; }
+ parts.push_back(line.substr(pos, next - pos));
+ pos = next + 1;
+ }
+ if (parts.size() != 7 || parts[0] != "v1") continue;
+
+ Meta m;
+ m.sha256 = parts[1];
+ if (m.sha256.size() != 64) continue;
+ m.size = _strtoui64(parts[2].c_str(), NULL, 10);
+ m.mtimeMs = _strtoui64(parts[3].c_str(), NULL, 10);
+ m.lastUsed = _strtoui64(parts[4].c_str(), NULL, 10);
+ m.remotePath = Utf8ToGbk(PctDecode(parts[5]));
+ m.localName = Utf8ToGbk(PctDecode(parts[6]));
+ if (m.localName.empty() || m.localName.find_first_of("\\/:") != std::string::npos ||
+ m.localName == "." || m.localName == "..")
+ continue;
+ out.push_back(m);
+ }
+ return true;
+}
+
+bool CFilePreviewMgr::SaveIndex(const std::string& clientDir, const std::vector& v)
+{
+ std::string path = IndexPath(clientDir);
+ char tmp[MAX_PATH] = {};
+ static std::atomic counter(0);
+ sprintf_s(tmp, sizeof(tmp), "%s.%u.%u.tmp", path.c_str(), (unsigned)GetCurrentProcessId(),
+ (unsigned)counter.fetch_add(1));
+ {
+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
+ if (!f) return false;
+ f << "# YAMA preview index v1\n";
+ for (const auto& m : v) {
+ f << "v1\t" << m.sha256
+ << '\t' << m.size
+ << '\t' << m.mtimeMs
+ << '\t' << m.lastUsed
+ << '\t' << PctEncode(GbkToUtf8(m.remotePath))
+ << '\t' << PctEncode(GbkToUtf8(m.localName))
+ << '\n';
+ }
+ f.flush();
+ if (!f) { f.close(); DeleteFileA(tmp); return false; }
+ }
+ if (!MoveFileExA(tmp, path.c_str(), MOVEFILE_REPLACE_EXISTING)) {
+ DeleteFileA(tmp);
+ return false;
+ }
+ return true;
+}
+
+bool CFilePreviewMgr::FindByPath(const std::vector& v, const std::string& remotePath,
+ uint64_t size, uint64_t mtimeMs, Meta& out)
+{
+ for (const auto& m : v) {
+ if (m.remotePath != remotePath || m.size != size) continue;
+ // 元数据命中只比较秒级 mtime(Unix 列表只有秒)。
+ if (m.mtimeMs / 1000 != mtimeMs / 1000) continue;
+ out = m;
+ return true;
+ }
+ return false;
+}
+
+bool CFilePreviewMgr::FindBySha(const std::vector& v, const std::string& sha256, Meta& out)
+{
+ if (sha256.empty()) return false;
+ for (const auto& m : v) {
+ if (_stricmp(m.sha256.c_str(), sha256.c_str()) == 0) { out = m; return true; }
+ }
+ return false;
+}
+
+bool CFilePreviewMgr::VerifyLocalFile(const std::string& path, uint64_t size, const std::string& sha256)
+{
+ DWORD attr = GetFileAttributesA(path.c_str());
+ if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
+ return false;
+ HANDLE h = CreateFileA(path.c_str(), GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (h == INVALID_HANDLE_VALUE) return false;
+ LARGE_INTEGER li = {};
+ bool ok = GetFileSizeEx(h, &li) && li.QuadPart >= 0 && (uint64_t)li.QuadPart == size;
+ CloseHandle(h);
+ if (!ok || sha256.empty()) return ok;
+
+ BYTE digest[32] = {};
+ if (!HashFileSha256(path, digest)) return false;
+ std::string actual = HexLower(digest, sizeof(digest));
+ return _stricmp(actual.c_str(), sha256.c_str()) == 0;
+}
+
+std::string CFilePreviewMgr::MakeLocalName(const std::string& sha256, const std::string& basename,
+ const std::vector& index,
+ const std::string& remotePath)
+{
+ std::string sha = ToLowerAscii(sha256);
+ std::string prefix = sha.size() >= 16 ? sha.substr(0, 16) : sha;
+ std::string base = SanitizeBaseName(basename);
+ std::string cand = prefix + "_" + base;
+
+ auto conflicts = [&](const std::string& name) {
+ for (const auto& m : index) {
+ if (m.localName != name) continue;
+ if (m.remotePath == remotePath) continue;
+ if (_stricmp(m.sha256.c_str(), sha.c_str()) != 0) return true;
+ }
+ return false;
+ };
+
+ if (!conflicts(cand)) return cand;
+ if (sha.size() >= 32) {
+ std::string longer = sha.substr(0, 32) + "_" + base;
+ if (!conflicts(longer)) return longer;
+ }
+ for (int i = 2; i < 1000; ++i) {
+ std::string name = prefix + "_" + std::to_string(i) + "_" + base;
+ if (!conflicts(name)) return name;
+ }
+ return prefix + "_" + std::to_string(GetTickCount64()) + "_" + base;
+}
+
+bool CFilePreviewMgr::WriteEmptyFile(const std::string& path)
+{
+ HANDLE h = CreateFileA(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
+ NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (h == INVALID_HANDLE_VALUE) return false;
+ CloseHandle(h);
+ return true;
+}
+
+void CFilePreviewMgr::EnforceCacheLimits(const std::string& clientDir, std::vector& index)
+{
+ int maxFiles = 200;
+ int maxMB = 512;
+ maxFiles = THIS_CFG.GetInt("settings", "PreviewCacheMaxFiles", 200);
+ maxMB = THIS_CFG.GetInt("settings", "PreviewCacheMaxMB", 512);
+ if (maxFiles <= 0) maxFiles = 200;
+ if (maxMB <= 0) maxMB = 512;
+
+ auto uniqueBytes = [&]() -> uint64_t {
+ std::map seen;
+ for (const auto& m : index) {
+ if (seen.find(m.localName) != seen.end()) continue;
+ std::string p = clientDir + "\\" + m.localName;
+ HANDLE h = CreateFileA(p.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ uint64_t sz = 0;
+ if (h != INVALID_HANDLE_VALUE) {
+ LARGE_INTEGER li = {};
+ if (GetFileSizeEx(h, &li) && li.QuadPart > 0) sz = (uint64_t)li.QuadPart;
+ CloseHandle(h);
+ }
+ seen[m.localName] = sz;
+ }
+ uint64_t total = 0;
+ for (const auto& kv : seen) total += kv.second;
+ return total;
+ };
+
+ uint64_t limitBytes = (uint64_t)maxMB * 1024ULL * 1024ULL;
+ if ((int)index.size() <= maxFiles && uniqueBytes() <= limitBytes)
+ return;
+
+ std::sort(index.begin(), index.end(), [](const Meta& a, const Meta& b) {
+ return a.lastUsed < b.lastUsed;
+ });
+ while ((int)index.size() > maxFiles || uniqueBytes() > limitBytes) {
+ if (index.empty()) break;
+ std::string name = index.front().localName;
+ index.erase(index.begin());
+ bool referenced = false;
+ for (const auto& m : index)
+ if (m.localName == name) { referenced = true; break; }
+ if (!referenced)
+ DeleteFileA((clientDir + "\\" + name).c_str());
+ }
+}
+
+bool CFilePreviewMgr::MoveOrCopy(const std::string& from, const std::string& to)
+{
+ for (int i = 0; i < 3; ++i) {
+ if (MoveFileExA(from.c_str(), to.c_str(), MOVEFILE_REPLACE_EXISTING))
+ return true;
+ ::Sleep(100);
+ }
+ if (CopyFileA(from.c_str(), to.c_str(), FALSE)) {
+ DeleteFileA(from.c_str());
+ return true;
+ }
+ return false;
+}
+
+void CFilePreviewMgr::RemoveTempDir(const std::string& tempDir)
+{
+ if (tempDir.empty()) return;
+ WIN32_FIND_DATAA fd = {};
+ HANDLE h = FindFirstFileA((tempDir + "*").c_str(), &fd);
+ if (h != INVALID_HANDLE_VALUE) {
+ do {
+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
+ DeleteFileA((tempDir + fd.cFileName).c_str());
+ } while (FindNextFileA(h, &fd));
+ FindClose(h);
+ }
+ RemoveDirectoryA(tempDir.c_str());
+}
+
+std::string CFilePreviewMgr::SanitizeBaseName(const std::string& name)
+{
+ std::string base = BaseNameOf(name);
+ std::string cleaned;
+ for (unsigned char c : base) {
+ if (c < 0x20 || c == '<' || c == '>' || c == ':' || c == '"' ||
+ c == '/' || c == '\\' || c == '|' || c == '?' || c == '*')
+ cleaned += '_';
+ else
+ cleaned += (char)c;
+ }
+ while (!cleaned.empty() && (cleaned.back() == '.' || cleaned.back() == ' '))
+ cleaned.pop_back();
+ if (cleaned.empty()) cleaned = "file";
+
+ size_t dot = cleaned.find_last_of('.');
+ std::string ext;
+ std::string stem = cleaned;
+ if (dot != std::string::npos && dot > 0) {
+ ext = cleaned.substr(dot);
+ stem = cleaned.substr(0, dot);
+ }
+ if (ext.size() > 20) ext = ext.substr(0, 20);
+ if (stem.size() > 150) stem = stem.substr(0, 150);
+ return stem + ext;
+}
+
+std::string CFilePreviewMgr::HexLower(const BYTE* data, size_t len)
+{
+ static const char* hex = "0123456789abcdef";
+ std::string out;
+ out.reserve(len * 2);
+ for (size_t i = 0; i < len; ++i) {
+ out += hex[data[i] >> 4];
+ out += hex[data[i] & 0x0F];
+ }
+ return out;
+}
+
+std::string CFilePreviewMgr::RandomHex(size_t bytes)
+{
+ std::vector buf(bytes, 0);
+ if (BCryptGenRandom(NULL, buf.data(), (ULONG)buf.size(),
+ BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) {
+ for (size_t i = 0; i < bytes; ++i)
+ buf[i] = (BYTE)(GetTickCount64() >> ((i % 8) * 8));
+ }
+ return HexLower(buf.data(), buf.size());
+}
+
+uint64_t CFilePreviewMgr::Fnv1a64(const std::string& s)
+{
+ uint64_t h = 1469598103934665603ULL;
+ for (unsigned char c : s) {
+ h ^= c;
+ h *= 1099511628211ULL;
+ }
+ return h;
+}
+
+bool CFilePreviewMgr::IsSingleFileUnder(const std::string& tempDir, const std::string& fullName)
+{
+ if (tempDir.empty() || fullName.size() <= tempDir.size())
+ return false;
+ if (!StartsWithNoCase(fullName, tempDir))
+ return false;
+ std::string rel = fullName.substr(tempDir.size());
+ if (rel.empty() || rel == "." || rel == "..")
+ return false;
+ if (rel.find_first_of("\\/:") != std::string::npos)
+ return false;
+ return true;
+}
+
+bool CFilePreviewMgr::IsExecutableExtension(const std::string& path)
+{
+ std::string base = ToLowerAscii(BaseNameOf(path));
+ size_t dot = base.find_last_of('.');
+ if (dot == std::string::npos || dot + 1 >= base.size()) return false;
+ std::string ext = base.substr(dot + 1);
+
+ static const char* kExts[] = {
+ "exe", "com", "bat", "cmd", "ps1", "psm1", "vbs", "vbe", "js", "jse",
+ "wsf", "wsh", "hta", "msi", "msp", "scr", "cpl", "dll", "lnk", "pif",
+ "reg", "jar", "py", "msc", "scf", "url", "application", "settingcontent-ms"
+ };
+ for (const char* e : kExts) {
+ if (ext == e) return true;
+ }
+ return false;
+}
+
+bool CFilePreviewMgr::IsGbkRepresentable(const std::wstring& w)
+{
+ if (w.empty()) return false;
+ int n = WideCharToMultiByte(936, 0, w.c_str(), (int)w.size(), NULL, 0, NULL, NULL);
+ if (n <= 0) return false;
+ std::string s((size_t)n, '\0');
+ WideCharToMultiByte(936, 0, w.c_str(), (int)w.size(), &s[0], n, NULL, NULL);
+ std::wstring back = GbkToWide(s);
+ return back == w;
+}
+
+std::string CFilePreviewMgr::WideToGbk(const std::wstring& w)
+{
+ if (w.empty()) return std::string();
+ int n = WideCharToMultiByte(936, 0, w.c_str(), (int)w.size(), NULL, 0, NULL, NULL);
+ if (n <= 0) return std::string();
+ std::string s((size_t)n, '\0');
+ WideCharToMultiByte(936, 0, w.c_str(), (int)w.size(), &s[0], n, NULL, NULL);
+ return s;
+}
+
+std::wstring CFilePreviewMgr::GbkToWide(const std::string& s)
+{
+ if (s.empty()) return std::wstring();
+ int n = MultiByteToWideChar(936, 0, s.c_str(), (int)s.size(), NULL, 0);
+ if (n <= 0) return std::wstring();
+ std::wstring w((size_t)n, L'\0');
+ MultiByteToWideChar(936, 0, s.c_str(), (int)s.size(), &w[0], n);
+ return w;
+}
+
+std::string CFilePreviewMgr::GbkToUtf8(const std::string& s)
+{
+ if (s.empty()) return std::string();
+ std::wstring w = GbkToWide(s);
+ if (w.empty()) return s;
+ int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), NULL, 0, NULL, NULL);
+ if (n <= 0) return s;
+ std::string out((size_t)n, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), &out[0], n, NULL, NULL);
+ return out;
+}
+
+std::string CFilePreviewMgr::Utf8ToGbk(const std::string& s)
+{
+ if (s.empty()) return std::string();
+ int wn = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), NULL, 0);
+ if (wn <= 0) return s;
+ std::wstring w((size_t)wn, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &w[0], wn);
+ return WideToGbk(w);
+}
+
+std::string CFilePreviewMgr::PctEncode(const std::string& s)
+{
+ static const char* hex = "0123456789ABCDEF";
+ std::string out;
+ out.reserve(s.size());
+ for (unsigned char c : s) {
+ if (c == '%' || c == '\t' || c == '\n' || c == '\r' || c < 0x20) {
+ out += '%';
+ out += hex[c >> 4];
+ out += hex[c & 0x0F];
+ } else {
+ out += (char)c;
+ }
+ }
+ return out;
+}
+
+std::string CFilePreviewMgr::PctDecode(const std::string& s)
+{
+ std::string out;
+ out.reserve(s.size());
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == '%' && i + 2 < s.size()) {
+ auto val = [](char c) -> int {
+ if (c >= '0' && c <= '9') return c - '0';
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+ return -1;
+ };
+ int hi = val(s[i + 1]);
+ int lo = val(s[i + 2]);
+ if (hi >= 0 && lo >= 0) {
+ out += (char)((hi << 4) | lo);
+ i += 2;
+ continue;
+ }
+ }
+ out += s[i];
+ }
+ return out;
+}
+
+bool CFilePreviewMgr::HashFileSha256(const std::string& path, BYTE out[32])
+{
+ HANDLE h = CreateFileA(path.c_str(), GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (h == INVALID_HANDLE_VALUE) return false;
+
+ BCRYPT_ALG_HANDLE alg = NULL;
+ BCRYPT_HASH_HANDLE hash = NULL;
+ PBYTE obj = NULL;
+ bool ok = false;
+ DWORD objLen = 0, cb = 0;
+
+ if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) != 0)
+ goto done;
+ if (BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&objLen,
+ sizeof(objLen), &cb, 0) != 0)
+ goto done;
+ obj = (PBYTE)HeapAlloc(GetProcessHeap(), 0, objLen);
+ if (!obj) goto done;
+ if (BCryptCreateHash(alg, &hash, obj, objLen, NULL, 0, 0) != 0)
+ goto done;
+ {
+ std::vector buf(64 * 1024);
+ for (;;) {
+ DWORD n = 0;
+ if (!ReadFile(h, buf.data(), (DWORD)buf.size(), &n, NULL)) goto done;
+ if (n == 0) break;
+ if (BCryptHashData(hash, buf.data(), n, 0) != 0) goto done;
+ }
+ }
+ if (BCryptFinishHash(hash, out, 32, 0) != 0) goto done;
+ ok = true;
+
+done:
+ if (hash) BCryptDestroyHash(hash);
+ if (obj) HeapFree(GetProcessHeap(), 0, obj);
+ if (alg) BCryptCloseAlgorithmProvider(alg, 0);
+ CloseHandle(h);
+ return ok;
+}
+
+// ============================================================================
+// 打开文件(UI 线程)
+// ============================================================================
+bool CFilePreviewMgr::OpenLocalFile(HWND owner, const std::string& localPath,
+ const std::string& remotePath, uint64_t size,
+ const std::string& sha256)
+{
+ if (localPath.empty() || GetFileAttributesA(localPath.c_str()) == INVALID_FILE_ATTRIBUTES) {
+ CString msg;
+ msg.Format(_TR("无法打开文件:%s(文件不存在)"), CString(localPath.c_str()));
+ ::MessageBoxA(owner, msg, _TR("提示"), MB_OK | MB_ICONWARNING);
+ return false;
+ }
+
+ if (IsExecutableExtension(localPath)) {
+ CString msg;
+ msg.Format(_TR("远程文件可能执行代码,确定要打开吗?\n\n远程路径:%s\n大小:%llu 字节\nSHA-256:%s"),
+ CString(remotePath.c_str()),
+ (unsigned long long)size,
+ CString(sha256.size() >= 16 ? sha256.substr(0, 16).c_str() : sha256.c_str()));
+ if (::MessageBoxA(owner, msg, _TR("安全确认"),
+ MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) != IDYES) {
+ return false;
+ }
+ }
+
+ HINSTANCE r = ShellExecuteA(owner, "open", localPath.c_str(), NULL, NULL, SW_SHOWNORMAL);
+ if ((INT_PTR)r <= 32) {
+ CString msg;
+ msg.Format(_TR("无法打开文件:%s(可能没有关联程序)"), CString(localPath.c_str()));
+ if (::MessageBoxA(owner, msg, _TR("提示"),
+ MB_OKCANCEL | MB_ICONWARNING) == IDOK) {
+ std::string cmd = "/select,\"" + localPath + "\"";
+ ShellExecuteA(owner, "open", "explorer.exe", cmd.c_str(), NULL, SW_SHOWNORMAL);
+ }
+ return false;
+ }
+ return true;
+}
diff --git a/server/2015Remote/FilePreview.h b/server/2015Remote/FilePreview.h
new file mode 100644
index 0000000..af0faed
--- /dev/null
+++ b/server/2015Remote/FilePreview.h
@@ -0,0 +1,201 @@
+// FilePreview.h — 文件管理器双击预览:设备传输闸门、平铺缓存、索引与接收挂钩
+//
+// 设计见 docs/FilePreview_Design.md。本文件只负责“非 UI”部分:
+// - DeviceTransferGate:预览与 MCP 三个文件传输入口共用的设备级原子闸门;
+// - 平铺缓存/索引:Preview\\_ + index.txt;
+// - 接收钩子:ObserveChunk / OnComplete(Windows 流式子连接与 Unix 同连接两处调用);
+// - 结果通过 WM_PREVIEW_RESULT 投递回文件管理器对话框,由 UI 线程确认并打开。
+#pragma once
+
+#include "StdAfx.h"
+#include
+
+#include
+#include
+#include