Merge pull request #115 from YinLiaoCo/feat/clipboard-file-sync
feat(guesttools): sync Windows copied files to macOS clipboard via zero-copy WebDAV (Agent v15)
This commit is contained in:
29 files changed
+2181
-297
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["YinLiaoCo"],
|
||||
"zh": "支持在 Windows 中复制或剪切本地文件与文件夹后直接粘贴到 macOS 虚拟机,复用宿主机零拷贝只读 WebDAV 共享并保留 Windows 的剪切状态和原文件。已有虚拟机需将 Guest Tools 更新至 `v15` 以启用剪贴板文件同步。",
|
||||
"en": "Copy or cut local Windows files and folders and paste them directly into a macOS VM through read-only, zero-copy WebDAV shares. The Windows cut state and original files are preserved. Update Guest Tools to `v15` in existing VMs to enable clipboard file sync."
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"bundle": "vite build && node scripts/check-ui-contract.mjs",
|
||||
"build": "tsc --noEmit && pnpm run bundle",
|
||||
|
||||
@@ -1 +1 @@
|
||||
f30a3646316b376820394ecddd138518
|
||||
a78cc1ea19b398308258a7f6c2f8f473
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
test('Guest Tools offers an update when a connected guest is older than the bundled agent', async () => {
|
||||
// Wails reads its window bindings at import time. Static rendering uses the VM detail before the first live poll.
|
||||
globalThis.window = {}
|
||||
try {
|
||||
const { render } = await loadTestModule(`
|
||||
import { createElement } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server.edge'
|
||||
import { TooltipProvider } from './ui/controls'
|
||||
import { VMPage } from './components/VMPage'
|
||||
|
||||
export function render(installed, bundled, connected = true) {
|
||||
return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(VMPage, {
|
||||
locale: 'en-US', name: 'mac', driverID: '', state: 'running', macosMajor: null,
|
||||
host: {}, pending: [], currentAgentVersion: bundled,
|
||||
detail: { guest_tools_configured: true, guest_tools_connected: connected, guest_tools_agent_version: installed }
|
||||
})))
|
||||
}
|
||||
`)
|
||||
for (const [guest, bundled, connected, needsUpdate] of [
|
||||
[13, 14, true, true], [14, 14, true, false], [14, 15, true, true],
|
||||
[15, 15, true, false], [16, 15, true, false], [14, 15, false, false],
|
||||
[15, 14, true, false], [0, 14, true, false], [13, 14, false, false],
|
||||
]) {
|
||||
const html = render(guest, bundled, connected)
|
||||
const context = `guest v${guest}, bundled v${bundled}, connected=${connected}`
|
||||
assert.equal(html.includes('>Update needed<'), needsUpdate, context)
|
||||
assert.equal(html.includes('Update…</button>'), needsUpdate, context)
|
||||
}
|
||||
} finally {
|
||||
delete globalThis.window
|
||||
}
|
||||
})
|
||||
@@ -1228,6 +1228,7 @@ export const App: React.FC = () => {
|
||||
macosMajor={macosMajors[selectedVM.name] ?? null}
|
||||
state={effectiveState}
|
||||
canSuspend={canSuspend}
|
||||
currentAgentVersion={state.current_agent_version}
|
||||
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
|
||||
installGuideEnabled={!!state.install_guide_enabled}
|
||||
detail={detail}
|
||||
|
||||
@@ -105,6 +105,7 @@ interface Props {
|
||||
state: string
|
||||
/** Whether the active runtime supports VM suspend/resume. */
|
||||
canSuspend: boolean
|
||||
currentAgentVersion: number
|
||||
/** Whether the native VM-window installation guide is currently active for this boot. */
|
||||
guideActive: boolean
|
||||
/** Whether the VM-window install guide setting on builtin.guest.macos is enabled. */
|
||||
@@ -179,7 +180,7 @@ interface Spec {
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -1063,7 +1064,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 < 14
|
||||
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < currentAgentVersion
|
||||
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
|
||||
|
||||
@@ -18,6 +18,7 @@ export namespace app {
|
||||
data_root_status: dataroot.Status;
|
||||
data_root_message?: string;
|
||||
app_version: string;
|
||||
current_agent_version: number;
|
||||
safe_mode?: boolean;
|
||||
plugin_crash_detected?: boolean;
|
||||
detected_locale?: string;
|
||||
@@ -47,6 +48,7 @@ export namespace app {
|
||||
this.data_root_status = this.convertValues(source["data_root_status"], dataroot.Status);
|
||||
this.data_root_message = source["data_root_message"];
|
||||
this.app_version = source["app_version"];
|
||||
this.current_agent_version = source["current_agent_version"];
|
||||
this.safe_mode = source["safe_mode"];
|
||||
this.plugin_crash_detected = source["plugin_crash_detected"];
|
||||
this.detected_locale = source["detected_locale"];
|
||||
|
||||
@@ -70,6 +70,7 @@ type AppState struct {
|
||||
DataRoot dataroot.Status `json:"data_root_status"`
|
||||
DataRootMessage string `json:"data_root_message,omitempty"` // why it is read-only, localized
|
||||
AppVersion string `json:"app_version"`
|
||||
CurrentAgentVersion int `json:"current_agent_version"`
|
||||
SafeMode bool `json:"safe_mode,omitempty"`
|
||||
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
|
||||
DetectedLocale string `json:"detected_locale,omitempty"`
|
||||
@@ -806,6 +807,7 @@ func (a *App) GetState() AppState {
|
||||
DataRoot: rootStatus,
|
||||
DataRootMessage: dataRootMessage(i18n.EffectiveLocale(cfgCopy.Locale), rootStatus),
|
||||
AppVersion: version.Version,
|
||||
CurrentAgentVersion: guesttools.CurrentAgentVersion,
|
||||
SafeMode: safeMode,
|
||||
PluginCrashDetected: crashDetected,
|
||||
DetectedLocale: string(i18n.DetectOSLocaleTag()),
|
||||
|
||||
@@ -37,7 +37,7 @@ 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 &")
|
||||
textInput := scriptSection(t, agent, "inject_text() {", "\ntext_input_loop &")
|
||||
hashing := scriptSection(t, agent, "hash_file() {", "update_desktop_link() {")
|
||||
_, mainLoop, _ := strings.Cut(agent, "\ntext_input_loop &")
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
// Git Bash ships sha256sum in place of macOS shasum.
|
||||
code += "shasum() { [ \"$1/$2\" = -a/256 ] || return 1; shift 2; sha256sum ${1+\"$@\"}; }\n"
|
||||
}
|
||||
code += "hash_file payload\nhash_png_file payload\n"
|
||||
code += "hash_file payload\nhash_png_file payload\nhash_files_file payload\n"
|
||||
if err := os.WriteFile(script, []byte(code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -64,7 +64,8 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
cmd := exec.CommandContext(ctx, sh, script)
|
||||
cmd.Dir = tmp
|
||||
out, err := cmd.CombinedOutput()
|
||||
want := fmt.Sprintf("%x\n%x\n", sha256.Sum256(data), sha256.Sum256(append([]byte("png:"), data...)))
|
||||
want := fmt.Sprintf("%x\n%x\n%x\n", sha256.Sum256(data),
|
||||
sha256.Sum256(append([]byte("png:"), data...)), sha256.Sum256(append([]byte("files:"), data...)))
|
||||
if err != nil || string(out) != want {
|
||||
t.Fatalf("clipboard hashes: got %q, want %q, error %v", out, want, err)
|
||||
}
|
||||
@@ -104,6 +105,17 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
{"input_errors_and_conflicts", []string{
|
||||
"input_failed", "input_preserves_new_copy", "input_exits_with_lock",
|
||||
}},
|
||||
{"file_delivery", []string{"host_files_sync_no_echo", "host_files_reordered_readback", "guest_files_do_not_overwrite_host", "foreign_drop_mount"}},
|
||||
{"file_retry", []string{
|
||||
"host_files_remount_and_fail_no_spin", "host_files_new_event_during_retry",
|
||||
"host_ignores_conditional_file_retry", "host_files_retry_preserves_new_copy",
|
||||
}},
|
||||
{"probe_errors", []string{
|
||||
"probe_failure_after_files", "probe_failure_during_get", "probe_failure_after_write",
|
||||
"probe_recovers_during_get", "failed_pbpaste_formats", "failed_file_probe",
|
||||
}},
|
||||
{"probe_recovery", []string{"failed_png_readback", "new_guest_png_after_failed_readback", "legacy_host_png"}},
|
||||
{"injection_timing", []string{"injection_during_read", "injection_during_get", "injection_finishes_during_read", "injection_finishes_during_get"}},
|
||||
} {
|
||||
t.Run(group.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -121,6 +133,19 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var cmdEnv []string
|
||||
if group.name == "file_delivery" {
|
||||
fixture, err := filepath.Abs("testdata/pasteboard.cjs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"host_files_sync_no_echo", "host_files_reordered_readback"} {
|
||||
if err := os.WriteFile(filepath.Join(tmp, name, "drop-resolve.js"), []byte(guestDropResolveJS), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cmdEnv = append(os.Environ(), "PASTEBOARD_FIXTURE="+filepath.ToSlash(fixture))
|
||||
}
|
||||
if err := os.WriteFile(script, []byte(code), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -128,6 +153,7 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, sh, append([]string{script}, group.cases...)...)
|
||||
cmd.Dir = tmp
|
||||
cmd.Env = cmdEnv
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
t.Fatalf("clipboard script: %v\n%s", ctx.Err(), out)
|
||||
@@ -140,12 +166,16 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
|
||||
const clipboardShellFixture = `
|
||||
TMP_DIR=.
|
||||
APP_DIR=.
|
||||
DROP_MOUNT=./drop_mount
|
||||
INJECT_LOCK=./injecting
|
||||
DROP_INJECT_LOCK=./drop-injecting
|
||||
CLIP_LOCK=./clip.lock
|
||||
cur_pid=$$
|
||||
REIMS_HOST_URL=http://stub
|
||||
REIMS_TOKEN=token
|
||||
REIMS_VM="Mac VM"
|
||||
printf owned > mount_owner
|
||||
printf A > local_value
|
||||
: > calls
|
||||
: > copies
|
||||
@@ -184,7 +214,26 @@ hash_file() {
|
||||
printf '%s' "$value"
|
||||
}
|
||||
hash_png_file() { printf 'png:'; hash_file "$1"; }
|
||||
hash_files_file() { printf 'files:'; read_file "$1"; }
|
||||
urlencode() { [ "$1" = "$REIMS_VM" ] && printf 'Mac%%20VM'; }
|
||||
is_reims_dav_mounted() {
|
||||
[ "$1" = "$DROP_MOUNT" ] && [ "$2" = '/dav-drop/Mac%20VM/' ] && [ "$(read_file mount_owner)" = owned ]
|
||||
}
|
||||
ensure_drop_webdav_mount() {
|
||||
echo ensure >> mounts
|
||||
if [ ! -s mount_owner ]; then printf owned > mount_owner; fi
|
||||
}
|
||||
unmount_shared_folder() { echo unmount >> mounts; : > mount_owner; }
|
||||
pbpaste() {
|
||||
case "$flags" in
|
||||
inject_read) : > "$INJECT_LOCK" ;;
|
||||
inject_finish)
|
||||
: > "$INJECT_LOCK"
|
||||
printf 'temporary IME text'
|
||||
mv -f "$INJECT_LOCK" "$INJECT_LOCK.completed"
|
||||
return
|
||||
;;
|
||||
esac
|
||||
read_file local_value
|
||||
[ "$flags" != failed_pbpaste ] && { [ "$failure_kind" != text ] || [ ! -f read_failure ]; }
|
||||
}
|
||||
@@ -198,21 +247,61 @@ pbcopy() {
|
||||
rm -f reencoded
|
||||
printf 'text\n' >> copies
|
||||
bump_clipboard_count
|
||||
if [ "$flags" = probe_after_write ]; then : > probe_failed; fi
|
||||
}
|
||||
osascript() {
|
||||
case "$2" in
|
||||
JavaScript)
|
||||
expect "$1/$3/$4" '-l/-e/ObjC.import("AppKit"); $.NSPasteboard.generalPasteboard.changeCount'
|
||||
[ ! -f change_count ] || read_file change_count
|
||||
case "$flags" in
|
||||
count_invalid) printf '1x\n' ;;
|
||||
count_failed) printf '12\n'; return 1 ;;
|
||||
if [ "$3" = -e ]; then
|
||||
expect "$1/$3/$4" '-l/-e/ObjC.import("AppKit"); $.NSPasteboard.generalPasteboard.changeCount'
|
||||
if [ "$flags" = typed_files ] && [ -f test-pasteboard.json ]; then
|
||||
node -p 'require("./test-pasteboard.json").changeCount'
|
||||
elif [ -f change_count ]; then
|
||||
read_file change_count
|
||||
fi
|
||||
case "$flags" in
|
||||
count_invalid) printf '1x\n' ;;
|
||||
count_failed) printf '12\n'; return 1 ;;
|
||||
esac
|
||||
return
|
||||
fi
|
||||
[ "$1" = -l ] && [ "$3" = "$APP_DIR/drop-resolve.js" ] || return 1
|
||||
case "$4" in
|
||||
read-clip-files)
|
||||
if [ "$flags" = failed_file_probe ]; then return 1; fi
|
||||
if [ "$flags" = typed_files ]; then
|
||||
node "$PASTEBOARD_FIXTURE" "$3" read-clip-files
|
||||
else
|
||||
read_file local_value
|
||||
fi
|
||||
;;
|
||||
write-clip-files)
|
||||
[ "$6" = "$DROP_MOUNT" ] && [ "$(read_file "$5")" = "$get_value" ] || return 1
|
||||
echo write >> writes
|
||||
if [ "$flags" = typed_files ]; then
|
||||
node "$PASTEBOARD_FIXTURE" "$3" write-clip-files "$5" "$6" "$7" || return 1
|
||||
: > file_clip
|
||||
elif [ "$flags" = stale ] || { [ "$flags" = heal ] && [ ! -f mounts ]; }; then
|
||||
echo remount
|
||||
else
|
||||
printf 'file:///shared/item' > local_value
|
||||
: > file_clip
|
||||
bump_clipboard_count
|
||||
echo ok
|
||||
fi
|
||||
;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
;;
|
||||
'clipboard info')
|
||||
printf 'info\n' >> clip_work
|
||||
[ "$flags" != unreadable_clipboard ] || return 1
|
||||
if [ -f read_failure ]; then
|
||||
if [ -f probe_failed ]; then
|
||||
printf 'Unicode text\n'
|
||||
return 1
|
||||
elif [ -f file_clip ]; then
|
||||
printf '«class furl», Unicode text\n'
|
||||
elif [ -f read_failure ]; then
|
||||
case "$failure_kind" in
|
||||
png) printf 'PNGf\n' ;;
|
||||
tiff_*) printf 'TIFF\n' ;;
|
||||
@@ -255,6 +344,7 @@ osascript() {
|
||||
: > reencoded
|
||||
: > wrote_png
|
||||
bump_clipboard_count
|
||||
if [ "$flags" = probe_after_write ]; then : > probe_failed; fi
|
||||
;;
|
||||
esac
|
||||
}
|
||||
@@ -267,6 +357,7 @@ sips() {
|
||||
curl() {
|
||||
method=GET
|
||||
headers=""
|
||||
accept=""
|
||||
output=""
|
||||
base=""
|
||||
body=""
|
||||
@@ -280,6 +371,7 @@ curl() {
|
||||
-H)
|
||||
case "$2" in
|
||||
'X-Clip-Base-Seq: '*) base="$2" ;;
|
||||
'Accept: '*) accept="$2" ;;
|
||||
esac
|
||||
shift
|
||||
;;
|
||||
@@ -330,6 +422,16 @@ curl() {
|
||||
printf '%s' "$post_code"
|
||||
else
|
||||
printf '%s %s\n' "$method" "$url" >> calls
|
||||
if [ "$get_kind" = files ] && [ "$get_code" = 200 ] && [ "$flags" != ignore_since ]; then
|
||||
case "$url" in
|
||||
*"since=$get_hash&"*'&since_seq='*)
|
||||
if [ "${url##*&since_seq=}" = "$get_seq" ]; then get_code=304; fi ;;
|
||||
*"since=$get_hash&"*) get_code=304 ;;
|
||||
esac
|
||||
fi
|
||||
if [ "$flags" = legacy_host ] && [ "$accept" != 'Accept: image/png' ]; then
|
||||
case "$url" in *'&accept=image') ;; *) get_code=304 ;; esac
|
||||
fi
|
||||
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers"
|
||||
printf '%s' "$get_value" > "$output"
|
||||
if [ "$fail_during_get" = 1 ]; then
|
||||
@@ -339,15 +441,20 @@ curl() {
|
||||
elif [ "$flags" = guest_change ]; then
|
||||
printf C > local_value
|
||||
bump_clipboard_count
|
||||
elif [ "$flags" = inject_during_get ]; then
|
||||
elif [ "$flags" = inject_during_get ] || [ "$flags" = inject_get ]; then
|
||||
date +%s > "$INJECT_LOCK"
|
||||
printf injected > local_value
|
||||
if [ "$flags" = inject_during_get ]; then printf injected > local_value; fi
|
||||
elif [ "$flags" = drop_during_get ]; then
|
||||
: > "$DROP_INJECT_LOCK"
|
||||
printf injected > local_value
|
||||
fi
|
||||
case "$flags" in
|
||||
probe_after_get) : > probe_failed ;;
|
||||
recover_probe) rm -f probe_failed ;;
|
||||
inject_finishes_get) : > "$INJECT_LOCK.completed" ;;
|
||||
esac
|
||||
case "$flags:$url" in
|
||||
repeat_after_switch:*'?since=B&wait=2&accept=image') printf 304 ;;
|
||||
repeat_after_switch:*'?since=B&wait=2&accept=image,files') printf 304 ;;
|
||||
*) printf '%s' "$get_code" ;;
|
||||
esac
|
||||
fi
|
||||
@@ -378,13 +485,225 @@ methods() {
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
host_files_*|host_ignores_conditional_file_retry|guest_files_do_not_overwrite_host|foreign_drop_mount|probe_failure_after_files|failed_file_probe)
|
||||
if [ ! -f "$APP_DIR/drop-resolve.js" ]; then : > "$APP_DIR/drop-resolve.js"; fi
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$1" in
|
||||
host_files_sync_no_echo|host_files_reordered_readback)
|
||||
flags=typed_files
|
||||
get_kind=files
|
||||
get_value='{"drop_id":"host","items":["z file.txt","a#note.txt"]}'
|
||||
mkdir -p "$DROP_MOUNT/host"
|
||||
touch "$DROP_MOUNT/host/z file.txt" "$DROP_MOUNT/host/a#note.txt"
|
||||
if [ "$1" = host_files_reordered_readback ]; then : > test-reverse-file-readback; fi
|
||||
sync_clipboard
|
||||
if [ "$1" = host_files_reordered_readback ]; then
|
||||
expect "$last_server_hash/$last_server_seq/$file_retry_polls" /8/3
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
exit 0
|
||||
fi
|
||||
expect "$last_server_hash" B
|
||||
expect "$synced_local_cc/$synced_local_kind" 2/files
|
||||
expect "$(read_local_clipboard readback)" files
|
||||
expect "$(awk 'END {print NR}' readback)" 2
|
||||
expect "$(sed 's|^file://.*/drop_mount/host/||' readback)" 'z%20file.txt
|
||||
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'
|
||||
;;
|
||||
guest_files_do_not_overwrite_host)
|
||||
local_info="«class furl», Unicode text"
|
||||
last_local_hash=old
|
||||
get_code=304
|
||||
printf 11 > change_count
|
||||
expect "$(read_local_clipboard ./clip_in)" files
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET
|
||||
expect "$last_local_hash" files:A
|
||||
expect "$synced_local_cc/$synced_local_kind" 11/files
|
||||
;;
|
||||
host_files_remount_and_fail_no_spin)
|
||||
get_kind=files
|
||||
flags=heal
|
||||
sync_clipboard
|
||||
expect "$(paste -sd , writes)" write,write
|
||||
expect "$(paste -sd , mounts)" unmount,ensure
|
||||
expect "$last_local_hash" files:file:///shared/item
|
||||
flags=stale
|
||||
get_hash=C
|
||||
get_seq=9
|
||||
sync_clipboard
|
||||
expect "$(paste -sd , mounts)" unmount,ensure,unmount,ensure
|
||||
expect "$last_server_hash/$last_server_seq/$(cat local_value)" B/9/file:///shared/item
|
||||
for i in 1 2 3; do sync_clipboard; done
|
||||
expect "$(grep -Fc 'since=C&' calls)" 3
|
||||
expect "$(wc -l < writes | tr -d ' ')" 4
|
||||
expect "$(paste -sd , mounts)" unmount,ensure,unmount,ensure
|
||||
flags=""
|
||||
sync_clipboard
|
||||
expect "$(paste -sd , writes)" write,write,write,write,write
|
||||
expect "$last_server_hash/$last_server_seq/$last_local_hash" C/9/files:file:///shared/item
|
||||
expect "$(tail -n 1 calls)" 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=9'
|
||||
expect "$(methods)" GET,GET,GET,GET,GET,GET
|
||||
;;
|
||||
host_files_new_event_during_retry)
|
||||
get_kind=files
|
||||
flags=stale
|
||||
sync_clipboard
|
||||
expect "$last_server_hash" ""
|
||||
flags=""
|
||||
get_hash=C
|
||||
sync_clipboard
|
||||
expect "$last_server_hash/$last_local_hash" C/files:file:///shared/item
|
||||
expect "$(methods)" GET,GET
|
||||
;;
|
||||
host_files_retry_preserves_new_copy)
|
||||
get_kind=files
|
||||
flags=stale
|
||||
sync_clipboard
|
||||
expect "$last_local_hash/$last_server_hash" A/
|
||||
flags=""
|
||||
printf new > local_value
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,POST
|
||||
expect "$(read_file host_value)/$file_retry_polls" new/0
|
||||
;;
|
||||
host_ignores_conditional_file_retry)
|
||||
get_kind=files
|
||||
flags=stale
|
||||
sync_clipboard
|
||||
flags=ignore_since
|
||||
sleep() { expect "$1" 2; echo pause >> pauses; }
|
||||
for i in 1 2 3; do sync_clipboard; done
|
||||
expect "$(wc -l < pauses | tr -d ' ')" 3
|
||||
expect "$(paste -sd , writes)" write,write
|
||||
sync_clipboard
|
||||
expect "$last_server_hash/$last_local_hash" B/files:file:///shared/item
|
||||
;;
|
||||
foreign_drop_mount)
|
||||
printf foreign > mount_owner
|
||||
get_kind=files
|
||||
sync_clipboard
|
||||
expect "$(cat mount_owner)/$(cat mounts)" foreign/ensure
|
||||
[ ! -e writes ]
|
||||
expect "$last_server_hash/$(cat local_value)" /A
|
||||
;;
|
||||
probe_failure_after_files)
|
||||
get_kind=files
|
||||
printf 1 > change_count
|
||||
sync_clipboard
|
||||
expect "$last_local_hash" files:file:///shared/item
|
||||
bump_clipboard_count
|
||||
: > probe_failed
|
||||
get_code=304
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,GET
|
||||
expect "$last_local_hash/$last_server_hash" files:file:///shared/item/B
|
||||
expect "$synced_local_cc/$synced_local_kind" 2/files
|
||||
;;
|
||||
probe_failure_during_get|probe_failure_after_write|probe_recovers_during_get)
|
||||
last_local_hash=A
|
||||
last_server_hash=old
|
||||
case "$1" in
|
||||
probe_failure_during_get) flags=probe_after_get; want=A/A/old ;;
|
||||
probe_failure_after_write) flags=probe_after_write; want=B/A/B ;;
|
||||
probe_recovers_during_get) flags=recover_probe; : > probe_failed; want=B/B/B ;;
|
||||
esac
|
||||
sync_clipboard
|
||||
expect "$(cat local_value)/$last_local_hash/$last_server_hash" "$want"
|
||||
expect "$(methods)" GET
|
||||
;;
|
||||
failed_png_readback|new_guest_png_after_failed_readback)
|
||||
last_local_hash=A
|
||||
printf 1 > change_count
|
||||
get_kind=png
|
||||
get_hash=png:B
|
||||
flags=probe_after_write
|
||||
sync_clipboard
|
||||
expect "$last_local_hash/$last_server_hash" A/png:B
|
||||
rm -f probe_failed
|
||||
flags=""
|
||||
if [ "$1" = new_guest_png_after_failed_readback ]; then
|
||||
bump_clipboard_count
|
||||
printf C > local_value
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,POST
|
||||
expect "$(cat host_value)" C
|
||||
else
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,GET
|
||||
expect "$last_local_hash" png:B-reencoded
|
||||
fi
|
||||
;;
|
||||
failed_pbpaste_formats)
|
||||
flags=failed_pbpaste
|
||||
last_local_hash=A
|
||||
get_code=304
|
||||
for local_info in 'Unicode text' unknown; do
|
||||
expect "$(read_local_clipboard ./clip_in)" error
|
||||
sync_clipboard
|
||||
expect "$last_local_hash" A
|
||||
done
|
||||
expect "$(methods)" GET,GET
|
||||
;;
|
||||
failed_file_probe)
|
||||
local_info="«class furl», Unicode text"
|
||||
flags=failed_file_probe
|
||||
last_local_hash=previous
|
||||
get_code=304
|
||||
expect "$(read_local_clipboard ./clip_in)" error
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET
|
||||
expect "$last_local_hash" previous
|
||||
rm "$APP_DIR/drop-resolve.js"
|
||||
expect "$(read_local_clipboard ./clip_in)" empty
|
||||
;;
|
||||
legacy_host_png)
|
||||
flags=legacy_host
|
||||
get_kind=png
|
||||
get_hash=png:B
|
||||
sync_clipboard
|
||||
expect "$last_local_hash/$last_server_hash" png:B-reencoded/png:B
|
||||
grep -Fx 'GET http://stub/v1/clipboard?since=&wait=2&accept=image,files' calls
|
||||
;;
|
||||
injection_finishes_during_read)
|
||||
last_local_hash=A
|
||||
flags=inject_finish
|
||||
sync_clipboard
|
||||
expect "$(methods)" ""
|
||||
flags=""
|
||||
get_code=304
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET
|
||||
expect "$last_local_hash" A
|
||||
;;
|
||||
injection_during_read|injection_during_get|injection_finishes_during_get)
|
||||
if [ "$1" = injection_during_read ]; then
|
||||
last_local_hash=old
|
||||
flags=inject_read
|
||||
sync_clipboard
|
||||
expect "$(methods)" ""
|
||||
expect "$last_local_hash/$(cat local_value)" old/A
|
||||
else
|
||||
flags=inject_get
|
||||
if [ "$1" = injection_finishes_during_get ]; then flags=inject_finishes_get; fi
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET
|
||||
expect "$last_server_hash/$(cat local_value)" /A
|
||||
fi
|
||||
;;
|
||||
read_failure_*)
|
||||
failure_kind="${1#read_failure_}"
|
||||
get_code=304
|
||||
printf '11\n' > change_count
|
||||
: > read_failure
|
||||
sync_clipboard
|
||||
expect "$synced_local_cc/$last_local_hash" /empty
|
||||
expect "$synced_local_cc/$last_local_hash" /
|
||||
expect "$(methods)" GET
|
||||
rm read_failure
|
||||
case "$failure_kind" in
|
||||
@@ -434,7 +753,7 @@ case "$1" in
|
||||
;;
|
||||
info_failed_with_count)
|
||||
expect "$(paste -sd ',' clip_work)" info
|
||||
expect "$synced_local_cc/$last_local_hash" /empty
|
||||
expect "$synced_local_cc/$last_local_hash" /
|
||||
;;
|
||||
change_during_read)
|
||||
expect "$(paste -sd ',' clip_work)" info,sha
|
||||
@@ -668,7 +987,7 @@ case "$1" in
|
||||
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 "$(tail -n 1 calls)" 'GET http://stub/v1/clipboard?since=&wait=2&accept=image,files'
|
||||
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" B/B/9/B
|
||||
;;
|
||||
cold_guest_only|cold_304)
|
||||
@@ -711,13 +1030,13 @@ case "$1" in
|
||||
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'
|
||||
expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&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_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=9'
|
||||
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(read_file local_value)" B/B/10/B
|
||||
;;
|
||||
stale_lock)
|
||||
@@ -817,7 +1136,10 @@ case "$1" in
|
||||
last_local_hash=previous
|
||||
get_code=304
|
||||
sync_clipboard
|
||||
expect "$(read_local_clipboard ./clip_in)" empty
|
||||
case "$1" in
|
||||
unreadable_clipboard|failed_pbpaste) expect "$(read_local_clipboard ./clip_in)" error ;;
|
||||
*) expect "$(read_local_clipboard ./clip_in)" empty ;;
|
||||
esac
|
||||
expect "$(methods)" GET
|
||||
[ ! -f host_value ]
|
||||
if [ "$1" = empty_text_clipboard ]; then
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
|
||||
package guesttools
|
||||
|
||||
import "sync"
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type OSClipboard struct {
|
||||
mu sync.Mutex
|
||||
kind ClipKind
|
||||
data []byte
|
||||
seq uint32
|
||||
mu sync.Mutex
|
||||
kind ClipKind
|
||||
data []byte
|
||||
files []string
|
||||
seq uint32
|
||||
}
|
||||
|
||||
func (c *OSClipboard) SequenceNumber() uint32 {
|
||||
@@ -32,19 +36,21 @@ func (c *OSClipboard) WriteText(text string) error {
|
||||
}
|
||||
|
||||
func (c *OSClipboard) Read() (ClipPayload, error) {
|
||||
payload, _, err := c.readClipboard(true)
|
||||
payload, _, err := c.readClipboard(true, true)
|
||||
return payload, err
|
||||
}
|
||||
|
||||
func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
|
||||
func (c *OSClipboard) readClipboard(wantImage, wantFiles bool) (ClipPayload, uint32, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !wantImage && c.kind == ClipPNG {
|
||||
return ClipPayload{Kind: ClipEmpty}, c.seq, nil
|
||||
var content ClipPayload
|
||||
if wantImage || c.kind != ClipPNG {
|
||||
content = ClipPayload{Kind: c.kind, Data: slices.Clone(c.data)}
|
||||
}
|
||||
cp := make([]byte, len(c.data))
|
||||
copy(cp, c.data)
|
||||
return ClipPayload{Kind: c.kind, Data: cp}, c.seq, nil
|
||||
if wantFiles {
|
||||
content = withClipboardFiles(slices.Clone(c.files), content)
|
||||
}
|
||||
return content, c.seq, nil
|
||||
}
|
||||
|
||||
func (c *OSClipboard) WritePNG(pngBytes []byte) error {
|
||||
@@ -58,8 +64,16 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint
|
||||
if baseSeq != nil && c.seq != *baseSeq {
|
||||
return c.seq, errClipboardConflict
|
||||
}
|
||||
c.files = slices.Clone(payload.Files)
|
||||
if payload.Kind == ClipFiles {
|
||||
content := ClipPayload{}
|
||||
if payload.companion != nil {
|
||||
content = *payload.companion
|
||||
}
|
||||
payload = content
|
||||
}
|
||||
c.kind = payload.Kind
|
||||
c.data = append([]byte(nil), payload.Data...)
|
||||
c.data = slices.Clone(payload.Data)
|
||||
c.seq++
|
||||
return c.seq, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClipboardFilesRejectRedirectedAncestor(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
parent := filepath.Join(dir, "parent")
|
||||
folder := filepath.Join(parent, "nested", "folder")
|
||||
if err := os.MkdirAll(folder, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(folder, "copied.txt")
|
||||
if err := os.WriteFile(file, []byte("copied"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := []string{file, folder}
|
||||
entries := prepareClipboardFiles(paths)
|
||||
fsys := &dropWebDAVFS{store: newDropShareStore(), allowClipboard: func() bool { return true }}
|
||||
if len(entries) != len(paths) || !fsys.store.ensure("clip", entries) {
|
||||
t.Fatalf("initial clipboard entries: %+v", entries)
|
||||
}
|
||||
|
||||
// Point a higher ancestor at the very same objects. Leaf identity and
|
||||
// metadata still match the original selection.
|
||||
saved := filepath.Join(dir, "saved")
|
||||
if err := os.Rename(parent, saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
makeSharedTestLink(t, saved, parent)
|
||||
if data, err := os.ReadFile(file); err != nil || string(data) != "copied" {
|
||||
t.Fatalf("redirected test file: %q, %v", data, err)
|
||||
}
|
||||
if got := prepareClipboardFiles(paths); len(got) != 0 {
|
||||
t.Errorf("clipboard accepted redirected paths: %+v", got)
|
||||
}
|
||||
list, err := fsys.OpenFile(t.Context(), "/clip", os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer list.Close()
|
||||
if entries, err := list.Readdir(-1); err != nil || len(entries) != 0 {
|
||||
t.Errorf("redirected entries in WebDAV listing: %v, %v", entries, err)
|
||||
}
|
||||
for _, rel := range []string{"copied.txt", "folder", "folder/copied.txt"} {
|
||||
if _, err := fsys.Stat(t.Context(), "/clip/"+rel); !errors.Is(err, os.ErrPermission) {
|
||||
t.Errorf("WebDAV Stat(%q): %v", rel, err)
|
||||
}
|
||||
resp := httptest.NewRecorder()
|
||||
serveDropFile(fsys, resp, httptest.NewRequest(http.MethodGet, "/", nil), "clip", rel)
|
||||
if resp.Code != http.StatusForbidden {
|
||||
t.Errorf("direct read %q: %d %q", rel, resp.Code, resp.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestClipboardFilesRequireLocalDrive(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "copied.txt")
|
||||
if err := os.WriteFile(file, []byte("local"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := clipboardDriveType
|
||||
t.Cleanup(func() { clipboardDriveType = original })
|
||||
root := filepath.VolumeName(file) + string(os.PathSeparator)
|
||||
driveType := uint32(windows.DRIVE_FIXED)
|
||||
clipboardDriveType = func(rootPtr *uint16) uint32 {
|
||||
if got := windows.UTF16PtrToString(rootPtr); got != root {
|
||||
t.Fatalf("GetDriveType root = %q, want %q", got, root)
|
||||
}
|
||||
return driveType
|
||||
}
|
||||
paths := []string{file}
|
||||
fsys := &dropWebDAVFS{store: newDropShareStore(), allowClipboard: func() bool { return true }}
|
||||
if !fsys.store.ensure("clip", prepareClipboardFiles(paths)) {
|
||||
t.Fatal("local clipboard registration failed")
|
||||
}
|
||||
for _, driveType = range []uint32{windows.DRIVE_FIXED, windows.DRIVE_REMOVABLE, windows.DRIVE_RAMDISK, windows.DRIVE_CDROM} {
|
||||
if len(prepareClipboardFiles(paths)) != 1 {
|
||||
t.Errorf("local drive type %d was filtered out", driveType)
|
||||
}
|
||||
}
|
||||
for _, driveType = range []uint32{windows.DRIVE_REMOTE, windows.DRIVE_UNKNOWN, windows.DRIVE_NO_ROOT_DIR} {
|
||||
if len(prepareClipboardFiles(paths)) != 0 {
|
||||
t.Errorf("drive type %d was accepted", driveType)
|
||||
}
|
||||
if _, err := fsys.Stat(t.Context(), "/clip/copied.txt"); !errors.Is(err, os.ErrPermission) {
|
||||
t.Errorf("read previously local file on drive type %d: %v", driveType, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,16 @@ package guesttools
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -261,7 +266,7 @@ type clipboardReadFailure struct {
|
||||
writeErr error
|
||||
}
|
||||
|
||||
func (c *clipboardReadFailure) readClipboard(bool) (ClipPayload, uint32, error) {
|
||||
func (c *clipboardReadFailure) readClipboard(bool, bool) (ClipPayload, uint32, error) {
|
||||
return ClipPayload{}, 0, errors.New("OpenClipboard failed")
|
||||
}
|
||||
|
||||
@@ -405,3 +410,223 @@ func TestClipboardPOSTTextLimitAndEmptyOverwrite(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardGETFilesZeroCopyWebDAV(t *testing.T) {
|
||||
first := filepath.Join(t.TempDir(), "a.txt")
|
||||
second := filepath.Join(t.TempDir(), "a.txt")
|
||||
folder := filepath.Join(t.TempDir(), "MyFolder")
|
||||
if err := os.Mkdir(folder, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for path, contents := range map[string]string{
|
||||
first: "first", second: "second", filepath.Join(folder, "sub.txt"): "nested",
|
||||
} {
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
paths := []string{first, second, folder, `\\server\share\x.txt`}
|
||||
link := filepath.Join(t.TempDir(), "link.txt")
|
||||
if err := os.Symlink(first, link); err == nil {
|
||||
paths = append(paths, link)
|
||||
}
|
||||
clip := &memClipboard{}
|
||||
clip.WriteFiles(paths)
|
||||
srv := NewServer(clip)
|
||||
shared := t.TempDir()
|
||||
srv.RegisterVM(VMConfig{VMName: "mac", Token: "guest", SharedDir: shared})
|
||||
get := func(path string, handler http.HandlerFunc) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.SetBasicAuth("mac", "guest")
|
||||
resp := httptest.NewRecorder()
|
||||
handler(resp, req)
|
||||
return resp
|
||||
}
|
||||
checkPing := func(want bool) {
|
||||
t.Helper()
|
||||
resp := get("/v1/ping", srv.handlePing)
|
||||
var ping struct {
|
||||
Capabilities []string `json:"capabilities"`
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &ping); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Code != http.StatusOK || slices.Contains(ping.Capabilities, "clipboard-files") != want {
|
||||
t.Fatalf("ping status %d, capabilities %v, want clipboard-files=%t", resp.Code, ping.Capabilities, want)
|
||||
}
|
||||
}
|
||||
policy := DefaultClipboardPolicy()
|
||||
policy.Enabled = true
|
||||
srv.SetGlobalClipboardPolicy(policy)
|
||||
checkPing(true)
|
||||
resp := get("/v1/clipboard?accept=image", srv.handleClipboard)
|
||||
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Kind") == "files" {
|
||||
t.Fatalf("legacy GET: %d %v %q", resp.Code, resp.Header(), resp.Body.String())
|
||||
}
|
||||
const endpoint = "/v1/clipboard?accept=image,files"
|
||||
resp = get(endpoint, srv.handleClipboard)
|
||||
if resp.Code != http.StatusOK || resp.Header().Get("X-Clip-Kind") != "files" || resp.Header().Get("Content-Type") != "application/json" {
|
||||
t.Fatalf("files GET: %d %v", resp.Code, resp.Header())
|
||||
}
|
||||
var manifest struct {
|
||||
DropID string `json:"drop_id"`
|
||||
Items []string `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := resp.Header().Get("X-Clip-Hash")
|
||||
if len(hash) != 64 || manifest.DropID != "clip-"+hash[:16] || !slices.Equal(manifest.Items, []string{"a.txt", "a (1).txt", "MyFolder"}) {
|
||||
t.Fatalf("unexpected hash %q or manifest %+v", hash, manifest)
|
||||
}
|
||||
for item, want := range map[string]string{"a.txt": "first", "a (1).txt": "second", "MyFolder/sub.txt": "nested"} {
|
||||
path := url.URL{Path: "/dav-drop/mac/" + manifest.DropID + "/" + item}
|
||||
resp := get(path.EscapedPath(), srv.handleDropWebDAV)
|
||||
if resp.Code != http.StatusOK || resp.Body.String() != want {
|
||||
t.Fatalf("GET %s: %d %q, want %q", item, resp.Code, resp.Body.String(), want)
|
||||
}
|
||||
}
|
||||
if files, err := os.ReadDir(shared); err != nil || len(files) != 0 {
|
||||
t.Fatalf("SharedDir contains %v, err=%v", files, err)
|
||||
}
|
||||
vm := srv.vms[vmRegistryKey("", "mac")]
|
||||
before := vm.dropShares.modTime
|
||||
resp = get(endpoint+"&since="+hash, srv.handleClipboard)
|
||||
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != hash ||
|
||||
resp.Header().Get("X-Clip-Kind") != "files" || !vm.dropShares.modTime.Equal(before) {
|
||||
t.Fatalf("conditional GET: %d %v, modTime %v (was %v)", resp.Code, resp.Header(), vm.dropShares.modTime, before)
|
||||
}
|
||||
policy.Direction = ClipboardGuestToHost
|
||||
srv.SetGlobalClipboardPolicy(policy)
|
||||
checkPing(false)
|
||||
if resp := get(endpoint, srv.handleClipboard); resp.Code != http.StatusNoContent || resp.Body.Len() != 0 {
|
||||
t.Fatalf("guest-to-host GET: %d %q", resp.Code, resp.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardFileCopyEventIdentity(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "a.txt")
|
||||
writeFile := func(contents string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(file, []byte(contents), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeFile("original")
|
||||
clip := &memClipboard{seq: 9}
|
||||
srv := newClipboardTestServer(clip)
|
||||
store := srv.vms[vmRegistryKey("", "clipboard-test")].dropShares
|
||||
poll := func(since string) *httptest.ResponseRecorder {
|
||||
return clipboardRequest(t, srv, http.MethodGet, "?accept=files&since="+since, "", "", nil)
|
||||
}
|
||||
copyAndRead := func(previousHash, wantSeq, wantContents string) (string, string) {
|
||||
t.Helper()
|
||||
clip.WriteFiles([]string{file})
|
||||
resp := poll(previousHash)
|
||||
hash := resp.Header().Get("X-Clip-Hash")
|
||||
if resp.Code != http.StatusOK || hash == "" || hash == previousHash || resp.Header().Get("X-Clip-Seq") != wantSeq {
|
||||
t.Fatalf("new copy: %d %v %s", resp.Code, resp.Header(), resp.Body)
|
||||
}
|
||||
var manifest struct {
|
||||
DropID string `json:"drop_id"`
|
||||
Items []string `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &manifest); err != nil || !slices.Equal(manifest.Items, []string{"a.txt"}) {
|
||||
t.Fatalf("manifest %q, err=%v", resp.Body, err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/dav-drop/clipboard-test/"+manifest.DropID+"/a.txt", nil)
|
||||
req.Header.Set("Authorization", "Bearer clipboard-test-token")
|
||||
dav := httptest.NewRecorder()
|
||||
srv.handleDropWebDAV(dav, req)
|
||||
if dav.Code != http.StatusOK || dav.Body.String() != wantContents {
|
||||
t.Fatalf("GET %s: %d %q, want %q", req.URL, dav.Code, dav.Body, wantContents)
|
||||
}
|
||||
return hash, manifest.DropID
|
||||
}
|
||||
|
||||
hash, id := copyAndRead("", "10", "original")
|
||||
// A Finder copy can replace the guest clipboard without changing the
|
||||
// last host hash that the guest sends in its next conditional poll.
|
||||
nextHash, nextID := copyAndRead(hash, "11", "original")
|
||||
if nextID == id {
|
||||
t.Fatal("copying the unchanged file again reused its WebDAV URL")
|
||||
}
|
||||
modTime := store.modTime
|
||||
writeFile("edited on disk")
|
||||
for range 3 {
|
||||
resp := poll(nextHash)
|
||||
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != nextHash ||
|
||||
resp.Header().Get("X-Clip-Seq") != "11" || !store.modTime.Equal(modTime) {
|
||||
t.Fatalf("disk edit without copy: %d %v, root modTime %v (was %v)", resp.Code, resp.Header(), store.modTime, modTime)
|
||||
}
|
||||
}
|
||||
_, editedID := copyAndRead(nextHash, "12", "edited on disk")
|
||||
if editedID == nextID || editedID == id {
|
||||
t.Fatal("copying the edited file reused a cached WebDAV URL")
|
||||
}
|
||||
}
|
||||
|
||||
type fileClipboardSnapshot struct {
|
||||
*memClipboard
|
||||
payload ClipPayload
|
||||
reads int
|
||||
}
|
||||
|
||||
func (c *fileClipboardSnapshot) readClipboard(bool, bool) (ClipPayload, uint32, error) {
|
||||
c.reads++
|
||||
return c.payload, 23, nil
|
||||
}
|
||||
|
||||
func TestClipboardGETFilteredFileCompanion(t *testing.T) {
|
||||
text := ClipPayload{Kind: ClipText, Data: []byte("copied caption")}
|
||||
image := ClipPayload{Kind: ClipPNG, Data: makeSamplePNG(t, 1, 2, 3)}
|
||||
blocked := []string{`\\server\share\file.txt`}
|
||||
local := filepath.Join(t.TempDir(), "local.txt")
|
||||
if err := os.WriteFile(local, []byte("local"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
overflow := slices.Repeat([]string{local}, MaxClipboardFiles+1)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
paths []string
|
||||
companion ClipPayload
|
||||
accept string
|
||||
maxImage int
|
||||
want ClipKind
|
||||
}{
|
||||
{"filtered with text", blocked, text, "files", 0, ClipText},
|
||||
{"overflow with text", overflow, text, "files", 0, ClipText},
|
||||
{"filtered with PNG", blocked, image, "files,image", len(image.Data), ClipPNG},
|
||||
{"PNG not requested", blocked, image, "files", 0, ClipEmpty},
|
||||
{"PNG over policy limit", blocked, image, "files,image", len(image.Data) - 1, ClipEmpty},
|
||||
{"v13 guest requests only the companion PNG", []string{local}, image, "image", len(image.Data), ClipPNG},
|
||||
{"valid file takes priority", []string{local}, text, "files", 0, ClipFiles},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
clip := &fileClipboardSnapshot{memClipboard: &memClipboard{}, payload: withClipboardFiles(tc.paths, tc.companion)}
|
||||
srv := newClipboardTestServer(clip)
|
||||
policy := DefaultClipboardPolicy()
|
||||
policy.MaxImageBytes = tc.maxImage
|
||||
srv.SetVMClipboardPolicy("clipboard-test", &policy)
|
||||
resp := clipboardRequest(t, srv, http.MethodGet, "?accept="+tc.accept, "", "", nil)
|
||||
if clip.reads != 1 || resp.Header().Get("X-Clip-Seq") != "23" {
|
||||
t.Fatalf("clipboard reads=%d, headers %v", clip.reads, resp.Header())
|
||||
}
|
||||
if tc.want == ClipEmpty {
|
||||
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 {
|
||||
t.Fatalf("unavailable companion: %d %q", resp.Code, resp.Body)
|
||||
}
|
||||
} else if resp.Code != http.StatusOK || resp.Header().Get("X-Clip-Kind") != string(tc.want) {
|
||||
t.Fatalf("GET: %d %v", resp.Code, resp.Header())
|
||||
} else if tc.want != ClipFiles && (!bytes.Equal(resp.Body.Bytes(), tc.companion.Data) || resp.Header().Get("X-Clip-Hash") != payloadHash(tc.companion)) {
|
||||
t.Fatalf("companion: %v %q", resp.Header(), resp.Body)
|
||||
}
|
||||
if tc.want == ClipPNG && resp.Header().Get("Content-Type") != "image/png" {
|
||||
t.Fatalf("PNG response has content type %q", resp.Header().Get("Content-Type"))
|
||||
}
|
||||
if tc.want != ClipFiles && len(srv.vms[vmRegistryKey("", "clipboard-test")].dropShares.records) != 0 {
|
||||
t.Fatal("filtered selection created a file share")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,19 @@ package guesttools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -53,12 +57,14 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
cfDIB = 8
|
||||
cfUnicodeText = 13
|
||||
gmemMoveable = 0x0002
|
||||
hwndMessage = ^uintptr(2)
|
||||
wmClipJob = 0x8000 // WM_APP
|
||||
maxDIBBytes = 128 << 20
|
||||
cfDIB = 8
|
||||
cfUnicodeText = 13
|
||||
cfHDrop = 15
|
||||
maxDropFilesBytes = 1 << 20
|
||||
gmemMoveable = 0x0002
|
||||
hwndMessage = ^uintptr(2)
|
||||
wmClipJob = 0x8000 // WM_APP
|
||||
maxDIBBytes = 128 << 20
|
||||
)
|
||||
|
||||
type OSClipboard struct {
|
||||
@@ -70,8 +76,10 @@ type clipboardCache struct {
|
||||
valid bool
|
||||
seq uint32
|
||||
hasImage bool
|
||||
hasFiles bool
|
||||
payload ClipPayload
|
||||
hash string
|
||||
files []string
|
||||
}
|
||||
|
||||
type clipboardWindowMessage struct {
|
||||
@@ -185,7 +193,7 @@ func unlockClipboardMem(h uintptr) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func readClipboardImageLocked(format uintptr, maxBytes int) ([]byte, bool, error) {
|
||||
func readClipboardBytesLocked(format uintptr, maxBytes int) ([]byte, bool, error) {
|
||||
h, _, _ := procGetClipboardData.Call(format)
|
||||
if h == 0 {
|
||||
return nil, true, nil
|
||||
@@ -253,11 +261,59 @@ func (*OSClipboard) ReadText() (string, error) {
|
||||
}
|
||||
|
||||
type clipboardSnapshot struct {
|
||||
files []string
|
||||
text []uint16
|
||||
png []byte // Validated before the snapshot is returned to the cache.
|
||||
dib []byte
|
||||
kind ClipKind
|
||||
imageReadFailed bool
|
||||
fileReadFailed bool
|
||||
}
|
||||
|
||||
func parseDropFilesBytes(raw []byte) []string {
|
||||
if len(raw) < 20 || len(raw) > maxDropFilesBytes {
|
||||
return nil
|
||||
}
|
||||
offset := binary.LittleEndian.Uint32(raw)
|
||||
if offset < 20 || uint64(offset) >= uint64(len(raw)) {
|
||||
return nil
|
||||
}
|
||||
width := 1
|
||||
if binary.LittleEndian.Uint32(raw[16:]) != 0 {
|
||||
width = 2
|
||||
}
|
||||
data := raw[offset:]
|
||||
var files []string
|
||||
start := 0
|
||||
for i := 0; i+width <= len(data); i += width {
|
||||
if data[i] != 0 || (width == 2 && data[i+1] != 0) {
|
||||
continue
|
||||
}
|
||||
if start == i {
|
||||
return files // Empty name after the final NUL-terminated path.
|
||||
}
|
||||
if len(files) == MaxClipboardFiles {
|
||||
return nil
|
||||
}
|
||||
name := data[start:i]
|
||||
words := make([]uint16, len(name)/width)
|
||||
if width == 2 {
|
||||
for j := range words {
|
||||
words[j] = binary.LittleEndian.Uint16(name[2*j:])
|
||||
}
|
||||
} else {
|
||||
const cpACP = 0
|
||||
const mbErrInvalidChars = 0x8
|
||||
n, err := windows.MultiByteToWideChar(cpACP, mbErrInvalidChars, &name[0], int32(len(name)), &words[0], int32(len(words)))
|
||||
if err != nil || n == 0 {
|
||||
return nil
|
||||
}
|
||||
words = words[:n]
|
||||
}
|
||||
files = append(files, string(utf16.Decode(words)))
|
||||
start = i + width
|
||||
}
|
||||
return nil // A partial final path or missing list terminator invalidates the selection.
|
||||
}
|
||||
|
||||
func (snap clipboardSnapshot) payload() ClipPayload {
|
||||
@@ -304,39 +360,52 @@ func (snap *clipboardSnapshot) readDIBLocked(wantImage bool, available func(uint
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image.
|
||||
// Read inspects the Windows clipboard and returns file paths, UTF-8 text, or a PNG image.
|
||||
func (c *OSClipboard) Read() (ClipPayload, error) {
|
||||
payload, _, err := c.readClipboard(true)
|
||||
payload, _, err := c.readClipboard(true, true)
|
||||
return payload, err
|
||||
}
|
||||
|
||||
func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
|
||||
return c.cache.read(wantImage, c.SequenceNumber, c.readClipboardSnapshot)
|
||||
func (c *OSClipboard) readClipboard(wantImage, wantFiles bool) (ClipPayload, uint32, error) {
|
||||
return c.cache.read(wantImage, wantFiles, c.SequenceNumber, c.readClipboardSnapshot)
|
||||
}
|
||||
|
||||
func (c *OSClipboard) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) {
|
||||
return c.cache.readForSync(wantImage, c.SequenceNumber, c.readClipboardSnapshot, payloadHash)
|
||||
func (c *OSClipboard) readClipboardForSync(wantImage, wantFiles bool) (ClipPayload, uint32, string, error) {
|
||||
return c.cache.readForSync(wantImage, wantFiles, c.SequenceNumber, c.readClipboardSnapshot, payloadHash)
|
||||
}
|
||||
|
||||
func (c *clipboardCache) read(wantImage bool, sequence func() uint32, readSnapshot func(bool) (clipboardSnapshot, uint32, error)) (ClipPayload, uint32, error) {
|
||||
payload, seq, _, err := c.readForSync(wantImage, sequence, readSnapshot, payloadHash)
|
||||
func (c *clipboardCache) read(wantImage, wantFiles bool, sequence func() uint32, readSnapshot func(bool, bool) (clipboardSnapshot, uint32, error)) (ClipPayload, uint32, error) {
|
||||
payload, seq, _, err := c.readForSync(wantImage, wantFiles, sequence, readSnapshot, payloadHash)
|
||||
payload.Data = bytes.Clone(payload.Data)
|
||||
payload.Files = slices.Clone(payload.Files)
|
||||
if payload.companion != nil {
|
||||
companion := *payload.companion
|
||||
companion.Data = bytes.Clone(companion.Data)
|
||||
payload.companion = &companion
|
||||
}
|
||||
return payload, seq, err
|
||||
}
|
||||
|
||||
func (c *clipboardCache) readForSync(wantImage bool, sequence func() uint32, readSnapshot func(bool) (clipboardSnapshot, uint32, error), hashPayload func(ClipPayload) string) (ClipPayload, uint32, string, error) {
|
||||
func (c *clipboardCache) readForSync(wantImage, wantFiles bool, sequence func() uint32, readSnapshot func(bool, bool) (clipboardSnapshot, uint32, error), hashPayload func(ClipPayload) string) (ClipPayload, uint32, string, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
curSeq := sequence()
|
||||
if curSeq != 0 && c.valid && c.seq == curSeq && (c.hasImage || !wantImage) {
|
||||
if !wantImage && c.payload.Kind == ClipPNG {
|
||||
return ClipPayload{Kind: ClipEmpty}, curSeq, "", nil
|
||||
if curSeq != 0 && c.valid && c.seq == curSeq && (c.hasImage || !wantImage) && (c.hasFiles || !wantFiles) {
|
||||
payload, hash := c.payload, c.hash
|
||||
if !wantImage && payload.Kind == ClipPNG {
|
||||
payload, hash = ClipPayload{}, ""
|
||||
}
|
||||
return c.payload, curSeq, c.hash, nil
|
||||
if wantFiles {
|
||||
payload = withClipboardFiles(c.files, payload)
|
||||
}
|
||||
return payload, curSeq, hash, nil
|
||||
}
|
||||
|
||||
snap, seq, err := readSnapshot(wantImage)
|
||||
snap, seq, err := readSnapshot(wantImage, wantFiles)
|
||||
if err != nil {
|
||||
if len(snap.files) > 0 {
|
||||
return withClipboardFiles(snap.files, ClipPayload{}), seq, "", nil
|
||||
}
|
||||
return ClipPayload{}, seq, "", err
|
||||
}
|
||||
payload := snap.payload()
|
||||
@@ -344,17 +413,26 @@ func (c *clipboardCache) readForSync(wantImage bool, sequence func() uint32, rea
|
||||
if payload.Kind != ClipEmpty {
|
||||
hash = hashPayload(payload)
|
||||
}
|
||||
if !(payload.Kind == ClipEmpty && snap.imageReadFailed) && seq != 0 && seq == sequence() {
|
||||
if !(payload.Kind == ClipEmpty && snap.imageReadFailed) && !snap.fileReadFailed && seq != 0 && seq == sequence() {
|
||||
// A guest requesting only files should not evict an already validated
|
||||
// PNG. Keep coverage for both formats within the same generation.
|
||||
sameGeneration := c.valid && c.seq == seq
|
||||
if !sameGeneration || wantImage || !c.hasImage {
|
||||
c.hasImage = wantImage
|
||||
c.payload = payload
|
||||
c.hash = hash
|
||||
}
|
||||
if !sameGeneration || wantFiles {
|
||||
c.hasFiles = wantFiles
|
||||
c.files = snap.files
|
||||
}
|
||||
c.valid = true
|
||||
c.seq = seq
|
||||
c.hasImage = wantImage
|
||||
c.payload = payload
|
||||
c.hash = hash
|
||||
}
|
||||
return payload, seq, hash, nil
|
||||
return withClipboardFiles(snap.files, payload), seq, hash, nil
|
||||
}
|
||||
|
||||
func (c *OSClipboard) readClipboardSnapshot(wantImage bool) (clipboardSnapshot, uint32, error) {
|
||||
func (c *OSClipboard) readClipboardSnapshot(wantImage, wantFiles bool) (clipboardSnapshot, uint32, error) {
|
||||
pngFormat, _ := registerPNGFormat()
|
||||
reader := clipboardSnapshotReader{
|
||||
withClipboard: func(read func() error) error {
|
||||
@@ -368,9 +446,9 @@ func (c *OSClipboard) readClipboardSnapshot(wantImage bool) (clipboardSnapshot,
|
||||
return available != 0
|
||||
},
|
||||
readText: readUnicodeTextLocked,
|
||||
readImage: readClipboardImageLocked,
|
||||
readBytes: readClipboardBytesLocked,
|
||||
}
|
||||
return reader.read(wantImage, pngFormat)
|
||||
return reader.read(wantImage, wantFiles, pngFormat)
|
||||
}
|
||||
|
||||
type clipboardSnapshotReader struct {
|
||||
@@ -378,14 +456,22 @@ type clipboardSnapshotReader struct {
|
||||
sequence func() uint32
|
||||
available func(uintptr) bool
|
||||
readText func() ([]uint16, error)
|
||||
readImage func(uintptr, int) ([]byte, bool, error)
|
||||
readBytes func(uintptr, int) ([]byte, bool, error)
|
||||
}
|
||||
|
||||
func (r clipboardSnapshotReader) read(wantImage bool, pngFormat uintptr) (clipboardSnapshot, uint32, error) {
|
||||
func (r clipboardSnapshotReader) read(wantImage, wantFiles bool, pngFormat uintptr) (clipboardSnapshot, uint32, error) {
|
||||
var snap clipboardSnapshot
|
||||
var seq uint32
|
||||
err := r.withClipboard(func() error {
|
||||
defer func() { seq = r.sequence() }()
|
||||
if wantFiles && r.available(cfHDrop) {
|
||||
raw, failed, err := r.readBytes(cfHDrop, maxDropFilesBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
snap.files = parseDropFilesBytes(raw)
|
||||
snap.fileReadFailed = failed
|
||||
}
|
||||
if r.available(cfUnicodeText) {
|
||||
var err error
|
||||
snap.text, err = r.readText()
|
||||
@@ -397,7 +483,7 @@ func (r clipboardSnapshotReader) read(wantImage bool, pngFormat uintptr) (clipbo
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return snap.readImagesLocked(wantImage, pngFormat, r.available, r.readImage)
|
||||
return snap.readImagesLocked(wantImage, pngFormat, r.available, r.readBytes)
|
||||
})
|
||||
if err != nil || len(snap.png) == 0 {
|
||||
return snap, seq, err
|
||||
@@ -420,7 +506,7 @@ func (r clipboardSnapshotReader) read(wantImage bool, pngFormat uintptr) (clipbo
|
||||
return nil
|
||||
}
|
||||
defer func() { seq = r.sequence() }()
|
||||
return snap.readDIBLocked(true, r.available, r.readImage)
|
||||
return snap.readDIBLocked(true, r.available, r.readBytes)
|
||||
})
|
||||
return snap, seq, err
|
||||
}
|
||||
@@ -563,6 +649,7 @@ func (c *clipboardCache) updateAfterWrite(payload ClipPayload, seq uint32, err e
|
||||
c.valid = false
|
||||
c.payload = ClipPayload{}
|
||||
c.hash = ""
|
||||
c.files = nil
|
||||
if err != nil || payload.Kind != ClipPNG || seq == 0 || seq != sequence() {
|
||||
return
|
||||
}
|
||||
@@ -572,6 +659,7 @@ func (c *clipboardCache) updateAfterWrite(payload ClipPayload, seq uint32, err e
|
||||
c.hash = payloadHash(c.payload)
|
||||
c.seq = seq
|
||||
c.hasImage = true
|
||||
c.hasFiles = true
|
||||
c.valid = true
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,12 @@ import (
|
||||
"image/png"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
@@ -132,12 +135,12 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) {
|
||||
return (format == cfUnicodeText && tc.fixture.text != nil) || images[format] != nil
|
||||
},
|
||||
readText: func() ([]uint16, error) { return tc.fixture.text, nil },
|
||||
readImage: func(format uintptr, _ int) ([]byte, bool, error) {
|
||||
readBytes: func(format uintptr, _ int) ([]byte, bool, error) {
|
||||
formats = append(formats, format)
|
||||
return images[format], false, nil
|
||||
},
|
||||
}
|
||||
snap, snapSeq, err := reader.read(true, pngFormat)
|
||||
snap, snapSeq, err := reader.read(true, false, pngFormat)
|
||||
if err != nil || snapSeq != initialSeq || snap.imageReadFailed != tc.replace {
|
||||
t.Fatalf("snapshot sequence %d, image read failed %t, error %v", snapSeq, snap.imageReadFailed, err)
|
||||
}
|
||||
@@ -166,7 +169,7 @@ func TestWindowsClipboardReadUsesSequenceCache(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reads := 0
|
||||
readSnapshot := func(wantImage bool) (clipboardSnapshot, uint32, error) {
|
||||
readSnapshot := func(wantImage, _ bool) (clipboardSnapshot, uint32, error) {
|
||||
reads++
|
||||
if !wantImage {
|
||||
return clipboardSnapshot{kind: ClipEmpty}, seq, nil
|
||||
@@ -188,7 +191,7 @@ func TestWindowsClipboardReadUsesSequenceCache(t *testing.T) {
|
||||
{0, true, 5},
|
||||
} {
|
||||
seq = tc.seq
|
||||
got, gotSeq, err := cache.read(tc.wantImage, sequence, readSnapshot)
|
||||
got, gotSeq, err := cache.read(tc.wantImage, false, 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)
|
||||
}
|
||||
@@ -212,13 +215,20 @@ type windowsClipboardSyncFixture struct {
|
||||
lastPayload ClipPayload
|
||||
}
|
||||
|
||||
func (c *windowsClipboardSyncFixture) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) {
|
||||
payload, seq, hash, err := c.cache.readForSync(wantImage, func() uint32 {
|
||||
func (c *windowsClipboardSyncFixture) readClipboardForSync(wantImage, wantFiles bool) (ClipPayload, uint32, string, error) {
|
||||
payload, seq, hash, err := c.cache.readForSync(wantImage, wantFiles, func() uint32 {
|
||||
c.sequenceChecks++
|
||||
return c.SequenceNumber()
|
||||
}, func(bool) (clipboardSnapshot, uint32, error) {
|
||||
}, func(wantImage, wantFiles bool) (clipboardSnapshot, uint32, error) {
|
||||
c.reads++
|
||||
return c.snapshot, c.SequenceNumber(), nil
|
||||
snap := c.snapshot
|
||||
if !wantFiles {
|
||||
snap.files = nil
|
||||
}
|
||||
if !wantImage {
|
||||
snap.png, snap.dib = nil, nil
|
||||
}
|
||||
return snap, c.SequenceNumber(), nil
|
||||
}, func(payload ClipPayload) string {
|
||||
c.hashes++
|
||||
return payloadHash(payload)
|
||||
@@ -337,6 +347,39 @@ func TestWindowsClipboardGETUsesWrittenPNGCache(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsClipboardGETReusesFileCompanion(t *testing.T) {
|
||||
pixels := makeSamplePNG(t, 1, 2, 3)
|
||||
clip := &windowsClipboardSyncFixture{
|
||||
memClipboard: &memClipboard{seq: 7},
|
||||
snapshot: clipboardSnapshot{files: []string{`\\server\share\blocked.txt`}, png: pixels},
|
||||
}
|
||||
srv := newClipboardTestServer(clip)
|
||||
imageHash := payloadHash(ClipPayload{Kind: ClipPNG, Data: pixels})
|
||||
for _, tc := range []struct {
|
||||
accept string
|
||||
wantReads int
|
||||
wantStatus int
|
||||
}{
|
||||
{"image", 1, http.StatusOK},
|
||||
{"files", 2, http.StatusNotModified},
|
||||
{"files,image", 2, http.StatusOK},
|
||||
{"image", 2, http.StatusOK},
|
||||
} {
|
||||
resp := clipboardRequest(t, srv, http.MethodGet, "?accept="+tc.accept, "", "", nil)
|
||||
if resp.Code != tc.wantStatus || resp.Header().Get("X-Clip-Seq") != "7" ||
|
||||
clip.reads != tc.wantReads || clip.hashes != 1 {
|
||||
t.Fatalf("accept=%s: %d %v, %d reads, %d hashes", tc.accept, resp.Code, resp.Header(), clip.reads, clip.hashes)
|
||||
}
|
||||
if tc.wantStatus == http.StatusOK {
|
||||
if resp.Header().Get("X-Clip-Hash") != imageHash || !bytes.Equal(resp.Body.Bytes(), pixels) {
|
||||
t.Fatalf("accept=%s: unexpected image response %v", tc.accept, resp.Header())
|
||||
}
|
||||
} else if resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Hash") != "" {
|
||||
t.Fatalf("accept=%s: image leaked in %v %x", tc.accept, resp.Header(), resp.Body.Bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsClipboardSequenceAfterWrite(t *testing.T) {
|
||||
const hwnd = 1
|
||||
pixels := makeSamplePNG(t, 1, 2, 3)
|
||||
@@ -401,7 +444,7 @@ func TestWindowsClipboardRetriesTransientImageReads(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var cache clipboardCache
|
||||
reads := 0
|
||||
readSnapshot := func(wantImage bool) (clipboardSnapshot, uint32, error) {
|
||||
readSnapshot := func(wantImage, _ bool) (clipboardSnapshot, uint32, error) {
|
||||
reads++
|
||||
var snap clipboardSnapshot
|
||||
err := snap.readImagesLocked(wantImage, pngFormat, func(format uintptr) bool {
|
||||
@@ -418,7 +461,7 @@ func TestWindowsClipboardRetriesTransientImageReads(t *testing.T) {
|
||||
return snap, seq, err
|
||||
}
|
||||
sequence := func() uint32 { return seq }
|
||||
got, _, err := cache.read(true, sequence, readSnapshot)
|
||||
got, _, err := cache.read(true, false, sequence, readSnapshot)
|
||||
if err != nil || (cache.valid != tc.fallback) {
|
||||
t.Fatalf("first read: cache valid %t, error %v", cache.valid, err)
|
||||
}
|
||||
@@ -435,7 +478,7 @@ func TestWindowsClipboardRetriesTransientImageReads(t *testing.T) {
|
||||
} else if tc.failedFormat == cfDIB {
|
||||
want = dibPNG
|
||||
}
|
||||
got, _, err = cache.read(true, sequence, readSnapshot)
|
||||
got, _, err = cache.read(true, false, 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)
|
||||
}
|
||||
@@ -462,3 +505,171 @@ func TestWindowsClipboardSnapshotSkipsDisabledImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDropFilesBytes(paths []string, wide bool) []byte {
|
||||
raw := make([]byte, 20)
|
||||
binary.LittleEndian.PutUint32(raw, uint32(len(raw)))
|
||||
list := strings.Join(paths, "\x00") + "\x00\x00"
|
||||
if !wide {
|
||||
return append(raw, list...)
|
||||
}
|
||||
binary.LittleEndian.PutUint32(raw[16:], 1)
|
||||
for _, word := range utf16.Encode([]rune(list)) {
|
||||
raw = binary.LittleEndian.AppendUint16(raw, word)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestParseDropFilesBytes(t *testing.T) {
|
||||
wide := []string{`C:\one.txt`, `D:\资料\中文.txt`}
|
||||
ansi := []string{`C:\one.txt`, `D:\two.txt`}
|
||||
for _, tc := range []struct {
|
||||
raw []byte
|
||||
want []string
|
||||
}{
|
||||
{testDropFilesBytes(wide, true), wide},
|
||||
{testDropFilesBytes(ansi, false), ansi},
|
||||
} {
|
||||
if got := parseDropFilesBytes(tc.raw); !slices.Equal(got, tc.want) {
|
||||
t.Errorf("decoded %q, want %q", got, tc.want)
|
||||
}
|
||||
}
|
||||
raw := testDropFilesBytes(wide, true)
|
||||
for _, offset := range []uint32{0, 19, uint32(len(raw)), ^uint32(0)} {
|
||||
bad := bytes.Clone(raw)
|
||||
binary.LittleEndian.PutUint32(bad, offset)
|
||||
if got := parseDropFilesBytes(bad); len(got) != 0 {
|
||||
t.Errorf("offset %d decoded %q", offset, got)
|
||||
}
|
||||
}
|
||||
for _, bad := range [][]byte{nil, raw[:19], raw[:len(raw)-1]} {
|
||||
if got := parseDropFilesBytes(bad); len(got) != 0 {
|
||||
t.Errorf("truncated DROPFILES (%d bytes) decoded %q", len(bad), got)
|
||||
}
|
||||
}
|
||||
many := make([]string, MaxClipboardFiles+1)
|
||||
for i := range many {
|
||||
many[i] = strconv.Itoa(i)
|
||||
}
|
||||
for _, wide := range []bool{true, false} {
|
||||
limit := testDropFilesBytes(many[:MaxClipboardFiles], wide)
|
||||
if got := parseDropFilesBytes(limit); !slices.Equal(got, many[:MaxClipboardFiles]) {
|
||||
t.Errorf("wide=%t: complete selection at the limit returned %d files", wide, len(got))
|
||||
}
|
||||
for name, bad := range map[string][]byte{
|
||||
"file count": testDropFilesBytes(many, wide),
|
||||
"missing list NUL": limit[:len(limit)-1],
|
||||
"byte limit": append(limit, make([]byte, maxDropFilesBytes+1-len(limit))...),
|
||||
} {
|
||||
if got := parseDropFilesBytes(bad); got != nil {
|
||||
t.Errorf("wide=%t: %s returned %d files", wide, name, len(got))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDropFilesANSIUsesActiveCodePage(t *testing.T) {
|
||||
// Encode a representable non-ASCII filename with the system code page.
|
||||
encode := kernel32.NewProc("WideCharToMultiByte")
|
||||
const wcNoBestFitChars = 0x400
|
||||
flags := uintptr(wcNoBestFitChars)
|
||||
if cp := windows.GetACP(); cp == 65001 || cp == 54936 {
|
||||
flags = 0 // UTF-8 and GB18030 do not support WC_NO_BEST_FIT_CHARS.
|
||||
}
|
||||
for _, name := range []string{"é", "中", "А", "Ω", "א", "ش", "ก", "あ", "한"} {
|
||||
words := utf16.Encode([]rune(name))
|
||||
var encoded [8]byte
|
||||
n, _, err := encode.Call(0, flags, uintptr(unsafe.Pointer(&words[0])), uintptr(len(words)),
|
||||
uintptr(unsafe.Pointer(&encoded[0])), uintptr(len(encoded)), 0, 0)
|
||||
if n == 0 {
|
||||
t.Fatalf("WideCharToMultiByte: %v", err)
|
||||
}
|
||||
if string(encoded[:n]) == "?" {
|
||||
continue
|
||||
}
|
||||
raw := testDropFilesBytes([]string{`C:\` + string(encoded[:n]) + ".txt"}, false)
|
||||
want := []string{`C:\` + name + ".txt"}
|
||||
if got := parseDropFilesBytes(raw); !slices.Equal(got, want) {
|
||||
t.Errorf("code page %d: decoded %q, want %q", windows.GetACP(), got, want)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no representable test filename on code page %d", windows.GetACP())
|
||||
}
|
||||
|
||||
func TestWindowsClipboardSnapshotFiles(t *testing.T) {
|
||||
const pngFormat = 0xc000
|
||||
paths := []string{`C:\example.txt`}
|
||||
raw := testDropFilesBytes(paths, true)
|
||||
png := makeSamplePNG(t, 1, 2, 3)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
wantFiles, wantImage bool
|
||||
hasText bool
|
||||
raw []byte
|
||||
want, companion ClipKind
|
||||
}{
|
||||
{"files and text before PNG", true, true, true, raw, ClipFiles, ClipText},
|
||||
{"files with PNG", true, true, false, raw, ClipFiles, ClipPNG},
|
||||
{"files without disabled PNG", true, false, false, raw, ClipFiles, ClipEmpty},
|
||||
{"files disabled", false, true, true, raw, ClipText, ClipEmpty},
|
||||
{"empty files", true, true, true, nil, ClipText, ClipEmpty},
|
||||
{"corrupt files", true, true, false, []byte{1, 2, 3}, ClipPNG, ClipEmpty},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reader := clipboardSnapshotReader{
|
||||
withClipboard: func(read func() error) error { return read() },
|
||||
sequence: func() uint32 { return 23 },
|
||||
available: func(format uintptr) bool {
|
||||
return format == cfHDrop || format == pngFormat || format == cfDIB || (format == cfUnicodeText && tc.hasText)
|
||||
},
|
||||
readBytes: func(format uintptr, limit int) ([]byte, bool, error) {
|
||||
switch {
|
||||
case tc.wantFiles && format == cfHDrop && limit == maxDropFilesBytes:
|
||||
return tc.raw, false, nil
|
||||
case !tc.hasText && tc.wantImage && format == pngFormat && limit == MaxClipboardBytes:
|
||||
return png, false, nil
|
||||
}
|
||||
t.Fatalf("unexpected read format %d or limit %d", format, limit)
|
||||
return nil, false, nil
|
||||
},
|
||||
readText: func() ([]uint16, error) {
|
||||
if !tc.hasText {
|
||||
t.Fatal("clipboard does not contain text")
|
||||
}
|
||||
return []uint16{'x', 0}, nil
|
||||
},
|
||||
}
|
||||
var cache clipboardCache
|
||||
got, seq, err := cache.read(tc.wantImage, tc.wantFiles, reader.sequence, func(wantImage, wantFiles bool) (clipboardSnapshot, uint32, error) {
|
||||
return reader.read(wantImage, wantFiles, pngFormat)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seq != 23 {
|
||||
t.Fatalf("sequence = %d, want 23", seq)
|
||||
}
|
||||
if got.Kind != tc.want || (got.Kind == ClipFiles && !slices.Equal(got.Files, paths)) {
|
||||
t.Fatalf("unexpected payload %+v", got)
|
||||
}
|
||||
content := got
|
||||
if got.Kind == ClipFiles {
|
||||
if tc.companion == ClipEmpty {
|
||||
if got.companion != nil {
|
||||
t.Fatalf("unexpected companion %+v", got.companion)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got.companion == nil || got.companion.Kind != tc.companion {
|
||||
t.Fatalf("companion %+v, want %s", got.companion, tc.companion)
|
||||
}
|
||||
content = *got.companion
|
||||
}
|
||||
if (content.Kind == ClipText && string(content.Data) != "x") ||
|
||||
(content.Kind == ClipPNG && !bytes.Equal(content.Data, png)) {
|
||||
t.Fatalf("unexpected %s data %x", content.Kind, content.Data)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -339,6 +339,14 @@ func (s *Server) RegisterDropShare(vmKey, dropID string, entries []DropShareEntr
|
||||
return vm != nil && vm.dropShares.register(dropID, entries)
|
||||
}
|
||||
|
||||
func (s *Server) ensureClipboardShare(vmKey, dropID string, entries []DropShareEntry) bool {
|
||||
key := normalizeVMRegistryKey(vmKey)
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
vm := s.vms[key]
|
||||
return vm != nil && s.effectiveClipboardPolicyLocked(key).allowsHostToGuest() && vm.dropShares.ensure(dropID, entries)
|
||||
}
|
||||
|
||||
func (s *Server) RevokeDropShare(vmKey, dropID string) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
@@ -384,7 +392,7 @@ func (s *Server) handleDropFile(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
(&dropWebDAVFS{store: vm.dropShares}).serveDropFile(w, r, q.Get("drop_id"), q.Get("path"))
|
||||
serveDropFile(vm.dropDAVHandler.FileSystem, w, r, q.Get("drop_id"), q.Get("path"))
|
||||
}
|
||||
|
||||
func (s *Server) handleDropEventsPaste(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -61,8 +61,10 @@ function resolveTarget(args) {
|
||||
return [id === 'com.apple.Photos' ? 'photos' : 'window', label, id, String(top.kCGWindowNumber || 0)].join('\t')
|
||||
}
|
||||
|
||||
const stealthTypes = ['org.nspasteboard.TransientType', 'org.nspasteboard.AutoGeneratedType']
|
||||
|
||||
function addStealth(item) {
|
||||
for (const type of ['org.nspasteboard.TransientType', 'org.nspasteboard.AutoGeneratedType'])
|
||||
for (const type of stealthTypes)
|
||||
if (!item.types.containsObject($(type)) && !item.setDataForType($.NSData.data, $(type))) throw Error('Cannot mark pasteboard item')
|
||||
return item
|
||||
}
|
||||
@@ -143,15 +145,20 @@ function resolveCommandKey() {
|
||||
}
|
||||
|
||||
function requestPaste(url, id, activateClick, commandKey, focusWaitMs) {
|
||||
const rawTok = $.NSProcessInfo.processInfo.environment.objectForKey($('REIMS_TOKEN'))
|
||||
const token = rawTok && !rawTok.isNil() ? rawTok.js : ''
|
||||
if (!token || /[\r\n\0]/.test(url + token) || !/^[A-Za-z0-9_-]+$/.test(id)) throw Error('Invalid paste request')
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(id)) throw Error('Invalid drop ID')
|
||||
const body = {drop_id: id}
|
||||
if (activateClick) body.activate_click = true
|
||||
if (commandKey && commandKey !== 'meta_l') body.command_key = commandKey
|
||||
if (focusWaitMs > 0) body.focus_wait_ms = focusWaitMs
|
||||
const config = ['url = ' + JSON.stringify(url), 'header = ' + JSON.stringify('Authorization: Bearer ' + token),
|
||||
'header = "Content-Type: application/json"', 'data-raw = ' + JSON.stringify(JSON.stringify(body))].join('\n') + '\n'
|
||||
postToHost(url, body)
|
||||
}
|
||||
|
||||
function postToHost(url, body) {
|
||||
const rawTok = $.NSProcessInfo.processInfo.environment.objectForKey($('REIMS_TOKEN'))
|
||||
const token = rawTok && !rawTok.isNil() ? rawTok.js : ''
|
||||
if (!token || /[\r\n\0]/.test(url + token)) throw Error('Invalid paste request')
|
||||
const config = ['url = ' + JSON.stringify(url), 'header = ' + JSON.stringify('Authorization: Bearer ' + token)]
|
||||
if (body) config.push('header = "Content-Type: application/json"', 'data-raw = ' + JSON.stringify(JSON.stringify(body)))
|
||||
const task = $.NSTask.alloc.init
|
||||
const input = $.NSPipe.pipe
|
||||
task.launchPath = '/usr/bin/curl'
|
||||
@@ -159,12 +166,64 @@ function requestPaste(url, id, activateClick, commandKey, focusWaitMs) {
|
||||
task.standardInput = input
|
||||
task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice
|
||||
task.launch
|
||||
try { input.fileHandleForWriting.writeData($(config).dataUsingEncoding($.NSUTF8StringEncoding)) }
|
||||
try { input.fileHandleForWriting.writeData($(config.join('\n') + '\n').dataUsingEncoding($.NSUTF8StringEncoding)) }
|
||||
finally { input.fileHandleForWriting.closeFile }
|
||||
task.waitUntilExit
|
||||
if (task.terminationStatus !== 0) throw Error('Paste request failed')
|
||||
}
|
||||
|
||||
function withStagedPasteboard(items, action, stealthRestore = false) {
|
||||
const pb = $.NSPasteboard.generalPasteboard
|
||||
const originalCount = pb.changeCount
|
||||
const originals = pb.pasteboardItems
|
||||
const saved = []
|
||||
if (originals && !originals.isNil()) {
|
||||
for (let i = 0; i < originals.count; i++) {
|
||||
const source = originals.objectAtIndex(i)
|
||||
const copy = $.NSPasteboardItem.alloc.init
|
||||
const types = source.types
|
||||
for (let j = 0; j < types.count; j++) {
|
||||
const type = types.objectAtIndex(j)
|
||||
if (stealthRestore && stealthTypes.includes(type.js)) continue
|
||||
try {
|
||||
const data = source.dataForType(type)
|
||||
if (!data || data.isNil() || !copy.setDataForType(data, type))
|
||||
throw Error('Cannot save pasteboard flavor ' + type.js)
|
||||
} catch (err) {
|
||||
// Drag paste can skip unavailable promised flavors. IME must leave them intact.
|
||||
if (!stealthRestore) throw err
|
||||
}
|
||||
}
|
||||
if (!stealthRestore || copy.types.count) saved.push(stealthRestore ? addStealth(copy) : copy)
|
||||
}
|
||||
}
|
||||
if (pb.changeCount !== originalCount) throw Error('Pasteboard changed during backup')
|
||||
let stagedCount = pb.clearContents
|
||||
try {
|
||||
if (!pb.writeObjects($(items))) throw Error('Cannot stage clipboard')
|
||||
stagedCount = pb.changeCount
|
||||
return action()
|
||||
} finally {
|
||||
if (pb.changeCount === stagedCount) {
|
||||
pb.clearContents
|
||||
if (saved.length && !pb.writeObjects($(saved))) throw Error('Cannot restore clipboard')
|
||||
flushPasteboard(saved.length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function injectText(textFile, url, inputID) {
|
||||
if (!/^[0-9]+$/.test(inputID)) throw Error('Invalid text input ID')
|
||||
const value = $.NSString.stringWithContentsOfFileEncodingError(textFile, $.NSUTF8StringEncoding, null)
|
||||
const item = $.NSPasteboardItem.alloc.init
|
||||
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
||||
throw Error('Cannot stage text')
|
||||
return withStagedPasteboard([addStealth(item)], () => {
|
||||
postToHost(url + '?id=' + inputID)
|
||||
return 'ok'
|
||||
})
|
||||
}
|
||||
|
||||
function pasteCore(hitArgs, expected, bundleId, mode, url, id, items) {
|
||||
const {top, windows} = hit(hitArgs)
|
||||
if (!top || String(top.kCGWindowNumber || 0) !== expected) return 'cancelled'
|
||||
@@ -188,60 +247,25 @@ function pasteCore(hitArgs, expected, bundleId, mode, url, id, items) {
|
||||
if (activated && !(hit(hitArgs).windows || []).some(w => String(w.kCGWindowNumber) === expected)) return 'cancelled'
|
||||
const fm = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
||||
const activateClick = !!(top.kCGWindowOwnerPID && (!isTopOfApp || !fm || fm.isNil() || fm.processIdentifier !== top.kCGWindowOwnerPID))
|
||||
const pb = $.NSPasteboard.generalPasteboard
|
||||
const savedItems = []
|
||||
const clipboardItems = pb.pasteboardItems
|
||||
if (clipboardItems && !clipboardItems.isNil()) {
|
||||
for (let i = 0; i < clipboardItems.count; i++) {
|
||||
const item = clipboardItems.objectAtIndex(i)
|
||||
const pairs = []
|
||||
const types = item.types
|
||||
for (let j = 0; j < types.count; j++) {
|
||||
const type = types.objectAtIndex(j)
|
||||
if (type.js === 'org.nspasteboard.TransientType' || type.js === 'org.nspasteboard.AutoGeneratedType') continue
|
||||
try {
|
||||
const data = item.dataForType(type)
|
||||
if (data && !data.isNil()) pairs.push({type, data})
|
||||
} catch (_) { /* The owner could not provide this promised flavor. */ }
|
||||
}
|
||||
if (pairs.length) savedItems.push(pairs)
|
||||
}
|
||||
}
|
||||
let primaryErr = null
|
||||
try {
|
||||
pb.clearContents
|
||||
const newItems = items.map(path => {
|
||||
const item = $.NSPasteboardItem.alloc.init
|
||||
if (mode === 'files') {
|
||||
const png = items.length === 1 && bundleId !== 'com.apple.finder' ? readImagePNG(path) : null
|
||||
if ((!png || !browserBundles.has(bundleId)) &&
|
||||
!item.setStringForType($.NSURL.fileURLWithPath(path).absoluteString, $.NSPasteboardTypeFileURL))
|
||||
throw Error('Cannot stage file')
|
||||
if (png && !item.setDataForType(png, $.NSPasteboardTypePNG)) throw Error('Cannot stage PNG')
|
||||
} else if (mode === 'text' || mode === 'text-raw') {
|
||||
const value = mode === 'text-raw' ? $(path) : $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)
|
||||
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
||||
throw Error('Cannot stage text')
|
||||
} else throw Error('Invalid paste mode')
|
||||
return addStealth(item)
|
||||
})
|
||||
if (!pb.writeObjects($(newItems))) throw Error('Cannot stage clipboard')
|
||||
const newItems = items.map(path => {
|
||||
const item = $.NSPasteboardItem.alloc.init
|
||||
if (mode === 'files') {
|
||||
const png = items.length === 1 && bundleId !== 'com.apple.finder' ? readImagePNG(path) : null
|
||||
if ((!png || !browserBundles.has(bundleId)) &&
|
||||
!item.setStringForType($.NSURL.fileURLWithPath(path).absoluteString, $.NSPasteboardTypeFileURL))
|
||||
throw Error('Cannot stage file')
|
||||
if (png && !item.setDataForType(png, $.NSPasteboardTypePNG)) throw Error('Cannot stage PNG')
|
||||
} else if (mode === 'text' || mode === 'text-raw') {
|
||||
const value = mode === 'text-raw' ? $(path) : $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)
|
||||
if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString))
|
||||
throw Error('Cannot stage text')
|
||||
} else throw Error('Invalid paste mode')
|
||||
return addStealth(item)
|
||||
})
|
||||
return withStagedPasteboard(newItems, () => {
|
||||
requestPaste(url, id, activateClick, resolveCommandKey(), bundleId === 'com.apple.finder' ? 220 : 0)
|
||||
return 'pasted'
|
||||
} catch (err) {
|
||||
primaryErr = err
|
||||
throw err
|
||||
} finally {
|
||||
pb.clearContents
|
||||
const restored = savedItems.map(pairs => {
|
||||
const item = $.NSPasteboardItem.alloc.init
|
||||
for (const {type, data} of pairs) {
|
||||
try { item.setDataForType(data, type) } catch (_) { /* Continue with the remaining flavors. */ }
|
||||
}
|
||||
return addStealth(item)
|
||||
})
|
||||
if (restored.length && !pb.writeObjects($(restored)) && !primaryErr) throw Error('Cannot restore clipboard')
|
||||
}
|
||||
}, true)
|
||||
}
|
||||
|
||||
function parseEventData(eventFile) {
|
||||
@@ -334,8 +358,70 @@ function runDrop(eventFile, mount, url) {
|
||||
return ['fallback', header, target].concat(items).join('\n')
|
||||
}
|
||||
|
||||
// Short-lived osascript can exit before pboard commits multi-item XPC payloads unless the run loop runs briefly.
|
||||
function flushPasteboard(count) {
|
||||
const secs = Math.min(0.25, 0.06 + count * 0.0005)
|
||||
$.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(secs))
|
||||
}
|
||||
|
||||
function readClipFiles() {
|
||||
const items = $.NSPasteboard.generalPasteboard.pasteboardItems
|
||||
const urls = []
|
||||
if (items && !items.isNil()) {
|
||||
for (let i = 0; i < items.count; i++) {
|
||||
const value = items.objectAtIndex(i).stringForType($.NSPasteboardTypeFileURL)
|
||||
if (value && !value.isNil()) {
|
||||
const url = ObjC.unwrap(value)
|
||||
if (url) urls.push(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!urls.length) throw Error('No clip files')
|
||||
return urls.join('\n')
|
||||
}
|
||||
|
||||
function writeClipFiles(manifestFile, mount, expectedCount) {
|
||||
if (!mount) return 'remount'
|
||||
const ev = JSON.parse($.NSString.stringWithContentsOfFileEncodingError(manifestFile, $.NSUTF8StringEncoding, null).js)
|
||||
const safeName = name => typeof name === 'string' && name.length > 0 && name !== '.' &&
|
||||
name !== '..' && !/[/\\\0\r\n\t]/.test(name)
|
||||
if (!ev || typeof ev.drop_id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ev.drop_id) ||
|
||||
!Array.isArray(ev.items) || !ev.items.length || !ev.items.every(safeName)) throw Error('Invalid clipboard manifest')
|
||||
|
||||
const fm = $.NSFileManager.defaultManager
|
||||
const dir = mount + '/' + ev.drop_id
|
||||
const isDir = Ref()
|
||||
const exists = () => fm.fileExistsAtPathIsDirectory(dir, isDir) && isDir[0]
|
||||
if (!exists()) {
|
||||
fm.contentsOfDirectoryAtPathError(mount, null)
|
||||
if (!exists()) return 'remount'
|
||||
}
|
||||
const paths = ev.items.map(name => dir + '/' + name)
|
||||
if (!mountHealthy([mount, dir]) || !paths.every(p => fm.fileExistsAtPath(p))) return 'remount'
|
||||
const urls = paths.map(p => $.NSURL.fileURLWithPath(p).absoluteString)
|
||||
const newItems = urls.map(url => {
|
||||
const item = $.NSPasteboardItem.alloc.init
|
||||
if (!item.setStringForType(url, $.NSPasteboardTypeFileURL))
|
||||
throw Error('Invalid clipboard file URL')
|
||||
return item
|
||||
})
|
||||
const pb = $.NSPasteboard.generalPasteboard
|
||||
if (expectedCount && String(pb.changeCount) !== expectedCount) return 'changed'
|
||||
pb.clearContents
|
||||
if (!pb.writeObjects($(newItems))) throw Error('Clipboard write failed')
|
||||
const writtenCount = pb.changeCount
|
||||
flushPasteboard(newItems.length)
|
||||
const readback = readClipFiles()
|
||||
if (pb.changeCount !== writtenCount || readback !== urls.map(url => ObjC.unwrap(url)).join('\n'))
|
||||
throw Error('Clipboard file readback did not match')
|
||||
return 'ok'
|
||||
}
|
||||
|
||||
function run(argv) {
|
||||
const [mode, ...args] = argv
|
||||
if (mode === 'inject-text') return injectText(...args)
|
||||
if (mode === 'read-clip-files') return readClipFiles()
|
||||
if (mode === 'write-clip-files') return writeClipFiles(...args)
|
||||
if (mode === 'run-drop') return runDrop(...args)
|
||||
if (mode === 'resolve') return resolve(args)
|
||||
if (mode === 'check-mount') {
|
||||
|
||||
@@ -36,6 +36,7 @@ type DropShareEntry struct {
|
||||
|
||||
type dropShareRecord struct {
|
||||
id string
|
||||
clipboard bool
|
||||
entries map[string]DropShareEntry
|
||||
order []string
|
||||
createdAt time.Time
|
||||
@@ -60,11 +61,41 @@ func (s *dropShareStore) touchRootLocked(now time.Time) {
|
||||
s.modTime = now
|
||||
}
|
||||
|
||||
func sameDropEntries(rec *dropShareRecord, entries []DropShareEntry) bool {
|
||||
if len(rec.order) != len(entries) {
|
||||
return false
|
||||
}
|
||||
for i, entry := range entries {
|
||||
entry.HostPath = filepath.Clean(entry.HostPath)
|
||||
if rec.order[i] != entry.Name || rec.entries[entry.Name] != entry {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *dropShareStore) ensure(id string, entries []DropShareEntry) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := s.now()
|
||||
if rec := s.records[id]; rec != nil && rec.clipboard && now.Before(rec.expiresAt) && sameDropEntries(rec, entries) {
|
||||
rec.renew(now)
|
||||
return true
|
||||
}
|
||||
return s.registerLocked(id, entries, true, now)
|
||||
}
|
||||
|
||||
func (s *dropShareStore) register(id string, entries []DropShareEntry) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.registerLocked(id, entries, false, s.now())
|
||||
}
|
||||
|
||||
func (s *dropShareStore) registerLocked(id string, entries []DropShareEntry, clipboard bool, now time.Time) bool {
|
||||
if !dropIDPattern.MatchString(id) || len(entries) == 0 {
|
||||
return false
|
||||
}
|
||||
rec := &dropShareRecord{id: id, entries: make(map[string]DropShareEntry, len(entries))}
|
||||
rec := &dropShareRecord{id: id, clipboard: clipboard, entries: make(map[string]DropShareEntry, len(entries))}
|
||||
for _, e := range entries {
|
||||
if e.Name == "" || e.Name == "." || e.Name == ".." || strings.ContainsAny(e.Name, "/\\") ||
|
||||
strings.IndexFunc(e.Name, unicode.IsControl) >= 0 || !filepath.IsAbs(e.HostPath) {
|
||||
@@ -77,9 +108,6 @@ func (s *dropShareStore) register(id string, entries []DropShareEntry) bool {
|
||||
rec.entries[e.Name] = e
|
||||
rec.order = append(rec.order, e.Name)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := s.now()
|
||||
s.prune(now)
|
||||
delete(s.records, id)
|
||||
for len(s.records) >= MaxDropWebDAVEntries {
|
||||
@@ -110,12 +138,19 @@ func (s *dropShareStore) prune(now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *dropShareStore) touch(id string) *dropShareRecord {
|
||||
func (rec *dropShareRecord) renew(now time.Time) {
|
||||
rec.expiresAt = now.Add(DropWebDAVTTL)
|
||||
if limit := rec.createdAt.Add(DropWebDAVMaxLifetime); limit.Before(rec.expiresAt) {
|
||||
rec.expiresAt = limit
|
||||
}
|
||||
}
|
||||
|
||||
func (s *dropShareStore) touch(id string, allowClipboard bool) *dropShareRecord {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := s.now()
|
||||
rec := s.records[id]
|
||||
if rec == nil {
|
||||
if rec == nil || (rec.clipboard && !allowClipboard) {
|
||||
return nil
|
||||
}
|
||||
if !now.Before(rec.expiresAt) {
|
||||
@@ -123,20 +158,20 @@ func (s *dropShareStore) touch(id string) *dropShareRecord {
|
||||
s.touchRootLocked(now)
|
||||
return nil
|
||||
}
|
||||
rec.expiresAt = now.Add(DropWebDAVTTL)
|
||||
if limit := rec.createdAt.Add(DropWebDAVMaxLifetime); limit.Before(rec.expiresAt) {
|
||||
rec.expiresAt = limit
|
||||
}
|
||||
rec.renew(now)
|
||||
snapshot := *rec // entries and order are immutable after registration.
|
||||
return &snapshot
|
||||
}
|
||||
|
||||
func (s *dropShareStore) rootSnapshot() (time.Time, []virtualFileInfo) {
|
||||
func (s *dropShareStore) rootSnapshot(allowClipboard bool) (time.Time, []virtualFileInfo) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.prune(s.now())
|
||||
entries := make([]virtualFileInfo, 0, len(s.records))
|
||||
for id, rec := range s.records {
|
||||
if rec.clipboard && !allowClipboard {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, virtualFileInfo{name: id, when: rec.createdAt})
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].name < entries[j].name })
|
||||
@@ -152,6 +187,20 @@ func (s *dropShareStore) revoke(id string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *dropShareStore) revokeClipboard() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
count := len(s.records)
|
||||
for id, rec := range s.records {
|
||||
if rec.clipboard {
|
||||
delete(s.records, id)
|
||||
}
|
||||
}
|
||||
if len(s.records) != count {
|
||||
s.touchRootLocked(s.now())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *dropShareStore) clear() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -161,7 +210,10 @@ func (s *dropShareStore) clear() {
|
||||
}
|
||||
}
|
||||
|
||||
type dropWebDAVFS struct{ store *dropShareStore }
|
||||
type dropWebDAVFS struct {
|
||||
store *dropShareStore
|
||||
allowClipboard func() bool
|
||||
}
|
||||
|
||||
var _ webdav.FileSystem = (*dropWebDAVFS)(nil)
|
||||
|
||||
@@ -226,14 +278,65 @@ func IsDropSymlink(st os.FileInfo) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func dropEntryInfo(e DropShareEntry) (os.FileInfo, error) {
|
||||
st, err := os.Lstat(e.HostPath)
|
||||
// resolveDropPath returns a pinned parent and the checked leaf beneath it.
|
||||
// Clipboard paths must be walked from the local volume root: opening the
|
||||
// selected directory by its absolute name would follow junctions in its parents.
|
||||
func resolveDropPath(hostPath, sub string, clipboard bool) (*os.Root, string, os.FileInfo, error) {
|
||||
dir, rel := filepath.Dir(hostPath), filepath.Base(hostPath)
|
||||
if clipboard {
|
||||
dir = filepath.VolumeName(hostPath) + string(os.PathSeparator)
|
||||
if err := checkClipboardDrive(dir); err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
rel = strings.TrimPrefix(hostPath, dir)
|
||||
}
|
||||
if dir == hostPath {
|
||||
rel = "."
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
if sub != "" {
|
||||
rel += "/" + sub
|
||||
}
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
for {
|
||||
part, tail, more := strings.Cut(rel, "/")
|
||||
st, err := root.Lstat(part)
|
||||
if err == nil && (IsDropSymlink(st) || (!st.IsDir() && (more || !st.Mode().IsRegular()))) {
|
||||
err = os.ErrPermission
|
||||
}
|
||||
if err != nil {
|
||||
root.Close()
|
||||
return nil, "", nil, err
|
||||
}
|
||||
if !more {
|
||||
return root, part, st, nil
|
||||
}
|
||||
child, err := root.OpenRoot(part)
|
||||
root.Close()
|
||||
if err != nil {
|
||||
return nil, "", nil, err
|
||||
}
|
||||
actual, err := child.Stat(".")
|
||||
if err == nil && (IsDropSymlink(actual) || !os.SameFile(st, actual)) {
|
||||
err = os.ErrPermission
|
||||
}
|
||||
if err != nil {
|
||||
child.Close()
|
||||
return nil, "", nil, err
|
||||
}
|
||||
root, rel = child, tail
|
||||
}
|
||||
}
|
||||
|
||||
func statDropPath(hostPath string, clipboard bool) (os.FileInfo, error) {
|
||||
root, _, st, err := resolveDropPath(hostPath, "", clipboard)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if IsDropSymlink(st) || st.IsDir() != e.IsDir || (!e.IsDir && !st.Mode().IsRegular()) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
root.Close()
|
||||
return st, nil
|
||||
}
|
||||
|
||||
@@ -249,8 +352,9 @@ func (f *dropWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.F
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allowClipboard := f.allowClipboard != nil && f.allowClipboard()
|
||||
if rel == "." {
|
||||
when, entries := f.store.rootSnapshot()
|
||||
when, entries := f.store.rootSnapshot(allowClipboard)
|
||||
d := &virtualDAVDir{info: virtualFileInfo{name: ".", when: when}}
|
||||
for _, entry := range entries {
|
||||
d.entries = append(d.entries, entry)
|
||||
@@ -258,14 +362,15 @@ func (f *dropWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.F
|
||||
return d, nil
|
||||
}
|
||||
id, rest, hasRest := strings.Cut(rel, "/")
|
||||
rec := f.store.touch(id)
|
||||
rec := f.store.touch(id, allowClipboard)
|
||||
if rec == nil {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
if !hasRest {
|
||||
d := &virtualDAVDir{info: virtualFileInfo{name: id, when: rec.createdAt}}
|
||||
for _, alias := range rec.order {
|
||||
if st, err := dropEntryInfo(rec.entries[alias]); err == nil {
|
||||
e := rec.entries[alias]
|
||||
if st, err := statDropPath(e.HostPath, rec.clipboard); err == nil && st.IsDir() == e.IsDir {
|
||||
d.entries = append(d.entries, dropNamedInfo{st, alias})
|
||||
}
|
||||
}
|
||||
@@ -276,70 +381,26 @@ func (f *dropWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.F
|
||||
if !ok || (hasSub && !e.IsDir) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
expected, err := dropEntryInfo(e)
|
||||
root, target, expected, err := resolveDropPath(e.HostPath, sub, rec.clipboard)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dir, target := filepath.Dir(e.HostPath), filepath.Base(e.HostPath)
|
||||
if e.IsDir {
|
||||
dir, target = e.HostPath, "."
|
||||
}
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Pin each checked directory before looking up its child.
|
||||
defer func() {
|
||||
if root != nil {
|
||||
root.Close()
|
||||
}
|
||||
}()
|
||||
if e.IsDir {
|
||||
st, err := statDAVEntry(root, ".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if IsDropSymlink(st) || !os.SameFile(expected, st) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
}
|
||||
if hasSub {
|
||||
alias = path.Base(sub)
|
||||
for {
|
||||
part, tail, more := strings.Cut(sub, "/")
|
||||
expected, err = statDAVEntry(root, part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if IsDropSymlink(expected) || (!expected.IsDir() && !expected.Mode().IsRegular()) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
if !more {
|
||||
target = part
|
||||
break
|
||||
}
|
||||
next, err := root.OpenRoot(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root.Close()
|
||||
root = next
|
||||
st, err := root.Stat(".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !os.SameFile(expected, st) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
sub = tail
|
||||
}
|
||||
} else if expected.IsDir() != e.IsDir {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
file, err := root.Open(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := file.Stat()
|
||||
if err != nil || !os.SameFile(expected, st) {
|
||||
if err != nil || IsDropSymlink(st) || !os.SameFile(expected, st) {
|
||||
file.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -395,7 +456,7 @@ func (f *dropWebDAVFS) Stat(ctx context.Context, name string) (os.FileInfo, erro
|
||||
return file.Stat()
|
||||
}
|
||||
|
||||
func (f *dropWebDAVFS) serveDropFile(w http.ResponseWriter, r *http.Request, dropID, relPath string) {
|
||||
func serveDropFile(f webdav.FileSystem, w http.ResponseWriter, r *http.Request, dropID, relPath string) {
|
||||
rel, err := davRelativePath(relPath)
|
||||
if !dropIDPattern.MatchString(dropID) || err != nil || rel != relPath || rel == "." {
|
||||
http.Error(w, "invalid drop path", http.StatusBadRequest)
|
||||
|
||||
@@ -1,17 +1,151 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/webdav"
|
||||
)
|
||||
|
||||
func TestClipboardSharePolicyWithdrawal(t *testing.T) {
|
||||
const name = "clipboard-test"
|
||||
enabled := DefaultClipboardPolicy()
|
||||
disabled := enabled
|
||||
disabled.Enabled = false
|
||||
inbound := enabled
|
||||
inbound.Direction = ClipboardGuestToHost
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
withdraw func(*Server)
|
||||
otherActive bool
|
||||
}{
|
||||
{"global disable", func(s *Server) { s.SetGlobalClipboardPolicy(disabled) }, true},
|
||||
{"VM guest to host", func(s *Server) { s.SetVMClipboardPolicy(name, &inbound) }, true},
|
||||
{"clear VM override", func(s *Server) {
|
||||
s.SetVMClipboardPolicy(name, &enabled)
|
||||
s.SetGlobalClipboardPolicy(inbound)
|
||||
s.SetVMClipboardPolicy(name, nil)
|
||||
}, true},
|
||||
{"extension deactivated", func(s *Server) { s.SetClipboardActive(false) }, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
host := filepath.Join(t.TempDir(), "shared.txt")
|
||||
if err := os.WriteFile(host, []byte("content"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clip := &memClipboard{}
|
||||
clip.WriteFiles([]string{host})
|
||||
srv := newClipboardTestServer(clip)
|
||||
srv.RegisterVM(VMConfig{VMName: "other", Token: "other-token"})
|
||||
srv.SetVMClipboardPolicy("other", &enabled)
|
||||
entries := []DropShareEntry{{Name: "shared.txt", HostPath: host}}
|
||||
if !srv.RegisterDropShare(name, "drag", entries) || !srv.ensureClipboardShare("other", "other-clip", entries) {
|
||||
t.Fatal("registering control shares failed")
|
||||
}
|
||||
resp := clipboardRequest(t, srv, http.MethodGet, "?accept=files", "", "", nil)
|
||||
var manifest struct {
|
||||
DropID string `json:"drop_id"`
|
||||
}
|
||||
if err := json.Unmarshal(resp.Body.Bytes(), &manifest); err != nil || resp.Code != http.StatusOK || manifest.DropID == "" {
|
||||
t.Fatalf("clipboard manifest: %d %q, %v", resp.Code, resp.Body, err)
|
||||
}
|
||||
|
||||
request := func(vm, method, path string, handler http.HandlerFunc) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.SetBasicAuth(vm, vm+"-token")
|
||||
r.Header.Set("Depth", "1")
|
||||
w := httptest.NewRecorder()
|
||||
handler(w, r)
|
||||
return w
|
||||
}
|
||||
checkShare := func(vm, id string, visible bool) {
|
||||
t.Helper()
|
||||
prefix := "/dav-drop/" + vm + "/"
|
||||
list := request(vm, "PROPFIND", prefix, srv.handleDropWebDAV)
|
||||
if list.Code != http.StatusMultiStatus || strings.Contains(list.Body.String(), prefix+id+"/") != visible {
|
||||
t.Fatalf("root listing, want %s visible=%t: %d %s", id, visible, list.Code, list.Body)
|
||||
}
|
||||
for _, op := range []struct {
|
||||
method, path string
|
||||
handler http.HandlerFunc
|
||||
status int
|
||||
}{
|
||||
{"PROPFIND", prefix + id + "/", srv.handleDropWebDAV, http.StatusMultiStatus},
|
||||
{"GET", prefix + id + "/shared.txt", srv.handleDropWebDAV, http.StatusOK},
|
||||
{"GET", "/v1/drop-file?drop_id=" + id + "&path=shared.txt", srv.handleDropFile, http.StatusOK},
|
||||
} {
|
||||
w := request(vm, op.method, op.path, op.handler)
|
||||
wantStatus := op.status
|
||||
if !visible {
|
||||
wantStatus = http.StatusNotFound
|
||||
}
|
||||
if w.Code != wantStatus {
|
||||
t.Fatalf("%s %s: %d %s, want %d", op.method, op.path, w.Code, w.Body, wantStatus)
|
||||
}
|
||||
if visible && op.method == "GET" && w.Body.String() != "content" {
|
||||
t.Fatalf("GET %s: unexpected content %q", op.path, w.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
checkShare(name, manifest.DropID, true)
|
||||
tc.withdraw(srv)
|
||||
checkShare(name, manifest.DropID, false)
|
||||
checkShare(name, "drag", true)
|
||||
checkShare("other", "other-clip", tc.otherActive)
|
||||
store := srv.vms[vmRegistryKey("", name)].dropShares
|
||||
if store.touch(manifest.DropID, true) != nil {
|
||||
t.Fatal("withdrawn share still registered")
|
||||
}
|
||||
if srv.ensureClipboardShare(name, manifest.DropID, entries) {
|
||||
t.Fatal("in-flight clipboard poll recreated a withdrawn share")
|
||||
}
|
||||
|
||||
// Exercise serving policy independently of revocation by injecting a stale record.
|
||||
if !store.ensure("stale", entries) {
|
||||
t.Fatal("creating stale record failed")
|
||||
}
|
||||
checkShare(name, "stale", false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropShareEnsureConcurrentFirstPoll(t *testing.T) {
|
||||
store := newDropShareStore()
|
||||
start := time.Unix(1700000000, 0)
|
||||
store.modTime = start.Add(-time.Second)
|
||||
now := start
|
||||
store.now = func() time.Time {
|
||||
value := now
|
||||
now = now.Add(time.Nanosecond)
|
||||
return value
|
||||
}
|
||||
entries := []DropShareEntry{{Name: "file", HostPath: filepath.Join(t.TempDir(), "file")}}
|
||||
var wg sync.WaitGroup
|
||||
ready := make(chan struct{})
|
||||
for range 64 {
|
||||
wg.Go(func() {
|
||||
<-ready
|
||||
if !store.ensure("clip", entries) {
|
||||
t.Error("ensure failed")
|
||||
}
|
||||
})
|
||||
}
|
||||
close(ready)
|
||||
wg.Wait()
|
||||
rec := store.records["clip"]
|
||||
if rec == nil || !rec.createdAt.Equal(start) || !store.modTime.Equal(start) {
|
||||
t.Fatalf("first poll should register exactly once: record %+v, root modtime %v", rec, store.modTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropWebDAV(t *testing.T) {
|
||||
f := &dropWebDAVFS{store: newDropShareStore()}
|
||||
now := time.Unix(1700000000, 0)
|
||||
@@ -73,7 +207,7 @@ func TestDropWebDAV(t *testing.T) {
|
||||
}
|
||||
direct := func(id, rel string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
f.serveDropFile(w, httptest.NewRequest("GET", "/", nil), id, rel)
|
||||
serveDropFile(f, w, httptest.NewRequest("GET", "/", nil), id, rel)
|
||||
return w
|
||||
}
|
||||
for name, child := range map[string]string{"/": "/drop", "/drop": "/alias.txt", "/drop/folder": "/host.txt"} {
|
||||
|
||||
@@ -43,6 +43,9 @@ func TestGuestAgentFolderMounts(t *testing.T) {
|
||||
"/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command",
|
||||
)
|
||||
uninstall = dnsPaths.Replace(uninstall)
|
||||
if CurrentAgentVersion != ClipboardFilesAgentVersion {
|
||||
t.Fatalf("CurrentAgentVersion = %d, want clipboard files version %d", CurrentAgentVersion, ClipboardFilesAgentVersion)
|
||||
}
|
||||
versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,`
|
||||
if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") {
|
||||
t.Fatal("Guest Tools scripts do not advertise the current agent version")
|
||||
|
||||
@@ -19,7 +19,9 @@ const TimezoneAgentVersion = 11
|
||||
const HostDNSAgentVersion = 12
|
||||
const WindowDropAgentVersion = 13
|
||||
const ClipboardReliabilityAgentVersion = 14
|
||||
const CurrentAgentVersion = ClipboardReliabilityAgentVersion
|
||||
const ClipboardFilesAgentVersion = 15
|
||||
|
||||
const CurrentAgentVersion = ClipboardFilesAgentVersion
|
||||
|
||||
type SharedFolderConfig struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -26,10 +26,11 @@ import (
|
||||
)
|
||||
|
||||
type memClipboard struct {
|
||||
mu sync.Mutex
|
||||
kind ClipKind
|
||||
data []byte
|
||||
seq uint32
|
||||
mu sync.Mutex
|
||||
kind ClipKind
|
||||
data []byte
|
||||
files []string
|
||||
seq uint32
|
||||
}
|
||||
|
||||
func (m *memClipboard) SequenceNumber() uint32 {
|
||||
@@ -50,6 +51,7 @@ func (m *memClipboard) ReadText() (string, error) {
|
||||
func (m *memClipboard) WriteText(s string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.files = nil
|
||||
m.kind = ClipText
|
||||
m.data = []byte(s)
|
||||
m.seq++
|
||||
@@ -65,18 +67,28 @@ func (m *memClipboard) Read() (ClipPayload, error) {
|
||||
if k == "" && len(cp) > 0 {
|
||||
k = ClipText
|
||||
}
|
||||
return ClipPayload{Kind: k, Data: cp}, nil
|
||||
return ClipPayload{Kind: k, Data: cp, Files: append([]string(nil), m.files...)}, nil
|
||||
}
|
||||
|
||||
func (m *memClipboard) WritePNG(b []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.files = nil
|
||||
m.kind = ClipPNG
|
||||
m.data = append([]byte(nil), b...)
|
||||
m.seq++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memClipboard) WriteFiles(paths []string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.kind = ClipFiles
|
||||
m.data = nil
|
||||
m.files = append([]string(nil), paths...)
|
||||
m.seq++
|
||||
}
|
||||
|
||||
func makeSamplePNG(t *testing.T, r, g, b uint8) []byte {
|
||||
t.Helper()
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 4, 3))
|
||||
|
||||
+208
-54
@@ -156,7 +156,7 @@ INJECT_LOCK="$TMP_DIR/injecting"
|
||||
DROP_INJECT_LOCK="$TMP_DIR/drop-injecting"
|
||||
CLIP_LOCK="$TMP_DIR/clip.lock"
|
||||
mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR" "$DROP_MOUNT"
|
||||
rm -f "$INJECT_LOCK" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true
|
||||
rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true
|
||||
rm -rf "$CLIP_LOCK" "$CLIP_LOCK".reaping.* 2>/dev/null || true
|
||||
|
||||
CAFFEINATE_PID=""
|
||||
@@ -184,7 +184,7 @@ cleanup() {
|
||||
if [ -n "$CLIPBOARD_PID" ]; then
|
||||
kill "$CLIPBOARD_PID" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$INJECT_LOCK" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true
|
||||
rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 0' INT TERM
|
||||
@@ -223,6 +223,10 @@ hash_png_file() {
|
||||
{ printf 'png:'; cat "$1"; } | shasum -a 256 2>/dev/null | awk '{print $1}'
|
||||
}
|
||||
|
||||
hash_files_file() {
|
||||
{ printf 'files:'; cat "$1"; } | shasum -a 256 2>/dev/null | awk '{print $1}'
|
||||
}
|
||||
|
||||
update_desktop_link() {
|
||||
target="$1"
|
||||
if [ -L "$DESKTOP_LINK" ]; then
|
||||
@@ -549,19 +553,39 @@ read_local_clipboard() {
|
||||
out_file="$1"
|
||||
read_failed=0
|
||||
if ! cinfo=$(osascript -e 'clipboard info' 2>/dev/null); then
|
||||
echo "empty"
|
||||
if [ "${2:-}" = sync ]; then return 1; fi
|
||||
echo "error"
|
||||
return 0
|
||||
fi
|
||||
case "$cinfo" in
|
||||
*furl*)
|
||||
if [ -z "${APP_DIR:-}" ] || [ ! -f "$APP_DIR/drop-resolve.js" ]; then
|
||||
echo "empty"
|
||||
elif osascript -l JavaScript "$APP_DIR/drop-resolve.js" read-clip-files >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then
|
||||
echo "files"
|
||||
else
|
||||
echo "error"
|
||||
fi
|
||||
return 0
|
||||
;;
|
||||
*utf8*|*"Unicode text"*|*string*)
|
||||
if ! pbpaste >"$out_file" 2>/dev/null; then
|
||||
read_failed=1
|
||||
echo "error"
|
||||
return 0
|
||||
elif [ -s "$out_file" ]; then
|
||||
echo "text"
|
||||
return 0
|
||||
fi
|
||||
;;
|
||||
*PNGf*|*TIFF*) ;;
|
||||
*)
|
||||
# Without a recognized text flavor, pbpaste can fall back to RTF or EPS.
|
||||
if pbpaste >/dev/null 2>&1; then
|
||||
echo "empty"
|
||||
else
|
||||
echo "error"
|
||||
fi
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
case "$cinfo" in
|
||||
*PNGf*)
|
||||
@@ -599,8 +623,11 @@ read_local_clipboard() {
|
||||
read_failed=1
|
||||
;;
|
||||
esac
|
||||
echo "empty"
|
||||
if [ "${2:-}" = sync ] && [ "$read_failed" = 1 ]; then return 1; fi
|
||||
if [ "$read_failed" = 1 ]; then
|
||||
echo "error"
|
||||
else
|
||||
echo "empty"
|
||||
fi
|
||||
}
|
||||
|
||||
read_clipboard_change_count() {
|
||||
@@ -612,8 +639,27 @@ write_local_png() {
|
||||
osascript -e "set the clipboard to (read (POSIX file \"$1\") as «class PNGf»)" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
write_local_files() (
|
||||
[ -n "${DROP_MOUNT:-}" ] && [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ] || return 1
|
||||
[ -n "${REIMS_VM:-}" ] || return 1
|
||||
route="/dav-drop/$(urlencode "$REIMS_VM")/"
|
||||
for attempt in first retry; do
|
||||
if ! is_reims_dav_mounted "$DROP_MOUNT" "$route"; then
|
||||
ensure_drop_webdav_mount && is_reims_dav_mounted "$DROP_MOUNT" "$route" || return 1
|
||||
fi
|
||||
clipboard_poll_interrupted && return 1
|
||||
res=$(osascript -l JavaScript "$APP_DIR/drop-resolve.js" write-clip-files "$1" "$DROP_MOUNT" "$2" 2>/dev/null) || return 1
|
||||
[ "$res" != ok ] || return 0
|
||||
[ "$res" = remount ] && [ "$attempt" = first ] &&
|
||||
is_reims_dav_mounted "$DROP_MOUNT" "$route" &&
|
||||
unmount_shared_folder "$DROP_MOUNT" >/dev/null 2>&1 || return 1
|
||||
done
|
||||
return 1
|
||||
)
|
||||
|
||||
local_clip_hash() {
|
||||
case "$1" in
|
||||
files) hash_files_file "$2" ;;
|
||||
png) hash_png_file "$2" ;;
|
||||
text) hash_file "$2" ;;
|
||||
empty) echo "empty" ;;
|
||||
@@ -623,9 +669,10 @@ local_clip_hash() {
|
||||
read_clipboard_for_sync() {
|
||||
read_ok=1
|
||||
read_cc=""
|
||||
if ! read_kind=$(read_local_clipboard "$clip_in" sync); then
|
||||
read_kind=$(read_local_clipboard "$clip_in")
|
||||
read_hash=""
|
||||
if [ "$read_kind" = error ]; then
|
||||
read_ok=0
|
||||
read_hash=empty
|
||||
return 0
|
||||
fi
|
||||
read_hash=$(local_clip_hash "$read_kind" "$clip_in")
|
||||
@@ -658,6 +705,11 @@ synced_local_cc=""
|
||||
synced_local_kind=""
|
||||
last_server_hash=""
|
||||
last_server_seq=""
|
||||
unreadable_baseline=0
|
||||
readback_kind=""
|
||||
readback_cc=""
|
||||
file_retry_hash=""
|
||||
file_retry_polls=0
|
||||
tick=0
|
||||
TAB=$(printf '\t')
|
||||
|
||||
@@ -734,6 +786,23 @@ inject_lock_active() {
|
||||
return 1
|
||||
}
|
||||
|
||||
clipboard_poll_interrupted() {
|
||||
[ -f "$INJECT_LOCK.completed" ] || inject_lock_active
|
||||
}
|
||||
|
||||
remember_pre_get_clipboard() {
|
||||
if [ "$local_kind" != error ] && [ -z "$last_local_hash" ]; then
|
||||
last_local_hash="$cur_hash"
|
||||
fi
|
||||
}
|
||||
|
||||
defer_file_delivery() {
|
||||
remember_pre_get_clipboard
|
||||
file_retry_hash="$new_hash"
|
||||
file_retry_polls=3
|
||||
last_server_seq="$new_seq"
|
||||
}
|
||||
|
||||
sync_clipboard() {
|
||||
if [ -z "$REIMS_HOST_URL" ] || [ -z "$REIMS_TOKEN" ]; then
|
||||
sleep 2
|
||||
@@ -748,6 +817,12 @@ sync_clipboard() {
|
||||
sleep 1
|
||||
return 0
|
||||
fi
|
||||
# Clear the previous injection marker while holding the clipboard lock.
|
||||
if [ -f "$INJECT_LOCK.completed" ] && ! rm -f "$INJECT_LOCK.completed"; then
|
||||
release_clip_lock
|
||||
sleep 1
|
||||
return 0
|
||||
fi
|
||||
clip_in="$TMP_DIR/clip_in"
|
||||
clip_out="$TMP_DIR/clip_out"
|
||||
hdr_out="$TMP_DIR/clip_hdr"
|
||||
@@ -759,15 +834,39 @@ sync_clipboard() {
|
||||
local_kind="$synced_local_kind"
|
||||
cur_hash="$last_local_hash"
|
||||
else
|
||||
synced_local_cc=""
|
||||
read_clipboard_for_sync "$cur_cc"
|
||||
local_kind="$read_kind"
|
||||
cur_hash="$read_hash"
|
||||
fi
|
||||
if clipboard_poll_interrupted; then
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
# Recover the baseline after a successful text or PNG write whose
|
||||
# readback failed. A later copy has a different pasteboard change count.
|
||||
if [ "$local_kind" != error ] && [ -n "$readback_kind" ]; then
|
||||
if [ "$local_kind" = "$readback_kind" ]; then
|
||||
if [ -z "$read_cc" ]; then
|
||||
local_kind=error
|
||||
elif [ -z "$readback_cc" ] || [ "$read_cc" = "$readback_cc" ]; then
|
||||
last_local_hash="$cur_hash"
|
||||
fi
|
||||
fi
|
||||
if [ "$local_kind" != error ]; then readback_kind=""; fi
|
||||
fi
|
||||
if [ "$local_kind" != error ] && [ "$cur_cc" != "$synced_local_cc" ]; then
|
||||
synced_local_cc=""
|
||||
fi
|
||||
release_clip_lock
|
||||
post_conflict=0
|
||||
|
||||
if [ "$local_kind" != "empty" ] && [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then
|
||||
if [ "$local_kind" = files ]; then
|
||||
last_local_hash="$cur_hash"
|
||||
synced_local_cc="$read_cc"
|
||||
synced_local_kind="$local_kind"
|
||||
elif { [ "$local_kind" = text ] || [ "$local_kind" = png ]; } &&
|
||||
{ [ -n "$last_local_hash" ] || [ "$unreadable_baseline" = 1 ]; } &&
|
||||
[ "$cur_hash" != "$last_local_hash" ]; then
|
||||
ct="text/plain; charset=utf-8"
|
||||
[ "$local_kind" = "png" ] && ct="image/png"
|
||||
set --
|
||||
@@ -786,6 +885,7 @@ sync_clipboard() {
|
||||
synced_local_kind="$local_kind"
|
||||
last_server_hash=$(clip_header x-clip-hash)
|
||||
last_server_seq=$(clip_header x-clip-seq)
|
||||
file_retry_polls=0
|
||||
return 0
|
||||
;;
|
||||
204|413)
|
||||
@@ -803,12 +903,20 @@ 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"
|
||||
poll_hash="$last_server_hash"
|
||||
cooling_file=0
|
||||
if [ "$file_retry_polls" -gt 0 ]; then
|
||||
# Poll for a new event during cooldown without acknowledging delivery.
|
||||
cooling_file=1
|
||||
poll_hash="$file_retry_hash"
|
||||
file_retry_polls=$((file_retry_polls - 1))
|
||||
fi
|
||||
clip_url="$REIMS_HOST_URL/v1/clipboard?since=$poll_hash&wait=2&accept=image,files"
|
||||
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" \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" \
|
||||
"$clip_url" 2>/dev/null) || code=000
|
||||
case "$code" in
|
||||
200)
|
||||
@@ -816,17 +924,24 @@ sync_clipboard() {
|
||||
[ -n "$new_hash" ] || { sleep 2; return 0; }
|
||||
new_kind=$(clip_header x-clip-kind)
|
||||
new_seq=$(clip_header x-clip-seq)
|
||||
if [ "$cooling_file" = 1 ] && [ "$new_hash" = "$poll_hash" ]; then
|
||||
# A host that ignores conditional polls can return immediately.
|
||||
last_server_seq="$new_seq"
|
||||
sleep 2
|
||||
return 0
|
||||
fi
|
||||
file_retry_polls=0
|
||||
acquire_clip_lock || {
|
||||
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
|
||||
remember_pre_get_clipboard
|
||||
return 0
|
||||
}
|
||||
if inject_lock_active; then
|
||||
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
|
||||
if clipboard_poll_interrupted; then
|
||||
remember_pre_get_clipboard
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
read_clipboard_change_count
|
||||
if [ -n "$read_cc" ] && [ "$clip_cc" = "$read_cc" ]; then
|
||||
if [ "$local_kind" != error ] && [ -n "$read_cc" ] && [ "$clip_cc" = "$read_cc" ]; then
|
||||
read_ok=1
|
||||
read_kind="$local_kind"
|
||||
read_hash="$cur_hash"
|
||||
@@ -834,33 +949,67 @@ sync_clipboard() {
|
||||
read_clipboard_for_sync "$clip_cc"
|
||||
fi
|
||||
post_get_hash="$read_hash"
|
||||
if [ "$read_ok" = 0 ] || [ "$post_get_hash" != "$cur_hash" ]; then
|
||||
[ -n "$last_local_hash" ] || last_local_hash="$cur_hash"
|
||||
synced_local_cc=""
|
||||
last_server_seq="$new_seq"
|
||||
if clipboard_poll_interrupted; then
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
if [ "$new_hash" != "$cur_hash" ]; then
|
||||
if [ "$new_kind" = "png" ]; then
|
||||
if [ "$read_ok" = 0 ] ||
|
||||
{ [ "$local_kind" != error ] && [ "$post_get_hash" != "$cur_hash" ]; } ||
|
||||
{ [ "$local_kind" = error ] && [ -n "$cur_cc" ] && [ "$cur_cc" != "$read_cc" ]; }; then
|
||||
remember_pre_get_clipboard
|
||||
if [ "$read_ok" = 1 ]; then synced_local_cc=""; fi
|
||||
last_server_seq="$new_seq"
|
||||
if [ "$read_ok" = 0 ] && [ "$new_kind" = files ]; then defer_file_delivery; fi
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
if [ "$new_hash" != "$post_get_hash" ]; then
|
||||
if [ "$new_kind" = files ]; then
|
||||
if ! write_local_files "$clip_out" "$read_cc"; then
|
||||
defer_file_delivery
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
elif [ "$new_kind" = "png" ]; then
|
||||
write_local_png "$clip_out" || { release_clip_lock; sleep 2; return 0; }
|
||||
else
|
||||
pbcopy <"$clip_out" 2>/dev/null || { release_clip_lock; sleep 2; return 0; }
|
||||
fi
|
||||
read_clipboard_change_count
|
||||
read_clipboard_for_sync "$clip_cc"
|
||||
write_cc="$clip_cc"
|
||||
read_clipboard_for_sync "$write_cc"
|
||||
if clipboard_poll_interrupted; then
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
if [ "$new_kind" = files ] &&
|
||||
{ [ "$read_kind" != files ] || { [ -n "$write_cc" ] && [ "$read_cc" != "$write_cc" ]; }; }; then
|
||||
defer_file_delivery
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
post_get_hash="$read_hash"
|
||||
fi
|
||||
release_clip_lock
|
||||
last_local_hash="$post_get_hash"
|
||||
synced_local_cc="$read_cc"
|
||||
synced_local_kind="$read_kind"
|
||||
if [ "$read_ok" = 1 ]; then
|
||||
last_local_hash="$post_get_hash"
|
||||
synced_local_cc="$read_cc"
|
||||
synced_local_kind="$read_kind"
|
||||
readback_kind=""
|
||||
else
|
||||
readback_kind="${new_kind:-text}"
|
||||
readback_cc="$write_cc"
|
||||
fi
|
||||
last_server_hash="$new_hash"
|
||||
last_server_seq="$new_seq"
|
||||
;;
|
||||
204|304)
|
||||
if [ -z "$last_local_hash" ]; then
|
||||
last_local_hash="$cur_hash"
|
||||
if [ "$local_kind" = error ]; then
|
||||
unreadable_baseline=1
|
||||
else
|
||||
last_local_hash="$cur_hash"
|
||||
fi
|
||||
fi
|
||||
if [ "$code" = 204 ]; then
|
||||
last_server_seq=""
|
||||
@@ -874,7 +1023,7 @@ sync_clipboard() {
|
||||
last_local_hash="$cur_hash"
|
||||
fi
|
||||
fi
|
||||
if [ "$last_local_hash" = "$cur_hash" ]; then
|
||||
if [ "$local_kind" != error ] && [ "$last_local_hash" = "$cur_hash" ]; then
|
||||
synced_local_cc="$read_cc"
|
||||
synced_local_kind="$local_kind"
|
||||
fi
|
||||
@@ -914,13 +1063,37 @@ clipboard_loop() {
|
||||
|
||||
` + strings.ReplaceAll(guestFileSync+guestDropAgent, "\r\n", "\n") + `
|
||||
|
||||
inject_text() {
|
||||
if [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ]; then
|
||||
REIMS_TOKEN="$REIMS_TOKEN" osascript -l JavaScript "$APP_DIR/drop-resolve.js" inject-text \
|
||||
"$1" "$REIMS_HOST_URL/v1/text-input/ack" "$2" >/dev/null
|
||||
return $?
|
||||
fi
|
||||
|
||||
bak="$TMP_DIR/txt_clip_bak"
|
||||
cur_chk="$TMP_DIR/txt_clip_chk"
|
||||
bak_kind=$(read_local_clipboard "$bak" keep_tiff)
|
||||
[ "$bak_kind" != error ] || return 1
|
||||
pbcopy <"$1" 2>/dev/null || return 1
|
||||
inj_hash=$(hash_file "$1")
|
||||
curl -fsS -m 8 -X POST -H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
"$REIMS_HOST_URL/v1/text-input/ack?id=$2" >/dev/null 2>&1 || 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
|
||||
}
|
||||
|
||||
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"
|
||||
cur_chk="$TMP_DIR/txt_clip_chk"
|
||||
while :; do
|
||||
load_conf
|
||||
if [ -z "$REIMS_HOST_URL" ] || [ -z "$REIMS_TOKEN" ]; then
|
||||
@@ -932,6 +1105,7 @@ 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")
|
||||
[ -n "$input_id" ] || continue
|
||||
attempts=0
|
||||
while ! acquire_clip_lock; do
|
||||
attempts=$((attempts + 1))
|
||||
@@ -941,30 +1115,10 @@ text_input_loop() {
|
||||
[ "$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
|
||||
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
|
||||
inject_text "$body" "$input_id" || echo "Text injection failed" >&2
|
||||
# A poll that released the lock for its GET still holds an older snapshot.
|
||||
mv -f "$INJECT_LOCK" "$INJECT_LOCK.completed" || rm -f "$INJECT_LOCK"
|
||||
trap - EXIT
|
||||
rm -f "$INJECT_LOCK" 2>/dev/null || true
|
||||
release_clip_lock
|
||||
elif [ "$code" != "204" ]; then
|
||||
sleep 1
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func checkClipboardDrive(string) error { return nil }
|
||||
|
||||
func canonicalExistingPath(name string) (string, error) {
|
||||
return filepath.EvalSymlinks(name)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,25 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var clipboardDriveType = windows.GetDriveType
|
||||
|
||||
func checkClipboardDrive(root string) error {
|
||||
// Only ordinary drive letters can identify a local clipboard volume.
|
||||
if _, ok := NormalizeDriveLetter(root); !ok {
|
||||
return os.ErrPermission
|
||||
}
|
||||
ptr, err := windows.UTF16PtrFromString(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch clipboardDriveType(ptr) {
|
||||
case windows.DRIVE_FIXED, windows.DRIVE_REMOVABLE, windows.DRIVE_RAMDISK, windows.DRIVE_CDROM:
|
||||
return nil
|
||||
default:
|
||||
return os.ErrPermission
|
||||
}
|
||||
}
|
||||
|
||||
func finalWindowsPath(f *os.File) (string, error) {
|
||||
buf := make([]uint16, windows.MAX_PATH)
|
||||
for {
|
||||
|
||||
+136
-27
@@ -21,6 +21,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
@@ -31,7 +32,8 @@ import (
|
||||
const (
|
||||
DefaultPort = 19847
|
||||
MaxPort = 19860
|
||||
MaxClipboardBytes = 16 << 20 // 16 MiB (supports Retina PNG screenshots)
|
||||
MaxClipboardBytes = 16 << 20 // 16 MiB (supports Retina PNG screenshots)
|
||||
MaxClipboardFiles = 256
|
||||
MaxTextInputBytes = 1 << 20 // 1 MiB per injected text payload
|
||||
MaxUploadBytes = 256 << 20 // 256 MiB
|
||||
MaxSharedFiles = 2000
|
||||
@@ -52,13 +54,28 @@ type ClipKind string
|
||||
const (
|
||||
ClipEmpty ClipKind = ""
|
||||
ClipText ClipKind = "text"
|
||||
ClipFiles ClipKind = "files"
|
||||
ClipPNG ClipKind = "png"
|
||||
)
|
||||
|
||||
// ClipPayload holds a single clipboard item (either UTF-8 text or PNG bytes).
|
||||
// ClipPayload holds a single clipboard item.
|
||||
type ClipPayload struct {
|
||||
Kind ClipKind
|
||||
Data []byte
|
||||
Kind ClipKind
|
||||
Data []byte
|
||||
Files []string
|
||||
// A text or image format read alongside Files while the clipboard was locked.
|
||||
companion *ClipPayload
|
||||
}
|
||||
|
||||
func withClipboardFiles(files []string, content ClipPayload) ClipPayload {
|
||||
if len(files) == 0 {
|
||||
return content
|
||||
}
|
||||
payload := ClipPayload{Kind: ClipFiles, Files: files}
|
||||
if content.Kind != ClipEmpty {
|
||||
payload.companion = &content
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// Clipboard abstracts host OS clipboard reads/writes for testing.
|
||||
@@ -537,8 +554,11 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
textNotify: make(chan struct{}),
|
||||
}
|
||||
cur.dropDAVHandler = &webdav.Handler{
|
||||
Prefix: "/dav-drop/" + cur.name,
|
||||
FileSystem: &dropWebDAVFS{store: cur.dropShares},
|
||||
Prefix: "/dav-drop/" + cur.name,
|
||||
FileSystem: &dropWebDAVFS{
|
||||
store: cur.dropShares,
|
||||
allowClipboard: func() bool { return s.EffectiveClipboardPolicy(key).allowsHostToGuest() },
|
||||
},
|
||||
LockSystem: webdav.NewMemLS(),
|
||||
}
|
||||
s.vms[key] = cur
|
||||
@@ -661,7 +681,7 @@ func (s *Server) SetHostTextHandler(fn func(vmKey, vmName, text string)) {
|
||||
// InjectText delivers arbitrary UTF-8 text (including CJK/emoji) into a running
|
||||
// macOS VM without Accessibility permissions:
|
||||
// - Guest Tools v3 (preferred): pushes text over /v1/text-input, waits for
|
||||
// the guest to run pbcopy and POST /v1/text-input/ack, invokes pasteFn
|
||||
// the guest to stage the text and POST /v1/text-input/ack, invokes pasteFn
|
||||
// (QMP Command+V), waits briefly for the focused app to consume NSPasteboard,
|
||||
// then unblocks the ack so the guest restores its previous clipboard.
|
||||
// - Guest Tools v2 (fallback): serves a one-shot clipboard override on
|
||||
@@ -688,7 +708,7 @@ func (s *Server) InjectText(ctx context.Context, vmName, text string, pasteFn fu
|
||||
return "", ErrGuestToolsNotConnected
|
||||
}
|
||||
|
||||
// Serialize per-VM injections so two phrases never overlap pbcopy/Cmd+V.
|
||||
// Serialize per-VM injections so staging one phrase cannot interrupt another paste.
|
||||
vm.injectMu.Lock()
|
||||
defer vm.injectMu.Unlock()
|
||||
|
||||
@@ -905,7 +925,6 @@ func (s *Server) authenticateToken(tok string) *registeredVM {
|
||||
key: vm.key,
|
||||
name: vm.name,
|
||||
token: vm.token,
|
||||
dropShares: vm.dropShares,
|
||||
dropDAVHandler: vm.dropDAVHandler,
|
||||
sharedDir: vm.sharedDir,
|
||||
sharedRoot: vm.sharedRoot,
|
||||
@@ -955,6 +974,9 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "keymap-carrier", "drop-events", "drop-webdav", "drop-paste"}
|
||||
if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled {
|
||||
if policy.allowsHostToGuest() {
|
||||
caps = append(caps, "clipboard-files")
|
||||
}
|
||||
caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...)
|
||||
if policy.SyncImages {
|
||||
caps = append([]string{"clipboard-png"}, caps...)
|
||||
@@ -1062,11 +1084,11 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) {
|
||||
func (s *Server) readClipboardState(wantImage, wantFiles bool) (ClipPayload, uint32, error) {
|
||||
if clip, ok := s.clip.(interface {
|
||||
readClipboard(bool) (ClipPayload, uint32, error)
|
||||
readClipboard(bool, bool) (ClipPayload, uint32, error)
|
||||
}); ok {
|
||||
return clip.readClipboard(wantImage)
|
||||
return clip.readClipboard(wantImage, wantFiles)
|
||||
}
|
||||
// A clipboard without atomic snapshots can return a newer payload with
|
||||
// this sequence, which is safe for a subsequent conditional write.
|
||||
@@ -1075,14 +1097,15 @@ func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error)
|
||||
return payload, seq, err
|
||||
}
|
||||
|
||||
func (s *Server) readClipboardForSync(wantImage bool) (ClipPayload, uint32, string, error) {
|
||||
func (s *Server) readClipboardForSync(wantImage, wantFiles bool) (ClipPayload, uint32, string, error) {
|
||||
if clip, ok := s.clip.(interface {
|
||||
// The returned data is immutable and can be passed to io.Writer.
|
||||
readClipboardForSync(bool) (ClipPayload, uint32, string, error)
|
||||
// For files, the cached hash describes the companion, if present.
|
||||
readClipboardForSync(bool, bool) (ClipPayload, uint32, string, error)
|
||||
}); ok {
|
||||
return clip.readClipboardForSync(wantImage)
|
||||
return clip.readClipboardForSync(wantImage, wantFiles)
|
||||
}
|
||||
payload, seq, err := s.readClipboardState(wantImage)
|
||||
payload, seq, err := s.readClipboardState(wantImage, wantFiles)
|
||||
return payload, seq, "", err
|
||||
}
|
||||
|
||||
@@ -1110,14 +1133,102 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func acceptsClipFormat(raw, want string) bool {
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
if strings.EqualFold(strings.TrimSpace(part), want) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func prepareClipboardFiles(rawPaths []string) []DropShareEntry {
|
||||
if len(rawPaths) > MaxClipboardFiles {
|
||||
return nil
|
||||
}
|
||||
used := make(map[string]bool)
|
||||
var entries []DropShareEntry
|
||||
for _, raw := range rawPaths {
|
||||
if raw == "" || strings.ContainsRune(raw, '\x00') ||
|
||||
strings.HasPrefix(strings.ReplaceAll(raw, "\\", "/"), "//") || !filepath.IsAbs(raw) {
|
||||
continue
|
||||
}
|
||||
clean := filepath.Clean(raw)
|
||||
st, err := statDropPath(clean, true)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
base := filepath.Base(clean)
|
||||
if !filepath.IsLocal(base) || base == "." || base == ".." ||
|
||||
strings.ContainsAny(base, "/\\\x00:<>|\"?*\r\n") || strings.IndexFunc(base, unicode.IsControl) >= 0 {
|
||||
continue
|
||||
}
|
||||
ext := ""
|
||||
if !st.IsDir() {
|
||||
ext = filepath.Ext(base)
|
||||
}
|
||||
alias := base
|
||||
for i := 1; used[strings.ToLower(alias)]; i++ {
|
||||
alias = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(base, ext), i, ext)
|
||||
}
|
||||
used[strings.ToLower(alias)] = true
|
||||
entries = append(entries, DropShareEntry{Name: alias, HostPath: clean, IsDir: st.IsDir()})
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func (s *Server) clipboardFileManifest(vmKey string, seq uint32, entries []DropShareEntry) (ClipPayload, string) {
|
||||
// A new copy needs a fresh WebDAV URL even if the guest last synced the
|
||||
// same paths. On-disk edits alone must leave the clipboard untouched.
|
||||
h := sha256.New()
|
||||
fmt.Fprintf(h, "files:%d\x00", seq)
|
||||
items := make([]string, len(entries))
|
||||
for i, entry := range entries {
|
||||
items[i] = entry.Name
|
||||
fmt.Fprintf(h, "%s\x00%s\x00", entry.HostPath, entry.Name)
|
||||
}
|
||||
hash := hex.EncodeToString(h.Sum(nil))
|
||||
dropID := "clip-" + hash[:16]
|
||||
if !s.ensureClipboardShare(vmKey, dropID, entries) {
|
||||
return ClipPayload{}, ""
|
||||
}
|
||||
body, _ := json.Marshal(struct {
|
||||
DropID string `json:"drop_id"`
|
||||
Items []string `json:"items"`
|
||||
}{dropID, items})
|
||||
return ClipPayload{Kind: ClipFiles, Data: body}, hash
|
||||
}
|
||||
|
||||
func (s *Server) clipboardForGuest(vmKey string, payload ClipPayload, seq uint32, hash string, wantFiles, wantImage bool, maxImageBytes int) (ClipPayload, string) {
|
||||
if payload.Kind == ClipFiles {
|
||||
if wantFiles {
|
||||
if entries := prepareClipboardFiles(payload.Files); len(entries) > 0 {
|
||||
return s.clipboardFileManifest(vmKey, seq, entries)
|
||||
}
|
||||
}
|
||||
if payload.companion == nil {
|
||||
return ClipPayload{}, ""
|
||||
}
|
||||
payload = *payload.companion
|
||||
}
|
||||
if payload.Kind == ClipText || (payload.Kind == ClipPNG && wantImage && len(payload.Data) <= maxImageBytes) {
|
||||
if hash == "" {
|
||||
hash = payloadHash(payload)
|
||||
}
|
||||
return payload, hash
|
||||
}
|
||||
return ClipPayload{}, ""
|
||||
}
|
||||
|
||||
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) {
|
||||
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)
|
||||
wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
|
||||
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")
|
||||
since := r.URL.Query().Get("since")
|
||||
sinceSeq, seqErr := strconv.ParseUint(r.URL.Query().Get("since_seq"), 10, 32)
|
||||
hasSinceSeq := seqErr == nil
|
||||
@@ -1129,7 +1240,7 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
writeFeatureDisabled(w, "clipboard")
|
||||
return
|
||||
}
|
||||
if policy.Direction != ClipboardGuestToHost {
|
||||
if policy.allowsHostToGuest() {
|
||||
if ov := s.takeClipOverride(vmKey); ov != nil {
|
||||
s.touchLastSeen(vmKey)
|
||||
atomic.AddUint64(&s.clipStatsH2G, 1)
|
||||
@@ -1143,18 +1254,14 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
}
|
||||
|
||||
wantImage := wantsImage && policy.SyncImages
|
||||
payload, seq, h, err := s.readClipboardForSync(wantImage)
|
||||
payload, seq, h, err := s.readClipboardForSync(wantImage, wantsFiles)
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.clipStatsErr, 1)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG &&
|
||||
wantImage && len(payload.Data) <= policy.MaxImageBytes)
|
||||
if syncable {
|
||||
if h == "" {
|
||||
h = payloadHash(payload)
|
||||
}
|
||||
payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantsFiles, wantImage, policy.MaxImageBytes)
|
||||
if h != "" {
|
||||
unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq))
|
||||
if !unchanged || time.Until(deadline) <= 0 {
|
||||
setClipboardSeq(w, seq)
|
||||
@@ -1166,7 +1273,9 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
return
|
||||
}
|
||||
atomic.AddUint64(&s.clipStatsH2G, 1)
|
||||
if payload.Kind == ClipPNG {
|
||||
if payload.Kind == ClipFiles {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
} else if payload.Kind == ClipPNG {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
@@ -1279,7 +1388,7 @@ func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint3
|
||||
if baseSeq != nil && seq != *baseSeq {
|
||||
return seq, errClipboardConflict
|
||||
}
|
||||
current, seq, err := s.readClipboardState(true)
|
||||
current, seq, err := s.readClipboardState(true, false)
|
||||
if err == nil {
|
||||
if baseSeq != nil && seq != *baseSeq {
|
||||
return seq, errClipboardConflict
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
// Run the installed JXA resolver against a pasteboard shared by shell fixture processes.
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const {pathToFileURL} = require('node:url')
|
||||
|
||||
const [resolver, ...argv] = process.argv.slice(2)
|
||||
const stateFile = 'test-pasteboard.json'
|
||||
const state = fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile)) : {changeCount: 0, items: []}
|
||||
const nil = {isNil: () => true}
|
||||
const wrap = js => js == null ? nil : {
|
||||
js, isNil: () => false, dataUsingEncoding: () => js
|
||||
}
|
||||
const unwrap = value => value?.js ?? value
|
||||
const array = values => ({
|
||||
count: values.length, isNil: () => false, objectAtIndex: i => values[i],
|
||||
containsObject: v => values.some(entry => unwrap(entry) === unwrap(v))
|
||||
})
|
||||
const item = (flavors = {}) => ({
|
||||
flavors,
|
||||
get types() { return array(Object.keys(flavors).map(wrap)) },
|
||||
dataForType: type => wrap(flavors[unwrap(type)]),
|
||||
stringForType: type => wrap(flavors[unwrap(type)]),
|
||||
setDataForType(value, type) { flavors[unwrap(type)] = unwrap(value); return true },
|
||||
setStringForType(value, type) { flavors[unwrap(type)] = unwrap(value); return true }
|
||||
})
|
||||
|
||||
const pasteboard = {
|
||||
get pasteboardItems() {
|
||||
const items = state.items.map(item)
|
||||
if (fs.existsSync('test-reverse-file-readback')) items.reverse()
|
||||
return array(items)
|
||||
},
|
||||
get changeCount() { return state.changeCount },
|
||||
get clearContents() { state.items = []; return ++state.changeCount },
|
||||
writeObjects(items) {
|
||||
state.items = items.map(i => i.flavors)
|
||||
state.changeCount++
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// The host reads the staged clipboard, optionally allowing a user copy before it releases the ACK.
|
||||
class CurlTask {
|
||||
get waitUntilExit() {
|
||||
fs.writeFileSync('test-ack.json', JSON.stringify({
|
||||
path: this.launchPath, args: this.arguments, config: this.standardInput.config, items: state.items
|
||||
}))
|
||||
if (fs.existsSync('test-user-copy.json')) {
|
||||
state.items = JSON.parse(fs.readFileSync('test-user-copy.json'))
|
||||
state.changeCount++
|
||||
}
|
||||
this.terminationStatus = fs.existsSync('test-fail-ack') ? 22 : 0
|
||||
}
|
||||
}
|
||||
|
||||
const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value, {
|
||||
NSPasteboard: {generalPasteboard: pasteboard},
|
||||
NSPasteboardItem: {alloc: {get init() { return item() }}},
|
||||
NSPasteboardTypeFileURL: 'public.file-url',
|
||||
NSPasteboardTypeString: 'public.utf8-plain-text',
|
||||
NSData: {data: wrap('')},
|
||||
NSString: {stringWithContentsOfFileEncodingError: path => wrap(fs.readFileSync(path, 'utf8'))},
|
||||
NSURL: {fileURLWithPath: path => ({
|
||||
absoluteString: wrap(pathToFileURL(path).href), fileReferenceURL: fs.existsSync(path) ? wrap(path) : nil
|
||||
})},
|
||||
NSFileManager: {defaultManager: {
|
||||
fileExistsAtPathIsDirectory(path, dir) {
|
||||
dir[0] = fs.statSync(path, {throwIfNoEntry: false})?.isDirectory() ?? false
|
||||
return fs.existsSync(path)
|
||||
},
|
||||
contentsOfDirectoryAtPathError: path => fs.readdirSync(path),
|
||||
fileExistsAtPath: fs.existsSync
|
||||
}},
|
||||
NSDate: {dateWithTimeIntervalSinceNow: seconds => seconds},
|
||||
NSRunLoop: {currentRunLoop: {runUntilDate: () => fs.writeFileSync('test-pasteboard-flush', String(state.changeCount))}},
|
||||
NSProcessInfo: {processInfo: {environment: {objectForKey: key => wrap(process.env[unwrap(key)])}}},
|
||||
NSTask: {alloc: {get init() { return new CurlTask() }}},
|
||||
NSPipe: {get pipe() {
|
||||
const pipe = {fileHandleForWriting: {writeData(data) { pipe.config = data }}}
|
||||
return pipe
|
||||
}},
|
||||
NSFileHandle: {fileHandleWithNullDevice: null}
|
||||
})
|
||||
const context = {ObjC: {import() {}, unwrap}, $, argv, Ref: () => []}
|
||||
try {
|
||||
console.log(vm.runInNewContext(fs.readFileSync(resolver, 'utf8') + '\nrun(argv)', context))
|
||||
} finally {
|
||||
fs.writeFileSync(stateFile, JSON.stringify(state))
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGuestAgentTextInjection(t *testing.T) {
|
||||
sh, err := exec.LookPath("sh")
|
||||
if err != nil {
|
||||
t.Skip("POSIX sh is unavailable")
|
||||
}
|
||||
fixture, err := filepath.Abs("testdata/pasteboard.cjs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent := string(GuestAgentScript())
|
||||
script := "set -eu\n" + scriptSection(t, agent, "read_local_clipboard() {", "\nsync_files() {") +
|
||||
scriptSection(t, agent, "inject_text() {", "\ntext_input_loop &") + textInjectionFixture
|
||||
const phrase = "远程输入 📝"
|
||||
original := []map[string]string{
|
||||
{"public.file-url": "file:///share/first", "public.utf8-plain-text": "first", "public.png": "iVBORw0KGgo=", "public.tiff": "SUkqAA=="},
|
||||
{"public.file-url": "file:///share/second", "example.custom": "opaque"},
|
||||
}
|
||||
userCopy := []map[string]string{{"public.utf8-plain-text": phrase}} // Same text, different owner and flavors.
|
||||
for _, scenario := range []string{"files", "failed_ack", "user_copy", "legacy"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
lockShellFixture(t)
|
||||
dir := t.TempDir()
|
||||
write := func(name string, value []byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), value, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
read := func(name string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
items, err := json.Marshal(original)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write("test-pasteboard.json", []byte(`{"changeCount":17,"items":`+string(items)+"}"))
|
||||
if scenario != "legacy" {
|
||||
write("drop-resolve.js", []byte(guestDropResolveJS))
|
||||
}
|
||||
if scenario == "user_copy" {
|
||||
next, err := json.Marshal(userCopy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write("test-user-copy.json", next)
|
||||
}
|
||||
if scenario == "failed_ack" {
|
||||
write("test-fail-ack", nil)
|
||||
}
|
||||
write("body", []byte(phrase))
|
||||
cmd := exec.Command(sh, "-s", "--", scenario)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "PASTEBOARD_FIXTURE="+filepath.ToSlash(fixture))
|
||||
cmd.Stdin = strings.NewReader(script)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("guest injection: %v\n%s", err, out)
|
||||
}
|
||||
if scenario == "legacy" {
|
||||
return
|
||||
}
|
||||
var ack struct {
|
||||
Path string
|
||||
Args []string
|
||||
Config string
|
||||
Items []map[string]string
|
||||
}
|
||||
if err := json.Unmarshal(read("test-ack.json"), &ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack.Path != "/usr/bin/curl" || !slices.Equal(ack.Args, []string{"-fsS", "-m", "10", "-X", "POST", "-K", "-"}) ||
|
||||
!strings.Contains(ack.Config, `url = "http://stub/v1/text-input/ack?id=7"`) ||
|
||||
!strings.Contains(ack.Config, `header = "Authorization: Bearer fixture-token"`) {
|
||||
t.Fatalf("unexpected ACK request: %+v", ack)
|
||||
}
|
||||
staged := []map[string]string{{"public.utf8-plain-text": phrase, "org.nspasteboard.TransientType": "", "org.nspasteboard.AutoGeneratedType": ""}}
|
||||
if !reflect.DeepEqual(ack.Items, staged) {
|
||||
t.Fatalf("pasteboard at ACK: %v, want %v", ack.Items, staged)
|
||||
}
|
||||
var after struct {
|
||||
ChangeCount json.Number
|
||||
Items []map[string]string
|
||||
}
|
||||
if err := json.Unmarshal(read("test-pasteboard.json"), &after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := original
|
||||
if scenario == "user_copy" {
|
||||
want = userCopy
|
||||
} else if !bytes.Equal(read("test-pasteboard-flush"), []byte(after.ChangeCount.String())) {
|
||||
t.Fatal("restored pasteboard was not flushed")
|
||||
}
|
||||
if !reflect.DeepEqual(after.Items, want) {
|
||||
t.Fatalf("restored items: %v, want %v", after.Items, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const textInjectionFixture = `
|
||||
TMP_DIR=. APP_DIR=. REIMS_HOST_URL=http://stub REIMS_TOKEN=fixture-token
|
||||
INJECT_LOCK=./injecting
|
||||
CLIP_LOCK=./clip.lock
|
||||
cur_pid=$$
|
||||
scenario=$1
|
||||
load_conf() { if [ -f ./txt_hdr ]; then exit 0; fi; }
|
||||
osascript() {
|
||||
if [ "$1" = -e ] && [ "$2" = 'clipboard info' ]; then
|
||||
if [ "$scenario" = legacy ]; then echo 'Unicode text'; else echo '«class furl», Unicode text'; fi
|
||||
return
|
||||
fi
|
||||
[ "$1" = -l ] && [ "$2" = JavaScript ] || return 1
|
||||
if [ "$3" = -e ]; then node -p 'require("./test-pasteboard.json").changeCount'; return; fi
|
||||
if [ "$4" = inject-text ]; then [ -f "$INJECT_LOCK" ] && [ -d "$CLIP_LOCK" ] || return 1; fi
|
||||
shift 2
|
||||
node "$PASTEBOARD_FIXTURE" "$@"
|
||||
}
|
||||
hash_file() { cat "$1"; }
|
||||
hash_files_file() { cat "$1"; }
|
||||
pbcopy() { echo pbcopy >> legacy-calls; cat > legacy-text; }
|
||||
pbpaste() { echo pbpaste >> legacy-calls; cat legacy-text; }
|
||||
curl() {
|
||||
case " $* " in
|
||||
*'/v1/text-input?wait=25 '*) printf 'X-Input-ID: 7\r\n' > ./txt_hdr; cp body ./txt_body; printf 200 ;;
|
||||
*'/v1/text-input/ack?id=7 '*) [ -d "$CLIP_LOCK" ] && cmp body legacy-text && echo ack >> legacy-calls ;;
|
||||
*' -X POST '*) echo POST >> calls; return 1 ;;
|
||||
*) echo GET >> calls; : > ./clip_hdr; printf 304 ;;
|
||||
esac
|
||||
}
|
||||
printf old > legacy-text
|
||||
(text_input_loop) 2> injection-errors
|
||||
[ ! -e "$INJECT_LOCK" ]
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
[ -f "$INJECT_LOCK.completed" ]
|
||||
if [ "$scenario" = failed_ack ]; then
|
||||
grep -q 'Text injection failed' injection-errors
|
||||
else
|
||||
[ ! -s injection-errors ] || { cat injection-errors >&2; exit 1; }
|
||||
fi
|
||||
if [ "$scenario" = legacy ]; then
|
||||
[ "$(cat legacy-text)" = old ] && [ "$(paste -sd , legacy-calls)" = pbpaste,pbcopy,ack,pbpaste,pbcopy ]
|
||||
exit $?
|
||||
fi
|
||||
if [ "$scenario" != user_copy ]; then
|
||||
last_local_hash=$(printf 'file:///share/first\nfile:///share/second')
|
||||
last_server_hash=windows-cut last_server_seq=7
|
||||
sync_clipboard
|
||||
sync_clipboard
|
||||
[ "$(paste -sd , calls)" = GET,GET ]
|
||||
[ "$last_local_hash" = "$(printf 'file:///share/first\nfile:///share/second')" ]
|
||||
fi
|
||||
[ ! -e legacy-calls ]
|
||||
`
|
||||
@@ -26,6 +26,10 @@ type ClipboardPolicy struct {
|
||||
MaxImageBytes int `json:"max_image_bytes"`
|
||||
}
|
||||
|
||||
func (p ClipboardPolicy) allowsHostToGuest() bool {
|
||||
return p.Enabled && p.Direction != ClipboardGuestToHost
|
||||
}
|
||||
|
||||
// DefaultClipboardPolicy returns the default bidirectional text+image policy.
|
||||
func DefaultClipboardPolicy() ClipboardPolicy {
|
||||
return ClipboardPolicy{
|
||||
@@ -102,6 +106,9 @@ func (s *Server) SetClipboardActive(active bool) {
|
||||
return
|
||||
}
|
||||
s.globalClipPolicy.Enabled = false
|
||||
for _, vm := range s.vms {
|
||||
vm.dropShares.revokeClipboard()
|
||||
}
|
||||
delete(s.dynamicRoutes, "/v1/clipboard")
|
||||
cancel := s.watchCancel
|
||||
s.watchCancel = nil
|
||||
@@ -130,6 +137,11 @@ func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) {
|
||||
p = normalizeClipboardPolicy(p)
|
||||
s.mu.Lock()
|
||||
s.globalClipPolicy = p
|
||||
for key, vm := range s.vms {
|
||||
if !s.effectiveClipboardPolicyLocked(key).allowsHostToGuest() {
|
||||
vm.dropShares.revokeClipboard()
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.broadcastClipChange()
|
||||
}
|
||||
@@ -146,6 +158,9 @@ func (s *Server) SetVMClipboardPolicy(vmName string, p *ClipboardPolicy) {
|
||||
} else {
|
||||
s.vmClipPolicies[vmName] = normalizeClipboardPolicy(*p)
|
||||
}
|
||||
if vm := s.vms[vmName]; vm != nil && !s.effectiveClipboardPolicyLocked(vmName).allowsHostToGuest() {
|
||||
vm.dropShares.revokeClipboard()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.broadcastClipChange()
|
||||
}
|
||||
@@ -155,6 +170,10 @@ func (s *Server) EffectiveClipboardPolicy(vmName string) ClipboardPolicy {
|
||||
vmName = normalizeVMRegistryKey(vmName)
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.effectiveClipboardPolicyLocked(vmName)
|
||||
}
|
||||
|
||||
func (s *Server) effectiveClipboardPolicyLocked(vmName string) ClipboardPolicy {
|
||||
if !s.clipboardActive {
|
||||
p := s.globalClipPolicy
|
||||
p.Enabled = false
|
||||
|
||||
Reference in new issue
Block a user