跳到主要内容

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

浏览文件

0009-relay-ignore-own-removals.patch

495 行 · 15.4 KB历史下载
1diff --git a/pkg/reversesshfs/reversesshfs.go b/pkg/reversesshfs/reversesshfs.go
2index fe77c0f..4aae8ea 100644
3--- a/pkg/reversesshfs/reversesshfs.go
4+++ b/pkg/reversesshfs/reversesshfs.go
5@@ -51,14 +51,14 @@ type ReverseSSHFS struct {
6 // ExpectRemove makes the next removal of hostPath requested by the remote, within a few seconds,
7 // succeed without touching hostPath. It is used to relay a local deletion to the remote,
8 // by removing the path there, which emits an inotify event on the remote.
9-// It returns false when unsupported, i.e., when not using DriverBuiltin on Linux, macOS, or Windows.
10+// It returns false, and the removal must not be relayed, when unsupported (not using DriverBuiltin
11+// on Linux, macOS, or Windows), or when the remote itself just removed or moved away hostPath.
12 func (rsf *ReverseSSHFS) ExpectRemove(hostPath string) bool {
13 h := rsf.rooted.Load()
14 if h == nil {
15 return false
16 }
17- h.expectRemove(hostPath)
18- return true
19+ return h.expectRemove(hostPath)
20 }
21
22 func (rsf *ReverseSSHFS) Prepare() error {
23diff --git a/pkg/reversesshfs/rooted.go b/pkg/reversesshfs/rooted.go
24index 77b9ce8..84fb0b2 100644
25--- a/pkg/reversesshfs/rooted.go
26+++ b/pkg/reversesshfs/rooted.go
27@@ -34,16 +34,14 @@ type rootedHandlers struct {
28 guardRoot string // the served directory as Guard is told
29 rootedSys
30
31- mu sync.Mutex
32- noopRemovals map[string]time.Time // expiry, keyed by request path
33+ mu sync.Mutex // protects relay
34+ relay *relay
35+ now func() time.Time
36 }
37
38 // maxHandles bounds the files and directories a client keeps open.
39 const maxHandles = 4096
40
41-// noopRemovalTTL bounds how long an ExpectRemove token waits for the guest.
42-const noopRemovalTTL = 5 * time.Second
43-
44 func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, readonlyNames []string) (*sftp.RequestServer, *rootedHandlers, error) {
45 root, err := os.OpenRoot(localPath)
46 if err != nil {
47@@ -61,7 +59,8 @@ func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, re
48 readonlyNames: readonlyNames,
49 guardRoot: filepath.Clean(localPath),
50 rootedSys: sys,
51- noopRemovals: make(map[string]time.Time),
52+ relay: newRelay(),
53+ now: time.Now,
54 }
55 for _, n := range readonlyNames {
56 h.foldedNames = append(h.foldedNames, FoldName(n))
57@@ -81,33 +80,6 @@ func (h *rootedHandlers) Close() error {
58 return errors.Join(h.root.Close(), h.rootedSys.close())
59 }
60
61-// expectRemove makes the next Remove or Rmdir request for p, within noopRemovalTTL,
62-// succeed without touching the host. p is a host path under the root.
63-func (h *rootedHandlers) expectRemove(p string) {
64- p = slashPath(p)
65- now := time.Now()
66- h.mu.Lock()
67- defer h.mu.Unlock()
68- for k, expiry := range h.noopRemovals {
69- if now.After(expiry) {
70- delete(h.noopRemovals, k)
71- }
72- }
73- h.noopRemovals[p] = now.Add(noopRemovalTTL)
74-}
75-
76-func (h *rootedHandlers) consumeNoopRemoval(p string) bool {
77- p = path.Clean(p)
78- h.mu.Lock()
79- defer h.mu.Unlock()
80- expiry, ok := h.noopRemovals[p]
81- if !ok {
82- return false
83- }
84- delete(h.noopRemovals, p)
85- return time.Now().Before(expiry)
86-}
87-
88 // rel maps a request path to a path relative to the root.
89 // The result has no "." or ".." component, except "." for the root itself.
90 func (h *rootedHandlers) rel(p string) (string, error) {
91@@ -236,6 +208,9 @@ func (f writableFile) WriteAt(b []byte, off int64) (int, error) {
92 }
93
94 func (h *rootedHandlers) openWritable(r *sftp.Request) (writableFile, error) {
95+ if r.Pflags().Creat {
96+ h.creating(r.Filepath)
97+ }
98 f, err := h.openFile(r)
99 if err != nil {
100 return writableFile{}, err
101@@ -293,8 +268,9 @@ func (h *rootedHandlers) Filecmd(r *sftp.Request) error {
102 }
103 return h.setstat(r)
104 case "Rename":
105- return h.rename(r, true)
106+ return h.renaming(r, true)
107 case "Link":
108+ h.creating(r.Target)
109 return h.link(r)
110 case "Remove", "Rmdir":
111 // The guest agent removes a path deleted on the host, so that the guest emits IN_DELETE.
112@@ -302,10 +278,13 @@ func (h *rootedHandlers) Filecmd(r *sftp.Request) error {
113 if h.consumeNoopRemoval(r.Filepath) {
114 return nil
115 }
116- return h.remove(r)
117+ h.removing(r.Filepath)
118+ return h.removalFailed(r.Filepath, h.remove(r))
119 case "Mkdir":
120+ h.creating(r.Filepath)
121 return h.mkdir(r)
122 case "Symlink":
123+ h.creating(r.Target)
124 return h.symlink(r)
125 }
126 return sftp.ErrSSHFxOpUnsupported
127@@ -313,7 +292,13 @@ func (h *rootedHandlers) Filecmd(r *sftp.Request) error {
128
129 // PosixRename implements sftp.PosixRenameFileCmder.
130 func (h *rootedHandlers) PosixRename(r *sftp.Request) error {
131- return h.rename(r, false)
132+ return h.renaming(r, false)
133+}
134+
135+func (h *rootedHandlers) renaming(r *sftp.Request, noReplace bool) error {
136+ h.removing(r.Filepath)
137+ h.creating(r.Target)
138+ return h.removalFailed(r.Filepath, h.rename(r, noReplace))
139 }
140
141 // isOpenAt reports whether f is the file at p, a request path, without following a symlink at p.
142diff --git a/pkg/reversesshfs/rooted_others.go b/pkg/reversesshfs/rooted_others.go
143index 5669be5..1fc4972 100644
144--- a/pkg/reversesshfs/rooted_others.go
145+++ b/pkg/reversesshfs/rooted_others.go
146@@ -17,4 +17,4 @@ func newRootedServer(io.ReadWriteCloser, string, bool, []string) (*sftp.RequestS
147
148 func (*rootedHandlers) Close() error { return nil }
149
150-func (*rootedHandlers) expectRemove(string) {}
151+func (*rootedHandlers) expectRemove(string) bool { return false }
152diff --git a/pkg/reversesshfs/rooted_relay.go b/pkg/reversesshfs/rooted_relay.go
153new file mode 100644
154index 0000000..91cdfe0
155--- /dev/null
156+++ b/pkg/reversesshfs/rooted_relay.go
157@@ -0,0 +1,159 @@
158+//go:build linux || darwin || windows
159+
160+package reversesshfs
161+
162+import (
163+ "errors"
164+ "io/fs"
165+ "time"
166+)
167+
168+// noopRemovalTTL bounds how long an ExpectRemove token waits for the guest.
169+const noopRemovalTTL = 5 * time.Second
170+
171+// ownRemovalTTL bounds how long a removal made by the server hides the host's event for it.
172+const ownRemovalTTL = 2 * time.Second
173+
174+// maxRelayEntries bounds each table, whatever the host does.
175+const maxRelayEntries = 1 << 20
176+
177+// expiring is a set of keys that each expire ttl after being added. Entries
178+// are queued in the order they expire, so purging costs O(1) per entry.
179+type expiring struct {
180+ ttl time.Duration
181+ m map[string]time.Time
182+ q []expiringKey
183+ front int
184+}
185+
186+type expiringKey struct {
187+ key string
188+ expiry time.Time
189+}
190+
191+func newExpiring(ttl time.Duration) *expiring {
192+ return &expiring{ttl: ttl, m: make(map[string]time.Time)}
193+}
194+
195+// add reports false when the set is full.
196+func (e *expiring) add(key string, now time.Time) bool {
197+ e.purge(now)
198+ if len(e.q)-e.front >= maxRelayEntries {
199+ return false
200+ }
201+ expiry := now.Add(e.ttl)
202+ e.m[key] = expiry
203+ e.q = append(e.q, expiringKey{key, expiry})
204+ return true
205+}
206+
207+func (e *expiring) has(key string, now time.Time) bool {
208+ e.purge(now)
209+ _, ok := e.m[key]
210+ return ok
211+}
212+
213+// remove reports whether key was there. Its queue entry stays until it expires.
214+func (e *expiring) remove(key string, now time.Time) bool {
215+ ok := e.has(key, now)
216+ delete(e.m, key)
217+ return ok
218+}
219+
220+func (e *expiring) purge(now time.Time) {
221+ for e.front < len(e.q) && !now.Before(e.q[e.front].expiry) {
222+ k := e.q[e.front]
223+ // A key added again has a later expiry, and its own queue entry.
224+ if e.m[k.key].Equal(k.expiry) {
225+ delete(e.m, k.key)
226+ }
227+ e.q[e.front] = expiringKey{}
228+ e.front++
229+ }
230+ if e.front >= 1024 && e.front*2 >= len(e.q) {
231+ e.q = append(e.q[:0], e.q[e.front:]...)
232+ e.front = 0
233+ }
234+}
235+
236+// relay is the state behind ExpectRemove.
237+//
238+// The hostagent relays a deletion made on the host by having the guest remove the path, which
239+// makes the guest emit an event. The server must then answer that removal without touching the host:
240+// the path may have been created again there since. Two things must not be mistaken for it:
241+// the host's event for a removal that the guest itself asked for, and a removal of a path the
242+// guest created after the host deleted it.
243+type relay struct {
244+ tokens *expiring // paths whose next removal is the relayed one
245+ own *expiring // paths the server just removed or renamed away
246+}
247+
248+func newRelay() *relay {
249+ return &relay{tokens: newExpiring(noopRemovalTTL), own: newExpiring(ownRemovalTTL)}
250+}
251+
252+// expectRemove makes the next Remove or Rmdir request for p, within noopRemovalTTL, succeed without
253+// touching the host, and reports true. p is a host path under the root. It reports false, and
254+// the removal must not be relayed, when the server removed p itself just now.
255+func (h *rootedHandlers) expectRemove(p string) bool {
256+ rel, err := h.rel(slashPath(p))
257+ if err != nil {
258+ return false
259+ }
260+ now := h.now()
261+ h.mu.Lock()
262+ defer h.mu.Unlock()
263+ if h.relay.own.has(rel, now) {
264+ return false
265+ }
266+ return h.relay.tokens.add(rel, now)
267+}
268+
269+func (h *rootedHandlers) consumeNoopRemoval(p string) bool {
270+ rel, err := h.rel(p)
271+ if err != nil {
272+ return false
273+ }
274+ h.mu.Lock()
275+ defer h.mu.Unlock()
276+ return h.relay.tokens.remove(rel, h.now())
277+}
278+
279+// removing records that the server is about to remove or move away p, a request path.
280+// This is before the removal, as the host's event can come right after it.
281+func (h *rootedHandlers) removing(p string) {
282+ rel, err := h.rel(p)
283+ if err != nil {
284+ return
285+ }
286+ h.mu.Lock()
287+ defer h.mu.Unlock()
288+ h.relay.own.add(rel, h.now())
289+}
290+
291+// removalFailed takes back removing(p) when the removal or move did not happen: nothing of the host's
292+// changed, so a later deletion of p there is not the server's own. A path that was not there stays: an
293+// earlier removal of it may be the one the host's event is about.
294+func (h *rootedHandlers) removalFailed(p string, err error) error {
295+ if err == nil || errors.Is(err, fs.ErrNotExist) {
296+ return err
297+ }
298+ if rel, rerr := h.rel(p); rerr == nil {
299+ h.mu.Lock()
300+ h.relay.own.remove(rel, h.now())
301+ h.mu.Unlock()
302+ }
303+ return err
304+}
305+
306+// creating records that the server is about to create p, a request path: a removal of it that follows
307+// is the guest's own, not a relayed one.
308+func (h *rootedHandlers) creating(p string) {
309+ rel, err := h.rel(p)
310+ if err != nil {
311+ return
312+ }
313+ h.mu.Lock()
314+ defer h.mu.Unlock()
315+ h.relay.tokens.remove(rel, h.now())
316+}
317diff --git a/pkg/reversesshfs/rooted_relay_test.go b/pkg/reversesshfs/rooted_relay_test.go
318new file mode 100644
319index 0000000..386da54
320--- /dev/null
321+++ b/pkg/reversesshfs/rooted_relay_test.go
322@@ -0,0 +1,158 @@
323+//go:build linux || darwin || windows
324+
325+package reversesshfs
326+
327+import (
328+ "fmt"
329+ "os"
330+ "path/filepath"
331+ "testing"
332+ "time"
333+)
334+
335+// A removal the server made for the guest is not relayed: the host's event for it must not
336+// leave a token that swallows the guest's next removal of a file it created again.
337+func TestRootedOwnRemovalNotRelayed(t *testing.T) {
338+ c, root, h := setupRootedHandlers(t, false)
339+ p := func(s string) string { return filepath.Join(root, s) }
340+ create := func(s string) {
341+ t.Helper()
342+ f, err := c.Create(p(s))
343+ if err != nil {
344+ t.Fatal(err)
345+ }
346+ f.Close()
347+ }
348+ create("f")
349+ if err := c.Remove(p("f")); err != nil {
350+ t.Fatal(err)
351+ }
352+ if h.expectRemove(p("f")) {
353+ t.Fatal("the host's event for the guest's own removal was relayed")
354+ }
355+ create("f")
356+ if err := c.Remove(p("f")); err != nil {
357+ t.Fatal(err)
358+ }
359+ if _, err := os.Lstat(p("f")); err == nil {
360+ t.Fatal("rm f; touch f; rm f left the file on the host")
361+ }
362+
363+ // A rename away is a removal as well: log rotation.
364+ create("log")
365+ if err := c.PosixRename(p("log"), p("log.1")); err != nil {
366+ t.Fatal(err)
367+ }
368+ create("log")
369+ if h.expectRemove(p("log")) {
370+ t.Fatal("the host's event for the guest's rename was relayed")
371+ }
372+ if err := c.Remove(p("log")); err != nil {
373+ t.Fatal(err)
374+ }
375+ if _, err := os.Lstat(p("log")); err == nil {
376+ t.Fatal("the new log was not removed")
377+ }
378+
379+ // Once the event window is over, a host deletion is relayed again.
380+ now := time.Now()
381+ h.now = func() time.Time { return now.Add(ownRemovalTTL + time.Second) }
382+ if !h.expectRemove(p("log")) {
383+ t.Error("not relayed after the window")
384+ }
385+}
386+
387+// A removal that fails removed nothing: the host's deletion of the path that follows is still relayed.
388+func TestRootedFailedRemovalNotOwn(t *testing.T) {
389+ c, root, h := setupRootedHandlers(t, false)
390+ p := func(s string) string { return filepath.Join(root, s) }
391+ if err := os.MkdirAll(p("d/sub"), 0o755); err != nil {
392+ t.Fatal(err)
393+ }
394+ if err := c.RemoveDirectory(p("d")); err == nil {
395+ t.Fatal("a folder with something in it was removed")
396+ }
397+ if !h.expectRemove(p("d")) {
398+ t.Error("a removal that failed hid the host's deletion")
399+ }
400+}
401+
402+// A file the guest creates after the host deleted it, within the token's life, is its own.
403+func TestRootedTokenDroppedByCreate(t *testing.T) {
404+ c, root, h := setupRootedHandlers(t, false)
405+ p := func(s string) string { return filepath.Join(root, s) }
406+ if !h.expectRemove(p("new")) {
407+ t.Fatal("not expected")
408+ }
409+ f, err := c.Create(p("new"))
410+ if err != nil {
411+ t.Fatal(err)
412+ }
413+ f.Close()
414+ if err := c.Remove(p("new")); err != nil {
415+ t.Fatal(err)
416+ }
417+ if _, err := os.Lstat(p("new")); err == nil {
418+ t.Fatal("the removal was swallowed though the guest created the file")
419+ }
420+
421+ // Same for the other ways to create a name.
422+ for name, create := range map[string]func(string) error{
423+ "mkdir": func(s string) error { return c.Mkdir(s) },
424+ "symlink": func(s string) error { return c.Symlink("x", s) },
425+ "rename": func(s string) error { return c.PosixRename(p("src/main.go"), s) },
426+ } {
427+ target := p("t-" + name)
428+ h.expectRemove(target)
429+ if err := create(target); err != nil {
430+ t.Fatal(name, err)
431+ }
432+ if err := c.Remove(target); err != nil {
433+ if err := c.RemoveDirectory(target); err != nil {
434+ t.Fatal(name, err)
435+ }
436+ }
437+ if _, err := os.Lstat(target); err == nil {
438+ t.Errorf("%s: the removal was swallowed", name)
439+ }
440+ }
441+}
442+
443+// A host rm -rf of many files must not stall the server.
444+func TestExpectRemoveMany(t *testing.T) {
445+ _, root, h := setupRootedHandlers(t, false)
446+ start := time.Now()
447+ const n = 200000
448+ for i := 0; i < n; i++ {
449+ h.expectRemove(filepath.Join(root, "src", fmt.Sprint(i)))
450+ }
451+ if d := time.Since(start); d > 5*time.Second {
452+ t.Fatalf("%d tokens took %v", n, d)
453+ }
454+ // They expire in order, and the tables empty out.
455+ now := time.Now()
456+ h.now = func() time.Time { return now.Add(noopRemovalTTL + time.Second) }
457+ h.expectRemove(filepath.Join(root, "x"))
458+ h.mu.Lock()
459+ defer h.mu.Unlock()
460+ if len(h.relay.tokens.m) != 1 {
461+ t.Errorf("%d tokens left", len(h.relay.tokens.m))
462+ }
463+}
464+
465+func TestExpiringKeyAddedAgain(t *testing.T) {
466+ e := newExpiring(10 * time.Second)
467+ t0 := time.Now()
468+ e.add("k", t0)
469+ e.add("k", t0.Add(8*time.Second))
470+ // The first entry expired, the key is still there with the later expiry.
471+ if !e.has("k", t0.Add(12*time.Second)) {
472+ t.Error("key added again was purged by its first entry")
473+ }
474+ if e.has("k", t0.Add(19*time.Second)) {
475+ t.Error("key not expired")
476+ }
477+ if len(e.m) != 0 {
478+ t.Error("left over")
479+ }
480+}
481diff --git a/pkg/reversesshfs/rooted_test.go b/pkg/reversesshfs/rooted_test.go
482index 01fe96a..2b8a60c 100644
483--- a/pkg/reversesshfs/rooted_test.go
484+++ b/pkg/reversesshfs/rooted_test.go
485@@ -602,9 +602,7 @@ func TestRootedNoopRemoval(t *testing.T) {
486
487 // An expired token.
488 h.expectRemove(p(".git/config"))
489- h.mu.Lock()
490- h.noopRemovals[slashPath(p(".git/config"))] = time.Now().Add(-time.Second)
491- h.mu.Unlock()
492+ h.now = func() time.Time { return time.Now().Add(noopRemovalTTL + time.Second) }
493 if err := c.Remove(p(".git/config")); err == nil {
494 t.Fatal("expected an error")
495 }