From cb9ee87d3328a67a079a6ba157297627d468a85a Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Thu, 3 Dec 2026 08:34:47 +0800 Subject: [PATCH] fix(guesttools): verify Windows clipboard files before publishing --- changes/file-clipboard-readiness.json | 7 + internal/guesttools/clipboard_agent_test.go | 85 +++++++++- internal/guesttools/clipboard_file_receipt.go | 97 +++++++++++ .../guesttools/clipboard_file_receipt_test.go | 150 ++++++++++++++++++ .../guesttools/clipboard_readability_test.go | 90 +++++++++++ internal/guesttools/drop_resolve.js | 37 +++++ internal/guesttools/folder_share.go | 3 +- internal/guesttools/image.go | 25 ++- internal/guesttools/server.go | 11 ++ internal/guesttools/testdata/pasteboard.cjs | 29 +++- internal/guesttools/transport.go | 32 ++-- internal/plugin/builtin/builtin.go | 11 +- 12 files changed, 550 insertions(+), 27 deletions(-) create mode 100644 changes/file-clipboard-readiness.json create mode 100644 internal/guesttools/clipboard_file_receipt.go create mode 100644 internal/guesttools/clipboard_file_receipt_test.go create mode 100644 internal/guesttools/clipboard_readability_test.go diff --git a/changes/file-clipboard-readiness.json b/changes/file-clipboard-readiness.json new file mode 100644 index 0000000..d01cce0 --- /dev/null +++ b/changes/file-clipboard-readiness.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["yxc0915"], + "zh": "Windows 文件复制到 macOS 时,挂载文件不可读会改用下载回退。诊断报告会记录客体确认写入文件剪贴板的次数。", + "en": "When Windows clipboard files cannot be read from the mounted share on macOS, Guest Tools uses the download fallback. Diagnostics count file clipboard writes confirmed by the guest." +} diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 3132a42..0601183 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -80,6 +80,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { "paste_ack_text", "paste_ack_preapplied", "paste_ack_local_change", "paste_ack_unmarked", "paste_ack_png", "paste_ack_unstable_png", "paste_ack_without_request", "paste_recheck_guest_owned", "paste_recheck_local_change", "paste_recheck_inject", "paste_recheck_drop", + "paste_recheck_file_receipt", }}, {"download_during_copy", []string{ "guest_changes_during_get", "cold_guest_changes_during_get", "cold_lock_during_get", "repeat_host_copy", @@ -111,6 +112,10 @@ func TestGuestAgentClipboardScript(t *testing.T) { "input_failed", "input_preserves_new_copy", "input_exits_with_lock", }}, {"file_delivery", []string{"host_files_sync_no_echo", "host_files_reordered_readback", "host_files_failed_write", "host_files_partial_write", "guest_files_do_not_overwrite_host", "foreign_drop_mount", "host_files_tar_fallback", "host_files_tar_fallback_changed"}}, + {"file_readiness", []string{ + "host_files_receipt", "host_files_both_receipts", "host_files_unreadable_fallback", "host_files_unreadable_fallback_conflict", + "host_files_unreadable_without_fallback", "host_files_no_ack_failed_write", + }}, {"file_upload", []string{"guest_files_tar_upload", "guest_files_legacy_no_upload", "guest_files_tar_hosted_no_upload", "guest_files_tar_upload_changed", "guest_files_tar_upload_retry"}}, {"file_retry", []string{ "host_files_remount_and_fail_no_spin", "host_files_new_event_during_retry", @@ -140,12 +145,12 @@ func TestGuestAgentClipboardScript(t *testing.T) { } } var cmdEnv []string - if group.name == "file_delivery" { + if group.name == "file_delivery" || group.name == "file_readiness" { fixture, err := filepath.Abs("testdata/pasteboard.cjs") if err != nil { t.Fatal(err) } - for _, name := range []string{"host_files_sync_no_echo", "host_files_reordered_readback", "host_files_failed_write", "host_files_partial_write", "host_files_tar_fallback", "host_files_tar_fallback_changed"} { + for _, name := range group.cases { if err := os.WriteFile(filepath.Join(tmp, name, "drop-resolve.js"), []byte(guestDropResolveJS), 0o600); err != nil { t.Fatal(err) } @@ -232,6 +237,7 @@ get_hash=B get_seq=8 get_kind=text get_value=B +get_receipt="" post_code=200 post_hash=C post_seq=9 @@ -424,6 +430,8 @@ curl() { acknowledged_hash="" acknowledged_generation="" acknowledged_request="" + receipt_capability="" + receipt_request="" body="" archive_upload="" url="" @@ -442,6 +450,8 @@ curl() { 'X-Clip-Hash: '*) acknowledged_hash="${2#*: }" ;; 'X-Reims-Clipboard-Generation: '*) acknowledged_generation="${2#*: }" ;; 'X-Reims-Clipboard-Request: '*) acknowledged_request="${2#*: }" ;; + 'X-Reims-Clipboard-File-Receipt: '*) receipt_capability="$2" ;; + 'X-Reims-Clipboard-File-Request: '*) receipt_request="${2#*: }" ;; 'Accept: '*) accept="$2" ;; esac shift @@ -451,6 +461,12 @@ curl() { shift done case "$url" in + */v1/clipboard/files/applied) + [ ! -d "$CLIP_LOCK" ] || exit 1 + [ "$method" = POST ] && [ -n "$get_receipt" ] || exit 1 + expect "$receipt_request/$acknowledged_seq/$acknowledged_hash" "$get_receipt/$get_seq/$get_hash" + printf 'FILE-ACK\n' >> calls + return ;; */v1/clipboard\?format=tar\&drop_id=clip-0123456789abcdef) [ ! -d "$CLIP_LOCK" ] || exit 1 cp guest-fallback.tar "$output" || exit 1 @@ -521,7 +537,7 @@ curl() { printf '%s' "$post_code" else printf '%s %s\n' "$method" "$url" >> calls - if [ "$get_kind" = files ] && [ "$get_code" = 200 ] && [ "$flags" != ignore_since ]; then + if [ "$get_kind" = files ] && [ "$get_code" = 200 ] && [ "$flags" != ignore_since ] && [ "$offer_recheck" != 1 ]; then case "$url" in *"since=$get_hash&"*'&since_seq='*) if [ "${url##*&since_seq=}" = "$get_seq" ]; then get_code=304; fi ;; @@ -543,6 +559,10 @@ curl() { fi fi fi + if [ -n "$get_receipt" ] && [ "$get_code" = 200 ]; then + expect "$receipt_capability" 'X-Reims-Clipboard-File-Receipt: 1' + printf 'x-rEiMs-Clipboard-File-Request: %s\r\n' "$get_receipt" >> "$headers" + fi printf '%s' "$get_value" > "$output" if [ "$fail_during_get" = 1 ]; then printf C > local_value @@ -637,6 +657,57 @@ a%23note.txt' expect "$(methods)" GET,ACK,GET expect_call -Fx "GET http://stub/v1/clipboard?since=$get_hash&wait=2&accept=image,files&since_seq=8" ;; + host_files_receipt|host_files_both_receipts|host_files_unreadable_fallback|host_files_unreadable_fallback_conflict|host_files_unreadable_without_fallback|host_files_no_ack_failed_write) + flags=typed_files + get_kind=files + get_hash=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + get_receipt=ABCDEFGHIJKLMNOPQRSTUVWXYZ + get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}' + mkdir -p "$DROP_MOUNT/clip-0123456789abcdef" + printf mounted > "$DROP_MOUNT/clip-0123456789abcdef/fallback.txt" + printf '%s\n' '{"changeCount":1,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json + case "$1" in + host_files_unreadable_*) + printf '%s\n' '["./drop_mount/clip-0123456789abcdef/fallback.txt"]' > test-hosted-probe-denied.json + ;; + host_files_no_ack_failed_write) : > test-fail-file-write ;; + host_files_both_receipts) offer_ack=1 ;; + esac + case "$1" in + host_files_unreadable_fallback*) + printf '0 1048576\n' > clip_file_config + printf downloaded > fallback.txt + tar -cf guest-fallback.tar fallback.txt + ;; + esac + if [ "$1" = host_files_unreadable_fallback_conflict ]; then : > change_during_archive; fi + sync_clipboard + [ ! -e mounts ] && [ ! -d "$CLIP_LOCK" ] + case "$1" in + host_files_receipt|host_files_both_receipts) + expected_calls=GET,FILE-ACK + if [ "$1" = host_files_both_receipts ]; then expected_calls=GET,ACK,FILE-ACK; fi + expect "$(methods)" "$expected_calls" + expect "$last_server_hash" "$get_hash" + sync_clipboard + expect "$(methods)" "$expected_calls,GET" + ;; + host_files_unreadable_fallback) + expect "$(methods)" GET,DOWNLOAD,FILE-ACK + expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" downloaded + expect "$(read_local_clipboard readback)" files + grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback + ;; + host_files_unreadable_fallback_conflict) + expect "$(methods)" GET,DOWNLOAD + expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy' + ;; + *) + expect "$(methods)" GET + expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" A + ;; + esac + ;; host_files_tar_fallback|host_files_tar_fallback_changed) flags=typed_files get_kind=files @@ -1110,11 +1181,17 @@ a%23note.txt' paste_recheck_local_change) flags=guest_change ;; paste_recheck_inject) flags=inject_during_get ;; paste_recheck_drop) flags=drop_during_get ;; + paste_recheck_file_receipt) + get_kind=files + get_value='{"drop_id":"clip-0123456789abcdef","items":["a.txt"]}' + get_receipt=ABCDEFGHIJKLMNOPQRSTUVWXYZ + ;; esac sync_clipboard [ ! -s copies ] case "$1" in - paste_recheck_guest_owned) expect "$(methods)/$(read_file local_value)" GET,ACK/guest-own ;; + paste_recheck_guest_owned|paste_recheck_file_receipt) + expect "$(methods)/$(read_file local_value)" GET,ACK/guest-own ;; paste_recheck_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;; *) expect "$(methods)" GET ;; esac diff --git a/internal/guesttools/clipboard_file_receipt.go b/internal/guesttools/clipboard_file_receipt.go new file mode 100644 index 0000000..32122f6 --- /dev/null +++ b/internal/guesttools/clipboard_file_receipt.go @@ -0,0 +1,97 @@ +package guesttools + +import ( + "crypto/rand" + "encoding/base32" + "encoding/hex" + "net/http" + "strconv" +) + +const ( + fileClipboardAppliedPath = "/v1/clipboard/files/applied" + fileClipboardReceiptHeader = "X-Reims-Clipboard-File-Receipt" + fileClipboardRequestHeader = "X-Reims-Clipboard-File-Request" +) + +var fileClipboardRequests = base32.StdEncoding.WithPadding(base32.NoPadding) + +// fileClipboardReceipt tracks only the latest offered file selection for one +// VM. The clipboard response owns the manifest and file paths. +type fileClipboardReceipt struct { + seq uint32 + hash string + request string + applied bool +} + +// fileClipboardReceiptVMLocked revalidates authentication and current policy. +// The caller holds s.mu. +func (s *Server) fileClipboardReceiptVMLocked(vm *registeredVM, seq uint32) *registeredVM { + cur := s.vms[vm.key] + if cur == nil || cur.regGen != vm.regGen || cur.token != vm.token || + !s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuestFiles() || s.clip.SequenceNumber() != seq { + return nil + } + return cur +} + +func (s *Server) offerFileClipboardReceipt(vm *registeredVM, seq uint32, hash string) string { + s.mu.Lock() + defer s.mu.Unlock() + cur := s.fileClipboardReceiptVMLocked(vm, seq) + if cur == nil { + return "" + } + receipt := &cur.fileClipboardReceipt + if receipt.request == "" || receipt.seq != seq || receipt.hash != hash { + var nonce [16]byte + rand.Read(nonce[:]) + *receipt = fileClipboardReceipt{seq: seq, hash: hash, request: fileClipboardRequests.EncodeToString(nonce[:])} + } + return receipt.request +} + +func (s *Server) handleFileClipboardApplied(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + seq, seqErr := strconv.ParseUint(r.Header.Get("X-Clip-Seq"), 10, 32) + hash := r.Header.Get("X-Clip-Hash") + request := r.Header.Get(fileClipboardRequestHeader) + if seqErr != nil || len(hash) != 64 || len(request) != 26 || r.ContentLength != 0 { + http.Error(w, "invalid file clipboard receipt", http.StatusBadRequest) + return + } + _, hashErr := hex.DecodeString(hash) + _, requestErr := fileClipboardRequests.DecodeString(request) + if hashErr != nil || requestErr != nil { + http.Error(w, "invalid file clipboard receipt", http.StatusBadRequest) + return + } + + s.mu.Lock() + cur := s.fileClipboardReceiptVMLocked(vm, uint32(seq)) + accepted := false + if cur != nil { + receipt := &cur.fileClipboardReceipt + accepted = receipt.seq == uint32(seq) && receipt.hash == hash && receipt.request == request + if accepted && !receipt.applied { + receipt.applied = true + s.clipFilesApplied.Add(1) + } + } + s.mu.Unlock() + if !accepted { + http.Error(w, "file clipboard receipt expired", http.StatusConflict) + return + } + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/guesttools/clipboard_file_receipt_test.go b/internal/guesttools/clipboard_file_receipt_test.go new file mode 100644 index 0000000..e44a478 --- /dev/null +++ b/internal/guesttools/clipboard_file_receipt_test.go @@ -0,0 +1,150 @@ +package guesttools + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +const fileReceiptTestToken = "clipboard-test-token" + +func fileReceiptFixture(t *testing.T) (*Server, *memClipboard, string) { + t.Helper() + file := filepath.Join(t.TempDir(), "selected.txt") + if err := os.WriteFile(file, []byte("selected file"), 0o600); err != nil { + t.Fatal(err) + } + clip := &memClipboard{} + clip.WriteFiles([]string{file}) + return newClipboardTestServer(clip), clip, file +} + +func fileReceiptGET(srv *Server, token string, optIn bool) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodGet, "/v1/clipboard?accept=files", nil) + r.Header.Set("Authorization", "Bearer "+token) + if optIn { + r.Header.Set(fileClipboardReceiptHeader, "1") + } + w := httptest.NewRecorder() + srv.handleClipboard(w, r) + return w +} + +func postFileReceipt(srv *Server, token string, offer http.Header) int { + r := httptest.NewRequest(http.MethodPost, fileClipboardAppliedPath, nil) + r.Header.Set("Authorization", "Bearer "+token) + for _, key := range []string{"X-Clip-Seq", "X-Clip-Hash", fileClipboardRequestHeader} { + r.Header.Set(key, offer.Get(key)) + } + w := httptest.NewRecorder() + srv.dispatchDynamicRoute(fileClipboardAppliedPath, "clipboard")(w, r) + return w.Code +} + +func TestFileClipboardReceiptOnlyMarksOptedInFileSelection(t *testing.T) { + srv, clip, _ := fileReceiptFixture(t) + original := fileReceiptGET(srv, fileReceiptTestToken, false) + if original.Code != http.StatusOK || original.Header().Get("X-Clip-Kind") != "files" || + original.Header().Get(fileClipboardRequestHeader) != "" { + t.Fatalf("unexpected legacy response: %d %v", original.Code, original.Header()) + } + offer := fileReceiptGET(srv, fileReceiptTestToken, true) + request := offer.Header().Get(fileClipboardRequestHeader) + if offer.Code != http.StatusOK || len(request) != 26 || offer.Body.String() != original.Body.String() || + offer.Header().Get("X-Reims-Clipboard-Request") != "" { + t.Fatalf("unexpected negotiated response: %d %v", offer.Code, offer.Header()) + } + duplicate := fileReceiptGET(srv, fileReceiptTestToken, true) + if duplicate.Header().Get(fileClipboardRequestHeader) != request || + duplicate.Header().Get("X-Clip-Seq") != offer.Header().Get("X-Clip-Seq") { + t.Fatalf("the same selection did not retain its receipt: %v", duplicate.Header()) + } + for _, result := range []int{postFileReceipt(srv, fileReceiptTestToken, offer.Header()), + postFileReceipt(srv, fileReceiptTestToken, duplicate.Header())} { + if result != http.StatusNoContent { + t.Fatalf("receipt or its retry got %d, want 204", result) + } + } + if got := srv.ClipboardDiagnostics().HostToGuestFilesAppliedCount; got != 1 { + t.Fatalf("host-to-guest file applications counted %d, want 1", got) + } + if err := clip.WriteText("a new text selection"); err != nil { + t.Fatal(err) + } + if text := fileReceiptGET(srv, fileReceiptTestToken, true); text.Code != http.StatusOK || + text.Header().Get("X-Clip-Kind") != "text" || text.Header().Get(fileClipboardRequestHeader) != "" { + t.Fatalf("unexpected text clipboard negotiation: %d %v", text.Code, text.Header()) + } +} + +func TestFileClipboardReceiptRejectsWrongVMAndStaleRevision(t *testing.T) { + srv, clip, file := fileReceiptFixture(t) + srv.RegisterVM(VMConfig{VMName: "other", Token: "other-token"}) + first := fileReceiptGET(srv, fileReceiptTestToken, true).Header() + other := fileReceiptGET(srv, "other-token", true).Header() + if first.Get(fileClipboardRequestHeader) == other.Get(fileClipboardRequestHeader) { + t.Fatal("receipt ID did not distinguish VM registrations") + } + if code := postFileReceipt(srv, "other-token", first); code != http.StatusConflict { + t.Fatalf("cross-VM receipt got %d, want 409", code) + } + if code := postFileReceipt(srv, "invalid-token", first); code != http.StatusUnauthorized { + t.Fatalf("unauthorized receipt got %d, want 401", code) + } + fake := first.Clone() + fake.Set("X-Clip-Hash", strings.Repeat("0", 64)) + if code := postFileReceipt(srv, fileReceiptTestToken, fake); code != http.StatusConflict { + t.Fatalf("incorrect hash got %d, want 409", code) + } + fake.Set(fileClipboardRequestHeader, "invalid") + if code := postFileReceipt(srv, fileReceiptTestToken, fake); code != http.StatusBadRequest { + t.Fatalf("malformed receipt ID got %d, want 400", code) + } + clip.WriteFiles([]string{file}) + if code := postFileReceipt(srv, fileReceiptTestToken, first); code != http.StatusConflict { + t.Fatalf("outdated Windows clipboard sequence got %d, want 409", code) + } + second := fileReceiptGET(srv, fileReceiptTestToken, true).Header() + if first.Get(fileClipboardRequestHeader) == second.Get(fileClipboardRequestHeader) || + first.Get("X-Clip-Seq") == second.Get("X-Clip-Seq") { + t.Fatal("copying the same file again did not generate an independent receipt") + } + if code := postFileReceipt(srv, fileReceiptTestToken, second); code != http.StatusNoContent { + t.Fatalf("current receipt got %d, want 204", code) + } +} + +func TestFileClipboardReceiptFollowsRegistrationAndPolicy(t *testing.T) { + srv, _, _ := fileReceiptFixture(t) + first := fileReceiptGET(srv, fileReceiptTestToken, true).Header() + srv.RegisterVM(VMConfig{VMName: "clipboard-test", Token: fileReceiptTestToken}) + if code := postFileReceipt(srv, fileReceiptTestToken, first); code != http.StatusConflict { + t.Fatalf("receipt from previous registration got %d, want 409", code) + } + current := fileReceiptGET(srv, fileReceiptTestToken, true).Header() + policy := DefaultClipboardPolicy() + policy.SyncFiles = false + srv.SetVMClipboardPolicy("clipboard-test", &policy) + if code := postFileReceipt(srv, fileReceiptTestToken, current); code != http.StatusConflict { + t.Fatalf("receipt with file sharing disabled got %d, want 409", code) + } + srv.SetVMClipboardPolicy("clipboard-test", nil) + if code := postFileReceipt(srv, fileReceiptTestToken, current); code != http.StatusConflict { + t.Fatalf("receipt survived file policy withdrawal, got %d", code) + } + fresh := fileReceiptGET(srv, fileReceiptTestToken, true).Header() + srv.SetClipboardActive(false) + if srv.HasRoute(fileClipboardAppliedPath) { + t.Fatal("receipt route survived clipboard deactivation") + } + srv.SetClipboardActive(true) + if code := postFileReceipt(srv, fileReceiptTestToken, fresh); code != http.StatusConflict { + t.Fatalf("receipt survived clipboard deactivation, got %d", code) + } + if got := srv.ClipboardDiagnostics().HostToGuestFilesAppliedCount; got != 0 { + t.Fatalf("invalid or deactivated acknowledgments incremented the counter: %d", got) + } +} diff --git a/internal/guesttools/clipboard_readability_test.go b/internal/guesttools/clipboard_readability_test.go new file mode 100644 index 0000000..d8cb821 --- /dev/null +++ b/internal/guesttools/clipboard_readability_test.go @@ -0,0 +1,90 @@ +package guesttools + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestGuestAgentChecksHostedClipboardReadabilityBeforePublishing(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("Node.js is unavailable") + } + fixture, err := filepath.Abs("testdata/pasteboard.cjs") + if err != nil { + t.Fatal(err) + } + const dropID = "clip-0123456789abcdef" + const previous = `{"changeCount":7,"items":[{"public.utf8-plain-text":"guest copy"}]}` + paths := []string{"mount/" + dropID + "/empty.txt", "mount/" + dropID + "/empty-dir", "mount/" + dropID + "/folder"} + for _, tc := range []struct { + name string + denied string + mode string + want string + probe bool + }{ + {name: "files and folders readable", want: "ok", probe: true}, + {name: "file stat passes but cannot read", denied: paths[0], want: "unreadable", probe: true}, + {name: "directory stat passes but cannot list", denied: paths[1], want: "unreadable", probe: true}, + {name: "missing selection", want: "remount"}, + {name: "local archive cache skips the network probe", denied: paths[0], mode: "cache", want: "ok"}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + write := func(name, contents string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + } + for _, path := range paths[1:] { + if err := os.MkdirAll(filepath.Join(dir, path), 0o700); err != nil { + t.Fatal(err) + } + } + if tc.want != "remount" { + write(paths[0], "") + } + write(paths[2]+"/first.txt", "first") + write("manifest.json", `{"drop_id":"`+dropID+`","items":["empty.txt","empty-dir","folder"]}`) + write("drop-resolve.js", guestDropResolveJS) + write("test-pasteboard.json", previous) + if tc.denied != "" { + data, err := json.Marshal([]string{tc.denied}) + if err != nil { + t.Fatal(err) + } + write("test-hosted-probe-denied.json", string(data)) + } + cmd := exec.CommandContext(t.Context(), node, fixture, "drop-resolve.js", "write-clip-files", + "manifest.json", "mount", "7", tc.mode) + cmd.Dir = dir + output, err := cmd.CombinedOutput() + if got := strings.TrimSpace(string(output)); err != nil || got != tc.want { + t.Fatalf("write clipboard = %q, want %q, err=%v", got, tc.want, err) + } + probed, err := os.ReadFile(filepath.Join(dir, "test-hosted-probe.json")) + if tc.probe { + var got []string + if err != nil || json.Unmarshal(probed, &got) != nil || !slices.Equal(got, paths) { + t.Fatalf("probe paths = %q, want %v, err=%v", probed, paths, err) + } + } else if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("unexpected probe for %s, err=%v", tc.want, err) + } + if tc.want != "ok" { + got, err := os.ReadFile(filepath.Join(dir, "test-pasteboard.json")) + if err != nil || string(got) != previous { + t.Fatalf("guest clipboard changed after failed readiness check: %q, err=%v", got, err) + } + } + }) + } +} diff --git a/internal/guesttools/drop_resolve.js b/internal/guesttools/drop_resolve.js index 949899c..dbb118a 100644 --- a/internal/guesttools/drop_resolve.js +++ b/internal/guesttools/drop_resolve.js @@ -459,6 +459,42 @@ function validateClipArchive(manifestFile, entriesFile) { return 'ok' } +function mountedClipboardSourcesReadable(paths) { + // Metadata can remain visible when WebDAV can no longer serve the item. + // Give the entire probe a deadline, without downloading the selection. + const check = ` + alarm 5; + for my $path (@ARGV) { + if (-d $path) { + opendir(my $dir, $path) or exit 1; + while (1) { + $! = 0; + my $name = readdir($dir); + exit 1 if !defined($name) && $!; + last if !defined($name) || ($name ne '.' && $name ne '..'); + } + closedir($dir) or exit 1; + } elsif (-f $path) { + open(my $file, '<:raw', $path) or exit 1; + defined(sysread($file, my $byte, 1)) or exit 1; + close($file) or exit 1; + } else { + exit 1; + } + } + ` + try { + const task = $.NSTask.alloc.init + task.launchPath = '/usr/bin/perl' + task.arguments = $(['-e', check, '--', ...paths]) + task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice + task.standardError = $.NSFileHandle.fileHandleWithNullDevice + task.launch + task.waitUntilExit + return task.terminationStatus === 0 + } catch (_) { return false } +} + function writeClipFiles(manifestFile, mount, expectedCount, cached = false) { if (!mount) return 'remount' const ev = readClipManifest(manifestFile) @@ -472,6 +508,7 @@ function writeClipFiles(manifestFile, mount, expectedCount, cached = false) { } const paths = ev.items.map(name => dir + '/' + name) if ((!cached && !mountHealthy([mount, dir])) || !paths.every(p => fm.fileExistsAtPath(p))) return 'remount' + if (!cached && !mountedClipboardSourcesReadable(paths)) return 'unreadable' const urls = paths.map(p => $.NSURL.fileURLWithPath(p).absoluteString) const newItems = urls.map(url => { const item = $.NSPasteboardItem.alloc.init diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index 107c8b5..3b0e8e0 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -23,8 +23,9 @@ const ClipboardFilesAgentVersion = 15 const BidirectionalClipboardFilesAgentVersion = 16 const WindowReportAgentVersion = 17 const PasteReadyAgentVersion = 18 +const FileClipboardReadinessAgentVersion = 19 -const CurrentAgentVersion = PasteReadyAgentVersion +const CurrentAgentVersion = FileClipboardReadinessAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index d6e30ee..426f94e 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -704,6 +704,7 @@ write_local_files() ( res=$(osascript -l JavaScript "$APP_DIR/drop-resolve.js" write-clip-files "$1" "$DROP_MOUNT" "$2" 2>/dev/null) || return 1 case "$res" in ok) return 0 ;; + unreadable) return 2 ;; remount) ;; *) return 1 ;; esac @@ -873,7 +874,8 @@ clip_header() { x-reims-clipboard-ack:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Aa][Cc][Kk]|\ x-reims-clipboard-generation:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Gg][Ee][Nn][Ee][Rr][Aa][Tt][Ii][Oo][Nn]|\ x-reims-clipboard-request:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Qq][Uu][Ee][Ss][Tt]|\ - x-reims-clipboard-recheck:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Cc][Hh][Ee][Cc][Kk]) + x-reims-clipboard-recheck:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Cc][Hh][Ee][Cc][Kk]|\ + x-reims-clipboard-file-request:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Ff][Ii][Ll][Ee]-[Rr][Ee][Qq][Uu][Ee][Ss][Tt]) hdr_val=${hdr_val#"${hdr_val%%[![:space:]]*}"} hdr_val=${hdr_val%"${hdr_val##*[![:space:]]}"} printf '%s\n' "$hdr_val" @@ -907,6 +909,17 @@ acknowledge_clipboard() { "$REIMS_HOST_URL/v1/clipboard/applied" >/dev/null 2>&1 || true } +ack_file_clipboard() ( + receipt=$(clip_header x-reims-clipboard-file-request) + case "$receipt" in ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]*) return 0 ;; esac + case "$1" in ''|*[!0-9]*) return 0 ;; esac + case "$2" in ''|*[!0123456789abcdef]*) return 0 ;; esac + [ "${#receipt}" -eq 26 ] && [ "${#1}" -le 10 ] && [ "${#2}" -eq 64 ] || return 0 + curl -fsS -m 2 -X POST -H "Authorization: Bearer $REIMS_TOKEN" \ + -H "X-Reims-Clipboard-File-Request: $receipt" -H "X-Clip-Seq: $1" -H "X-Clip-Hash: $2" \ + "$REIMS_HOST_URL/v1/clipboard/files/applied" >/dev/null 2>&1 || true +) + last_local_hash="" synced_local_cc="" synced_local_kind="" @@ -1147,7 +1160,8 @@ sync_clipboard() { clip_url="$clip_url&since_seq=$last_server_seq" fi code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \ - -H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" -H "X-Reims-Clipboard-Ack: 1" \ + -H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" \ + -H "X-Reims-Clipboard-Ack: 1" -H "X-Reims-Clipboard-File-Receipt: 1" \ "$clip_url" 2>/dev/null) || code=000 case "$code" in 200) @@ -1155,6 +1169,7 @@ sync_clipboard() { [ -n "$new_hash" ] || { sleep 2; return 0; } new_kind=$(clip_header x-clip-kind) new_seq=$(clip_header x-clip-seq) + file_applied=0 if [ "$cooling_file" = 1 ] && [ "$new_hash" = "$poll_hash" ]; then # A host that ignores conditional polls can return immediately. last_server_seq="$new_seq" @@ -1247,6 +1262,9 @@ sync_clipboard() { release_clip_lock return 0 fi + if [ "$new_kind" = files ] && [ -n "$write_cc" ] && [ "$read_cc" = "$write_cc" ]; then + file_applied=1 + fi post_get_hash="$read_hash" fi release_clip_lock @@ -1262,6 +1280,9 @@ sync_clipboard() { last_server_hash="$new_hash" last_server_seq="$new_seq" acknowledge_clipboard 0 + if [ "$file_applied" = 1 ] && ! clipboard_poll_interrupted; then + ack_file_clipboard "$new_seq" "$new_hash" + fi ;; 204|304) if [ -z "$last_local_hash" ]; then diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 1df12dd..414490a 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -277,6 +277,7 @@ type registeredVM struct { windowReportGen uint64 windowReport windowReport clipboardDelivery guestClipboardDelivery + fileClipboardReceipt fileClipboardReceipt dropShares *dropShareStore dropDAVHandler *webdav.Handler @@ -318,6 +319,7 @@ type Server struct { vmClipPolicies map[string]ClipboardPolicy watcherCount atomic.Int32 clipStatsH2G uint64 + clipFilesApplied atomic.Uint64 clipStatsG2H uint64 clipStatsErr uint64 port int @@ -353,6 +355,7 @@ func NewServer(clip Clipboard) *Server { hostDNS: defaultHostDNS, } s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard + s.dynamicRoutes[fileClipboardAppliedPath] = s.handleFileClipboardApplied return s } @@ -402,6 +405,7 @@ func (s *Server) Start(preferredPort int) (int, error) { mux.HandleFunc("/v1/dns-query", s.handleDNSQuery) mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard")) mux.HandleFunc(clipboardAppliedPath, s.handleClipboardApplied) + mux.HandleFunc(fileClipboardAppliedPath, s.dispatchDynamicRoute(fileClipboardAppliedPath, "clipboard")) mux.HandleFunc("/v1/text-input", s.handleTextInput) mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck) mux.HandleFunc("/v1/drop-events", s.handleDropEvents) @@ -512,6 +516,7 @@ func (s *Server) Close(ctx context.Context) error { vm.windowReportGen = 0 vm.windowReport = windowReport{} vm.clipboardDelivery = guestClipboardDelivery{} + vm.fileClipboardReceipt = fileClipboardReceipt{} } s.mu.Unlock() s.cleanupClipFiles() @@ -621,6 +626,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { } s.registrationGen++ cur.regGen = s.registrationGen + cur.fileClipboardReceipt = fileClipboardReceipt{} cur.token = cfg.Token cur.sharedDir = cfg.SharedDir cur.sharedRoot = root @@ -1345,6 +1351,11 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vm *regist atomic.AddUint64(&s.clipStatsH2G, 1) if payload.Kind == ClipFiles { w.Header().Set("Content-Type", "application/json") + if r.Header.Get(fileClipboardReceiptHeader) == "1" && w.Header().Get(clipboardRecheckHeader) == "" { + if request := s.offerFileClipboardReceipt(vm, seq, h); request != "" { + w.Header().Set(fileClipboardRequestHeader, request) + } + } } else if payload.Kind == ClipPNG { w.Header().Set("Content-Type", "image/png") } else { diff --git a/internal/guesttools/testdata/pasteboard.cjs b/internal/guesttools/testdata/pasteboard.cjs index 78bcef5..479268a 100644 --- a/internal/guesttools/testdata/pasteboard.cjs +++ b/internal/guesttools/testdata/pasteboard.cjs @@ -47,9 +47,32 @@ const pasteboard = { } } -// The host reads the staged clipboard, optionally allowing a user copy before it releases the ACK. -class CurlTask { +class FixtureTask { get waitUntilExit() { + if (this.launchPath === '/usr/bin/perl') { + const [, , , ...paths] = this.arguments + fs.writeFileSync('test-hosted-probe.json', JSON.stringify(paths)) + const denied = fs.existsSync('test-hosted-probe-denied.json') + ? JSON.parse(fs.readFileSync('test-hosted-probe-denied.json')) : [] + try { + for (const path of paths) { + if (denied.includes(path)) throw Error('Cannot read hosted clipboard source') + const info = fs.statSync(path) + if (info.isDirectory()) { + const dir = fs.opendirSync(path) + try { dir.readSync() } finally { dir.closeSync() } + } else if (info.isFile()) { + const fd = fs.openSync(path, 'r') + try { fs.readSync(fd, Buffer.alloc(1)) } finally { fs.closeSync(fd) } + } else { + throw Error('Cannot read hosted clipboard source') + } + } + this.terminationStatus = 0 + } catch (_) { this.terminationStatus = 1 } + return + } + // The host reads the staged clipboard and may allow a new user copy before it releases the ACK. fs.writeFileSync('test-ack.json', JSON.stringify({ path: this.launchPath, args: this.arguments, config: this.standardInput.config, items: state.items })) @@ -92,7 +115,7 @@ const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value NSDate: {dateWithTimeIntervalSinceNow: seconds => seconds}, NSRunLoop: {currentRunLoop: {runUntilDate: () => fs.writeFileSync('test-pasteboard-flush', String(state.changeCount))}}, NSProcessInfo: {processInfo: {environment: {objectForKey: key => wrap(process.env[unwrap(key)])}}}, - NSTask: {alloc: {get init() { return new CurlTask() }}}, + NSTask: {alloc: {get init() { return new FixtureTask() }}}, NSPipe: {get pipe() { const pipe = {fileHandleForWriting: {writeData(data) { pipe.config = data }}} return pipe diff --git a/internal/guesttools/transport.go b/internal/guesttools/transport.go index 8562eda..812d33d 100644 --- a/internal/guesttools/transport.go +++ b/internal/guesttools/transport.go @@ -53,11 +53,12 @@ func DefaultClipboardPolicy() ClipboardPolicy { // ClipboardStats tracks privacy-safe counters (never clipboard content, §5.4). type ClipboardStats struct { - HostToGuestCount uint64 `json:"host_to_guest_count"` - GuestToHostCount uint64 `json:"guest_to_host_count"` - ErrorCount uint64 `json:"error_count"` - Active bool `json:"active"` - WatcherRunning bool `json:"watcher_running"` + HostToGuestCount uint64 `json:"host_to_guest_count"` + HostToGuestFilesAppliedCount uint64 `json:"host_to_guest_files_applied_count"` + GuestToHostCount uint64 `json:"guest_to_host_count"` + ErrorCount uint64 `json:"error_count"` + Active bool `json:"active"` + WatcherRunning bool `json:"watcher_running"` } // NewTransportServer constructs a Guest Tools HTTP transport server with @@ -66,6 +67,7 @@ func NewTransportServer(clip Clipboard) *Server { s := NewServer(clip) s.clipboardActive = false delete(s.dynamicRoutes, "/v1/clipboard") + delete(s.dynamicRoutes, fileClipboardAppliedPath) s.globalClipPolicy = DefaultClipboardPolicy() s.globalClipPolicy.Enabled = false return s @@ -96,8 +98,8 @@ func (s *Server) HasRoute(routePath string) bool { } // SetClipboardActive enables or disables the clipboard extension on this bridge. -// Enabling registers /v1/clipboard and starts the host clipboard watcher; -// disabling removes the route and stops the watcher with zero residue (§5.4). +// Enabling registers the clipboard routes and starts the host clipboard watcher. +// Disabling removes the routes and stops the watcher (§5.4). func (s *Server) SetClipboardActive(active bool) { s.mu.Lock() s.clipboardActive = active @@ -107,6 +109,7 @@ func (s *Server) SetClipboardActive(active bool) { if active { s.globalClipPolicy.Enabled = true s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard + s.dynamicRoutes[fileClipboardAppliedPath] = s.handleFileClipboardApplied if s.listener != nil && s.watchCancel == nil { watchCtx, watchCancel := context.WithCancel(context.Background()) s.watchCancel = watchCancel @@ -119,9 +122,11 @@ func (s *Server) SetClipboardActive(active bool) { s.globalClipPolicy.Enabled = false for _, vm := range s.vms { vm.dropShares.revokeClipboard() + vm.fileClipboardReceipt = fileClipboardReceipt{} } s.clearAllClipFilesLocked() delete(s.dynamicRoutes, "/v1/clipboard") + delete(s.dynamicRoutes, fileClipboardAppliedPath) cancel := s.watchCancel s.watchCancel = nil s.mu.Unlock() @@ -154,6 +159,7 @@ func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) { policy := s.effectiveClipboardPolicyLocked(key) if !policy.allowsHostToGuestFiles() { vm.dropShares.revokeClipboard() + vm.fileClipboardReceipt = fileClipboardReceipt{} } if !policy.allowsGuestToHostFiles() { s.clearVMClipFilesLocked(key) @@ -180,6 +186,7 @@ func (s *Server) SetVMClipboardPolicy(vmName string, p *ClipboardPolicy) { policy := s.effectiveClipboardPolicyLocked(vmName) if !policy.allowsHostToGuestFiles() { vm.dropShares.revokeClipboard() + vm.fileClipboardReceipt = fileClipboardReceipt{} } if !policy.allowsGuestToHostFiles() { s.clearVMClipFilesLocked(vmName) @@ -213,11 +220,12 @@ func (s *Server) effectiveClipboardPolicyLocked(vmName string) ClipboardPolicy { // ClipboardDiagnostics returns privacy-safe clipboard metrics (counts/errors only, §5.4). func (s *Server) ClipboardDiagnostics() ClipboardStats { return ClipboardStats{ - HostToGuestCount: atomic.LoadUint64(&s.clipStatsH2G), - GuestToHostCount: atomic.LoadUint64(&s.clipStatsG2H), - ErrorCount: atomic.LoadUint64(&s.clipStatsErr), - Active: s.IsClipboardActive(), - WatcherRunning: s.IsClipboardWatcherRunning(), + HostToGuestCount: atomic.LoadUint64(&s.clipStatsH2G), + HostToGuestFilesAppliedCount: s.clipFilesApplied.Load(), + GuestToHostCount: atomic.LoadUint64(&s.clipStatsG2H), + ErrorCount: atomic.LoadUint64(&s.clipStatsErr), + Active: s.IsClipboardActive(), + WatcherRunning: s.IsClipboardWatcherRunning(), } } diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index fcbc8a2..c1102ab 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -354,11 +354,12 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo PluginID: IDClipboard, Title: "Clipboard Sync Counters", Data: map[string]any{ - "active": stats.Active, - "watcher_running": stats.WatcherRunning, - "host_to_guest_count": stats.HostToGuestCount, - "guest_to_host_count": stats.GuestToHostCount, - "error_count": stats.ErrorCount, + "active": stats.Active, + "watcher_running": stats.WatcherRunning, + "host_to_guest_count": stats.HostToGuestCount, + "host_to_guest_files_applied_count": stats.HostToGuestFilesAppliedCount, + "guest_to_host_count": stats.GuestToHostCount, + "error_count": stats.ErrorCount, }, }, nil })