package mcp import ( "bytes" "context" "crypto/sha256" "encoding/binary" "encoding/hex" "encoding/json" "hash" "os" "path" "path/filepath" "strconv" "strings" "sync" "time" "unicode/utf16" "unicode/utf8" "golang.org/x/text/encoding/simplifiedchinese" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // read_file pulls one small file over the V2 stream receiver and returns it as // paged text (design §5.4). The flow reuses the file-manager handshake M6 built: // // main conn : COMMAND_LIST_DRIVE(1) // fm sub : [CMD_DOWN_FILES_V2(94)][targetDir\0][path\0][\0] // stream : COMMAND_SEND_FILE_V2(85) chunks … // → COMMAND_FILE_COMPLETE_V2(91) with the whole-file SHA-256 // // Windows clients open a fresh authenticated sub-connection for the chunks; // POSIX clients send them on the file-manager sub-connection itself, so that // connection must stay open until the call ends (MFC §13 F3 does the same — // the plan's "close the file sub-conn first" only holds for Windows). // // Nothing the client sends is used as a filesystem path: every byte lands in // /content, and the client-supplied name is only validated (it starts // with the target directory we chose) as a defence-in-depth check against a // compromised client steering writes elsewhere. const ( // FileChunkPacketV2, packed (common/file_upload.h), 77 bytes: // cmd(1) transferID(8) srcClientID(8) dstClientID(8) fileIndex(4) // totalFiles(4) fileSize(8) offset(8) dataLength(8) nameLength(8) // flags(2) checksum(2) reserved(8), then name, then data. fileChunkHeaderLen = 77 fileChunkOffTransferID = 1 fileChunkOffDstClientID = 17 fileChunkOffFileIndex = 25 fileChunkOffTotalFiles = 29 fileChunkOffFileSize = 33 fileChunkOffOffset = 41 fileChunkOffDataLength = 49 fileChunkOffNameLength = 57 fileChunkOffFlags = 65 // FileCompletePacketV2, packed, 69 bytes: // cmd(1) transferID(8) srcClientID(8) dstClientID(8) fileIndex(4) // fileSize(8) sha256(32). fileCompleteHeaderLen = 69 fileCompleteOffTransferID = 1 fileCompleteOffDstClientID = 17 fileCompleteOffFileIndex = 25 fileCompleteOffFileSize = 29 fileCompleteOffSHA256 = 37 fileCompleteOffSHA256Length = 32 // FileFlagsV2 bits that matter here. ffV2LastChunk uint16 = 0x0001 ffV2Directory uint16 = 0x0010 // read_file argument bounds, matching the published schema and MFC. readFileDefaultLimit = 2000 readFileMaxLimit = 200000 readFileDefaultMaxBytes = 262144 readFileMinMaxBytes = 1024 readFileMaxMaxBytes = 2 << 20 readFileOffsetBound = 100000000 // readFilePathMaxGBK keeps the path inside the client's MAX_PATH buffer // once it has been widened to the ANSI form it passes to the Win32 APIs. readFilePathMaxGBK = 249 // transferContentName is the single file every transfer writes to. The // client's name never reaches the filesystem. transferContentName = "content" ) // Transfer watchdogs. Variables only so tests can shorten them. var ( fileTransferStallTimeout = 60 * time.Second fileTransferTotalTimeout = 120 * time.Second fileTransferPollInterval = 250 * time.Millisecond ) // fileTransferFailure is a terminal session error, already in MCP shape. type fileTransferFailure = rpcError // transferSession is one in-flight V2 download for a device. Every packet is // processed synchronously on the TCP read loop under mu; the waiting call only // polls the small state below, which keeps packet ordering (and therefore the // chunk-offset check) exact. type transferSession struct { mu sync.Mutex deviceID string remotePath string // as the caller wrote it, for messages and the result dir string // private temp directory contentPath string targetDir string // forward-slash form with a trailing '/', for name checks maxFileBytes uint64 fm *connection.Context // file-manager sub-conn that answered the drive list stream *connection.Context // sub-conn chunks arrive on (== fm for POSIX clients) transferID uint64 haveTransfer bool fileIndex uint32 totalFiles uint32 haveFile bool fileSize uint64 received uint64 digest hash.Hash sha256hex string // filled in by the complete packet once verified file *os.File name string // last validated relative name, for logs only lastAt time.Time failure *fileTransferFailure done bool closed bool } // transferTable holds the single pending download per device. The per-device // call lock already serialises tools; the table also rejects a second session // rather than letting two calls share one stream. type transferTable struct { mu sync.Mutex byDevice map[string]*transferSession } func newTransferTable() *transferTable { return &transferTable{byDevice: make(map[string]*transferSession)} } func (t *transferTable) begin(deviceID string, maxFileBytes uint64, remotePath, dir, targetDir string) (*transferSession, bool) { t.mu.Lock() defer t.mu.Unlock() if _, ok := t.byDevice[deviceID]; ok { return nil, false } s := &transferSession{ deviceID: deviceID, remotePath: remotePath, dir: dir, contentPath: filepath.Join(dir, transferContentName), targetDir: targetDir, maxFileBytes: maxFileBytes, lastAt: time.Now(), } t.byDevice[deviceID] = s return s, true } // end removes the session and releases its file. Safe to call once per call; // a packet that already grabbed the pointer sees closed and drops itself. func (t *transferTable) end(deviceID string, s *transferSession) { t.mu.Lock() if t.byDevice[deviceID] == s { delete(t.byDevice, deviceID) } t.mu.Unlock() s.close() } func (t *transferTable) find(deviceID string) *transferSession { t.mu.Lock() defer t.mu.Unlock() return t.byDevice[deviceID] } // owns reports whether ctx belongs to a live transfer. OnFilePacket consults it // before retiring an orphan file-manager sub-conn: on POSIX that connection is // also the data stream, and closing it would break a running read_file. func (t *transferTable) owns(ctx *connection.Context) bool { t.mu.Lock() sessions := make([]*transferSession, 0, len(t.byDevice)) for _, s := range t.byDevice { sessions = append(sessions, s) } t.mu.Unlock() for _, s := range sessions { s.mu.Lock() own := s.fm == ctx || s.stream == ctx s.mu.Unlock() if own { return true } } return false } // attachFM records the file-manager sub-connection the handshake produced. func (t *transferSession) attachFM(ctx *connection.Context) { t.mu.Lock() t.fm = ctx t.mu.Unlock() } // fail records a terminal error unless the transfer already finished. func (t *transferSession) fail(code int, format string, args ...any) { if t.failure == nil && !t.done { t.failure = errf(code, format, args...) } t.done = true } func (t *transferSession) close() { t.mu.Lock() defer t.mu.Unlock() t.closed = true if t.file != nil { _ = t.file.Close() t.file = nil } // The data sub-conn exists only for this transfer. Closing it tells the // client to stop: without that, a batch the server rejected (size gate, // directory) keeps streaming in the background until the client finishes // reading the whole thing. POSIX streams on the file-manager conn instead, // which retireFileConn already closes. if t.stream != nil { _ = t.stream.Close() } } // waitState is the waiter's view of the session. type waitState struct { done bool failure *fileTransferFailure fm *connection.Context stream *connection.Context sha256 string } func (t *transferSession) state() waitState { t.mu.Lock() defer t.mu.Unlock() return waitState{done: t.done, failure: t.failure, fm: t.fm, stream: t.stream, sha256: t.sha256hex} } func (t *transferSession) stalled(limit time.Duration) bool { t.mu.Lock() defer t.mu.Unlock() return !t.done && time.Since(t.lastAt) >= limit } // admits reports whether ctx may carry bytes for this call, and adopts the // client's data sub-connection the first time one shows up (Windows opens a // fresh sub-conn per download; POSIX streams on the file-manager sub-conn). // // Connections are numbered monotonically when the server accepts them, and // this call's file-manager conn was created after the request went out, so a // connection with a lower ID was opened for an earlier call. That matters // because a client keeps streaming the rest of a batch after the server // rejects it (the size gate is the common case), and those late bytes must not // be able to attach to — or fail — the next call. The caller holds t.mu. func (t *transferSession) admits(ctx *connection.Context) bool { if ctx == t.fm { return true // POSIX: chunks travel on the file-manager sub-conn itself } if t.stream != nil { return ctx == t.stream } if t.fm != nil && ctx.ID <= t.fm.ID { return false // stale sub-conn from an earlier transfer } t.stream = ctx return true } // acceptChunk validates and stores one COMMAND_SEND_FILE_V2 packet. The caller // has already checked the framing (name/data lengths fit the packet). func (t *transferSession) acceptChunk(ctx *connection.Context, transferID uint64, fileIndex, totalFiles uint32, fileSize, offset uint64, flags uint16, name []byte, payload []byte) { t.mu.Lock() defer t.mu.Unlock() if t.done || t.closed { return } if !t.admits(ctx) { return // not this call's connection } if !t.haveTransfer { t.transferID = transferID t.haveTransfer = true } if transferID != t.transferID { return // a late packet from an exhausted transfer } t.lastAt = time.Now() nameStr := string(name) if strings.ContainsAny(nameStr, "\x00\r\n") { t.fail(CodeInternal, "Path traversal detected in received path (control byte): %s", quoteWireName(nameStr)) return } if flags&ffV2Directory != 0 { t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } rel, ok := transferNameWithinDir(t.targetDir, nameStr) if !ok { t.fail(CodeInternal, "Path traversal detected in received path: %s (expected a path inside %s)", quoteWireName(nameStr), t.targetDir) return } if !t.haveFile { // The client expands a directory into one chunk stream per file and puts // the batch size in every chunk. Checking it here rejects a directory // before anything is written — waiting for a second fileIndex would let a // two-file directory complete on its first file and be returned as if it // were the answer. totalFiles == 0 means "not reported": older senders // may leave it unset, and a single file is still the only valid read. if totalFiles > 1 { t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } if fileSize > t.maxFileBytes { t.fail(CodeInvalidParams, "File is larger than %d bytes: this minimal server has no download_file; read it in parts with "+ "terminal_exec (type/tail/Get-Content) or use the Windows controller server (%s)", t.maxFileBytes, t.remotePath) return } if offset != 0 { t.fail(CodeInternal, "Unexpected chunk offset %d at the start of the transfer", offset) return } f, err := os.Create(t.contentPath) if err != nil { t.fail(CodeInternal, "Failed to store the downloaded file: %v", err) return } t.file = f t.digest = sha256.New() t.fileIndex = fileIndex t.totalFiles = totalFiles t.fileSize = fileSize t.haveFile = true } else if fileIndex != t.fileIndex { // A second file index means the remote path matched more than one file. t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } t.name = rel if offset != t.received { t.fail(CodeInternal, "Unexpected chunk offset %d (expected %d)", offset, t.received) return } if t.received+uint64(len(payload)) > t.fileSize { t.fail(CodeInternal, "Chunk overruns the declared file size (%d > %d)", t.received+uint64(len(payload)), t.fileSize) return } if len(payload) > 0 { if _, err := t.file.Write(payload); err != nil { t.fail(CodeInternal, "Failed to store the downloaded file: %v", err) return } t.digest.Write(payload) t.received += uint64(len(payload)) } if flags&ffV2LastChunk != 0 && t.received != t.fileSize { t.fail(CodeInternal, "Incomplete transfer: received %d of %d bytes", t.received, t.fileSize) } } // acceptComplete verifies the whole-file SHA-256 and closes the transfer. An // empty file arrives as a complete packet with no chunk at all (Windows // clients never send a zero-length chunk). func (t *transferSession) acceptComplete(ctx *connection.Context, transferID uint64, fileIndex uint32, fileSize uint64, sum []byte) { t.mu.Lock() defer t.mu.Unlock() if t.done || t.closed { return } if !t.admits(ctx) { return // not this call's connection } if !t.haveTransfer { t.transferID = transferID t.haveTransfer = true } if transferID != t.transferID { return } t.lastAt = time.Now() if t.haveFile { if fileIndex != t.fileIndex { return // another file's completion; ours cannot be done yet } if fileSize != t.fileSize { t.fail(CodeInternal, "Completion packet reports %d bytes, chunks reported %d", fileSize, t.fileSize) return } if t.received != t.fileSize { t.fail(CodeInternal, "Incomplete transfer: received %d of %d bytes", t.received, t.fileSize) return } got := t.digest.Sum(nil) if len(sum) != sha256.Size || !bytes.Equal(got, sum) { t.fail(CodeInternal, "File SHA-256 verification failed") return } t.sha256hex = hex.EncodeToString(got) } else { // No chunk at all: only an empty file may complete this way. if fileSize != 0 { t.fail(CodeInternal, "Incomplete transfer: the host sent no data for a %d-byte file", fileSize) return } f, err := os.Create(t.contentPath) if err != nil { t.fail(CodeInternal, "Failed to store the downloaded file: %v", err) return } t.file = f t.fileIndex = fileIndex t.haveFile = true t.fileSize = 0 got := sha256.Sum256(nil) if len(sum) == sha256.Size && !bytes.Equal(got[:], sum) { t.fail(CodeInternal, "File SHA-256 verification failed") return } t.sha256hex = hex.EncodeToString(got[:]) } if t.file != nil { if err := t.file.Close(); err != nil { t.file = nil t.fail(CodeInternal, "Failed to store the downloaded file: %v", err) return } t.file = nil } t.done = true } // acceptDownloadError turns the file-manager sub-conn's TOKEN_DOWNLOAD_ERROR // into the same codes MFC reports (2/3 → -32009, 5 → -32010, else -32000). func (t *transferSession) acceptDownloadError(ctx *connection.Context, win32err uint32) { t.mu.Lock() defer t.mu.Unlock() if t.done || t.closed || ctx != t.fm { return } t.lastAt = time.Now() switch win32err { case errorFileNotFound, errorPathNotFound: t.fail(CodeNotFound, "Remote path does not exist: %s (win32=%d)", t.remotePath, win32err) case errorAccessDenied: t.fail(CodePermission, "Access denied to remote path: %s (win32=%d)", t.remotePath, win32err) default: t.fail(CodeInternal, "Client could not queue the download of %s (win32=%d)", t.remotePath, win32err) } } // quoteWireName renders a client-supplied wire name for an error message. The // name is GBK bytes on the wire, so it is quoted verbatim and bounded: never use // it as a path, only show it. func quoteWireName(name string) string { const maxShown = 200 if len(name) > maxShown { name = name[:maxShown] + "…" } return strconv.Quote(name) } // transferNameWithinDir returns name relative to targetDir, or ok=false when it // resolves outside it. Separators are normalised first and path.Clean folds // '..' before the prefix test, so `..\..\x`, `a/../../b`, absolute paths, UNC // paths and mixed separators are all rejected by the same rule. func transferNameWithinDir(targetDir, name string) (string, bool) { if name == "" || strings.ContainsAny(name, "\x00\r\n") { return "", false } base := path.Clean(strings.ReplaceAll(targetDir, "\\", "/")) + "/" got := path.Clean(strings.ReplaceAll(name, "\\", "/")) if !strings.HasPrefix(got, base) { return "", false } rel := got[len(base):] if rel == "" || rel == "." { return "", false } return rel, true } // ----- packet entry points --------------------------------------------------- // OnTransferPacket feeds one V2 transfer packet from a sub-connection to the // pending read_file call. It reports whether the packet belongs to this // protocol at all; cmd/main.go forwards 85/91/173. func (s *Server) OnTransferPacket(ctx *connection.Context, data []byte) bool { if s == nil || len(data) == 0 { return false } switch data[0] { case protocol.CommandSendFileV2, protocol.CommandFileCompleteV2, protocol.TokenDownloadError: default: return false } deviceID := ctx.GetInfo().ClientID if deviceID == "" { return true } if s.cfg.Hub != nil && s.cfg.Hub.MainConn(deviceID) == ctx { return true // chunks never travel on the main connection } sess := s.transfers.find(deviceID) if sess == nil { return true // no call is waiting: a late packet from a finished transfer } switch data[0] { case protocol.CommandSendFileV2: s.onFileChunkPacket(sess, ctx, data) case protocol.CommandFileCompleteV2: if len(data) < fileCompleteHeaderLen { return true } if binary.LittleEndian.Uint64(data[fileCompleteOffDstClientID:]) != 0 { return true // relayed C2C traffic, not ours } transferID := binary.LittleEndian.Uint64(data[fileCompleteOffTransferID:]) fileIndex := binary.LittleEndian.Uint32(data[fileCompleteOffFileIndex:]) fileSize := binary.LittleEndian.Uint64(data[fileCompleteOffFileSize:]) sum := data[fileCompleteOffSHA256 : fileCompleteOffSHA256+fileCompleteOffSHA256Length] sess.acceptComplete(ctx, transferID, fileIndex, fileSize, sum) case protocol.TokenDownloadError: var win32err uint32 if len(data) >= 5 { win32err = binary.LittleEndian.Uint32(data[1:5]) } sess.acceptDownloadError(ctx, win32err) } return true } // onFileChunkPacket checks the packed header against the packet length before // handing the payload to the session; a malformed chunk is dropped rather than // failing the transfer (the client may still send a good one). func (s *Server) onFileChunkPacket(sess *transferSession, ctx *connection.Context, data []byte) { if len(data) < fileChunkHeaderLen { return } nameLen := binary.LittleEndian.Uint64(data[fileChunkOffNameLength:]) dataLen := binary.LittleEndian.Uint64(data[fileChunkOffDataLength:]) avail := uint64(len(data) - fileChunkHeaderLen) if nameLen > avail || dataLen > avail-nameLen { return } if binary.LittleEndian.Uint64(data[fileChunkOffDstClientID:]) != 0 { return // relayed C2C traffic, not ours } start := fileChunkHeaderLen + int(nameLen) sess.acceptChunk(ctx, binary.LittleEndian.Uint64(data[fileChunkOffTransferID:]), binary.LittleEndian.Uint32(data[fileChunkOffFileIndex:]), binary.LittleEndian.Uint32(data[fileChunkOffTotalFiles:]), binary.LittleEndian.Uint64(data[fileChunkOffFileSize:]), binary.LittleEndian.Uint64(data[fileChunkOffOffset:]), binary.LittleEndian.Uint16(data[fileChunkOffFlags:]), data[fileChunkHeaderLen:start], data[start:start+int(dataLen)], ) } // ----- tool call ------------------------------------------------------------- // readFileArgs is the published inputSchema as Go. limit and max_bytes are // pointers so an explicit out-of-range value is rejected instead of being // mistaken for "absent". type readFileArgs struct { ID string `json:"id"` Path string `json:"path"` Offset int `json:"offset"` Limit *int `json:"limit"` Encoding string `json:"encoding"` MaxBytes *int `json:"max_bytes"` } // readFileOutput mirrors outputSchema exactly; the model relies on these names. type readFileOutput struct { Path string `json:"path"` Size int `json:"size"` Encoding string `json:"encoding"` EOL string `json:"eol"` LinesTotal int `json:"lines_total"` Offset int64 `json:"offset"` LinesReturned int `json:"lines_returned"` Truncated bool `json:"truncated"` Text string `json:"text"` SHA256 string `json:"sha256"` } // callReadFile streams one file down and returns the requested text window. func (s *Server) callReadFile(ctx context.Context, raw json.RawMessage) (any, *rpcError) { if s.cfg.Hub == nil { return nil, errf(CodeInternal, "server device registry is not configured") } var args readFileArgs if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } if args.ID == "" { return nil, errf(CodeInvalidParams, "Missing required parameter: id") } if !isDecimalID(args.ID) { return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") } if s.cfg.Hub.MainConn(args.ID) == nil { return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID) } if !protocol.SupportsCap(s.cfg.Hub.Capability(args.ID), protocol.ClientCapV2) { return nil, errf(CodeUnsupported, "Host does not support V2 file transfer: the client does not declare CLIENT_CAP_V2 (upgrade the client)") } if args.Path == "" { return nil, errf(CodeInvalidParams, "Missing required parameter: path") } if strings.ContainsAny(args.Path, "\x00\r\n") { return nil, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed") } pathGBK := protocol.UTF8ToGBK(args.Path) if len(pathGBK) >= readFilePathMaxGBK { return nil, errf(CodeInvalidParams, "Path too long: %d bytes after conversion to the client's GBK encoding (limit %d)", len(pathGBK), readFilePathMaxGBK-1) } encoding, rerr := normalizeEncoding(args.Encoding) if rerr != nil { return nil, rerr } if args.Offset < -readFileOffsetBound || args.Offset > readFileOffsetBound { return nil, errf(CodeInvalidParams, "offset out of range") } limit := readFileDefaultLimit if args.Limit != nil { if *args.Limit < 1 || *args.Limit > readFileMaxLimit { return nil, errf(CodeInvalidParams, "limit must be in range 1..%d", readFileMaxLimit) } limit = *args.Limit } maxBytes := readFileDefaultMaxBytes if args.MaxBytes != nil { if *args.MaxBytes < readFileMinMaxBytes || *args.MaxBytes > readFileMaxMaxBytes { return nil, errf(CodeInvalidParams, "max_bytes must be in range %d..%d", readFileMinMaxBytes, readFileMaxMaxBytes) } maxBytes = *args.MaxBytes } dir, err := os.MkdirTemp("", "yama-mcp-read-*") if err != nil { return nil, errf(CodeInternal, "Failed to create the MCP temp directory: %v", err) } defer os.RemoveAll(dir) // The client concatenates its relative name onto this string verbatim; the // trailing separator is what makes that a directory prefix (GetRelativePath // returns a bare basename when the root is the file itself). targetDir := dir + string(os.PathSeparator) maxFileBytes := uint64(s.cfg.ReadMax) sess, ok := s.transfers.begin(args.ID, maxFileBytes, args.Path, dir, targetDir) if !ok { return nil, errf(CodeBusy, "Device busy: another file request is already pending for host %s", args.ID) } defer s.transfers.end(args.ID, sess) sub, req, drives, rerr := s.openFileManagerConn(ctx, args.ID) if rerr != nil { return nil, rerr } defer s.closeFileManagerConn(args.ID, req) sess.attachFM(sub) // POSIX hosts report their single root as the '/' drive. Their paths are // checked before the request goes out so a Windows-style path fails with a // clear message instead of a stall. if driveListPosix(drives) { if !strings.HasPrefix(args.Path, "/") { return nil, errf(CodeInvalidParams, "path must be an absolute POSIX path for Linux/macOS hosts, e.g. /etc/app.conf") } if strings.Contains(args.Path, "\\") { return nil, errf(CodeInvalidParams, "path must not contain backslashes on Linux/macOS hosts; use '/'") } if hasDotDotSegment(args.Path) { return nil, errf(CodeInvalidParams, "path must not contain '..' path segments") } } pkt := make([]byte, 0, 3+len(targetDir)+len(pathGBK)) pkt = append(pkt, protocol.CmdDownFilesV2) pkt = append(pkt, protocol.UTF8ToGBK(targetDir)...) pkt = append(pkt, 0) pkt = append(pkt, pathGBK...) pkt = append(pkt, 0, 0) if err := s.cfg.Hub.SendToConn(sub, pkt); err != nil { return nil, errf(CodeSendFailed, "Failed to send the download request on the file-manager channel: %v", err) } if rerr := s.waitFileTransfer(ctx, sess); rerr != nil { return nil, rerr } fileBytes, err := os.ReadFile(sess.contentPath) if err != nil { return nil, errf(CodeInternal, "Failed to read the downloaded temp file: %v", err) } return buildReadFileResult(args.Path, fileBytes, sess.state().sha256, encoding, args.Offset, limit, maxBytes), nil } // waitFileTransfer blocks until the session finishes, fails, or a watchdog // fires. Packets are processed on the read loop, so polling every 250 ms costs // nothing and keeps the packet path lock-free of the waiter. func (s *Server) waitFileTransfer(ctx context.Context, sess *transferSession) *rpcError { deadline := time.Now().Add(fileTransferTotalTimeout) for { st := sess.state() if st.failure != nil { return st.failure } if st.done { return nil } if ctx.Err() != nil { return errf(CodeTimeout, "Request cancelled while waiting for the file transfer") } if st.stream != nil && st.stream.IsClosed() { // The completion packet would have been processed before the close: // a closed stream with no result is a lost transfer. return errf(CodeTimeout, "Connection lost: the transfer sub-connection closed") } if st.fm != nil && st.fm.IsClosed() { // POSIX clients stream on the file-manager sub-conn, so its close is // the only early sign that the transfer died; Windows clients only // close it when the call ends. return errf(CodeTimeout, "Connection lost: the file-manager sub-connection closed") } if !time.Now().Before(deadline) { return errf(CodeTimeout, "Timeout waiting for the file transfer") } if sess.stalled(fileTransferStallTimeout) { return errf(CodeTimeout, "File transfer stalled: no data received for %s (the remote path is probably missing or inaccessible; verify it with list_files first)", fileTransferStallTimeout) } select { case <-time.After(fileTransferPollInterval): case <-ctx.Done(): } } } // driveListPosix reports whether the handshake came from a POSIX host: it // advertises its single root as the '/' drive. func driveListPosix(drives []driveEntry) bool { for _, d := range drives { if d.Drive == "/" { return true } } return false } // hasDotDotSegment reports whether any '/'-separated segment is exactly "..". func hasDotDotSegment(p string) bool { for _, seg := range strings.Split(p, "/") { if seg == ".." { return true } } return false } // normalizeEncoding validates the requested encoding before the download so a // typo does not cost a full transfer, and canonicalises the name. func normalizeEncoding(requested string) (string, *rpcError) { switch strings.ToLower(strings.TrimSpace(requested)) { case "", "auto": return "auto", nil case "utf-8", "utf8": return "utf-8", nil case "gbk": return "gbk", nil case "gb18030": return "gb18030", nil case "latin1", "iso-8859-1": return "latin1", nil default: return "", errf(CodeInvalidParams, "Unsupported encoding: %s (use auto / utf-8 / gbk / gb18030 / latin1)", requested) } } // ----- text windowing -------------------------------------------------------- // buildReadFileResult decodes, normalises and windows the downloaded bytes and // assembles the MCP envelope the published outputSchema describes. func buildReadFileResult(remotePath string, rawBytes []byte, sha256hex, requested string, offset, limit, maxBytes int) toolResult { text, encoding := decodeFileText(rawBytes, requested) eol := detectEOL(text) normalized := normalizeEOL(text) lines := splitTextLines(normalized) total := len(lines) start := offset if start < 0 { start = total + start } start = max(start, 0) start = min(start, total) var textOut strings.Builder count := 0 capHit := false for i := start; i < total && count < limit; i++ { ln := lines[i] add := len(ln) if textOut.Len() > 0 { add++ } if textOut.Len()+add > maxBytes { if textOut.Len() == 0 { // A single line longer than the budget: cut hard but back off to // a UTF-8 character boundary so the JSON stays valid. cut := maxBytes for cut > 0 && cut < len(ln) && ln[cut]&0xC0 == 0x80 { cut-- } textOut.WriteString(ln[:cut]) count = 1 } capHit = true break } if textOut.Len() > 0 { textOut.WriteByte('\n') } textOut.WriteString(ln) count++ } window := textOut.String() linesReturned := len(splitTextLines(window)) truncated := capHit || start+count < total head := "[read_file] " + remotePath + " | " + strconv.Itoa(len(rawBytes)) + " bytes | " + encoding + " | " + eol + " | lines " + strconv.Itoa(start) + "-" + strconv.Itoa(start+count) + " of " + strconv.Itoa(total) + " | truncated=" + boolString(truncated) + " | sha256=" + sha256hex return newToolResult(head+"\n"+window, readFileOutput{ Path: remotePath, Size: len(rawBytes), Encoding: encoding, EOL: eol, LinesTotal: total, Offset: int64(start), LinesReturned: linesReturned, Truncated: truncated, Text: window, SHA256: sha256hex, }) } // decodeFileText applies the same precedence as the Win32 server: BOM → valid // UTF-8 → GBK for "auto"; explicit encodings bypass detection. func decodeFileText(raw []byte, requested string) (string, string) { switch requested { case "utf-8": return string(stripUTF8BOM(raw)), "utf-8" case "gbk": return decodeGBKText(raw), "gbk" case "gb18030": return decodeGB18030Text(raw), "gb18030" case "latin1": return latin1ToUTF8(raw), "latin1" } if len(raw) >= 3 && raw[0] == 0xEF && raw[1] == 0xBB && raw[2] == 0xBF { return string(raw[3:]), "utf-8" } if len(raw) >= 2 && raw[0] == 0xFF && raw[1] == 0xFE { return utf16ToUTF8(raw[2:], binary.LittleEndian), "utf-16le" } if len(raw) >= 2 && raw[0] == 0xFE && raw[1] == 0xFF { return utf16ToUTF8(raw[2:], binary.BigEndian), "utf-16be" } if utf8.Valid(raw) { return string(raw), "utf-8" } return decodeGBKText(raw), "gbk" } func stripUTF8BOM(raw []byte) []byte { if len(raw) >= 3 && raw[0] == 0xEF && raw[1] == 0xBB && raw[2] == 0xBF { return raw[3:] } return raw } func utf16ToUTF8(raw []byte, order binary.ByteOrder) string { units := make([]uint16, len(raw)/2) for i := range units { units[i] = order.Uint16(raw[2*i:]) } return string(utf16.Decode(units)) } // decodeGBKText decodes CP936 without the NUL/printable filtering // GbkToUTF8 applies — file content must survive byte for byte. func decodeGBKText(raw []byte) string { out, err := simplifiedchinese.GBK.NewDecoder().Bytes(raw) if err != nil { return string(raw) // not GBK after all; the UTF-8 fallback matches GbkToUTF8 } return string(out) } func decodeGB18030Text(raw []byte) string { out, err := simplifiedchinese.GB18030.NewDecoder().Bytes(raw) if err != nil { return string(raw) } return string(out) } func latin1ToUTF8(raw []byte) string { var b strings.Builder b.Grow(len(raw) * 2) for _, c := range raw { if c < 0x80 { b.WriteByte(c) } else { b.WriteRune(rune(c)) } } return b.String() } // detectEOL classifies the line endings: crlf / lf / cr / mixed / none. func detectEOL(t string) string { var crlf, lf, cr int for i := 0; i < len(t); i++ { switch t[i] { case '\r': if i+1 < len(t) && t[i+1] == '\n' { crlf++ i++ } else { cr++ } case '\n': lf++ } } switch { case crlf+lf+cr == 0: return "none" case crlf > 0 && lf == 0 && cr == 0: return "crlf" case lf > 0 && crlf == 0 && cr == 0: return "lf" case cr > 0 && crlf == 0 && lf == 0: return "cr" default: return "mixed" } } // normalizeEOL converts CRLF and bare CR to '\n' so line numbers and the // returned text agree. func normalizeEOL(t string) string { if !strings.ContainsRune(t, '\r') { return t } var b strings.Builder b.Grow(len(t)) for i := 0; i < len(t); i++ { if t[i] == '\r' { if i+1 < len(t) && t[i+1] == '\n' { i++ } b.WriteByte('\n') continue } b.WriteByte(t[i]) } return b.String() } // splitTextLines splits on '\n'; a trailing newline does not add an empty line // (same as Get-Content / readlines). func splitTextLines(t string) []string { if t == "" { return nil } var out []string for start := 0; start < len(t); { i := strings.IndexByte(t[start:], '\n') if i < 0 { out = append(out, t[start:]) break } out = append(out, t[start:start+i]) start += i + 1 } return out } func boolString(b bool) string { if b { return "true" } return "false" }