package mcp import ( "bytes" "context" "encoding/binary" "encoding/json" "net" "strings" "testing" "time" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // fileRig is a live MCP server plus a hub whose sender records every outbound // write together with the connection it went to. Tests answer requests through // OnFilePacket, exactly what cmd/main.go does from the TCP read loop. type fileWire struct { ctx *connection.Context data []byte } type fileRig struct { t *testing.T s *Server h *hub.Hub main *connection.Context w chan fileWire connID uint64 // sub-connections get increasing IDs, like connection.Manager } func newFileRig(t *testing.T) *fileRig { t.Helper() oldTimeout, oldDelay := fileListTimeout, fileRetireDelay fileListTimeout = 5 * time.Second fileRetireDelay = 10 * time.Millisecond t.Cleanup(func() { fileListTimeout, fileRetireDelay = oldTimeout, oldDelay }) h := hub.New() main := &connection.Context{RemoteAddr: "10.0.0.1:4000"} main.Info.ClientID = "1001" main.Info.ClientType = "EXE" rig := &fileRig{t: t, h: h, main: main, w: make(chan fileWire, 32)} h.SetSender(func(ctx *connection.Context, data []byte) error { select { case rig.w <- fileWire{ctx: ctx, data: append([]byte(nil), data...)}: default: rig.t.Errorf("sender buffer full, dropping %v", data) } return nil }) h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: "1"}, main) rig.s = New(Config{Token: testToken, Hub: h}) t.Cleanup(rig.s.Close) return rig } // newSub builds a sub-connection context with the ClientID ConnAuth would pin. // The pipe gives Close something real to close; nothing writes to it. func (r *fileRig) newSub() *connection.Context { return r.newSubFor("1001") } func (r *fileRig) newSubFor(clientID string) *connection.Context { r.t.Helper() c1, c2 := net.Pipe() r.t.Cleanup(func() { _ = c1.Close(); _ = c2.Close() }) // Real contexts are numbered monotonically at accept time; read_file uses // that to tell a data sub-conn opened for this call from one left over by an // earlier call, so the fake ones have to be numbered too. r.connID++ ctx := &connection.Context{ID: r.connID, Conn: c1, RemoteAddr: "10.0.0.1:4100"} ctx.Info.ClientID = clientID return ctx } // registerDevice adds another online host so batch tests can fan out. func (r *fileRig) registerDevice(id, peerIP string) *connection.Context { r.t.Helper() main := &connection.Context{RemoteAddr: peerIP + ":4000"} main.Info.ClientID = id main.Info.ClientType = "EXE" r.h.Register(&hub.Device{ID: id, PeerIP: peerIP, Capability: "1"}, main) return main } // nextAny returns the next wire without asserting a destination. func (r *fileRig) nextAny() fileWire { r.t.Helper() select { case w := <-r.w: return w case <-time.After(5 * time.Second): r.t.Fatal("no wire was sent") return fileWire{} } } // nextIgnoringBye reads the next wire addressed to want, skipping COMMAND_BYE // frames that retiring sub-connections send asynchronously. func (r *fileRig) nextIgnoringBye(want *connection.Context) []byte { r.t.Helper() for { w := r.nextAny() if bytes.Equal(w.data, []byte{protocol.CommandBye}) { continue } if w.ctx != want { r.t.Fatalf("wire went to an unexpected connection (%p, want %p): %v", w.ctx, want, w.data) } return w.data } } func (r *fileRig) next(want *connection.Context) []byte { r.t.Helper() select { case w := <-r.w: if w.ctx != want { r.t.Fatalf("wire went to an unexpected connection (%p, want %p): %v", w.ctx, want, w.data) } return w.data case <-time.After(5 * time.Second): r.t.Fatal("no wire was sent") return nil } } func (r *fileRig) expectNothing() { r.t.Helper() select { case w := <-r.w: r.t.Fatalf("unexpected wire to %p: %v", w.ctx, w.data) case <-time.After(50 * time.Millisecond): } } type fileCall struct { res toolResult err *rpcError } func (r *fileRig) call(args string) <-chan fileCall { ch := make(chan fileCall, 1) go func() { res, rerr := r.s.callListFiles(context.Background(), []byte(args)) if rerr != nil { ch <- fileCall{err: rerr} return } tr, ok := res.(toolResult) if !ok { ch <- fileCall{err: errf(CodeInternal, "unexpected result type %T", res)} return } ch <- fileCall{res: tr} }() return ch } func (r *fileRig) wait(ch <-chan fileCall) fileCall { r.t.Helper() select { case c := <-ch: return c case <-time.After(5 * time.Second): r.t.Fatal("timed out waiting for the tool call") return fileCall{} } } // startDirectoryCall runs one list_files call up to and including the // COMMAND_LIST_FILES send, and returns the waiting call plus its sub-conn. func (r *fileRig) startDirectoryCall(args string) (<-chan fileCall, *connection.Context) { r.t.Helper() ch := r.call(args) if got := r.next(r.main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive) } sub := r.newSub() if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"})) { r.t.Fatal("drive-list packet was not consumed") } if got := r.next(sub); got[0] != protocol.CommandListFiles { r.t.Fatalf("directory request wire = %v, want token %d first", got, protocol.CommandListFiles) } return ch, sub } func waitClosed(t *testing.T, ctx *connection.Context) { t.Helper() deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { if ctx.IsClosed() { return } time.Sleep(5 * time.Millisecond) } t.Fatal("sub-connection was not closed") } // ----- wire fixtures -------------------------------------------------------- type driveRec struct { letter byte dtype byte total uint32 free uint32 typeName string // UTF-8, encoded as GBK on the wire fs string } func appendU32(buf []byte, v uint32) []byte { var b [4]byte binary.LittleEndian.PutUint32(b[:], v) return append(buf, b[:]...) } func driveListPacket(recs ...driveRec) []byte { buf := []byte{protocol.TokenDriveList} for _, r := range recs { buf = append(buf, r.letter, r.dtype) buf = appendU32(buf, r.total) buf = appendU32(buf, r.free) buf = append(buf, protocol.UTF8ToGBK(r.typeName)...) buf = append(buf, 0) buf = append(buf, protocol.UTF8ToGBK(r.fs)...) buf = append(buf, 0) } return buf } type fileRec struct { attr byte name string // UTF-8, encoded as GBK on the wire size uint64 mtime int64 // Unix seconds; 0 leaves FILETIME zero } func fileListPacket(recs ...fileRec) []byte { buf := []byte{protocol.TokenFileList} for _, r := range recs { buf = append(buf, r.attr) buf = append(buf, protocol.UTF8ToGBK(r.name)...) buf = append(buf, 0) buf = appendU32(buf, uint32(r.size>>32)) buf = appendU32(buf, uint32(r.size)) var ft uint64 if r.mtime != 0 { ft = uint64(r.mtime+filetimeEpochDiffSec) * filetimeTicksPerSec } buf = appendU32(buf, uint32(ft)) buf = appendU32(buf, uint32(ft>>32)) } return buf } func fileListErrorPacket(win32err uint32) []byte { buf := []byte{protocol.TokenFileListError} return appendU32(buf, win32err) } // checkInt asserts an exact int field. structuredContent here is a Go map, not // JSON that went through a float64 round trip, so intField does not apply. func checkInt(t *testing.T, m map[string]any, key string, want int) { t.Helper() got, ok := m[key].(int) if !ok { t.Fatalf("%q = %v (%T), want int", key, m[key], m[key]) } if got != want { t.Fatalf("%q = %d, want %d", key, got, want) } } // ----- argument validation -------------------------------------------------- func TestListFilesRejectsBadArguments(t *testing.T) { r := newFileRig(t) cases := []struct { name string args string code int }{ {"id and ids", `{"id":"1001","ids":["1002"]}`, CodeInvalidParams}, {"missing id", `{}`, CodeInvalidParams}, {"non-decimal id", `{"id":"abc"}`, CodeInvalidParams}, {"numeric id", `{"id":1001}`, CodeInvalidParams}, {"NUL in path", `{"id":"1001","path":"C:\\a\u0000b"}`, CodeInvalidParams}, {"newline in path", `{"id":"1001","path":"C:\\a\nb"}`, CodeInvalidParams}, {"path too long", `{"id":"1001","path":"` + strings.Repeat("a", 260) + `"}`, CodeInvalidParams}, {"offline", `{"id":"2002"}`, CodeOffline}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { _, rerr := r.s.callListFiles(context.Background(), []byte(c.args)) if rerr == nil { t.Fatalf("call succeeded, want error %d", c.code) } if rerr.Code != c.code { t.Fatalf("error code = %d (%s), want %d", rerr.Code, rerr.Message, c.code) } }) } r.expectNothing() } // ----- drive listing -------------------------------------------------------- func TestListFilesDrives(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001"}`) if got := r.next(r.main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { t.Fatalf("drive request wire = %v", got) } sub := r.newSub() pkt := driveListPacket( driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"}, driveRec{'/', 3, 100000, 50000, "Linux", "ext4"}, ) if !r.s.OnFilePacket(sub, pkt) { t.Fatal("drive-list packet was not consumed") } c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) drives := sc["drives"].([]driveEntry) if len(drives) != 2 { t.Fatalf("drives = %#v, want 2 entries", drives) } win, posix := drives[0], drives[1] if win.Drive != `C:\` || win.TypeName != "本地磁盘" || win.FileSystem != "NTFS" || win.TotalMB != 500000 || win.FreeMB != 123456 || win.Type != 3 { t.Fatalf("windows drive = %#v", win) } if posix.Drive != "/" || posix.FileSystem != "ext4" || posix.TotalMB != 100000 { t.Fatalf("posix drive = %#v", posix) } checkInt(t, sc, "total", 2) if !strings.Contains(c.res.Content[0].Text, "共 2 个驱动器") { t.Fatalf("summary = %q", c.res.Content[0].Text) } if !strings.Contains(c.res.Content[0].Text, "drive\ttypeName\tfileSystem\ttotalMB\tfreeMB") || !strings.Contains(c.res.Content[0].Text, "C:\\\t本地磁盘\tNTFS\t500000\t123456") { t.Fatalf("text = %q, want drive rows", c.res.Content[0].Text) } // A drive-only listing still leaves the sub-conn to be retired. if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandBye}) { t.Fatalf("retire wire = %v, want COMMAND_BYE", got) } waitClosed(t, sub) } func TestListFilesEmptyDriveList(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001","path":""}`) r.next(r.main) sub := r.newSub() r.s.OnFilePacket(sub, []byte{protocol.TokenDriveList}) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) if got := sc["drives"].([]driveEntry); len(got) != 0 { t.Fatalf("drives = %#v, want none", got) } if !strings.Contains(c.res.Content[0].Text, "共 0 个驱动器") { t.Fatalf("summary = %q", c.res.Content[0].Text) } } // ----- directory listing ---------------------------------------------------- func TestListFilesDirectory(t *testing.T) { r := newFileRig(t) ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\工作","limit":2,"offset":1}`) pkt := fileListPacket( fileRec{attr: 0x10, name: "子目录", mtime: 1700000000}, fileRec{attr: 0x00, name: "a.txt", size: 12345, mtime: 1700000000}, fileRec{attr: 0x00, name: "中文文档.docx", size: 5 << 30, mtime: 1600000000}, ) if !r.s.OnFilePacket(sub, pkt) { t.Fatal("file-list packet was not consumed") } c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) files := sc["files"].([]fileEntry) if len(files) != 2 { t.Fatalf("page = %#v, want 2 entries (offset 1, limit 2)", files) } // Offset 1 skips 子目录. if files[0].Name != "a.txt" || files[0].IsDir || files[0].Size != 12345 { t.Fatalf("first entry = %#v", files[0]) } if files[0].Mtime != 1700000000 { t.Fatalf("mtime = %d, want 1700000000", files[0].Mtime) } if files[1].Name != "中文文档.docx" || files[1].Size != 5<<30 { t.Fatalf("second entry = %#v", files[1]) } checkInt(t, sc, "total", 3) checkInt(t, sc, "totalAll", 3) checkInt(t, sc, "limit", 2) checkInt(t, sc, "offset", 1) if sc["hasMore"] != false { t.Fatalf("hasMore = %v, want false", sc["hasMore"]) } if !strings.Contains(c.res.Content[0].Text, "共 3 个条目") || !strings.Contains(c.res.Content[0].Text, "第 2-3 条") { t.Fatalf("summary = %q", c.res.Content[0].Text) } if !strings.Contains(c.res.Content[0].Text, "name\tisDir\tsize\tmtime") || !strings.Contains(c.res.Content[0].Text, "a.txt\tfalse\t12345\t1700000000") || !strings.Contains(c.res.Content[0].Text, "中文文档.docx\tfalse\t5368709120\t1600000000") { t.Fatalf("text = %q, want file rows for the returned page", c.res.Content[0].Text) } // The page window (offset 1) applies to the table as well. if strings.Contains(c.res.Content[0].Text, "子目录") { t.Fatalf("text = %q, offset-skipped entry leaked into the table", c.res.Content[0].Text) } if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandBye}) { t.Fatalf("retire wire = %v, want COMMAND_BYE", got) } waitClosed(t, sub) } func TestListFilesDirectoryRequestWire(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001","path":"C:\\工作"}`) r.next(r.main) sub := r.newSub() r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 1, 1, "本地磁盘", "NTFS"})) got := r.next(sub) want := append([]byte{protocol.CommandListFiles}, protocol.UTF8ToGBK(`C:\工作`)...) want = append(want, 0) if !bytes.Equal(got, want) { t.Fatalf("directory request wire = %v, want %v", got, want) } r.s.OnFilePacket(sub, fileListPacket()) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } } func TestListFilesRootSlashIsAPath(t *testing.T) { // tools.json says a non-empty path lists that directory; "/" must not be // folded into the drive list or a POSIX root listing is unreachable. r := newFileRig(t) ch := r.call(`{"id":"1001","path":"/"}`) r.next(r.main) sub := r.newSub() r.s.OnFilePacket(sub, driveListPacket(driveRec{'/', 3, 1, 1, "Linux", "ext4"})) if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandListFiles, '/', 0}) { t.Fatalf("wire = %v, want COMMAND_LIST_FILES plus \"/\" and a NUL", got) } r.s.OnFilePacket(sub, fileListPacket(fileRec{name: "etc"}, fileRec{name: "tmp"})) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) if files := sc["files"].([]fileEntry); len(files) != 2 || files[0].Name != "etc" { t.Fatalf("files = %#v", files) } } func TestListFilesEmptyDirectory(t *testing.T) { r := newFileRig(t) ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\empty"}`) // The Windows client sends just the token when a directory is empty. r.s.OnFilePacket(sub, []byte{protocol.TokenFileList}) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) if got := sc["files"].([]fileEntry); len(got) != 0 { t.Fatalf("files = %#v, want none", got) } if sc["hasMore"] != false { t.Fatalf("hasMore = %v", sc["hasMore"]) } } func TestListFilesPagingHasMore(t *testing.T) { r := newFileRig(t) ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\big","limit":2}`) var recs []fileRec for _, name := range []string{"a", "b", "c", "d", "e"} { recs = append(recs, fileRec{name: name, size: 1, mtime: 1700000000}) } r.s.OnFilePacket(sub, fileListPacket(recs...)) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) if got := sc["files"].([]fileEntry); len(got) != 2 || got[1].Name != "b" { t.Fatalf("page = %#v", got) } if sc["hasMore"] != true { t.Fatalf("hasMore = %v, want true", sc["hasMore"]) } checkInt(t, sc, "totalAll", 5) } func TestListFilesErrorMapping(t *testing.T) { cases := []struct { win32 uint32 code int }{ {5, CodePermission}, {2, CodeNotFound}, {3, CodeNotFound}, {32, CodeInternal}, {0, CodeInternal}, } r := newFileRig(t) for _, c := range cases { ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\missing"}`) r.s.OnFilePacket(sub, fileListErrorPacket(c.win32)) got := r.wait(ch) if got.err == nil { t.Fatalf("win32=%d: call succeeded, want %d", c.win32, c.code) } if got.err.Code != c.code { t.Fatalf("win32=%d: code = %d (%s), want %d", c.win32, got.err.Code, got.err.Message, c.code) } if wire := r.next(sub); !bytes.Equal(wire, []byte{protocol.CommandBye}) { t.Fatalf("win32=%d: retire wire = %v", c.win32, wire) } } } // An error reply can only arrive on the sub-conn, but a client that fails the // drive enumeration itself answers with TOKEN_FILE_LIST_ERROR before any // TOKEN_DRIVE_LIST. The first packet for a waiting call is adopted, so the // raw win32 code reaches the caller instead of a timeout. func TestListFilesErrorBeforeDriveList(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001","path":"C:\\missing"}`) r.next(r.main) sub := r.newSub() if !r.s.OnFilePacket(sub, fileListErrorPacket(2)) { t.Fatal("early error packet was not consumed") } got := r.wait(ch) if got.err == nil || got.err.Code != CodeNotFound { t.Fatalf("err = %#v, want not-found", got.err) } if wire := r.next(sub); !bytes.Equal(wire, []byte{protocol.CommandBye}) { t.Fatalf("retire wire = %v, want COMMAND_BYE", wire) } waitClosed(t, sub) } // cancel is the only place that both clears the pending slot and learns the // sub-conn, so it must hand the sub back for retirement. func TestFileTableCancelReturnsAnsweredSub(t *testing.T) { tbl := newFileTable() req, ok := tbl.begin("1001") if !ok { t.Fatal("begin rejected the first request") } if sub := tbl.cancel("1001", req); sub != nil { t.Fatalf("cancel before any packet returned %p", sub) } req, _ = tbl.begin("1001") ctx := &connection.Context{} if !tbl.deliver("1001", fileEvent{kind: fileEventDriveList, ctx: ctx}) { t.Fatal("drive list was not delivered") } if sub := tbl.cancel("1001", req); sub != ctx { t.Fatalf("cancel returned %p, want the answering sub-conn %p", sub, ctx) } if _, ok := tbl.begin("1001"); !ok { t.Fatal("the slot was not freed") } } // A packet that loses the race with the call's return must not be queued for a // reader that is gone; it is reported as unclaimed so the orphan sub-conn gets // retired. The second half pins the window where deliver already looked the // request up when cancel marked it: the abandoned flag decides. func TestFileTableDeliverAfterCancelIsUnclaimed(t *testing.T) { tbl := newFileTable() req, _ := tbl.begin("1001") tbl.cancel("1001", req) if tbl.deliver("1001", fileEvent{kind: fileEventDriveList, ctx: &connection.Context{}}) { t.Fatal("deliver accepted a packet for an abandoned request") } select { case ev := <-req.ch: t.Fatalf("abandoned request still received %#v", ev) default: } req, _ = tbl.begin("1001") req.mu.Lock() req.abandoned = true req.mu.Unlock() if tbl.deliver("1001", fileEvent{kind: fileEventDriveList, ctx: &connection.Context{}}) { t.Fatal("deliver accepted a packet after the request was abandoned") } } // ----- lifecycle ------------------------------------------------------------ func TestListFilesTimeoutRetiresLateSubConn(t *testing.T) { r := newFileRig(t) fileListTimeout = 40 * time.Millisecond ch := r.call(`{"id":"1001"}`) r.next(r.main) c := r.wait(ch) if c.err == nil || c.err.Code != CodeTimeout { t.Fatalf("err = %#v, want timeout", c.err) } // The client opens its sub-conn after we gave up: it is an orphan and must // be retired, or the client leaks a file-manager thread. sub := r.newSub() if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 1, 1, "本地磁盘", "NTFS"})) { t.Fatal("orphan drive list was not consumed") } if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandBye}) { t.Fatalf("orphan retire wire = %v, want COMMAND_BYE", got) } waitClosed(t, sub) } func TestListFilesTimeoutClearsPending(t *testing.T) { r := newFileRig(t) fileListTimeout = 40 * time.Millisecond ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\slow"}`) _ = sub.Close() // the client drops the sub-conn mid-request c := r.wait(ch) if c.err == nil || c.err.Code != CodeTimeout { t.Fatalf("err = %#v, want timeout", c.err) } r.s.files.mu.Lock() defer r.s.files.mu.Unlock() if len(r.s.files.byDevice) != 0 { t.Fatalf("pending table still holds %d requests", len(r.s.files.byDevice)) } } func TestListFilesDropsForeignSubConnPackets(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001","path":"C:\\"}`) r.next(r.main) real, foreign := r.newSub(), r.newSub() // A file list before the drive-list phase belongs to no known sub-conn. if !r.s.OnFilePacket(foreign, fileListPacket(fileRec{name: "stale"})) { t.Fatal("foreign file list was not claimed by the protocol") } // The real sub-conn announces itself and gets the directory request. r.s.OnFilePacket(real, driveListPacket(driveRec{'C', 3, 1, 1, "本地磁盘", "NTFS"})) r.next(real) // A second drive list from another connection is a duplicate: it is // retired rather than allowed to steal the pending call. r.s.OnFilePacket(foreign, driveListPacket(driveRec{'D', 3, 1, 1, "本地磁盘", "NTFS"})) if got := r.next(foreign); !bytes.Equal(got, []byte{protocol.CommandBye}) { t.Fatalf("duplicate sub-conn retire wire = %v", got) } // A stale file list from the duplicate is ignored, the real one wins. r.s.OnFilePacket(foreign, fileListPacket(fileRec{name: "stale"})) r.s.OnFilePacket(real, fileListPacket(fileRec{name: "good"})) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } files := c.res.StructuredContent.(map[string]any)["files"].([]fileEntry) if len(files) != 1 || files[0].Name != "good" { t.Fatalf("files = %#v, want only the real sub-conn's answer", files) } } func TestListFilesBusyWhenCallPending(t *testing.T) { r := newFileRig(t) ch := r.call(`{"id":"1001"}`) r.next(r.main) if _, rerr := r.s.callListFiles(context.Background(), []byte(`{"id":"1001","path":"C:\\"}`)); rerr == nil || rerr.Code != CodeBusy { t.Fatalf("second call err = %#v, want busy", rerr) } r.s.OnFilePacket(r.newSub(), driveListPacket()) if c := r.wait(ch); c.err != nil { t.Fatalf("first call failed: %d %s", c.err.Code, c.err.Message) } } // ----- parsers -------------------------------------------------------------- func TestParseDriveListStopsAtTerminator(t *testing.T) { pkt := driveListPacket(driveRec{'D', 2, 10, 5, "CD 驱动器", "CDFS"}) // The real client ends by buffer exhaustion; accept an explicit zero-letter // terminator too and stop before the trailing garbage. pkt = append(pkt, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) got := parseDriveList(pkt[1:]) // the parsers see the payload, token removed if len(got) != 1 || got[0].Drive != `D:\` || got[0].TypeName != "CD 驱动器" || got[0].Type != 2 { t.Fatalf("drives = %#v", got) } } func TestParseDriveListTruncated(t *testing.T) { payload := driveListPacket(driveRec{'D', 2, 10, 5, "CD 驱动器", "CDFS"})[1:] for _, n := range []int{0, 5, 12, len(payload) - 3} { if got := parseDriveList(payload[:n]); len(got) != 0 { t.Fatalf("truncated at %d: %#v", n, got) } } } func TestParseFileListBoundaries(t *testing.T) { if got, truncated := parseFileList(nil); len(got) != 0 || truncated { t.Fatalf("nil packet parsed to %#v", got) } payload := fileListPacket(fileRec{name: "a", size: 1, mtime: 1000})[1:] // Chop any part of the fixed tail: the partial record is dropped. for _, n := range []int{0, 1, 3, len(payload) - 1} { if got, _ := parseFileList(payload[:n]); len(got) != 0 { t.Fatalf("truncated at %d: %#v", n, got) } } // Trailing zero padding ends the parse cleanly. if got, truncated := parseFileList(append(payload, 0, 0, 0)); len(got) != 1 || truncated { t.Fatalf("padded packet parsed to %#v", got) } } func TestListFilesTruncationNote(t *testing.T) { // A directory beyond the parse cap must not look like "that is all there // is": the summary says the list was cut. r := newFileRig(t) ch, sub := r.startDirectoryCall(`{"id":"1001","path":"C:\\huge"}`) pkt := []byte{protocol.TokenFileList} for i := 0; i < fileListMaxEntries+1; i++ { pkt = append(pkt, 0, 'a', 0) pkt = append(pkt, make([]byte, 16)...) } r.s.OnFilePacket(sub, pkt) c := r.wait(ch) if c.err != nil { t.Fatalf("call failed: %d %s", c.err.Code, c.err.Message) } sc := c.res.StructuredContent.(map[string]any) checkInt(t, sc, "total", fileListMaxEntries) if v, ok := sc["truncated"].(bool); !ok || !v { t.Fatalf("structuredContent truncated = %#v, want true", sc["truncated"]) } if !strings.Contains(c.res.Content[0].Text, "total 只是上限内的数量") { t.Fatalf("summary does not mention the cap: %q", c.res.Content[0].Text) } // The note must stay on its own line, before the table. if !strings.Contains(c.res.Content[0].Text, "。\nname\tisDir\tsize\tmtime\n") { t.Fatalf("truncation note glued to the table: %q", c.res.Content[0].Text) } } func TestParseFileListEntryCap(t *testing.T) { var buf []byte for i := 0; i < fileListMaxEntries+5; i++ { buf = append(buf, 0, 'a', 0) buf = append(buf, make([]byte, 16)...) } files, truncated := parseFileList(buf) if len(files) != fileListMaxEntries || !truncated { t.Fatalf("parsed %d entries, truncated=%v", len(files), truncated) } } func TestParseFileListAtCapIsNotTruncated(t *testing.T) { // Exactly cap entries followed by the client's zero padding: nothing was // dropped, so the summary must not claim truncation. var buf []byte for i := 0; i < fileListMaxEntries; i++ { buf = append(buf, 0, 'a', 0) buf = append(buf, make([]byte, 16)...) } buf = append(buf, 0, 0, 0) files, truncated := parseFileList(buf) if len(files) != fileListMaxEntries || truncated { t.Fatalf("parsed %d entries, truncated=%v", len(files), truncated) } } // ----- batch (ids) ---------------------------------------------------------- // answerDirectoryCall drives one host through the two-phase file-manager // handshake and answers it with the given entries. It returns after the file // list was delivered, so the next host's drive request can be read. func (r *fileRig) answerDirectoryCall(main *connection.Context, clientID string, path string, files ...fileRec) { r.t.Helper() if got := r.nextIgnoringBye(main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive) } sub := r.newSubFor(clientID) if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"})) { r.t.Fatal("drive-list packet was not consumed") } got := r.next(sub) if got[0] != protocol.CommandListFiles || !bytes.Equal(got[1:len(got)-1], protocol.UTF8ToGBK(path)) { r.t.Fatalf("directory request wire = %v, want %d %q", got, protocol.CommandListFiles, path) } if !r.s.OnFilePacket(sub, fileListPacket(files...)) { r.t.Fatal("file-list packet was not consumed") } } func TestListFilesBatch(t *testing.T) { r := newFileRig(t) main2 := r.registerDevice("1002", "10.0.0.2") ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) r.answerDirectoryCall(r.main, "1001", `C:\`, fileRec{name: "a.txt", size: 3}) r.answerDirectoryCall(main2, "1002", `C:\`, fileRec{name: "b.txt", size: 5}) res := r.wait(ch) if res.err != nil { t.Fatalf("batch failed: %v", res.err) } sc, ok := res.res.StructuredContent.(map[string]any) if !ok { t.Fatalf("structuredContent type = %T", res.res.StructuredContent) } if sc["tool"] != "list_files" { t.Fatalf("tool = %v", sc["tool"]) } checkInt(t, sc, "total", 2) checkInt(t, sc, "succeeded", 2) checkInt(t, sc, "failed", 0) checkInt(t, sc, "skipped", 0) results, ok := sc["results"].([]map[string]any) if !ok || len(results) != 2 { t.Fatalf("results = %#v", sc["results"]) } for i, wantName := range []string{"a.txt", "b.txt"} { if results[i]["id"] != []string{"1001", "1002"}[i] || results[i]["ok"] != true { t.Fatalf("results[%d] = %#v", i, results[i]) } data, ok := results[i]["data"].(map[string]any) if !ok { t.Fatalf("results[%d].data type = %T", i, results[i]["data"]) } files, ok := data["files"].([]fileEntry) if !ok || len(files) != 1 || files[0].Name != wantName { t.Fatalf("results[%d].data.files = %#v", i, data["files"]) } } } func TestListFilesBatchDeadlineSkipsRest(t *testing.T) { r := newFileRig(t) old, oldTimeout := listFilesBatchDeadline, fileListTimeout listFilesBatchDeadline, fileListTimeout = -time.Second, time.Second t.Cleanup(func() { listFilesBatchDeadline, fileListTimeout = old, oldTimeout }) res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":["1001","1002"]}`)) if rerr != nil { t.Fatalf("batch failed: %v", rerr) } sc := res.(toolResult).StructuredContent.(map[string]any) checkInt(t, sc, "total", 2) checkInt(t, sc, "succeeded", 0) checkInt(t, sc, "failed", 0) checkInt(t, sc, "skipped", 2) results := sc["results"].([]map[string]any) for i, entry := range results { if entry["ok"] != false || entry["skipped"] != true { t.Fatalf("results[%d] = %#v", i, entry) } errObj, _ := entry["error"].(map[string]any) if errObj["code"] != CodeTimeout { t.Fatalf("results[%d].error = %#v", i, entry["error"]) } } r.expectNothing() // nothing was attempted } func TestListFilesBatchReportsBadID(t *testing.T) { r := newFileRig(t) res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":["abc"]}`)) if rerr != nil { t.Fatalf("batch failed: %v", rerr) } sc := res.(toolResult).StructuredContent.(map[string]any) checkInt(t, sc, "failed", 1) entry := sc["results"].([]map[string]any)[0] errObj, _ := entry["error"].(map[string]any) if entry["ok"] != false || errObj["code"] != CodeInvalidParams { t.Fatalf("entry = %#v", entry) } r.expectNothing() } func TestListFilesBatchRejectsTooManyIDs(t *testing.T) { r := newFileRig(t) ids := make([]string, listFilesBatchMaxIDs+1) for i := range ids { ids[i] = "1" } body, _ := json.Marshal(map[string]any{"ids": ids}) _, rerr := r.s.callListFiles(context.Background(), body) if rerr == nil || rerr.Code != CodeInvalidParams { t.Fatalf("error = %v, want -32602", rerr) } } func TestListFilesBatchAcceptsEmptyIDs(t *testing.T) { // The schema's anyOf accepts ids alone, including an empty array; Win32 // answers total=0 rather than calling it a missing id. r := newFileRig(t) res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":[]}`)) if rerr != nil { t.Fatalf("batch failed: %v", rerr) } sc := res.(toolResult).StructuredContent.(map[string]any) checkInt(t, sc, "total", 0) checkInt(t, sc, "succeeded", 0) if results := sc["results"].([]map[string]any); len(results) != 0 { t.Fatalf("results = %#v", results) } r.expectNothing() } func TestListFilesBatchReportsBusyHost(t *testing.T) { r := newFileRig(t) main2 := r.registerDevice("1002", "10.0.0.2") if _, ok := r.s.locks.tryAcquire("1001", "get_screenshot"); !ok { t.Fatal("could not take the device lock for the test") } defer r.s.locks.release("1001") ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) r.answerDirectoryCall(main2, "1002", `C:\`, fileRec{name: "b.txt", size: 5}) res := r.wait(ch) if res.err != nil { t.Fatalf("batch failed: %v", res.err) } sc := res.res.StructuredContent.(map[string]any) checkInt(t, sc, "succeeded", 1) checkInt(t, sc, "failed", 1) checkInt(t, sc, "skipped", 0) results := sc["results"].([]map[string]any) busy := results[0] errObj, _ := busy["error"].(map[string]any) if busy["ok"] != false || errObj["code"] != CodeBusy { t.Fatalf("results[0] = %#v", busy) } if results[1]["ok"] != true { t.Fatalf("results[1] = %#v", results[1]) } // The finished host retires its sub-conn with COMMAND_BYE; the locked host // was never contacted. if got := r.nextAny(); !bytes.Equal(got.data, []byte{protocol.CommandBye}) { t.Fatalf("unexpected wire after the batch: %v", got.data) } r.expectNothing() } func TestListFilesBatchRunningHostOutlivesDeadline(t *testing.T) { // Win32's deadline only stops *starting* new hosts: the host already running // gets its own timeout and is recorded as a normal success, not skipped or // "cancelled". r := newFileRig(t) oldDeadline, oldTimeout := listFilesBatchDeadline, fileListTimeout listFilesBatchDeadline, fileListTimeout = 50*time.Millisecond, 5*time.Second t.Cleanup(func() { listFilesBatchDeadline, fileListTimeout = oldDeadline, oldTimeout }) ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) if got := r.next(r.main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { t.Fatalf("drive request wire = %v", got) } sub := r.newSub() if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"})) { t.Fatal("drive-list packet was not consumed") } if got := r.next(sub); got[0] != protocol.CommandListFiles { t.Fatalf("directory request wire = %v", got) } time.Sleep(150 * time.Millisecond) // past the 50 ms batch deadline if !r.s.OnFilePacket(sub, fileListPacket(fileRec{name: "a.txt", size: 3})) { t.Fatal("file-list packet was not consumed") } res := r.wait(ch) if res.err != nil { t.Fatalf("batch failed: %v", res.err) } sc := res.res.StructuredContent.(map[string]any) checkInt(t, sc, "succeeded", 1) checkInt(t, sc, "failed", 0) checkInt(t, sc, "skipped", 1) results := sc["results"].([]map[string]any) if results[0]["ok"] != true { t.Fatalf("results[0] = %#v", results[0]) } if results[1]["ok"] != false || results[1]["skipped"] != true { t.Fatalf("results[1] = %#v", results[1]) } // The finished host retires its sub-conn with COMMAND_BYE; host 1002 got nothing. if got := r.nextAny(); !bytes.Equal(got.data, []byte{protocol.CommandBye}) { t.Fatalf("unexpected wire after the batch: %v", got.data) } r.expectNothing() }