Feature(Go): read_file over the V2 stream receiver

read_file reuses the list_files handshake: COMMAND_LIST_DRIVE opens the
file-manager sub-conn, which then gets
[CMD_DOWN_FILES_V2][targetDir\0][path\0][\0] and streams
COMMAND_SEND_FILE_V2 chunks plus a COMMAND_FILE_COMPLETE_V2 carrying the
whole-file SHA-256. Windows clients open a fresh authenticated sub-conn
for the chunks; POSIX clients stream on the file-manager conn itself, so
that conn is retired when the call ends rather than right after the
request. TOKEN_DOWNLOAD_ERROR on the file-manager conn maps to -32009 /
-32010 / -32000 like the Win32 server.

Bytes land only in a per-call os.MkdirTemp dir; the client name is
checked against the target dir (separator-normalised, path.Clean, so
..\.., absolute, UNC and mixed separators are refused) as
defence-in-depth, never used as a path. First chunk enforces the size
gate (ReadMax) and rejects multi-file batches, so an expanded directory
fails with -32602 instead of returning its first file. Chunks from a
sub-conn opened for an earlier call are dropped by connection ID, data
sub-conns are closed when the call ends, and a closed sub-conn fails the
call fast instead of waiting for the stall watchdog.

Text windowing, encoding detection (BOM / UTF-8 / GBK / explicit /
latin1) and EOL handling mirror McpServer.cpp. Verified with the Debug
ghost on Windows 11 and the WSL Ubuntu ghost: .env text plus newline is
byte-identical, sha256 equals SHA-256 over the file, windows/GBK/empty/
max_bytes/directory/size-gate/missing-path/POSIX-path cases all pass.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 23:04:35 +01:00
1 parent d7accf1d30
commit 9ce1a58bc3
7 files changed
+1790 -71

No files matched your search

+86 -50
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
@@ -197,6 +198,7 @@ func (t *fileTable) deliver(deviceID string, ev fileEvent) bool {
func (s *Server) registerFileTools() {
s.handlers["list_files"] = s.callListFiles
s.handlers["read_file"] = s.callReadFile
}
// OnFilePacket feeds one file-manager packet from a sub-connection to the
@@ -244,7 +246,9 @@ func (s *Server) OnFilePacket(ctx *connection.Context, data []byte) bool {
// Nothing is waiting for this sub-conn: the call it belonged to already
// timed out or finished. Retire it so the client does not leak its
// file-manager thread, but only once the sub-conn has announced itself.
if ev.kind == fileEventDriveList {
// A live read_file keeps its file-manager sub-conn registered in the
// transfer table (POSIX clients stream on it), so never close that one.
if ev.kind == fileEventDriveList && !s.transfers.owns(ctx) {
s.retireFileConn(ctx)
}
return true
@@ -296,6 +300,67 @@ type fileEntry struct {
Mtime int64 `json:"mtime"`
}
// openFileManagerConn asks the device for its file-manager sub-connection
// (COMMAND_LIST_DRIVE on the main connection) and waits for the drive list.
// On success it returns the sub-connection, the still-pending request (later
// packets are matched against it) and the parsed drives; the caller owns both
// and must call closeFileManagerConn when done. Every failure path retires the
// sub-connection here, so a timed-out or rejected handshake leaves no orphan
// file-manager thread on the client.
func (s *Server) openFileManagerConn(ctx context.Context, deviceID string) (*connection.Context, *fileRequest, []driveEntry, *rpcError) {
req, ok := s.files.begin(deviceID)
if !ok {
return nil, nil, nil, errf(CodeBusy, "Device busy: another file request is already pending for host %s", deviceID)
}
keep := false
defer func() {
if !keep {
if sub := s.files.cancel(deviceID, req); sub != nil {
s.retireFileConn(sub)
}
}
}()
if err := s.cfg.Hub.SendToDevice(deviceID, []byte{protocol.CommandListDrive}); err != nil {
if errors.Is(err, hub.ErrDeviceOffline) {
return nil, nil, nil, errf(CodeOffline, "Host not found or offline: %s", deviceID)
}
return nil, nil, nil, errf(CodeSendFailed, "Failed to ask the host for its file-manager channel: %v", err)
}
timer := time.NewTimer(fileListTimeout)
defer timer.Stop()
select {
case ev := <-req.ch:
switch ev.kind {
case fileEventDriveList:
keep = true
return ev.ctx, req, parseDriveList(ev.payload), nil
case fileEventError:
return nil, nil, nil, errf(win32ErrorCode(ev.win32err),
"Failed to open the file-manager channel on host %s (win32=%d)", deviceID, ev.win32err)
default:
return nil, nil, nil, errf(CodeInternal, "Unexpected file-manager reply while listing drives")
}
case <-timer.C:
return nil, nil, nil, errf(CodeTimeout,
"Timeout waiting for the host to open a file-manager channel (%s). Older clients that do not implement file browsing stay silent; retrying will not help.",
fileListTimeout)
case <-ctx.Done():
return nil, nil, nil, errf(CodeTimeout, "Request cancelled while waiting for the host's file-manager channel")
}
}
// closeFileManagerConn ends the request and retires the sub-connection it
// learned about. It is the single retirement point for that sub-conn: the
// cancel below also covers a call that gave up while its drive-list packet was
// already queued (the select taking the timer branch with both ready).
func (s *Server) closeFileManagerConn(deviceID string, req *fileRequest) {
if sub := s.files.cancel(deviceID, req); sub != nil {
s.retireFileConn(sub)
}
}
// callListFiles lists drives (no path) or one directory level.
func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
@@ -335,62 +400,17 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *
"Path too long: %d bytes after conversion to the client's GBK encoding (limit 249)", len(pathGBK))
}
req, ok := s.files.begin(args.ID)
if !ok {
return nil, errf(CodeBusy, "Device busy: another list_files request is already pending for host %s", args.ID)
}
// One retirement point for every exit path, including the ones where the
// drive-list packet is already queued but the select picks the timer or a
// cancelled request: cancel hands back the sub-conn it saw so the client's
// file-manager thread is closed instead of leaked.
defer func() {
if sub := s.files.cancel(args.ID, req); sub != nil {
s.retireFileConn(sub)
}
}()
if err := s.cfg.Hub.SendToDevice(args.ID, []byte{protocol.CommandListDrive}); err != nil {
if err == hub.ErrDeviceOffline {
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
}
return nil, errf(CodeSendFailed, "Failed to ask the host for its file-manager channel: %v", err)
}
timer := time.NewTimer(fileListTimeout)
defer timer.Stop()
// Phase 1: the client opens the sub-conn and sends its drive list. The
// sub-conn stays open for the directory request.
var drives []driveEntry
select {
case ev := <-req.ch:
switch ev.kind {
case fileEventDriveList:
drives = parseDriveList(ev.payload)
case fileEventError:
return nil, fileWin32Error(ev.win32err, path)
default:
return nil, errf(CodeInternal, "Unexpected file-manager reply while listing drives")
}
case <-timer.C:
return nil, errf(CodeTimeout,
"Timeout waiting for the host to open a file-manager channel (%s). Older clients that do not implement file browsing stay silent; retrying will not help.",
fileListTimeout)
case <-ctx.Done():
return nil, errf(CodeTimeout, "Request cancelled while waiting for the host's file-manager channel")
sub, req, drives, rerr := s.openFileManagerConn(ctx, args.ID)
if rerr != nil {
return nil, rerr
}
defer s.closeFileManagerConn(args.ID, req)
if listDrives {
return listFilesResult(args, drives, nil, false), nil
}
// Phase 2: reuse the same sub-conn for the directory itself.
sub := req.subConn()
if sub == nil {
// The list above succeeded, so a sub-conn was recorded; a nil here
// would mean the request was cancelled underneath us.
return nil, errf(CodeInternal, "File-manager channel closed before the directory request")
}
pkt := make([]byte, 0, 2+len(pathGBK))
pkt = append(pkt, protocol.CommandListFiles)
pkt = append(pkt, pathGBK...)
@@ -399,6 +419,8 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *
return nil, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err)
}
timer := time.NewTimer(fileListTimeout)
defer timer.Stop()
select {
case ev := <-req.ch:
switch ev.kind {
@@ -419,6 +441,20 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *
}
}
// win32ErrorCode maps a client-reported Win32 error onto an MCP code the same
// way the Win32 server does: 5 is a permission problem, 2/3 mean "no such
// target", everything else is an internal failure carrying the raw code.
func win32ErrorCode(win32err uint32) int {
switch win32err {
case errorAccessDenied:
return CodePermission
case errorFileNotFound, errorPathNotFound:
return CodeNotFound
default:
return CodeInternal
}
}
// fileWin32Error maps the client's win32 error onto MCP codes the same way the
// Win32 server does: 5 is a permission problem, 2/3 mean "no such target",
// everything else is an internal failure carrying the raw code.