跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

0004-robustness.patch

837 行 · 26.3 KB历史下载
1diff -ruN a/attrs_atime_darwin.go b/attrs_atime_darwin.go
2--- a/attrs_atime_darwin.go 1970-01-01 01:00:00.000000000 +0100
3+++ b/attrs_atime_darwin.go 2026-10-02 22:16:29.708925353 +0200
4@@ -0,0 +1,10 @@
5+//go:build darwin
6+// +build darwin
7+
8+package sftp
9+
10+import "syscall"
11+
12+func statAtime(st *syscall.Stat_t) (int64, bool) {
13+ return int64(st.Atimespec.Sec), true
14+}
15diff -ruN a/attrs_atime_linux.go b/attrs_atime_linux.go
16--- a/attrs_atime_linux.go 1970-01-01 01:00:00.000000000 +0100
17+++ b/attrs_atime_linux.go 2026-10-02 22:16:29.708925353 +0200
18@@ -0,0 +1,10 @@
19+//go:build !android && linux
20+// +build !android,linux
21+
22+package sftp
23+
24+import "syscall"
25+
26+func statAtime(st *syscall.Stat_t) (int64, bool) {
27+ return int64(st.Atim.Sec), true
28+}
29diff -ruN a/attrs_atime_other.go b/attrs_atime_other.go
30--- a/attrs_atime_other.go 1970-01-01 01:00:00.000000000 +0100
31+++ b/attrs_atime_other.go 2026-10-02 22:16:29.708925353 +0200
32@@ -0,0 +1,11 @@
33+//go:build dragonfly || freebsd || netbsd || openbsd || solaris || aix || js || zos
34+// +build dragonfly freebsd netbsd openbsd solaris aix js zos
35+
36+package sftp
37+
38+import "syscall"
39+
40+// statAtime is not implemented here: the access time stays the modification time.
41+func statAtime(*syscall.Stat_t) (int64, bool) {
42+ return 0, false
43+}
44diff -ruN a/attrs_atime_test.go b/attrs_atime_test.go
45--- a/attrs_atime_test.go 1970-01-01 01:00:00.000000000 +0100
46+++ b/attrs_atime_test.go 2026-10-02 22:16:29.708925353 +0200
47@@ -0,0 +1,26 @@
48+//go:build darwin || (!android && linux)
49+// +build darwin !android,linux
50+
51+package sftp
52+
53+import (
54+ "os"
55+ "path/filepath"
56+ "testing"
57+ "time"
58+
59+ "github.com/stretchr/testify/assert"
60+ "github.com/stretchr/testify/require"
61+)
62+
63+func TestFileStatFromInfoAtime(t *testing.T) {
64+ f := filepath.Join(t.TempDir(), "f")
65+ require.NoError(t, os.WriteFile(f, nil, 0o644))
66+ at, mt := time.Unix(1000000000, 0), time.Unix(1500000000, 0)
67+ require.NoError(t, os.Chtimes(f, at, mt))
68+ fi, err := os.Stat(f)
69+ require.NoError(t, err)
70+ _, st := fileStatFromInfo(fi)
71+ assert.Equal(t, uint32(at.Unix()), st.Atime)
72+ assert.Equal(t, uint32(mt.Unix()), st.Mtime)
73+}
74diff -ruN a/attrs_unix.go b/attrs_unix.go
75--- a/attrs_unix.go 2026-10-02 22:07:37.989644104 +0200
76+++ b/attrs_unix.go 2026-10-02 22:16:29.708925353 +0200
77@@ -13,5 +13,8 @@
78 *flags |= sshFileXferAttrUIDGID
79 fileStat.UID = statt.Uid
80 fileStat.GID = statt.Gid
81+ if atime, ok := statAtime(statt); ok {
82+ fileStat.Atime = uint32(atime)
83+ }
84 }
85 }
86diff -ruN a/errno_posix.go b/errno_posix.go
87--- a/errno_posix.go 2026-10-02 22:07:37.989644104 +0200
88+++ b/errno_posix.go 2026-10-02 22:16:29.708925353 +0200
89@@ -4,6 +4,8 @@
90 package sftp
91
92 import (
93+ "errors"
94+ "io/fs"
95 "os"
96 "syscall"
97 )
98@@ -17,29 +19,38 @@
99 return err
100 }
101
102-// translateErrno translates a syscall error number to a SFTP error code.
103+// translateErrno translates a syscall error number to a SFTP error code,
104+// as OpenSSH's errno_to_portable does.
105 func translateErrno(errno syscall.Errno) uint32 {
106 switch errno {
107 case 0:
108 return sshFxOk
109- case syscall.ENOENT:
110+ case syscall.ENOENT, syscall.ENOTDIR, syscall.ELOOP:
111 return sshFxNoSuchFile
112 case syscall.EACCES, syscall.EPERM:
113 return sshFxPermissionDenied
114+ case syscall.ENAMETOOLONG, syscall.EINVAL:
115+ return sshFxBadMessage
116+ case syscall.ENOSYS:
117+ return sshFxOPUnsupported
118+ }
119+ // Errors of other systems with the same meaning, such as ERROR_ACCESS_DENIED on Windows.
120+ switch {
121+ case errors.Is(errno, fs.ErrNotExist):
122+ return sshFxNoSuchFile
123+ case errors.Is(errno, fs.ErrPermission):
124+ return sshFxPermissionDenied
125 }
126-
127 return sshFxFailure
128 }
129
130+// translateSyscallError finds a syscall.Errno in err, also wrapped in an
131+// *os.PathError, *os.LinkError or *os.SyscallError.
132 func translateSyscallError(err error) (uint32, bool) {
133- switch e := err.(type) {
134- case syscall.Errno:
135- return translateErrno(e), true
136- case *os.PathError:
137- debug("statusFromError,pathError: error is %T %#v", e.Err, e.Err)
138- if errno, ok := e.Err.(syscall.Errno); ok {
139- return translateErrno(errno), true
140- }
141+ var errno syscall.Errno
142+ if errors.As(err, &errno) {
143+ debug("statusFromError: errno %#v in %T", errno, err)
144+ return translateErrno(errno), true
145 }
146 return 0, false
147 }
148diff -ruN a/packet-manager.go b/packet-manager.go
149--- a/packet-manager.go 2026-10-02 22:07:37.989644104 +0200
150+++ b/packet-manager.go 2026-10-02 22:16:29.708925353 +0200
151@@ -85,7 +85,8 @@
152
153 func (o orderedPackets) Sort() {
154 sort.Slice(o, func(i, j int) bool {
155- return o[i].orderID() < o[j].orderID()
156+ // The difference, not the values: orderIDs wrap around after 2^32 packets.
157+ return int32(o[i].orderID()-o[j].orderID()) < 0
158 })
159 }
160
161@@ -142,7 +143,7 @@
162 pktChan := make(chan orderedRequest, SftpServerWorkerCount)
163 go func() {
164 for pkt := range pktChan {
165- switch pkt.requestPacket.(type) {
166+ switch p := pkt.requestPacket.(type) {
167 case *sshFxpReadPacket, *sshFxpWritePacket:
168 s.incomingPacket(pkt)
169 rwChan <- pkt
170@@ -151,6 +152,11 @@
171 // wait for reads/writes to finish when file is closed
172 // incomingPacket() call must occur after this
173 s.working.Wait()
174+ case *sshFxpExtendedPacket:
175+ // and before syncing the file they wrote
176+ if _, ok := p.SpecificPacket.(*sshFxpFsyncPacket); ok {
177+ s.working.Wait()
178+ }
179 }
180 s.incomingPacket(pkt)
181 // all non-RW use sequential cmdChan
182diff -ruN a/packet.go b/packet.go
183--- a/packet.go 2026-10-02 22:07:37.989644104 +0200
184+++ b/packet.go 2026-10-02 22:16:29.708925353 +0200
185@@ -1304,6 +1304,31 @@
186 return b, nil
187 }
188
189+func (p *sshFxpFsyncPacket) readonly() bool { return true }
190+
191+func (p *sshFxpFsyncPacket) UnmarshalBinary(b []byte) error {
192+ var err error
193+ if p.ID, b, err = unmarshalUint32Safe(b); err != nil {
194+ return err
195+ } else if _, b, err = unmarshalStringSafe(b); err != nil {
196+ return err
197+ } else if p.Handle, _, err = unmarshalStringSafe(b); err != nil {
198+ return err
199+ }
200+ return nil
201+}
202+
203+func (p *sshFxpFsyncPacket) respond(svr *Server) responsePacket {
204+ f, ok := svr.getHandle(p.Handle)
205+ if !ok {
206+ return statusFromError(p.ID, EBADF)
207+ }
208+ if s, ok := f.(interface{ Sync() error }); ok {
209+ return statusFromError(p.ID, s.Sync())
210+ }
211+ return statusFromError(p.ID, ErrSSHFxOpUnsupported)
212+}
213+
214 type sshFxpExtendedPacket struct {
215 ID uint32
216 ExtendedRequest string
217@@ -1345,6 +1370,8 @@
218 p.SpecificPacket = &sshFxpExtendedPacketPosixRename{}
219 case "[email protected]":
220 p.SpecificPacket = &sshFxpExtendedPacketHardlink{}
221+ case "[email protected]":
222+ p.SpecificPacket = &sshFxpFsyncPacket{}
223 default:
224 return fmt.Errorf("packet type %v: %w", p.SpecificPacket, errUnknownExtendedPacket)
225 }
226@@ -1409,7 +1436,7 @@
227
228 // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL
229 func (p *sshFxpExtendedPacketHardlink) id() uint32 { return p.ID }
230-func (p *sshFxpExtendedPacketHardlink) readonly() bool { return true }
231+func (p *sshFxpExtendedPacketHardlink) readonly() bool { return false }
232 func (p *sshFxpExtendedPacketHardlink) UnmarshalBinary(b []byte) error {
233 var err error
234 if p.ID, b, err = unmarshalUint32Safe(b); err != nil {
235diff -ruN a/request-server.go b/request-server.go
236--- a/request-server.go 2026-10-02 22:07:37.989644104 +0200
237+++ b/request-server.go 2026-10-02 22:16:29.708925353 +0200
238@@ -3,9 +3,11 @@
239 import (
240 "context"
241 "errors"
242+ "fmt"
243 "io"
244 "path"
245 "path/filepath"
246+ rdebug "runtime/debug"
247 "strconv"
248 "sync"
249 )
250@@ -29,6 +31,7 @@
251
252 startDirectory string
253 maxTxPacket uint32
254+ maxHandles int
255
256 mu sync.RWMutex
257 handleCount int
258@@ -74,6 +77,14 @@
259 }
260 }
261
262+// WithRSMaxHandles makes OPEN and OPENDIR fail once n handles are open.
263+// By default there is no limit, and each handle may hold a file descriptor and memory.
264+func WithRSMaxHandles(n int) RequestServerOption {
265+ return func(rs *RequestServer) {
266+ rs.maxHandles = n
267+ }
268+}
269+
270 // WithRSSequential processes requests one at a time, in the order they are received.
271 //
272 // By default, reads and writes run concurrently with each other and with the other
273@@ -126,6 +137,18 @@
274 return r.handle
275 }
276
277+// handleLimitReached reports whether no more handle may be opened (see WithRSMaxHandles).
278+func (rs *RequestServer) handleLimitReached() bool {
279+ if rs.maxHandles <= 0 {
280+ return false
281+ }
282+ rs.mu.RLock()
283+ defer rs.mu.RUnlock()
284+ return len(rs.openRequests) >= rs.maxHandles
285+}
286+
287+var errTooManyHandles = errors.New("too many open handles")
288+
289 // Returns Request from openRequests, bool is false if it is missing.
290 //
291 // The Requests in openRequests work essentially as open file descriptors that
292@@ -240,105 +263,135 @@
293 }
294 }
295
296- var rpkt responsePacket
297- switch pkt := pkt.requestPacket.(type) {
298- case *sshFxInitPacket:
299- rpkt = &sshFxVersionPacket{Version: sftpProtocolVersion, Extensions: sftpExtensions}
300- case *sshFxpClosePacket:
301- handle := pkt.getHandle()
302- rpkt = statusFromError(pkt.ID, rs.closeRequest(handle))
303- case *sshFxpRealpathPacket:
304- var realPath string
305- var err error
306-
307- switch pather := rs.Handlers.FileList.(type) {
308- case RealPathFileLister:
309- realPath, err = pather.RealPath(pkt.getPath())
310- case legacyRealPathFileLister:
311- realPath = pather.RealPath(pkt.getPath())
312- default:
313- realPath = cleanPathWithBase(rs.startDirectory, pkt.getPath())
314- }
315- if err != nil {
316- rpkt = statusFromError(pkt.ID, err)
317- } else {
318- rpkt = cleanPacketPath(pkt, realPath)
319- }
320- case *sshFxpOpendirPacket:
321- request := requestFromPacket(ctx, pkt, rs.startDirectory)
322- handle := rs.nextRequest(request)
323- rpkt = request.opendir(rs.Handlers, pkt)
324- if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
325- // if we return an error we have to remove the handle from the active ones
326- rs.closeRequest(handle)
327- }
328- case *sshFxpOpenPacket:
329- request := requestFromPacket(ctx, pkt, rs.startDirectory)
330- handle := rs.nextRequest(request)
331- rpkt = request.open(rs.Handlers, pkt)
332- if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
333- // if we return an error we have to remove the handle from the active ones
334- rs.closeRequest(handle)
335- }
336- case *sshFxpFstatPacket:
337- handle := pkt.getHandle()
338- request, ok := rs.getRequest(handle)
339- if !ok {
340- rpkt = statusFromError(pkt.ID, EBADF)
341- } else {
342- request = &Request{
343- Method: "Stat",
344- Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
345- handleFile: request.opened(),
346- }
347- rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
348- }
349- case *sshFxpFsetstatPacket:
350- handle := pkt.getHandle()
351- request, ok := rs.getRequest(handle)
352- if !ok {
353- rpkt = statusFromError(pkt.ID, EBADF)
354- } else {
355- request = &Request{
356- Method: "Setstat",
357- Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
358- handleFile: request.opened(),
359- }
360- rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
361- }
362- case *sshFxpExtendedPacketPosixRename:
363- request := &Request{
364- Method: "PosixRename",
365- Filepath: cleanPathWithBase(rs.startDirectory, pkt.Oldpath),
366- Target: cleanPathWithBase(rs.startDirectory, pkt.Newpath),
367+ rpkt := rs.handlePacket(ctx, pkt.requestPacket, orderID)
368+
369+ rs.pktMgr.readyPacket(
370+ rs.pktMgr.newOrderedResponse(rpkt, orderID))
371+ }
372+ return nil
373+}
374+
375+// handlePacket answers one packet. A panic in a handler fails that request, instead of
376+// the whole process, which may serve other connections or, as in Lima, run the VM.
377+func (rs *RequestServer) handlePacket(ctx context.Context, pkt requestPacket, orderID uint32) (rpkt responsePacket) {
378+ defer func() {
379+ if p := recover(); p != nil {
380+ debug("handlePacket: panic: %v\n%s", p, rdebug.Stack())
381+ rpkt = statusFromError(pkt.id(), fmt.Errorf("sftp server: internal error: %v", p))
382+ }
383+ }()
384+
385+ switch pkt := pkt.(type) {
386+ case *sshFxInitPacket:
387+ rpkt = &sshFxVersionPacket{Version: sftpProtocolVersion, Extensions: sftpExtensions}
388+ case *sshFxpClosePacket:
389+ handle := pkt.getHandle()
390+ rpkt = statusFromError(pkt.ID, rs.closeRequest(handle))
391+ case *sshFxpRealpathPacket:
392+ var realPath string
393+ var err error
394+
395+ switch pather := rs.Handlers.FileList.(type) {
396+ case RealPathFileLister:
397+ realPath, err = pather.RealPath(pkt.getPath())
398+ case legacyRealPathFileLister:
399+ realPath = pather.RealPath(pkt.getPath())
400+ default:
401+ realPath = cleanPathWithBase(rs.startDirectory, pkt.getPath())
402+ }
403+ if err != nil {
404+ rpkt = statusFromError(pkt.ID, err)
405+ } else {
406+ rpkt = cleanPacketPath(pkt, realPath)
407+ }
408+ case *sshFxpFsyncPacket:
409+ request, ok := rs.getRequest(pkt.Handle)
410+ if !ok {
411+ rpkt = statusFromError(pkt.ID, EBADF)
412+ } else if s, ok := request.opened().(interface{ Sync() error }); ok {
413+ rpkt = statusFromError(pkt.ID, s.Sync())
414+ } else {
415+ rpkt = statusFromError(pkt.ID, ErrSSHFxOpUnsupported)
416+ }
417+ case *sshFxpOpendirPacket:
418+ if rs.handleLimitReached() {
419+ rpkt = statusFromError(pkt.ID, errTooManyHandles)
420+ break
421+ }
422+ request := requestFromPacket(ctx, pkt, rs.startDirectory)
423+ handle := rs.nextRequest(request)
424+ rpkt = request.opendir(rs.Handlers, pkt)
425+ if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
426+ // if we return an error we have to remove the handle from the active ones
427+ rs.closeRequest(handle)
428+ }
429+ case *sshFxpOpenPacket:
430+ if rs.handleLimitReached() {
431+ rpkt = statusFromError(pkt.ID, errTooManyHandles)
432+ break
433+ }
434+ request := requestFromPacket(ctx, pkt, rs.startDirectory)
435+ handle := rs.nextRequest(request)
436+ rpkt = request.open(rs.Handlers, pkt)
437+ if _, ok := rpkt.(*sshFxpHandlePacket); !ok {
438+ // if we return an error we have to remove the handle from the active ones
439+ rs.closeRequest(handle)
440+ }
441+ case *sshFxpFstatPacket:
442+ handle := pkt.getHandle()
443+ request, ok := rs.getRequest(handle)
444+ if !ok {
445+ rpkt = statusFromError(pkt.ID, EBADF)
446+ } else {
447+ request = &Request{
448+ Method: "Stat",
449+ Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
450+ handleFile: request.opened(),
451 }
452 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
453- case *sshFxpExtendedPacketStatVFS:
454- request := &Request{
455- Method: "StatVFS",
456- Filepath: cleanPathWithBase(rs.startDirectory, pkt.Path),
457+ }
458+ case *sshFxpFsetstatPacket:
459+ handle := pkt.getHandle()
460+ request, ok := rs.getRequest(handle)
461+ if !ok {
462+ rpkt = statusFromError(pkt.ID, EBADF)
463+ } else {
464+ request = &Request{
465+ Method: "Setstat",
466+ Filepath: cleanPathWithBase(rs.startDirectory, request.Filepath),
467+ handleFile: request.opened(),
468 }
469 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
470- case hasHandle:
471- handle := pkt.getHandle()
472- request, ok := rs.getRequest(handle)
473- if !ok {
474- rpkt = statusFromError(pkt.id(), EBADF)
475- } else {
476- rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
477- }
478- case hasPath:
479- request := requestFromPacket(ctx, pkt, rs.startDirectory)
480+ }
481+ case *sshFxpExtendedPacketPosixRename:
482+ request := &Request{
483+ Method: "PosixRename",
484+ Filepath: cleanPathWithBase(rs.startDirectory, pkt.Oldpath),
485+ Target: cleanPathWithBase(rs.startDirectory, pkt.Newpath),
486+ }
487+ rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
488+ case *sshFxpExtendedPacketStatVFS:
489+ request := &Request{
490+ Method: "StatVFS",
491+ Filepath: cleanPathWithBase(rs.startDirectory, pkt.Path),
492+ }
493+ rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
494+ case hasHandle:
495+ handle := pkt.getHandle()
496+ request, ok := rs.getRequest(handle)
497+ if !ok {
498+ rpkt = statusFromError(pkt.id(), EBADF)
499+ } else {
500 rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
501- request.close()
502- default:
503- rpkt = statusFromError(pkt.id(), ErrSSHFxOpUnsupported)
504 }
505-
506- rs.pktMgr.readyPacket(
507- rs.pktMgr.newOrderedResponse(rpkt, orderID))
508+ case hasPath:
509+ request := requestFromPacket(ctx, pkt, rs.startDirectory)
510+ rpkt = request.call(rs.Handlers, pkt, rs.pktMgr.alloc, orderID, rs.maxTxPacket)
511+ request.close()
512+ default:
513+ rpkt = statusFromError(pkt.id(), ErrSSHFxOpUnsupported)
514 }
515- return nil
516+ return rpkt
517 }
518
519 // clean and return name packet for file
520diff -ruN a/request-server_robust_test.go b/request-server_robust_test.go
521--- a/request-server_robust_test.go 1970-01-01 01:00:00.000000000 +0100
522+++ b/request-server_robust_test.go 2026-10-02 22:16:29.708925353 +0200
523@@ -0,0 +1,256 @@
524+//go:build !plan9
525+// +build !plan9
526+
527+package sftp
528+
529+import (
530+ "io"
531+ "math"
532+ "net"
533+ "os"
534+ "path/filepath"
535+ "sync/atomic"
536+ "syscall"
537+ "testing"
538+ "time"
539+
540+ "github.com/stretchr/testify/assert"
541+ "github.com/stretchr/testify/require"
542+)
543+
544+// osHandlers serves dir with *os.File handles, write-only opens get an O_WRONLY file.
545+// Stat of "/panic" panics, Stat of "/slow" takes 100ms.
546+type osHandlers struct {
547+ dir string
548+}
549+
550+func (h *osHandlers) p(r *Request) string { return filepath.Join(h.dir, r.Filepath) }
551+
552+func (h *osHandlers) Fileread(r *Request) (io.ReaderAt, error) { return os.Open(h.p(r)) }
553+func (h *osHandlers) Filewrite(r *Request) (io.WriterAt, error) {
554+ return os.OpenFile(h.p(r), os.O_WRONLY|os.O_CREATE, 0o644)
555+}
556+func (h *osHandlers) OpenFile(r *Request) (WriterAtReaderAt, error) {
557+ return os.OpenFile(h.p(r), os.O_RDWR|os.O_CREATE, 0o644)
558+}
559+func (h *osHandlers) Filecmd(r *Request) error { return ErrSSHFxOpUnsupported }
560+func (h *osHandlers) Filelist(r *Request) (ListerAt, error) {
561+ switch r.Filepath {
562+ case "/panic":
563+ panic("handler bug")
564+ case "/slow":
565+ time.Sleep(100 * time.Millisecond)
566+ }
567+ if r.Method == "List" {
568+ f, err := os.Open(h.p(r))
569+ if err != nil {
570+ return nil, err
571+ }
572+ defer f.Close()
573+ fis, err := f.Readdir(-1)
574+ return listerat(fis), err
575+ }
576+ fi, err := os.Stat(h.p(r))
577+ if err != nil {
578+ return nil, err
579+ }
580+ return listerat{fi}, nil
581+}
582+
583+// rawClient sends packets a well-behaved client would not.
584+type rawClient struct {
585+ t *testing.T
586+ c net.Conn
587+ rs *RequestServer
588+ id uint32
589+}
590+
591+func newRawClient(t *testing.T, h Handlers, opts ...RequestServerOption) *rawClient {
592+ a, b := net.Pipe()
593+ rs := NewRequestServer(a, h, append([]RequestServerOption{WithRSSequential()}, opts...)...)
594+ go rs.Serve()
595+ t.Cleanup(func() { b.Close() })
596+ return &rawClient{t: t, c: b, rs: rs}
597+}
598+
599+type rawPacket []byte
600+
601+func (b rawPacket) MarshalBinary() ([]byte, error) { return b, nil }
602+
603+func (r *rawClient) send(typ byte, fields ...any) uint32 {
604+ r.id++
605+ b := []byte{0, 0, 0, 0, typ}
606+ b = marshalUint32(b, r.id)
607+ for _, f := range fields {
608+ b = marshal(b, f)
609+ }
610+ require.NoError(r.t, sendPacket(r.c, rawPacket(b)))
611+ return r.id
612+}
613+
614+func (r *rawClient) recv() (fxp, []byte) {
615+ require.NoError(r.t, r.c.SetReadDeadline(time.Now().Add(5*time.Second)))
616+ typ, data, err := recvPacket(r.c, nil, 0)
617+ require.NoError(r.t, err)
618+ return typ, data
619+}
620+
621+// status returns the code of a STATUS response, or fails.
622+func (r *rawClient) status() uint32 {
623+ typ, data := r.recv()
624+ require.Equal(r.t, fxp(sshFxpStatus), typ)
625+ _, data = unmarshalUint32(data)
626+ code, _ := unmarshalUint32(data)
627+ return code
628+}
629+
630+func (r *rawClient) handle(typ byte, path string, fields ...any) string {
631+ r.send(typ, append([]any{path}, fields...)...)
632+ rtyp, data := r.recv()
633+ require.Equal(r.t, fxp(sshFxpHandle), rtyp)
634+ _, data = unmarshalUint32(data)
635+ h, _ := unmarshalString(data)
636+ return h
637+}
638+
639+// A handle only answers the packets of what it was opened for.
640+func TestRequestHandlePacketMismatch(t *testing.T) {
641+ dir := t.TempDir()
642+ require.NoError(t, os.WriteFile(filepath.Join(dir, "f"), []byte("hello"), 0o644))
643+ require.NoError(t, os.WriteFile(filepath.Join(dir, "g"), nil, 0o644))
644+ h := &osHandlers{dir: dir}
645+ c := newRawClient(t, Handlers{h, h, h, h})
646+
647+ wh := c.handle(sshFxpOpen, "/f", uint32(sshFxfWrite), uint32(0))
648+ rh := c.handle(sshFxpOpen, "/f", uint32(sshFxfRead), uint32(0))
649+ dh := c.handle(sshFxpOpendir, "/")
650+
651+ c.send(sshFxpRead, wh, uint64(10), uint32(100))
652+ assert.NotEqual(t, uint32(sshFxOk), c.status(), "READ on a write-only handle")
653+ c.send(sshFxpWrite, rh, uint64(0), "XXXX")
654+ assert.NotEqual(t, uint32(sshFxOk), c.status(), "WRITE on a read-only handle")
655+ c.send(sshFxpReaddir, rh)
656+ assert.NotEqual(t, uint32(sshFxOk), c.status(), "READDIR on a file handle")
657+ c.send(sshFxpRead, dh, uint64(0), uint32(100))
658+ assert.NotEqual(t, uint32(sshFxOk), c.status(), "READ on a directory handle")
659+
660+ b, err := os.ReadFile(filepath.Join(dir, "f"))
661+ require.NoError(t, err)
662+ assert.Equal(t, "hello", string(b))
663+ c.send(sshFxpReaddir, dh)
664+ typ, data := c.recv()
665+ require.Equal(t, fxp(sshFxpName), typ, "the READ must not have consumed the entries")
666+ _, data = unmarshalUint32(data)
667+ n, _ := unmarshalUint32(data)
668+ assert.Equal(t, uint32(2), n)
669+}
670+
671+func TestRequestServerMaxHandles(t *testing.T) {
672+ dir := t.TempDir()
673+ require.NoError(t, os.WriteFile(filepath.Join(dir, "f"), nil, 0o644))
674+ h := &osHandlers{dir: dir}
675+ c := newRawClient(t, Handlers{h, h, h, h}, WithRSMaxHandles(2))
676+
677+ first := c.handle(sshFxpOpen, "/f", uint32(sshFxfRead), uint32(0))
678+ c.handle(sshFxpOpendir, "/")
679+ c.send(sshFxpOpen, "/f", uint32(sshFxfRead), uint32(0))
680+ assert.Equal(t, uint32(sshFxFailure), c.status(), "OPEN over the limit")
681+ c.send(sshFxpOpendir, "/")
682+ assert.Equal(t, uint32(sshFxFailure), c.status(), "OPENDIR over the limit")
683+ c.send(sshFxpClose, first)
684+ require.Equal(t, uint32(sshFxOk), c.status())
685+ c.handle(sshFxpOpen, "/f", uint32(sshFxfRead), uint32(0))
686+}
687+
688+// A panic in a handler fails its request, the server keeps serving.
689+func TestRequestServerHandlerPanic(t *testing.T) {
690+ h := &osHandlers{dir: t.TempDir()}
691+ c := newRawClient(t, Handlers{h, h, h, h})
692+ c.send(sshFxpStat, "/panic")
693+ assert.Equal(t, uint32(sshFxFailure), c.status())
694+ c.send(sshFxpStat, "/")
695+ typ, _ := c.recv()
696+ assert.Equal(t, fxp(sshFxpAttrs), typ)
697+}
698+
699+type syncCounter struct {
700+ *os.File
701+ n *atomic.Int32
702+}
703+
704+func (s syncCounter) Sync() error {
705+ s.n.Add(1)
706+ return s.File.Sync()
707+}
708+
709+type syncHandlers struct {
710+ *osHandlers
711+ n atomic.Int32
712+}
713+
714+func (h *syncHandlers) Filewrite(r *Request) (io.WriterAt, error) {
715+ f, err := os.OpenFile(h.p(r), os.O_WRONLY|os.O_CREATE, 0o644)
716+ if err != nil {
717+ return nil, err
718+ }
719+ return syncCounter{f, &h.n}, nil
720+}
721+
722+func TestRequestFsync(t *testing.T) {
723+ h := &syncHandlers{osHandlers: &osHandlers{dir: t.TempDir()}}
724+ c := newRawClient(t, Handlers{h, h, h, h})
725+ c.send(sshFxpInit) // INIT has a version where other packets have an id
726+ typ, data := c.recv()
727+ require.Equal(t, fxp(sshFxpVersion), typ)
728+ assert.Contains(t, string(data), "[email protected]")
729+
730+ wh := c.handle(sshFxpOpen, "/f", uint32(sshFxfWrite|sshFxfCreat), uint32(0))
731+ c.send(sshFxpExtended, "[email protected]", wh)
732+ assert.Equal(t, uint32(sshFxOk), c.status())
733+ assert.Equal(t, int32(1), h.n.Load())
734+
735+ dh := c.handle(sshFxpOpendir, "/")
736+ c.send(sshFxpExtended, "[email protected]", dh)
737+ assert.Equal(t, uint32(sshFxOPUnsupported), c.status())
738+ c.send(sshFxpExtended, "[email protected]", "nope")
739+ assert.NotEqual(t, uint32(sshFxOk), c.status())
740+}
741+
742+// Responses keep their order when orderIDs wrap around.
743+func TestRequestServerOrderIDWrap(t *testing.T) {
744+ dir := t.TempDir()
745+ require.NoError(t, os.WriteFile(filepath.Join(dir, "slow"), nil, 0o644))
746+ h := &osHandlers{dir: dir}
747+ a, b := net.Pipe()
748+ rs := NewRequestServer(a, Handlers{h, h, h, h})
749+ rs.pktMgr.packetCount = math.MaxUint32 - 1
750+ go rs.Serve()
751+ t.Cleanup(func() { b.Close() })
752+ c := &rawClient{t: t, c: b, rs: rs}
753+
754+ id1 := c.send(sshFxpStat, "/slow")
755+ id2 := c.send(sshFxpStat, "/")
756+ _, d1 := c.recv()
757+ _, d2 := c.recv()
758+ g1, _ := unmarshalUint32(d1)
759+ g2, _ := unmarshalUint32(d2)
760+ assert.Equal(t, []uint32{id1, id2}, []uint32{g1, g2})
761+}
762+
763+func TestStatusFromErrorErrno(t *testing.T) {
764+ for _, tc := range []struct {
765+ err error
766+ code uint32
767+ }{
768+ {&os.LinkError{Op: "rename", Old: "a", New: "b", Err: syscall.EACCES}, sshFxPermissionDenied},
769+ {&os.SyscallError{Syscall: "x", Err: syscall.EPERM}, sshFxPermissionDenied},
770+ {&os.PathError{Op: "open", Path: "x", Err: syscall.ENOTDIR}, sshFxNoSuchFile},
771+ {&os.PathError{Op: "open", Path: "x", Err: syscall.ELOOP}, sshFxNoSuchFile},
772+ {&os.PathError{Op: "open", Path: "x", Err: syscall.ENAMETOOLONG}, sshFxBadMessage},
773+ {syscall.EINVAL, sshFxBadMessage},
774+ {syscall.ENOSYS, sshFxOPUnsupported},
775+ {syscall.EEXIST, sshFxFailure},
776+ } {
777+ assert.Equal(t, tc.code, statusFromError(1, tc.err).Code, "%v", tc.err)
778+ }
779+}
780diff -ruN a/request-server_test.go b/request-server_test.go
781--- a/request-server_test.go 2026-10-02 22:07:37.989644104 +0200
782+++ b/request-server_test.go 2026-10-02 22:16:29.708925353 +0200
783@@ -779,14 +779,9 @@
784 t.Fatal("expected no error, got:", err)
785 }
786 }
787+ // ENOTDIR is SSH_FX_NO_SUCH_FILE, as in OpenSSH's sftp-server.
788 _, err := p.cli.ReadDir("/foo_01")
789- if runtime.GOOS == "zos" {
790- assert.Equal(t, &StatusError{Code: sshFxFailure,
791- msg: " /foo_01: EDC5135I Not a directory."}, err)
792- } else {
793- assert.Equal(t, &StatusError{Code: sshFxFailure,
794- msg: " /foo_01: not a directory"}, err)
795- }
796+ assert.Equal(t, os.ErrNotExist, err)
797 _, err = p.cli.ReadDir("/does_not_exist")
798 assert.Equal(t, os.ErrNotExist, err)
799 di, err := p.cli.ReadDir("/")
800diff -ruN a/request.go b/request.go
801--- a/request.go 2026-10-02 22:07:37.989644104 +0200
802+++ b/request.go 2026-10-02 22:16:29.708925353 +0200
803@@ -337,6 +337,23 @@
804
805 // called from worker to handle packet/request
806 func (r *Request) call(handlers Handlers, pkt requestPacket, alloc *allocator, orderID uint32, maxTxPacket uint32) responsePacket {
807+ // A handle only serves the packets of what it was opened for: otherwise a READ on a
808+ // write-only handle would write its zeroed buffer, and a READ on a directory consume entries.
809+ var allowed bool
810+ switch pkt.(type) {
811+ case *sshFxpReadPacket:
812+ allowed = r.Method == "Get" || r.Method == "Open"
813+ case *sshFxpWritePacket:
814+ allowed = r.Method == "Put" || r.Method == "Open"
815+ case *sshFxpReaddirPacket:
816+ allowed = r.Method == "List"
817+ default:
818+ allowed = true
819+ }
820+ if !allowed {
821+ return statusFromError(pkt.id(), EBADF)
822+ }
823+
824 switch r.Method {
825 case "Get":
826 return fileget(handlers.FileGet, r, pkt, alloc, orderID, maxTxPacket)
827diff -ruN a/sftp.go b/sftp.go
828--- a/sftp.go 2026-10-02 22:07:37.989644104 +0200
829+++ b/sftp.go 2026-10-02 22:16:29.708925353 +0200
830@@ -89,6 +89,7 @@
831 {"[email protected]", "1"},
832 {"[email protected]", "1"},
833 {"[email protected]", "2"},
834+ {"[email protected]", "1"},
835 }
836 sftpExtensions = supportedSFTPExtensions
837 )