diff --git a/changes/clipboard-file-sync.json b/changes/clipboard-file-sync.json index b2a0c0d..8b2712b 100644 --- a/changes/clipboard-file-sync.json +++ b/changes/clipboard-file-sync.json @@ -1,7 +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." + "authors": ["YinLiaoCo", "staytomorrow", "yxc0915"], + "zh": "支持在 Windows 与 macOS 虚拟机之间复制粘贴文件和文件夹。Windows 中剪切的文件可粘贴到 macOS,原文件和剪切状态会保留。可在插件页或虚拟机设置中调整文件同步和传输上限。已有虚拟机需将 Guest Tools 更新至 `v16` 以使用双向文件同步。", + "en": "Copy and paste files and folders between Windows and macOS VMs. Pasting files cut in Windows into macOS preserves the original files and the Windows cut state. Adjust file sync and transfer limits in the plugin or VM settings. Update Guest Tools to `v16` in existing VMs for bidirectional file sync." } diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 50448a7..47454fd 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -34,12 +34,14 @@ interface Props { onLocaleSwitch?: (l: Locale) => void } -// The plugin settings dialog shows app-scope fields only; per-VM fields live in -// each VM's settings. Same scope rule as SchemaForm. +// VM-only settings are edited in each VM's settings. function hasAppSettings(p: PluginInfo): boolean { const schema = p.settings if (!schema) return false - return Object.values(schema.properties ?? {}).some((prop) => (prop['x-scope'] || schema['x-scope'] || 'app') === 'app') + return Object.values(schema.properties ?? {}).some((prop) => { + const scope = prop['x-scope'] || schema['x-scope'] || 'app' + return scope === 'app' || scope === 'both' + }) } /** Top-level Plugins & Themes management page. */ @@ -288,11 +290,11 @@ export const PluginsPage: React.FC = ({ } } - const savePluginSettings = async (next: Record) => { - setSettingsValues(next) + const savePluginSettings = async (patch: Record) => { + setSettingsValues((current) => ({ ...current, ...patch })) if (!settingsTarget) return try { - await api.SetPluginSettings(settingsTarget.id, '', next) + await api.SetPluginSettings(settingsTarget.id, '', patch) onRefresh() } catch (e) { onError(tr('pluginFailSaveSettings'), e) @@ -871,7 +873,7 @@ export const PluginsPage: React.FC = ({ schema={settingsTarget.settings} values={settingsValues} scopeFilter="app" - onChange={(next) => void savePluginSettings(next)} + onChange={(_, patch) => void savePluginSettings(patch)} />
diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index cc212d3..510feb1 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -13,7 +13,7 @@ interface Props { values: Record scopeFilter?: 'app' | 'vm' groupFilter?: string - onChange: (next: Record) => void + onChange: (next: Record, patch: Record) => void hideGroupHeader?: boolean } @@ -32,7 +32,7 @@ export const SchemaForm: React.FC = ({ const prop = propsMap[k] const effScope = prop['x-scope'] || schema['x-scope'] || 'app' const effGroup = prop['x-group'] || schema['x-group'] || '' - if (scopeFilter && effScope !== scopeFilter) return false + if (scopeFilter && effScope !== scopeFilter && effScope !== 'both') return false if (groupFilter && effGroup !== groupFilter) return false return true }) @@ -46,7 +46,7 @@ export const SchemaForm: React.FC = ({ next[ek] = ev } next[k] = v - onChange(next) + onChange(next, { [k]: v }) } const effectBadge = (prop: SettingProperty) => { diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 2783664..665cab2 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -257,9 +257,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats return () => { live = false } }, [driverID, detail.name]) - const updateVMPluginSetting = (pluginID: string, next: Record) => { - setVmPluginVals((prev) => ({ ...prev, [pluginID]: next })) - void api.SetPluginSettings(pluginID, vmSettingsKey, next).catch((e) => setErr(parseAppError(e).summary)) + const updateVMPluginSetting = (pluginID: string, patch: Record) => { + setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } })) + void api.SetPluginSettings(pluginID, vmSettingsKey, patch).catch((e) => setErr(parseAppError(e).summary)) } const renderVMPluginGroup = (group: string) => { @@ -275,7 +275,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats values={vmPluginVals[p.id] ?? {}} scopeFilter="vm" groupFilter={group} - onChange={(next) => updateVMPluginSetting(p.id, next)} + onChange={(_, patch) => updateVMPluginSetting(p.id, patch)} /> ))} diff --git a/internal/app/app.go b/internal/app/app.go index 11317d8..534d246 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1086,6 +1086,7 @@ func (a *App) SetDataRoot(dir string) error { a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked()) } a.root = st + a.syncClipboardStagingLocked() a.mu.Unlock() a.logDataRoot(st) diff --git a/internal/app/dataroot_flow.go b/internal/app/dataroot_flow.go index e27c5e4..39db36b 100644 --- a/internal/app/dataroot_flow.go +++ b/internal/app/dataroot_flow.go @@ -21,6 +21,7 @@ func (a *App) openDataRoot() dataroot.Status { st := dataroot.Open(dir, version.Version) a.mu.Lock() a.root = st + a.syncClipboardStagingLocked() a.mu.Unlock() a.logDataRoot(st) return st @@ -97,6 +98,7 @@ func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) { } a.mu.Lock() a.root = st + a.syncClipboardStagingLocked() a.mu.Unlock() a.logDataRoot(st) diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 5b90b25..f75aa5f 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -162,6 +162,7 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() }) created = true } + a.syncClipboardStagingLocked() a.mu.Unlock() port, err = srv.Start(guesttools.DefaultPort) @@ -171,6 +172,18 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created return srv, port, created, nil } +// syncClipboardStagingLocked rebinds the current bridge as the data root changes. +func (a *App) syncClipboardStagingLocked() { + if a.guestTools == nil { + return + } + dir := "" + if a.cfg != nil && a.cfg.DataRoot != "" && !a.needsSetup && !a.root.ReadOnly { + dir = filepath.Join(a.cfg.TempDir(), "clip-files") + } + a.guestTools.SetClipStagingDir(dir) +} + // ensureGuestToolsBridge returns the bridge for features built on Guest Tools. // With the plugin system up it only hands out the server the Guest Tools // plugin provides, so switching that plugin off really stops the localhost diff --git a/internal/app/guesttools_toggle_test.go b/internal/app/guesttools_toggle_test.go index 51a8440..93e8558 100644 --- a/internal/app/guesttools_toggle_test.go +++ b/internal/app/guesttools_toggle_test.go @@ -2,11 +2,16 @@ package app import ( "context" + "fmt" + "net/http" + "os" + "path/filepath" "strings" "testing" "time" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" @@ -73,3 +78,121 @@ func TestGuestToolsBridgeFollowsPluginSwitch(t *testing.T) { t.Fatal("plugin switched back off: Guest Tools still reported as available") } } + +func TestClipboardFileSettingsInheritAndOverrideGlobalDefaults(t *testing.T) { + srv := guesttools.NewTransportServer(nil) + cfg := config.Default() + cfg.DataRoot = t.TempDir() + a := &App{cfg: cfg, guestTools: srv} + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: cfg.DataRoot, + HostVersion: "0.0.0", + OnSettingsChanged: a.onPluginSettingsChanged, + }) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + a.pluginMgr = mgr + + err = builtin.RegisterAll(mgr.Registry(), builtin.HostCallbacks{ + EnsureGuestTools: func() (*guesttools.Server, int, error) { return srv, 1, nil }, + }, func(id string, _ bool) bool { return id == builtin.IDGuestTools || id == builtin.IDClipboard }) + if err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + if !mgr.Registry().IsActive(builtin.IDClipboard) { + t.Fatal("clipboard plugin did not activate") + } + + vm := driver.NewVMRef("", "mac").Key() + set := func(vmKey string, vals map[string]any) { + t.Helper() + if err := a.SetPluginSettings(builtin.IDClipboard, vmKey, vals); err != nil { + t.Fatal(err) + } + } + set(vm, map[string]any{"sync_images": false, "direction": "host-to-guest"}) + set("", map[string]any{"sync_files": false, "max_file_mb": 64}) + policy := srv.EffectiveClipboardPolicy(vm) + if !policy.Enabled || policy.SyncFiles || policy.MaxFileBytes != 64<<20 || + policy.SyncImages || policy.Direction != guesttools.ClipboardHostToGuest { + t.Fatalf("global file defaults or existing VM policies lost: %+v", policy) + } + settings := a.GetVMPluginSettings(vm)[builtin.IDClipboard] + if settings["sync_files"] != false || settings["max_file_mb"] != 64 { + t.Fatalf("VM settings should display inherited values, got %v", settings) + } + + set(vm, map[string]any{"max_file_mb": 256}) + set("", map[string]any{"sync_files": true, "max_file_mb": 32}) + policy = srv.EffectiveClipboardPolicy(vm) + if !policy.SyncFiles || policy.MaxFileBytes != 256<<20 { + t.Fatalf("VM must inherit the new toggle and retain its own limit, got %+v", policy) + } + if peer := srv.EffectiveClipboardPolicy(driver.NewVMRef("", "peer").Key()); !peer.SyncFiles || peer.MaxFileBytes != 32<<20 { + t.Fatalf("unconfigured VM should use global defaults, got %+v", peer) + } +} + +func TestClipboardStagingFollowsWritableDataRoot(t *testing.T) { + cfg := config.Default() + cfg.DataRoot = t.TempDir() + srv := guesttools.NewServer(&guesttools.OSClipboard{}) + a := &App{cfg: cfg, needsSetup: true, guestTools: srv} + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = srv.Close(ctx) + }() + _, port, _, err := a.startGuestToolsServer() + if err != nil { + t.Fatal(err) + } + const token = "clipboard-setup-transition-token" + srv.RegisterVM(guesttools.VMConfig{VMName: "mac", Token: token}) + client := &http.Client{Timeout: time.Second} + postInvalidArchive := func(want int) { + t.Helper() + // Invalid archives reach staging validation without mutating the host clipboard. + address := fmt.Sprintf("http://127.0.0.1:%d/v1/clipboard", port) + req, err := http.NewRequest(http.MethodPost, address, strings.NewReader("invalid archive")) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/x-tar") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("POST clipboard archive returned %d, want %d", resp.StatusCode, want) + } + } + updateRoot := func(dir string, readOnly bool) { + a.mu.Lock() + defer a.mu.Unlock() + a.cfg.DataRoot = dir + a.needsSetup = false + a.root.ReadOnly = readOnly + a.syncClipboardStagingLocked() + } + + postInvalidArchive(http.StatusServiceUnavailable) + if entries := dirEntries(t, cfg.DataRoot); len(entries) != 0 { + t.Fatalf("staging used suggested data folder: %v", entries) + } + for i := 0; i < 2; i++ { + dir := t.TempDir() + updateRoot(dir, false) + postInvalidArchive(http.StatusBadRequest) + if info, err := os.Stat(filepath.Join(dir, "tmp", "clip-files")); err != nil || !info.IsDir() { + t.Fatalf("writable root %q was not used for staging: %v", dir, err) + } + } + updateRoot(cfg.DataRoot, true) + postInvalidArchive(http.StatusServiceUnavailable) +} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index ce09ffc..6af9b3b 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -486,12 +486,12 @@ func (a *App) syncClipboardPolicies() { } globalVals := mgr.GetSettings(builtin.IDClipboard, "", false) gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals)) - for vmKey, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) { + for vmKey := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) { ref, ok := driver.ParseVMRef(vmKey) if !ok { ref = driver.NewVMRef("", vmKey) } - pol := clipboardPolicyFromMap(vmVals) + pol := clipboardPolicyFromMap(mgr.GetSettings(builtin.IDClipboard, vmKey, false)) gt.SetVMClipboardPolicy(ref.Key(), &pol) } } @@ -499,23 +499,7 @@ func (a *App) syncClipboardPolicies() { func (a *App) onPluginSettingsChanged(pluginID, vmName string) { a.syncInputFilters() if pluginID == builtin.IDClipboard { - a.mu.Lock() - mgr := a.pluginMgr - gt := a.guestTools - a.mu.Unlock() - if mgr != nil && gt != nil { - vals := mgr.GetSettings(builtin.IDClipboard, vmName, false) - pol := clipboardPolicyFromMap(vals) - if vmName == "" { - gt.SetGlobalClipboardPolicy(pol) - } else { - ref, ok := driver.ParseVMRef(vmName) - if !ok { - ref = driver.NewVMRef("", vmName) - } - gt.SetVMClipboardPolicy(ref.Key(), &pol) - } - } + a.syncClipboardPolicies() } if pluginID == guest.ID && vmName == "" { a.mu.Lock() @@ -564,6 +548,19 @@ func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy { p.MaxImageBytes = v << 20 } } + if v, ok := vals["sync_files"].(bool); ok { + p.SyncFiles = v + } + var fileMB float64 + switch v := vals["max_file_mb"].(type) { + case int: + fileMB = float64(v) + case float64: + fileMB = v + } + if fileMB > 0 && !math.IsInf(fileMB, 0) { + p.MaxFileBytes = int(math.Round(min(max(fileMB, guesttools.MinClipboardMaxFileMB), guesttools.MaxClipboardMaxFileMB))) << 20 + } return p } diff --git a/internal/app/setup.go b/internal/app/setup.go index 2058c71..720d995 100644 --- a/internal/app/setup.go +++ b/internal/app/setup.go @@ -142,6 +142,7 @@ func (a *App) CompleteSetup(dir string) error { a.cfg = cfg a.needsSetup = false a.root = st + a.syncClipboardStagingLocked() a.mu.Unlock() a.logDataRoot(st) // Nothing touching the data folder ran before setup (startup), so plugins diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 0d1dea0..250d75b 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -105,7 +105,8 @@ 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_delivery", []string{"host_files_sync_no_echo", "host_files_reordered_readback", "host_files_failed_write", "host_files_partial_write", "guest_files_do_not_overwrite_host", "foreign_drop_mount", "host_files_tar_fallback", "host_files_tar_fallback_changed"}}, + {"file_upload", []string{"guest_files_tar_upload", "guest_files_legacy_no_upload", "guest_files_tar_hosted_no_upload", "guest_files_tar_upload_changed", "guest_files_tar_upload_retry"}}, {"file_retry", []string{ "host_files_remount_and_fail_no_spin", "host_files_new_event_during_retry", "host_ignores_conditional_file_retry", "host_files_retry_preserves_new_copy", @@ -139,7 +140,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { if err != nil { t.Fatal(err) } - for _, name := range []string{"host_files_sync_no_echo", "host_files_reordered_readback"} { + for _, name := range []string{"host_files_sync_no_echo", "host_files_reordered_readback", "host_files_failed_write", "host_files_partial_write", "host_files_tar_fallback", "host_files_tar_fallback_changed"} { if err := os.WriteFile(filepath.Join(tmp, name, "drop-resolve.js"), []byte(guestDropResolveJS), 0o600); err != nil { t.Fatal(err) } @@ -164,10 +165,47 @@ func TestGuestAgentClipboardScript(t *testing.T) { } } +func TestGuestAgentLocalFileClipboardPaths(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("Node.js is unavailable") + } + fixture, err := filepath.Abs("testdata/pasteboard.cjs") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + urls := strings.Join([]string{ + "file:///Users/guest/Desktop/local%20file.txt", + "file:///Users/guest/Desktop/local%20file.txt", + "file:///private/guest/dropmount/shared", + "file:///Volumes/DropAlias/shared", + "file:///.file/example", + "file:///private/guest/cache/clip-batch/fallback", + "file:///private/guest/", + "file:///private/guest/DropMount-neighbor/local/", + "file://server/volume/network", + }, "\n") + if err := os.WriteFile(filepath.Join(dir, "urls"), []byte(urls), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "resolver.js"), []byte(guestDropResolveJS), 0o600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(t.Context(), node, fixture, "resolver.js", "local-clip-paths", "urls", + "/private/guest/DropMount", "/private/guest/cache") + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if want := "/Users/guest/Desktop/local file.txt\n/private/guest/DropMount-neighbor/local\n"; err != nil || string(out) != want { + t.Fatalf("guest file clipboard paths: got %q, want %q, error %v", out, want, err) + } +} + const clipboardShellFixture = ` TMP_DIR=. APP_DIR=. DROP_MOUNT=./drop_mount +CLIP_CACHE=./clip_cache INJECT_LOCK=./injecting DROP_INJECT_LOCK=./drop-injecting CLIP_LOCK=./clip.lock @@ -194,6 +232,11 @@ post_hash=C post_seq=9 check_post_base=0 +# MSYS cannot apply RLIMIT_FSIZE. The fixture still verifies the archive and HTTP flow. +case "$(uname -s)" in + MINGW*|MSYS*) ulimit() { [ "$1" = -f ] && [ "$2" -gt 0 ]; } ;; +esac + date() { [ "$1" = +%s ] && printf '%s\n' "$now"; } read_file() { line= @@ -276,10 +319,11 @@ osascript() { fi ;; write-clip-files) - [ "$6" = "$DROP_MOUNT" ] && [ "$(read_file "$5")" = "$get_value" ] || return 1 + { [ "$6" = "$DROP_MOUNT" ] || [ "$6/${8:-}" = "$CLIP_CACHE/cache" ]; } && + [ "$(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 + node "$PASTEBOARD_FIXTURE" "$3" write-clip-files "$5" "$6" "$7" "${8:-}" || return 1 : > file_clip elif [ "$flags" = stale ] || { [ "$flags" = heal ] && [ ! -f mounts ]; }; then echo remount @@ -290,6 +334,12 @@ osascript() { echo ok fi ;; + clip-manifest-id|validate-clip-archive) + node "$PASTEBOARD_FIXTURE" "$3" "$4" "$5" "${6:-}" ;; + local-clip-paths) + [ "$flags" != hosted_upload ] || return 0 + if [ "$flags" = changed_upload ]; then printf '2\n' > change_count; fi + printf '%s\n' "$PWD/guest files/a.txt" "$PWD/guest tree" ;; *) return 1 ;; esac ;; @@ -361,6 +411,7 @@ curl() { output="" base="" body="" + archive_upload="" url="" while [ "$#" -gt 0 ]; do case "$1" in @@ -368,6 +419,7 @@ curl() { -D) headers="$2"; shift ;; -o) output="$2"; shift ;; --data-binary) body="${2#@}"; shift ;; + --upload-file) archive_upload="$2"; shift ;; -H) case "$2" in 'X-Clip-Base-Seq: '*) base="$2" ;; @@ -380,6 +432,15 @@ curl() { shift done case "$url" in + */v1/clipboard\?format=tar\&drop_id=clip-0123456789abcdef) + [ ! -d "$CLIP_LOCK" ] || exit 1 + cp guest-fallback.tar "$output" || exit 1 + if [ -f change_during_archive ]; then + printf '%s\n' '{"changeCount":3,"items":[{"public.utf8-plain-text":"new guest copy"}]}' > test-pasteboard.json + fi + printf 'DOWNLOAD %s\n' "$url" >> calls + printf '200' + return ;; */v1/config) printf 'config\n' >> config_calls if [ "$flags" = reenable ] && [ "$(read_file config_calls)" = config ]; then @@ -407,6 +468,18 @@ curl() { ;; esac [ ! -d "$CLIP_LOCK" ] || exit 1 + if [ -n "$archive_upload" ]; then + [ "$method" = POST ] || exit 1 + tar -tf "$archive_upload" > upload-contents || exit 1 + printf 'UPLOAD %s\n' "$base" >> calls + if [ "$flags" = retry_archive_upload ] && [ ! -f retry_archive_once ]; then + : > retry_archive_once + printf '503' + else + printf '200' + fi + return + fi if [ "$method" = POST ]; then printf '%s %s\n' "$method" "$base" >> calls if [ "$check_post_base" = 1 ] && [ "$get_code" != 204 ] && [ "$base" != "X-Clip-Base-Seq: $get_seq" ]; then @@ -432,7 +505,11 @@ curl() { 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" + if [ "$get_code" = 204 ] && [ ! -f explicit_disabled_seq ]; then + : > "$headers" + else + printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers" + fi printf '%s' "$get_value" > "$output" if [ "$fail_during_get" = 1 ]; then printf C > local_value @@ -485,22 +562,30 @@ 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) + host_files_*|host_ignores_conditional_file_retry|guest_files_*|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) + host_files_sync_no_echo|host_files_reordered_readback|host_files_failed_write|host_files_partial_write) 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 + get_value='{"drop_id":"clip-0123456789abcdef","items":["z file.txt","a#note.txt"]}' + mkdir -p "$DROP_MOUNT/clip-0123456789abcdef" + touch "$DROP_MOUNT/clip-0123456789abcdef/z file.txt" "$DROP_MOUNT/clip-0123456789abcdef/a#note.txt" + case "$1" in + host_files_reordered_readback) : > test-reverse-file-readback ;; + host_files_failed_write) : > test-fail-file-write ;; + host_files_partial_write) : > test-partial-file-write ;; + esac + if [ "$1" != host_files_sync_no_echo ]; then + printf '%s\n' '{"changeCount":17,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json + fi sync_clipboard - if [ "$1" = host_files_reordered_readback ]; then + if [ "$1" != host_files_sync_no_echo ]; then expect "$last_server_hash/$last_server_seq/$file_retry_polls" /8/3 + expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" A [ ! -d "$CLIP_LOCK" ] exit 0 fi @@ -508,7 +593,7 @@ case "$1" in 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 + expect "$(sed 's|^file://.*/drop_mount/clip-0123456789abcdef/||' readback)" 'z%20file.txt a%23note.txt' expect "$last_local_hash" "files:$(cat readback)" get_code=304 @@ -516,6 +601,58 @@ a%23note.txt' expect "$(methods)" GET,GET expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=8' ;; + host_files_tar_fallback|host_files_tar_fallback_changed) + flags=typed_files + get_kind=files + get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}' + printf foreign > mount_owner + printf '0 1048576\n' > clip_file_config + printf '%s\n' '{"changeCount":1,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json + printf fallback > fallback.txt + tar -cf guest-fallback.tar fallback.txt + if [ "$1" = host_files_tar_fallback_changed ]; then : > change_during_archive; fi + sync_clipboard + expect "$(methods)" GET,DOWNLOAD + [ ! -d "$CLIP_LOCK" ] + if [ "$1" = host_files_tar_fallback_changed ]; then + expect "$last_server_hash/$file_retry_polls" /3 + expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy' + else + expect "$last_server_hash" B + expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" fallback + expect "$(read_local_clipboard readback)" files + grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback + fi + ;; + guest_files_tar_upload|guest_files_legacy_no_upload|guest_files_tar_hosted_no_upload|guest_files_tar_upload_changed|guest_files_tar_upload_retry) + local_info="«class furl», Unicode text" + get_code=204 + : > explicit_disabled_seq + last_local_hash=empty + printf '%s\n' 'file:///local/guest-files' > local_value + printf '1\n' > change_count + mkdir -p 'guest files' 'guest tree/nested' + printf a > 'guest files/a.txt' + printf b > 'guest tree/nested/b.txt' + if [ "$1" != guest_files_legacy_no_upload ]; then printf '1 1048576\n' > clip_file_config; fi + if [ "$1" = guest_files_tar_hosted_no_upload ]; then flags=hosted_upload; fi + if [ "$1" = guest_files_tar_upload_changed ]; then flags=changed_upload; fi + if [ "$1" = guest_files_tar_upload_retry ]; then flags=retry_archive_upload; fi + sync_clipboard + expect "$last_server_seq" 8 + sync_clipboard + if [ -n "$file_upload_pid" ]; then wait "$file_upload_pid" || true; fi + if [ "$1" = guest_files_tar_upload ] || [ "$1" = guest_files_tar_upload_retry ]; then + if [ "$1" = guest_files_tar_upload_retry ]; then + expect "$(grep -xcF 'UPLOAD X-Clip-Base-Seq: 8' calls)" 2 + fi + expect_call -Fx 'UPLOAD X-Clip-Base-Seq: 8' + grep -qxF './a.txt' upload-contents + grep -qxF './guest tree/nested/b.txt' upload-contents + else + expect "$(methods)" GET,GET + fi + ;; guest_files_do_not_overwrite_host) local_info="«class furl», Unicode text" last_local_hash=old diff --git a/internal/guesttools/clipboard_archive.go b/internal/guesttools/clipboard_archive.go new file mode 100644 index 0000000..de70bd3 --- /dev/null +++ b/internal/guesttools/clipboard_archive.go @@ -0,0 +1,225 @@ +package guesttools + +import ( + "archive/tar" + "context" + "errors" + "io" + "net/http" + "os" + "path" + "strconv" + "strings" + "time" +) + +const ( + clipboardArchiveOverhead = 4 << 20 + maxClipboardArchiveDepth = 32 +) + +var errClipboardArchiveLimit = errors.New("clipboard archive exceeds the transfer limit") + +func (s *Server) serveClipboardArchive(w http.ResponseWriter, r *http.Request, vm *registeredVM) { + id := r.URL.Query().Get("drop_id") + if !dropIDPattern.MatchString(id) { + http.Error(w, "invalid clipboard share", http.StatusBadRequest) + return + } + if !s.clipArchiveMu.TryLock() { + http.Error(w, "another clipboard download is in progress", http.StatusServiceUnavailable) + return + } + defer s.clipArchiveMu.Unlock() + deadline := time.Now().Add(time.Minute) + ctx, cancel := context.WithDeadline(r.Context(), deadline) + defer cancel() + controller := http.NewResponseController(w) + if controller.SetWriteDeadline(deadline) == nil { + defer controller.SetWriteDeadline(time.Time{}) + } + + s.mu.RLock() + current := s.vms[vm.key] + policy := s.effectiveClipboardPolicyLocked(vm.key) + var store *dropShareStore + if current != nil && current.regGen == vm.regGen && policy.allowsHostToGuestFiles() { + store = current.dropShares + } + s.mu.RUnlock() + if store == nil { + http.Error(w, "clipboard files unavailable", http.StatusForbidden) + return + } + share := store.touch(id, true) + if share == nil || !share.clipboard { + http.NotFound(w, r) + return + } + fs := &dropWebDAVFS{store: store, allowClipboard: func() bool { + s.mu.RLock() + defer s.mu.RUnlock() + policyNow := s.effectiveClipboardPolicyLocked(vm.key) + return s.vms[vm.key] == current && current.regGen == vm.regGen && + policyNow.allowsHostToGuestFiles() && policyNow.MaxFileBytes >= policy.MaxFileBytes + }} + archive := clipboardArchive{ctx: ctx, fs: fs, id: id, remaining: int64(policy.MaxFileBytes)} + for _, name := range share.order { + if err := archive.appendEntry(name, 1); err != nil { + writeClipboardArchiveError(w, err) + return + } + } + length, err := archive.wireSize(int64(policy.MaxFileBytes) + clipboardArchiveOverhead) + if err != nil { + writeClipboardArchiveError(w, err) + return + } + if !fs.allowClipboard() { + writeClipboardArchiveError(w, os.ErrPermission) + return + } + w.Header().Set("Content-Type", "application/x-tar") + w.Header().Set("Content-Length", strconv.FormatInt(length, 10)) + w.Header().Set("Cache-Control", "no-store") + if err := archive.stream(w); err != nil { + // Close the connection instead of marking a partial archive as complete. + panic(http.ErrAbortHandler) + } +} + +func writeClipboardArchiveError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, context.Canceled): + return + case errors.Is(err, errClipboardArchiveLimit): + http.Error(w, errClipboardArchiveLimit.Error(), http.StatusRequestEntityTooLarge) + case errors.Is(err, os.ErrPermission): + http.Error(w, "clipboard files unavailable", http.StatusForbidden) + default: + http.Error(w, "clipboard files unavailable", http.StatusNotFound) + } +} + +type clipboardArchive struct { + ctx context.Context + fs *dropWebDAVFS + id string + remaining int64 + headers []tar.Header +} + +func (a *clipboardArchive) appendEntry(name string, depth int) error { + if depth > maxClipboardArchiveDepth || len(a.headers) >= MaxSharedFiles { + return errClipboardArchiveLimit + } + if err := a.ctx.Err(); err != nil { + return err + } + rel, err := davRelativePath(name) + if err != nil || rel != name || strings.ContainsAny(name, "\r\n\t") { + return os.ErrPermission + } + file, err := a.fs.OpenFile(a.ctx, path.Join(a.id, name), os.O_RDONLY, 0) + if err != nil { + return err + } + defer file.Close() + st, err := file.Stat() + if err != nil { + return err + } + header := tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0644, Size: st.Size(), Format: tar.FormatPAX, + ModTime: st.ModTime().Truncate(time.Second)} + if st.IsDir() { + header.Name += "/" + header.Typeflag, header.Mode, header.Size = tar.TypeDir, 0755, 0 + } + if header.Size < 0 || header.Size > a.remaining { + return errClipboardArchiveLimit + } + a.remaining -= header.Size + a.headers = append(a.headers, header) + if !st.IsDir() { + return nil + } + for { + children, err := file.Readdir(32) + for _, child := range children { + if err := a.appendEntry(path.Join(name, child.Name()), depth+1); err != nil { + return err + } + } + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + } +} + +type archiveByteCounter struct{ size, limit int64 } + +func (c *archiveByteCounter) Write(data []byte) (int, error) { + if int64(len(data)) > c.limit-c.size { + return 0, errClipboardArchiveLimit + } + c.size += int64(len(data)) + return len(data), nil +} + +func (a *clipboardArchive) wireSize(limit int64) (int64, error) { + counter := &archiveByteCounter{limit: limit} + writer := tar.NewWriter(counter) + var zeros [32 << 10]byte + for _, header := range a.headers { + if err := a.ctx.Err(); err != nil { + return 0, err + } + if err := writer.WriteHeader(&header); err != nil { + return 0, err + } + for left := header.Size; left > 0; { + n, err := writer.Write(zeros[:min(left, int64(len(zeros)))]) + if err != nil { + return 0, err + } + left -= int64(n) + } + } + if err := writer.Close(); err != nil { + return 0, err + } + return counter.size, nil +} + +func (a *clipboardArchive) stream(w io.Writer) error { + writer := tar.NewWriter(w) + for _, header := range a.headers { + if err := a.ctx.Err(); err != nil { + return err + } + if err := writer.WriteHeader(&header); err != nil { + return err + } + if header.Typeflag == tar.TypeDir { + continue + } + file, err := a.fs.OpenFile(a.ctx, path.Join(a.id, header.Name), os.O_RDONLY, 0) + if err != nil { + return err + } + st, err := file.Stat() + if err == nil && (!st.Mode().IsRegular() || st.Size() != header.Size) { + err = os.ErrInvalid + } + if err == nil { + _, err = io.CopyN(writer, file, header.Size) + } + if err = errors.Join(err, file.Close()); err != nil { + return err + } + } + return writer.Close() +} diff --git a/internal/guesttools/clipboard_archive_test.go b/internal/guesttools/clipboard_archive_test.go new file mode 100644 index 0000000..9e95b9c --- /dev/null +++ b/internal/guesttools/clipboard_archive_test.go @@ -0,0 +1,94 @@ +package guesttools + +import ( + "archive/tar" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" +) + +func TestClipboardArchiveUsesAuthorizedSelection(t *testing.T) { + root := t.TempDir() + folder := filepath.Join(root, "素材") + if err := os.Mkdir(folder, 0700); err != nil { + t.Fatal(err) + } + for name, data := range map[string]string{ + filepath.Join(folder, "hello.txt"): "hola", + filepath.Join(root, "selected.txt"): "windows", + filepath.Join(root, "unselected.txt"): "sibling", + } { + if err := os.WriteFile(name, []byte(data), 0600); err != nil { + t.Fatal(err) + } + } + srv := newClipboardTestServer(&memClipboard{}) + srv.RegisterVM(VMConfig{VMName: "other", Token: "other-token"}) + entries := []DropShareEntry{ + {Name: "素材", HostPath: folder, IsDir: true}, + {Name: "selected.txt", HostPath: filepath.Join(root, "selected.txt")}, + } + if !srv.ensureClipboardShare("clipboard-test", "clip-test", entries) || + !srv.RegisterDropShare("clipboard-test", "manual-drop", entries) { + t.Fatal("could not register shares") + } + get := func(id, token string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodGet, "/v1/clipboard?format=tar&drop_id="+id, nil) + r.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + srv.handleClipboard(w, r) + return w + } + const token = "clipboard-test-token" + w := get("clip-test", token) + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/x-tar" || + w.Header().Get("Content-Length") != strconv.Itoa(w.Body.Len()) { + t.Fatalf("archive GET: status %d, headers %v, body size %d", w.Code, w.Header(), w.Body.Len()) + } + tr := tar.NewReader(w.Body) + for _, entry := range []struct{ name, body string }{ + {"素材/", ""}, {"素材/hello.txt", "hola"}, {"selected.txt", "windows"}, + } { + h, err := tr.Next() + if err != nil || h.Name != entry.name { + t.Fatalf("want archive entry %q, got %v (%v)", entry.name, h, err) + } + data, err := io.ReadAll(tr) + if err != nil || string(data) != entry.body { + t.Fatalf("archive entry %s: %q (%v)", h.Name, data, err) + } + } + if h, err := tr.Next(); err != io.EOF { + t.Fatalf("expected end of archive, got %v (%v)", h, err) + } + for _, tc := range []struct { + id, token string + code int + }{ + {"manual-drop", token, http.StatusNotFound}, + {"clip-test", "other-token", http.StatusNotFound}, + {"clip-test", "invalid", http.StatusUnauthorized}, + } { + if w := get(tc.id, tc.token); w.Code != tc.code { + t.Fatalf("archive %s for %s: %d, want %d", tc.id, tc.token, w.Code, tc.code) + } + } + policy := DefaultClipboardPolicy() + policy.MaxFileBytes = 1 << 20 + srv.SetGlobalClipboardPolicy(policy) + if err := os.Truncate(entries[1].HostPath, int64(policy.MaxFileBytes)); err != nil { + t.Fatal(err) + } + if w := get("clip-test", token); w.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("oversize archive: %d", w.Code) + } + policy.SyncFiles = false + srv.SetVMClipboardPolicy("clipboard-test", &policy) + if w := get("clip-test", token); w.Code != http.StatusForbidden { + t.Fatalf("file sync disabled: %d", w.Code) + } +} diff --git a/internal/guesttools/clipboard_files.go b/internal/guesttools/clipboard_files.go new file mode 100644 index 0000000..14b2a5e --- /dev/null +++ b/internal/guesttools/clipboard_files.go @@ -0,0 +1,589 @@ +package guesttools + +import ( + "archive/tar" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net/http" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode" + "unicode/utf16" + "unicode/utf8" +) + +const ( + MinClipboardMaxFileMB = 1 + MaxClipboardMaxFileMB = 512 + DefaultClipboardMaxFileBytes = 128 << 20 + maxClipboardArchiveEntries = 2000 + maxRetainedClipboardBatches = 3 + clipboardBatchMaxAge = 30 * time.Minute + clipboardUploadTimeout = 2 * time.Minute + clipboardBatchPrefix = "clip-" + dropFilesHeaderSize = 20 + maxDropFilesBytes = 1 << 20 +) + +var ( + errClipArchiveTooLarge = errors.New("clipboard file archive exceeds limit") + errClipArchiveInvalid = errors.New("invalid clipboard file archive") +) + +type clipboardFileWriter interface { + writeClipboard(ClipPayload, *uint32) (uint32, error) +} + +type clipGuestBatch struct { + vmKey string + dir string + createdAt time.Time +} + +// The server mutex protects staging configuration and retained batches. +// uploadMu limits temporary upload storage to one transfer at a time. +type clipFileStaging struct { + dir string + epoch uint64 + uploadVM string + cancelUpload func() + batches []clipGuestBatch + cleanup []string + uploadMu sync.Mutex +} + +func (s *Server) SetClipStagingDir(dir string) { + if dir != "" { + dir = filepath.Clean(dir) + } + s.mu.Lock() + if s.clipFileStaging.dir != dir { + s.clearAllClipFilesLocked() + s.clipFileStaging.dir = dir + } + s.mu.Unlock() + s.cleanupClipFiles() +} + +func (s *Server) clipboardFileUploadsAvailable() bool { + s.mu.RLock() + defer s.mu.RUnlock() + _, writable := s.clip.(clipboardFileWriter) + return writable && filepath.IsAbs(s.clipFileStaging.dir) +} + +func clipBatchOwnsPath(dir, file string) bool { + rel, err := filepath.Rel(dir, file) + return err == nil && filepath.IsLocal(rel) +} + +func clipBatchOwnsFiles(dir string, paths []string) bool { + return slices.ContainsFunc(paths, func(file string) bool { return clipBatchOwnsPath(dir, file) }) +} + +func (s *Server) isStagedClipboardFiles(files []string) bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.clipFileStaging.dir != "" && clipBatchOwnsFiles(s.clipFileStaging.dir, files) +} + +func (s *Server) clearVMClipFilesLocked(vmKey string) { + if s.clipFileStaging.uploadVM == vmKey { + s.clipFileStaging.invalidateUpload() + } + s.removeClipBatchesLocked(func(batch clipGuestBatch) bool { return batch.vmKey == vmKey }, true) +} + +func (s *Server) clearAllClipFilesLocked() { + s.clipFileStaging.invalidateUpload() + s.removeClipBatchesLocked(func(clipGuestBatch) bool { return true }, true) +} + +func (staging *clipFileStaging) invalidateUpload() { + staging.epoch++ + if staging.cancelUpload != nil { + staging.cancelUpload() + } +} + +func (s *Server) removeClipBatchesLocked(remove func(clipGuestBatch) bool, clearClipboard bool) { + staging := &s.clipFileStaging + if clearClipboard && slices.ContainsFunc(staging.batches, remove) { + if writer, ok := s.clip.(clipboardFileWriter); ok { + payload, seq, err := s.readClipboardState(false, true) + ownedClipboard := err == nil && payload.Kind == ClipFiles && len(payload.Files) > 0 && + slices.ContainsFunc(staging.batches, func(batch clipGuestBatch) bool { + return remove(batch) && !slices.ContainsFunc(payload.Files, func(file string) bool { + return !clipBatchOwnsPath(batch.dir, file) + }) + }) + if ownedClipboard { + _, err = writer.writeClipboard(ClipPayload{}, &seq) + if err != nil && !errors.Is(err, errClipboardConflict) { + log.Print("Could not clear staged files from the host clipboard") + } + } + } + } + staging.batches = slices.DeleteFunc(staging.batches, func(batch clipGuestBatch) bool { + if !remove(batch) { + return false + } + staging.cleanup = append(staging.cleanup, batch.dir) + return true + }) +} + +func removeClipDirectory(dir string) error { + if !filepath.IsAbs(dir) || !strings.HasPrefix(filepath.Base(dir), clipboardBatchPrefix) { + return errors.New("invalid clipboard staging directory") + } + root, err := os.OpenRoot(filepath.Dir(dir)) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer root.Close() + return root.RemoveAll(filepath.Base(dir)) +} + +func (s *Server) cleanupClipFiles() { + s.mu.Lock() + dirs := s.clipFileStaging.cleanup + s.clipFileStaging.cleanup = nil + s.mu.Unlock() + for _, dir := range dirs { + if err := removeClipDirectory(dir); err != nil { + log.Print("Could not remove a staged clipboard directory") + s.mu.Lock() + s.clipFileStaging.cleanup = append(s.clipFileStaging.cleanup, dir) + s.mu.Unlock() + } + } +} + +func (s *Server) pruneExpiredClipStaging(now time.Time) { + s.mu.Lock() + expired := func(batch clipGuestBatch) bool { return now.Sub(batch.createdAt) >= clipboardBatchMaxAge } + if slices.ContainsFunc(s.clipFileStaging.batches, expired) { + if payload, _, err := s.readClipboardState(false, true); err == nil { + s.removeClipBatchesLocked(func(batch clipGuestBatch) bool { + return expired(batch) && !clipBatchOwnsFiles(batch.dir, payload.Files) + }, false) + } + } + s.mu.Unlock() + s.cleanupClipFiles() +} + +func encodeHDropBytes(paths []string) ([]byte, error) { + if len(paths) == 0 || len(paths) > MaxClipboardFiles { + return nil, errors.New("invalid clipboard file count") + } + raw := make([]byte, dropFilesHeaderSize) + binary.LittleEndian.PutUint32(raw, dropFilesHeaderSize) + binary.LittleEndian.PutUint32(raw[16:], 1) // UTF-16LE + for _, name := range paths { + if !filepath.IsAbs(name) || strings.ContainsRune(name, 0) || len(name) >= maxDropFilesBytes { + return nil, errors.New("invalid clipboard file path") + } + words := utf16.Encode([]rune(name)) + if len(raw)+(len(words)+2)*2 > maxDropFilesBytes { + return nil, errors.New("clipboard file paths exceed size limit") + } + for _, word := range words { + raw = binary.LittleEndian.AppendUint16(raw, word) + } + raw = append(raw, 0, 0) + } + return append(raw, 0, 0), nil +} + +func sanitizeClipArchiveName(name string) (string, error) { + if name == "" || name == "." || name == ".." || !utf8.ValidString(name) || + strings.IndexFunc(name, unicode.IsControl) >= 0 { + return "", errClipArchiveInvalid + } + safe := strings.Map(func(r rune) rune { + if strings.ContainsRune(`:*?"<>|`, r) { + return '_' + } + return r + }, name) + safe = strings.TrimRight(safe, ". ") + if safe == "" { + safe = "_" + } + stem, _, _ := strings.Cut(safe, ".") + stem = strings.ToUpper(strings.TrimRight(stem, " ")) + switch stem { + case "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + "COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³": + safe = "_" + safe + } + if !filepath.IsLocal(safe) || len(utf16.Encode([]rune(safe))) > 240 { + return "", errClipArchiveInvalid + } + return safe, nil +} + +type clipArchiveNode struct { + rel string + dir bool + explicit bool + modTime time.Time +} + +type clipArchive struct { + root *os.Root + bySource map[string]*clipArchiveNode + all []*clipArchiveNode + usedNames map[string]bool + topNames []string +} + +func (a *clipArchive) addPath(raw string, isDir bool, mod time.Time) (*clipArchiveNode, error) { + if strings.ContainsAny(raw, "\x00\\") || strings.HasPrefix(raw, "/") { + return nil, errClipArchiveInvalid + } + for strings.HasPrefix(raw, "./") { + raw = strings.TrimPrefix(raw, "./") + } + if raw == "." || raw == "" { + if isDir { + return nil, nil + } + return nil, errClipArchiveInvalid + } + parts := strings.Split(strings.TrimSuffix(raw, "/"), "/") + if len(parts) > maxClipboardArchiveDepth { + return nil, errClipArchiveInvalid + } + var parent string + for i, part := range parts { + name, err := sanitizeClipArchiveName(part) + if err != nil { + return nil, err + } + // Skip Finder metadata at every depth, including metadata directories. + if part == ".DS_Store" || strings.HasPrefix(part, "._") { + return nil, nil + } + // Key children by the allocated parent path so that duplicate directory + // roots in two consecutive tar trees cannot share descendants. + src := path.Join(parent, part) + last := i == len(parts)-1 + wantDir := !last || isDir + existing := a.bySource[src] + if existing != nil && wantDir && existing.dir { + if last && !existing.explicit { + existing.explicit, existing.modTime = true, mod + return existing, nil + } + if !last { + parent = existing.rel + continue + } + // A second explicit directory header starts a distinct tree with + // the same source name. Subsequent children attach to the new alias. + } + if len(a.all) >= maxClipboardArchiveEntries || (i == 0 && len(a.topNames) >= MaxClipboardFiles) { + return nil, errClipArchiveTooLarge + } + rel := path.Join(parent, name) + if a.usedNames[strings.ToUpper(rel)] { + ext := "" + if !wantDir && path.Ext(name) != name { + ext = path.Ext(name) + } + stem := strings.TrimSuffix(name, ext) + for n := 2; a.usedNames[strings.ToUpper(rel)]; n++ { + rel = path.Join(parent, fmt.Sprintf("%s (%d)%s", stem, n, ext)) + } + } + a.usedNames[strings.ToUpper(rel)] = true + node := &clipArchiveNode{rel: rel, dir: wantDir, explicit: last} + if last { + node.modTime = mod + } + if existing == nil || wantDir { + a.bySource[src] = node + } + a.all = append(a.all, node) + if i == 0 { + a.topNames = append(a.topNames, rel) + } + if node.dir { + if err := a.root.Mkdir(rel, 0o700); err != nil { + return nil, err + } + } + parent = rel + if last { + return node, nil + } + } + return nil, errClipArchiveInvalid +} + +func extractClipArchive(root *os.Root, body io.Reader, maxBytes int) ([]string, error) { + budget := int64(maxBytes) + bounded := &io.LimitedReader{R: body, N: budget + clipboardArchiveOverhead + 1} + reader := tar.NewReader(bounded) + archive := clipArchive{root: root, bySource: make(map[string]*clipArchiveNode), usedNames: make(map[string]bool)} + var total int64 + for count := 0; ; count++ { + hdr, err := reader.Next() + if bounded.N <= 0 { + return nil, errClipArchiveTooLarge + } + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, errClipArchiveInvalid + } + if count >= maxClipboardArchiveEntries || hdr.Size < 0 || hdr.Size > budget-total { + return nil, errClipArchiveTooLarge + } + total += hdr.Size + switch hdr.Typeflag { + case tar.TypeXGlobalHeader: + continue + case tar.TypeReg, tar.TypeDir: + default: + return nil, errClipArchiveInvalid + } + node, err := archive.addPath(hdr.Name, hdr.Typeflag == tar.TypeDir, hdr.ModTime) + if err != nil { + return nil, err + } + if node == nil || node.dir { + continue + } + out, err := root.OpenFile(node.rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return nil, err + } + n, copyErr := io.Copy(out, reader) + closeErr := out.Close() + if bounded.N <= 0 { + return nil, errClipArchiveTooLarge + } + if n != hdr.Size || errors.Is(copyErr, io.ErrUnexpectedEOF) { + return nil, errClipArchiveInvalid + } + if err := errors.Join(copyErr, closeErr); err != nil { + return nil, err + } + } + // tar.Reader stops at its end marker. Bound the whole upload, including padding. + if _, err := io.Copy(io.Discard, bounded); err != nil { + return nil, errClipArchiveInvalid + } + if bounded.N <= 0 { + return nil, errClipArchiveTooLarge + } + if len(archive.topNames) == 0 { + return nil, errClipArchiveInvalid + } + for i := len(archive.all) - 1; i >= 0; i-- { + if node := archive.all[i]; !node.modTime.IsZero() { + if err := root.Chtimes(node.rel, node.modTime, node.modTime); err != nil { + log.Print("Could not preserve a staged clipboard file timestamp") + } + } + } + return archive.topNames, nil +} + +func stageClipboardArchive(stagingDir string, body io.Reader, maxBytes int) (string, []string, error) { + if err := os.MkdirAll(stagingDir, 0o700); err != nil { + return "", nil, err + } + st, err := os.Lstat(stagingDir) + if err != nil { + return "", nil, err + } + if !st.IsDir() || IsDropSymlink(st) { + return "", nil, os.ErrPermission + } + dir, err := os.MkdirTemp(stagingDir, clipboardBatchPrefix) + if err != nil { + return "", nil, err + } + root, err := os.OpenRoot(dir) + var files []string + if err == nil { + files, err = extractClipArchive(root, body, maxBytes) + err = errors.Join(err, root.Close()) + } + if err != nil { + return dir, nil, err + } + for i, name := range files { + files[i] = filepath.Join(dir, name) + } + return dir, files, nil +} + +type clipUploadReader struct { + ctx context.Context + body io.Reader +} + +func (r clipUploadReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.body.Read(p) +} + +func (s *Server) postClipboardFiles(w http.ResponseWriter, r *http.Request, vm *registeredVM, policy ClipboardPolicy) { + if !policy.allowsGuestToHostFiles() { + w.WriteHeader(http.StatusNoContent) + return + } + writer, ok := s.clip.(clipboardFileWriter) + if !ok { + http.Error(w, "file clipboard writes unavailable", http.StatusServiceUnavailable) + return + } + var baseSeq *uint32 + if raw := r.Header.Get("X-Clip-Base-Seq"); raw != "" { + n, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + http.Error(w, "invalid X-Clip-Base-Seq", http.StatusBadRequest) + return + } + base := uint32(n) + baseSeq = &base + if curSeq := s.clip.SequenceNumber(); curSeq != base { + setClipboardSeq(w, curSeq) + http.Error(w, errClipboardConflict.Error(), http.StatusConflict) + return + } + } else { + // Even a guest-to-host-only agent must not replace an intervening host copy. + base := s.clip.SequenceNumber() + baseSeq = &base + } + staging := &s.clipFileStaging + if !staging.uploadMu.TryLock() { + w.Header().Set("Retry-After", "1") + http.Error(w, "clipboard file upload already in progress", http.StatusServiceUnavailable) + return + } + defer staging.uploadMu.Unlock() + uploadCtx, cancel := context.WithCancel(r.Context()) + defer cancel() + controller := http.NewResponseController(w) + deadlineSet := controller.SetReadDeadline(time.Now().Add(clipboardUploadTimeout)) == nil + if deadlineSet { + defer controller.SetReadDeadline(time.Time{}) + } + s.mu.Lock() + stagingDir, epoch := staging.dir, staging.epoch + staging.uploadVM = vm.key + staging.cancelUpload = func() { + cancel() + if deadlineSet { + _ = controller.SetReadDeadline(time.Now()) + } + } + s.mu.Unlock() + defer func() { + s.mu.Lock() + staging.uploadVM = "" + staging.cancelUpload = nil + s.mu.Unlock() + }() + if !filepath.IsAbs(stagingDir) { + http.Error(w, "clipboard file staging unavailable", http.StatusServiceUnavailable) + return + } + if r.ContentLength > int64(policy.MaxFileBytes)+clipboardArchiveOverhead { + http.Error(w, "clipboard files too large", http.StatusRequestEntityTooLarge) + return + } + dir, files, err := stageClipboardArchive(stagingDir, clipUploadReader{ctx: uploadCtx, body: r.Body}, policy.MaxFileBytes) + keep := false + defer func() { + if !keep && dir != "" { + s.mu.Lock() + staging.cleanup = append(staging.cleanup, dir) + s.mu.Unlock() + } + s.cleanupClipFiles() + }() + if err != nil { + switch { + case uploadCtx.Err() != nil: + w.Header().Set("Connection", "close") + http.Error(w, "clipboard file policy or session changed", http.StatusConflict) + case errors.Is(err, errClipArchiveTooLarge): + http.Error(w, "clipboard files too large", http.StatusRequestEntityTooLarge) + case errors.Is(err, errClipArchiveInvalid): + http.Error(w, errClipArchiveInvalid.Error(), http.StatusBadRequest) + default: + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, "could not stage clipboard files", http.StatusInternalServerError) + } + return + } + + s.clipWriteMu.Lock() + s.mu.Lock() + current := s.vms[vm.key] + currentPolicy := s.effectiveClipboardPolicyLocked(vm.key) + if current == nil || current.token != vm.token || current.regGen != vm.regGen || + staging.epoch != epoch || staging.dir != stagingDir || !currentPolicy.allowsGuestToHostFiles() || + currentPolicy.MaxFileBytes < policy.MaxFileBytes || uploadCtx.Err() != nil { + s.mu.Unlock() + s.clipWriteMu.Unlock() + http.Error(w, "clipboard file policy or session changed", http.StatusConflict) + return + } + seq, err := writer.writeClipboard(ClipPayload{Kind: ClipFiles, Files: files}, baseSeq) + if err == nil { + keep = true + staging.batches = append(staging.batches, clipGuestBatch{vmKey: vm.key, dir: dir, createdAt: time.Now()}) + for len(staging.batches) > maxRetainedClipboardBatches { + staging.cleanup = append(staging.cleanup, staging.batches[0].dir) + staging.batches = staging.batches[1:] + } + } + s.mu.Unlock() + s.clipWriteMu.Unlock() + if err != nil { + if errors.Is(err, errClipboardConflict) { + setClipboardSeq(w, seq) + http.Error(w, errClipboardConflict.Error(), http.StatusConflict) + } else { + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, "could not update the host clipboard", http.StatusInternalServerError) + } + return + } + atomic.AddUint64(&s.clipStatsG2H, 1) + s.touchLastSeen(vm.key) + s.broadcastClipChange() + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Kind", string(ClipFiles)) + w.WriteHeader(http.StatusOK) +} diff --git a/internal/guesttools/clipboard_files_test.go b/internal/guesttools/clipboard_files_test.go new file mode 100644 index 0000000..06e86c8 --- /dev/null +++ b/internal/guesttools/clipboard_files_test.go @@ -0,0 +1,433 @@ +package guesttools + +import ( + "archive/tar" + "bytes" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +type clipUploadTestEntry struct { + name string + kind byte + data string +} + +func clipUploadTestArchive(t *testing.T, entries ...clipUploadTestEntry) []byte { + t.Helper() + var buf bytes.Buffer + w := tar.NewWriter(&buf) + for _, entry := range entries { + kind := entry.kind + if kind == 0 { + kind = tar.TypeReg + } + hdr := &tar.Header{Name: entry.name, Typeflag: kind, Mode: 0o600, Size: int64(len(entry.data))} + if kind == tar.TypeSymlink || kind == tar.TypeLink { + hdr.Linkname = "file.txt" + } + if err := w.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := io.WriteString(w, entry.data); err != nil { + t.Fatal(err) + } + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +type clipUploadTestClipboard struct { + mu sync.Mutex + payload ClipPayload + seq uint32 +} + +func (c *clipUploadTestClipboard) SequenceNumber() uint32 { + c.mu.Lock() + defer c.mu.Unlock() + return c.seq +} + +func (c *clipUploadTestClipboard) ReadText() (string, error) { + payload, err := c.Read() + return string(payload.Data), err +} + +func (c *clipUploadTestClipboard) Read() (ClipPayload, error) { + payload, _, err := c.readClipboard(true, true) + return payload, err +} + +func (c *clipUploadTestClipboard) readClipboard(wantImage, wantFiles bool) (ClipPayload, uint32, error) { + c.mu.Lock() + defer c.mu.Unlock() + payload := c.payload + if (!wantFiles && payload.Kind == ClipFiles) || (!wantImage && payload.Kind == ClipPNG) { + payload = ClipPayload{} + } + return payload, c.seq, nil +} + +func (c *clipUploadTestClipboard) WriteText(text string) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil) + return err +} + +func (c *clipUploadTestClipboard) WritePNG(data []byte) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: data}, nil) + return err +} + +func (c *clipUploadTestClipboard) writeClipboard(payload ClipPayload, base *uint32) (uint32, error) { + c.mu.Lock() + defer c.mu.Unlock() + if base != nil && c.seq != *base { + return c.seq, errClipboardConflict + } + c.payload = payload + c.seq++ + return c.seq, nil +} + +func clipUploadTestServer(t *testing.T) (*Server, *clipUploadTestClipboard, string) { + t.Helper() + clip := &clipUploadTestClipboard{seq: 7} + srv := newClipboardTestServer(clip) + policy := DefaultClipboardPolicy() + policy.SyncFiles = true + srv.SetGlobalClipboardPolicy(policy) + stage := t.TempDir() + srv.SetClipStagingDir(stage) + return srv, clip, stage +} + +func requireClipStageCount(t *testing.T, stage string, want int) { + t.Helper() + files, err := os.ReadDir(stage) + if err != nil || len(files) != want { + t.Fatalf("staged directories = %v, error = %v, want %d", files, err, want) + } +} + +func TestClipboardUploadStagesFilesAndClearsOnlyItsClipboard(t *testing.T) { + srv, clip, stage := clipUploadTestServer(t) + body := clipUploadTestArchive(t, + clipUploadTestEntry{name: "你好:?", kind: tar.TypeDir}, + clipUploadTestEntry{name: "你好:?/readme.txt", data: "text"}, + clipUploadTestEntry{name: "hello.txt", data: "lowercase"}, + clipUploadTestEntry{name: "HELLO.TXT", data: "uppercase"}, + clipUploadTestEntry{name: "NUL.txt", data: "device name"}, + clipUploadTestEntry{name: "._ignored", data: "metadata"}, + ) + server := httptest.NewServer(http.HandlerFunc(srv.handleClipboard)) + defer server.Close() + req, err := http.NewRequest(http.MethodPost, server.URL+"/v1/clipboard", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer clipboard-test-token") + req.Header.Set("Content-Type", "application/x-tar") + req.Header.Set("X-Clip-Base-Seq", "7") + resp, err := server.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK || resp.Header.Get("X-Clip-Seq") != "8" || + resp.Header.Get("X-Clip-Kind") != string(ClipFiles) { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("status = %d, headers = %v, body = %q", resp.StatusCode, resp.Header, body) + } + payload, err := clip.Read() + if err != nil || payload.Kind != ClipFiles || len(payload.Files) != 4 { + t.Fatalf("host clipboard = %+v, error = %v", payload, err) + } + if !srv.isStagedClipboardFiles(payload.Files) { + t.Fatal("guest paths not recognized as staged") + } + batch := filepath.Dir(payload.Files[0]) + names := []string{"你好__", "hello.txt", "HELLO (2).TXT", "_NUL.txt"} + for i, name := range names { + if payload.Files[i] != filepath.Join(batch, name) { + t.Fatalf("path %d = %q, want %q", i, payload.Files[i], name) + } + } + for name, want := range map[string]string{ + "你好__/readme.txt": "text", "hello.txt": "lowercase", "HELLO (2).TXT": "uppercase", "_NUL.txt": "device name", + } { + data, err := os.ReadFile(filepath.Join(batch, filepath.FromSlash(name))) + if err != nil || string(data) != want { + t.Fatalf("%s = %q, error = %v", name, data, err) + } + } + requireClipStageCount(t, stage, 1) + get := clipboardRequest(t, srv, http.MethodGet, "?accept=files", "", "", nil) + if get.Code != http.StatusNotModified { + t.Fatalf("staged guest files returned as a host copy: %d %s", get.Code, get.Body) + } + srv.pruneExpiredClipStaging(time.Now().Add(clipboardBatchMaxAge)) + requireClipStageCount(t, stage, 1) + if err := clip.WriteText("host copy"); err != nil { + t.Fatal(err) + } + srv.pruneExpiredClipStaging(time.Now().Add(clipboardBatchMaxAge)) + requireClipStageCount(t, stage, 0) + if text, _ := clip.ReadText(); text != "host copy" { + t.Fatalf("cleanup replaced later host copy: %q", text) + } + + res := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "9", body) + if res.Code != http.StatusOK { + t.Fatalf("second upload = %d %s", res.Code, res.Body) + } + srv.UnregisterVM("clipboard-test") + requireClipStageCount(t, stage, 0) + if payload, _ := clip.Read(); payload.Kind != ClipEmpty { + t.Fatalf("stale clipboard after unregister: %+v", payload) + } +} + +func TestClipboardUploadRejectsInvalidArchivesAndKeepsClipboard(t *testing.T) { + srv, clip, stage := clipUploadTestServer(t) + policy := DefaultClipboardPolicy() + policy.SyncFiles = true + policy.MaxFileBytes = 1 << 20 + srv.SetGlobalClipboardPolicy(policy) + raw := clipUploadTestArchive(t, clipUploadTestEntry{name: "valid.txt", data: "bytes"}) + tests := []struct { + name string + data []byte + code int + }{ + {"empty", clipUploadTestArchive(t), 400}, + {"relative traversal", clipUploadTestArchive(t, clipUploadTestEntry{name: "folder/../other", data: "bytes"}), 400}, + {"absolute", clipUploadTestArchive(t, clipUploadTestEntry{name: "/target", data: "bytes"}), 400}, + {"backslash", clipUploadTestArchive(t, clipUploadTestEntry{name: `folder\leaf`, data: "bytes"}), 400}, + {"symlink", clipUploadTestArchive(t, clipUploadTestEntry{name: "link", kind: tar.TypeSymlink}), 400}, + {"hardlink", clipUploadTestArchive(t, clipUploadTestEntry{name: "link", kind: tar.TypeLink}), 400}, + {"overdepth", clipUploadTestArchive(t, clipUploadTestEntry{name: strings.Repeat("folder/", maxClipboardArchiveDepth) + "leaf"}), 400}, + {"truncated", raw[:514], 400}, + {"file too large", clipUploadTestArchive(t, clipUploadTestEntry{name: "large", data: strings.Repeat("X", (1<<20)+1)}), 413}, + {"trailing data too large", append(bytes.Clone(raw), make([]byte, (1<<20)+clipboardArchiveOverhead)...), 413}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + res := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "7", test.data) + if res.Code != test.code { + t.Fatalf("upload = %d, want %d, body = %s", res.Code, test.code, res.Body) + } + requireClipStageCount(t, stage, 0) + if seq := clip.SequenceNumber(); seq != 7 { + t.Fatalf("invalid archive changed host clipboard sequence to %d", seq) + } + }) + } +} + +type clipUploadMutationReader struct { + once sync.Once + mutate func() + reader io.Reader +} + +func (r *clipUploadMutationReader) Read(p []byte) (int, error) { + r.once.Do(r.mutate) + return r.reader.Read(p) +} + +func TestClipboardUploadRevalidatesSequenceAndRegistration(t *testing.T) { + for _, scenario := range []string{"new host copy", "policy revoked and restored", "registration replaced"} { + t.Run(scenario, func(t *testing.T) { + srv, clip, stage := clipUploadTestServer(t) + body := clipUploadTestArchive(t, clipUploadTestEntry{name: "valid.txt", data: "bytes"}) + mutate := func() { + switch scenario { + case "new host copy": + if err := clip.WriteText("fresh host copy"); err != nil { + t.Fatal(err) + } + case "policy revoked and restored": + policy := DefaultClipboardPolicy() + policy.SyncFiles = false + srv.SetGlobalClipboardPolicy(policy) + policy.SyncFiles = true + srv.SetGlobalClipboardPolicy(policy) + case "registration replaced": + srv.RegisterVM(VMConfig{VMName: "clipboard-test", Token: "changed-token"}) + } + } + req := httptest.NewRequest(http.MethodPost, "/v1/clipboard", &clipUploadMutationReader{reader: bytes.NewReader(body), mutate: mutate}) + req.Header.Set("Authorization", "Bearer clipboard-test-token") + req.Header.Set("Content-Type", "application/x-tar") + req.Header.Set("X-Clip-Base-Seq", "7") + res := httptest.NewRecorder() + srv.handleClipboard(res, req) + if res.Code != http.StatusConflict { + t.Fatalf("upload = %d %s", res.Code, res.Body) + } + if scenario == "new host copy" { + if text, _ := clip.ReadText(); text != "fresh host copy" || res.Header().Get("X-Clip-Seq") != "8" { + t.Fatalf("host copy = %q, headers = %v", text, res.Header()) + } + } + requireClipStageCount(t, stage, 0) + }) + } +} + +type clipUploadReadProbe struct { + io.ReadCloser + reads int + secondRead chan struct{} +} + +func (r *clipUploadReadProbe) Read(p []byte) (int, error) { + r.reads++ + if r.reads == 2 { + close(r.secondRead) + } + return r.ReadCloser.Read(p) +} + +func TestClipboardUploadCancelsStalledStreamOnPolicyWithdrawal(t *testing.T) { + srv, clip, stage := clipUploadTestServer(t) + body := clipUploadTestArchive(t, clipUploadTestEntry{name: "file", data: "contents"}) + secondRead := make(chan struct{}) + handlerDone := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = &clipUploadReadProbe{ReadCloser: r.Body, secondRead: secondRead} + srv.handleClipboard(w, r) + close(handlerDone) + })) + defer server.Close() + pr, pw := io.Pipe() + defer pw.Close() + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, server.URL+"/v1/clipboard", pr) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer clipboard-test-token") + req.Header.Set("Content-Type", "application/x-tar") + req.Header.Set("X-Clip-Base-Seq", "7") + clientDone := make(chan error, 1) + go func() { + resp, err := server.Client().Do(req) + if resp != nil { + resp.Body.Close() + } + clientDone <- err + }() + go func() { + if _, err := pw.Write(body[:512]); err != nil { + _ = pw.CloseWithError(err) + } + }() + select { + case <-secondRead: + case err := <-clientDone: + t.Fatalf("client returned before upload stalled: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("upload never reached second read") + } + policy := DefaultClipboardPolicy() + policy.SyncFiles = false + srv.SetGlobalClipboardPolicy(policy) + select { + case <-handlerDone: + case <-time.After(5 * time.Second): + t.Fatal("withdrawing permission did not interrupt the upload") + } + requireClipStageCount(t, stage, 0) + if seq := clip.SequenceNumber(); seq != 7 { + t.Fatalf("withdrawn upload changed the clipboard sequence to %d", seq) + } +} + +func TestClipboardUploadRetainsThreeRecentBatches(t *testing.T) { + srv, clip, stage := clipUploadTestServer(t) + body := clipUploadTestArchive(t, clipUploadTestEntry{name: "valid.txt", data: "bytes"}) + var dirs []string + for i := 0; i < maxRetainedClipboardBatches+1; i++ { + seq := strconv.FormatUint(uint64(clip.SequenceNumber()), 10) + res := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", seq, body) + if res.Code != http.StatusOK { + t.Fatalf("upload %d = %d %s", i, res.Code, res.Body) + } + payload, _ := clip.Read() + dirs = append(dirs, filepath.Base(filepath.Dir(payload.Files[0]))) + } + files, err := os.ReadDir(stage) + if err != nil { + t.Fatal(err) + } + var got []string + for _, entry := range files { + got = append(got, entry.Name()) + } + want := dirs[1:] + slices.Sort(want) + if !slices.Equal(got, want) { + t.Fatalf("batches = %v, want %v", got, want) + } + srv.SetClipboardActive(false) + requireClipStageCount(t, stage, 0) +} + +func TestClipboardArchiveStreamCapsTrailingBytes(t *testing.T) { + root, err := os.OpenRoot(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer root.Close() + body := clipUploadTestArchive(t, clipUploadTestEntry{name: "accepted.txt"}) + body = append(body, make([]byte, clipboardArchiveOverhead)...) + _, err = extractClipArchive(root, bytes.NewReader(body), 1) + if !errors.Is(err, errClipArchiveTooLarge) { + t.Fatalf("trailing stream overflow = %v", err) + } +} + +func TestClipboardArchiveSeparatesDuplicateDirectoryTrees(t *testing.T) { + dir := t.TempDir() + root, err := os.OpenRoot(dir) + if err != nil { + t.Fatal(err) + } + defer root.Close() + body := clipUploadTestArchive(t, + clipUploadTestEntry{name: "./folder/", kind: tar.TypeDir}, + clipUploadTestEntry{name: "./folder/sub/first.txt", data: "first file"}, + clipUploadTestEntry{name: "./folder/sub/", kind: tar.TypeDir}, + clipUploadTestEntry{name: "./folder/", kind: tar.TypeDir}, + clipUploadTestEntry{name: "./folder/sub/", kind: tar.TypeDir}, + clipUploadTestEntry{name: "./folder/sub/second.txt", data: "second file"}, + ) + names, err := extractClipArchive(root, bytes.NewReader(body), 1<<20) + if err != nil || !slices.Equal(names, []string{"folder", "folder (2)"}) { + t.Fatalf("top names = %q, error = %v", names, err) + } + for name, want := range map[string]string{ + "folder/sub/first.txt": "first file", "folder (2)/sub/second.txt": "second file", + } { + data, err := root.ReadFile(name) + if err != nil || string(data) != want { + t.Fatalf("%s = %q, error = %v", name, data, err) + } + } + if _, err := root.Stat("folder/sub/second.txt"); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("second tree merged into first: %v", err) + } +} diff --git a/internal/guesttools/clipboard_windows.go b/internal/guesttools/clipboard_windows.go index a7ffd69..0f6812e 100644 --- a/internal/guesttools/clipboard_windows.go +++ b/internal/guesttools/clipboard_windows.go @@ -57,14 +57,13 @@ var ( ) const ( - cfDIB = 8 - cfUnicodeText = 13 - cfHDrop = 15 - maxDropFilesBytes = 1 << 20 - gmemMoveable = 0x0002 - hwndMessage = ^uintptr(2) - wmClipJob = 0x8000 // WM_APP - maxDIBBytes = 128 << 20 + cfDIB = 8 + cfUnicodeText = 13 + cfHDrop = 15 + gmemMoveable = 0x0002 + hwndMessage = ^uintptr(2) + wmClipJob = 0x8000 // WM_APP + maxDIBBytes = 128 << 20 ) type OSClipboard struct { @@ -271,11 +270,11 @@ type clipboardSnapshot struct { } func parseDropFilesBytes(raw []byte) []string { - if len(raw) < 20 || len(raw) > maxDropFilesBytes { + if len(raw) < dropFilesHeaderSize || len(raw) > maxDropFilesBytes { return nil } offset := binary.LittleEndian.Uint32(raw) - if offset < 20 || uint64(offset) >= uint64(len(raw)) { + if offset < dropFilesHeaderSize || uint64(offset) >= uint64(len(raw)) { return nil } width := 1 @@ -565,7 +564,8 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq if len(payload.Data) > MaxClipboardBytes { return 0, fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes) } - if payload.Kind == ClipPNG { + switch payload.Kind { + case ClipPNG: dib, err := EncodePNGToDIB(payload.Data) if err != nil { return 0, err @@ -584,7 +584,29 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq return 0, err } mem = append(mem, dibMem) - } else { + case ClipFiles: + raw, err := encodeHDropBytes(payload.Files) + if err != nil { + return 0, err + } + formatName := utf16.Encode([]rune("Preferred DropEffect\x00")) + preferredEffect, _, err := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(&formatName[0]))) + if preferredEffect == 0 { + return 0, fmt.Errorf("RegisterClipboardFormatW: %w", err) + } + // These files belong to the staging directory and should stay there when pasted. + var dropEffect uint32 = 1 // DROPEFFECT_COPY + effectMem, err := prepareClipboardMem(preferredEffect, 4, unsafe.Pointer(&dropEffect)) + if err != nil { + return 0, err + } + mem = append(mem, effectMem) + fileMem, err := prepareClipboardMem(cfHDrop, uintptr(len(raw)), unsafe.Pointer(&raw[0])) + if err != nil { + return 0, err + } + mem = append(mem, fileMem) + case ClipText: norm := strings.ReplaceAll(strings.ReplaceAll(string(payload.Data), "\r\n", "\n"), "\n", "\r\n") words := append(utf16.Encode([]rune(norm)), 0) textMem, err := prepareClipboardMem(cfUnicodeText, uintptr(len(words)*2), unsafe.Pointer(&words[0])) @@ -592,6 +614,10 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq return 0, err } mem = append(mem, textMem) + case ClipEmpty: + // Clear the clipboard without replacing staged files with an empty text item. + default: + return 0, errors.New("unsupported clipboard format") } c.cache.mu.Lock() @@ -611,6 +637,9 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq item := &mem[i] if ok, _, err := procSetClipboardData.Call(item.format, item.handle); ok == 0 { writeErr = errors.Join(writeErr, fmt.Errorf("SetClipboardData(%d): %w", item.format, err)) + if payload.Kind == ClipFiles { + break + } } else { item.handle = 0 // The system now owns the handle. } diff --git a/internal/guesttools/clipboard_windows_test.go b/internal/guesttools/clipboard_windows_test.go index 3a8309f..3a9cc61 100644 --- a/internal/guesttools/clipboard_windows_test.go +++ b/internal/guesttools/clipboard_windows_test.go @@ -9,6 +9,7 @@ import ( "image" "image/png" "net/http" + "path/filepath" "slices" "strconv" "strings" @@ -20,6 +21,26 @@ import ( "golang.org/x/sys/windows" ) +func TestWindowsHDropWriteEncodingMatchesReadParser(t *testing.T) { + dir := t.TempDir() + paths := []string{filepath.Join(dir, "你好 📝.txt"), filepath.Join(dir, "folder")} + raw, err := encodeHDropBytes(paths) + if err != nil { + t.Fatal(err) + } + if got := parseDropFilesBytes(raw); !slices.Equal(got, paths) { + t.Fatalf("roundtrip paths = %q, want %q", got, paths) + } + if binary.LittleEndian.Uint32(raw[16:20]) != 1 || !bytes.Equal(raw[len(raw)-4:], make([]byte, 4)) { + t.Fatalf("wide format or terminator missing: %x", raw) + } + for _, paths := range [][]string{nil, {"relative.txt"}, slices.Repeat(paths[:1], MaxClipboardFiles+1)} { + if _, err := encodeHDropBytes(paths); err == nil { + t.Fatal("invalid file list encoded successfully") + } + } +} + func TestClipboardWorkerUsesOneThreadAndWindow(t *testing.T) { type owner struct { thread uint32 diff --git a/internal/guesttools/drop.go b/internal/guesttools/drop.go index d2efe45..07a5af6 100644 --- a/internal/guesttools/drop.go +++ b/internal/guesttools/drop.go @@ -120,7 +120,7 @@ func (s *Server) handleHostDrop(w http.ResponseWriter, r *http.Request) { } const ( - DropEventTTL = 60 * time.Second + DropEventTTL = 60 * time.Second MaxPendingDropEvents = 32 MaxDropAckBodyBytes = 64 << 10 ) @@ -344,7 +344,7 @@ func (s *Server) ensureClipboardShare(vmKey, dropID string, entries []DropShareE s.mu.RLock() defer s.mu.RUnlock() vm := s.vms[key] - return vm != nil && s.effectiveClipboardPolicyLocked(key).allowsHostToGuest() && vm.dropShares.ensure(dropID, entries) + return vm != nil && s.effectiveClipboardPolicyLocked(key).allowsHostToGuestFiles() && vm.dropShares.ensure(dropID, entries) } func (s *Server) RevokeDropShare(vmKey, dropID string) { diff --git a/internal/guesttools/drop_resolve.js b/internal/guesttools/drop_resolve.js index a7b5784..949899c 100644 --- a/internal/guesttools/drop_resolve.js +++ b/internal/guesttools/drop_resolve.js @@ -172,31 +172,41 @@ function postToHost(url, body) { if (task.terminationStatus !== 0) throw Error('Paste request failed') } +function savePasteboard(pb, allowMissing, stealthRestore) { + const originals = pb.pasteboardItems + const saved = [] + if (!originals || originals.isNil()) return saved + 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) { + if (!allowMissing) throw err + } + } + if (copy.types.count) saved.push(stealthRestore ? addStealth(copy) : copy) + } + return saved +} + +function restorePasteboard(pb, saved) { + pb.clearContents + if (saved.length && !pb.writeObjects($(saved))) throw Error('Cannot restore clipboard') + flushPasteboard(saved.length) +} + 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) - } - } + // A deferred flavor can time out. Preserve all readable flavors and keep input working. + const saved = savePasteboard(pb, true, stealthRestore) if (pb.changeCount !== originalCount) throw Error('Pasteboard changed during backup') let stagedCount = pb.clearContents try { @@ -204,11 +214,7 @@ function withStagedPasteboard(items, action, stealthRestore = false) { 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) - } + if (pb.changeCount === stagedCount) restorePasteboard(pb, saved) } } @@ -376,18 +382,86 @@ function readClipFiles() { } } } + if (!urls.length && typeof $.NSPasteboard.generalPasteboard.propertyListForType === 'function') { + const paths = ObjC.deepUnwrap($.NSPasteboard.generalPasteboard.propertyListForType('NSFilenamesPboardType')) + if (Array.isArray(paths)) { + for (const p of paths) { + if (typeof p === 'string' && p.startsWith('/')) + urls.push(ObjC.unwrap($.NSURL.fileURLWithPath(p).absoluteString)) + } + } + } 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) +function textFile(path) { + const value = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null) + if (!value || value.isNil()) throw Error('Cannot read clipboard file') + return value.js +} + +function localClipPaths(list, roots) { + const comparePath = value => value.normalize('NFC').toLowerCase().replace(/\/+$/, '') + const hosted = roots.filter(Boolean).flatMap(p => { + const path = $(p) + return [p, ObjC.unwrap(path.stringByStandardizingPath), ObjC.unwrap(path.stringByResolvingSymlinksInPath)] + }).filter(p => typeof p === 'string' && p.startsWith('/')).map(comparePath) + const urls = textFile(list).split('\n').filter(Boolean) + if (urls.length > 256) throw Error('Too many clipboard files') + const paths = new Set() + for (const raw of urls) { + const url = $.NSURL.URLWithString(raw) + if (!url || url.isNil() || !url.isFileURL) continue + const host = ObjC.unwrap(url.host) + if (host && host !== 'localhost') continue + const pathURL = raw.startsWith('file:///.file/') ? url.filePathURL : url + if (!pathURL || pathURL.isNil()) continue + const path = pathURL.path + if (!path || path.isNil()) continue + const names = [ObjC.unwrap(path), ObjC.unwrap(path.stringByStandardizingPath), ObjC.unwrap(path.stringByResolvingSymlinksInPath)] + // A selected ancestor would recursively include the private fallback cache. + if (names.filter(n => typeof n === 'string').map(comparePath) + .some(n => hosted.some(root => n === root || n.startsWith(root + '/') || root.startsWith(n + '/')))) continue + const file = (names[1] || names[0])?.replace(/\/+$/, '') + if (file?.startsWith('/') && !/[\x00-\x1f\x7f]/.test(file)) paths.add(file) + } + return Array.from(paths).join('\n') +} + +function readClipManifest(manifestFile) { + const ev = JSON.parse(textFile(manifestFile)) 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') + if (!ev || typeof ev.drop_id !== 'string' || !/^clip-[a-f0-9]{16}$/.test(ev.drop_id) || + !Array.isArray(ev.items) || !ev.items.length || ev.items.length > 256 || + !ev.items.every(safeName) || new Set(ev.items).size !== ev.items.length) throw Error('Invalid clipboard manifest') + return ev +} +function validateClipArchive(manifestFile, entriesFile) { + const ev = readClipManifest(manifestFile) + const roots = new Set(ev.items) + const found = new Set() + const seen = new Set() + const entries = textFile(entriesFile).split('\n') + if (entries.pop() !== '' || entries.length > 2000) throw Error('Invalid clipboard archive size') + for (const entry of entries) { + const path = entry.replace(/\/$/, '') + const parts = path.split('/') + if (!roots.has(parts[0]) || parts.length > 32 || seen.has(path) || + parts.some(p => !p || p === '.' || p === '..' || /[\\\x00-\x1f\x7f]/.test(p))) + throw Error('Invalid clipboard archive path') + seen.add(path) + if (parts.length === 1) found.add(parts[0]) + } + if (found.size !== roots.size) throw Error('Clipboard archive does not match its manifest') + return 'ok' +} + +function writeClipFiles(manifestFile, mount, expectedCount, cached = false) { + if (!mount) return 'remount' + const ev = readClipManifest(manifestFile) const fm = $.NSFileManager.defaultManager const dir = mount + '/' + ev.drop_id const isDir = Ref() @@ -397,7 +471,7 @@ function writeClipFiles(manifestFile, mount, expectedCount) { if (!exists()) return 'remount' } const paths = ev.items.map(name => dir + '/' + name) - if (!mountHealthy([mount, dir]) || !paths.every(p => fm.fileExistsAtPath(p))) return 'remount' + if ((!cached && !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 @@ -406,22 +480,33 @@ function writeClipFiles(manifestFile, mount, expectedCount) { 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' + const originalCount = pb.changeCount + if (expectedCount && String(originalCount) !== expectedCount) return 'changed' + const saved = savePasteboard(pb, false, false) + if (pb.changeCount !== originalCount) return 'changed' + let writtenCount = pb.clearContents + try { + if (!pb.writeObjects($(newItems))) throw Error('Clipboard write failed') + writtenCount = pb.changeCount + flushPasteboard(newItems.length) + if (pb.changeCount !== writtenCount) return 'changed' + if (readClipFiles() !== urls.map(url => ObjC.unwrap(url)).join('\n')) + throw Error('Clipboard file readback did not match') + return 'ok' + } catch (err) { + if (pb.changeCount === writtenCount) restorePasteboard(pb, saved) + throw err + } } 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 === 'local-clip-paths') return localClipPaths(args[0], args.slice(1)) + if (mode === 'clip-manifest-id') return readClipManifest(args[0]).drop_id + if (mode === 'validate-clip-archive') return validateClipArchive(...args) + if (mode === 'write-clip-files') return writeClipFiles(args[0], args[1], args[2], args[3] === 'cache') if (mode === 'run-drop') return runDrop(...args) if (mode === 'resolve') return resolve(args) if (mode === 'check-mount') { diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index b04f19f..55a2958 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -43,8 +43,8 @@ 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) + if CurrentAgentVersion != BidirectionalClipboardFilesAgentVersion { + t.Fatalf("CurrentAgentVersion = %d, want bidirectional clipboard files version %d", CurrentAgentVersion, BidirectionalClipboardFilesAgentVersion) } versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,` if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") { diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index 2c5baa6..ba5a197 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -20,8 +20,9 @@ const HostDNSAgentVersion = 12 const WindowDropAgentVersion = 13 const ClipboardReliabilityAgentVersion = 14 const ClipboardFilesAgentVersion = 15 +const BidirectionalClipboardFilesAgentVersion = 16 -const CurrentAgentVersion = ClipboardFilesAgentVersion +const CurrentAgentVersion = BidirectionalClipboardFilesAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 87082c4..fb2ebdb 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -146,6 +146,7 @@ SHARE_SYNC="$HOME/ReimsShare" SHARE_MOUNT="$HOME/ReimsShareMount" DROP_MOUNT="$HOME/Library/Caches/ReimsDropMount" DROP_CACHE="$HOME/Library/Caches/ReimsDropCache" +CLIP_CACHE="$APP_DIR/clipboard-files" DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" @@ -156,7 +157,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" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true +rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" "$TMP_DIR/clip_file_config" 2>/dev/null || true rm -rf "$CLIP_LOCK" "$CLIP_LOCK".reaping.* 2>/dev/null || true CAFFEINATE_PID="" @@ -499,6 +500,21 @@ apply_host_config() { fi printf '%s\n' "$clip_enabled" > "$TMP_DIR/clip_enabled.tmp" && mv -f "$TMP_DIR/clip_enabled.tmp" "$TMP_DIR/clip_enabled" + archive_bytes=0 + upload_files=0 + if [ "$clip_enabled" = 1 ] && + printf '%s' "$cfg_json" | grep -q '"clipboard_sync_files"[[:space:]]*:[[:space:]]*true'; then + max_bytes=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"clipboard_max_file_bytes"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') + case "$max_bytes" in + ''|*[!0-9]*|0*) ;; + *) if [ "${#max_bytes}" -le 9 ] && [ "$max_bytes" -le 536870912 ]; then archive_bytes=$max_bytes; fi ;; + esac + if printf '%s' "$cfg_json" | grep -q '"clipboard_upload_files"[[:space:]]*:[[:space:]]*true'; then + upload_files=1 + fi + fi + printf '%s %s\n' "$upload_files" "$archive_bytes" > "$TMP_DIR/clip_file_config.tmp" && + mv -f "$TMP_DIR/clip_file_config.tmp" "$TMP_DIR/clip_file_config" sync_drive_mounts "$cfg_json" folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') sync_folder_mounts "${folders_count:-0}" @@ -557,7 +573,7 @@ read_local_clipboard() { return 0 fi case "$cinfo" in - *furl*) + *furl*|*NSFilenamesPboardType*) 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 @@ -640,21 +656,147 @@ write_local_png() { } write_local_files() ( - [ -n "${DROP_MOUNT:-}" ] && [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ] || return 1 - [ -n "${REIMS_VM:-}" ] || return 1 + [ -n "${DROP_MOUNT:-}" ] && [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ] || return 2 + [ -n "${REIMS_VM:-}" ] || return 2 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 + ensure_drop_webdav_mount && is_reims_dav_mounted "$DROP_MOUNT" "$route" || return 2 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 + case "$res" in + ok) return 0 ;; + remount) ;; + *) return 1 ;; + esac + [ "$attempt" = first ] && is_reims_dav_mounted "$DROP_MOUNT" "$route" && + unmount_shared_folder "$DROP_MOUNT" >/dev/null 2>&1 || return 2 + done + return 2 +) + +read_clip_file_config() { + upload_files=0 + archive_bytes=0 + if [ -f "$TMP_DIR/clip_file_config" ]; then + read -r upload_files archive_bytes < "$TMP_DIR/clip_file_config" || archive_bytes=0 + fi + case "$archive_bytes" in ''|*[!0-9]*|0*) archive_bytes=0 ;; esac + if [ "${#archive_bytes}" -gt 9 ] || [ "$archive_bytes" -gt 536870912 ]; then archive_bytes=0; fi +} + +prune_clip_cache() { + [ -n "${CLIP_CACHE:-}" ] && [ -d "$CLIP_CACHE" ] && [ ! -L "$CLIP_CACHE" ] || return 0 + ls -1dt "$CLIP_CACHE"/clip-[0-9a-f]* 2>/dev/null | + sed -n '4,$p' | + while IFS= read -r old_batch; do + [ "$old_batch" = "$CLIP_CACHE/$1" ] || rm -rf "$old_batch" + done +} + +stage_clip_archive() ( + [ -n "${CLIP_CACHE:-}" ] && [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ] || return 1 + umask 077 + [ ! -L "$CLIP_CACHE" ] && mkdir -p "$CLIP_CACHE" || return 1 + drop_id=$(osascript -l JavaScript "$APP_DIR/drop-resolve.js" clip-manifest-id "$1" 2>/dev/null) || return 1 + case "$drop_id" in clip-*) ;; *) return 1 ;; esac + case "${drop_id#clip-}" in ''|*[!0-9a-f]*) return 1 ;; esac + [ "${#drop_id}" -eq 21 ] || return 1 + cache_dir="$CLIP_CACHE/$drop_id" + [ ! -L "$cache_dir" ] || return 1 + if [ -d "$cache_dir" ]; then + touch "$cache_dir" || return 1 + printf '%s\n' "$drop_id" + return 0 + fi + + stage=$(mktemp -d "$CLIP_CACHE/stage.XXXXXX") || return 1 + trap 'rm -rf "$stage"' EXIT + trap 'exit 1' INT TERM + mkdir "$stage/files" || return 1 + max_wire=$(($2 + 4194304)) + code=$( + ulimit -f "$((max_wire / 512))" || exit 1 + curl -sS -m 15 --max-filesize "$max_wire" -o "$stage/archive.tar" -w '%{http_code}' \ + -H "Authorization: Bearer $REIMS_TOKEN" \ + "$REIMS_HOST_URL/v1/clipboard?format=tar&drop_id=$drop_id" 2>/dev/null + ) || return 1 + [ "$code" = 200 ] && [ -s "$stage/archive.tar" ] || return 1 + # The host writes an uncompressed ustar/pax archive. Verify the entry types + # and manifest before extracting regular files/directories into a private directory. + [ "$(dd if="$stage/archive.tar" bs=1 skip=257 count=5 2>/dev/null)" = ustar ] || return 1 + (ulimit -f 32768 && tar -tvf "$stage/archive.tar") >"$stage/types" 2>/dev/null || return 1 + awk -v max="$2" ' + !/^[-d]/ || NR > 2000 { exit 1 } + /^-/ { + size = $4 ~ /^[0-9][0-9][0-9][0-9]-/ ? $3 : $5 + if (size !~ /^[0-9]+$/) exit 1 + total += size + if (total > max) exit 1 + } + ' "$stage/types" || return 1 + (ulimit -f 32768 && tar -tf "$stage/archive.tar") >"$stage/entries" 2>/dev/null || return 1 + [ "$(osascript -l JavaScript "$APP_DIR/drop-resolve.js" validate-clip-archive "$1" "$stage/entries" 2>/dev/null)" = ok ] || return 1 + COPYFILE_DISABLE=1 tar -xkf "$stage/archive.tar" --no-same-owner --no-same-permissions -C "$stage/files" 2>/dev/null || return 1 + mv "$stage/files" "$cache_dir" || return 1 + prune_clip_cache "$drop_id" + printf '%s\n' "$drop_id" +) + +pack_clip_upload() ( + list=$1 + archive=$2 + max_wire=$3 + item_count=0 + set -- + while IFS= read -r path || [ -n "$path" ]; do + case "$path" in /*) ;; *) return 1 ;; esac + if [ -L "$path" ] || { [ ! -f "$path" ] && [ ! -d "$path" ]; }; then return 1; fi + base=${path##*/} + parent=${path%/*} + # Limit the preflight traversal before invoking tar. Do not follow links. + count=$(find "$path" -xdev \( \( -type d -o -type f \) -print -o -exec printf 'invalid\n' \; -quit \) 2>/dev/null | + awk -v remaining="$((2000 - item_count))" ' + $0 == "invalid" || NR > remaining { invalid = 1; exit } + END { if (invalid || NR == 0) exit 1; print NR } + ') || return 1 + item_count=$((item_count + count)) + set -- ${1+"$@"} -C "${parent:-/}" "./$base" + done < "$list" + [ "$#" -gt 0 ] || return 1 + ulimit -f "$((max_wire / 512))" || return 1 + # Use an uncompressed streaming archive and suppress resource-fork sidecars. + COPYFILE_DISABLE=1 tar -cf "$archive" --one-file-system ${1+"$@"} 2>/dev/null +) + +upload_clip_files() ( + umask 077 + selection=$1 + stage=$(mktemp -d "$TMP_DIR/clip_upload.XXXXXX") || { rm -f "$selection"; return 1; } + trap 'rm -f "$selection"; rm -rf "$stage"' EXIT + trap 'exit 1' INT TERM + osascript -l JavaScript "$APP_DIR/drop-resolve.js" local-clip-paths "$selection" \ + "${DROP_MOUNT:-}" "${DROP_CACHE:-}" "${CLIP_CACHE:-}" "${SHARE_MOUNT:-}" \ + "${DRIVE_MOUNT_ROOT:-}" "${FOLDER_MOUNT_ROOT:-}" >"$stage/paths" 2>/dev/null || return 1 + [ -s "$stage/paths" ] && pack_clip_upload "$stage/paths" "$stage/upload.tar" "$(($2 + 4194304))" || return 1 + for attempt in first retry; do + read_clip_file_config + [ "$upload_files" = 1 ] && [ "$archive_bytes" = "$2" ] || return 1 + read_clipboard_change_count + [ "$clip_cc" = "$3" ] && ! clipboard_poll_interrupted || return 1 + # Reuse the original base on retry. If the first response was lost + # after committing, the host comparison will reject the duplicate. + code=$(curl -sS -m 60 -X POST -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $REIMS_TOKEN" -H 'Content-Type: application/x-tar' \ + -H "X-Clip-Base-Seq: $4" --upload-file "$stage/upload.tar" \ + "$REIMS_HOST_URL/v1/clipboard" 2>/dev/null) || code=000 + case "$code" in + 200|204) return 0 ;; + 000|502|503|504) [ "$attempt" = first ] || return 1; sleep 1 ;; + *) return 1 ;; + esac done - return 1 ) local_clip_hash() { @@ -710,6 +852,8 @@ readback_kind="" readback_cc="" file_retry_hash="" file_retry_polls=0 +file_upload_pid="" +file_upload_cc="" tick=0 TAB=$(printf '\t') @@ -818,10 +962,14 @@ sync_clipboard() { 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 + input_restored=0 + if [ -f "$INJECT_LOCK.completed" ]; then + if ! rm -f "$INJECT_LOCK.completed"; then + release_clip_lock + sleep 1 + return 0 + fi + input_restored=1 fi clip_in="$TMP_DIR/clip_in" clip_out="$TMP_DIR/clip_out" @@ -861,6 +1009,24 @@ sync_clipboard() { post_conflict=0 if [ "$local_kind" = files ]; then + read_clip_file_config + if [ "$upload_files" = 1 ] && [ "$archive_bytes" -gt 0 ] && + [ -n "$last_server_seq" ] && [ -n "$read_cc" ] && + [ -n "${APP_DIR:-}" ] && [ -f "$APP_DIR/drop-resolve.js" ] && + { [ "$cur_hash" != "$last_local_hash" ] || + { [ "$read_cc" != "$file_upload_cc" ] && [ "$input_restored" = 0 ]; }; } && + { [ -z "$file_upload_pid" ] || ! kill -0 "$file_upload_pid" 2>/dev/null; }; then + # Freeze the URL list before returning to the polling loop. + if clip_selection=$(mktemp "$TMP_DIR/clip_selection.XXXXXX") && cp "$clip_in" "$clip_selection"; then + upload_clip_files "$clip_selection" "$archive_bytes" "$read_cc" "$last_server_seq" >/dev/null 2>&1 & + file_upload_pid=$! + file_upload_cc="$read_cc" + elif [ -n "${clip_selection:-}" ]; then + rm -f "$clip_selection" + fi + elif [ "$input_restored" = 1 ] && [ "$cur_hash" = "$last_local_hash" ]; then + file_upload_cc="$read_cc" + fi last_local_hash="$cur_hash" synced_local_cc="$read_cc" synced_local_kind="$local_kind" @@ -965,7 +1131,28 @@ sync_clipboard() { fi if [ "$new_hash" != "$post_get_hash" ]; then if [ "$new_kind" = files ]; then - if ! write_local_files "$clip_out" "$read_cc"; then + delivery=0 + write_local_files "$clip_out" "$read_cc" || delivery=$? + if [ "$delivery" = 2 ] && [ -n "$read_cc" ]; then + read_clip_file_config + if [ "$archive_bytes" -gt 0 ]; then + # Keep IME responsive during HTTP I/O. Require the original + # change count again before changing the pasteboard. + release_clip_lock + cache_id=$(stage_clip_archive "$clip_out" "$archive_bytes") || cache_id="" + if ! acquire_clip_lock; then + defer_file_delivery + return 0 + fi + read_clip_file_config + if [ -n "$cache_id" ] && [ "$archive_bytes" -gt 0 ] && ! clipboard_poll_interrupted && + [ "$(osascript -l JavaScript "$APP_DIR/drop-resolve.js" write-clip-files \ + "$clip_out" "$CLIP_CACHE" "$read_cc" cache 2>/dev/null)" = ok ]; then + delivery=0 + fi + fi + fi + if [ "$delivery" != 0 ]; then defer_file_delivery release_clip_lock return 0 @@ -1012,7 +1199,7 @@ sync_clipboard() { fi fi if [ "$code" = 204 ]; then - last_server_seq="" + last_server_seq=$(clip_header x-clip-seq) else new_seq=$(clip_header x-clip-seq) if [ -n "$new_seq" ]; then @@ -1040,6 +1227,8 @@ sync_clipboard() { clipboard_loop() { cur_pid=$(sh -c 'echo $PPID') + trap 'jobs -p | while IFS= read -r job; do kill "$job" 2>/dev/null || true; done' EXIT + trap 'exit 0' INT TERM while :; do load_conf clip_enabled=1 diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 8dffc48..87e3da4 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -12,6 +12,7 @@ import ( "fmt" "io" "maps" + "mime" "net" "net/http" "os" @@ -299,7 +300,9 @@ type Server struct { management map[string]*managementRelay fileMu sync.Mutex clipWriteMu sync.Mutex + clipArchiveMu sync.Mutex clip Clipboard + clipFileStaging clipFileStaging vms map[string]*registeredVM // keyed by driver.VMRef.Key() davCache map[string]davCacheEntry folderAccessMu sync.RWMutex @@ -441,11 +444,15 @@ func (s *Server) watchClipboardLoop(ctx context.Context) { defer s.watcherCount.Add(-1) ticker := time.NewTicker(150 * time.Millisecond) defer ticker.Stop() + pruneTicker := time.NewTicker(time.Minute) + defer pruneTicker.Stop() lastSeq := s.clip.SequenceNumber() for { select { case <-ctx.Done(): return + case now := <-pruneTicker.C: + s.pruneExpiredClipStaging(now) case <-ticker.C: seq := s.clip.SequenceNumber() if seq != lastSeq { @@ -494,7 +501,9 @@ func (s *Server) Close(ctx context.Context) error { s.watchCancel = nil relays := s.management s.management = nil + s.clearAllClipFilesLocked() s.mu.Unlock() + s.cleanupClipFiles() for _, relay := range relays { relay.close() } @@ -524,6 +533,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { } driveRoots := configuredDriveRoots(cfg) key := vmRegistryKey(cfg.DriverID, cfg.VMName) + defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() @@ -557,11 +567,14 @@ func (s *Server) RegisterVM(cfg VMConfig) { Prefix: "/dav-drop/" + cur.name, FileSystem: &dropWebDAVFS{ store: cur.dropShares, - allowClipboard: func() bool { return s.EffectiveClipboardPolicy(key).allowsHostToGuest() }, + allowClipboard: func() bool { return s.EffectiveClipboardPolicy(key).allowsHostToGuestFiles() }, }, LockSystem: webdav.NewMemLS(), } s.vms[key] = cur + } else if cur.token != cfg.Token { + cur.dropShares.revokeClipboard() + s.clearVMClipFilesLocked(key) } folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders)) for _, folder := range cfg.ResolvedFolders { @@ -629,6 +642,7 @@ func (s *Server) UnregisterVMIfGen(vmKey string, gen uint64) bool { return false } key := normalizeVMRegistryKey(vmKey) + defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() @@ -645,6 +659,7 @@ func (s *Server) UnregisterVMIfGen(vmKey string, gen uint64) bool { // requests retain only their own snapshot and fail authentication on retry. func (s *Server) UnregisterVM(vmKey string) { key := normalizeVMRegistryKey(vmKey) + defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() @@ -658,6 +673,7 @@ func (s *Server) UnregisterVM(vmKey string) { } func (s *Server) unregisterVMLocked(key string) { + s.clearVMClipFilesLocked(key) if vm := s.vms[key]; vm != nil && vm.dropShares != nil { vm.dropShares.clear() } @@ -925,6 +941,7 @@ func (s *Server) authenticateToken(tok string) *registeredVM { key: vm.key, name: vm.name, token: vm.token, + regGen: vm.regGen, dropDAVHandler: vm.dropDAVHandler, sharedDir: vm.sharedDir, sharedRoot: vm.sharedRoot, @@ -974,7 +991,7 @@ 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() { + if policy.allowsHostToGuestFiles() { caps = append(caps, "clipboard-files") } caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...) @@ -1004,19 +1021,22 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { policy := s.EffectiveClipboardPolicy(vm.key) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ - "vm": vm.name, - "keymap_carrier_enabled": vm.keymapCarrierEnabled, - "prevent_sleep": vm.preventSleep, - "webdav_drop_path": "/dav-drop/" + vm.name + "/", - "host_dns_enabled": vm.hostDNSEnabled, - "timezone": effectiveTimezone(vm.guestTimezone), - "webdav_path": "/dav/" + vm.name + "/", - "shared_drives": enabledDriveLetters(vm), - "shared_folders_count": len(vm.resolvedFolders), - "clipboard_enabled": policy.Enabled, - "clipboard_direction": policy.Direction, - "clipboard_sync_images": policy.SyncImages, - "clipboard_max_bytes": policy.MaxImageBytes, + "vm": vm.name, + "keymap_carrier_enabled": vm.keymapCarrierEnabled, + "prevent_sleep": vm.preventSleep, + "webdav_drop_path": "/dav-drop/" + vm.name + "/", + "host_dns_enabled": vm.hostDNSEnabled, + "timezone": effectiveTimezone(vm.guestTimezone), + "webdav_path": "/dav/" + vm.name + "/", + "shared_drives": enabledDriveLetters(vm), + "shared_folders_count": len(vm.resolvedFolders), + "clipboard_enabled": policy.Enabled, + "clipboard_direction": policy.Direction, + "clipboard_sync_images": policy.SyncImages, + "clipboard_max_bytes": policy.MaxImageBytes, + "clipboard_sync_files": policy.Enabled && policy.SyncFiles, + "clipboard_max_file_bytes": policy.MaxFileBytes, + "clipboard_upload_files": policy.allowsGuestToHostFiles() && s.clipboardFileUploadsAvailable(), }) } @@ -1121,8 +1141,21 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { } switch r.Method { case http.MethodGet: + if r.URL.Query().Get("format") == "tar" { + s.serveClipboardArchive(w, r, vm) + return + } s.getClipboard(w, r, vm.key) case http.MethodPost, http.MethodPut: + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if mediaType == "application/x-tar" { + if err != nil { + http.Error(w, "invalid clipboard content type", http.StatusBadRequest) + return + } + s.postClipboardFiles(w, r, vm, s.EffectiveClipboardPolicy(vm.key)) + return + } s.postClipboard(w, r, vm.key) default: if !s.EffectiveClipboardPolicy(vm.key).Enabled { @@ -1201,7 +1234,7 @@ func (s *Server) clipboardFileManifest(vmKey string, seq uint32, entries []DropS 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 wantFiles && !s.isStagedClipboardFiles(payload.Files) { if entries := prepareClipboardFiles(payload.Files); len(entries) > 0 { return s.clipboardFileManifest(vmKey, seq, entries) } @@ -1254,13 +1287,14 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri } wantImage := wantsImage && policy.SyncImages - payload, seq, h, err := s.readClipboardForSync(wantImage, wantsFiles) + wantFiles := wantsFiles && policy.allowsHostToGuestFiles() + payload, seq, h, err := s.readClipboardForSync(wantImage, wantFiles) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) return } - payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantsFiles, wantImage, policy.MaxImageBytes) + payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantFiles, wantImage, policy.MaxImageBytes) if h != "" { unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq)) if !unchanged || time.Until(deadline) <= 0 { @@ -1291,6 +1325,7 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri } } else if time.Until(deadline) <= 0 { // Keep guest-to-host-only agents from busy-looping. + setClipboardSeq(w, s.clip.SequenceNumber()) w.WriteHeader(http.StatusNoContent) return } diff --git a/internal/guesttools/testdata/pasteboard.cjs b/internal/guesttools/testdata/pasteboard.cjs index 639e95a..78bcef5 100644 --- a/internal/guesttools/testdata/pasteboard.cjs +++ b/internal/guesttools/testdata/pasteboard.cjs @@ -1,6 +1,7 @@ // Run the installed JXA resolver against a pasteboard shared by shell fixture processes. const fs = require('node:fs') const vm = require('node:vm') +const {posix} = require('node:path') const {pathToFileURL} = require('node:url') const [resolver, ...argv] = process.argv.slice(2) @@ -8,7 +9,11 @@ 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 + js, isNil: () => false, dataUsingEncoding: () => js, + get stringByStandardizingPath() { return wrap(posix.normalize(js)) }, + get stringByResolvingSymlinksInPath() { + return wrap(posix.normalize(js).replace(/^\/Volumes\/DropAlias(?=\/|$)/, '/private/guest/DropMount')) + } } const unwrap = value => value?.js ?? value const array = values => ({ @@ -33,7 +38,10 @@ const pasteboard = { get changeCount() { return state.changeCount }, get clearContents() { state.items = []; return ++state.changeCount }, writeObjects(items) { + const incomingFiles = items.every(i => i.flavors['public.file-url']) + if (incomingFiles && fs.existsSync('test-fail-file-write')) return false state.items = items.map(i => i.flavors) + if (incomingFiles && fs.existsSync('test-partial-file-write')) state.items.pop() state.changeCount++ return true } @@ -60,9 +68,19 @@ const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value 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 - })}, + NSURL: { + fileURLWithPath: path => ({ + absoluteString: wrap(pathToFileURL(path).href), fileReferenceURL: fs.existsSync(path) ? wrap(path) : nil + }), + URLWithString: raw => { + const url = new URL(raw) + return { + isFileURL: url.protocol === 'file:', isNil: () => false, + host: wrap(url.host), path: wrap(decodeURIComponent(url.pathname)), + filePathURL: {isNil: () => false, path: wrap('/private/guest/DropMount/readback')} + } + } + }, NSFileManager: {defaultManager: { fileExistsAtPathIsDirectory(path, dir) { dir[0] = fs.statSync(path, {throwIfNoEntry: false})?.isDirectory() ?? false @@ -81,7 +99,7 @@ const $ = Object.assign(value => typeof value === 'string' ? wrap(value) : value }}, NSFileHandle: {fileHandleWithNullDevice: null} }) -const context = {ObjC: {import() {}, unwrap}, $, argv, Ref: () => []} +const context = {ObjC: {import() {}, unwrap, deepUnwrap: unwrap}, $, argv, Ref: () => []} try { console.log(vm.runInNewContext(fs.readFileSync(resolver, 'utf8') + '\nrun(argv)', context)) } finally { diff --git a/internal/guesttools/text_input_agent_test.go b/internal/guesttools/text_input_agent_test.go index 7a8d061..1214600 100644 --- a/internal/guesttools/text_input_agent_test.go +++ b/internal/guesttools/text_input_agent_test.go @@ -30,7 +30,7 @@ func TestGuestAgentTextInjection(t *testing.T) { {"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"} { + for _, scenario := range []string{"files", "failed_ack", "user_copy", "legacy", "deferred_flavor"} { t.Run(scenario, func(t *testing.T) { lockShellFixture(t) dir := t.TempDir() @@ -52,6 +52,9 @@ func TestGuestAgentTextInjection(t *testing.T) { if err != nil { t.Fatal(err) } + if scenario == "deferred_flavor" { + items = bytes.Replace(items, []byte("{"), []byte(`{"example.deferred":null,`), 1) + } write("test-pasteboard.json", []byte(`{"changeCount":17,"items":`+string(items)+"}")) if scenario != "legacy" { write("drop-resolve.js", []byte(guestDropResolveJS)) diff --git a/internal/guesttools/transport.go b/internal/guesttools/transport.go index cbcb6c1..8562eda 100644 --- a/internal/guesttools/transport.go +++ b/internal/guesttools/transport.go @@ -24,19 +24,30 @@ type ClipboardPolicy struct { Direction ClipboardDirection `json:"direction"` SyncImages bool `json:"sync_images"` MaxImageBytes int `json:"max_image_bytes"` + SyncFiles bool `json:"sync_files"` + MaxFileBytes int `json:"max_file_bytes"` } func (p ClipboardPolicy) allowsHostToGuest() bool { return p.Enabled && p.Direction != ClipboardGuestToHost } -// DefaultClipboardPolicy returns the default bidirectional text+image policy. +func (p ClipboardPolicy) allowsHostToGuestFiles() bool { + return p.SyncFiles && p.allowsHostToGuest() +} + +func (p ClipboardPolicy) allowsGuestToHostFiles() bool { + return p.Enabled && p.SyncFiles && p.Direction != ClipboardHostToGuest +} + func DefaultClipboardPolicy() ClipboardPolicy { return ClipboardPolicy{ Enabled: true, Direction: ClipboardBidirectional, SyncImages: true, MaxImageBytes: MaxClipboardBytes, + SyncFiles: true, + MaxFileBytes: DefaultClipboardMaxFileBytes, } } @@ -109,6 +120,7 @@ func (s *Server) SetClipboardActive(active bool) { for _, vm := range s.vms { vm.dropShares.revokeClipboard() } + s.clearAllClipFilesLocked() delete(s.dynamicRoutes, "/v1/clipboard") cancel := s.watchCancel s.watchCancel = nil @@ -117,6 +129,7 @@ func (s *Server) SetClipboardActive(active bool) { if cancel != nil { cancel() } + s.cleanupClipFiles() s.broadcastClipChange() } @@ -138,11 +151,16 @@ func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) { s.mu.Lock() s.globalClipPolicy = p for key, vm := range s.vms { - if !s.effectiveClipboardPolicyLocked(key).allowsHostToGuest() { + policy := s.effectiveClipboardPolicyLocked(key) + if !policy.allowsHostToGuestFiles() { vm.dropShares.revokeClipboard() } + if !policy.allowsGuestToHostFiles() { + s.clearVMClipFilesLocked(key) + } } s.mu.Unlock() + s.cleanupClipFiles() s.broadcastClipChange() } @@ -158,10 +176,17 @@ 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() + if vm := s.vms[vmName]; vm != nil { + policy := s.effectiveClipboardPolicyLocked(vmName) + if !policy.allowsHostToGuestFiles() { + vm.dropShares.revokeClipboard() + } + if !policy.allowsGuestToHostFiles() { + s.clearVMClipFilesLocked(vmName) + } } s.mu.Unlock() + s.cleanupClipFiles() s.broadcastClipChange() } @@ -205,6 +230,10 @@ func normalizeClipboardPolicy(p ClipboardPolicy) ClipboardPolicy { if p.MaxImageBytes <= 0 || p.MaxImageBytes > MaxClipboardBytes { p.MaxImageBytes = MaxClipboardBytes } + if p.MaxFileBytes == 0 { + p.MaxFileBytes = DefaultClipboardMaxFileBytes + } + p.MaxFileBytes = max(MinClipboardMaxFileMB<<20, min(MaxClipboardMaxFileMB<<20, p.MaxFileBytes)) return p } diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index 24c0617..ff02bcb 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -227,6 +227,8 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef { minMB := 1.0 maxMB := 16.0 + minFileMB := float64(guesttools.MinClipboardMaxFileMB) + maxFileMB := float64(guesttools.MaxClipboardMaxFileMB) return plugin.PluginDef{ Manifest: plugin.Manifest{ Schema: 1, @@ -234,8 +236,8 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Version: ver, Name: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"}, Description: plugin.LocalizedText{ - ZhCN: "在 Windows 和 macOS 之间同步复制的文本与截图", - EnUS: "Sync copied text and screenshots between Windows and macOS", + ZhCN: "在 Windows 和 macOS 之间同步复制的文本、截图与文件", + EnUS: "Sync copied text, screenshots, and files between Windows and macOS", }, Publisher: "Reims-Go", License: "Apache-2.0", @@ -246,7 +248,7 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"}, Group: "collaboration", Scope: "vm", - Order: []string{"enabled", "direction", "sync_images", "max_image_mb"}, + Order: []string{"enabled", "direction", "sync_images", "max_image_mb", "sync_files", "max_file_mb"}, Properties: map[string]plugin.SettingProperty{ "enabled": { Type: "boolean", @@ -288,6 +290,28 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Scope: "vm", Group: "collaboration", }, + "sync_files": { + Type: "boolean", + Title: plugin.LocalizedText{ZhCN: "同步剪贴板文件", EnUS: "Sync clipboard files"}, + Default: true, + Effect: "immediate", + Scope: "both", + Group: "collaboration", + }, + "max_file_mb": { + Type: "integer", + Title: plugin.LocalizedText{ZhCN: "文件传输上限 (MB)", EnUS: "File transfer limit (MB)"}, + Description: plugin.LocalizedText{ + ZhCN: "限制从 macOS 粘贴到 Windows 或共享挂载不可用时的单次传输总大小。", + EnUS: "Limits the total size per paste from macOS to Windows or when the shared mount is unavailable.", + }, + Default: guesttools.DefaultClipboardPolicy().MaxFileBytes >> 20, + Minimum: &minFileMB, + Maximum: &maxFileMB, + Effect: "immediate", + Scope: "both", + Group: "collaboration", + }, }, }, }, diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 87ed7fe..32119e3 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -908,6 +908,20 @@ func (m *Manager) stateNotLoadedErr() error { // --- Settings store (app-scoped & vm-scoped, hiding x-secret on readback) --- +func inheritsAppSetting(schema *SettingsSchema, key string) bool { + if schema == nil { + return false + } + prop, exists := schema.Properties[key] + if !exists { + return false + } + if prop.Scope != "" { + return prop.Scope == "both" + } + return schema.Scope == "both" +} + func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[string]any { var schema *SettingsSchema if info, ok := m.registry.Info(pluginID); ok { @@ -926,12 +940,13 @@ func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[str } if m.state != nil { if rec := m.state.Plugins[pluginID]; rec != nil { - if vmName == "" { - for k, v := range rec.AppSettings { + for k, v := range rec.AppSettings { + if vmName == "" || inheritsAppSetting(schema, k) { out[k] = v } - } else if vmMap := rec.VMSettings[vmName]; vmMap != nil { - for k, v := range vmMap { + } + if vmName != "" { + for k, v := range rec.VMSettings[vmName] { out[k] = v } } @@ -1104,10 +1119,10 @@ func (m *Manager) GetAllVMSettings(vmName string) map[string]map[string]any { if info.Settings == nil { continue } - hasVMProp := info.Settings.Scope == "vm" + hasVMProp := info.Settings.Scope == "vm" || info.Settings.Scope == "both" if !hasVMProp { for _, p := range info.Settings.Properties { - if p.Scope == "vm" { + if p.Scope == "vm" || p.Scope == "both" { hasVMProp = true break } diff --git a/internal/plugin/types.go b/internal/plugin/types.go index 71ead56..04ba606 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -660,7 +660,7 @@ type DiagnosticsContribution struct { type SettingsSchema struct { Title LocalizedText `json:"title,omitempty"` Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration" - Scope string `json:"x-scope,omitempty"` // "app" | "vm" + Scope string `json:"x-scope,omitempty"` // "app" | "vm" | "both" Properties map[string]SettingProperty `json:"properties"` Order []string `json:"x-order,omitempty"` } @@ -677,7 +677,7 @@ type SettingProperty struct { Maximum *float64 `json:"maximum,omitempty"` Secret bool `json:"x-secret,omitempty"` Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start" - Scope string `json:"x-scope,omitempty"` // "app" | "vm" + Scope string `json:"x-scope,omitempty"` // "app" | "vm" | "both" Group string `json:"x-group,omitempty"` // VM settings section id Required bool `json:"required,omitempty"` }