Feature: double-click file preview in the classic file manager #10

Merged
yuanyuanxiang merged 10 commits from feature/file-preview into main 2026-12-05 15:59:14 +00:00
Owner

概述

为经典文件管理器(CFileManagerDlg)增加双击预览:本地文件用系统默认程序打开;远程 ≤8 MiB 文件复用既有 V2 传输拉回主控端预览缓存,校验后打开,命中缓存则免传输。设计见 docs/FilePreview_Design.md(修订版 3)。

主要改动

  • 远程哈希查询协议:COMMAND_FILE_HASH/TOKEN_FILE_HASH(182/183)、CLIENT_CAP_FILE_HASH(0x100000)、FILE_PREVIEW_MAX_BYTES 宏;Windows/Linux/macOS/Android 客户端实现(client/FileManager.cpp、common/FileManager.h)。
  • 预览管理器(新增 server/2015Remote/FilePreview.h/.cpp):平铺缓存 + index.txt 索引、LRU、空文件特殊处理、看门狗、可执行确认、逐块路径约束。
  • 两条 V2 接收路径都挂钩:Windows 流式子连接(2015RemoteDlg.cpp/CDlgFileSend.cpp)与 Unix 同连接(FileManagerDlg.cpp 的 OnRecvFileV2Chunk/Complete)。
  • 设备级传输闸门:预览与 MCP 文件传输原子互斥(McpServer.cpp),全局锁顺序 DeviceGate → m_PendingMutex → m_FileXferMutex。
  • 能力位从主连接解析;老客户端(ConnAuth 缺失、ID=0)靠随机 tempDir 前缀绑定;size+mtime 降级命中。
  • 文案本地化(en_US/zh_TW/de_DE)、能力矩阵文档更新。

测试计划

  • 本地双击文件/目录、本地搜索结果第 3 列路径打开
  • Windows 流式路径远程小文件预览 + 二次命中免传输
  • Linux/macOS/Android 同连接路径预览 + 命中
  • >8 MiB 拒绝、0 字节文件不走 V2
  • 内容变化重传、缓存损坏自愈
  • 老客户端(无哈希/未 ConnAuth)降级与绑定
  • 可执行/脚本确认框(按本地扩展名)、恶意 chunk 逐块路径约束拒绝
  • 预览 ↔ MCP download_file 并发原子互斥、无死锁
  • NAT/FRP 下两个老客户端不共用缓存

注:跨路径去重、索引丢失按哈希前缀恢复属 P2(依赖预取哈希)。

## 概述 为经典文件管理器(`CFileManagerDlg`)增加双击预览:本地文件用系统默认程序打开;远程 ≤8 MiB 文件复用既有 V2 传输拉回主控端预览缓存,校验后打开,命中缓存则免传输。设计见 `docs/FilePreview_Design.md`(修订版 3)。 ## 主要改动 - **远程哈希查询协议**:`COMMAND_FILE_HASH`/`TOKEN_FILE_HASH`(182/183)、`CLIENT_CAP_FILE_HASH`(0x100000)、`FILE_PREVIEW_MAX_BYTES` 宏;Windows/Linux/macOS/Android 客户端实现(`client/FileManager.cpp`、`common/FileManager.h`)。 - **预览管理器**(新增 `server/2015Remote/FilePreview.h/.cpp`):平铺缓存 + `index.txt` 索引、LRU、空文件特殊处理、看门狗、可执行确认、逐块路径约束。 - **两条 V2 接收路径都挂钩**:Windows 流式子连接(`2015RemoteDlg.cpp`/`CDlgFileSend.cpp`)与 Unix 同连接(`FileManagerDlg.cpp` 的 `OnRecvFileV2Chunk/Complete`)。 - **设备级传输闸门**:预览与 MCP 文件传输原子互斥(`McpServer.cpp`),全局锁顺序 DeviceGate → m_PendingMutex → m_FileXferMutex。 - 能力位从主连接解析;老客户端(ConnAuth 缺失、ID=0)靠随机 tempDir 前缀绑定;size+mtime 降级命中。 - 文案本地化(en_US/zh_TW/de_DE)、能力矩阵文档更新。 ## 测试计划 - [ ] 本地双击文件/目录、本地搜索结果第 3 列路径打开 - [ ] Windows 流式路径远程小文件预览 + 二次命中免传输 - [ ] Linux/macOS/Android 同连接路径预览 + 命中 - [ ] >8 MiB 拒绝、0 字节文件不走 V2 - [ ] 内容变化重传、缓存损坏自愈 - [ ] 老客户端(无哈希/未 ConnAuth)降级与绑定 - [ ] 可执行/脚本确认框(按本地扩展名)、恶意 chunk 逐块路径约束拒绝 - [ ] 预览 ↔ MCP download_file 并发原子互斥、无死锁 - [ ] NAT/FRP 下两个老客户端不共用缓存 > 注:跨路径去重、索引丢失按哈希前缀恢复属 P2(依赖预取哈希)。
yuanyuanxiang added 9 commits 2026-12-05 15:42:04 +00:00
Describe the finalized design for previewing remote files from the
file manager: reuse V2 transfer on both the Windows stream sub-connection
and the Unix same-connection path, cache files flat under
Preview\<clientKey>\<hash16>_<basename>, keep a per-client index keyed by
SHA-256, cap single files with FILE_PREVIEW_MAX_BYTES, and require a
confirmation before opening remote executables. Hash queries are an
optional P2 capability; P1 uses the exact size/mtime from the listing.

Co-Authored-By: deepseek-flash
Add COMMAND_FILE_HASH/TOKEN_FILE_HASH (182/183) and the
CLIENT_CAP_FILE_HASH capability so the server can ask a client for a
single file's exact size, mtime and SHA-256 without transferring it.
This is the P2 half of the double-click preview design; old clients do
not advertise the capability and are skipped by the caller.

Windows hashes with BCrypt through the existing VerifyV2 helper; Unix
and Android stream Sha256 while reading. Both clamp the peer-supplied
maxBytes to FILE_PREVIEW_MAX_BYTES, echo the original request path bytes
for correlation, and return TOO_LARGE without reading the file. The Unix
loop also verifies the bytes hashed match stat() so a file changed
mid-read reports an error instead of a mismatched hash.

No existing command changes; the new values are explicit and the four
DefaultCaps branches advertise the capability.

Co-Authored-By: deepseek-flash
Add FilePreview.h/.cpp with the non-UI half of the double-click preview:
a flat per-client cache (Preview\<clientKey>\<hash16>_<basename>), a
per-client index keyed by remote path and SHA-256, size/mtime metadata
hits, the 8 MiB gate, empty-file handling, LRU caps, and the executable
confirmation plus ShellExecute helper.

DeviceTransferGate is the shared device-level claim used by preview and
the MCP file-transfer entry points so one device can only run one file
transfer at a time; C2C claims both src and dst. The receive hooks
(ObserveChunk/OnComplete) are implemented here and called by the file
manager paths in the next commit.

Co-Authored-By: deepseek-flash
Double-clicking a local file now opens it, and a remote file is fetched
through the existing V2 transfer into Preview\<clientKey>\<hash16>_<basename>
and opened with the default program. The cache index is checked first by
remote path + size/mtime; a transfer records the complete packet's SHA-256
and verifies it before moving the file into the cache.

Hook both V2 receive paths: the Windows stream sub-connection observes
the first chunk in MessageHandle and later chunks in CDlgFileSend; the
Unix/Android same-connection path observes in OnRecvFileV2Chunk. A failed
basename bound or path escape cancels the stream. The filename is now
bounded by the packet's nameLength (it is not NUL-terminated), which also
fixes the 1 MiB transfer case where trailing bytes were misread as a path.

Search-result lists use column 3 as the directory and get their own
result flag; the exact size/FILETIME from the listing feeds the 8 MiB gate.
Remote executables require a confirmation before ShellExecute. A Debug-only
WM_APP+0x123 hook drives the same double-click handler for end-to-end tests.

Verified with a Debug x64 server and client: a 1 MiB remote file was
transferred, SHA-256 verified, cached and indexed; a second double-click
hit the cache without a transfer.

Co-Authored-By: deepseek-flash
Preview and MCP must not run file transfers on one device at the same
time: MCP's stream interceptor is device-keyed and not tool-aware, so a
preview stream arriving while an upload/C2C session exists would be
swallowed. Claim the shared DeviceTransferGate in all three MCP entry
points (download/read, upload_file, copy_files_c2c) before touching the
pending/file-transfer registries, and release it in ClearFileTransfer.

C2C claims both src and dst atomically; a failed registry check releases
the claim before returning. The gate is acquired before m_PendingMutex
and m_FileXferMutex to keep the documented order.

Co-Authored-By: deepseek-flash
Add the preview strings to en_US, zh_TW and de_DE (GBK, no '=' in keys;
German uses ASCII transliterations where GBK cannot encode umlauts), and
pass the cached entry's SHA-256 back to the open helper so the executable
confirmation shows the actual hash on a cache hit.

Honour PreviewEnabled=0 by leaving double-click unchanged, and document
the preview plus COMMAND_FILE_HASH capability in the client matrix.

Co-Authored-By: deepseek-flash
Release the DeviceTransferGate only after leaving m_PendingMutex in the
three MCP begin paths, matching the documented gate -> pending -> xfer
order (the gate mutex is brief, but this keeps the order explicit and
avoids future nesting mistakes).

Also short-circuit ObserveChunk when there are no preview requests or
tombstones, so ordinary V2 chunk paths do not scan the preview maps.

Co-Authored-By: deepseek-flash
When the main connection advertises CLIENT_CAP_FILE_HASH, double-click
sends COMMAND_FILE_HASH first and continues from the async
TOKEN_FILE_HASH response (posted to the UI thread). A matching SHA-256
opens the cached copy without a transfer, including content found under
a different remote path; the new path is added to the index. Too-large
and error responses are handled, and a 5 second timeout falls back to the
P1 size/mtime path.

The response parser is based on FileHashResponseHeader and the echoed
request path; pending state is cleared on close and the hash timer is
killed with the dialog.

Verified with the Debug server and client: a 1 MiB file was hashed,
transferred and cached under its SHA-256; an identical copy at a second
path hit the cache with no new transfer or stream connection.

Co-Authored-By: deepseek-flash
Consume TOKEN_DOWNLOAD_ERROR in the file manager and fail the matching
preview request with the client's win32 code instead of sending
COMMAND_EXCEPTION and leaving the request to the 15 s watchdog.

Key the exact size/mtime metadata by the list's displayed ANSI/GBK text,
not the raw protocol bytes: Linux/macOS send UTF-8 names while GetItemText
returns the process ACP, so non-ASCII files previously missed the metadata
lookup and could not start a preview.

Bind the Unix progress dialog to the preview request so a stalled transfer
closes it on timeout; save the index after LRU eviction; make the local
right-click Open honour search-result paths; reject over-long received
names; and defer abandoned temp-dir deletion to the watchdog.

The new download-error and hash-error strings are added to en_US, zh_TW
and de_DE.

Co-Authored-By: deepseek-flash
yuanyuanxiang left a comment
Author
Owner

文件预览功能代码审查(feature/file-preview)

已通读全部 22 个变更文件(FilePreview.h/.cpp、McpServer 闸门、两条接收路径挂钩、FileManagerDlg 集成、客户端/Unix 哈希、commands.h/context.h),并对照设计文档 v3 逐项核验。总体实现质量高,设计评审阶段提出的主要问题均已在代码中落实。下面先列已验证正确项,再按严重度给出发现。

一、已验证正确 / 设计问题已落实

  • 设备闸门全覆盖(设计 S6 已修复):BeginFileTransferPending、BeginFileUpload、BeginC2CTransfer 三个 MCP 传输入口均在注册表锁之前认领 DeviceTransferGate(C2C 用 TryClaimPair 原子认领 src+dst),失败路径释放。预览与 MCP 共用同一临界区,互斥成立。
  • 锁序正确:闸门为叶锁(仅触碰自身 m_mtx),ClearFileTransfer 在 m_FileXferMutex 作用域之外释放闸门,无 DeviceGate→Pending→FileXfer 的反向嵌套,无死锁风险。
  • 逐 chunk 路径约束强于 MCP:ObserveChunk 对每个 chunk 做 IsSingleFileUnder + MAX_PATH-64 校验,先于写盘;两条接收路径(Windows CDlgFileSend 流式子连接、Unix 同连接)挂钩一致。
  • 首包/name 截断正确:各调用点 name = buf + sizeof(FileChunkPacketV2),nameLength 钳制到 len - sizeof(...),越界包被拒;首包闸门校验 totalFiles==1 / 非目录 / fileSize<=8MiB。
  • 可执行确认按本地扩展名:IsExecutableExtension 覆盖 exe/com/bat/cmd/ps1/msc/scf/url/application/settingcontent-ms 等,OpenLocalFile 用 MB_DEFBUTTON2 二次确认;explorer /select 路径已净化,无引号注入。
  • 协议结构严谨:FileHashResponseHeader pack(1) + static_assert(57 字节);FileCompletePacketV2.sha256[32] 与 OnComplete 的 HexLower 一致。
  • 向后兼容:新增能力位 CLIENT_CAP_FILE_HASH,服务端仅在 SupportsFileHash() 为真时下发 182;旧客户端不声明该位即跳过,旧服务端不认识 182 也不会下发。命令号 182/183、能力位均空闲无冲突。
  • 客户端哈希防御到位:Windows/Unix 均把 maxBytes 钳制到 FILE_PREVIEW_MAX_BYTES;Unix 流式 64KiB SHA-256 处理文件增长(tooLarge)与截断(total!=size→ERROR);空文件回标准空 SHA。
  • 消息/定时器无功能碰撞:WM_PREVIEW_RESULT/HASH_RESP 与既有 WM_MY_MESSAGE/SEARCH/RECVFILEV2 不冲突;kPreviewHashTimer(0x51) 在 OnTimer 中提前 return,不影响进度条 StepIt。

二、发现(按严重度)

[中] 哈希响应路径不匹配会永久卡死该窗口预览 — FileManagerDlg.cpp:1469 OnPreviewHashResult
KillTimer(kPreviewHashTimer) 在路径匹配判断之前无条件执行。若 r->path != expected(重复/迟到/异常响应),内层 if (r->path == expected) 不成立,m_pendingHash 不被清空,而定时器已被杀。此后该对话框所有 BeginRemotePreview 都会因 m_pendingHash 非空而返回“正在预览另一个文件”,直到窗口关闭。正常单请求场景路径必匹配,触发概率低,但属可恢复性缺陷。
建议:把 KillTimer 移入路径匹配分支,或在消费任意响应时统一清空 m_pendingHash。

[低] Done 请求保留 ctx/transferID 60s 且未立墓碑 — FilePreview.cpp:401 OnComplete
完成后 req.ctx 未置空、tempDir 未 TombstoneLocked,与 FailLocked(437-438 行立即 RemoveTempDir + 清 ctx)不一致。当前依赖 GenerateTransferID 的时间单调性避免新旧 transferID 碰撞,风险较低;但建议 Done 时同样清 ctx 并对 tempDir 立墓碑,缩短残留窗口、统一两条结束路径的清理语义。

[低] EnforceCacheLimits 重复开文件 O(n²) — FilePreview.cpp:847
uniqueBytes() 在每轮淘汰循环里重新打开全部缓存文件统计大小,缓存条目多时 CreateFile 调用呈平方级。建议一次性统计后在内存中维护累计字节,淘汰时增量更新。

[低] 并发索引 lost-update — FinalizeThread(624) 与 Prepare(205) 各自 LoadIndex/SaveIndex 无共享锁
两个 finalize/prepare 并发时后写覆盖先写,可能丢条目。设计已接受(仅影响命中率,不影响正确性/安全),此处仅记录确认。

[低] 消息编号进制风格不一致 — FilePreview.h:23/25
既有消息用十进制 WM_USER+300..305,新增用十六进制 WM_USER+0x306/0x307(=774/775)。功能不碰撞,但易被误读为“306 续号”。建议统一为十进制 306/307(仍空闲)或加注释说明。

[低] Windows HandleFileHash 整文件读入内存 + 未拒重解析点 — client/FileManager.cpp
实现把整文件读入 vector<BYTE>(≤8MiB,可接受)而非设计建议的流式;另仅判 FILE_ATTRIBUTE_DIRECTORY,未拒 FILE_ATTRIBUTE_REPARSE_POINT(符号链接会被跟随)。风险低,建议与设计对齐补 reparse 拒绝。

[低] Unix mtimeMs 秒级 — common/FileManager.h
用 st_mtime*1000 而非 st_mtim,与秒级元数据命中一致,仅记录。

[低] 无关范围改动 — IOCPServer.cpp PostRecv 错误日志(GetLastError→WSAGetLastError+peer)
属日志改进,与预览功能无关,建议拆分或在 PR 描述中说明,便于回溯。

三、结论

核心互斥、路径约束、协议与向后兼容均正确,设计评审问题已落实,无阻断性缺陷。建议修复 [中] 哈希响应卡死 项后合并;其余低危项可择机处理或记录跟进。

## 文件预览功能代码审查(feature/file-preview) 已通读全部 22 个变更文件(FilePreview.h/.cpp、McpServer 闸门、两条接收路径挂钩、FileManagerDlg 集成、客户端/Unix 哈希、commands.h/context.h),并对照设计文档 v3 逐项核验。总体实现质量高,设计评审阶段提出的主要问题均已在代码中落实。下面先列已验证正确项,再按严重度给出发现。 ### 一、已验证正确 / 设计问题已落实 - **设备闸门全覆盖(设计 S6 已修复)**:`BeginFileTransferPending`、`BeginFileUpload`、`BeginC2CTransfer` 三个 MCP 传输入口均在注册表锁之前认领 `DeviceTransferGate`(C2C 用 `TryClaimPair` 原子认领 src+dst),失败路径释放。预览与 MCP 共用同一临界区,互斥成立。 - **锁序正确**:闸门为叶锁(仅触碰自身 m_mtx),`ClearFileTransfer` 在 `m_FileXferMutex` 作用域之外释放闸门,无 DeviceGate→Pending→FileXfer 的反向嵌套,无死锁风险。 - **逐 chunk 路径约束强于 MCP**:`ObserveChunk` 对每个 chunk 做 `IsSingleFileUnder` + MAX_PATH-64 校验,先于写盘;两条接收路径(Windows `CDlgFileSend` 流式子连接、Unix 同连接)挂钩一致。 - **首包/name 截断正确**:各调用点 `name = buf + sizeof(FileChunkPacketV2)`,`nameLength` 钳制到 `len - sizeof(...)`,越界包被拒;首包闸门校验 totalFiles==1 / 非目录 / fileSize<=8MiB。 - **可执行确认按本地扩展名**:`IsExecutableExtension` 覆盖 exe/com/bat/cmd/ps1/msc/scf/url/application/settingcontent-ms 等,`OpenLocalFile` 用 MB_DEFBUTTON2 二次确认;explorer /select 路径已净化,无引号注入。 - **协议结构严谨**:`FileHashResponseHeader` pack(1) + static_assert(57 字节);`FileCompletePacketV2.sha256[32]` 与 `OnComplete` 的 HexLower 一致。 - **向后兼容**:新增能力位 `CLIENT_CAP_FILE_HASH`,服务端仅在 `SupportsFileHash()` 为真时下发 182;旧客户端不声明该位即跳过,旧服务端不认识 182 也不会下发。命令号 182/183、能力位均空闲无冲突。 - **客户端哈希防御到位**:Windows/Unix 均把 maxBytes 钳制到 `FILE_PREVIEW_MAX_BYTES`;Unix 流式 64KiB SHA-256 处理文件增长(tooLarge)与截断(total!=size→ERROR);空文件回标准空 SHA。 - **消息/定时器无功能碰撞**:WM_PREVIEW_RESULT/HASH_RESP 与既有 WM_MY_MESSAGE/SEARCH/RECVFILEV2 不冲突;kPreviewHashTimer(0x51) 在 OnTimer 中提前 return,不影响进度条 StepIt。 ### 二、发现(按严重度) **[中] 哈希响应路径不匹配会永久卡死该窗口预览** — `FileManagerDlg.cpp:1469` `OnPreviewHashResult` `KillTimer(kPreviewHashTimer)` 在路径匹配判断之前无条件执行。若 `r->path != expected`(重复/迟到/异常响应),内层 `if (r->path == expected)` 不成立,`m_pendingHash` 不被清空,而定时器已被杀。此后该对话框所有 `BeginRemotePreview` 都会因 `m_pendingHash` 非空而返回“正在预览另一个文件”,直到窗口关闭。正常单请求场景路径必匹配,触发概率低,但属可恢复性缺陷。 建议:把 `KillTimer` 移入路径匹配分支,或在消费任意响应时统一清空 `m_pendingHash`。 **[低] Done 请求保留 ctx/transferID 60s 且未立墓碑** — `FilePreview.cpp:401` `OnComplete` 完成后 `req.ctx` 未置空、tempDir 未 `TombstoneLocked`,与 `FailLocked`(437-438 行立即 RemoveTempDir + 清 ctx)不一致。当前依赖 `GenerateTransferID` 的时间单调性避免新旧 transferID 碰撞,风险较低;但建议 Done 时同样清 ctx 并对 tempDir 立墓碑,缩短残留窗口、统一两条结束路径的清理语义。 **[低] EnforceCacheLimits 重复开文件 O(n²)** — `FilePreview.cpp:847` `uniqueBytes()` 在每轮淘汰循环里重新打开全部缓存文件统计大小,缓存条目多时 CreateFile 调用呈平方级。建议一次性统计后在内存中维护累计字节,淘汰时增量更新。 **[低] 并发索引 lost-update** — `FinalizeThread`(624) 与 `Prepare`(205) 各自 LoadIndex/SaveIndex 无共享锁 两个 finalize/prepare 并发时后写覆盖先写,可能丢条目。设计已接受(仅影响命中率,不影响正确性/安全),此处仅记录确认。 **[低] 消息编号进制风格不一致** — `FilePreview.h:23/25` 既有消息用十进制 `WM_USER+300..305`,新增用十六进制 `WM_USER+0x306/0x307`(=774/775)。功能不碰撞,但易被误读为“306 续号”。建议统一为十进制 306/307(仍空闲)或加注释说明。 **[低] Windows HandleFileHash 整文件读入内存 + 未拒重解析点** — `client/FileManager.cpp` 实现把整文件读入 `vector<BYTE>`(≤8MiB,可接受)而非设计建议的流式;另仅判 `FILE_ATTRIBUTE_DIRECTORY`,未拒 `FILE_ATTRIBUTE_REPARSE_POINT`(符号链接会被跟随)。风险低,建议与设计对齐补 reparse 拒绝。 **[低] Unix mtimeMs 秒级** — `common/FileManager.h` 用 `st_mtime*1000` 而非 `st_mtim`,与秒级元数据命中一致,仅记录。 **[低] 无关范围改动** — `IOCPServer.cpp` PostRecv 错误日志(GetLastError→WSAGetLastError+peer) 属日志改进,与预览功能无关,建议拆分或在 PR 描述中说明,便于回溯。 ### 三、结论 核心互斥、路径约束、协议与向后兼容均正确,设计评审问题已落实,无阻断性缺陷。建议修复 **[中] 哈希响应卡死** 项后合并;其余低危项可择机处理或记录跟进。
yuanyuanxiang added 1 commit 2026-12-05 15:50:12 +00:00
Only consume a TOKEN_FILE_HASH response whose echoed path matches the
pending request, and kill the 5 s timer only in that branch. A late,
duplicate or malformed response previously killed the timer but left
m_pendingHash set, so every later double-click in that window was
rejected as "another preview is in progress" until the dialog closed.

A mismatched response is now ignored and the timer still falls back to
the size/mtime path, which clears the pending state.

Co-Authored-By: deepseek-flash
yuanyuanxiang merged commit ee20326bbf into main 2026-12-05 15:59:14 +00:00
yuanyuanxiang deleted branch feature/file-preview 2026-12-05 15:59:14 +00:00
Sign in to join this conversation.
No Reviewers
No labels
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: yuanyuanxiang/SimpleRemoter#10