fix(guesttools,app): stabilize host-to-guest clipboard sync and suspend resume

This commit is contained in:
棠渚听潮 committed 2026-12-02 02:18:04 +08:00
1 parent 08b3089569
commit f8515656fb
15 files changed
+1205 -140

No files matched your search

@@ -0,0 +1,7 @@
{
"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`."
}
+1 -1
View File
@@ -973,7 +973,7 @@ export const VMPage: React.FC<Props> = ({
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 10
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 11
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
+75 -2
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
@@ -100,10 +101,17 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
defer end()
var extraEnv []string
var newRegistration *guesttools.Server
var newRegGen uint64
var epoch uint64
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") {
extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory, a.vmDeleteEpoch(ref.Name))...)
epoch = a.vmDeleteEpoch(ref.Name)
active, rerr := rt.ResolveActive(&cfgCopy)
unicodeInput := rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input")
extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput)
if len(extraEnv) > 0 {
a.syncKeymapRules()
}
}
@@ -111,6 +119,13 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
if err != nil {
if newRegistration != nil && newRegGen > 0 {
unlock := a.lockGuestToolsVM(ref.Name)
if a.vmDeleteEpoch(ref.Name) == epoch {
newRegistration.UnregisterVMIfGen(key, newRegGen)
}
unlock()
}
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
return err
}
@@ -129,6 +144,64 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
return nil
}
func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeInput bool) ([]string, *guesttools.Server, uint64) {
ref := vm.Ref()
unlock := a.lockGuestToolsVM(ref.Name)
defer unlock()
if a.vmDeleteEpoch(ref.Name) != epoch {
return nil, nil, 0
}
cfg, configured, err := guesttools.ReadVMConfigStrict(vm.Directory)
if err != nil {
a.emitLog(ref.Name, "Warning: could not load Guest Tools config: "+err.Error())
return nil, nil, 0
}
if !configured {
return nil, nil, 0
}
if err := requireGuestToolsVM(vm.Directory); err != nil {
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
return nil, nil, 0
}
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return nil, nil, 0
}
existing := srv.HasVM(ref.Key())
oldName := cfg.VMName
cfg.VMName = ref.Name
oldDir := cfg.SharedDir
if unicodeInput || cfg.SharedDir == "" {
cfg.SharedDir = a.vmSharedDir(ref.Name)
}
if cfg.Port != port || (unicodeInput && (oldName != cfg.VMName || oldDir != cfg.SharedDir)) {
cfg.Port = port
if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil {
a.emitLog(ref.Name, "Warning: could not save Guest Tools config: "+err.Error())
return nil, nil, 0
}
}
if err := a.registerGuestToolsConfig(srv, vm.Directory, cfg); err != nil {
a.emitLog(ref.Name, "Warning: could not register Guest Tools config: "+err.Error())
return nil, nil, 0
}
var newRegistration *guesttools.Server
var newRegGen uint64
if !existing {
newRegistration = srv
newRegGen = srv.RegistrationGen(ref.Key())
}
if !unicodeInput {
return nil, newRegistration, newRegGen
}
srv.SetKeymapCarrier(ref.Name, false)
return []string{
fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port),
"REIMS_GO_INPUT_TOKEN=" + cfg.Token,
}, newRegistration, newRegGen
}
// DiscardSuspend deletes a stopped VM's saved execution state.
func (a *App) DiscardSuspend(name string) error {
return a.DiscardSuspendWithDriver("", name)
+178
View File
@@ -1,15 +1,193 @@
package app
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
type resumeGuestToolsDriver struct {
*appSecondDriver
driver.SuspendDriver
onResume func(driver.ResumeRequest)
resumeErr error
}
func (d *resumeGuestToolsDriver) Resume(_ context.Context, req driver.ResumeRequest) (driver.StartResult, error) {
d.onResume(req)
return driver.StartResult{}, d.resumeErr
}
func TestResumeVMRegistersSavedGuestToolsWithoutUnicodeInput(t *testing.T) {
resumeErr := errors.New("resume failed")
for _, tc := range []struct {
name string
manifest string
unicodeInput bool
savedConfig bool
preRegistered bool
concurrentUpdate bool
resumeErr error
}{
{name: "runtime installed=true", manifest: `{"commit":"legacy"}`, savedConfig: true},
{name: "runtime installed=false", savedConfig: true},
{name: "failure rolls back new registration", savedConfig: true, resumeErr: resumeErr},
{name: "failure keeps preexisting registration", savedConfig: true, preRegistered: true, resumeErr: resumeErr},
{name: "failure keeps concurrent registration update", savedConfig: true, concurrentUpdate: true, resumeErr: resumeErr},
{name: "Unicode input failure rolls back new registration", savedConfig: true, unicodeInput: true, resumeErr: resumeErr,
manifest: `{"commit":"unicode","capabilities":["win32-unicode-input"]}`},
{name: "no saved config leaves bridge stopped", resumeErr: resumeErr},
{name: "Unicode input without saved config leaves bridge stopped", unicodeInput: true,
manifest: `{"commit":"unicode","capabilities":["win32-unicode-input"]}`, resumeErr: resumeErr},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
if tc.manifest != "" {
runtimeDir := filepath.Join(cfg.RuntimesDir(), "legacy")
if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte(tc.manifest), 0o600); err != nil {
t.Fatal(err)
}
active, err := rt.ResolveActive(cfg)
if err != nil || active.Manifest.HasCapability("win32-unicode-input") != tc.unicodeInput {
t.Fatalf("unexpected runtime capabilities: %+v, %v", active, err)
}
}
const name = "resume-guest-tools"
vmDir := t.TempDir()
t.Cleanup(func() { stopVMMonitor(name) })
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), nil, 0o600); err != nil {
t.Fatal(err)
}
var srv *guesttools.Server
var port int
var saved guesttools.VMConfig
if tc.savedConfig {
srv = guesttools.NewServer(nil)
var err error
port, err = srv.Start(-1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := srv.Close(ctx); err != nil {
t.Error(err)
}
})
saved, err = guesttools.LoadOrCreateVMConfig(vmDir, name, filepath.Join(cfg.SharedDir(), name), port)
if err != nil {
t.Fatal(err)
}
}
client := &http.Client{Timeout: 2 * time.Second}
ping := func(want int) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/v1/ping", port), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+saved.Token)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("Guest Tools ping status = %d, want %d", resp.StatusCode, want)
}
}
if tc.savedConfig {
ping(http.StatusUnauthorized)
if tc.preRegistered {
srv.RegisterVM(saved)
ping(http.StatusOK)
}
}
const driverID = driver.BuiltinReimsMacOSDriverID
drv := &resumeGuestToolsDriver{
appSecondDriver: &appSecondDriver{id: driverID, vms: []driver.VMInfo{
{Name: name, DriverID: driverID, Directory: vmDir, State: "suspended"},
}},
onResume: func(req driver.ResumeRequest) {
if tc.unicodeInput && tc.savedConfig {
if len(req.ExtraEnv) != 2 ||
req.ExtraEnv[0] != fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port) ||
req.ExtraEnv[1] != "REIMS_GO_INPUT_TOKEN="+saved.Token {
t.Error("missing Unicode input environment")
}
} else if len(req.ExtraEnv) != 0 {
t.Error("unexpected Unicode input environment")
}
if tc.savedConfig {
ping(http.StatusOK)
if tc.concurrentUpdate {
updated := saved
updated.PreventSleep = !updated.PreventSleep
srv.RegisterVM(updated)
}
}
},
resumeErr: tc.resumeErr,
}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.resume", Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
a := &App{
cfg: cfg, guestTools: srv, transitions: map[string]string{},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
}
t.Cleanup(func() {
if a.guestTools != nil && a.guestTools != srv {
if err := a.guestTools.Close(context.Background()); err != nil {
t.Error(err)
}
}
})
if err := a.ResumeVM(name); !errors.Is(err, tc.resumeErr) {
t.Fatalf("ResumeVM error = %v, want %v", err, tc.resumeErr)
}
if !tc.savedConfig {
if a.guestTools != nil {
t.Fatal("resuming a VM without Guest Tools config started a bridge")
}
} else if tc.resumeErr != nil && !tc.preRegistered && !tc.concurrentUpdate {
ping(http.StatusUnauthorized)
} else {
ping(http.StatusOK)
}
})
}
}
func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
suspendedDir := t.TempDir()
stoppedDir := t.TempDir()
+376 -49
View File
@@ -1,22 +1,28 @@
package guesttools
import (
"context"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
)
func TestGuestAgentClipboardScript(t *testing.T) {
sh, err := exec.LookPath("sh")
if err != nil {
sh = "C:/Program Files/Git/bin/sh.exe"
if _, err := os.Stat(sh); err != nil {
t.Skip("POSIX sh is unavailable")
if runtime.GOOS == "windows" {
const gitSH = "C:/Program Files/Git/bin/sh.exe"
if _, statErr := os.Stat(gitSH); statErr == nil {
sh, err = gitSH, nil
}
}
if err != nil {
t.Skip("POSIX sh is unavailable")
}
agent := string(GuestAgentScript())
start := strings.Index(agent, "read_local_clipboard() {")
end := strings.Index(agent, "sync_files() {")
@@ -29,24 +35,56 @@ func TestGuestAgentClipboardScript(t *testing.T) {
if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) {
t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u")
}
textInput := scriptSection(t, agent, "text_input_loop() {", "\ntext_input_loop &")
_, mainLoop, _ := strings.Cut(agent, "\ntext_input_loop &")
for _, name := range []string{
"failed_png", "failed_text", "reencoded_png", "guest_changes_during_get",
"conflict", "conflict_skipped_host", "oversized", "disabled_upload", "post_error",
"guest_only_after_switch", "cold_guest_only", "cold_304", "empty_text_and_png_fallback",
for _, group := range []struct {
name string
cases []string
}{
{"sync_basic", []string{
"failed_png", "failed_text", "missing_hash", "reencoded_png",
"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",
}},
{"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",
}},
} {
t.Run(name, func(t *testing.T) {
t.Run(group.name, func(t *testing.T) {
t.Parallel()
lockShellFixture(t)
tmp := t.TempDir()
script := filepath.Join(tmp, "clipboard-test.sh")
code := "set -eu\n" + agent[start:end] + clipboardShellFixture
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" {
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"
for _, name := range group.cases {
if err := os.Mkdir(filepath.Join(tmp, name), 0o700); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(script, []byte(code), 0o600); err != nil {
t.Fatal(err)
}
cmd := exec.Command(sh, script, name)
ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, sh, append([]string{script}, group.cases...)...)
cmd.Dir = tmp
if out, err := cmd.CombinedOutput(); err != nil {
if ctx.Err() != nil {
t.Fatalf("clipboard script: %v\n%s", ctx.Err(), out)
}
t.Fatalf("clipboard script: %v\n%s", err, out)
}
})
@@ -54,13 +92,15 @@ func TestGuestAgentClipboardScript(t *testing.T) {
}
const clipboardShellFixture = `
PATH="/usr/bin:/bin:$PATH"
TMP_DIR=.
INJECT_LOCK=./injecting
CLIP_LOCK=./clip.lock
cur_pid=$$
REIMS_HOST_URL=http://stub
REIMS_TOKEN=token
printf A > local_value
: > calls
: > copies
local_info="Unicode text"
flags=""
get_code=200
@@ -73,18 +113,37 @@ post_hash=C
post_seq=9
check_post_base=0
hash_file() { cat "$1"; }
hash_png_file() { printf 'png:'; cat "$1"; }
pbpaste() { cat local_value; }
date() { [ "$1" = +%s ] && printf '%s\n' "$now"; }
read_file() {
line=
while IFS= read -r line; do
printf '%s\n' "$line"
done < "$1"
printf '%s' "$line"
}
hash_file() { IFS= read -r value < "$1" || :; printf '%s' "$value"; }
hash_png_file() { printf 'png:'; hash_file "$1"; }
pbpaste() { hash_file local_value; [ "$flags" != failed_pbpaste ]; }
pbcopy() {
[ "$flags" != fail ] || return 1
cat > local_value
[ "$flags" != fail ] && [ "$flags" != input_failed ] || return 1
if [ "$flags" = input_exits_with_lock ]; then
exit 7
fi
IFS= read -r value || :
printf '%s' "$value" > local_value
rm -f reencoded
printf 'text\n' >> copies
}
osascript() {
case "$2" in
'clipboard info')
[ "$flags" != unreadable_clipboard ] || return 1
if [ -f reencoded ]; then
printf 'PNGf\n'
elif [ "$flags" = input_restores_tiff ] && [ -s copies ]; then
printf 'Unicode text\n'
elif [ -s local_value ] && [ "$local_info" = input ]; then
printf 'Unicode text\n'
else
printf '%s\n' "$local_info"
fi
@@ -93,19 +152,23 @@ osascript() {
case "$6" in
*PNGf*)
[ -f reencoded ] || return 1
cat local_value > ./clip_in
hash_file local_value > "$out_file"
;;
*TIFF*) printf 'tiff' > ./clip_in.tiff ;;
*TIFF*) printf 'tiff' > "$tiff_tmp" ;;
esac
;;
'set the clipboard'*)
[ "$flags" != fail ] || return 1
printf 'B-reencoded' > local_value
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 ;;
*) printf 'B-reencoded' > local_value ;;
esac
: > reencoded
;;
esac
}
sips() { printf 'tiff-converted' > "$6"; }
sips() { : > sips_called; printf 'tiff-converted' > "$6"; }
curl() {
method=GET
headers=""
@@ -129,6 +192,34 @@ curl() {
esac
shift
done
case "$url" in
*/v1/config)
printf 'config\n' >> config_calls
if [ "$flags" = reenable ] && [ "$(read_file config_calls)" = config ]; then
printf '{"clipboard_enabled":false}'
else
printf '{"clipboard_enabled":true}'
fi
return
;;
*/v1/text-input\?wait=25)
printf 'X-Input-Id: 4\r\n' > "$headers"
printf injected > "$output"
: > input_polled
printf '200'
return
;;
*/v1/text-input/ack\?id=4)
[ -d "$CLIP_LOCK" ] || exit 1
inject_lock_active || exit 1
printf 'ack\n' >> calls
if [ "$flags" = input_preserves_new_copy ]; then
printf new > local_value
fi
return
;;
esac
[ ! -d "$CLIP_LOCK" ] || exit 1
if [ "$method" = POST ]; then
printf '%s %s\n' "$method" "$base" >> calls
if [ "$check_post_base" = 1 ] && [ "$get_code" != 204 ] && [ "$base" != "X-Clip-Base-Seq: $get_seq" ]; then
@@ -137,7 +228,7 @@ curl() {
return
fi
if [ "$post_code" = 200 ]; then
cat "$body" > host_value
hash_file "$body" > host_value
fi
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\n' "$post_hash" "$post_seq" > "$headers"
printf '%s' "$post_code"
@@ -147,8 +238,14 @@ curl() {
printf '%s' "$get_value" > "$output"
if [ "$flags" = guest_change ]; then
printf C > local_value
elif [ "$flags" = inject_during_get ]; then
date +%s > "$INJECT_LOCK"
printf injected > local_value
fi
printf '%s' "$get_code"
case "$flags:$url" in
repeat_after_switch:*'?since=B&wait=2&accept=image') printf 304 ;;
*) printf '%s' "$get_code" ;;
esac
fi
}
expect() {
@@ -158,19 +255,41 @@ expect() {
exit 1
fi
}
methods() { awk '{print $1}' calls | paste -sd ',' -; }
expect_call() {
while IFS= read -r line; do
case "$1:$line" in
-Fx:"$2"|-F:*"$2"*) return 0 ;;
esac
done < calls
printf 'missing call <%s>\n' "$2" >&2
cat calls >&2
exit 1
}
methods() {
separator=
while read -r method rest; do
printf '%s%s' "$separator" "$method"
separator=,
done < calls
}
case "$1" in
failed_png|failed_text)
failed_png|failed_text|missing_hash)
[ "$1" != failed_png ] || get_kind=png
last_local_hash=A
last_server_hash=A
last_server_seq=7
flags=fail
if [ "$1" = missing_hash ]; then
get_hash=""
else
flags=fail
fi
sleep() { expect "$1" 2; [ ! -d "$CLIP_LOCK" ]; printf 'backoff\n' >> sleeps; }
sync_clipboard
sync_clipboard
expect "$(methods)" GET,GET
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/7/A
expect "$(paste -sd ',' sleeps)" backoff,backoff
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" A/A/7/A
;;
reencoded_png)
get_kind=png
@@ -180,21 +299,24 @@ case "$1" in
get_code=304
sync_clipboard
expect "$(methods)" GET,GET
grep -F 'since=png:B&' calls
expect_call -F 'since=png:B&'
;;
guest_changes_during_get)
last_local_hash=A
last_server_hash=A
last_server_seq=7
guest_changes_during_get|cold_guest_changes_during_get)
if [ "$1" = guest_changes_during_get ]; then
last_local_hash=A
last_server_hash=A
last_server_seq=7
fi
previous_server_hash="$last_server_hash"
flags=guest_change
check_post_base=1
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/8/C
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" "A/$previous_server_hash/8/C"
flags=""
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)/$(cat host_value)" C/C/9/C/C
expect_call -Fx 'POST X-Clip-Base-Seq: 8'
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)/$(read_file host_value)" C/C/9/C/C
;;
conflict|conflict_skipped_host|oversized|disabled_upload|post_error)
last_local_hash=old
@@ -214,25 +336,25 @@ case "$1" in
esac
sync_clipboard
expect "$(methods)" POST,GET
grep -Fx 'POST X-Clip-Base-Seq: 7' calls
grep -F 'since=old-remote&' calls
expect_call -Fx 'POST X-Clip-Base-Seq: 7'
expect_call -F 'since=old-remote&'
case "$1" in
conflict_skipped_host)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/8/A
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" A/old-remote/8/A
sync_clipboard
expect "$(methods)" POST,GET,GET
expect "$(cat host_value)" host-image
expect "$(read_file host_value)" host-image
printf C > local_value
sync_clipboard
expect "$(methods)" POST,GET,GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" C/C/9/C
expect_call -Fx 'POST X-Clip-Base-Seq: 8'
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file host_value)" C/C/9/C
;;
disabled_upload)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/7/A
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" A/old-remote/7/A
;;
*)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" B/B/8/B
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" B/B/8/B
;;
esac
if [ "$1" = oversized ]; then
@@ -252,12 +374,27 @@ case "$1" in
printf C > local_value
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$(cat host_value)" C
expect_call -Fx 'POST X-Clip-Base-Seq: 8'
expect "$(read_file host_value)" C
sync_clipboard
expect "$(methods)" GET,POST,GET
expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/
;;
repeat_after_direction_switch)
sync_clipboard
get_code=204
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq" B/B/
printf C > local_value
post_code=204
get_code=200
get_seq=9
flags=repeat_after_switch
sync_clipboard
expect "$(methods)" GET,GET,POST,GET
expect "$(tail -n 1 calls)" 'GET http://stub/v1/clipboard?since=&wait=2&accept=image'
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" B/B/9/B
;;
cold_guest_only|cold_304)
get_code=204
expected_base="POST "
@@ -271,7 +408,7 @@ case "$1" in
printf C > local_value
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx "$expected_base" calls
expect_call -Fx "$expected_base"
expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/9
if [ "$1" = cold_guest_only ]; then
check_post_base=1
@@ -282,15 +419,205 @@ case "$1" in
printf D > local_value
sync_clipboard
expect "$(methods)" GET,POST,POST
grep -Fx 'POST X-Clip-Base-Seq: 9' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" D/D/11/D
expect_call -Fx 'POST X-Clip-Base-Seq: 9'
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file host_value)" D/D/11/D
fi
;;
empty_text_and_png_fallback)
local_info="Unicode text, PNGf, TIFF"
: > local_value
expect "$(read_local_clipboard ./clip_in)" png
expect "$(cat ./clip_in)" tiff-converted
expect "$(read_file ./clip_in)" tiff-converted
;;
repeat_host_copy)
sync_clipboard
get_seq=9
sync_clipboard
expect "$(read_file copies)" text
expect "$last_local_hash/$last_server_hash/$last_server_seq" B/B/9
expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image&since_seq=8'
get_seq=10
printf C > local_value
post_code=409
sync_clipboard
expect "$(methods)" GET,GET,POST,GET
expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image&since_seq=9'
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" B/B/10/B
;;
stale_lock)
printf '1\n' > "$INJECT_LOCK"
sync_clipboard
[ ! -f "$INJECT_LOCK" ]
expect "$(read_file local_value)" B
printf A > local_value
: > "$INJECT_LOCK"
sleep() { expect "$1" 1; }
sync_clipboard
expect "$(methods)" GET
[ -f "$INJECT_LOCK" ]
touch -t 200001010000 "$INJECT_LOCK"
post_code=409
sync_clipboard
[ ! -f "$INJECT_LOCK" ]
expect "$(read_file local_value)" B
;;
cold_lock_during_get)
flags=inject_during_get
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq" A//
rm -f "$INJECT_LOCK"
flags=""
printf C > local_value
sync_clipboard
expect "$(methods)" GET,POST
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file host_value)" C/C/9/C
;;
lock_during_get)
last_server_hash=A
last_server_seq=7
last_local_hash=A
flags=inject_during_get
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" A/A/7/injected
expect "$(methods)" GET
[ ! -s copies ]
;;
live_lock)
(
cur_pid=$(sh -c 'echo $PPID')
acquire_clip_lock
printf '1\n' > "$CLIP_LOCK/at"
printf '%s:1\n' "$cur_pid" > "$INJECT_LOCK"
: > ready
waits=0
while [ ! -f checked ] && [ "$waits" -lt 250 ]; do
sleep 0.02
waits=$((waits + 1))
done
release_clip_lock
) &
holder=$!
trap 'kill "$holder" 2>/dev/null || true; wait "$holder" 2>/dev/null || true' EXIT
waits=0
while [ ! -f ready ] && [ "$waits" -lt 250 ]; do
sleep 0.02
waits=$((waits + 1))
done
[ -f ready ]
[ "$(read_file "$CLIP_LOCK/pid")" != "$$" ]
inject_lock_active
sleep() { expect "$1" 1; }
sync_clipboard
[ -d "$CLIP_LOCK" ]
[ -f "$INJECT_LOCK" ]
[ ! -s calls ]
: > checked
wait "$holder"
trap - EXIT
if inject_lock_active; then exit 1; fi
[ ! -f "$INJECT_LOCK" ]
;;
dead_lock)
(cur_pid=$(sh -c 'echo $PPID'); acquire_clip_lock)
[ -d "$CLIP_LOCK" ]
dead_pid=$(read_file "$CLIP_LOCK/pid")
if kill -0 "$dead_pid" 2>/dev/null; then exit 1; fi
mkdir "$CLIP_LOCK.reaping.$dead_pid"
sync_clipboard
expect "$(read_file local_value)" B
[ ! -d "$CLIP_LOCK" ]
[ ! -d "$CLIP_LOCK.reaping.$dead_pid" ]
;;
unreadable_clipboard|non_text_clipboard|empty_text_clipboard|failed_pbpaste)
flags="$1"
case "$1" in
non_text_clipboard) local_info="picture" ;;
empty_text_clipboard) : > local_value ;;
esac
last_local_hash=previous
get_code=304
sync_clipboard
expect "$(read_local_clipboard ./clip_in)" empty
expect "$(methods)" GET
[ ! -f host_value ]
;;
clipboard_worker)
text_input_loop() { :; }
load_conf() { :; }
sync_clipboard() { printf 'clip\n' >> calls; exit; }
apply_host_config() { :; }
ensure_webdav_mount() {
wait "$CLIPBOARD_PID" || expect "$?" 127
expect "$(read_file calls)" clip
exit
}
;;
clipboard_disabled)
printf '0\n' > clip_enabled
load_conf() { printf 'conf\n' >> calls; }
sleep() { expect "$1" 3; printf '1\n' > clip_enabled; }
sync_clipboard() { expect "$(methods)" conf,conf; exit; }
clipboard_loop
;;
clipboard_reenabled)
printf '0\n' > clip_enabled
flags=reenable
load_conf() { :; }
sleep() { expect "$1" 3; expect "$(read_file clip_enabled)" 0; }
sync_clipboard() {
expect "$(paste -sd ',' config_calls)" config,config
expect "$(read_file clip_enabled)" 1
exit
}
clipboard_loop
;;
input_*)
flags="$1"
local_info=input
case "$1" in
input_restores_empty) : > local_value ;;
input_restores_png) : > reencoded ;;
input_restores_tiff) local_info=TIFF ;;
esac
load_conf() {
if [ -f input_polled ]; then
[ ! -f "$INJECT_LOCK" ]
exit
fi
}
status=0
(text_input_loop) || status=$?
[ ! -f "$INJECT_LOCK" ]
[ ! -d "$CLIP_LOCK" ]
case "$1" in
input_exits_with_lock)
expect "$status" 7
[ ! -s calls ]
;;
input_failed)
expect "$status" 0
expect "$(read_file local_value)" A
[ ! -s calls ] && [ ! -s copies ]
;;
*)
expect "$status" 0
expect "$(read_file calls)" ack
case "$1" in
input_restores_text) expect "$(read_file local_value)" A ;;
input_restores_png)
[ -f reencoded ]
expect "$(read_file local_value)" A
;;
input_restores_empty) [ ! -s local_value ] ;;
input_restores_tiff)
[ -f restored_tiff ]
[ ! -f sips_called ]
expect "$(read_file local_value)" tiff
;;
input_preserves_new_copy) expect "$(read_file local_value)" new ;;
esac
;;
esac
;;
esac
`
+31
View File
@@ -124,6 +124,37 @@ func newClipboardTestServer(clip Clipboard) *Server {
return srv
}
func TestClipboardGETSequenceWithUnchangedHash(t *testing.T) {
clip := &memClipboard{kind: ClipText, data: []byte("same text"), seq: 7}
srv := newClipboardTestServer(clip)
initial := clipboardRequest(t, srv, http.MethodGet, "", "", "", nil)
hash := initial.Header().Get("X-Clip-Hash")
if initial.Code != http.StatusOK || hash == "" || initial.Header().Get("X-Clip-Seq") != "7" {
t.Fatalf("initial GET: %d %v", initial.Code, initial.Header())
}
if err := clip.WriteText("same text"); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, query, body string
status int
}{
{"new sequence", "&since_seq=7&wait=2", "same text", http.StatusOK},
{"same sequence", "&since_seq=8", "", http.StatusNotModified},
{"legacy guest", "", "", http.StatusNotModified},
{"invalid sequence", "&since_seq=invalid", "", http.StatusNotModified},
{"out of range sequence", "&since_seq=4294967296", "", http.StatusNotModified},
} {
t.Run(tc.name, func(t *testing.T) {
got := clipboardRequest(t, srv, http.MethodGet, "?since="+hash+tc.query, "", "", nil)
if got.Code != tc.status || got.Body.String() != tc.body || got.Header().Get("X-Clip-Seq") != "8" ||
got.Header().Get("X-Clip-Hash") != hash || got.Header().Get("X-Clip-Kind") != string(ClipText) {
t.Fatalf("GET: %d %v %q, want status %d and body %q", got.Code, got.Header(), got.Body, tc.status, tc.body)
}
})
}
}
func TestClipboardPOSTSequenceConflict(t *testing.T) {
oldPNG := makeSamplePNG(t, 255, 0, 0)
newPNG := makeSamplePNG(t, 0, 255, 0)
+75 -26
View File
@@ -3,6 +3,7 @@
package guesttools
import (
"bytes"
"errors"
"fmt"
"runtime"
@@ -58,7 +59,17 @@ const (
maxDIBBytes = 128 << 20
)
type OSClipboard struct{}
type OSClipboard struct {
cache clipboardCache
}
type clipboardCache struct {
mu sync.Mutex
valid bool
seq uint32
hasImage bool
payload ClipPayload
}
type clipboardWindowMessage struct {
hwnd uintptr
@@ -158,7 +169,7 @@ func registerPNGFormat() (uintptr, error) {
return pngFormatID, pngFormatErr
}
func (OSClipboard) SequenceNumber() uint32 {
func (*OSClipboard) SequenceNumber() uint32 {
r, _, _ := procGetClipboardSequenceNumber.Call()
return uint32(r)
}
@@ -171,22 +182,25 @@ func unlockClipboardMem(h uintptr) error {
return nil
}
func readClipboardImageLocked(format uintptr, maxBytes int) ([]byte, error) {
func readClipboardImageLocked(format uintptr, maxBytes int) ([]byte, bool, error) {
h, _, _ := procGetClipboardData.Call(format)
if h == 0 {
return nil, nil
return nil, true, nil
}
size, _, _ := procGlobalSize.Call(h)
if size == 0 || size > uintptr(maxBytes) {
return nil, nil
if size == 0 {
return nil, true, nil
}
if size > uintptr(maxBytes) {
return nil, false, nil
}
ptr, _, _ := procGlobalLock.Call(h)
if ptr == 0 {
return nil, nil
return nil, true, nil
}
buf := make([]byte, int(size))
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, size)
return buf, unlockClipboardMem(h)
return buf, false, unlockClipboardMem(h)
}
func readUnicodeTextLocked() ([]uint16, error) {
@@ -217,7 +231,7 @@ func decodeClipboardText(words []uint16) string {
}
// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF.
func (OSClipboard) ReadText() (string, error) {
func (*OSClipboard) ReadText() (string, error) {
var words []uint16
err := onClipboardThread(func(hwnd uintptr) error {
return withOpenClipboard(hwnd, func() error {
@@ -236,17 +250,18 @@ func (OSClipboard) ReadText() (string, error) {
}
type clipboardSnapshot struct {
text []uint16
png []byte
dib []byte
kind ClipKind
text []uint16
png []byte
dib []byte
kind ClipKind
imageReadFailed bool
}
func (snap clipboardSnapshot) payload() ClipPayload {
if snap.kind == ClipText && len(snap.text) > 0 && snap.text[0] != 0 {
return ClipPayload{Kind: ClipText, Data: []byte(decodeClipboardText(snap.text))}
}
if data, ok := TrimPNG(snap.png); ok {
if data, ok := ValidatePNG(snap.png); ok {
return ClipPayload{Kind: ClipPNG, Data: data}
}
if len(snap.dib) > 0 {
@@ -257,14 +272,14 @@ func (snap clipboardSnapshot) payload() ClipPayload {
return ClipPayload{Kind: snap.kind}
}
func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintptr, available func(uintptr) bool, readImage func(uintptr, int) ([]byte, error)) error {
func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintptr, available func(uintptr) bool, readImage func(uintptr, int) ([]byte, bool, error)) error {
if pngFormat != 0 && available(pngFormat) {
snap.kind = ClipEmpty
if !wantImage {
return nil
}
var err error
snap.png, err = readImage(pngFormat, MaxClipboardBytes)
snap.png, snap.imageReadFailed, err = readImage(pngFormat, MaxClipboardBytes)
if err != nil {
return err
}
@@ -273,8 +288,10 @@ func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintpt
if available(cfDIB) {
snap.kind = ClipEmpty
if wantImage {
var failed bool
var err error
snap.dib, err = readImage(cfDIB, maxDIBBytes)
snap.dib, failed, err = readImage(cfDIB, maxDIBBytes)
snap.imageReadFailed = snap.imageReadFailed || failed
return err
}
}
@@ -282,12 +299,43 @@ func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintpt
}
// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image.
func (c OSClipboard) Read() (ClipPayload, error) {
func (c *OSClipboard) Read() (ClipPayload, error) {
payload, _, err := c.readClipboard(true)
return payload, err
}
func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
return c.cache.read(wantImage, c.SequenceNumber, c.readClipboardSnapshot)
}
func (c *clipboardCache) read(wantImage bool, sequence func() uint32, readSnapshot func(bool) (clipboardSnapshot, uint32, error)) (ClipPayload, uint32, 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
}
payload := c.payload
payload.Data = bytes.Clone(payload.Data)
return payload, curSeq, nil
}
snap, seq, err := readSnapshot(wantImage)
if err != nil {
return ClipPayload{}, seq, err
}
payload := snap.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)}
}
return payload, seq, nil
}
func (c *OSClipboard) readClipboardSnapshot(wantImage bool) (clipboardSnapshot, uint32, error) {
pngFormat, _ := registerPNGFormat()
var snap clipboardSnapshot
var seq uint32
@@ -311,10 +359,7 @@ func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error)
}, readClipboardImageLocked)
})
})
if err != nil {
return ClipPayload{}, seq, err
}
return snap.payload(), seq, nil
return snap, seq, err
}
type clipboardMem struct {
@@ -346,18 +391,18 @@ func prepareClipboardMem(format, size uintptr, src unsafe.Pointer) (clipboardMem
}
// WriteText writes UTF-8 text as CF_UNICODETEXT, with CRLF for Windows apps.
func (c OSClipboard) WriteText(text string) error {
func (c *OSClipboard) WriteText(text string) error {
_, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil)
return err
}
// WritePNG writes an image in both native "PNG" and 32-bit CF_DIB formats.
func (c OSClipboard) WritePNG(pngBytes []byte) error {
func (c *OSClipboard) WritePNG(pngBytes []byte) error {
_, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil)
return err
}
func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq uint32, err error) {
func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq uint32, err error) {
var mem []clipboardMem
defer func() {
for _, item := range mem {
@@ -400,6 +445,8 @@ func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq u
mem = append(mem, textMem)
}
c.cache.mu.Lock()
defer c.cache.mu.Unlock()
err = onClipboardThread(func(hwnd uintptr) error {
return withOpenClipboard(hwnd, func() error {
seq = c.SequenceNumber()
@@ -422,5 +469,7 @@ func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq u
return writeErr
})
})
c.cache.valid = false
c.cache.payload = ClipPayload{}
return seq, err
}
+154 -2
View File
@@ -4,6 +4,10 @@ package guesttools
import (
"bytes"
"encoding/binary"
"hash/crc32"
"image/png"
"strings"
"sync"
"testing"
@@ -51,6 +55,33 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) {
if err != nil {
t.Fatal(err)
}
badPixels := bytes.Clone(origPNG)
for off := len(pngMagic); off < len(badPixels); {
size := int(binary.BigEndian.Uint32(badPixels[off:]))
chunkEnd := off + 8 + size
if string(badPixels[off+4:off+8]) == "IDAT" {
badPixels[off+8] ^= 0xff
binary.BigEndian.PutUint32(badPixels[chunkEnd:], crc32.ChecksumIEEE(badPixels[off+4:chunkEnd]))
break
}
off = chunkEnd + 4
}
if _, ok := TrimPNG(badPixels); !ok {
t.Fatal("corrupted pixels must leave PNG chunk structure intact")
}
if _, err := png.DecodeConfig(bytes.NewReader(badPixels)); err != nil {
t.Fatalf("corrupted pixels must leave PNG config intact: %v", err)
}
oversizedPNG := bytes.Clone(origPNG)
binary.BigEndian.PutUint32(oversizedPNG[16:20], 8192)
binary.BigEndian.PutUint32(oversizedPNG[20:24], 4097)
binary.BigEndian.PutUint32(oversizedPNG[29:33], crc32.ChecksumIEEE(oversizedPNG[12:29]))
if _, err := decodeClipboardPNG(oversizedPNG); err == nil || !strings.Contains(err.Error(), "pixel count") {
t.Fatalf("oversized PNG must fail the pixel check before decoding, got %v", err)
}
if _, ok := ValidatePNG(oversizedPNG); ok {
t.Fatal("ValidatePNG accepted a PNG above the pixel limit")
}
for _, tc := range []struct {
name string
snap clipboardSnapshot
@@ -62,6 +93,10 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) {
ClipPayload{Kind: ClipPNG, Data: origPNG}},
{"bad PNG falls back to DIB", clipboardSnapshot{png: origPNG[:len(origPNG)-2], dib: dib},
ClipPayload{Kind: ClipPNG, Data: dibPNG}},
{"undecodable PNG pixels fall back to DIB", clipboardSnapshot{png: badPixels, dib: dib},
ClipPayload{Kind: ClipPNG, Data: dibPNG}},
{"oversized PNG falls back to DIB", clipboardSnapshot{png: oversizedPNG, dib: dib},
ClipPayload{Kind: ClipPNG, Data: dibPNG}},
{"empty text is representable", clipboardSnapshot{text: []uint16{0}, kind: ClipText},
ClipPayload{Kind: ClipText}},
{"unusable image is skipped", clipboardSnapshot{dib: []byte{1, 2}},
@@ -76,15 +111,132 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) {
}
}
func TestWindowsClipboardReadUsesSequenceCache(t *testing.T) {
var cache clipboardCache
seq := uint32(15)
sequence := func() uint32 { return seq }
pixels := makeSamplePNG(t, 1, 2, 3)
dib, err := EncodePNGToDIB(pixels)
if err != nil {
t.Fatal(err)
}
want, err := DecodeDIBToPNG(dib)
if err != nil {
t.Fatal(err)
}
reads := 0
readSnapshot := func(wantImage bool) (clipboardSnapshot, uint32, error) {
reads++
if !wantImage {
return clipboardSnapshot{kind: ClipEmpty}, seq, nil
}
return clipboardSnapshot{dib: dib}, seq, nil
}
for _, tc := range []struct {
seq uint32
wantImage bool
wantReads int
}{
{15, false, 1},
{15, false, 1},
{15, true, 2},
{15, true, 2},
{15, false, 2},
{16, true, 3},
{0, true, 4},
{0, true, 5},
} {
seq = tc.seq
got, gotSeq, err := cache.read(tc.wantImage, sequence, readSnapshot)
if err != nil || gotSeq != seq || reads != tc.wantReads {
t.Fatalf("read: sequence %d, reads %d, error %v, want sequence %d and reads %d", gotSeq, reads, err, seq, tc.wantReads)
}
if tc.wantImage {
if got.Kind != ClipPNG || !bytes.Equal(got.Data, want) {
t.Fatalf("expected intact PNG, got kind %q and %d bytes", got.Kind, len(got.Data))
}
got.Data[0] ^= 0xff
} else if got.Kind != ClipEmpty {
t.Fatalf("expected empty result without images, got %q", got.Kind)
}
}
}
func TestWindowsClipboardRetriesTransientImageReads(t *testing.T) {
const pngFormat = 0xc000
const seq = 15
pixels := makeSamplePNG(t, 1, 2, 3)
dib, err := EncodePNGToDIB(pixels)
if err != nil {
t.Fatal(err)
}
dibPNG, err := DecodeDIBToPNG(dib)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
failedFormat uintptr
fallback bool
}{
{"PNG temporarily unavailable", pngFormat, false},
{"DIB temporarily unavailable", cfDIB, false},
{"DIB fallback stays cached", pngFormat, true},
} {
t.Run(tc.name, func(t *testing.T) {
var cache clipboardCache
reads := 0
readSnapshot := func(wantImage bool) (clipboardSnapshot, uint32, error) {
reads++
var snap clipboardSnapshot
err := snap.readImagesLocked(wantImage, pngFormat, func(format uintptr) bool {
return tc.fallback || format == tc.failedFormat
}, func(format uintptr, _ int) ([]byte, bool, error) {
if reads == 1 && format == tc.failedFormat {
return nil, true, nil
}
if format == cfDIB {
return dib, false, nil
}
return pixels, false, nil
})
return snap, seq, err
}
sequence := func() uint32 { return seq }
got, _, err := cache.read(true, sequence, readSnapshot)
if err != nil || (cache.valid != tc.fallback) {
t.Fatalf("first read: cache valid %t, error %v", cache.valid, err)
}
if tc.fallback {
if got.Kind != ClipPNG || !bytes.Equal(got.Data, dibPNG) {
t.Fatal("first read did not fall back to DIB")
}
} else if got.Kind != ClipEmpty {
t.Fatalf("first read kind = %q, want empty", got.Kind)
}
want, wantReads := pixels, 2
if tc.fallback {
want, wantReads = dibPNG, 1
} else if tc.failedFormat == cfDIB {
want = dibPNG
}
got, _, err = cache.read(true, sequence, readSnapshot)
if err != nil || reads != wantReads || got.Kind != ClipPNG || !bytes.Equal(got.Data, want) {
t.Fatalf("second read: kind %q, %d snapshot reads, error %v", got.Kind, reads, err)
}
})
}
}
func TestWindowsClipboardSnapshotSkipsDisabledImages(t *testing.T) {
const pngFormat = 0xc000
for _, format := range []uintptr{pngFormat, cfDIB} {
for _, snap := range []clipboardSnapshot{{}, {text: []uint16{0}, kind: ClipText}} {
err := snap.readImagesLocked(false, pngFormat, func(candidate uintptr) bool {
return candidate == format
}, func(uintptr, int) ([]byte, error) {
}, func(uintptr, int) ([]byte, bool, error) {
t.Fatalf("disabled image format %#x must not be copied for decoding", format)
return nil, nil
return nil, false, nil
})
if err != nil {
t.Fatal(err)
+28 -2
View File
@@ -15,7 +15,10 @@ import (
// pngMagic is the standard 8-byte PNG file signature.
var pngMagic = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}
const maxClipboardImageDim = 16384
const (
maxClipboardImageDim = 16384
maxClipboardImagePixels = 33_554_432
)
// IsPNG reports whether data starts with the PNG signature.
func IsPNG(data []byte) bool {
@@ -44,6 +47,18 @@ func TrimPNG(raw []byte) ([]byte, bool) {
return nil, false
}
// ValidatePNG trims clipboard padding and checks that the PNG can be decoded.
func ValidatePNG(raw []byte) ([]byte, bool) {
data, ok := TrimPNG(raw)
if !ok {
return nil, false
}
if _, err := decodeClipboardPNG(data); err != nil {
return nil, false
}
return data, true
}
// EncodeImageToDIB encodes an image into a standard 32-bit bottom-up Windows
// CF_DIB (BITMAPINFOHEADER + BGRA pixels) accepted by all Windows applications.
func EncodeImageToDIB(img image.Image) ([]byte, error) {
@@ -87,6 +102,14 @@ func EncodePNGToDIB(pngBytes []byte) ([]byte, error) {
if !IsPNG(pngBytes) {
return nil, errors.New("payload is not a valid PNG")
}
img, err := decodeClipboardPNG(pngBytes)
if err != nil {
return nil, err
}
return EncodeImageToDIB(img)
}
func decodeClipboardPNG(pngBytes []byte) (image.Image, error) {
cfg, err := png.DecodeConfig(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG config: %w", err)
@@ -94,11 +117,14 @@ func EncodePNGToDIB(pngBytes []byte) ([]byte, error) {
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxClipboardImageDim || cfg.Height > maxClipboardImageDim {
return nil, fmt.Errorf("PNG dimensions out of bounds: %dx%d", cfg.Width, cfg.Height)
}
if uint64(cfg.Width)*uint64(cfg.Height) > maxClipboardImagePixels {
return nil, fmt.Errorf("PNG pixel count out of bounds: %dx%d", cfg.Width, cfg.Height)
}
img, err := png.Decode(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode PNG: %w", err)
}
return EncodeImageToDIB(img)
return img, nil
}
// DecodeDIBToPNG converts 24/32-bit BI_RGB or 16/32-bit BI_BITFIELDS to PNG.
+3 -3
View File
@@ -45,7 +45,7 @@ print $mounts "$url on $target (webdav, read-only)\n";
t.Fatal(err)
}
script := string(GuestAgentScript())
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":10,`) {
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":11,`) {
t.Fatal("Windows drive sharing requires version 8 and the generated agent reports version 10")
}
harness := `set -eu
@@ -128,8 +128,8 @@ test "$(wc -l <"$MOUNT_STATE")" -eq 1
}
func TestShellSingleQuoteAndAgentVersion(t *testing.T) {
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":10,`) {
t.Fatal("GuestAgentScript must report agent_version 10")
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":11,`) {
t.Fatal("GuestAgentScript must report agent_version 11")
}
if DriveShareAgentVersion != 8 {
t.Fatalf("DriveShareAgentVersion = %d, want 8", DriveShareAgentVersion)
+17 -2
View File
@@ -37,8 +37,8 @@ func TestGuestAgentFolderMounts(t *testing.T) {
}
}
agent, uninstall, install := string(GuestAgentScript()), string(GuestUninstallScript()), string(GuestInstallScript())
if CurrentAgentVersion != KeymapAgentVersion {
t.Fatalf("CurrentAgentVersion = %d, want keymap version %d", CurrentAgentVersion, KeymapAgentVersion)
if CurrentAgentVersion != ClipboardReliabilityAgentVersion {
t.Fatalf("CurrentAgentVersion = %d, want clipboard reliability version %d", CurrentAgentVersion, ClipboardReliabilityAgentVersion)
}
versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,`
if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") {
@@ -46,6 +46,21 @@ func TestGuestAgentFolderMounts(t *testing.T) {
}
mounts := scriptSection(t, agent, "urlencode() {", "\nhash_file() {") +
scriptSection(t, agent, "\ndrive_mount_failures=", "\nreport_status() {")
t.Run("clipboard_setting_before_mounts", func(t *testing.T) {
run(t, folderShellFixture+mounts+`
curl() { printf '{"clipboard_enabled":%s}' "$enabled"; }
sync_drive_mounts() {
expect "$(cat "$TMP_DIR/clip_enabled")" "$expected"
[ ! -e "$TMP_DIR/clip_enabled.tmp" ]
}
enabled=false
expected=0
apply_host_config
enabled=true
expected=1
apply_host_config
`, "-s")
})
t.Run("reconcile", func(t *testing.T) {
run(t, folderShellFixture+mounts+folderReconcileChecks, "-s")
})
+2 -1
View File
@@ -15,7 +15,8 @@ import (
const SharedFolderAgentVersion = 9
const KeymapAgentVersion = 10
const CurrentAgentVersion = KeymapAgentVersion
const ClipboardReliabilityAgentVersion = 11
const CurrentAgentVersion = ClipboardReliabilityAgentVersion
type SharedFolderConfig struct {
ID string `json:"id"`
+209 -48
View File
@@ -99,11 +99,13 @@ FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders"
DESKTOP_LINK="$HOME/Desktop/ReimsShare"
TMP_DIR="$APP_DIR/tmp"
INJECT_LOCK="$TMP_DIR/injecting"
CLIP_LOCK="$TMP_DIR/clip.lock"
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR"
rm -f "$INJECT_LOCK" 2>/dev/null || true
rm -rf "$CLIP_LOCK" "$CLIP_LOCK".reaping.* "$INJECT_LOCK" 2>/dev/null || true
CAFFEINATE_PID=""
TEXT_INPUT_PID=""
CLIPBOARD_PID=""
keymap_active="false"
keymap_applied="false"
` + guestKeymapCarrier + `
@@ -119,7 +121,9 @@ cleanup() {
if [ -n "$TEXT_INPUT_PID" ]; then
kill "$TEXT_INPUT_PID" 2>/dev/null || true
fi
rm -f "$INJECT_LOCK" 2>/dev/null || true
if [ -n "$CLIPBOARD_PID" ]; then
kill "$CLIPBOARD_PID" 2>/dev/null || true
fi
}
trap cleanup EXIT
trap 'exit 0' INT TERM
@@ -129,8 +133,11 @@ trap 'exit 0' INT TERM
load_conf() {
if [ -f "/Volumes/REIMSTOOLS/config" ] &&
{ [ ! -f "$CONF" ] || same_guest_identity "$CONF" "/Volumes/REIMSTOOLS/config"; }; then
cp "/Volumes/REIMSTOOLS/config" "$CONF" 2>/dev/null || true
chmod 600 "$CONF" 2>/dev/null || true
if conf_tmp=$(mktemp "$TMP_DIR/config.XXXXXX"); then
if ! cp "/Volumes/REIMSTOOLS/config" "$conf_tmp" || ! mv -f "$conf_tmp" "$CONF"; then
rm -f "$conf_tmp"
fi
fi
fi
if [ -f "$CONF" ]; then
# shellcheck disable=SC1090
@@ -403,15 +410,17 @@ apply_host_config() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true)
[ -n "$cfg_json" ] || return 0
sync_drive_mounts "$cfg_json"
folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p')
sync_folder_mounts "${folders_count:-0}"
sync_keymap_carrier "$cfg_json"
if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then
clip_enabled="0"
else
clip_enabled="1"
fi
printf '%s\n' "$clip_enabled" > "$TMP_DIR/clip_enabled.tmp" &&
mv -f "$TMP_DIR/clip_enabled.tmp" "$TMP_DIR/clip_enabled"
sync_drive_mounts "$cfg_json"
folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p')
sync_folder_mounts "${folders_count:-0}"
sync_keymap_carrier "$cfg_json"
if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then
if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then
if command -v caffeinate >/dev/null 2>&1; then
@@ -438,13 +447,16 @@ report_status() {
curl -fsS -m "${1:-3}" -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":10,\"keymap_active\":$keymap_active}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":11,\"keymap_active\":$keymap_active}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
read_local_clipboard() {
out_file="$1"
cinfo=$(osascript -e 'clipboard info' 2>/dev/null || true)
if ! cinfo=$(osascript -e 'clipboard info' 2>/dev/null); then
echo "empty"
return 0
fi
case "$cinfo" in
*utf8*|*"Unicode text"*|*string*)
if pbpaste >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then
@@ -467,29 +479,27 @@ read_local_clipboard() {
esac
case "$cinfo" in
*TIFF*)
tiff_tmp="$TMP_DIR/clip_in.tiff"
tiff_tmp="$out_file.tiff"
rm -f "$tiff_tmp" "$out_file"
if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as TIFF picture) to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ] &&
sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then
rm -f "$tiff_tmp"
echo "png"
return 0
-e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ]; then
if [ "${2:-}" = "keep_tiff" ]; then
if mv -f "$tiff_tmp" "$out_file"; then
echo "tiff"
return 0
fi
elif sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then
rm -f "$tiff_tmp"
echo "png"
return 0
fi
fi
rm -f "$tiff_tmp"
;;
esac
case "$cinfo" in
*PNGf*|*TIFF*)
echo "empty"
;;
*)
pbpaste >"$out_file" 2>/dev/null || : >"$out_file"
echo "text"
;;
esac
echo "empty"
}
write_local_png() {
@@ -505,19 +515,109 @@ local_clip_hash() {
}
clip_header() {
awk -v name="$1:" 'tolower($1)==name {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out"
while IFS=':' read -r hdr_key hdr_val; do
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])
hdr_val=${hdr_val#"${hdr_val%%[![:space:]]*}"}
hdr_val=${hdr_val%"${hdr_val##*[![:space:]]}"}
printf '%s\n' "$hdr_val"
return 0
;;
esac
done < "$hdr_out"
}
last_local_hash=""
last_server_hash=""
last_server_seq=""
clip_enabled="1"
tick=0
TAB=$(printf '\t')
clip_lock_recent() {
lock_at="$2"
case "$lock_at" in
""|*[!0-9]*)
lock_at=$(stat -f %m "$1" 2>/dev/null) ||
lock_at=$(stat -c %Y "$1" 2>/dev/null) || return 1
;;
esac
[ "$lock_at" -ge "$(($(date +%s) - 15))" ]
}
clip_lock_owner_active() {
case "$2" in
""|0|*[!0-9]*) clip_lock_recent "$1" "$3" ;;
*) kill -0 "$2" 2>/dev/null ;;
esac
}
acquire_clip_lock() {
if ! mkdir "$CLIP_LOCK" 2>/dev/null; then
lock_pid=""
lock_time=""
[ ! -f "$CLIP_LOCK/pid" ] || IFS= read -r lock_pid < "$CLIP_LOCK/pid" || lock_pid=""
[ ! -f "$CLIP_LOCK/at" ] || IFS= read -r lock_time < "$CLIP_LOCK/at" || lock_time=""
clip_lock_owner_active "$CLIP_LOCK" "$lock_pid" "$lock_time" && return 1
# Serialize stale lock removal and recheck ownership before deleting.
(
reap_lock="$CLIP_LOCK.reaping.$(sh -c 'echo $PPID')"
mkdir "$reap_lock" 2>/dev/null || exit 1
trap 'rmdir "$reap_lock"' EXIT
trap 'exit 1' INT TERM
for claim in "$CLIP_LOCK".reaping.*; do
[ "$claim" != "$reap_lock" ] || continue
kill -0 "${claim##*.}" 2>/dev/null && exit 1
rmdir "$claim" 2>/dev/null || true
done
lock_pid=""
lock_time=""
[ ! -f "$CLIP_LOCK/pid" ] || IFS= read -r lock_pid < "$CLIP_LOCK/pid" || lock_pid=""
[ ! -f "$CLIP_LOCK/at" ] || IFS= read -r lock_time < "$CLIP_LOCK/at" || lock_time=""
[ -d "$CLIP_LOCK" ] || exit 0
clip_lock_owner_active "$CLIP_LOCK" "$lock_pid" "$lock_time" && exit 1
rm -rf "$CLIP_LOCK"
) || return 1
mkdir "$CLIP_LOCK" 2>/dev/null || return 1
fi
printf '%s\n' "$cur_pid" > "$CLIP_LOCK/pid"
date +%s > "$CLIP_LOCK/at"
}
release_clip_lock() {
lock_pid=""
[ ! -f "$CLIP_LOCK/pid" ] || IFS= read -r lock_pid < "$CLIP_LOCK/pid" || lock_pid=""
[ -z "$lock_pid" ] || [ "$lock_pid" = "${cur_pid:-}" ] || return 0
rm -f "$CLIP_LOCK/at" "$CLIP_LOCK/pid" 2>/dev/null || true
rmdir "$CLIP_LOCK" 2>/dev/null || true
}
inject_lock_active() {
[ -f "$INJECT_LOCK" ] || return 1
lock_value=""
IFS= read -r lock_value < "$INJECT_LOCK" || lock_value=""
case "$lock_value" in
*:*) lock_pid="${lock_value%%:*}"; lock_time="${lock_value#*:}" ;;
*) lock_pid=""; lock_time="$lock_value" ;;
esac
clip_lock_owner_active "$INJECT_LOCK" "$lock_pid" "$lock_time" && return 0
rm -f "$INJECT_LOCK" 2>/dev/null || true
return 1
}
sync_clipboard() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
if [ -f "$INJECT_LOCK" ]; then
if [ -z "$REIMS_HOST_URL" ] || [ -z "$REIMS_TOKEN" ]; then
sleep 2
return 0
fi
if ! acquire_clip_lock; then
sleep 1
return 0
fi
if inject_lock_active; then
release_clip_lock
sleep 1
return 0
fi
@@ -527,6 +627,7 @@ sync_clipboard() {
local_kind=$(read_local_clipboard "$clip_in")
cur_hash=$(local_clip_hash "$local_kind" "$clip_in")
release_clip_lock
post_conflict=0
if [ "$local_kind" != "empty" ] && [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then
@@ -550,6 +651,9 @@ sync_clipboard() {
;;
204|413)
last_local_hash="$cur_hash"
if [ -z "$last_server_seq" ]; then
last_server_hash=""
fi
;;
409)
post_conflict=1
@@ -558,30 +662,46 @@ sync_clipboard() {
fi
# Long-poll up to 2s: host changes return immediately (~150ms), idle stays quiet.
clip_url="$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=image"
if [ -n "$last_server_seq" ]; then
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" \
"$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=image" 2>/dev/null) || code=000
"$clip_url" 2>/dev/null) || code=000
case "$code" in
200)
new_hash=$(clip_header x-clip-hash)
[ -n "$new_hash" ] || return 0
[ -n "$new_hash" ] || { sleep 2; return 0; }
new_kind=$(clip_header x-clip-kind)
new_seq=$(clip_header x-clip-seq)
acquire_clip_lock || {
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
return 0
}
if inject_lock_active; then
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
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
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
last_server_seq="$new_seq"
release_clip_lock
return 0
fi
if [ "$new_hash" != "$cur_hash" ]; then
if [ "$new_kind" = "png" ]; then
write_local_png "$clip_out" || return 0
write_local_png "$clip_out" || { release_clip_lock; sleep 2; return 0; }
else
pbcopy <"$clip_out" 2>/dev/null || return 0
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")
fi
release_clip_lock
last_local_hash="$post_get_hash"
last_server_hash="$new_hash"
last_server_seq="$new_seq"
@@ -607,15 +727,40 @@ sync_clipboard() {
# Feature disabled on host: back off instead of busy-looping osascript + curl.
sleep 5
;;
000)
*)
sleep 2
;;
esac
}
clipboard_loop() {
cur_pid=$(sh -c 'echo $PPID')
while :; do
load_conf
clip_enabled=1
if [ -f "$TMP_DIR/clip_enabled" ]; then
read -r clip_enabled < "$TMP_DIR/clip_enabled"
fi
if [ "$clip_enabled" = "1" ]; then
sync_clipboard
else
sleep 3
if [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ]; then
cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null) || continue
if [ -n "$cfg_json" ] && ! printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then
printf '1\n' > "$TMP_DIR/clip_enabled.worker.tmp" &&
mv -f "$TMP_DIR/clip_enabled.worker.tmp" "$TMP_DIR/clip_enabled"
fi
fi
fi
done
}
` + guestFileSync + `
text_input_loop() {
trap 'exit 0' INT TERM
cur_pid=$(sh -c 'echo $PPID')
hdr="$TMP_DIR/txt_hdr"
body="$TMP_DIR/txt_body"
bak="$TMP_DIR/txt_clip_bak"
@@ -631,22 +776,40 @@ text_input_loop() {
"$REIMS_HOST_URL/v1/text-input?wait=25" 2>/dev/null || echo "000")
if [ "$code" = "200" ]; then
input_id=$(awk 'tolower($1)=="x-input-id:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr")
: > "$INJECT_LOCK"
pbpaste >"$bak" 2>/dev/null || : >"$bak"
pbcopy <"$body" 2>/dev/null || true
attempts=0
while ! acquire_clip_lock; do
attempts=$((attempts + 1))
[ "$attempts" -lt 35 ] || break
sleep 0.1
done
[ "$attempts" -lt 35 ] || continue
trap 'rm -f "$INJECT_LOCK" 2>/dev/null || true; release_clip_lock' EXIT
printf '%s:%s\n' "$cur_pid" "$(date +%s)" > "$INJECT_LOCK"
bak_kind=$(read_local_clipboard "$bak" keep_tiff)
if ! pbcopy <"$body" 2>/dev/null; then
trap - EXIT
rm -f "$INJECT_LOCK" 2>/dev/null || true
release_clip_lock
continue
fi
inj_hash=$(hash_file "$body")
if [ -n "$input_id" ]; then
curl -fsS -m 8 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/text-input/ack?id=$input_id" >/dev/null 2>&1 || true
fi
# Restore prior text clipboard unless user copied something else during paste.
pbpaste >"$cur_chk" 2>/dev/null || : >"$cur_chk"
cur_after=$(hash_file "$cur_chk")
if [ "$cur_after" = "$inj_hash" ] && [ -s "$bak" ]; then
pbcopy <"$bak" 2>/dev/null || true
cur_kind=$(read_local_clipboard "$cur_chk" keep_tiff)
if [ "$cur_kind" = "text" ] && [ "$(local_clip_hash "$cur_kind" "$cur_chk")" = "$inj_hash" ]; then
case "$bak_kind" in
text) [ ! -s "$bak" ] || pbcopy <"$bak" 2>/dev/null || true ;;
png) [ ! -s "$bak" ] || write_local_png "$bak" || true ;;
tiff) osascript -e "set the clipboard to (read (POSIX file \"$bak\") as TIFF picture)" >/dev/null 2>&1 || true ;;
empty) pbcopy </dev/null 2>/dev/null || true ;;
esac
fi
trap - EXIT
rm -f "$INJECT_LOCK" 2>/dev/null || true
release_clip_lock
elif [ "$code" != "204" ]; then
sleep 1
fi
@@ -655,23 +818,21 @@ text_input_loop() {
text_input_loop &
TEXT_INPUT_PID=$!
clipboard_loop &
CLIPBOARD_PID=$!
while :; do
if [ $((tick % 5)) -eq 0 ]; then
load_conf
ensure_webdav_mount
apply_host_config
ensure_webdav_mount
report_status
fi
if [ "$clip_enabled" = "1" ]; then
sync_clipboard
else
sleep 3
fi
if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then
sync_files
fi
tick=$((tick + 1))
sleep 2
done
`)
}
+3 -2
View File
@@ -22,8 +22,8 @@ func TestGuestAgentKeymapScript(t *testing.T) {
agent := string(GuestAgentScript())
start := strings.Index(agent, "apply_hidutil_carrier() {")
end := strings.Index(agent, "load_conf() {")
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":10,\"keymap_active\":$keymap_active`) {
t.Fatal("missing guest keymap script or version 10 status")
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":11,\"keymap_active\":$keymap_active`) {
t.Fatal("missing guest keymap script or version 11 status")
}
for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} {
t.Run(input, func(t *testing.T) {
@@ -120,6 +120,7 @@ const keymapShellFixture = `set -eu
PATH="/usr/bin:/bin:$PATH"
CAFFEINATE_PID=
TEXT_INPUT_PID=
CLIPBOARD_PID=
INJECT_LOCK=./injecting
keymap_active=false
keymap_applied=false
+46 -2
View File
@@ -211,6 +211,7 @@ type pendingClipOverride struct {
type registeredVM struct {
key string
name string
regGen uint64
token string
sharedDir string
sharedRoot sharedRoot
@@ -504,6 +505,7 @@ func (s *Server) RegisterVM(cfg VMConfig) {
delete(s.davCache, davKey)
}
}
cur.regGen++
cur.token = cfg.Token
cur.sharedDir = cfg.SharedDir
cur.sharedRoot = root
@@ -516,6 +518,45 @@ func (s *Server) RegisterVM(cfg VMConfig) {
cur.verifyFolderRoot = cfg.VerifyFolderRoot
}
// HasVM reports whether vmKey is registered with the bridge.
func (s *Server) HasVM(vmKey string) bool {
return s.RegistrationGen(vmKey) > 0
}
// RegistrationGen returns the current registration generation for vmKey, or 0 if unregistered.
func (s *Server) RegistrationGen(vmKey string) uint64 {
s.mu.RLock()
defer s.mu.RUnlock()
if vm := s.vms[normalizeVMRegistryKey(vmKey)]; vm != nil {
return vm.regGen
}
return 0
}
// UnregisterVMIfGen unregisters vmKey only when its current registration generation matches gen.
func (s *Server) UnregisterVMIfGen(vmKey string, gen uint64) bool {
if gen == 0 {
return false
}
key := normalizeVMRegistryKey(vmKey)
s.folderAccessMu.Lock()
defer s.folderAccessMu.Unlock()
s.mu.Lock()
defer s.mu.Unlock()
vm := s.vms[key]
if vm == nil || vm.regGen != gen {
return false
}
delete(s.vms, key)
delete(s.davCache, key)
for davKey := range s.davCache {
if strings.HasPrefix(davKey, key+"/") {
delete(s.davCache, davKey)
}
}
return true
}
// UnregisterVM releases all host-side state owned by a deleted VM. In-flight
// requests retain only their own snapshot and fail authentication on retry.
func (s *Server) UnregisterVM(vmKey string) {
@@ -946,6 +987,8 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
since := r.URL.Query().Get("since")
sinceSeq, seqErr := strconv.ParseUint(r.URL.Query().Get("since_seq"), 10, 32)
hasSinceSeq := seqErr == nil
for {
ch := s.clipNotifyChan()
@@ -978,12 +1021,13 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
wantImage && len(payload.Data) <= policy.MaxImageBytes)
if syncable {
h := payloadHash(payload)
if since != h || time.Until(deadline) <= 0 {
unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq))
if !unchanged || time.Until(deadline) <= 0 {
setClipboardSeq(w, seq)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
s.touchLastSeen(vmKey)
if since == h {
if unchanged {
w.WriteHeader(http.StatusNotModified)
return
}