fix: synchronize clipboard for macOS app windows
This commit is contained in:
1 parent
3bfbc3604d
commit
a9b2553727
13 files changed
+840
-38
No files matched your search
@@ -2,6 +2,6 @@
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "可在 Windows 独立窗口中查看和操作正在运行的 macOS 虚拟机的前台应用。",
|
||||
"en": "View and interact with the foreground app of a running macOS VM in a separate Windows window."
|
||||
"zh": "可在 Windows 独立窗口中操作正在运行的 macOS 虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
|
||||
"en": "Interact with the foreground app of a running macOS VM in a separate Windows window with bidirectional copy and paste."
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func (a *App) OpenAppWindow(driverID, name string) error {
|
||||
if !status.Connected {
|
||||
return coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
|
||||
}
|
||||
if status.AgentVersion < guesttools.WindowReportAgentVersion {
|
||||
if status.AgentVersion < guesttools.PasteReadyAgentVersion {
|
||||
return coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
|
||||
}
|
||||
service := a.computerUseInternalService()
|
||||
@@ -102,6 +102,18 @@ func (a *App) OpenAppWindow(driverID, name string) error {
|
||||
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) {
|
||||
return bridge.ActiveWindow(name, maxAge)
|
||||
},
|
||||
PrepareClipboard: func(wait context.Context) (func(), error) {
|
||||
return bridge.PrepareGuestClipboardPaste(wait, name)
|
||||
},
|
||||
OnClipboardError: func(err error) {
|
||||
a.emitVMLogForDriver(info.DriverID, name, "App window paste: "+err.Error())
|
||||
a.mu.Lock()
|
||||
manager := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
if manager != nil {
|
||||
manager.Notify(i18n.T(locale, "tray.notify.app_window_paste_retry"), name, true)
|
||||
}
|
||||
},
|
||||
})
|
||||
if errors.Is(err, appwindow.ErrNoWindow) {
|
||||
return coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil)
|
||||
|
||||
@@ -24,6 +24,7 @@ var ErrNoWindow = errors.New("no foreground guest window reported")
|
||||
const (
|
||||
windowMaxAge = time.Second
|
||||
frameTimeout = 800 * time.Millisecond
|
||||
pasteTimeout = 4 * time.Second
|
||||
maxFramePixels = 4096 * 2160
|
||||
)
|
||||
|
||||
@@ -40,10 +41,12 @@ type Console interface {
|
||||
}
|
||||
|
||||
type SessionOptions struct {
|
||||
VMDir string
|
||||
TmpDir string
|
||||
Window func(time.Duration) (guesttools.ActiveWindow, bool)
|
||||
Console Console
|
||||
VMDir string
|
||||
TmpDir string
|
||||
Window func(time.Duration) (guesttools.ActiveWindow, bool)
|
||||
Console Console
|
||||
PrepareClipboard func(context.Context) (func(), error)
|
||||
OnClipboardError func(error)
|
||||
}
|
||||
|
||||
type frameMapping struct {
|
||||
@@ -64,34 +67,52 @@ type session struct {
|
||||
}
|
||||
|
||||
type inputQueue struct {
|
||||
mu sync.Mutex
|
||||
events []ViewerEvent
|
||||
ready chan struct{}
|
||||
mu sync.Mutex
|
||||
events []queuedInput
|
||||
ready chan struct{}
|
||||
focus context.Context
|
||||
cancelFocus context.CancelFunc
|
||||
}
|
||||
|
||||
type queuedInput struct {
|
||||
ViewerEvent
|
||||
focus context.Context
|
||||
}
|
||||
|
||||
func (q *inputQueue) push(event ViewerEvent) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if event.Kind == ViewerFocus || event.Kind == ViewerClose {
|
||||
if q.cancelFocus != nil {
|
||||
q.cancelFocus()
|
||||
q.focus, q.cancelFocus = nil, nil
|
||||
}
|
||||
if event.Kind == ViewerFocus && event.Down {
|
||||
q.focus, q.cancelFocus = context.WithCancel(context.Background())
|
||||
}
|
||||
}
|
||||
input := queuedInput{ViewerEvent: event, focus: q.focus}
|
||||
last := len(q.events) - 1
|
||||
if last >= 0 && q.events[last].Kind == ViewerMouseMove && event.Kind == ViewerMouseMove {
|
||||
q.events[last] = event
|
||||
q.events[last] = input
|
||||
return true
|
||||
}
|
||||
if len(q.events) == 64 {
|
||||
return event.Kind == ViewerMouseMove
|
||||
}
|
||||
q.events = append(q.events, event)
|
||||
q.events = append(q.events, input)
|
||||
if last < 0 {
|
||||
q.ready <- struct{}{}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (q *inputQueue) pop() ViewerEvent {
|
||||
func (q *inputQueue) pop() queuedInput {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
event := q.events[0]
|
||||
copy(q.events, q.events[1:])
|
||||
q.events[len(q.events)-1] = queuedInput{}
|
||||
q.events = q.events[:len(q.events)-1]
|
||||
if len(q.events) > 0 {
|
||||
q.ready <- struct{}{}
|
||||
@@ -310,7 +331,8 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e
|
||||
return ErrNoWindow
|
||||
}
|
||||
case <-queue.ready:
|
||||
event := queue.pop()
|
||||
input := queue.pop()
|
||||
event := input.ViewerEvent
|
||||
if event.Kind == ViewerClose || (event.Kind == ViewerFocus && !event.Down) {
|
||||
if err := release(frameTimeout); err != nil {
|
||||
return fmt.Errorf("release app window input: %w", err)
|
||||
@@ -319,9 +341,42 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e
|
||||
continue
|
||||
}
|
||||
mapping, active := s.eventMapping(event)
|
||||
request, cancel := context.WithTimeout(ctx, frameTimeout)
|
||||
base := ctx
|
||||
finish := func() {}
|
||||
paste := active && s.PrepareClipboard != nil && isPaste(event, keys)
|
||||
if paste {
|
||||
if input.focus == nil || input.focus.Err() != nil {
|
||||
continue
|
||||
}
|
||||
focused, cancelFocus := context.WithCancel(ctx)
|
||||
stopFocus := context.AfterFunc(input.focus, cancelFocus)
|
||||
wait, cancelWait := context.WithTimeout(focused, pasteTimeout)
|
||||
releasePaste, err := s.PrepareClipboard(wait)
|
||||
cancelWait()
|
||||
finish = func() {
|
||||
if releasePaste != nil {
|
||||
releasePaste()
|
||||
}
|
||||
stopFocus()
|
||||
cancelFocus()
|
||||
}
|
||||
if err != nil || input.focus.Err() != nil || focused.Err() != nil {
|
||||
finish()
|
||||
if err != nil && input.focus.Err() == nil && ctx.Err() == nil && s.OnClipboardError != nil {
|
||||
s.OnClipboardError(err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
mapping, active = s.eventMapping(event)
|
||||
base = focused
|
||||
}
|
||||
request, cancel := context.WithTimeout(base, frameTimeout)
|
||||
err := s.forwardEvent(request, event, mapping, active, keys, buttons, &wheel)
|
||||
cancel()
|
||||
finish()
|
||||
if err != nil && paste && input.focus.Err() != nil {
|
||||
continue
|
||||
}
|
||||
// A newer movement supersedes a timed-out hover. Button and key
|
||||
// transitions still fail the session so held input gets released.
|
||||
if err != nil && event.Kind != ViewerMouseMove {
|
||||
@@ -331,6 +386,11 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e
|
||||
}
|
||||
}
|
||||
|
||||
func isPaste(event ViewerEvent, keys map[string]bool) bool {
|
||||
return event.Kind == ViewerKey && event.Down && qmp.QKeyCode(event.VirtualKey) == "v" &&
|
||||
!keys["v"] && (keys["meta_l"] || keys["meta_r"])
|
||||
}
|
||||
|
||||
func (s *session) forwardEvent(ctx context.Context, event ViewerEvent, m frameMapping, active bool, keys, buttons map[string]bool, wheel *int) error {
|
||||
if event.Kind == ViewerKey {
|
||||
key := qmp.QKeyCode(event.VirtualKey)
|
||||
|
||||
@@ -13,6 +13,90 @@ import (
|
||||
|
||||
type captureConsole struct{ Console }
|
||||
|
||||
type pasteConsole struct {
|
||||
Console
|
||||
sent chan string
|
||||
}
|
||||
|
||||
func (c pasteConsole) SendKey(_ context.Context, _, key string, down bool) error {
|
||||
if down {
|
||||
c.sent <- key
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c pasteConsole) ReleaseInputs(context.Context, string, []string, []string) error {
|
||||
c.sent <- "released"
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPasteWaitsForClipboardAndCancelsOnBlur(t *testing.T) {
|
||||
for _, name := range []string{"applied", "blur"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
window := guesttools.ActiveWindow{ID: 1}
|
||||
ready, entered := make(chan struct{}), make(chan struct{})
|
||||
console := pasteConsole{sent: make(chan string, 8)}
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Console: console,
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return window, true },
|
||||
PrepareClipboard: func(ctx context.Context) (func(), error) {
|
||||
close(entered)
|
||||
select {
|
||||
case <-ready:
|
||||
return func() {}, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
},
|
||||
id: 1, tag: 1, mapping: frameMapping{window: window}, lastFrame: time.Now(),
|
||||
}
|
||||
queue := &inputQueue{ready: make(chan struct{}, 1)}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- s.forwardInput(ctx, queue) }()
|
||||
defer func() {
|
||||
cancel()
|
||||
<-done
|
||||
}()
|
||||
|
||||
queue.push(ViewerEvent{Kind: ViewerFocus, Down: true})
|
||||
queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 0x11, Down: true})
|
||||
queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 'V', Down: true})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("clipboard wait did not start")
|
||||
}
|
||||
if key := <-console.sent; key != "meta_l" {
|
||||
t.Fatalf("first key = %q", key)
|
||||
}
|
||||
select {
|
||||
case key := <-console.sent:
|
||||
t.Fatalf("forwarded %q before clipboard changed", key)
|
||||
default:
|
||||
}
|
||||
want := "v"
|
||||
if name == "blur" {
|
||||
queue.push(ViewerEvent{Kind: ViewerFocus})
|
||||
want = "released"
|
||||
} else {
|
||||
close(ready)
|
||||
}
|
||||
select {
|
||||
case key := <-console.sent:
|
||||
if key != want {
|
||||
t.Fatalf("event = %q, want %q", key, want)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("did not receive %q", want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInputQueueKeepsClickBetweenMoves(t *testing.T) {
|
||||
q := &inputQueue{ready: make(chan struct{}, 1)}
|
||||
for _, event := range []ViewerEvent{
|
||||
@@ -36,7 +120,7 @@ func TestInputQueueKeepsClickBetweenMoves(t *testing.T) {
|
||||
default:
|
||||
t.Fatal("queue did not notify its reader")
|
||||
}
|
||||
if got := q.pop(); got != want {
|
||||
if got := q.pop().ViewerEvent; got != want {
|
||||
t.Fatalf("event = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,11 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
cases []string
|
||||
}{
|
||||
{"download", []string{"failed_png", "failed_text", "missing_hash", "reencoded_png"}},
|
||||
{"paste_ready", []string{
|
||||
"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",
|
||||
}},
|
||||
{"download_during_copy", []string{
|
||||
"guest_changes_during_get", "cold_guest_changes_during_get", "cold_lock_during_get", "repeat_host_copy",
|
||||
}},
|
||||
@@ -231,6 +236,10 @@ post_code=200
|
||||
post_hash=C
|
||||
post_seq=9
|
||||
check_post_base=0
|
||||
offer_ack=0
|
||||
offer_recheck=0
|
||||
ack_hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
ack_nonce=ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
|
||||
# MSYS cannot apply RLIMIT_FSIZE. The fixture still verifies the archive and HTTP flow.
|
||||
case "$(uname -s)" in
|
||||
@@ -410,6 +419,11 @@ curl() {
|
||||
accept=""
|
||||
output=""
|
||||
base=""
|
||||
request_ack=""
|
||||
acknowledged_seq=""
|
||||
acknowledged_hash=""
|
||||
acknowledged_generation=""
|
||||
acknowledged_request=""
|
||||
body=""
|
||||
archive_upload=""
|
||||
url=""
|
||||
@@ -423,6 +437,11 @@ curl() {
|
||||
-H)
|
||||
case "$2" in
|
||||
'X-Clip-Base-Seq: '*) base="$2" ;;
|
||||
'X-Reims-Clipboard-Ack: '*) request_ack="${2#*: }" ;;
|
||||
'X-Clip-Seq: '*) acknowledged_seq="${2#*: }" ;;
|
||||
'X-Clip-Hash: '*) acknowledged_hash="${2#*: }" ;;
|
||||
'X-Reims-Clipboard-Generation: '*) acknowledged_generation="${2#*: }" ;;
|
||||
'X-Reims-Clipboard-Request: '*) acknowledged_request="${2#*: }" ;;
|
||||
'Accept: '*) accept="$2" ;;
|
||||
esac
|
||||
shift
|
||||
@@ -466,6 +485,13 @@ curl() {
|
||||
fi
|
||||
return
|
||||
;;
|
||||
*/v1/clipboard/applied)
|
||||
[ ! -d "$CLIP_LOCK" ] || exit 1
|
||||
expect "$method/$acknowledged_seq/$acknowledged_hash/$acknowledged_generation/$acknowledged_request" \
|
||||
"POST/$get_seq/$get_hash/14/$ack_nonce"
|
||||
printf 'ACK %s\n' "$url" >> calls
|
||||
return
|
||||
;;
|
||||
esac
|
||||
[ ! -d "$CLIP_LOCK" ] || exit 1
|
||||
if [ -n "$archive_upload" ]; then
|
||||
@@ -509,6 +535,13 @@ curl() {
|
||||
: > "$headers"
|
||||
else
|
||||
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers"
|
||||
if [ "$offer_ack/$get_code" = 1/200 ]; then
|
||||
expect "$request_ack" 1
|
||||
printf 'X-Reims-Clipboard-Ack: 1\r\nX-Reims-Clipboard-Generation: 14\r\nX-Reims-Clipboard-Request: %s\r\n' "$ack_nonce" >> "$headers"
|
||||
if [ "$offer_recheck" = 1 ]; then
|
||||
printf 'X-Reims-Clipboard-Recheck: 1\r\n' >> "$headers"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
printf '%s' "$get_value" > "$output"
|
||||
if [ "$fail_during_get" = 1 ]; then
|
||||
@@ -579,7 +612,10 @@ case "$1" in
|
||||
host_files_failed_write) : > test-fail-file-write ;;
|
||||
host_files_partial_write) : > test-partial-file-write ;;
|
||||
esac
|
||||
if [ "$1" != host_files_sync_no_echo ]; then
|
||||
if [ "$1" = host_files_sync_no_echo ]; then
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
else
|
||||
printf '%s\n' '{"changeCount":17,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json
|
||||
fi
|
||||
sync_clipboard
|
||||
@@ -589,7 +625,7 @@ case "$1" in
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
exit 0
|
||||
fi
|
||||
expect "$last_server_hash" B
|
||||
expect "$last_server_hash" "$get_hash"
|
||||
expect "$synced_local_cc/$synced_local_kind" 2/files
|
||||
expect "$(read_local_clipboard readback)" files
|
||||
expect "$(awk 'END {print NR}' readback)" 2
|
||||
@@ -598,12 +634,14 @@ a%23note.txt'
|
||||
expect "$last_local_hash" "files:$(cat readback)"
|
||||
get_code=304
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,GET
|
||||
expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=8'
|
||||
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_tar_fallback|host_files_tar_fallback_changed)
|
||||
flags=typed_files
|
||||
get_kind=files
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}'
|
||||
printf foreign > mount_owner
|
||||
printf '0 1048576\n' > clip_file_config
|
||||
@@ -612,13 +650,14 @@ a%23note.txt'
|
||||
tar -cf guest-fallback.tar fallback.txt
|
||||
if [ "$1" = host_files_tar_fallback_changed ]; then : > change_during_archive; fi
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,DOWNLOAD
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
if [ "$1" = host_files_tar_fallback_changed ]; then
|
||||
expect "$(methods)" GET,DOWNLOAD
|
||||
expect "$last_server_hash/$file_retry_polls" /3
|
||||
expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy'
|
||||
else
|
||||
expect "$last_server_hash" B
|
||||
expect "$(methods)" GET,DOWNLOAD,ACK
|
||||
expect "$last_server_hash" "$get_hash"
|
||||
expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" fallback
|
||||
expect "$(read_local_clipboard readback)" files
|
||||
grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback
|
||||
@@ -1033,6 +1072,53 @@ a%23note.txt'
|
||||
expect "$(methods)" GET,GET
|
||||
expect_call -F 'since=png:B&'
|
||||
;;
|
||||
paste_ack_*)
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
get_value="$get_hash"
|
||||
printf '10\n' > change_count
|
||||
case "$1" in
|
||||
paste_ack_preapplied) printf '%s' "$get_value" > local_value ;;
|
||||
paste_ack_local_change) flags=guest_change ;;
|
||||
paste_ack_unmarked) offer_ack=0 ;;
|
||||
paste_ack_png) get_kind=png ;;
|
||||
paste_ack_unstable_png) get_kind=png; flags=change_after_write ;;
|
||||
paste_ack_without_request) ack_nonce="" ;;
|
||||
esac
|
||||
sync_clipboard
|
||||
case "$1" in
|
||||
paste_ack_text|paste_ack_preapplied)
|
||||
expect "$(methods)/$(read_file local_value)" "GET,ACK/$get_value"
|
||||
if [ "$1" = paste_ack_preapplied ]; then [ ! -s copies ]; fi
|
||||
;;
|
||||
paste_ack_png) expect "$(methods)/$synced_local_kind" GET,ACK/png ;;
|
||||
paste_ack_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;;
|
||||
*) expect "$(methods)" GET ;;
|
||||
esac
|
||||
;;
|
||||
paste_recheck_*)
|
||||
offer_ack=1
|
||||
offer_recheck=1
|
||||
get_hash="$ack_hash"
|
||||
get_value="$get_hash"
|
||||
last_server_hash="$get_hash"
|
||||
last_server_seq="$get_seq"
|
||||
last_local_hash=guest-own
|
||||
printf '%s' "$last_local_hash" > local_value
|
||||
printf '10\n' > change_count
|
||||
case "$1" in
|
||||
paste_recheck_local_change) flags=guest_change ;;
|
||||
paste_recheck_inject) flags=inject_during_get ;;
|
||||
paste_recheck_drop) flags=drop_during_get ;;
|
||||
esac
|
||||
sync_clipboard
|
||||
[ ! -s copies ]
|
||||
case "$1" in
|
||||
paste_recheck_guest_owned) 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
|
||||
;;
|
||||
guest_changes_during_get|cold_guest_changes_during_get)
|
||||
if [ "$1" = guest_changes_during_get ]; then
|
||||
last_local_hash=A
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
clipboardAppliedPath = "/v1/clipboard/applied"
|
||||
clipboardAckHeader = "X-Reims-Clipboard-Ack"
|
||||
clipboardWindowHeader = "X-Reims-Clipboard-Generation"
|
||||
clipboardRequestHeader = "X-Reims-Clipboard-Request"
|
||||
clipboardRecheckHeader = "X-Reims-Clipboard-Recheck"
|
||||
)
|
||||
|
||||
type guestClipboardStamp struct {
|
||||
window uint64
|
||||
seq uint32
|
||||
hash string
|
||||
}
|
||||
|
||||
type guestClipboardDelivery struct {
|
||||
ticket string
|
||||
window uint64
|
||||
wanted guestClipboardStamp
|
||||
offered guestClipboardStamp
|
||||
applied guestClipboardStamp
|
||||
}
|
||||
|
||||
type guestClipboardOffer struct {
|
||||
ticket string
|
||||
window uint64
|
||||
}
|
||||
|
||||
// clipboardWindowVMLocked resolves an authenticated view of the active app
|
||||
// window. The caller holds s.mu for reading or writing.
|
||||
func (s *Server) clipboardWindowVMLocked(vm *registeredVM) *registeredVM {
|
||||
cur := s.vms[vm.key]
|
||||
if cur == nil || cur.token != vm.token || cur.windowReportGen == 0 {
|
||||
return nil
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
func (s *Server) windowClipboardActive(vm *registeredVM) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.clipboardWindowVMLocked(vm) != nil
|
||||
}
|
||||
|
||||
// offerGuestClipboard marks only snapshots currently requested by a paste.
|
||||
// For unchanged content, the caller asks the agent to recheck its own
|
||||
// pasteboard without overwriting a newer local selection.
|
||||
func (s *Server) offerGuestClipboard(vm *registeredVM, seq uint32, hash string, recheck, expired bool) guestClipboardOffer {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
cur := s.clipboardWindowVMLocked(vm)
|
||||
if cur == nil || !s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest() {
|
||||
return guestClipboardOffer{}
|
||||
}
|
||||
stamp := guestClipboardStamp{window: cur.windowReportGen, seq: seq, hash: hash}
|
||||
delivery := &cur.clipboardDelivery
|
||||
if delivery.ticket == "" || delivery.wanted != stamp || delivery.applied == stamp ||
|
||||
(recheck && delivery.offered == stamp && !expired) {
|
||||
return guestClipboardOffer{}
|
||||
}
|
||||
delivery.offered = stamp
|
||||
return guestClipboardOffer{ticket: delivery.ticket, window: delivery.window}
|
||||
}
|
||||
|
||||
func (s *Server) handleClipboardApplied(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)
|
||||
window, windowErr := strconv.ParseUint(r.Header.Get(clipboardWindowHeader), 10, 64)
|
||||
hash := r.Header.Get("X-Clip-Hash")
|
||||
ticket := r.Header.Get(clipboardRequestHeader)
|
||||
if seqErr != nil || windowErr != nil || window == 0 || len(hash) != 64 || ticket == "" || len(ticket) > 128 {
|
||||
http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, err := hex.DecodeString(hash); err != nil {
|
||||
http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
stamp := guestClipboardStamp{window: window, seq: uint32(seq), hash: hash}
|
||||
hostSeq := s.clip.SequenceNumber()
|
||||
s.mu.Lock()
|
||||
cur := s.clipboardWindowVMLocked(vm)
|
||||
accepted := cur != nil && cur.windowReportGen == stamp.window && hostSeq == stamp.seq && cur.clipboardDelivery.ticket == ticket &&
|
||||
cur.clipboardDelivery.wanted == stamp && cur.clipboardDelivery.offered == stamp &&
|
||||
s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest()
|
||||
changed := accepted && cur.clipboardDelivery.applied != stamp
|
||||
if changed {
|
||||
cur.clipboardDelivery.applied = stamp
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !accepted {
|
||||
http.Error(w, "clipboard acknowledgment expired", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
s.broadcastClipChange()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) beginGuestClipboardWait(vmKey string) (guestClipboardOffer, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
vm := s.vms[vmKey]
|
||||
if vm == nil || vm.windowReportGen == 0 || !s.effectiveClipboardPolicyLocked(vmKey).allowsHostToGuest() {
|
||||
return guestClipboardOffer{}, nil
|
||||
}
|
||||
if vm.clipboardDelivery.ticket != "" && vm.clipboardDelivery.window == vm.windowReportGen {
|
||||
return guestClipboardOffer{}, errors.New("guest clipboard paste is already pending")
|
||||
}
|
||||
request := guestClipboardOffer{ticket: rand.Text(), window: vm.windowReportGen}
|
||||
vm.clipboardDelivery = guestClipboardDelivery{ticket: request.ticket, window: request.window}
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (s *Server) endGuestClipboardWait(vmKey string, request guestClipboardOffer) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if vm := s.vms[vmKey]; vm != nil && vm.clipboardDelivery.ticket == request.ticket {
|
||||
vm.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForGuestClipboard waits until the active app window's guest agent has
|
||||
// applied the newest eligible host clipboard snapshot. Disabled or ineligible
|
||||
// clipboard data leaves the guest's ordinary Paste behavior available.
|
||||
func (s *Server) WaitForGuestClipboard(ctx context.Context, vmKey string) error {
|
||||
vmKey = normalizeVMRegistryKey(vmKey)
|
||||
request, err := s.beginGuestClipboardWait(vmKey)
|
||||
if err != nil || request.ticket == "" {
|
||||
return err
|
||||
}
|
||||
defer s.endGuestClipboardWait(vmKey, request)
|
||||
// The watcher also wakes the wait, but an independent sample covers a
|
||||
// concurrent change during server startup or registration teardown.
|
||||
tick := time.NewTicker(150 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
changed := s.clipNotifyChan()
|
||||
policy := s.EffectiveClipboardPolicy(vmKey)
|
||||
if !policy.allowsHostToGuest() {
|
||||
return nil
|
||||
}
|
||||
payload, seq, hash, err := s.readClipboardForSync(policy.SyncImages, policy.SyncFiles)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, hash = s.clipboardForGuest(vmKey, payload, seq, hash, policy.SyncFiles, policy.SyncImages, policy.MaxImageBytes)
|
||||
stamp := guestClipboardStamp{window: request.window, seq: seq, hash: hash}
|
||||
if seq != s.clip.SequenceNumber() {
|
||||
continue
|
||||
}
|
||||
s.mu.Lock()
|
||||
vm := s.vms[vmKey]
|
||||
active := vm != nil && vm.windowReportGen == request.window && vm.clipboardDelivery.ticket == request.ticket
|
||||
currentPolicy := s.effectiveClipboardPolicyLocked(vmKey)
|
||||
var pendingChanged, applied bool
|
||||
if active && currentPolicy == policy {
|
||||
delivery := &vm.clipboardDelivery
|
||||
if pendingChanged = delivery.wanted != stamp; pendingChanged {
|
||||
delivery.wanted = stamp
|
||||
delivery.offered = guestClipboardStamp{}
|
||||
delivery.applied = guestClipboardStamp{}
|
||||
}
|
||||
applied = delivery.applied == stamp
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !active {
|
||||
return errors.New("guest clipboard window is no longer active")
|
||||
}
|
||||
if currentPolicy != policy || seq != s.clip.SequenceNumber() {
|
||||
continue
|
||||
}
|
||||
if applied || hash == "" {
|
||||
return ctx.Err()
|
||||
}
|
||||
if pendingChanged {
|
||||
s.broadcastClipChange()
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-changed:
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareGuestClipboardPaste holds the per-VM text injection lock from
|
||||
// readiness check through actual Paste dispatch. Always call the returned
|
||||
// release function on success.
|
||||
func (s *Server) PrepareGuestClipboardPaste(ctx context.Context, vmKey string) (release func(), err error) {
|
||||
vmKey = normalizeVMRegistryKey(vmKey)
|
||||
s.mu.RLock()
|
||||
vm := s.vms[vmKey]
|
||||
var token string
|
||||
if vm != nil {
|
||||
token = vm.token
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if vm == nil {
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
tick := time.NewTicker(25 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for !vm.injectMu.TryLock() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
release = sync.OnceFunc(vm.injectMu.Unlock)
|
||||
s.mu.RLock()
|
||||
current := s.vms[vmKey] == vm && vm.token == token
|
||||
s.mu.RUnlock()
|
||||
if !current {
|
||||
release()
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
release()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.WaitForGuestClipboard(ctx, vmKey); err != nil {
|
||||
release()
|
||||
return nil, err
|
||||
}
|
||||
s.mu.RLock()
|
||||
current = s.vms[vmKey] == vm && vm.token == token
|
||||
s.mu.RUnlock()
|
||||
if !current {
|
||||
release()
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
return release, nil
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const clipboardReadyTestVM = "clipboard-test"
|
||||
|
||||
func clipboardOffer(t *testing.T, srv *Server, query string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/clipboard"+query, nil)
|
||||
req.Header.Set("Authorization", "Bearer clipboard-test-token")
|
||||
req.Header.Set(clipboardAckHeader, "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleClipboard(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func sendClipboardApplied(srv *Server, offer http.Header) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, clipboardAppliedPath, nil)
|
||||
req.Header.Set("Authorization", "Bearer clipboard-test-token")
|
||||
for _, key := range []string{"X-Clip-Seq", "X-Clip-Hash", clipboardWindowHeader, clipboardRequestHeader} {
|
||||
req.Header.Set(key, offer.Get(key))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleClipboardApplied(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func startGuestClipboardWait(t *testing.T, srv *Server) <-chan error {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
request := srv.clipNotifyChan()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM) }()
|
||||
select {
|
||||
case <-request:
|
||||
case err := <-done:
|
||||
t.Fatalf("paste did not request a clipboard snapshot: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("paste did not request a clipboard snapshot")
|
||||
}
|
||||
return done
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardWaitRequiresLatestAppliedOffer(t *testing.T) {
|
||||
clip := &memClipboard{kind: ClipText, data: []byte("first"), seq: 7}
|
||||
srv := newClipboardTestServer(clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
old := clipboardOffer(t, srv, "")
|
||||
if old.Code != http.StatusOK || old.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("guest clipboard offer: %d %v", old.Code, old.Header())
|
||||
}
|
||||
|
||||
request := srv.clipNotifyChan()
|
||||
if err := clip.WriteText("newest"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, old.Header()); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("stale acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
select {
|
||||
case <-request:
|
||||
case err := <-done:
|
||||
t.Fatalf("paste did not request the newest clipboard: %v", err)
|
||||
}
|
||||
latest := clipboardOffer(t, srv, "")
|
||||
if latest.Body.String() != "newest" || latest.Header().Get("X-Clip-Seq") != "8" || latest.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("latest clipboard offer: %q %v", latest.Body.String(), latest.Header())
|
||||
}
|
||||
forged := latest.Header().Clone()
|
||||
forged.Set("X-Clip-Hash", strings.Repeat("0", 64))
|
||||
if resp := sendClipboardApplied(srv, forged); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("unoffered acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("clipboard wait returned with no applied offer: %v", err)
|
||||
default:
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, latest.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("current acknowledgment got %d, want 204", resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardRechecksSynchronizedValueForEveryPaste(t *testing.T) {
|
||||
srv := newClipboardTestServer(&memClipboard{kind: ClipText, data: []byte("unchanged"), seq: 7})
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
first := clipboardOffer(t, srv, "")
|
||||
if first.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("ordinary synchronization should not ask for an acknowledgment: %v", first.Header())
|
||||
}
|
||||
query := "?since=" + url.QueryEscape(first.Header().Get("X-Clip-Hash")) + "&since_seq=7"
|
||||
if same := clipboardOffer(t, srv, query); same.Code != http.StatusNotModified || same.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("no pending paste should return 304: %d %v", same.Code, same.Header())
|
||||
}
|
||||
var previous http.Header
|
||||
for _, reopen := range []bool{false, false, true} {
|
||||
if reopen {
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, false)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
if untouched := clipboardOffer(t, srv, query); untouched.Code != http.StatusNotModified {
|
||||
t.Fatalf("reopening a window should not reoffer an unchanged clipboard: %d", untouched.Code)
|
||||
}
|
||||
}
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
current := clipboardOffer(t, srv, query)
|
||||
if current.Code != http.StatusOK || current.Header().Get(clipboardAckHeader) != "1" ||
|
||||
current.Header().Get(clipboardRecheckHeader) != "1" || current.Header().Get(clipboardRequestHeader) == "" {
|
||||
t.Fatalf("pending paste should request a non-writing recheck: %d %v", current.Code, current.Header())
|
||||
}
|
||||
if previous != nil {
|
||||
if current.Header().Get(clipboardRequestHeader) == previous.Get(clipboardRequestHeader) {
|
||||
t.Fatal("per-paste request ID was reused")
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, previous); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("previous paste acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, current.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("current paste acknowledgment got %d, want 204", resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous = current.Header()
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardWaitSkipsUnavailableHostPayload(t *testing.T) {
|
||||
clip := &memClipboard{seq: 7}
|
||||
srv := newClipboardTestServer(clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
||||
defer cancel()
|
||||
if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil {
|
||||
t.Fatalf("no host content should not delay Paste: %v", err)
|
||||
}
|
||||
if err := clip.WriteText("kept on host"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy := DefaultClipboardPolicy()
|
||||
policy.Direction = ClipboardGuestToHost
|
||||
srv.SetGlobalClipboardPolicy(policy)
|
||||
if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil {
|
||||
t.Fatalf("guest-to-host policy should not delay Paste: %v", err)
|
||||
}
|
||||
if denied := clipboardOffer(t, srv, ""); denied.Code != http.StatusNoContent || denied.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("guest-to-host policy offered host data: %d %v", denied.Code, denied.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardAcknowledgesOrdinaryFormats(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "clip.txt")
|
||||
if err := os.WriteFile(path, []byte("file"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
clip Clipboard
|
||||
}{
|
||||
{"png", &memClipboard{kind: ClipPNG, data: makeSamplePNG(t, 1, 2, 3), seq: 23}},
|
||||
{"files", &fileClipboardSnapshot{
|
||||
memClipboard: &memClipboard{seq: 23},
|
||||
payload: ClipPayload{Kind: ClipFiles, Files: []string{path}},
|
||||
}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newClipboardTestServer(tt.clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)]
|
||||
vm.clipOverride = &pendingClipOverride{text: "temporary", hash: strings.Repeat("a", 64), servedCh: make(chan struct{})}
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
if temporary := clipboardOffer(t, srv, "?accept=image,files"); temporary.Body.String() != "temporary" ||
|
||||
temporary.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("temporary text should not register an acknowledgment: %d %v", temporary.Code, temporary.Header())
|
||||
}
|
||||
ordinary := clipboardOffer(t, srv, "?accept=image,files")
|
||||
if ordinary.Code != http.StatusOK || ordinary.Header().Get("X-Clip-Kind") != tt.name ||
|
||||
ordinary.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("ordinary %s was not offered for acknowledgment: %d %v", tt.name, ordinary.Code, ordinary.Header())
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, ordinary.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("%s acknowledgment got %d, want 204", tt.name, resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("paste readiness after applying %s: %v", tt.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardPrepareHoldsInjectionLockUntilRelease(t *testing.T) {
|
||||
srv := newClipboardTestServer(&memClipboard{seq: 7})
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)]
|
||||
vm.injectMu.Lock()
|
||||
blocked, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
|
||||
_, err := srv.PrepareGuestClipboardPaste(blocked, clipboardReadyTestVM)
|
||||
cancel()
|
||||
vm.injectMu.Unlock()
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("paste should be cancellable while text injection owns the clipboard: %v", err)
|
||||
}
|
||||
release, err := srv.PrepareGuestClipboardPaste(t.Context(), clipboardReadyTestVM)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer release()
|
||||
if vm.injectMu.TryLock() {
|
||||
vm.injectMu.Unlock()
|
||||
t.Fatal("paste released the text injection lock before dispatch")
|
||||
}
|
||||
release()
|
||||
if !vm.injectMu.TryLock() {
|
||||
t.Fatal("paste release did not unlock the clipboard")
|
||||
}
|
||||
vm.injectMu.Unlock()
|
||||
}
|
||||
@@ -22,8 +22,9 @@ const ClipboardReliabilityAgentVersion = 14
|
||||
const ClipboardFilesAgentVersion = 15
|
||||
const BidirectionalClipboardFilesAgentVersion = 16
|
||||
const WindowReportAgentVersion = 17
|
||||
const PasteReadyAgentVersion = 18
|
||||
|
||||
const CurrentAgentVersion = WindowReportAgentVersion
|
||||
const CurrentAgentVersion = PasteReadyAgentVersion
|
||||
|
||||
type SharedFolderConfig struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -174,6 +174,15 @@ keymap_active="false"
|
||||
keymap_applied="false"
|
||||
` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + `
|
||||
|
||||
stop_window_reporter() {
|
||||
if [ -n "${WINDOW_REPORTER_PID:-}" ]; then
|
||||
kill "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
wait "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
fi
|
||||
WINDOW_REPORTER_PID=""
|
||||
window_report_generation=""
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ "$keymap_applied" = "true" ]; then
|
||||
apply_hidutil_carrier disable
|
||||
@@ -496,15 +505,6 @@ EOF
|
||||
fi
|
||||
}
|
||||
|
||||
stop_window_reporter() {
|
||||
if [ -n "${WINDOW_REPORTER_PID:-}" ]; then
|
||||
kill "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
wait "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
fi
|
||||
WINDOW_REPORTER_PID=""
|
||||
window_report_generation=""
|
||||
}
|
||||
|
||||
sync_window_reporter() {
|
||||
requested_generation=$(printf '%s\n' "$1" | sed -n 's/.*"window_report_generation"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p')
|
||||
case "$requested_generation" in
|
||||
@@ -869,7 +869,11 @@ clip_header() {
|
||||
case "$1:$hdr_key" in
|
||||
x-clip-hash:[Xx]-[Cc][Ll][Ii][Pp]-[Hh][Aa][Ss][Hh]|\
|
||||
x-clip-kind:[Xx]-[Cc][Ll][Ii][Pp]-[Kk][Ii][Nn][Dd]|\
|
||||
x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq])
|
||||
x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq]|\
|
||||
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])
|
||||
hdr_val=${hdr_val#"${hdr_val%%[![:space:]]*}"}
|
||||
hdr_val=${hdr_val%"${hdr_val##*[![:space:]]}"}
|
||||
printf '%s\n' "$hdr_val"
|
||||
@@ -879,6 +883,30 @@ clip_header() {
|
||||
done < "$hdr_out"
|
||||
}
|
||||
|
||||
acknowledge_clipboard() {
|
||||
[ "$(clip_header x-reims-clipboard-ack)" = 1 ] &&
|
||||
[ "$read_ok" = 1 ] && [ -n "$read_cc" ] && ! clipboard_poll_interrupted || return 0
|
||||
if [ "$1" != 1 ]; then
|
||||
# macOS can re-encode PNGs, and a file offer's hash identifies the
|
||||
# Windows manifest, so only text has the same wire and read-back hash.
|
||||
[ "$read_kind" = "$new_kind" ] || return 0
|
||||
[ "$new_kind" != text ] || [ "$read_hash" = "$new_hash" ] || return 0
|
||||
fi
|
||||
case "$new_seq" in ''|*[!0-9]*) return 0 ;; esac
|
||||
case "$new_hash" in ''|*[!0-9a-f]*) return 0 ;; esac
|
||||
ack_generation=$(clip_header x-reims-clipboard-generation)
|
||||
case "$ack_generation" in ''|0*|*[!0-9]*) return 0 ;; esac
|
||||
ack_request=$(clip_header x-reims-clipboard-request)
|
||||
case "$ack_request" in ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]*) return 0 ;; esac
|
||||
[ "${#new_seq}" -le 10 ] && [ "${#new_hash}" -eq 64 ] &&
|
||||
[ "${#ack_generation}" -le 20 ] && [ "${#ack_request}" -eq 26 ] || return 0
|
||||
curl -fsS -m 1 -X POST -H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
-H "X-Clip-Seq: $new_seq" -H "X-Clip-Hash: $new_hash" \
|
||||
-H "X-Reims-Clipboard-Generation: $ack_generation" \
|
||||
-H "X-Reims-Clipboard-Request: $ack_request" \
|
||||
"$REIMS_HOST_URL/v1/clipboard/applied" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
last_local_hash=""
|
||||
synced_local_cc=""
|
||||
synced_local_kind=""
|
||||
@@ -1119,7 +1147,7 @@ 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 "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" -H "X-Reims-Clipboard-Ack: 1" \
|
||||
"$clip_url" 2>/dev/null) || code=000
|
||||
case "$code" in
|
||||
200)
|
||||
@@ -1166,6 +1194,13 @@ sync_clipboard() {
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
if [ "$(clip_header x-reims-clipboard-recheck)" = 1 ]; then
|
||||
# A paste of an unchanged host snapshot uses the current
|
||||
# ordinary macOS clipboard. A newer guest copy keeps ownership.
|
||||
release_clip_lock
|
||||
acknowledge_clipboard 1
|
||||
return 0
|
||||
fi
|
||||
if [ "$new_hash" != "$post_get_hash" ]; then
|
||||
if [ "$new_kind" = files ]; then
|
||||
delivery=0
|
||||
@@ -1226,6 +1261,7 @@ sync_clipboard() {
|
||||
fi
|
||||
last_server_hash="$new_hash"
|
||||
last_server_seq="$new_seq"
|
||||
acknowledge_clipboard 0
|
||||
;;
|
||||
204|304)
|
||||
if [ -z "$last_local_hash" ]; then
|
||||
|
||||
@@ -276,6 +276,7 @@ type registeredVM struct {
|
||||
lastSeen time.Time
|
||||
windowReportGen uint64
|
||||
windowReport windowReport
|
||||
clipboardDelivery guestClipboardDelivery
|
||||
|
||||
dropShares *dropShareStore
|
||||
dropDAVHandler *webdav.Handler
|
||||
@@ -400,6 +401,7 @@ func (s *Server) Start(preferredPort int) (int, error) {
|
||||
mux.HandleFunc("/v1/status", s.handleStatus)
|
||||
mux.HandleFunc("/v1/dns-query", s.handleDNSQuery)
|
||||
mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard"))
|
||||
mux.HandleFunc(clipboardAppliedPath, s.handleClipboardApplied)
|
||||
mux.HandleFunc("/v1/text-input", s.handleTextInput)
|
||||
mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck)
|
||||
mux.HandleFunc("/v1/drop-events", s.handleDropEvents)
|
||||
@@ -509,6 +511,7 @@ func (s *Server) Close(ctx context.Context) error {
|
||||
for _, vm := range s.vms {
|
||||
vm.windowReportGen = 0
|
||||
vm.windowReport = windowReport{}
|
||||
vm.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.cleanupClipFiles()
|
||||
@@ -585,6 +588,7 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
s.clearVMClipFilesLocked(key)
|
||||
cur.windowReportGen = 0
|
||||
cur.windowReport = windowReport{}
|
||||
cur.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders))
|
||||
for _, folder := range cfg.ResolvedFolders {
|
||||
@@ -1157,7 +1161,7 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
|
||||
s.serveClipboardArchive(w, r, vm)
|
||||
return
|
||||
}
|
||||
s.getClipboard(w, r, vm.key)
|
||||
s.getClipboard(w, r, vm)
|
||||
case http.MethodPost, http.MethodPut:
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if mediaType == "application/x-tar" {
|
||||
@@ -1265,12 +1269,15 @@ func (s *Server) clipboardForGuest(vmKey string, payload ClipPayload, seq uint32
|
||||
return ClipPayload{}, ""
|
||||
}
|
||||
|
||||
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) {
|
||||
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vm *registeredVM) {
|
||||
vmKey := vm.key
|
||||
waitSec, err := strconv.Atoi(r.URL.Query().Get("wait"))
|
||||
if err != nil {
|
||||
waitSec = 0
|
||||
}
|
||||
deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second)
|
||||
wait := time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second
|
||||
ackCapable := r.Header.Get(clipboardAckHeader) == "1"
|
||||
start := time.Now()
|
||||
wantsImage := acceptsClipFormat(r.URL.Query().Get("accept"), "image") ||
|
||||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
|
||||
wantsFiles := acceptsClipFormat(r.URL.Query().Get("accept"), "files")
|
||||
@@ -1280,6 +1287,10 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
|
||||
for {
|
||||
ch := s.clipNotifyChan()
|
||||
deadline := start.Add(wait)
|
||||
if ackCapable && s.windowClipboardActive(vm) {
|
||||
deadline = start.Add(min(wait, 250*time.Millisecond))
|
||||
}
|
||||
policy := s.EffectiveClipboardPolicy(vmKey)
|
||||
if !policy.Enabled {
|
||||
writeFeatureDisabled(w, "clipboard")
|
||||
@@ -1309,7 +1320,20 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantFiles, wantImage, policy.MaxImageBytes)
|
||||
if h != "" {
|
||||
unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq))
|
||||
if !unchanged || time.Until(deadline) <= 0 {
|
||||
expired := !time.Now().Before(deadline)
|
||||
if ackCapable {
|
||||
recheck := unchanged && hasSinceSeq
|
||||
if offer := s.offerGuestClipboard(vm, seq, h, recheck, expired); offer.ticket != "" {
|
||||
w.Header().Set(clipboardAckHeader, "1")
|
||||
w.Header().Set(clipboardWindowHeader, strconv.FormatUint(offer.window, 10))
|
||||
w.Header().Set(clipboardRequestHeader, offer.ticket)
|
||||
if recheck {
|
||||
w.Header().Set(clipboardRecheckHeader, "1")
|
||||
}
|
||||
unchanged = false
|
||||
}
|
||||
}
|
||||
if !unchanged || expired {
|
||||
setClipboardSeq(w, seq)
|
||||
w.Header().Set("X-Clip-Hash", h)
|
||||
w.Header().Set("X-Clip-Kind", string(payload.Kind))
|
||||
|
||||
@@ -591,6 +591,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"tray.menu.stop": "关机(&D)",
|
||||
"tray.menu.suspend": "挂起(&P)",
|
||||
"tray.menu.toggle_fullscreen": "切换全屏",
|
||||
"tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次",
|
||||
"tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态",
|
||||
"tray.notify.focus_fail": "找不到 {name} 的窗口",
|
||||
"tray.notify.force_stop_fail": "无法强制关机 {name}",
|
||||
@@ -1268,6 +1269,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"tray.menu.stop": "Shut &Down",
|
||||
"tray.menu.suspend": "Sus&pend",
|
||||
"tray.menu.toggle_fullscreen": "Toggle full screen",
|
||||
"tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again",
|
||||
"tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}",
|
||||
"tray.notify.focus_fail": "Couldn't find the window of {name}",
|
||||
"tray.notify.force_stop_fail": "Couldn't force shut down {name}",
|
||||
|
||||
@@ -318,6 +318,7 @@
|
||||
"err.app_window_pointer": "Enable the USB tablet for {name} and try again",
|
||||
"err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again",
|
||||
"err.app_window_capture": "Could not capture the app window in {name}",
|
||||
"tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again",
|
||||
"err.vm_window_not_found": "Couldn’t find the display window for {name}",
|
||||
"err.fullscreen_failed": "Couldn’t toggle full screen for {name}",
|
||||
"err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake",
|
||||
|
||||
@@ -318,6 +318,7 @@
|
||||
"err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口",
|
||||
"err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试",
|
||||
"err.app_window_capture": "无法获取 {name} 的应用画面",
|
||||
"tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次",
|
||||
"err.vm_window_not_found": "找不到 {name} 的显示窗口",
|
||||
"err.fullscreen_failed": "无法切换 {name} 的全屏状态",
|
||||
"err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
|
||||
|
||||
Reference in new issue
Block a user