diff --git a/changes/fix-clipboard-sync-stability.json b/changes/fix-clipboard-sync-stability.json index de54b0c..700eb14 100644 --- a/changes/fix-clipboard-sync-stability.json +++ b/changes/fix-clipboard-sync-stability.json @@ -2,6 +2,6 @@ "group": "fixes", "order": 0, "authors": ["reiasu2"], - "zh": "修复 Windows 宿主机与 macOS 虚拟机之间的剪贴板同步失效问题,包括重复复制和挂起恢复后的失效。请在虚拟机内重新安装 Guest Tools 以升级到 `v11`。", - "en": "Fix clipboard sync between a Windows host and a macOS VM, including failures after copying the same content again or resuming a suspended VM. Reinstall Guest Tools inside the VM to upgrade to `v11`." + "zh": "修复 Windows 宿主机与 macOS 虚拟机之间的剪贴板同步失效问题,包括重复复制和挂起恢复后的失效。剪贴板内容未变时,同步会跳过重复读取和处理图片。请在虚拟机内重新安装 Guest Tools 以升级到 `v11`。", + "en": "Fix clipboard sync between a Windows host and a macOS VM, including failures after copying the same content again or resuming a suspended VM. Sync skips repeated image reads and processing while the clipboard stays unchanged. Reinstall Guest Tools inside the VM to upgrade to `v11`." } diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 9f92eb1..4b2cf59 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -2,6 +2,8 @@ package guesttools import ( "context" + "crypto/sha256" + "fmt" "os" "os/exec" "path/filepath" @@ -36,26 +38,71 @@ func TestGuestAgentClipboardScript(t *testing.T) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") } textInput := scriptSection(t, agent, "text_input_loop() {", "\ntext_input_loop &") + hashing := scriptSection(t, agent, "hash_file() {", "update_desktop_link() {") _, mainLoop, _ := strings.Cut(agent, "\ntext_input_loop &") + t.Run("hashing", func(t *testing.T) { + t.Parallel() + lockShellFixture(t) + tmp := t.TempDir() + data := []byte("first line\nsecond line\x00\xff") + if err := os.WriteFile(filepath.Join(tmp, "payload"), data, 0o600); err != nil { + t.Fatal(err) + } + script := filepath.Join(tmp, "hash-test.sh") + code := "set -eu\nPATH=\"/usr/bin:/bin:$PATH\"\n" + hashing + if runtime.GOOS == "windows" { + // Git Bash ships sha256sum in place of macOS shasum. + code += "shasum() { [ \"$1/$2\" = -a/256 ] || return 1; shift 2; sha256sum ${1+\"$@\"}; }\n" + } + code += "hash_file payload\nhash_png_file payload\n" + if err := os.WriteFile(script, []byte(code), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, sh, script) + cmd.Dir = tmp + out, err := cmd.CombinedOutput() + want := fmt.Sprintf("%x\n%x\n", sha256.Sum256(data), sha256.Sum256(append([]byte("png:"), data...))) + if err != nil || string(out) != want { + t.Fatalf("clipboard hashes: got %q, want %q, error %v", out, want, err) + } + }) + for _, group := range []struct { name string cases []string }{ - {"sync_basic", []string{ - "failed_png", "failed_text", "missing_hash", "reencoded_png", + {"download", []string{"failed_png", "failed_text", "missing_hash", "reencoded_png"}}, + {"download_during_copy", []string{ "guest_changes_during_get", "cold_guest_changes_during_get", "cold_lock_during_get", "repeat_host_copy", - "conflict", "conflict_skipped_host", "oversized", "disabled_upload", "post_error", }}, - {"sync_edge", []string{ - "guest_only_after_switch", "repeat_after_direction_switch", "cold_guest_only", "cold_304", - "empty_text_and_png_fallback", "unreadable_clipboard", "non_text_clipboard", "empty_text_clipboard", "failed_pbpaste", - "stale_lock", "lock_during_get", "live_lock", "dead_lock", + {"upload_conflicts", []string{"conflict", "conflict_skipped_host"}}, + {"upload_errors", []string{"oversized", "disabled_upload", "post_error"}}, + {"direction_switch", []string{"guest_only_after_switch", "repeat_after_direction_switch"}}, + {"initial_sync", []string{"cold_guest_only", "cold_304"}}, + {"local_formats", []string{ + "empty_text_and_png_fallback", "unreadable_clipboard", "non_text_clipboard", "empty_text_clipboard", }}, - {"worker_and_input", []string{ - "clipboard_worker", "clipboard_disabled", "clipboard_reenabled", - "input_failed", "input_restores_text", "input_restores_png", "input_restores_empty", - "input_restores_tiff", "input_preserves_new_copy", "input_exits_with_lock", + {"locking", []string{"stale_lock", "lock_during_get", "live_lock", "dead_lock"}}, + {"static_count", []string{"static_tiff", "static_png", "host_image_while_static"}}, + {"changing_count", []string{"new_local_png", "change_during_read", "change_during_get"}}, + {"count_after_write", []string{"change_after_write", "injection_restores_png"}}, + {"upload_retries", []string{"retry_conflict", "retry_server_error", "retry_transport_error"}}, + {"settled_uploads", []string{"settled_conflict", "settled_oversized", "settled_disabled"}}, + {"unavailable_count", []string{"count_unavailable", "count_invalid", "count_failed"}}, + {"read_recovery", []string{"info_failed_with_count", "failed_pbpaste", "read_failure_text"}}, + {"image_read_recovery", []string{"read_failure_png", "read_failure_tiff_export", "read_failure_tiff_sips"}}, + {"failed_download_recheck", []string{ + "recheck_failure_png", "recheck_failure_tiff_export", "recheck_failure_tiff_sips", + }}, + {"worker", []string{"clipboard_worker", "clipboard_disabled", "clipboard_reenabled"}}, + {"input_restore", []string{ + "input_restores_text", "input_restores_png", "input_restores_empty", "input_restores_tiff", + }}, + {"input_errors_and_conflicts", []string{ + "input_failed", "input_preserves_new_copy", "input_exits_with_lock", }}, } { t.Run(group.name, func(t *testing.T) { @@ -65,7 +112,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { script := filepath.Join(tmp, "clipboard-test.sh") code := "set -eu\nPATH=\"/usr/bin:/bin:$PATH\"\nnow=$(date +%s)\nrun_case() (\ncd \"$1\"\n" + agent[start:end] + textInput + clipboardShellFixture - if group.name == "worker_and_input" { + if group.name == "worker" { code += "\nif [ \"$1\" = clipboard_worker ]; then\ntext_input_loop &" + mainLoop + "\nfi\n" } code += "\n)\nfor scenario do\n printf '%s\\n' \"$scenario\"\n run_case \"$scenario\"\ndone\n" @@ -101,8 +148,11 @@ REIMS_TOKEN=token printf A > local_value : > calls : > copies +: > clip_work local_info="Unicode text" flags="" +failure_kind="" +fail_during_get=0 get_code=200 get_hash=B get_seq=8 @@ -121,9 +171,22 @@ read_file() { done < "$1" printf '%s' "$line" } -hash_file() { IFS= read -r value < "$1" || :; printf '%s' "$value"; } +bump_clipboard_count() { + if [ -f change_count ]; then + printf '%s\n' "$(($(read_file change_count) + 1))" > change_count + fi +} +hash_file() { + printf 'sha\n' >> clip_work + value="" + IFS= read -r value < "$1" || : + printf '%s' "$value" +} hash_png_file() { printf 'png:'; hash_file "$1"; } -pbpaste() { hash_file local_value; [ "$flags" != failed_pbpaste ]; } +pbpaste() { + read_file local_value + [ "$flags" != failed_pbpaste ] && { [ "$failure_kind" != text ] || [ ! -f read_failure ]; } +} pbcopy() { [ "$flags" != fail ] && [ "$flags" != input_failed ] || return 1 if [ "$flags" = input_exits_with_lock ]; then @@ -133,12 +196,28 @@ pbcopy() { printf '%s' "$value" > local_value rm -f reencoded printf 'text\n' >> copies + bump_clipboard_count } osascript() { case "$2" in + JavaScript) + expect "$1/$3/$4" '-l/-e/ObjC.import("AppKit"); $.NSPasteboard.generalPasteboard.changeCount' + [ ! -f change_count ] || read_file change_count + case "$flags" in + count_invalid) printf '1x\n' ;; + count_failed) printf '12\n'; return 1 ;; + esac + ;; 'clipboard info') + printf 'info\n' >> clip_work [ "$flags" != unreadable_clipboard ] || return 1 - if [ -f reencoded ]; then + if [ -f read_failure ]; then + case "$failure_kind" in + png) printf 'PNGf\n' ;; + tiff_*) printf 'TIFF\n' ;; + text) printf 'Unicode text\n' ;; + esac + elif [ -f reencoded ]; then printf 'PNGf\n' elif [ "$flags" = input_restores_tiff ] && [ -s copies ]; then printf 'Unicode text\n' @@ -152,23 +231,38 @@ osascript() { case "$6" in *PNGf*) [ -f reencoded ] || return 1 - hash_file local_value > "$out_file" + read_file local_value > "$out_file" + if [ "$flags" = change_during_read ] || + { [ "$flags" = change_after_write ] && [ -f wrote_png ]; }; then + printf C > local_value + bump_clipboard_count + fi + ;; + *TIFF*) + [ "$failure_kind" != tiff_export ] || [ ! -f read_failure ] || return 1 + printf 'tiff' > "$tiff_tmp" ;; - *TIFF*) printf 'tiff' > "$tiff_tmp" ;; esac ;; 'set the clipboard'*) [ "$flags" != fail ] || return 1 case "$2" in - *'as TIFF picture'*) hash_file "$TMP_DIR/txt_clip_bak" > local_value; : > restored_tiff; return ;; - *txt_clip_bak*) hash_file "$TMP_DIR/txt_clip_bak" > local_value ;; + *'as TIFF picture'*) read_file "$TMP_DIR/txt_clip_bak" > local_value; : > restored_tiff; return ;; + *txt_clip_bak*) read_file "$TMP_DIR/txt_clip_bak" > local_value ;; *) printf 'B-reencoded' > local_value ;; esac : > reencoded + : > wrote_png + bump_clipboard_count ;; esac } -sips() { : > sips_called; printf 'tiff-converted' > "$6"; } +sips() { + printf 'sips\n' >> clip_work + : > sips_called + [ "$failure_kind" != tiff_sips ] || [ ! -f read_failure ] || return 1 + printf 'tiff-converted' > "$6" +} curl() { method=GET headers="" @@ -228,16 +322,22 @@ curl() { return fi if [ "$post_code" = 200 ]; then - hash_file "$body" > host_value + read_file "$body" > host_value fi printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\n' "$post_hash" "$post_seq" > "$headers" + [ "$post_code" != 000 ] || return 1 printf '%s' "$post_code" else printf '%s %s\n' "$method" "$url" >> calls printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers" printf '%s' "$get_value" > "$output" - if [ "$flags" = guest_change ]; then + if [ "$fail_during_get" = 1 ]; then printf C > local_value + : > read_failure + bump_clipboard_count + elif [ "$flags" = guest_change ]; then + printf C > local_value + bump_clipboard_count elif [ "$flags" = inject_during_get ]; then date +%s > "$INJECT_LOCK" printf injected > local_value @@ -274,6 +374,178 @@ methods() { } case "$1" in + read_failure_*) + failure_kind="${1#read_failure_}" + get_code=304 + printf '11\n' > change_count + : > read_failure + sync_clipboard + expect "$synced_local_cc/$last_local_hash" /empty + expect "$(methods)" GET + rm read_failure + case "$failure_kind" in + png) : > reencoded; post_hash=png:A; expected_value=A ;; + tiff_*) local_info=TIFF; post_hash=png:tiff-converted; expected_value=tiff-converted ;; + text) post_hash=A; expected_value=A ;; + esac + sync_clipboard + expect "$(methods)/$(read_file host_value)/$synced_local_cc/$last_local_hash" "GET,POST/$expected_value/11/$post_hash" + ;; + recheck_failure_*) + failure_kind="${1#recheck_failure_}" + fail_during_get=1 + : > local_value + printf '11\n' > change_count + sync_clipboard + expect "$synced_local_cc/$last_local_hash/$last_server_hash/$last_server_seq" /empty//8 + expect "$(methods)/$(read_file local_value)/$(read_file change_count)" GET/C/12 + [ ! -s copies ] + [ ! -d "$CLIP_LOCK" ] + ;; + static_tiff|static_png|host_image_while_static|new_local_png|change_during_read|change_during_get|change_after_write|injection_restores_png|retry_*|settled_*|count_*|info_failed_with_count) + get_code=304 + : > reencoded + printf '11\n' > change_count + case "$1" in + static_tiff|host_image_while_static) + rm reencoded + local_info=TIFF + ;; + count_unavailable|count_invalid|count_failed) + rm change_count + flags="$1" + ;; + info_failed_with_count) flags=unreadable_clipboard ;; + change_during_read) flags="$1" ;; + esac + sync_clipboard + case "$1" in + static_tiff|host_image_while_static) + expect "$(paste -sd ',' clip_work)" info,sips,sha + expect "$synced_local_cc/$synced_local_kind/$last_local_hash" 11/png/png:tiff-converted + ;; + count_*) + expect "$(paste -sd ',' clip_work)" info,sha + expect "$synced_local_cc" "" + ;; + info_failed_with_count) + expect "$(paste -sd ',' clip_work)" info + expect "$synced_local_cc/$last_local_hash" /empty + ;; + change_during_read) + expect "$(paste -sd ',' clip_work)" info,sha + expect "$synced_local_cc/$last_local_hash/$(read_file change_count)" /png:A/12 + ;; + *) + expect "$(paste -sd ',' clip_work)" info,sha + expect "$synced_local_cc/$synced_local_kind/$last_local_hash" 11/png/png:A + ;; + esac + : > clip_work + case "$1" in + static_tiff|static_png) + sync_clipboard + sync_clipboard + [ ! -s clip_work ] + expect "$(methods)" GET,GET,GET + ;; + host_image_while_static|change_after_write) + get_code=200 + get_kind=png + get_hash=png:B + if [ "$1" = change_after_write ]; then flags="$1"; fi + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + if [ "$1" = host_image_while_static ]; then + expect "$synced_local_cc/$last_local_hash" 12/png:B-reencoded + get_code=304 + : > clip_work + sync_clipboard + [ ! -s clip_work ] + expect "$(methods)" GET,GET,GET + else + expect "$synced_local_cc/$last_local_hash/$(read_file change_count)" /png:B-reencoded/13 + flags="" + : > clip_work + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + expect "$(methods)/$(read_file host_value)/$synced_local_cc" GET,GET,POST/C/13 + fi + ;; + change_during_get) + get_code=200 + flags=guest_change + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + expect "$synced_local_cc/$last_local_hash/$(read_file local_value)" /png:A/C + flags="" + sync_clipboard + expect "$(methods)/$(read_file host_value)/$synced_local_cc" GET,GET,POST/C/12 + ;; + new_local_png|change_during_read|info_failed_with_count) + flags="" + if [ "$1" = new_local_png ]; then + printf C > local_value + bump_clipboard_count + fi + post_hash=png:C + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + expect "$(methods)/$(read_file host_value)/$synced_local_cc" "GET,POST/$(read_file local_value)/$(read_file change_count)" + ;; + injection_restores_png) + flags=input_restores_png + load_conf() { if [ -f input_polled ]; then exit; fi; } + (text_input_loop) + expect "$(read_file local_value)/$(read_file change_count)" A/13 + : > clip_work + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + expect "$(methods)/$synced_local_cc" GET,ack,GET/13 + : > clip_work + sync_clipboard + [ ! -s clip_work ] + ;; + retry_*|settled_*) + printf C > local_value + bump_clipboard_count + case "$1" in + retry_conflict|settled_conflict) post_code=409 ;; + retry_server_error) post_code=500 ;; + retry_transport_error) post_code=000 ;; + settled_oversized) post_code=413 ;; + settled_disabled) post_code=204; get_code=204 ;; + esac + if [ "$1" = settled_conflict ]; then get_hash=""; fi + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + : > clip_work + post_code=200 + post_hash=png:C + case "$1" in + retry_*) + expect "$synced_local_cc/$last_local_hash" /png:A + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha + expect "$(methods)/$(read_file host_value)" GET,POST,GET,POST/C + ;; + settled_*) + expect "$synced_local_cc/$last_local_hash" 12/png:C + sync_clipboard + [ ! -s clip_work ] + expect "$(methods)" GET,POST,GET,GET + ;; + esac + expect "$synced_local_cc/$last_local_hash" 12/png:C + ;; + count_*) + sync_clipboard + sync_clipboard + expect "$(paste -sd ',' clip_work)" info,sha,info,sha + expect "$(methods)/$synced_local_cc" GET,GET,GET/ + ;; + esac + ;; failed_png|failed_text|missing_hash) [ "$1" != failed_png ] || get_kind=png last_local_hash=A @@ -532,7 +804,10 @@ case "$1" in flags="$1" case "$1" in non_text_clipboard) local_info="picture" ;; - empty_text_clipboard) : > local_value ;; + empty_text_clipboard) + : > local_value + printf '11\n' > change_count + ;; esac last_local_hash=previous get_code=304 @@ -540,6 +815,11 @@ case "$1" in expect "$(read_local_clipboard ./clip_in)" empty expect "$(methods)" GET [ ! -f host_value ] + if [ "$1" = empty_text_clipboard ]; then + last_local_hash=empty + sync_clipboard + expect "$synced_local_cc/$last_local_hash" 11/empty + fi ;; clipboard_worker) text_input_loop() { :; } diff --git a/internal/guesttools/clipboard_test.go b/internal/guesttools/clipboard_test.go index bb8e86f..66c7cf7 100644 --- a/internal/guesttools/clipboard_test.go +++ b/internal/guesttools/clipboard_test.go @@ -155,6 +155,34 @@ func TestClipboardGETSequenceWithUnchangedHash(t *testing.T) { } } +func TestClipboardPOSTNormalizesPNG(t *testing.T) { + clip := &memClipboard{} + srv := newClipboardTestServer(clip) + pixels := makeSamplePNG(t, 1, 2, 3) + padded := append(bytes.Clone(pixels), 0, 0, 0) + post := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", padded) + hash, seq := post.Header().Get("X-Clip-Hash"), post.Header().Get("X-Clip-Seq") + if post.Code != http.StatusOK || hash != payloadHash(ClipPayload{Kind: ClipPNG, Data: pixels}) || seq == "" { + t.Fatalf("padded PNG POST: %d %v", post.Code, post.Header()) + } + got, err := clip.Read() + if err != nil || got.Kind != ClipPNG || !bytes.Equal(got.Data, pixels) { + t.Fatalf("stored PNG: kind %q, %d bytes, error %v", got.Kind, len(got.Data), err) + } + get := clipboardRequest(t, srv, http.MethodGet, "?accept=image&since="+hash+"&since_seq="+seq, "", "", nil) + if get.Code != http.StatusNotModified || get.Body.Len() != 0 { + t.Fatalf("GET after padded PNG POST: %d, %d body bytes", get.Code, get.Body.Len()) + } + repeated := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", padded) + if repeated.Code != http.StatusOK || repeated.Header().Get("X-Clip-Seq") != seq { + t.Fatalf("repeated padded PNG POST: %d %v", repeated.Code, repeated.Header()) + } + invalid := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", pixels[:len(pixels)-1]) + if invalid.Code != http.StatusBadRequest { + t.Fatalf("truncated PNG POST: %d, want %d", invalid.Code, http.StatusBadRequest) + } +} + func TestClipboardPOSTSequenceConflict(t *testing.T) { oldPNG := makeSamplePNG(t, 255, 0, 0) newPNG := makeSamplePNG(t, 0, 255, 0) diff --git a/internal/guesttools/clipboard_windows.go b/internal/guesttools/clipboard_windows.go index 86c78a1..ea5de85 100644 --- a/internal/guesttools/clipboard_windows.go +++ b/internal/guesttools/clipboard_windows.go @@ -29,6 +29,8 @@ var ( procSetClipboardData = user32.NewProc("SetClipboardData") procIsClipboardFormatAvail = user32.NewProc("IsClipboardFormatAvailable") procGetClipboardSequenceNumber = user32.NewProc("GetClipboardSequenceNumber") + procGetClipboardOwner = user32.NewProc("GetClipboardOwner") + procGetOpenClipboardWindow = user32.NewProc("GetOpenClipboardWindow") procRegisterClipboardFormatW = user32.NewProc("RegisterClipboardFormatW") kernel32 = syscall.NewLazyDLL("kernel32.dll") @@ -69,6 +71,7 @@ type clipboardCache struct { seq uint32 hasImage bool payload ClipPayload + hash string } type clipboardWindowMessage struct { @@ -308,31 +311,44 @@ func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) return c.cache.read(wantImage, c.SequenceNumber, c.readClipboardSnapshot) } +func (c *OSClipboard) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) { + return c.cache.readForSync(wantImage, c.SequenceNumber, c.readClipboardSnapshot, payloadHash) +} + func (c *clipboardCache) read(wantImage bool, sequence func() uint32, readSnapshot func(bool) (clipboardSnapshot, uint32, error)) (ClipPayload, uint32, error) { + payload, seq, _, err := c.readForSync(wantImage, sequence, readSnapshot, payloadHash) + payload.Data = bytes.Clone(payload.Data) + return payload, seq, err +} + +func (c *clipboardCache) readForSync(wantImage bool, sequence func() uint32, readSnapshot func(bool) (clipboardSnapshot, uint32, error), hashPayload func(ClipPayload) string) (ClipPayload, uint32, string, error) { c.mu.Lock() defer c.mu.Unlock() curSeq := sequence() if curSeq != 0 && c.valid && c.seq == curSeq && (c.hasImage || !wantImage) { if !wantImage && c.payload.Kind == ClipPNG { - return ClipPayload{Kind: ClipEmpty}, curSeq, nil + return ClipPayload{Kind: ClipEmpty}, curSeq, "", nil } - payload := c.payload - payload.Data = bytes.Clone(payload.Data) - return payload, curSeq, nil + return c.payload, curSeq, c.hash, nil } snap, seq, err := readSnapshot(wantImage) if err != nil { - return ClipPayload{}, seq, err + return ClipPayload{}, seq, "", err } payload := snap.payload() + var hash string + if payload.Kind != ClipEmpty { + hash = hashPayload(payload) + } if !(payload.Kind == ClipEmpty && snap.imageReadFailed) && seq != 0 && seq == sequence() { c.valid = true c.seq = seq c.hasImage = wantImage - c.payload = ClipPayload{Kind: payload.Kind, Data: bytes.Clone(payload.Data)} + c.payload = payload + c.hash = hash } - return payload, seq, nil + return payload, seq, hash, nil } func (c *OSClipboard) readClipboardSnapshot(wantImage bool) (clipboardSnapshot, uint32, error) { @@ -447,8 +463,9 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq c.cache.mu.Lock() defer c.cache.mu.Unlock() + var cacheSeq uint32 err = onClipboardThread(func(hwnd uintptr) error { - return withOpenClipboard(hwnd, func() error { + if err := withOpenClipboard(hwnd, func() error { seq = c.SequenceNumber() if baseSeq != nil && seq != *baseSeq { return errClipboardConflict @@ -465,11 +482,49 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq item.handle = 0 // The system now owns the handle. } } - seq = c.SequenceNumber() return writeErr + }); err != nil { + return err + } + // Closing the clipboard can synthesize formats and advance the sequence. + seq, cacheSeq = clipboardSequenceAfterWrite(hwnd, c.SequenceNumber, func() (uintptr, uintptr) { + owner, _, _ := procGetClipboardOwner.Call() + openWin, _, _ := procGetOpenClipboardWindow.Call() + return owner, openWin }) + return nil }) - c.cache.valid = false - c.cache.payload = ClipPayload{} + c.cache.updateAfterWrite(payload, cacheSeq, err, c.SequenceNumber) return seq, err } + +func clipboardSequenceAfterWrite(hwnd uintptr, sequence func() uint32, windows func() (uintptr, uintptr)) (seq, cacheSeq uint32) { + s1 := sequence() + owner, openWin := windows() + s2 := sequence() + if s1 != 0 && s1 == s2 && owner == hwnd && openWin == 0 { + return s1, s1 + } + if s2 != 0 { + return s2, 0 + } + return s1, 0 +} + +// updateAfterWrite runs with the cache locked across the clipboard write. +func (c *clipboardCache) updateAfterWrite(payload ClipPayload, seq uint32, err error, sequence func() uint32) { + c.valid = false + c.payload = ClipPayload{} + c.hash = "" + if err != nil || payload.Kind != ClipPNG || seq == 0 || seq != sequence() { + return + } + // Match the bytes returned by a clipboard read, including trimming padding. + if png, ok := TrimPNG(payload.Data); ok { + c.payload = ClipPayload{Kind: ClipPNG, Data: bytes.Clone(png)} + c.hash = payloadHash(c.payload) + c.seq = seq + c.hasImage = true + c.valid = true + } +} diff --git a/internal/guesttools/clipboard_windows_test.go b/internal/guesttools/clipboard_windows_test.go index 0cac021..0f787f5 100644 --- a/internal/guesttools/clipboard_windows_test.go +++ b/internal/guesttools/clipboard_windows_test.go @@ -6,7 +6,9 @@ import ( "bytes" "encoding/binary" "hash/crc32" + "image" "image/png" + "net/http" "strings" "sync" "testing" @@ -162,6 +164,180 @@ func TestWindowsClipboardReadUsesSequenceCache(t *testing.T) { } } +type windowsClipboardSyncFixture struct { + *memClipboard + cache clipboardCache + snapshot clipboardSnapshot + reads, hashes int + sequenceChecks int + lastPayload ClipPayload +} + +func (c *windowsClipboardSyncFixture) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) { + payload, seq, hash, err := c.cache.readForSync(wantImage, func() uint32 { + c.sequenceChecks++ + return c.SequenceNumber() + }, func(bool) (clipboardSnapshot, uint32, error) { + c.reads++ + return c.snapshot, c.SequenceNumber(), nil + }, func(payload ClipPayload) string { + c.hashes++ + return payloadHash(payload) + }) + c.lastPayload = payload + return payload, seq, hash, err +} + +func TestWindowsClipboardGETReusesLargePNG(t *testing.T) { + var encoded bytes.Buffer + encoder := png.Encoder{CompressionLevel: png.NoCompression} + if err := encoder.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 2048, 1536))); err != nil { + t.Fatal(err) + } + data := encoded.Bytes() + if len(data) < 10<<20 || len(data) > MaxClipboardBytes { + t.Fatalf("unexpected PNG size: %d", len(data)) + } + clip := &windowsClipboardSyncFixture{ + memClipboard: &memClipboard{seq: 7}, + snapshot: clipboardSnapshot{png: data}, + } + srv := newClipboardTestServer(clip) + hash := payloadHash(ClipPayload{Kind: ClipPNG, Data: data}) + const imageQuery = "?accept=image" + query := imageQuery + "&since=" + hash + "&since_seq=7" + for _, suffix := range []string{"", "&wait=1", ""} { + before := clip.sequenceChecks + resp := clipboardRequest(t, srv, http.MethodGet, query+suffix, "", "", nil) + if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || + resp.Header().Get("X-Clip-Seq") != "7" || resp.Header().Get("X-Clip-Hash") != hash || + resp.Header().Get("X-Clip-Kind") != string(ClipPNG) { + t.Fatalf("unchanged GET: %d %v, %d body bytes", resp.Code, resp.Header(), resp.Body.Len()) + } + if suffix != "" && clip.sequenceChecks-before < 2 { + t.Fatal("long poll did not recheck the clipboard on timeout") + } + if clip.reads != 1 || clip.hashes != 1 || len(clip.lastPayload.Data) != len(data) || + &clip.lastPayload.Data[0] != &clip.cache.payload.Data[0] { + t.Fatalf("unchanged GET: %d snapshot reads, %d hashes, %d payload bytes", clip.reads, clip.hashes, len(clip.lastPayload.Data)) + } + } + + // The server uses the supplied hash without hashing the snapshot again. + clip.cache.hash = "cached-hash" + resp := clipboardRequest(t, srv, http.MethodGet, imageQuery+"&since=cached-hash", "", "", nil) + if resp.Code != http.StatusNotModified || resp.Header().Get("X-Clip-Hash") != "cached-hash" { + t.Fatalf("cached hash GET: %d %v", resp.Code, resp.Header()) + } + for _, tc := range []struct { + query string + syncImages bool + maxBytes int + }{ + {"", true, len(data)}, + {imageQuery, true, len(data) - 1}, + {imageQuery, false, len(data)}, + } { + policy := DefaultClipboardPolicy() + policy.SyncImages = tc.syncImages + policy.MaxImageBytes = tc.maxBytes + srv.SetGlobalClipboardPolicy(policy) + resp := clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil) + if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != "" { + t.Fatalf("filtered GET: %d %v, %d body bytes", resp.Code, resp.Header(), resp.Body.Len()) + } + } + if clip.reads != 1 || clip.hashes != 1 { + t.Fatalf("filtered GETs: %d snapshot reads, %d hashes", clip.reads, clip.hashes) + } + + srv.SetGlobalClipboardPolicy(DefaultClipboardPolicy()) + next := makeSamplePNG(t, 4, 5, 6) + clip.snapshot.png = next + clip.seq++ + resp = clipboardRequest(t, srv, http.MethodGet, query, "", "", nil) + if resp.Code != http.StatusOK || !bytes.Equal(resp.Body.Bytes(), next) || resp.Header().Get("X-Clip-Seq") != "8" || + resp.Header().Get("X-Clip-Hash") != payloadHash(ClipPayload{Kind: ClipPNG, Data: next}) || + clip.reads != 2 || clip.hashes != 2 { + t.Fatalf("changed GET: %d %v, %d body bytes, %d snapshot reads, %d hashes", resp.Code, resp.Header(), resp.Body.Len(), clip.reads, clip.hashes) + } +} + +func TestWindowsClipboardGETUsesWrittenPNGCache(t *testing.T) { + pixels := makeSamplePNG(t, 1, 2, 3) + input := ClipPayload{Kind: ClipPNG, Data: append(bytes.Clone(pixels), 0, 0)} + clip := &windowsClipboardSyncFixture{memClipboard: &memClipboard{seq: 7}} + srv := newClipboardTestServer(clip) + clip.cache.updateAfterWrite(input, 7, nil, clip.SequenceNumber) + input.Data[0] ^= 0xff + + resp := clipboardRequest(t, srv, http.MethodGet, "?accept=image", "", "", nil) + if resp.Code != http.StatusOK || !bytes.Equal(resp.Body.Bytes(), pixels) || + resp.Header().Get("X-Clip-Hash") != payloadHash(ClipPayload{Kind: ClipPNG, Data: pixels}) || + clip.reads != 0 || clip.hashes != 0 { + t.Fatalf("written PNG GET: %d %v, %d body bytes, %d snapshot reads, %d hashes", resp.Code, resp.Header(), resp.Body.Len(), clip.reads, clip.hashes) + } + + input.Data[0] ^= 0xff + for _, tc := range []struct { + seq uint32 + err error + }{ + {7, errClipboardConflict}, + {6, nil}, + {0, nil}, + } { + clip.cache.updateAfterWrite(input, 7, nil, clip.SequenceNumber) + if !clip.cache.valid { + t.Fatal("expected a valid cache before write failure") + } + clip.cache.updateAfterWrite(input, tc.seq, tc.err, clip.SequenceNumber) + if clip.cache.valid || len(clip.cache.payload.Data) != 0 || clip.cache.hash != "" { + t.Fatalf("write with sequence %d and error %v left a cached payload", tc.seq, tc.err) + } + } +} + +func TestWindowsClipboardSequenceAfterWrite(t *testing.T) { + const hwnd = 1 + pixels := makeSamplePNG(t, 1, 2, 3) + payload := ClipPayload{Kind: ClipPNG, Data: pixels} + for _, tc := range []struct { + name string + owner uintptr + openWin uintptr + advance uint32 + cached bool + }{ + {"close synthesizes two formats", hwnd, 0, 0, true}, + {"ownership taken after close", 2, 0, 0, false}, + {"another window opened clipboard", hwnd, 2, 0, false}, + {"sequence changes during sampling", hwnd, 0, 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + clip := &windowsClipboardSyncFixture{memClipboard: &memClipboard{seq: 3}} + clip.cache.updateAfterWrite(payload, 3, nil, clip.SequenceNumber) + clip.seq += 2 // CloseClipboard synthesizes CF_BITMAP and CF_DIBV5. + seq, cacheSeq := clipboardSequenceAfterWrite(hwnd, clip.SequenceNumber, func() (uintptr, uintptr) { + clip.seq += tc.advance + return tc.owner, tc.openWin + }) + clip.cache.updateAfterWrite(payload, cacheSeq, nil, clip.SequenceNumber) + if seq != 5+tc.advance || clip.cache.valid != tc.cached { + t.Fatalf("sequence %d, cache valid %t, want %d, %t", seq, clip.cache.valid, 5+tc.advance, tc.cached) + } + if !tc.cached { + return + } + resp := clipboardRequest(t, newClipboardTestServer(clip), http.MethodGet, "?accept=image", "", "", nil) + if resp.Code != http.StatusOK || resp.Header().Get("X-Clip-Seq") != "5" || + !bytes.Equal(resp.Body.Bytes(), pixels) || clip.reads != 0 || clip.hashes != 0 { + t.Fatalf("GET after write: %d %v, %d snapshot reads, %d hashes", resp.Code, resp.Header(), clip.reads, clip.hashes) + } + }) + } +} + func TestWindowsClipboardRetriesTransientImageReads(t *testing.T) { const pngFormat = 0xc000 const seq = 15 diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index a6af49c..20e24e5 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -453,13 +453,17 @@ report_status() { read_local_clipboard() { out_file="$1" + read_failed=0 if ! cinfo=$(osascript -e 'clipboard info' 2>/dev/null); then echo "empty" + if [ "${2:-}" = sync ]; then return 1; fi return 0 fi case "$cinfo" in *utf8*|*"Unicode text"*|*string*) - if pbpaste >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then + if ! pbpaste >"$out_file" 2>/dev/null; then + read_failed=1 + elif [ -s "$out_file" ]; then echo "text" return 0 fi @@ -475,6 +479,7 @@ read_local_clipboard() { echo "png" return 0 fi + read_failed=1 ;; esac case "$cinfo" in @@ -497,9 +502,16 @@ read_local_clipboard() { fi fi rm -f "$tiff_tmp" + read_failed=1 ;; esac echo "empty" + if [ "${2:-}" = sync ] && [ "$read_failed" = 1 ]; then return 1; fi +} + +read_clipboard_change_count() { + clip_cc=$(osascript -l JavaScript -e 'ObjC.import("AppKit"); $.NSPasteboard.generalPasteboard.changeCount' 2>/dev/null) || clip_cc="" + case "$clip_cc" in ""|*[!0-9]*) clip_cc="" ;; esac } write_local_png() { @@ -514,6 +526,24 @@ local_clip_hash() { esac } +read_clipboard_for_sync() { + read_ok=1 + read_cc="" + if ! read_kind=$(read_local_clipboard "$clip_in" sync); then + read_ok=0 + read_hash=empty + return 0 + fi + read_hash=$(local_clip_hash "$read_kind" "$clip_in") + # Only associate the snapshot with a count if it stayed stable through the read. + if [ -n "$1" ]; then + read_clipboard_change_count + if [ "$1" = "$clip_cc" ]; then + read_cc="$1" + fi + fi +} + clip_header() { while IFS=':' read -r hdr_key hdr_val; do case "$1:$hdr_key" in @@ -530,6 +560,8 @@ clip_header() { } last_local_hash="" +synced_local_cc="" +synced_local_kind="" last_server_hash="" last_server_seq="" tick=0 @@ -625,8 +657,18 @@ sync_clipboard() { clip_out="$TMP_DIR/clip_out" hdr_out="$TMP_DIR/clip_hdr" - local_kind=$(read_local_clipboard "$clip_in") - cur_hash=$(local_clip_hash "$local_kind" "$clip_in") + read_clipboard_change_count + cur_cc="$clip_cc" + if [ -n "$cur_cc" ] && [ "$cur_cc" = "$synced_local_cc" ] && [ -n "$last_local_hash" ]; then + read_cc="$cur_cc" + local_kind="$synced_local_kind" + cur_hash="$last_local_hash" + else + synced_local_cc="" + read_clipboard_for_sync "$cur_cc" + local_kind="$read_kind" + cur_hash="$read_hash" + fi release_clip_lock post_conflict=0 @@ -645,12 +687,16 @@ sync_clipboard() { case "$code" in 200) last_local_hash="$cur_hash" + synced_local_cc="$read_cc" + synced_local_kind="$local_kind" last_server_hash=$(clip_header x-clip-hash) last_server_seq=$(clip_header x-clip-seq) return 0 ;; 204|413) last_local_hash="$cur_hash" + synced_local_cc="$read_cc" + synced_local_kind="$local_kind" if [ -z "$last_server_seq" ]; then last_server_hash="" fi @@ -684,10 +730,18 @@ sync_clipboard() { release_clip_lock return 0 fi - post_get_kind=$(read_local_clipboard "$clip_in") - post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in") - if [ "$post_get_hash" != "$cur_hash" ]; then + read_clipboard_change_count + if [ -n "$read_cc" ] && [ "$clip_cc" = "$read_cc" ]; then + read_ok=1 + read_kind="$local_kind" + read_hash="$cur_hash" + else + read_clipboard_for_sync "$clip_cc" + fi + post_get_hash="$read_hash" + if [ "$read_ok" = 0 ] || [ "$post_get_hash" != "$cur_hash" ]; then [ -n "$last_local_hash" ] || last_local_hash="$cur_hash" + synced_local_cc="" last_server_seq="$new_seq" release_clip_lock return 0 @@ -698,11 +752,14 @@ sync_clipboard() { else pbcopy <"$clip_out" 2>/dev/null || { release_clip_lock; sleep 2; return 0; } fi - post_get_kind=$(read_local_clipboard "$clip_in") - post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in") + read_clipboard_change_count + read_clipboard_for_sync "$clip_cc" + post_get_hash="$read_hash" fi release_clip_lock last_local_hash="$post_get_hash" + synced_local_cc="$read_cc" + synced_local_kind="$read_kind" last_server_hash="$new_hash" last_server_seq="$new_seq" ;; @@ -722,6 +779,10 @@ sync_clipboard() { last_local_hash="$cur_hash" fi fi + if [ "$last_local_hash" = "$cur_hash" ]; then + synced_local_cc="$read_cc" + synced_local_kind="$local_kind" + fi ;; 503) # Feature disabled on host: back off instead of busy-looping osascript + curl. diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 6c980ce..37de860 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -954,6 +954,17 @@ func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) return payload, seq, err } +func (s *Server) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) { + if clip, ok := s.clip.(interface { + // The returned data is immutable and can be passed to io.Writer. + readClipboardForSync(bool) (ClipPayload, uint32, string, error) + }); ok { + return clip.readClipboardForSync(wantImage) + } + payload, seq, err := s.readClipboardState(wantImage) + return payload, seq, "", err +} + func setClipboardSeq(w http.ResponseWriter, seq uint32) { w.Header().Set("X-Clip-Seq", strconv.FormatUint(uint64(seq), 10)) } @@ -1011,7 +1022,7 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri } wantImage := wantsImage && policy.SyncImages - payload, seq, err := s.readClipboardState(wantImage) + payload, seq, h, err := s.readClipboardForSync(wantImage) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) @@ -1020,7 +1031,9 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG && wantImage && len(payload.Data) <= policy.MaxImageBytes) if syncable { - h := payloadHash(payload) + if h == "" { + h = payloadHash(payload) + } unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq)) if !unchanged || time.Until(deadline) <= 0 { setClipboardSeq(w, seq) @@ -1106,11 +1119,12 @@ func (s *Server) postClipboard(w http.ResponseWriter, r *http.Request, vmName st } payload := ClipPayload{Kind: ClipText, Data: body} if isImage { - if !IsPNG(body) { + png, ok := TrimPNG(body) + if !ok { http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest) return } - payload.Kind = ClipPNG + payload = ClipPayload{Kind: ClipPNG, Data: png} } else { if !utf8.Valid(body) { http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest)