From f6989a40f727bb5d489a6058d1e9739846264a8c Mon Sep 17 00:00:00 2001 From: staytomorrow Date: Wed, 2 Dec 2026 23:38:11 +0800 Subject: [PATCH 1/3] feat(guesttools): add bidirectional file and folder clipboard sync --- changes/clipboard-file-sync.json | 7 + docs/architecture.md | 2 +- frontend/src/components/PluginsPage.tsx | 9 +- frontend/src/components/SchemaForm.tsx | 2 +- frontend/src/components/VMPage.tsx | 2 +- internal/app/guesttools_flow.go | 3 + internal/app/plugins_flow.go | 52 +- internal/guesttools/clipboard_agent_test.go | 194 +++- internal/guesttools/clipboard_files.go | 978 ++++++++++++++++++ internal/guesttools/clipboard_files_test.go | 401 +++++++ internal/guesttools/clipboard_other.go | 27 +- internal/guesttools/clipboard_webdav.go | 615 +++++++++++ internal/guesttools/clipboard_windows.go | 76 +- internal/guesttools/clipboard_windows_test.go | 38 +- internal/guesttools/folder_agent_test.go | 25 +- internal/guesttools/folder_share.go | 3 +- internal/guesttools/guesttools_test.go | 24 +- internal/guesttools/image.go | 628 ++++++++++- internal/guesttools/server.go | 178 +++- internal/guesttools/transport.go | 34 +- internal/guesttools/transport_test.go | 17 +- internal/plugin/builtin/builtin.go | 50 +- internal/plugin/builtin/builtin_test.go | 28 +- internal/plugin/manager.go | 19 +- 24 files changed, 3251 insertions(+), 161 deletions(-) create mode 100644 changes/clipboard-file-sync.json create mode 100644 internal/guesttools/clipboard_files.go create mode 100644 internal/guesttools/clipboard_files_test.go create mode 100644 internal/guesttools/clipboard_webdav.go diff --git a/changes/clipboard-file-sync.json b/changes/clipboard-file-sync.json new file mode 100644 index 0000000..cafbbaf --- /dev/null +++ b/changes/clipboard-file-sync.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 70, + "authors": ["yxc0915"], + "zh": "剪贴板互通支持在 Windows 与 macOS 之间双向复制粘贴文件与文件夹,宿主到虚拟机按需只读挂载免预拷贝,虚拟机到宿主默认限制单次 `128 MB`(可在插件设置中于 `1–512 MB` 间调节),已安装的虚拟机需更新至第 13 版 Guest Tools。", + "en": "Sync copied files and folders both ways in Clipboard Sync, mounting on demand from Windows to macOS without pre-copying and capping macOS-to-Windows transfers at `128 MB` by default (adjustable from `1` to `512 MB` in plugin settings); installed VMs require Guest Tools v13." +} diff --git a/docs/architecture.md b/docs/architecture.md index b9e9761..b5a6d96 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ Windows 10 缺少虚拟化分区热重置能力,客体内部重启会导致虚 宿客协作服务仅监听本机回环地址 `127.0.0.1`,为每台虚拟机分配独立的 256 位随机访问令牌,所有连接状态、剪贴板策略与文件路由均按驱动和实例隔离。 -共享文件夹服务对每次读写强制约束在授权根目录之内,拦截目录穿越与越界符号链接。Windows 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。 +共享文件夹服务对每次读写强制约束在授权根目录之内,拦截目录穿越与越界符号链接。Windows 盘符只读共享默认全部关闭;启用后同时限制只读打开标志与写请求方法、核对持久化卷标识防止盘符漂移、限制目录遍历深度,并验证目录联接与符号链接目标仍位于已授权盘符内。文件剪贴板在宿主到虚拟机方向采用按批次隔离的只读虚拟挂载以省去预先拷贝,在虚拟机到宿主方向流式校验归档并解包至数据目录临时空间,插件停用或应用退出时自动清空暂存目录。 ### 宿主机体检与资源约束 diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 50448a7..cdbd2d7 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -34,12 +34,15 @@ 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. +// The plugin settings dialog shows app-scope (or shared 'both'-scope) fields; +// per-VM overrides live in each VM's settings. Same scope rule as SchemaForm. 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. */ diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index cc212d3..071f0a7 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -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 }) diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index b042fef..193ac78 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -1063,7 +1063,7 @@ export const VMPage: React.FC = ({ const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 - const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 13 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 14 const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached') // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 65d49f8..68ba348 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -108,6 +108,9 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created } else { srv = guesttools.NewServer(nil) } + if a.cfg != nil && a.cfg.DataRoot != "" && !a.needsSetup && !a.root.ReadOnly { + srv.SetClipStagingDir(filepath.Join(a.cfg.TempDir(), "clip-files")) + } srv.SetHostDropHandler(a.handleHostDrop) srv.SetDropAckHandler(a.handleHostDropAck) srv.SetDropPasteHandler(a.handleHostDropPaste) diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index a612cf2..e53fe8e 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -477,12 +477,13 @@ 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) + mergedVals := mgr.GetSettings(builtin.IDClipboard, vmKey, false) + pol := clipboardPolicyFromMap(mergedVals) gt.SetVMClipboardPolicy(ref.Key(), &pol) } } @@ -490,16 +491,16 @@ 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 { + if vmName == "" { + a.syncClipboardPolicies() + } else { + 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) ref, ok := driver.ParseVMRef(vmName) if !ok { ref = driver.NewVMRef("", vmName) @@ -555,6 +556,33 @@ func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy { p.MaxImageBytes = v << 20 } } + if v, ok := vals["sync_files"].(bool); ok { + p.SyncFiles = v + } + switch v := vals["max_file_mb"].(type) { + case float64: + if v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) { + mb := int(math.Round(v)) + if mb < guesttools.MinClipboardMaxFileMB { + mb = guesttools.MinClipboardMaxFileMB + } + if mb > guesttools.MaxClipboardMaxFileMB { + mb = guesttools.MaxClipboardMaxFileMB + } + p.MaxFileBytes = mb << 20 + } + case int: + if v > 0 { + mb := v + if mb < guesttools.MinClipboardMaxFileMB { + mb = guesttools.MinClipboardMaxFileMB + } + if mb > guesttools.MaxClipboardMaxFileMB { + mb = guesttools.MaxClipboardMaxFileMB + } + p.MaxFileBytes = mb << 20 + } + } return p } diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 678fa1f..ca3c46e 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -12,8 +12,18 @@ import ( func TestGuestAgentClipboardScript(t *testing.T) { sh, err := exec.LookPath("sh") if err != nil { - sh = "C:/Program Files/Git/bin/sh.exe" - if _, err := os.Stat(sh); err != nil { + candidates := []string{"C:/Program Files/Git/bin/sh.exe"} + if gitExe, lookErr := exec.LookPath("git"); lookErr == nil { + gitRoot := filepath.Dir(filepath.Dir(gitExe)) + candidates = append(candidates, filepath.ToSlash(filepath.Join(gitRoot, "bin", "sh.exe"))) + } + for _, cand := range candidates { + if _, statErr := os.Stat(cand); statErr == nil { + sh, err = cand, nil + break + } + } + if err != nil { t.Skip("POSIX sh is unavailable") } } @@ -29,11 +39,35 @@ func TestGuestAgentClipboardScript(t *testing.T) { if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") } + clipSection := agent[start:end] + for _, bad := range []string{ + "$.NSMutableArray.array()", + "$.NSMutableArray.alloc.init", + "EncodingError(mfPath, $.NSUTF8StringEncoding, null)", + "EncodingError(outPath, true, $.NSUTF8StringEncoding, null)", + "attributesOfItemAtPathError(p, null)", + } { + if strings.Contains(clipSection, bad) { + t.Fatalf("guest JXA clipboard code contains broken ObjC bridge pattern: %s", bad) + } + } + for _, must := range []string{ + "$.NSMutableArray.arrayWithCapacity(", + "pb.clearContents", + `rawURL.indexOf("file:///.file/") === 0`, + `attrs.objectForKey("NSFileType")`, + } { + if !strings.Contains(clipSection, must) { + t.Fatalf("guest JXA clipboard code missing required ObjC bridge pattern: %s", must) + } + } for _, name := range []string{ "failed_png", "failed_text", "reencoded_png", "guest_changes_during_get", "conflict", "conflict_skipped_host", "oversized", "disabled_upload", "post_error", "guest_only_after_switch", "cold_guest_only", "cold_304", "empty_text_and_png_fallback", + "files_guest_to_host", "files_host_to_guest_webdav", "files_host_to_guest_webdav_remount", + "files_host_to_guest_tar_fallback", "files_oversized_local", } { t.Run(name, func(t *testing.T) { t.Parallel() @@ -75,12 +109,36 @@ check_post_base=0 hash_file() { cat "$1"; } hash_png_file() { printf 'png:'; cat "$1"; } +hash_files_manifest() { printf 'files-local:'; tr '\n\t' '__' < "$1"; } +urlencode() { printf '%s' "$1"; } pbpaste() { cat local_value; } pbcopy() { [ "$flags" != fail ] || return 1 cat > local_value } osascript() { + if [ "$1" = "-l" ] && [ "$2" = "JavaScript" ]; then + case "$4" in + '/* reims-read-files */'*) + if [ -f local_files_manifest ]; then + cp local_files_manifest "$REIMS_CLIP_OUT_FILE" + cat local_files_mode + fi + ;; + '/* reims-write-files */'*) + [ "$flags" != fail ] || { printf 'err\n'; return 0; } + item_name=$(sed -n 's/.*"items"[[:space:]]*:[[:space:]]*\["\([^"]*\)".*/\1/p' "$REIMS_CLIP_MANIFEST_FILE") + target_file="${REIMS_CLIP_BATCH_DIR%/}/$item_name" + [ -e "$target_file" ] || { printf 'err\n'; return 0; } + printf 'hosted\t%s\n' "$target_file" > local_files_manifest + printf 'files_hosted\n' > local_files_mode + local_info="«class furl», Unicode text" + printf '%s\n' "$target_file" > written_clip_path + printf 'ok\n' + ;; + esac + return 0 + fi case "$2" in 'clipboard info') if [ -f reencoded ]; then @@ -111,6 +169,7 @@ curl() { headers="" output="" base="" + ctype="" body="" url="" while [ "$#" -gt 0 ]; do @@ -122,6 +181,7 @@ curl() { -H) case "$2" in 'X-Clip-Base-Seq: '*) base="$2" ;; + 'Content-Type: '*) ctype="${2#Content-Type: }" ;; esac shift ;; @@ -131,6 +191,7 @@ curl() { done if [ "$method" = POST ]; then printf '%s %s\n' "$method" "$base" >> calls + printf '%s\n' "$ctype" > last_post_ctype if [ "$check_post_base" = 1 ] && [ "$get_code" != 204 ] && [ "$base" != "X-Clip-Base-Seq: $get_seq" ]; then printf 'X-Clip-Seq: %s\r\n' "$get_seq" > "$headers" printf '409' @@ -143,6 +204,15 @@ curl() { printf '%s' "$post_code" else printf '%s %s\n' "$method" "$url" >> calls + case "$url" in + *'format=tar'*) + if [ "${tar_dl_code:-200}" = "200" ] && [ -f host_tar_payload ]; then + cp host_tar_payload "$output" + fi + printf '%s' "${tar_dl_code:-200}" + return + ;; + esac printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers" printf '%s' "$get_value" > "$output" if [ "$flags" = guest_change ]; then @@ -292,5 +362,125 @@ case "$1" in expect "$(read_local_clipboard ./clip_in)" png expect "$(cat ./clip_in)" tiff-converted ;; + files_guest_to_host) + last_local_hash=init + last_server_hash=init-srv + last_server_seq=3 + post_hash=files-srv-hash + post_seq=4 + mkdir -p src_dir + printf 'hello-from-finder' > src_dir/report.txt + # Finder puts both furl and plain filename text on pasteboard; furl must win. + printf 'report.txt' > local_value + local_info="«class furl», Unicode text" + printf 'f\t17\t1700000000\t%s/src_dir/report.txt\n' "$PWD" > local_files_manifest + printf 'files\n' > local_files_mode + sync_clipboard + expect "$(methods)" POST + expect "$(cat last_post_ctype)" "application/x-tar" + mkdir -p unpacked_post + tar -xf host_value -C unpacked_post + expect "$(cat unpacked_post/report.txt)" "hello-from-finder" + expect "$last_server_hash/$last_server_seq" "files-srv-hash/4" + # Next poll must send accept=image,files and not re-POST unchanged local files. + get_code=304 + get_hash=files-srv-hash + get_seq=4 + sync_clipboard + expect "$(methods)" POST,GET + grep -F 'accept=image,files' calls + ;; + files_host_to_guest_webdav) + REIMS_VM=mac + CLIP_MOUNT="$PWD/clip_mount" + mount_calls=0 + ensure_clip_mount() { + mount_calls=$((mount_calls + 1)) + mkdir -p "$CLIP_MOUNT/b_host1" + printf 'zero-copy-payload' > "$CLIP_MOUNT/b_host1/movie.mp4" + return 0 + } + get_kind=files + get_hash=host-batch-1 + get_seq=11 + get_value='{"batch":"b_host1","items":["movie.mp4"],"total_bytes":999999999,"exceeds_tar_limit":true}' + sync_clipboard + expect "$mount_calls" 1 + expect "$(cat written_clip_path)" "$CLIP_MOUNT/b_host1/movie.mp4" + expect "$last_server_hash/$last_server_seq" "host-batch-1/11" + # Hosted clip_mount paths must NEVER echo back as a guest->host POST! + get_code=304 + sync_clipboard + expect "$(methods)" GET,GET + ;; + files_host_to_guest_webdav_remount) + REIMS_VM=mac + CLIP_MOUNT="$PWD/clip_mount" + mkdir -p "$CLIP_MOUNT" + mount_calls=0 + unmount_calls=0 + unmount_shared_folder() { + unmount_calls=$((unmount_calls + 1)) + return 0 + } + ensure_clip_mount() { + mount_calls=$((mount_calls + 1)) + if [ "$unmount_calls" -ge 1 ]; then + mkdir -p "$CLIP_MOUNT/b_fresh" + printf 'remounted-payload' > "$CLIP_MOUNT/b_fresh/doc.docx" + fi + return 0 + } + get_kind=files + get_hash=host-batch-fresh + get_seq=21 + get_value='{"batch":"b_fresh","items":["doc.docx"],"total_bytes":17,"exceeds_tar_limit":false}' + sync_clipboard + expect "$unmount_calls" 1 + expect "$mount_calls" 2 + expect "$(cat written_clip_path)" "$CLIP_MOUNT/b_fresh/doc.docx" + expect "$last_server_hash/$last_server_seq" "host-batch-fresh/21" + ;; + files_host_to_guest_tar_fallback) + REIMS_VM=mac + CLIP_MOUNT="$PWD/clip_mount" + CLIP_FALLBACK_DIR="$PWD/clip_files" + ensure_clip_mount() { return 1; } + mkdir -p host_src + printf 'tar-fallback-data' > host_src/small.txt + tar -cf host_tar_payload -C host_src ./small.txt + get_kind=files + get_hash=host-batch-small + get_seq=12 + get_value='{"batch":"b_small","items":["small.txt"],"total_bytes":17,"exceeds_tar_limit":false}' + sync_clipboard + expect "$(cat written_clip_path)" "$CLIP_FALLBACK_DIR/b_small/small.txt" + expect "$(cat "$CLIP_FALLBACK_DIR/b_small/small.txt")" "tar-fallback-data" + # Oversized batch when WebDAV is down skips cleanly and records hash to avoid tight loops. + get_hash=host-batch-huge + get_seq=13 + get_value='{"batch":"b_huge","items":["huge.iso"],"total_bytes":999999999,"exceeds_tar_limit":true}' + sync_clipboard + expect "$last_server_hash/$last_server_seq" "host-batch-huge/13" + ;; + files_oversized_local) + last_local_hash=old + last_server_hash=old-srv + last_server_seq=5 + clip_max_file_bytes=10 + mkdir -p big_src + printf '0123456789ABCDEF' > big_src/big.bin + local_info="«class furl», Unicode text" + printf 'f\t16\t1700000000\t%s/big_src/big.bin\n' "$PWD" > local_files_manifest + printf 'files\n' > local_files_mode + get_code=304 + get_hash=old-srv + get_seq=5 + sync_clipboard + # Must skip POST (neither tar nor fallback filename text) and advance last_local_hash. + expect "$(methods)" GET + sync_clipboard + expect "$(methods)" GET,GET + ;; esac ` diff --git a/internal/guesttools/clipboard_files.go b/internal/guesttools/clipboard_files.go new file mode 100644 index 0000000..8843c08 --- /dev/null +++ b/internal/guesttools/clipboard_files.go @@ -0,0 +1,978 @@ +package guesttools + +import ( + "archive/tar" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode" + "unicode/utf16" +) + +const ( + cfHDrop = 15 + dropFilesHeaderSize = 20 + MaxClipboardFileCount = 2000 + MaxClipboardFileBatches = 3 + clipStagingMaxAge = 30 * time.Minute + tarStreamSlackBytes = 2 << 20 // Tar headers and 512-byte padding overhead +) + +var ( + errClipArchiveTooLarge = errors.New("clipboard file archive exceeds limit") + errClipArchiveInvalid = errors.New("invalid clipboard file archive") + errClipStagingUnset = errors.New("clipboard file staging directory not configured") +) + +type clipBatchManifest struct { + Batch string `json:"batch"` + Items []string `json:"items"` + TotalBytes int64 `json:"total_bytes"` + ExceedsTarLimit bool `json:"exceeds_tar_limit,omitempty"` +} + +type clipBatchItem struct { + name string + hostPath string + parentDir string + baseName string + dirRoot sharedRoot + isDir bool + size int64 + modNano int64 +} + +type clipHostBatch struct { + id string + hash string + createdAt time.Time + order []string + items map[string]clipBatchItem + totalBytes int64 + scannedLimit int64 + exceedsTarLimit bool +} + +type clipGuestBatch struct { + id string + dir string + createdAt time.Time +} + +// SetClipStagingDir sets the root directory under DataRoot (e.g. /tmp/clip-files) +// used to unpack guest-to-host file clipboard archives. Any stale residue in dir is cleared. +func (s *Server) SetClipStagingDir(dir string) { + clean := "" + if strings.TrimSpace(dir) != "" { + if abs, err := filepath.Abs(dir); err == nil { + clean = abs + } else { + clean = filepath.Clean(dir) + } + } + s.mu.Lock() + old := s.clipStagingDir + s.clipStagingDir = clean + s.clipGuestBatches = make(map[string][]clipGuestBatch) + s.mu.Unlock() + + if old != "" && old != clean { + _ = os.RemoveAll(old) + } + if clean != "" { + _ = os.RemoveAll(clean) + } +} + +func (s *Server) clearAllClipFiles() { + s.mu.Lock() + staging := s.clipStagingDir + s.clipHostBatches = make(map[string][]*clipHostBatch) + s.clipGuestBatches = make(map[string][]clipGuestBatch) + s.clipDAVHandlers = make(map[string]*clipDAVEntry) + s.mu.Unlock() + + if staging != "" { + _ = os.RemoveAll(staging) + } +} + +func (s *Server) clearVMClipFiles(vmKey string) { + vmKey = normalizeVMRegistryKey(vmKey) + s.mu.Lock() + staging := s.clipStagingDir + batches := s.clipGuestBatches[vmKey] + delete(s.clipHostBatches, vmKey) + delete(s.clipGuestBatches, vmKey) + delete(s.clipDAVHandlers, vmKey) + s.mu.Unlock() + + for _, b := range batches { + if b.dir != "" { + _ = os.RemoveAll(b.dir) + } + } + if staging != "" { + _ = os.RemoveAll(filepath.Join(staging, vmStagingSubdir(vmKey))) + } +} + +func (s *Server) pruneExpiredClipStaging(now time.Time) { + var toRemove []string + s.mu.Lock() + for vmKey, list := range s.clipGuestBatches { + kept := list[:0] + for _, b := range list { + if now.Sub(b.createdAt) > clipStagingMaxAge { + if b.dir != "" { + toRemove = append(toRemove, b.dir) + } + continue + } + kept = append(kept, b) + } + if len(kept) == 0 { + delete(s.clipGuestBatches, vmKey) + } else { + s.clipGuestBatches[vmKey] = kept + } + } + s.mu.Unlock() + + for _, dir := range toRemove { + _ = os.RemoveAll(dir) + } +} + +func vmStagingSubdir(vmKey string) string { + sum := sha256.Sum256([]byte(vmKey)) + return hex.EncodeToString(sum[:8]) +} + +func newClipBatchID() (string, error) { + var raw [12]byte + if _, err := rand.Read(raw[:]); err != nil { + return "", err + } + return "b_" + hex.EncodeToString(raw[:]), nil +} + +// encodeHDropBytes encodes a non-empty list of file paths into a Win32 CF_HDROP +// DROPFILES structure with UTF-16LE double-NUL-terminated paths. +func encodeHDropBytes(paths []string) ([]byte, error) { + if len(paths) == 0 { + return nil, errors.New("empty clipboard file list") + } + if len(paths) > MaxClipboardFileCount { + return nil, fmt.Errorf("clipboard file list exceeds %d items", MaxClipboardFileCount) + } + var words []uint16 + for _, raw := range paths { + p := strings.TrimSpace(raw) + if p == "" || strings.ContainsRune(p, 0) { + return nil, errors.New("invalid clipboard file path") + } + p = filepath.Clean(p) + words = append(words, utf16.Encode([]rune(p))...) + words = append(words, 0) + } + words = append(words, 0) // terminating double-NUL + + out := make([]byte, dropFilesHeaderSize+len(words)*2) + binary.LittleEndian.PutUint32(out[0:4], dropFilesHeaderSize) // pFiles + binary.LittleEndian.PutUint32(out[4:8], 0) // pt.x + binary.LittleEndian.PutUint32(out[8:12], 0) // pt.y + binary.LittleEndian.PutUint32(out[12:16], 0) // fNC + binary.LittleEndian.PutUint32(out[16:20], 1) // fWide = TRUE (UTF-16LE) + for i, w := range words { + binary.LittleEndian.PutUint16(out[dropFilesHeaderSize+i*2:], w) + } + return out, nil +} + +// parseHDropBytes decodes a Win32 CF_HDROP DROPFILES memory block into paths. +func parseHDropBytes(raw []byte) ([]string, error) { + if len(raw) < dropFilesHeaderSize { + return nil, errors.New("CF_HDROP buffer too short") + } + offset := binary.LittleEndian.Uint32(raw[0:4]) + if offset < dropFilesHeaderSize || int(offset) >= len(raw) { + return nil, errors.New("CF_HDROP offset out of bounds") + } + wide := binary.LittleEndian.Uint32(raw[16:20]) != 0 + payload := raw[offset:] + + var paths []string + if wide { + nWords := len(payload) / 2 + var cur []uint16 + for i := 0; i < nWords; i++ { + u := binary.LittleEndian.Uint16(payload[i*2:]) + if u == 0 { + if len(cur) == 0 { + break + } + p := strings.TrimSpace(string(utf16.Decode(cur))) + if p != "" { + paths = append(paths, filepath.Clean(p)) + if len(paths) >= MaxClipboardFileCount { + break + } + } + cur = cur[:0] + continue + } + cur = append(cur, u) + } + } else { + for len(payload) > 0 { + idx := strings.IndexByte(string(payload), 0) + if idx < 0 { + break + } + if idx == 0 { + break + } + p := strings.TrimSpace(string(payload[:idx])) + if p != "" { + paths = append(paths, filepath.Clean(p)) + if len(paths) >= MaxClipboardFileCount { + break + } + } + payload = payload[idx+1:] + } + } + return paths, nil +} + +func uniqueClipEntryName(base string, used map[string]bool) string { + if !used[base] { + used[base] = true + return base + } + ext := filepath.Ext(base) + stem := strings.TrimSuffix(base, ext) + if stem == "" { + stem = base + ext = "" + } + for n := 2; ; n++ { + cand := fmt.Sprintf("%s (%d)%s", stem, n, ext) + if !used[cand] { + used[cand] = true + return cand + } + } +} + +func sanitizeClipBaseName(name string) (string, bool) { + name = strings.TrimSpace(name) + if name == "" || name == "." || name == ".." { + return "", false + } + if strings.ContainsAny(name, "\x00/\\") { + return "", false + } + for _, r := range name { + if unicode.IsControl(r) { + return "", false + } + } + return name, true +} + +func inspectHostClipPaths(paths []string) ([]clipBatchItem, string) { + if len(paths) == 0 { + return nil, textHash("") + } + seenHost := make(map[string]bool, len(paths)) + usedNames := make(map[string]bool, len(paths)) + items := make([]clipBatchItem, 0, min(len(paths), MaxClipboardFileCount)) + + h := sha256.New() + h.Write([]byte("files:")) + + for _, raw := range paths { + if len(items) >= MaxClipboardFileCount { + break + } + trimmed := strings.TrimSpace(raw) + if trimmed == "" || strings.HasPrefix(trimmed, `\\.\`) { + continue + } + abs, err := filepath.Abs(trimmed) + if err != nil { + continue + } + parentDir := filepath.Dir(abs) + baseName := filepath.Base(abs) + if parentDir == abs { + // Never expose an entire drive root through clipboard selection. + continue + } + if _, ok := sanitizeClipBaseName(baseName); !ok { + continue + } + dedupKey := abs + if seenHost[dedupKey] { + continue + } + parentRoot, err := os.OpenRoot(parentDir) + if err != nil { + continue + } + info, statErr := statDAVEntry(parentRoot, baseName) + _ = parentRoot.Close() + if statErr != nil { + continue + } + isDir := info.IsDir() + if !isDir && !isSharedRegularFile(info.Mode()) { + continue + } + var dRoot sharedRoot + if isDir { + dRoot = configureSharedRoot(abs) + if dRoot.err != nil { + continue + } + } + seenHost[dedupKey] = true + entryName := uniqueClipEntryName(baseName, usedNames) + item := clipBatchItem{ + name: entryName, + hostPath: abs, + parentDir: parentDir, + baseName: baseName, + dirRoot: dRoot, + isDir: isDir, + size: info.Size(), + modNano: info.ModTime().UnixNano(), + } + items = append(items, item) + kindTag := "f" + if isDir { + kindTag = "d" + } + _, _ = fmt.Fprintf(h, "%s|%s|%s|%d|%d\n", abs, entryName, kindTag, item.size, item.modNano) + } + if len(items) == 0 { + return nil, textHash("") + } + return items, hex.EncodeToString(h.Sum(nil)) +} + +func clipFilesPayloadHash(paths []string) string { + _, hash := inspectHostClipPaths(paths) + return hash +} + +func measureClipBatchBytes(items []clipBatchItem, limit int64) (int64, bool) { + if limit <= 0 { + limit = DefaultClipboardMaxFileBytes + } + var total int64 + count := 0 + for _, it := range items { + count++ + if count > MaxClipboardFileCount { + return total, true + } + if !it.isDir { + total += it.size + if total > limit { + return total, true + } + continue + } + root, err := openSharedRoot(it.dirRoot, false) + if err != nil { + return total, true + } + exceeded := false + _ = fs.WalkDir(root.FS(), ".", func(rel string, d fs.DirEntry, walkErr error) error { + if rel == "." { + return walkErr + } + if walkErr != nil { + return nil + } + if d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + if strings.Count(rel, "/")+1 > MaxSharedDepth { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + info, err := statDAVEntry(root, rel) + if err != nil { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + count++ + if count > MaxClipboardFileCount { + exceeded = true + return fs.SkipAll + } + if isSharedRegularFile(info.Mode()) { + total += info.Size() + if total > limit { + exceeded = true + return fs.SkipAll + } + } + return nil + }) + _ = root.Close() + if exceeded { + return total, true + } + } + return total, false +} + +func (s *Server) registerOrGetClipBatch(vmKey string, files []string, maxTarBytes int) (*clipHostBatch, bool) { + items, hash := inspectHostClipPaths(files) + if len(items) == 0 { + return nil, false + } + vmKey = normalizeVMRegistryKey(vmKey) + limit := int64(maxTarBytes) + if limit <= 0 { + limit = DefaultClipboardMaxFileBytes + } + + s.mu.RLock() + for _, existing := range s.clipHostBatches[vmKey] { + if existing.hash == hash && existing.scannedLimit == limit { + cp := *existing + s.mu.RUnlock() + return &cp, true + } + } + s.mu.RUnlock() + + totalBytes, exceeds := measureClipBatchBytes(items, limit) + id, err := newClipBatchID() + if err != nil { + return nil, false + } + order := make([]string, 0, len(items)) + byName := make(map[string]clipBatchItem, len(items)) + for _, it := range items { + order = append(order, it.name) + byName[it.name] = it + } + batch := &clipHostBatch{ + id: id, + hash: hash, + createdAt: time.Now(), + order: order, + items: byName, + totalBytes: totalBytes, + scannedLimit: limit, + exceedsTarLimit: exceeds, + } + + s.mu.Lock() + defer s.mu.Unlock() + if s.clipHostBatches == nil { + s.clipHostBatches = make(map[string][]*clipHostBatch) + } + list := s.clipHostBatches[vmKey] + for i, existing := range list { + if existing.hash == hash { + existing.totalBytes = totalBytes + existing.scannedLimit = limit + existing.exceedsTarLimit = exceeds + // Move reused batch to most-recent slot so it is evicted last. + list = append(append(list[:i], list[i+1:]...), existing) + s.clipHostBatches[vmKey] = list + cp := *existing + return &cp, true + } + } + list = append(list, batch) + if len(list) > MaxClipboardFileBatches { + list = append([]*clipHostBatch(nil), list[len(list)-MaxClipboardFileBatches:]...) + } + s.clipHostBatches[vmKey] = list + cp := *batch + return &cp, true +} + +func (s *Server) lookupClipHostBatch(vmKey, batchID string) *clipHostBatch { + vmKey = normalizeVMRegistryKey(vmKey) + s.mu.RLock() + defer s.mu.RUnlock() + if !s.clipboardActive { + return nil + } + policy := s.globalClipPolicy + if ov, ok := s.vmClipPolicies[vmKey]; ok { + policy = ov + } + if !policy.Enabled || !policy.SyncFiles || policy.Direction == ClipboardGuestToHost { + return nil + } + for _, b := range s.clipHostBatches[vmKey] { + if b.id == batchID { + cp := *b + return &cp + } + } + return nil +} + +func (s *Server) listClipHostBatches(vmKey string) []*clipHostBatch { + vmKey = normalizeVMRegistryKey(vmKey) + s.mu.RLock() + defer s.mu.RUnlock() + if !s.clipboardActive { + return nil + } + policy := s.globalClipPolicy + if ov, ok := s.vmClipPolicies[vmKey]; ok { + policy = ov + } + if !policy.Enabled || !policy.SyncFiles || policy.Direction == ClipboardGuestToHost { + return nil + } + src := s.clipHostBatches[vmKey] + if len(src) == 0 { + return nil + } + out := make([]*clipHostBatch, len(src)) + for i, b := range src { + cp := *b + out[i] = &cp + } + return out +} + +func acceptQueryHas(rawQuery, want string) bool { + for _, part := range strings.Split(rawQuery, ",") { + if strings.EqualFold(strings.TrimSpace(part), want) { + return true + } + } + return false +} + +// --- Guest-to-Host streaming tar extraction & CF_HDROP write --- + +var windowsReservedNames = map[string]bool{ + "con": true, "prn": true, "aux": true, "nul": true, + "com1": true, "com2": true, "com3": true, "com4": true, "com5": true, + "com6": true, "com7": true, "com8": true, "com9": true, + "lpt1": true, "lpt2": true, "lpt3": true, "lpt4": true, "lpt5": true, + "lpt6": true, "lpt7": true, "lpt8": true, "lpt9": true, +} + +func sanitizeArchiveSegment(seg string) (string, error) { + if seg == "" || seg == "." || seg == ".." { + return "", errClipArchiveInvalid + } + for _, r := range seg { + if unicode.IsControl(r) { + return "", errClipArchiveInvalid + } + } + checkReserved := func(s string) bool { + stem := s + if dot := strings.IndexByte(stem, '.'); dot >= 0 { + stem = stem[:dot] + } + return windowsReservedNames[strings.ToLower(strings.TrimSpace(stem))] + } + if checkReserved(seg) { + return "", errClipArchiveInvalid + } + var b strings.Builder + b.Grow(len(seg)) + for _, r := range seg { + switch r { + case ':', '*', '?', '"', '<', '>', '|': + b.WriteByte('_') + default: + b.WriteRune(r) + } + } + cleaned := strings.TrimRight(b.String(), ". ") + if cleaned == "" || cleaned == "." || cleaned == ".." { + cleaned = "_" + } + if checkReserved(cleaned) { + cleaned = "_" + cleaned + } + return cleaned, nil +} + +func cleanClipArchivePath(raw string) (rel string, top string, skip bool, err error) { + if strings.ContainsAny(raw, "\x00\\") { + return "", "", false, errClipArchiveInvalid + } + trimmed := strings.TrimSuffix(raw, "/") + for strings.HasPrefix(trimmed, "./") { + trimmed = strings.TrimPrefix(trimmed, "./") + } + if trimmed == "" || trimmed == "." { + return "", "", true, nil + } + if strings.HasPrefix(raw, "/") || strings.HasPrefix(trimmed, "/") { + return "", "", false, errClipArchiveInvalid + } + parts := strings.Split(trimmed, "/") + if len(parts) == 0 || len(parts) > MaxSharedDepth { + return "", "", false, errClipArchiveInvalid + } + // Skip macOS Finder metadata files before segment sanitization so "._foo" stays skipped. + base := parts[len(parts)-1] + if base == ".DS_Store" || strings.HasPrefix(base, "._") { + return "", "", true, nil + } + sanitized := make([]string, len(parts)) + for i, seg := range parts { + cleanSeg, segErr := sanitizeArchiveSegment(seg) + if segErr != nil { + return "", "", false, segErr + } + sanitized[i] = cleanSeg + } + clean := path.Clean(strings.Join(sanitized, "/")) + if clean == "." || clean == ".." || strings.HasPrefix(clean, "../") || !filepath.IsLocal(filepath.FromSlash(clean)) { + return "", "", false, errClipArchiveInvalid + } + return clean, sanitized[0], false, nil +} + +func mkdirAllInRoot(root *os.Root, relDir string) error { + if relDir == "" || relDir == "." { + return nil + } + parts := strings.Split(relDir, "/") + cur := "" + for _, seg := range parts { + if cur == "" { + cur = seg + } else { + cur = cur + "/" + seg + } + err := root.Mkdir(cur, 0o755) + if err != nil && !errors.Is(err, fs.ErrExist) { + return err + } + info, statErr := statDAVEntry(root, cur) + if statErr != nil { + return statErr + } + if !info.IsDir() { + return errClipArchiveInvalid + } + } + return nil +} + +func (s *Server) extractClipboardTar(vmKey string, body io.Reader, maxBytes int) (batchDir string, topPaths []string, err error) { + vmKey = normalizeVMRegistryKey(vmKey) + s.pruneExpiredClipStaging(time.Now()) + + s.mu.RLock() + stagingRoot := s.clipStagingDir + s.mu.RUnlock() + if stagingRoot == "" { + return "", nil, errClipStagingUnset + } + + batchID, err := newClipBatchID() + if err != nil { + return "", nil, err + } + vmDir := filepath.Join(stagingRoot, vmStagingSubdir(vmKey)) + batchDir = filepath.Join(vmDir, batchID) + if err := os.MkdirAll(batchDir, 0o700); err != nil { + return "", nil, err + } + cleanupOnErr := true + defer func() { + if cleanupOnErr { + _ = os.RemoveAll(batchDir) + } + }() + + root, err := os.OpenRoot(batchDir) + if err != nil { + return "", nil, err + } + defer root.Close() + + limit := int64(maxBytes) + if limit <= 0 { + limit = DefaultClipboardMaxFileBytes + } + streamCap := limit + tarStreamSlackBytes + lr := &io.LimitedReader{R: body, N: streamCap + 1} + tr := tar.NewReader(lr) + + var ( + totalBytes int64 + entryCount int + topOrder []string + topSeen = make(map[string]bool) + dirTimes []struct { + rel string + mod time.Time + } + ) + + for { + hdr, nextErr := tr.Next() + if errors.Is(nextErr, io.EOF) { + break + } + if nextErr != nil { + if lr.N <= 0 { + return "", nil, errClipArchiveTooLarge + } + return "", nil, fmt.Errorf("%w: %v", errClipArchiveInvalid, nextErr) + } + if lr.N <= 0 { + return "", nil, errClipArchiveTooLarge + } + + switch hdr.Typeflag { + case tar.TypeXGlobalHeader: + continue + case tar.TypeDir, tar.TypeReg, tar.TypeRegA: + default: + // Reject symlinks, hardlinks, FIFOs, and device nodes unconditionally. + return "", nil, fmt.Errorf("%w: unsupported tar entry type %d", errClipArchiveInvalid, hdr.Typeflag) + } + + cleanRel, topName, skip, cleanErr := cleanClipArchivePath(hdr.Name) + if cleanErr != nil { + return "", nil, cleanErr + } + if skip { + continue + } + + entryCount++ + if entryCount > MaxClipboardFileCount { + return "", nil, errClipArchiveTooLarge + } + if hdr.Size < 0 || totalBytes+hdr.Size > limit { + return "", nil, errClipArchiveTooLarge + } + + if hdr.Typeflag == tar.TypeDir { + if !topSeen[topName] { + topSeen[topName] = true + topOrder = append(topOrder, topName) + } + if err := mkdirAllInRoot(root, cleanRel); err != nil { + return "", nil, err + } + if !hdr.ModTime.IsZero() { + dirTimes = append(dirTimes, struct { + rel string + mod time.Time + }{rel: cleanRel, mod: hdr.ModTime}) + } + continue + } + + parentRel := path.Dir(cleanRel) + if parentRel != "." { + if err := mkdirAllInRoot(root, parentRel); err != nil { + return "", nil, err + } + } + targetRel := cleanRel + outFile, err := root.OpenFile(targetRel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, fs.ErrExist) { + baseName := path.Base(cleanRel) + ext := path.Ext(baseName) + stem := strings.TrimSuffix(baseName, ext) + if stem == "" { + stem, ext = baseName, "" + } + for dup := 2; dup <= MaxClipboardFileCount+2; dup++ { + candBase := fmt.Sprintf("%s (%d)%s", stem, dup, ext) + if parentRel == "." { + targetRel = candBase + } else { + targetRel = parentRel + "/" + candBase + } + outFile, err = root.OpenFile(targetRel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if !errors.Is(err, fs.ErrExist) { + if parentRel == "." { + topName = candBase + } + break + } + } + } + if err != nil { + return "", nil, fmt.Errorf("%w: %v", errClipArchiveInvalid, err) + } + if !topSeen[topName] { + topSeen[topName] = true + topOrder = append(topOrder, topName) + } + written, copyErr := io.Copy(outFile, io.LimitReader(tr, hdr.Size+1)) + closeErr := outFile.Close() + if copyErr != nil || closeErr != nil { + return "", nil, errors.Join(copyErr, closeErr) + } + if written != hdr.Size { + return "", nil, errClipArchiveInvalid + } + totalBytes += written + if totalBytes > limit { + return "", nil, errClipArchiveTooLarge + } + if !hdr.ModTime.IsZero() { + _ = os.Chtimes(filepath.Join(batchDir, filepath.FromSlash(targetRel)), hdr.ModTime, hdr.ModTime) + } + } + + if len(topOrder) == 0 { + return "", nil, fmt.Errorf("%w: empty file archive", errClipArchiveInvalid) + } + + // Restore directory mtimes bottom-up after writing child files. + for i := len(dirTimes) - 1; i >= 0; i-- { + _ = os.Chtimes(filepath.Join(batchDir, filepath.FromSlash(dirTimes[i].rel)), dirTimes[i].mod, dirTimes[i].mod) + } + + topPaths = make([]string, 0, len(topOrder)) + for _, name := range topOrder { + topPaths = append(topPaths, filepath.Join(batchDir, name)) + } + cleanupOnErr = false + return batchDir, topPaths, nil +} + +func (s *Server) commitGuestClipBatch(vmKey, batchDir string) { + vmKey = normalizeVMRegistryKey(vmKey) + var evicted []string + s.mu.Lock() + if s.clipGuestBatches == nil { + s.clipGuestBatches = make(map[string][]clipGuestBatch) + } + list := append(s.clipGuestBatches[vmKey], clipGuestBatch{ + id: filepath.Base(batchDir), + dir: batchDir, + createdAt: time.Now(), + }) + if len(list) > MaxClipboardFileBatches { + cutoff := len(list) - MaxClipboardFileBatches + for _, old := range list[:cutoff] { + if old.dir != "" { + evicted = append(evicted, old.dir) + } + } + list = append([]clipGuestBatch(nil), list[cutoff:]...) + } + s.clipGuestBatches[vmKey] = list + s.mu.Unlock() + + for _, dir := range evicted { + _ = os.RemoveAll(dir) + } +} + +func (s *Server) postClipboardFiles(w http.ResponseWriter, r *http.Request, vmKey string, policy ClipboardPolicy) { + if policy.Direction == ClipboardHostToGuest || !policy.SyncFiles { + w.WriteHeader(http.StatusNoContent) + return + } + + var baseSeq *uint32 + if raw := r.Header.Get("X-Clip-Base-Seq"); policy.Direction != ClipboardGuestToHost && 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 + } + } + + batchDir, topPaths, err := s.extractClipboardTar(vmKey, r.Body, policy.MaxFileBytes) + if err != nil { + switch { + case errors.Is(err, errClipArchiveTooLarge): + http.Error(w, "clipboard files too large", http.StatusRequestEntityTooLarge) + case errors.Is(err, errClipArchiveInvalid): + http.Error(w, err.Error(), http.StatusBadRequest) + case errors.Is(err, errClipStagingUnset): + http.Error(w, err.Error(), http.StatusServiceUnavailable) + default: + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + payload := ClipPayload{Kind: ClipFiles, Files: topPaths} + seq, err := s.applyClipboardPost(payload, baseSeq) + if errors.Is(err, errClipboardConflict) { + _ = os.RemoveAll(batchDir) + setClipboardSeq(w, seq) + http.Error(w, errClipboardConflict.Error(), http.StatusConflict) + return + } + if err != nil { + _ = os.RemoveAll(batchDir) + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + s.commitGuestClipBatch(vmKey, batchDir) + s.touchLastSeen(vmKey) + h := payloadHash(payload) + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Kind", string(ClipFiles)) + w.Header().Set("X-Clip-Hash", h) + w.WriteHeader(http.StatusOK) +} + +func clipPayloadEqual(a, b ClipPayload) bool { + if a.Kind != b.Kind { + return false + } + if a.Kind == ClipFiles { + return slices.Equal(a.Files, b.Files) + } + return string(a.Data) == string(b.Data) +} diff --git a/internal/guesttools/clipboard_files_test.go b/internal/guesttools/clipboard_files_test.go new file mode 100644 index 0000000..1917982 --- /dev/null +++ b/internal/guesttools/clipboard_files_test.go @@ -0,0 +1,401 @@ +package guesttools + +import ( + "archive/tar" + "bytes" + "context" + "encoding/binary" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestHDropEncodeDecodeRoundTrip(t *testing.T) { + want := []string{ + filepath.Clean(`C:\Users\Alice\Documents\报告 2026.pdf`), + filepath.Clean(`D:\Media\Project Folder`), + } + raw, err := encodeHDropBytes(want) + if err != nil { + t.Fatalf("encodeHDropBytes: %v", err) + } + got, err := parseHDropBytes(raw) + if err != nil { + t.Fatalf("parseHDropBytes: %v", err) + } + if !slices.Equal(got, want) { + t.Fatalf("got %v, want %v", got, want) + } + + // ANSI (fWide=0) compatibility fallback. + ansi := make([]byte, dropFilesHeaderSize) + binary.LittleEndian.PutUint32(ansi[0:4], dropFilesHeaderSize) + binary.LittleEndian.PutUint32(ansi[16:20], 0) + ansi = append(ansi, []byte("C:\\temp\\one.txt\x00D:\\two.bin\x00\x00")...) + ansiPaths, err := parseHDropBytes(ansi) + if err != nil { + t.Fatalf("parseHDropBytes ANSI: %v", err) + } + wantANSI := []string{filepath.Clean(`C:\temp\one.txt`), filepath.Clean(`D:\two.bin`)} + if !slices.Equal(ansiPaths, wantANSI) { + t.Fatalf("ANSI got %v, want %v", ansiPaths, wantANSI) + } + + if _, err := encodeHDropBytes(nil); err == nil { + t.Fatal("expected error on empty path list") + } + if _, err := encodeHDropBytes([]string{"bad\x00path"}); err == nil { + t.Fatal("expected error on NUL byte in path") + } + if _, err := parseHDropBytes([]byte("short")); err == nil { + t.Fatal("expected error on short buffer") + } +} + +type tarTestEntry struct { + name string + typeflag byte + body string + linkname string +} + +func buildTestTar(t *testing.T, entries []tarTestEntry) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, e := range entries { + tf := e.typeflag + if tf == 0 { + tf = tar.TypeReg + } + hdr := &tar.Header{ + Name: e.name, + Typeflag: tf, + Mode: 0o644, + Linkname: e.linkname, + } + if tf == tar.TypeDir { + hdr.Mode = 0o755 + } else if tf == tar.TypeXGlobalHeader { + hdr.Mode = 0 + hdr.PAXRecords = map[string]string{"comment": "macos-pax"} + } else if tf == tar.TypeReg { + hdr.Size = int64(len(e.body)) + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if tf == tar.TypeReg && len(e.body) > 0 { + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestClipboardHostToGuestVirtualWebDAVAndIsolation(t *testing.T) { + tmp := t.TempDir() + hostDir := filepath.Join(tmp, "host-src") + subDir := filepath.Join(hostDir, "bundle") + if err := os.MkdirAll(subDir, 0o755); err != nil { + t.Fatal(err) + } + selectedFile := filepath.Join(hostDir, "video.mp4") + siblingSecret := filepath.Join(hostDir, "secret-sibling.txt") + nestedFile := filepath.Join(subDir, "readme.md") + if err := os.WriteFile(selectedFile, []byte("large-video-stream"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(siblingSecret, []byte("DO-NOT-EXPOSE"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(nestedFile, []byte("# Nested Doc"), 0o644); err != nil { + t.Fatal(err) + } + + clip := &memClipboard{} + if err := clip.WriteFiles([]string{selectedFile, subDir}); err != nil { + t.Fatal(err) + } + + srv := NewServer(clip) + srv.SetClipStagingDir(filepath.Join(tmp, "staging")) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + defer func() { _ = srv.Close(context.Background()) }() + + srv.RegisterVM(VMConfig{VMName: "mac1", Token: "tok-mac1-0000000000000000000000000000"}) + srv.RegisterVM(VMConfig{VMName: "mac2", Token: "tok-mac2-0000000000000000000000000000"}) + baseURL := "http://127.0.0.1:" + strconvItoa(port) + + doAuth := func(token, method, path string) *http.Response { + req, err := http.NewRequest(method, baseURL+path, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + return resp + } + + // Legacy guest without accept=files must NOT receive JSON manifest. + legacyResp := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/v1/clipboard?accept=image") + _ = legacyResp.Body.Close() + if legacyResp.StatusCode != http.StatusNotModified { + t.Fatalf("legacy client without accept=files got %d, want 304", legacyResp.StatusCode) + } + + // Upgraded guest with accept=image,files receives lightweight JSON batch manifest. + resp := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/v1/clipboard?accept=image,files") + if resp.StatusCode != http.StatusOK || resp.Header.Get("X-Clip-Kind") != string(ClipFiles) { + t.Fatalf("GET files clipboard = %d kind=%q", resp.StatusCode, resp.Header.Get("X-Clip-Kind")) + } + clipHash := resp.Header.Get("X-Clip-Hash") + var mf clipBatchManifest + if err := json.NewDecoder(resp.Body).Decode(&mf); err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if !strings.HasPrefix(mf.Batch, "b_") || !slices.Equal(mf.Items, []string{"video.mp4", "bundle"}) { + t.Fatalf("unexpected manifest: %+v", mf) + } + + // Subsequent poll with matching since=hash returns 304 without creating new batches. + unchanged := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/v1/clipboard?accept=image,files&since="+clipHash) + _ = unchanged.Body.Close() + if unchanged.StatusCode != http.StatusNotModified { + t.Fatalf("unchanged poll got %d, want 304", unchanged.StatusCode) + } + + // Read explicitly selected file and nested file over /dav-clip/mac1//. + rFile := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+mf.Batch+"/video.mp4") + fileBody, _ := io.ReadAll(rFile.Body) + _ = rFile.Body.Close() + if rFile.StatusCode != http.StatusOK || string(fileBody) != "large-video-stream" { + t.Fatalf("read selected file = %d %q", rFile.StatusCode, fileBody) + } + + rNested := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+mf.Batch+"/bundle/readme.md") + nestedBody, _ := io.ReadAll(rNested.Body) + _ = rNested.Body.Close() + if rNested.StatusCode != http.StatusOK || string(nestedBody) != "# Nested Doc" { + t.Fatalf("read nested file = %d %q", rNested.StatusCode, nestedBody) + } + + // Unselected sibling in the same parent folder must NEVER be reachable. + rSibling := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+mf.Batch+"/secret-sibling.txt") + _ = rSibling.Body.Close() + if rSibling.StatusCode != http.StatusNotFound { + t.Fatalf("sibling file status = %d, want 404", rSibling.StatusCode) + } + + // Cross-VM isolation: mac2 cannot read mac1's route or batch. + rWrongVM := doAuth("tok-mac2-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+mf.Batch+"/video.mp4") + _ = rWrongVM.Body.Close() + if rWrongVM.StatusCode != http.StatusForbidden { + t.Fatalf("cross-VM route status = %d, want 403", rWrongVM.StatusCode) + } + rOtherBatch := doAuth("tok-mac2-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac2/"+mf.Batch+"/video.mp4") + _ = rOtherBatch.Body.Close() + if rOtherBatch.StatusCode != http.StatusNotFound { + t.Fatalf("cross-VM batch status = %d, want 404", rOtherBatch.StatusCode) + } + + // All WebDAV write methods must be rejected. + for _, method := range []string{http.MethodPut, http.MethodDelete, "MKCOL", "MOVE", "COPY", "LOCK"} { + wResp := doAuth("tok-mac1-0000000000000000000000000000", method, "/dav-clip/mac1/"+mf.Batch+"/video.mp4") + _ = wResp.Body.Close() + if wResp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("write method %s status = %d, want 405", method, wResp.StatusCode) + } + } + + // Rolling retention keeps the latest 3 batches and evicts the oldest (4th). + batches := []string{mf.Batch} + for i := 0; i < 3; i++ { + f := filepath.Join(hostDir, "extra-"+strconvItoa(i)+".txt") + if err := os.WriteFile(f, []byte("extra"), 0o644); err != nil { + t.Fatal(err) + } + _ = clip.WriteFiles([]string{f}) + bResp := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/v1/clipboard?accept=files") + var bMf clipBatchManifest + _ = json.NewDecoder(bResp.Body).Decode(&bMf) + _ = bResp.Body.Close() + batches = append(batches, bMf.Batch) + } + evicted := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+batches[0]+"/video.mp4") + _ = evicted.Body.Close() + if evicted.StatusCode != http.StatusNotFound { + t.Fatalf("oldest batch after 4 copies status = %d, want 404", evicted.StatusCode) + } + kept := doAuth("tok-mac1-0000000000000000000000000000", http.MethodGet, "/dav-clip/mac1/"+batches[1]+"/extra-0.txt") + _ = kept.Body.Close() + if kept.StatusCode != http.StatusOK { + t.Fatalf("3rd most recent batch status = %d, want 200", kept.StatusCode) + } +} + +func TestClipboardHostToGuestTarFallbackAndLimit(t *testing.T) { + tmp := t.TempDir() + smallFile := filepath.Join(tmp, "note.txt") + largeFile := filepath.Join(tmp, "big.bin") + if err := os.WriteFile(smallFile, []byte("fallback-ok"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(largeFile, bytes.Repeat([]byte("X"), 4096), 0o644); err != nil { + t.Fatal(err) + } + + clip := &memClipboard{} + srv := NewServer(clip) + srv.RegisterVM(VMConfig{VMName: "mac", Token: "tok-fallback-0000000000000000000000"}) + pol := DefaultClipboardPolicy() + pol.MaxFileBytes = 1024 + srv.SetGlobalClipboardPolicy(pol) + + // Small file fits within MaxFileBytes -> tar fallback succeeds. + _ = clip.WriteFiles([]string{smallFile}) + mfRec := clipboardRequest(t, srv, http.MethodGet, "?accept=files", "", "", nil) + // Authenticate with the registered token via custom helper. + doGet := func(query string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/v1/clipboard"+query, nil) + req.Header.Set("Authorization", "Bearer tok-fallback-0000000000000000000000") + rec := httptest.NewRecorder() + srv.handleClipboard(rec, req) + return rec + } + _ = mfRec + resSmall := doGet("?accept=files") + var mfSmall clipBatchManifest + if err := json.Unmarshal(resSmall.Body.Bytes(), &mfSmall); err != nil { + t.Fatal(err) + } + if mfSmall.ExceedsTarLimit { + t.Fatalf("expected small batch within tar limit: %+v", mfSmall) + } + tarSmall := doGet("?batch=" + mfSmall.Batch + "&format=tar") + if tarSmall.Code != http.StatusOK { + t.Fatalf("small tar fallback status = %d", tarSmall.Code) + } + tr := tar.NewReader(bytes.NewReader(tarSmall.Body.Bytes())) + hdr, err := tr.Next() + if err != nil || hdr.Name != "note.txt" { + t.Fatalf("tar entry = %+v, err=%v", hdr, err) + } + + // Large file exceeds MaxFileBytes -> WebDAV manifest still works, tar fallback returns 413. + _ = clip.WriteFiles([]string{largeFile}) + resLarge := doGet("?accept=files") + var mfLarge clipBatchManifest + if err := json.Unmarshal(resLarge.Body.Bytes(), &mfLarge); err != nil { + t.Fatal(err) + } + if !mfLarge.ExceedsTarLimit { + t.Fatalf("expected ExceedsTarLimit=true for 4096B > 1024B: %+v", mfLarge) + } + tarLarge := doGet("?batch=" + mfLarge.Batch + "&format=tar") + if tarLarge.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("large tar fallback status = %d, want 413", tarLarge.Code) + } +} + +func TestClipboardGuestToHostTarUploadSecurityAndCleanup(t *testing.T) { + tmp := t.TempDir() + staging := filepath.Join(tmp, "tmp", "clip-files") + clip := &memClipboard{seq: 5} + srv := newClipboardTestServer(clip) + srv.SetClipStagingDir(staging) + + // Valid multi-entry archive unpacks into staging, writes ClipFiles, and suppresses echo. + validTar := buildTestTar(t, []tarTestEntry{ + {name: "pax_global_header", typeflag: tar.TypeXGlobalHeader}, + {name: "./hello.txt", body: "from-macos"}, + {name: "folder/", typeflag: tar.TypeDir}, + {name: "folder/.DS_Store", body: "ignored"}, + {name: "folder/._appledouble", body: "ignored"}, + {name: "folder/sub.txt", body: "nested"}, + {name: "note 14:30.md", body: "colon-ok"}, + {name: "note 14?30.md", body: "dedup-ok"}, + }) + post := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "5", validTar) + if post.Code != http.StatusOK || post.Header().Get("X-Clip-Kind") != string(ClipFiles) { + t.Fatalf("valid tar POST = %d %v %q", post.Code, post.Header(), post.Body.String()) + } + postHash := post.Header().Get("X-Clip-Hash") + if postHash == "" || post.Header().Get("X-Clip-Seq") != "6" { + t.Fatalf("unexpected POST headers: %v", post.Header()) + } + gotClip, _ := clip.Read() + if gotClip.Kind != ClipFiles || len(gotClip.Files) != 4 { + t.Fatalf("host clipboard after tar POST = %+v", gotClip) + } + if data, err := os.ReadFile(gotClip.Files[0]); err != nil || string(data) != "from-macos" { + t.Fatalf("unpacked hello.txt = %q, err=%v", data, err) + } + if _, err := os.Stat(filepath.Join(gotClip.Files[1], ".DS_Store")); !os.IsNotExist(err) { + t.Fatal(".DS_Store should be stripped on host unpack") + } + if filepath.Base(gotClip.Files[2]) != "note 14_30.md" || filepath.Base(gotClip.Files[3]) != "note 14_30 (2).md" { + t.Fatalf("unexpected sanitized/deduped names: %q, %q", gotClip.Files[2], gotClip.Files[3]) + } + + // Echo prevention: polling with X-Clip-Hash returned by POST yields 304 Not Modified. + echoPoll := clipboardRequest(t, srv, http.MethodGet, "?accept=image,files&since="+postHash, "", "", nil) + if echoPoll.Code != http.StatusNotModified { + t.Fatalf("echo poll after guest upload = %d, want 304", echoPoll.Code) + } + + // Reject malicious archives (traversal, absolute path, symlink, hardlink, reserved names). + for _, bad := range []struct { + name string + entry tarTestEntry + }{ + {"parent traversal", tarTestEntry{name: "../escape.txt", body: "bad"}}, + {"nested traversal", tarTestEntry{name: "dir/../../escape.txt", body: "bad"}}, + {"absolute path", tarTestEntry{name: "/etc/passwd", body: "bad"}}, + {"backslash path", tarTestEntry{name: `dir\escape.txt`, body: "bad"}}, + {"windows reserved device", tarTestEntry{name: "CON.txt", body: "bad"}}, + {"symlink entry", tarTestEntry{name: "link", typeflag: tar.TypeSymlink, linkname: "/etc/passwd"}}, + {"hardlink entry", tarTestEntry{name: "hlink", typeflag: tar.TypeLink, linkname: "hello.txt"}}, + } { + t.Run(bad.name, func(t *testing.T) { + badTar := buildTestTar(t, []tarTestEntry{bad.entry}) + res := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "", badTar) + if res.Code != http.StatusBadRequest { + t.Fatalf("%s: got %d (%s), want 400", bad.name, res.Code, res.Body.String()) + } + }) + } + + // Reject oversized payload with 413. + pol := DefaultClipboardPolicy() + pol.MaxFileBytes = 32 + srv.SetGlobalClipboardPolicy(pol) + bigTar := buildTestTar(t, []tarTestEntry{{name: "big.bin", body: strings.Repeat("A", 128)}}) + over := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "", bigTar) + if over.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("oversized tar = %d, want 413", over.Code) + } + + // Disabling clipboard plugin wipes staging directory completely (zero residue). + srv.SetClipboardActive(false) + if _, err := os.Stat(staging); !os.IsNotExist(err) { + t.Fatalf("expected staging dir %s removed on disable, stat err=%v", staging, err) + } +} diff --git a/internal/guesttools/clipboard_other.go b/internal/guesttools/clipboard_other.go index 2c177f4..aa24a72 100644 --- a/internal/guesttools/clipboard_other.go +++ b/internal/guesttools/clipboard_other.go @@ -5,10 +5,11 @@ package guesttools import "sync" type OSClipboard struct { - mu sync.Mutex - kind ClipKind - data []byte - seq uint32 + mu sync.Mutex + kind ClipKind + data []byte + files []string + seq uint32 } func (c *OSClipboard) SequenceNumber() uint32 { @@ -32,19 +33,27 @@ func (c *OSClipboard) WriteText(text string) error { } func (c *OSClipboard) Read() (ClipPayload, error) { - payload, _, err := c.readClipboard(true) + payload, _, err := c.readClipboardOpts(true, true) return payload, err } func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) { + return c.readClipboardOpts(wantImage, false) +} + +func (c *OSClipboard) readClipboardOpts(wantImage, wantFiles bool) (ClipPayload, uint32, error) { c.mu.Lock() defer c.mu.Unlock() + if !wantFiles && c.kind == ClipFiles { + return ClipPayload{Kind: ClipEmpty}, c.seq, nil + } if !wantImage && c.kind == ClipPNG { return ClipPayload{Kind: ClipEmpty}, c.seq, nil } cp := make([]byte, len(c.data)) copy(cp, c.data) - return ClipPayload{Kind: c.kind, Data: cp}, c.seq, nil + files := append([]string(nil), c.files...) + return ClipPayload{Kind: c.kind, Data: cp, Files: files}, c.seq, nil } func (c *OSClipboard) WritePNG(pngBytes []byte) error { @@ -52,6 +61,11 @@ func (c *OSClipboard) WritePNG(pngBytes []byte) error { return err } +func (c *OSClipboard) WriteFiles(paths []string) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipFiles, Files: paths}, nil) + return err +} + func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) { c.mu.Lock() defer c.mu.Unlock() @@ -60,6 +74,7 @@ func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint } c.kind = payload.Kind c.data = append([]byte(nil), payload.Data...) + c.files = append([]string(nil), payload.Files...) c.seq++ return c.seq, nil } diff --git a/internal/guesttools/clipboard_webdav.go b/internal/guesttools/clipboard_webdav.go new file mode 100644 index 0000000..ab78f9b --- /dev/null +++ b/internal/guesttools/clipboard_webdav.go @@ -0,0 +1,615 @@ +package guesttools + +import ( + "archive/tar" + "context" + "errors" + "io" + "io/fs" + "net/http" + "os" + "strings" + "sync/atomic" + "time" + + "golang.org/x/net/webdav" +) + +type clipDAVEntry struct { + prefix string + token string + handler *webdav.Handler +} + +// --- Read-only virtual WebDAV at /dav-clip// --- + +func (s *Server) handleClipWebDAV(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + w.Header().Set("WWW-Authenticate", `Basic realm="ReimsClipboard"`) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if !s.EffectiveClipboardPolicy(vm.key).Enabled { + writeFeatureDisabled(w, "clipboard") + return + } + trimmed := strings.TrimPrefix(r.URL.Path, "/dav-clip/") + vmPart, _, _ := strings.Cut(trimmed, "/") + if vmPart != vm.name { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + if !allowPROPFINDDepth(w, r) { + return + } + if !allowReadOnlyDAV(w, r) { + return + } + handler, err := s.getOrCreateClipDAVHandler(vm) + if err != nil { + http.Error(w, "clipboard share unavailable", http.StatusNotFound) + return + } + handler.ServeHTTP(w, r) +} + +func (s *Server) getOrCreateClipDAVHandler(vm *registeredVM) (*webdav.Handler, error) { + prefix := "/dav-clip/" + vm.name + s.mu.Lock() + defer s.mu.Unlock() + live := s.vms[vm.key] + if live == nil || live.token != vm.token || !s.clipboardActive { + return nil, os.ErrPermission + } + if s.clipDAVHandlers == nil { + s.clipDAVHandlers = make(map[string]*clipDAVEntry) + } + if entry, ok := s.clipDAVHandlers[vm.key]; ok && entry.prefix == prefix && entry.token == vm.token { + return entry.handler, nil + } + fsys := &clipWebDAVFS{ + srv: s, + vmKey: vm.key, + vmToken: vm.token, + } + handler := &webdav.Handler{ + Prefix: prefix, + FileSystem: fsys, + LockSystem: webdav.NewMemLS(), + } + s.clipDAVHandlers[vm.key] = &clipDAVEntry{ + prefix: prefix, + token: vm.token, + handler: handler, + } + return handler, nil +} + +type clipWebDAVFS struct { + srv *Server + vmKey string + vmToken string +} + +func (f *clipWebDAVFS) verifyAccess() error { + f.srv.mu.RLock() + defer f.srv.mu.RUnlock() + if !f.srv.clipboardActive { + return os.ErrPermission + } + live := f.srv.vms[f.vmKey] + if live == nil || live.token != f.vmToken { + return os.ErrPermission + } + return nil +} + +func (f *clipWebDAVFS) Mkdir(_ context.Context, _ string, _ os.FileMode) error { + return os.ErrPermission +} + +func (f *clipWebDAVFS) RemoveAll(_ context.Context, _ string) error { + return os.ErrPermission +} + +func (f *clipWebDAVFS) Rename(_ context.Context, _, _ string) error { + return os.ErrPermission +} + +func statClipBatchItem(item clipBatchItem) (fs.FileInfo, error) { + if !item.isDir { + parentRoot, err := os.OpenRoot(item.parentDir) + if err != nil { + return nil, err + } + defer parentRoot.Close() + info, err := statDAVEntry(parentRoot, item.baseName) + if err != nil { + return nil, err + } + if info.IsDir() || !isSharedRegularFile(info.Mode()) { + return nil, os.ErrPermission + } + return renamedFileInfo{FileInfo: info, name: item.name}, nil + } + dirRoot, err := openSharedRoot(item.dirRoot, false) + if err != nil { + return nil, err + } + defer dirRoot.Close() + info, err := statDAVEntry(dirRoot, ".") + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, os.ErrPermission + } + return renamedFileInfo{FileInfo: info, name: item.name}, nil +} + +func (f *clipWebDAVFS) Stat(_ context.Context, name string) (os.FileInfo, error) { + if err := f.verifyAccess(); err != nil { + return nil, err + } + rel, err := davRelativePath(name) + if err != nil { + return nil, err + } + if rel == "." { + return virtualDirInfo{name: "/", modTime: time.Now()}, nil + } + batchID, rest, hasRest := strings.Cut(rel, "/") + batch := f.srv.lookupClipHostBatch(f.vmKey, batchID) + if batch == nil { + return nil, os.ErrNotExist + } + if !hasRest { + return virtualDirInfo{name: batchID, modTime: batch.createdAt}, nil + } + entryName, subPath, hasSub := strings.Cut(rest, "/") + item, ok := batch.items[entryName] + if !ok { + return nil, os.ErrNotExist + } + if !item.isDir { + if hasSub { + return nil, os.ErrNotExist + } + return statClipBatchItem(item) + } + if !hasSub { + return statClipBatchItem(item) + } + dirRoot, err := openSharedRoot(item.dirRoot, false) + if err != nil { + return nil, err + } + defer dirRoot.Close() + if err := checkSharedFileParents(dirRoot, subPath); err != nil { + return nil, os.ErrPermission + } + return statDAVEntry(dirRoot, subPath) +} + +func (f *clipWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.FileMode) (webdav.File, error) { + const writeFlags = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC + if flag&writeFlags != 0 { + return nil, os.ErrPermission + } + if err := f.verifyAccess(); err != nil { + return nil, err + } + rel, err := davRelativePath(name) + if err != nil { + return nil, err + } + if rel == "." { + batches := f.srv.listClipHostBatches(f.vmKey) + entries := make([]fs.FileInfo, 0, len(batches)) + var latest time.Time + for _, b := range batches { + entries = append(entries, virtualDirInfo{name: b.id, modTime: b.createdAt}) + if b.createdAt.After(latest) { + latest = b.createdAt + } + } + if latest.IsZero() { + latest = time.Now() + } + return &virtualDirFile{ + info: virtualDirInfo{name: "/", modTime: latest}, + entries: entries, + }, nil + } + + batchID, rest, hasRest := strings.Cut(rel, "/") + batch := f.srv.lookupClipHostBatch(f.vmKey, batchID) + if batch == nil { + return nil, os.ErrNotExist + } + if !hasRest { + entries := make([]fs.FileInfo, 0, len(batch.order)) + for _, entryName := range batch.order { + it := batch.items[entryName] + if info, err := statClipBatchItem(it); err == nil { + entries = append(entries, info) + } + } + return &virtualDirFile{ + info: virtualDirInfo{name: batchID, modTime: batch.createdAt}, + entries: entries, + }, nil + } + + entryName, subPath, hasSub := strings.Cut(rest, "/") + item, ok := batch.items[entryName] + if !ok { + return nil, os.ErrNotExist + } + if !item.isDir { + if hasSub { + return nil, os.ErrNotExist + } + parentRoot, err := os.OpenRoot(item.parentDir) + if err != nil { + return nil, err + } + defer parentRoot.Close() + info, err := statDAVEntry(parentRoot, item.baseName) + if err != nil { + return nil, err + } + if info.IsDir() || !isSharedRegularFile(info.Mode()) { + return nil, os.ErrPermission + } + file, err := parentRoot.OpenFile(item.baseName, os.O_RDONLY, 0) + if err != nil { + return nil, err + } + return &readOnlyClipFile{File: file, overrideName: item.name}, nil + } + + dirRoot, err := openSharedRoot(item.dirRoot, false) + if err != nil { + return nil, err + } + targetRel := "." + overrideName := item.name + if hasSub { + if err := checkSharedFileParents(dirRoot, subPath); err != nil { + _ = dirRoot.Close() + return nil, os.ErrPermission + } + targetRel = subPath + overrideName = "" + } + info, err := statDAVEntry(dirRoot, targetRel) + if err != nil { + _ = dirRoot.Close() + return nil, err + } + file, err := dirRoot.OpenFile(targetRel, os.O_RDONLY, 0) + if err != nil { + _ = dirRoot.Close() + return nil, err + } + if !info.IsDir() { + _ = dirRoot.Close() + return &readOnlyClipFile{File: file}, nil + } + // Keep dirRoot open on directory handles so Readdir can Lstat children safely. + return &readOnlyClipDirFile{ + File: file, + dirRoot: dirRoot, + dirRel: targetRel, + overrideName: overrideName, + }, nil +} + +type virtualDirInfo struct { + name string + modTime time.Time +} + +func (d virtualDirInfo) Name() string { return d.name } +func (d virtualDirInfo) Size() int64 { return 0 } +func (d virtualDirInfo) Mode() fs.FileMode { return fs.ModeDir | 0o555 } +func (d virtualDirInfo) ModTime() time.Time { return d.modTime } +func (d virtualDirInfo) IsDir() bool { return true } +func (d virtualDirInfo) Sys() any { return nil } + +type renamedFileInfo struct { + fs.FileInfo + name string +} + +func (r renamedFileInfo) Name() string { + if r.name != "" { + return r.name + } + return r.FileInfo.Name() +} + +type virtualDirFile struct { + info fs.FileInfo + entries []fs.FileInfo + pos int +} + +func (d *virtualDirFile) Close() error { return nil } +func (d *virtualDirFile) Read([]byte) (int, error) { return 0, io.EOF } +func (d *virtualDirFile) Write([]byte) (int, error) { return 0, os.ErrPermission } +func (d *virtualDirFile) Stat() (fs.FileInfo, error) { return d.info, nil } +func (d *virtualDirFile) Seek(offset int64, whence int) (int64, error) { + if offset == 0 && whence == io.SeekStart { + d.pos = 0 + return 0, nil + } + return 0, os.ErrInvalid +} + +func (d *virtualDirFile) Readdir(count int) ([]fs.FileInfo, error) { + if count <= 0 { + out := append([]fs.FileInfo(nil), d.entries[d.pos:]...) + d.pos = len(d.entries) + return out, nil + } + if d.pos >= len(d.entries) { + return nil, io.EOF + } + end := min(d.pos+count, len(d.entries)) + out := append([]fs.FileInfo(nil), d.entries[d.pos:end]...) + d.pos = end + return out, nil +} + +type readOnlyClipFile struct { + *os.File + overrideName string +} + +func (f *readOnlyClipFile) Write([]byte) (int, error) { return 0, os.ErrPermission } + +func (f *readOnlyClipFile) Stat() (fs.FileInfo, error) { + info, err := f.File.Stat() + if err != nil || f.overrideName == "" { + return info, err + } + return renamedFileInfo{FileInfo: info, name: f.overrideName}, nil +} + +type readOnlyClipDirFile struct { + *os.File + dirRoot *os.Root + dirRel string + overrideName string + filtered []fs.FileInfo + loaded bool + pos int +} + +func (f *readOnlyClipDirFile) Write([]byte) (int, error) { return 0, os.ErrPermission } + +func (f *readOnlyClipDirFile) Close() error { + err1 := f.File.Close() + var err2 error + if f.dirRoot != nil { + err2 = f.dirRoot.Close() + f.dirRoot = nil + } + return errors.Join(err1, err2) +} + +func (f *readOnlyClipDirFile) Stat() (fs.FileInfo, error) { + info, err := f.File.Stat() + if err != nil || f.overrideName == "" { + return info, err + } + return renamedFileInfo{FileInfo: info, name: f.overrideName}, nil +} + +func (f *readOnlyClipDirFile) Readdir(count int) ([]fs.FileInfo, error) { + if !f.loaded { + raw, err := f.File.Readdir(-1) + if err != nil { + return nil, err + } + f.loaded = true + f.filtered = make([]fs.FileInfo, 0, len(raw)) + for _, child := range raw { + name := child.Name() + if name == "" || name == "." || name == ".." { + continue + } + childRel := name + if f.dirRel != "." { + childRel = f.dirRel + "/" + name + } + checked, err := statDAVEntry(f.dirRoot, childRel) + if err != nil { + continue + } + if !checked.IsDir() && !isSharedRegularFile(checked.Mode()) { + continue + } + f.filtered = append(f.filtered, checked) + } + } + if count <= 0 { + out := append([]fs.FileInfo(nil), f.filtered[f.pos:]...) + f.pos = len(f.filtered) + return out, nil + } + if f.pos >= len(f.filtered) { + return nil, io.EOF + } + end := min(f.pos+count, len(f.filtered)) + out := append([]fs.FileInfo(nil), f.filtered[f.pos:end]...) + f.pos = end + return out, nil +} + +// --- Host-to-Guest HTTP tar fallback when WebDAV mount is unavailable --- + +func (s *Server) serveClipboardBatchTar(w http.ResponseWriter, _ *http.Request, vmKey, batchID string) { + policy := s.EffectiveClipboardPolicy(vmKey) + if !policy.Enabled { + writeFeatureDisabled(w, "clipboard") + return + } + if !policy.SyncFiles || policy.Direction == ClipboardGuestToHost { + http.Error(w, "file clipboard disabled", http.StatusForbidden) + return + } + batch := s.lookupClipHostBatch(vmKey, batchID) + if batch == nil { + http.Error(w, "clipboard batch not found", http.StatusNotFound) + return + } + maxBytes := int64(policy.MaxFileBytes) + if batch.scannedLimit == maxBytes && batch.exceedsTarLimit { + http.Error(w, "clipboard files exceed fallback size limit", http.StatusRequestEntityTooLarge) + return + } + if total, exceeds := measureClipBatchBytes(orderedBatchItems(batch), maxBytes); exceeds || total > maxBytes { + http.Error(w, "clipboard files exceed fallback size limit", http.StatusRequestEntityTooLarge) + return + } + + s.touchLastSeen(vmKey) + w.Header().Set("Content-Type", "application/x-tar") + w.Header().Set("X-Clip-Batch", batch.id) + tw := tar.NewWriter(w) + defer func() { _ = tw.Close() }() + + var writtenBytes int64 + var fileCount int + for _, entryName := range batch.order { + item := batch.items[entryName] + if err := writeClipItemToTar(tw, item, maxBytes, &writtenBytes, &fileCount); err != nil { + atomic.AddUint64(&s.clipStatsErr, 1) + return + } + } +} + +func orderedBatchItems(b *clipHostBatch) []clipBatchItem { + out := make([]clipBatchItem, 0, len(b.order)) + for _, name := range b.order { + out = append(out, b.items[name]) + } + return out +} + +func writeClipItemToTar(tw *tar.Writer, item clipBatchItem, maxBytes int64, writtenBytes *int64, fileCount *int) error { + if !item.isDir { + *fileCount++ + if *fileCount > MaxClipboardFileCount { + return errClipArchiveTooLarge + } + parentRoot, err := os.OpenRoot(item.parentDir) + if err != nil { + return err + } + defer parentRoot.Close() + info, err := statDAVEntry(parentRoot, item.baseName) + if err != nil { + return err + } + if !isSharedRegularFile(info.Mode()) { + return os.ErrPermission + } + if *writtenBytes+info.Size() > maxBytes { + return errClipArchiveTooLarge + } + f, err := parentRoot.OpenFile(item.baseName, os.O_RDONLY, 0) + if err != nil { + return err + } + defer f.Close() + hdr := &tar.Header{ + Typeflag: tar.TypeReg, + Name: item.name, + Size: info.Size(), + Mode: 0o644, + ModTime: info.ModTime(), + } + if err := tw.WriteHeader(hdr); err != nil { + return err + } + n, err := io.CopyN(tw, f, info.Size()) + *writtenBytes += n + return err + } + + dirRoot, err := openSharedRoot(item.dirRoot, false) + if err != nil { + return err + } + defer dirRoot.Close() + + return fs.WalkDir(dirRoot.FS(), ".", func(rel string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if rel != "." && d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + if rel != "." && strings.Count(rel, "/")+1 > MaxSharedDepth { + if d.IsDir() { + return fs.SkipDir + } + return nil + } + info, err := statDAVEntry(dirRoot, rel) + if err != nil { + if d.IsDir() && rel != "." { + return fs.SkipDir + } + return nil + } + *fileCount++ + if *fileCount > MaxClipboardFileCount { + return errClipArchiveTooLarge + } + arcName := item.name + if rel != "." { + arcName = item.name + "/" + rel + } + if info.IsDir() { + return tw.WriteHeader(&tar.Header{ + Typeflag: tar.TypeDir, + Name: arcName + "/", + Mode: 0o755, + ModTime: info.ModTime(), + }) + } + if !isSharedRegularFile(info.Mode()) { + return nil + } + if *writtenBytes+info.Size() > maxBytes { + return errClipArchiveTooLarge + } + f, err := dirRoot.OpenFile(rel, os.O_RDONLY, 0) + if err != nil { + return nil + } + defer f.Close() + if err := tw.WriteHeader(&tar.Header{ + Typeflag: tar.TypeReg, + Name: arcName, + Size: info.Size(), + Mode: 0o644, + ModTime: info.ModTime(), + }); err != nil { + return err + } + n, err := io.CopyN(tw, f, info.Size()) + *writtenBytes += n + return err + }) +} diff --git a/internal/guesttools/clipboard_windows.go b/internal/guesttools/clipboard_windows.go index 6dbf86d..8ffcaca 100644 --- a/internal/guesttools/clipboard_windows.go +++ b/internal/guesttools/clipboard_windows.go @@ -56,6 +56,7 @@ const ( hwndMessage = ^uintptr(2) wmClipJob = 0x8000 // WM_APP maxDIBBytes = 128 << 20 + maxHDropBytes = 1 << 20 ) type OSClipboard struct{} @@ -236,13 +237,17 @@ func (OSClipboard) ReadText() (string, error) { } type clipboardSnapshot struct { - text []uint16 - png []byte - dib []byte - kind ClipKind + files []string + text []uint16 + png []byte + dib []byte + kind ClipKind } func (snap clipboardSnapshot) payload() ClipPayload { + if snap.kind == ClipFiles && len(snap.files) > 0 { + return ClipPayload{Kind: ClipFiles, Files: append([]string(nil), snap.files...)} + } if snap.kind == ClipText && len(snap.text) > 0 && snap.text[0] != 0 { return ClipPayload{Kind: ClipText, Data: []byte(decodeClipboardText(snap.text))} } @@ -257,6 +262,26 @@ func (snap clipboardSnapshot) payload() ClipPayload { return ClipPayload{Kind: snap.kind} } +func (snap *clipboardSnapshot) readFilesLocked(wantFiles bool, available func(uintptr) bool, readBytes func(uintptr, int) ([]byte, error)) (bool, error) { + if !available(cfHDrop) { + return false, nil + } + if !wantFiles { + snap.kind = ClipEmpty + return false, nil + } + raw, err := readBytes(cfHDrop, maxHDropBytes) + if err != nil { + return false, err + } + if files, parseErr := parseHDropBytes(raw); parseErr == nil && len(files) > 0 { + snap.files = files + snap.kind = ClipFiles + return true, nil + } + return false, nil +} + func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintptr, available func(uintptr) bool, readImage func(uintptr, int) ([]byte, error)) error { if pngFormat != 0 && available(pngFormat) { snap.kind = ClipEmpty @@ -281,20 +306,31 @@ func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintpt return nil } -// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image. +// Read inspects the Windows clipboard and returns files, UTF-8 text, or a PNG image. func (c OSClipboard) Read() (ClipPayload, error) { - payload, _, err := c.readClipboard(true) + payload, _, err := c.readClipboardOpts(true, true) return payload, err } func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) { + return c.readClipboardOpts(wantImage, false) +} + +func (c OSClipboard) readClipboardOpts(wantImage, wantFiles bool) (ClipPayload, uint32, error) { pngFormat, _ := registerPNGFormat() var snap clipboardSnapshot var seq uint32 + isAvail := func(format uintptr) bool { + avail, _, _ := procIsClipboardFormatAvail.Call(format) + return avail != 0 + } err := onClipboardThread(func(hwnd uintptr) error { return withOpenClipboard(hwnd, func() error { defer func() { seq = c.SequenceNumber() }() - if avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText); avail != 0 { + if ok, err := snap.readFilesLocked(wantFiles, isAvail, readClipboardImageLocked); err != nil || ok { + return err + } + if isAvail(cfUnicodeText) { var err error snap.text, err = readUnicodeTextLocked() if err != nil { @@ -305,10 +341,7 @@ func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) return nil } } - return snap.readImagesLocked(wantImage, pngFormat, func(format uintptr) bool { - avail, _, _ := procIsClipboardFormatAvail.Call(format) - return avail != 0 - }, readClipboardImageLocked) + return snap.readImagesLocked(wantImage, pngFormat, isAvail, readClipboardImageLocked) }) }) if err != nil { @@ -357,6 +390,12 @@ func (c OSClipboard) WritePNG(pngBytes []byte) error { return err } +// WriteFiles writes a list of local paths to the Windows clipboard as CF_HDROP. +func (c OSClipboard) WriteFiles(paths []string) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipFiles, Files: paths}, nil) + return err +} + func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq uint32, err error) { var mem []clipboardMem defer func() { @@ -371,7 +410,18 @@ func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq u if len(payload.Data) > MaxClipboardBytes { return 0, fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes) } - if payload.Kind == ClipPNG { + switch payload.Kind { + case ClipFiles: + hdrop, err := encodeHDropBytes(payload.Files) + if err != nil { + return 0, err + } + hdropMem, err := prepareClipboardMem(cfHDrop, uintptr(len(hdrop)), unsafe.Pointer(&hdrop[0])) + if err != nil { + return 0, err + } + mem = append(mem, hdropMem) + case ClipPNG: dib, err := EncodePNGToDIB(payload.Data) if err != nil { return 0, err @@ -390,7 +440,7 @@ func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq u return 0, err } mem = append(mem, dibMem) - } else { + default: 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])) diff --git a/internal/guesttools/clipboard_windows_test.go b/internal/guesttools/clipboard_windows_test.go index 3779cb8..3f11c12 100644 --- a/internal/guesttools/clipboard_windows_test.go +++ b/internal/guesttools/clipboard_windows_test.go @@ -56,6 +56,8 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) { snap clipboardSnapshot want ClipPayload }{ + {"files first", clipboardSnapshot{files: []string{`C:\work\report.pdf`}, text: []uint16{'x', 0}, kind: ClipFiles}, + ClipPayload{Kind: ClipFiles, Files: []string{`C:\work\report.pdf`}}}, {"text first", clipboardSnapshot{text: []uint16{'x', 0}, png: origPNG, kind: ClipText}, ClipPayload{Kind: ClipText, Data: []byte("x")}}, {"empty text does not hide PNG", clipboardSnapshot{text: []uint16{0}, png: append(bytes.Clone(origPNG), 0, 0)}, @@ -69,8 +71,9 @@ func TestWindowsClipboardSnapshotFormats(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { got := tc.snap.payload() - if got.Kind != tc.want.Kind || !bytes.Equal(got.Data, tc.want.Data) { - t.Fatalf("got %s (%d bytes), want %s (%d bytes)", got.Kind, len(got.Data), tc.want.Kind, len(tc.want.Data)) + if !clipPayloadEqual(got, tc.want) { + t.Fatalf("got %s (%d bytes, files=%v), want %s (%d bytes, files=%v)", + got.Kind, len(got.Data), got.Files, tc.want.Kind, len(tc.want.Data), tc.want.Files) } }) } @@ -95,3 +98,34 @@ func TestWindowsClipboardSnapshotSkipsDisabledImages(t *testing.T) { } } } + +func TestWindowsClipboardSnapshotFilesGate(t *testing.T) { + hdrop, err := encodeHDropBytes([]string{`C:\Docs\a.txt`, `C:\Docs\Sub`}) + if err != nil { + t.Fatal(err) + } + var disabled clipboardSnapshot + ok, err := disabled.readFilesLocked(false, func(candidate uintptr) bool { + return candidate == cfHDrop + }, func(uintptr, int) ([]byte, error) { + t.Fatal("disabled CF_HDROP must not copy clipboard memory") + return nil, nil + }) + if err != nil || ok { + t.Fatalf("disabled readFilesLocked = (%v, %v), want (false, nil)", ok, err) + } + + var enabled clipboardSnapshot + ok, err = enabled.readFilesLocked(true, func(candidate uintptr) bool { + return candidate == cfHDrop + }, func(uintptr, int) ([]byte, error) { + return hdrop, nil + }) + if err != nil || !ok { + t.Fatalf("enabled readFilesLocked = (%v, %v), want (true, nil)", ok, err) + } + got := enabled.payload() + if got.Kind != ClipFiles || len(got.Files) != 2 || got.Files[0] != `C:\Docs\a.txt` || got.Files[1] != `C:\Docs\Sub` { + t.Fatalf("enabled payload = %+v", got) + } +} diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 4173485..194fc8c 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -12,10 +12,19 @@ import ( func TestGuestAgentFolderMounts(t *testing.T) { sh, err := exec.LookPath("sh") + var gitUsrBin string if runtime.GOOS == "windows" { - const gitSH = "C:/Program Files/Git/bin/sh.exe" - if _, statErr := os.Stat(gitSH); statErr == nil { - sh, err = gitSH, nil + candidates := []string{"C:/Program Files/Git/bin/sh.exe"} + if gitExe, lookErr := exec.LookPath("git"); lookErr == nil { + gitRoot := filepath.Dir(filepath.Dir(gitExe)) + candidates = append(candidates, filepath.ToSlash(filepath.Join(gitRoot, "bin", "sh.exe"))) + } + for _, cand := range candidates { + if _, statErr := os.Stat(cand); statErr == nil { + sh, err = cand, nil + gitUsrBin = filepath.Join(filepath.Dir(filepath.Dir(filepath.FromSlash(cand))), "usr", "bin") + break + } } } if err != nil { @@ -30,7 +39,11 @@ func TestGuestAgentFolderMounts(t *testing.T) { if err := os.WriteFile(filepath.Join(cmd.Dir, "mount_webdav"), []byte(folderMountWebDAV), 0o755); err != nil { t.Fatal(err) } - cmd.Env = append(os.Environ(), "MSYS=winsymlinks:sys") + env := append(os.Environ(), "MSYS=winsymlinks:sys") + if gitUsrBin != "" { + env = append(env, "PATH="+gitUsrBin+string(os.PathListSeparator)+os.Getenv("PATH")) + } + cmd.Env = env cmd.Stdin = strings.NewReader(script) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("sh %v: %v\n%s", args, err, out) @@ -43,8 +56,8 @@ func TestGuestAgentFolderMounts(t *testing.T) { "/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command", ) uninstall = dnsPaths.Replace(uninstall) - if CurrentAgentVersion != WindowDropAgentVersion { - t.Fatalf("CurrentAgentVersion = %d, want window drop version %d", CurrentAgentVersion, WindowDropAgentVersion) + if CurrentAgentVersion != ClipboardFilesAgentVersion { + t.Fatalf("CurrentAgentVersion = %d, want Clipboard Files version %d", CurrentAgentVersion, ClipboardFilesAgentVersion) } versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,` if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") { diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index 177799f..054b022 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -18,7 +18,8 @@ const KeymapAgentVersion = 10 const TimezoneAgentVersion = 11 const HostDNSAgentVersion = 12 const WindowDropAgentVersion = 13 -const CurrentAgentVersion = WindowDropAgentVersion +const ClipboardFilesAgentVersion = 14 +const CurrentAgentVersion = ClipboardFilesAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index d57a103..84b1eab 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -26,10 +26,11 @@ import ( ) type memClipboard struct { - mu sync.Mutex - kind ClipKind - data []byte - seq uint32 + mu sync.Mutex + kind ClipKind + data []byte + files []string + seq uint32 } func (m *memClipboard) SequenceNumber() uint32 { @@ -52,6 +53,7 @@ func (m *memClipboard) WriteText(s string) error { defer m.mu.Unlock() m.kind = ClipText m.data = []byte(s) + m.files = nil m.seq++ return nil } @@ -61,11 +63,12 @@ func (m *memClipboard) Read() (ClipPayload, error) { defer m.mu.Unlock() cp := make([]byte, len(m.data)) copy(cp, m.data) + files := append([]string(nil), m.files...) k := m.kind if k == "" && len(cp) > 0 { k = ClipText } - return ClipPayload{Kind: k, Data: cp}, nil + return ClipPayload{Kind: k, Data: cp, Files: files}, nil } func (m *memClipboard) WritePNG(b []byte) error { @@ -73,6 +76,17 @@ func (m *memClipboard) WritePNG(b []byte) error { defer m.mu.Unlock() m.kind = ClipPNG m.data = append([]byte(nil), b...) + m.files = nil + m.seq++ + return nil +} + +func (m *memClipboard) WriteFiles(paths []string) error { + m.mu.Lock() + defer m.mu.Unlock() + m.kind = ClipFiles + m.data = nil + m.files = append([]string(nil), paths...) m.seq++ return nil } diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 8f50352..1ef5f79 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -151,6 +151,8 @@ FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" DESKTOP_LINK="$HOME/Desktop/ReimsShare" +CLIP_MOUNT="$APP_DIR/clip_mount" +CLIP_FALLBACK_DIR="$APP_DIR/clip_files" TMP_DIR="$APP_DIR/tmp" INJECT_LOCK="$TMP_DIR/injecting" DROP_INJECT_LOCK="$TMP_DIR/drop-injecting" @@ -178,6 +180,7 @@ cleanup() { if [ -n "$TEXT_INPUT_PID" ]; then kill "$TEXT_INPUT_PID" 2>/dev/null || true fi + unmount_clip_mount 2>/dev/null || true rm -f "$INJECT_LOCK" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true } trap cleanup EXIT @@ -186,8 +189,8 @@ trap 'exit 0' INT TERM ` + guestIdentityHelpers + ` load_conf() { - if [ -f "/Volumes/REIMSTOOLS/config" ] && - { [ ! -f "$CONF" ] || same_guest_identity "$CONF" "/Volumes/REIMSTOOLS/config"; }; then + if [ -f "/Volumes/REIMSTOOLS/config" ] && ( : < "/Volumes/REIMSTOOLS/config" ) 2>/dev/null && + { [ ! -f "$CONF" ] || same_guest_identity "$CONF" "/Volumes/REIMSTOOLS/config" 2>/dev/null; }; then cp "/Volumes/REIMSTOOLS/config" "$CONF" 2>/dev/null || true chmod 600 "$CONF" 2>/dev/null || true fi @@ -475,6 +478,18 @@ EOF fi } +unmount_clip_mount() { + clip_mp="${CLIP_MOUNT:-${APP_DIR:-$TMP_DIR}/clip_mount}" + clip_fb="${CLIP_FALLBACK_DIR:-${APP_DIR:-$TMP_DIR}/clip_files}" + if [ -n "${REIMS_VM:-}" ] && type is_reims_dav_mounted >/dev/null 2>&1 && + is_reims_dav_mounted "$clip_mp" "/dav-clip/$(urlencode "$REIMS_VM")/"; then + if unmount_shared_folder "$clip_mp"; then + rmdir "$clip_mp" 2>/dev/null || true + fi + fi + [ ! -d "$clip_fb" ] || rm -rf "$clip_fb" 2>/dev/null || true +} + apply_host_config() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true) @@ -489,6 +504,18 @@ apply_host_config() { else clip_enabled="1" fi + if printf '%s' "$cfg_json" | grep -q '"clipboard_sync_files"[[:space:]]*:[[:space:]]*false'; then + clip_sync_files="0" + else + clip_sync_files="1" + fi + cfg_clip_dir=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"clipboard_direction"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p') + [ -n "$cfg_clip_dir" ] && clip_direction="$cfg_clip_dir" + cfg_max_file=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"clipboard_max_file_bytes"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') + [ -n "$cfg_max_file" ] && clip_max_file_bytes="$cfg_max_file" + if [ "${clip_enabled:-1}" != "1" ] || [ "${clip_sync_files:-1}" != "1" ] || [ "${clip_direction:-bidirectional}" = "guest-to-host" ]; then + unmount_clip_mount + fi if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then if command -v caffeinate >/dev/null 2>&1; then @@ -537,6 +564,20 @@ report_status() { read_local_clipboard() { out_file="$1" cinfo=$(osascript -e 'clipboard info' 2>/dev/null || true) + case "$cinfo" in + *furl*|*NSFilenamesPboardType*) + if [ "${clip_sync_files:-1}" = "1" ]; then + rm -f "$out_file" + file_kind=$(read_local_files "$out_file") + if [ -n "$file_kind" ] && [ -s "$out_file" ]; then + echo "$file_kind" + return 0 + fi + fi + echo "empty" + return 0 + ;; + esac case "$cinfo" in *utf8*|*"Unicode text"*|*string*) if pbpaste >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then @@ -584,12 +625,455 @@ read_local_clipboard() { esac } +read_local_files() { + clip_mp="${CLIP_MOUNT:-${APP_DIR:-$TMP_DIR}/clip_mount}" + clip_fb="${CLIP_FALLBACK_DIR:-${APP_DIR:-$TMP_DIR}/clip_files}" + res=$(REIMS_CLIP_OUT_FILE="$1" \ + REIMS_CLIP_MOUNT_PREFIX="${clip_mp%/}/" \ + REIMS_CLIP_FALLBACK_PREFIX="${clip_fb%/}/" \ + osascript -l JavaScript -e '/* reims-read-files */ +(function() { + try { + ObjC.import("AppKit"); + ObjC.import("Foundation"); + var env = $.NSProcessInfo.processInfo.environment; + var outPath = ObjC.unwrap(env.objectForKey("REIMS_CLIP_OUT_FILE")) || ""; + var mountPrefix = ObjC.unwrap(env.objectForKey("REIMS_CLIP_MOUNT_PREFIX")) || ""; + var fbPrefix = ObjC.unwrap(env.objectForKey("REIMS_CLIP_FALLBACK_PREFIX")) || ""; + if (!outPath) return ""; + var pb = $.NSPasteboard.generalPasteboard; + var paths = []; + var seen = {}; + function addPath(p) { + if (!p || p === "/" || p.indexOf("\n") >= 0 || p.indexOf("\r") >= 0 || p.indexOf("\t") >= 0 || seen[p]) return; + seen[p] = true; + paths.push(p); + } + var items = ObjC.unwrap(pb.pasteboardItems); + if (items && items.length > 0) { + for (var i = 0; i < items.length; i++) { + var it = items[i]; + var rawURL = ObjC.unwrap(it.stringForType("public.file-url")); + if (!rawURL && $.NSPasteboardTypeFileURL) { + rawURL = ObjC.unwrap(it.stringForType($.NSPasteboardTypeFileURL)); + } + if (rawURL) { + var u = $.NSURL.URLWithString(rawURL); + if (u) { + var p = ""; + if (rawURL.indexOf("file:///.file/") === 0) { + var fp = u.filePathURL; + if (fp) p = ObjC.unwrap(fp.path) || ""; + } + if (!p) p = ObjC.unwrap(u.path) || ""; + if (p) addPath(String(p)); + } + } + } + } + if (paths.length === 0) { + var legacy = ObjC.deepUnwrap(pb.propertyListForType("NSFilenamesPboardType")); + if (Array.isArray(legacy)) { + for (var j = 0; j < legacy.length; j++) { + if (typeof legacy[j] === "string") addPath(legacy[j]); + } + } + } + if (paths.length === 0) return ""; + var fm = $.NSFileManager.defaultManager; + var hostedLines = []; + var localLines = []; + for (var k = 0; k < paths.length; k++) { + var p = paths[k]; + if ((mountPrefix && p.indexOf(mountPrefix) === 0) || (fbPrefix && p.indexOf(fbPrefix) === 0)) { + hostedLines.push("hosted\t" + p); + continue; + } + var attrErr = $(); + var attrs = fm.attributesOfItemAtPathError(p, attrErr); + if (!attrs) continue; + var ftype = ObjC.unwrap(attrs.objectForKey("NSFileType")); + if (ftype === "NSFileTypeSymbolicLink") continue; + var kind = ""; + if (ftype === "NSFileTypeRegular") kind = "f"; + else if (ftype === "NSFileTypeDirectory") kind = "d"; + else continue; + var sz = Number(ObjC.unwrap(attrs.objectForKey("NSFileSize")) || 0); + var dtObj = attrs.objectForKey("NSFileModificationDate"); + var mtime = 0; + if (dtObj) { + var dtVal = ObjC.unwrap(dtObj); + if (dtVal && typeof dtVal.getTime === "function") { + mtime = Math.floor(dtVal.getTime()); + } else if (typeof dtObj.timeIntervalSince1970 === "number") { + mtime = Math.floor(dtObj.timeIntervalSince1970 * 1000); + } else if (typeof dtObj.timeIntervalSince1970 === "function") { + try { mtime = Math.floor(dtObj.timeIntervalSince1970() * 1000); } catch (_e) {} + } + } + localLines.push(kind + "\t" + sz + "\t" + mtime + "\t" + p); + } + var out = ""; + var mode = ""; + if (localLines.length > 0) { + out = localLines.join("\n") + "\n"; + mode = "files"; + } else if (hostedLines.length > 0) { + out = hostedLines.join("\n") + "\n"; + mode = "files_hosted"; + } else { + return ""; + } + var writeErr = $(); + if (!$.NSString.stringWithString(out).writeToFileAtomicallyEncodingError(outPath, true, $.NSUTF8StringEncoding, writeErr)) return ""; + return mode; + } catch (e) { + return "err:" + String(e); + } +})();' 2>/dev/null || true) + case "$res" in + files|files_hosted) printf '%s\n' "$res" ;; + err:*) printf 'clipboard read files failed: %s\n' "$res" >&2 ;; + esac +} + write_local_png() { osascript -e "set the clipboard to (read (POSIX file \"$1\") as «class PNGf»)" >/dev/null 2>&1 } +write_local_files_from_manifest() { + res=$(REIMS_CLIP_MANIFEST_FILE="$1" REIMS_CLIP_BATCH_DIR="$2" osascript -l JavaScript -e '/* reims-write-files */ +(function() { + try { + ObjC.import("AppKit"); + ObjC.import("Foundation"); + var env = $.NSProcessInfo.processInfo.environment; + var mfPath = ObjC.unwrap(env.objectForKey("REIMS_CLIP_MANIFEST_FILE")) || ""; + var baseDir = ObjC.unwrap(env.objectForKey("REIMS_CLIP_BATCH_DIR")) || ""; + if (!mfPath || !baseDir) return "err:env"; + var readErr = $(); + var raw = ObjC.unwrap($.NSString.stringWithContentsOfFileEncodingError(mfPath, $.NSUTF8StringEncoding, readErr)); + if (!raw) return "err:read_manifest"; + var doc = JSON.parse(raw); + if (!doc || !Array.isArray(doc.items) || doc.items.length === 0) return "err:bad_manifest"; + var fm = $.NSFileManager.defaultManager; + var urls = $.NSMutableArray.arrayWithCapacity(doc.items.length); + var names = []; + var baseClean = baseDir.replace(/\/+$/, ""); + var count = 0; + for (var i = 0; i < doc.items.length; i++) { + var name = String(doc.items[i] || ""); + if (!name || name === "." || name === ".." || name.indexOf("/") >= 0 || name.indexOf("\\") >= 0 || name.indexOf("\0") >= 0) { + return "err:bad_item"; + } + var full = baseClean + "/" + name; + if (!fm.fileExistsAtPath(full)) { + var nfd = full.normalize ? full.normalize("NFD") : full; + var nfc = full.normalize ? full.normalize("NFC") : full; + if (nfd !== full && fm.fileExistsAtPath(nfd)) full = nfd; + else if (nfc !== full && fm.fileExistsAtPath(nfc)) full = nfc; + else return "err:missing:" + full; + } + var u = $.NSURL.fileURLWithPath(full); + if (!u) return "err:url"; + urls.addObject(u); + names.push(name); + count++; + } + if (count === 0) return "err:empty"; + var pb = $.NSPasteboard.generalPasteboard; + var cc = pb.clearContents; + if (typeof cc === "function") { + try { pb.clearContents(); } catch (_e) {} + } + if (!pb.writeObjects(urls)) return "err:write_pb"; + try { + pb.setStringForType(names.join("\n"), "public.utf8-plain-text"); + var curTypes = ObjC.deepUnwrap(pb.types) || []; + var curItems = ObjC.unwrap(pb.pasteboardItems) || []; + if (curTypes.indexOf("public.file-url") < 0 || curItems.length !== count) { + var cc2 = pb.clearContents; + if (typeof cc2 === "function") { + try { pb.clearContents(); } catch (_e2) {} + } + pb.writeObjects(urls); + } + } catch (_e3) {} + return "ok"; + } catch (e) { + return "err:exc:" + String(e); + } +})();' 2>/dev/null || true) + if [ "$res" = "ok" ]; then + return 0 + fi + [ -z "$res" ] || printf 'clipboard write files failed: %s\n' "$res" >&2 + return 1 +} + +backup_clip_files() { + REIMS_CLIP_BAK_FILE="$1" osascript -l JavaScript -e '/* reims-backup-files */ +(function() { + try { + ObjC.import("AppKit"); + ObjC.import("Foundation"); + var outPath = ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey("REIMS_CLIP_BAK_FILE")) || ""; + if (!outPath) return ""; + var pb = $.NSPasteboard.generalPasteboard; + var items = ObjC.unwrap(pb.pasteboardItems); + var paths = []; + if (items && items.length > 0) { + for (var i = 0; i < items.length; i++) { + var rawURL = ObjC.unwrap(items[i].stringForType("public.file-url")); + if (rawURL) { + var u = $.NSURL.URLWithString(rawURL); + if (u) { + var p = ""; + if (rawURL.indexOf("file:///.file/") === 0) { + var fp = u.filePathURL; + if (fp) p = ObjC.unwrap(fp.path) || ""; + } + if (!p) p = ObjC.unwrap(u.path) || ""; + if (p && p.indexOf("\n") < 0) paths.push(String(p)); + } + } + } + } + if (paths.length === 0) return ""; + var err = $(); + if (!$.NSString.stringWithString(paths.join("\n") + "\n").writeToFileAtomicallyEncodingError(outPath, true, $.NSUTF8StringEncoding, err)) return ""; + return "ok"; + } catch (_e) { return ""; } +})();' >/dev/null 2>&1 || true + [ -s "$1" ] +} + +restore_clip_files() { + REIMS_CLIP_BAK_FILE="$1" osascript -l JavaScript -e '/* reims-restore-files */ +(function() { + try { + ObjC.import("AppKit"); + ObjC.import("Foundation"); + var inPath = ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey("REIMS_CLIP_BAK_FILE")) || ""; + if (!inPath) return ""; + var err = $(); + var raw = ObjC.unwrap($.NSString.stringWithContentsOfFileEncodingError(inPath, $.NSUTF8StringEncoding, err)) || ""; + var lines = raw.split("\n"); + var fm = $.NSFileManager.defaultManager; + var urls = $.NSMutableArray.arrayWithCapacity(lines.length); + var names = []; + var count = 0; + for (var i = 0; i < lines.length; i++) { + var p = lines[i]; + if (!p || !fm.fileExistsAtPath(p)) continue; + var u = $.NSURL.fileURLWithPath(p); + if (!u) continue; + urls.addObject(u); + var parts = p.split("/"); + names.push(parts[parts.length - 1] || p); + count++; + } + if (count === 0) return ""; + var pb = $.NSPasteboard.generalPasteboard; + var cc = pb.clearContents; + if (typeof cc === "function") { + try { pb.clearContents(); } catch (_e) {} + } + if (!pb.writeObjects(urls)) return ""; + try { + pb.setStringForType(names.join("\n"), "public.utf8-plain-text"); + var curTypes = ObjC.deepUnwrap(pb.types) || []; + if (curTypes.indexOf("public.file-url") < 0) { + var cc2 = pb.clearContents; + if (typeof cc2 === "function") { + try { pb.clearContents(); } catch (_e2) {} + } + pb.writeObjects(urls); + } + } catch (_e3) {} + return "ok"; + } catch (_e) { return ""; } +})();' >/dev/null 2>&1 || true +} + +clear_local_clipboard() { + osascript -l JavaScript -e '/* reims-clear-clip */ +(function() { + try { + ObjC.import("AppKit"); + var pb = $.NSPasteboard.generalPasteboard; + var cc = pb.clearContents; + if (typeof cc === "function") { + try { pb.clearContents(); } catch (_e) {} + } + } catch (_e) {} +})();' >/dev/null 2>&1 || true +} + +ensure_clip_mount() { + clip_mp="${CLIP_MOUNT:-${APP_DIR:-$TMP_DIR}/clip_mount}" + [ -n "${REIMS_VM:-}" ] && [ -n "${REIMS_HOST_URL:-}" ] && [ -n "${REIMS_TOKEN:-}" ] || return 1 + [ ! -L "$clip_mp" ] || return 1 + clip_route="/dav-clip/$(urlencode "$REIMS_VM")/" + if type is_reims_dav_mounted >/dev/null 2>&1 && is_reims_dav_mounted "$clip_mp" "$clip_route"; then + return 0 + fi + if type is_drive_mounted >/dev/null 2>&1 && is_drive_mounted "$clip_mp"; then + return 1 + fi + command -v mount_webdav >/dev/null 2>&1 || return 1 + mkdir -p "$clip_mp" || return 1 + clip_dav_url="${REIMS_HOST_URL%/}$clip_route" + if mount_authenticated_webdav -o rdonly,nobrowse -v "ReimsClip" "$clip_dav_url" "$clip_mp" >/dev/null 2>&1 || \ + mount_authenticated_webdav -o rdonly -v "ReimsClip" "$clip_dav_url" "$clip_mp" >/dev/null 2>&1; then + return 0 + fi + rmdir "$clip_mp" 2>/dev/null || true + return 1 +} + +prune_clip_fallback_dirs() { + fb_root="$1" + keep_batch="$2" + [ -d "$fb_root" ] || return 0 + # Keep at most the 3 newest fallback batch directories. + old_dirs=$(ls -1dt "$fb_root"/b_* 2>/dev/null | awk 'NR > 3 { print }') + if [ -n "$old_dirs" ]; then + printf '%s\n' "$old_dirs" | while IFS= read -r d; do + [ -n "$d" ] && [ "$d" != "$fb_root/$keep_batch" ] && rm -rf "$d" 2>/dev/null || true + done + fi +} + +apply_remote_clip_files() { + mf_file="$1" + batch=$(sed -n 's/.*"batch"[[:space:]]*:[[:space:]]*"\([A-Za-z0-9_-][A-Za-z0-9_-]*\)".*/\1/p' "$mf_file" | head -n 1) + [ -n "$batch" ] || return 1 + exceeds_tar="false" + if grep -q '"exceeds_tar_limit"[[:space:]]*:[[:space:]]*true' "$mf_file" 2>/dev/null; then + exceeds_tar="true" + fi + total_bytes=$(sed -n 's/.*"total_bytes"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$mf_file" | head -n 1) + max_bytes="${clip_max_file_bytes:-134217728}" + clip_mp="${CLIP_MOUNT:-${APP_DIR:-$TMP_DIR}/clip_mount}" + dav_batch_ready=0 + if ensure_clip_mount; then + if [ ! -d "$clip_mp/$batch" ]; then + ls "$clip_mp" >/dev/null 2>&1 || true + fi + if [ ! -d "$clip_mp/$batch" ] && type unmount_shared_folder >/dev/null 2>&1; then + unmount_shared_folder "$clip_mp" >/dev/null 2>&1 || true + ensure_clip_mount || true + fi + if [ -d "$clip_mp/$batch" ]; then + dav_batch_ready=1 + if write_local_files_from_manifest "$mf_file" "$clip_mp/$batch"; then + return 0 + fi + fi + fi + if [ "$exceeds_tar" != "true" ] && [ "${total_bytes:-0}" -le "$max_bytes" ]; then + fb_root="${CLIP_FALLBACK_DIR:-${APP_DIR:-$TMP_DIR}/clip_files}" + fb_tar="$TMP_DIR/clip_dl.tar" + fb_dir="$fb_root/$batch" + rm -rf "$fb_tar" "$fb_dir" + mkdir -p "$fb_dir" || return 1 + dl_code=$(curl -sS -m 60 -o "$fb_tar" -w '%{http_code}' \ + -H "Authorization: Bearer $REIMS_TOKEN" \ + "$REIMS_HOST_URL/v1/clipboard?batch=$batch&format=tar" 2>/dev/null) || dl_code=000 + if [ "$dl_code" = "200" ] && [ -s "$fb_tar" ] && tar -xf "$fb_tar" -C "$fb_dir" 2>/dev/null; then + rm -f "$fb_tar" + prune_clip_fallback_dirs "$fb_root" "$batch" + if write_local_files_from_manifest "$mf_file" "$fb_dir"; then + return 0 + fi + return 1 + elif [ "$dl_code" = "413" ] || [ "$dl_code" = "403" ]; then + rm -rf "$fb_tar" "$fb_dir" + return 2 + else + rm -rf "$fb_tar" "$fb_dir" + return 1 + fi + fi + if [ "$dav_batch_ready" -eq 0 ]; then + return 2 + fi + return 1 +} + +pack_local_files_tar() { + manifest_file="$1" + out_tar="$2" + max_bytes="${clip_max_file_bytes:-134217728}" + rm -f "$out_tar" + total_bytes=0 + item_count=0 + seen_bases=" " + set -- + while IFS="$TAB" read -r fkind fsize _fmtime fpath; do + [ -n "$fpath" ] || continue + [ -e "$fpath" ] && [ ! -L "$fpath" ] || continue + fbase=$(basename "$fpath") + fdir=$(dirname "$fpath") + [ -n "$fbase" ] && [ "$fbase" != "/" ] && [ "$fbase" != "." ] && [ "$fbase" != ".." ] || continue + case "$seen_bases" in + *"|$fbase|"*) continue ;; + esac + if [ "$fkind" = "f" ]; then + item_count=$((item_count + 1)) + total_bytes=$((total_bytes + ${fsize:-0})) + if [ "$item_count" -gt 2000 ] || [ "$total_bytes" -gt "$max_bytes" ]; then + return 2 + fi + elif [ "$fkind" = "d" ]; then + if find -P "$fpath" -type l 2>/dev/null | grep -q .; then + return 2 + fi + if find -P "$fpath" -mindepth 8 2>/dev/null | grep -q .; then + return 2 + fi + sub_count=$(find -P "$fpath" 2>/dev/null | wc -l | tr -d '[:space:]') + item_count=$((item_count + ${sub_count:-1})) + if [ "$item_count" -gt 2000 ]; then + return 2 + fi + dir_kb=$(du -skP "$fpath" 2>/dev/null | awk '{print $1}') + dir_est=$(( ${dir_kb:-0} * 1024 )) + if [ "$dir_est" -gt $((max_bytes + 4194304)) ]; then + return 2 + fi + total_bytes=$((total_bytes + dir_est)) + else + continue + fi + seen_bases="${seen_bases}|${fbase}|" + set -- ${1+"$@"} -C "$fdir" "./$fbase" + done < "$manifest_file" + [ "$#" -gt 0 ] || return 2 + COPYFILE_DISABLE=1 tar -cf "$out_tar" "$@" 2>/dev/null || { + rm -f "$out_tar" + return 1 + } + [ -s "$out_tar" ] || { + rm -f "$out_tar" + return 1 + } + tar_bytes=$(wc -c < "$out_tar" | tr -d '[:space:]') + if [ "${tar_bytes:-0}" -gt $((max_bytes + 2097152)) ]; then + rm -f "$out_tar" + return 2 + fi + return 0 +} + +hash_files_manifest() { + { printf 'files-local:'; cat "$1"; } | shasum -a 256 2>/dev/null | awk '{print $1}' +} + local_clip_hash() { case "$1" in + files|files_hosted) hash_files_manifest "$2" ;; png) hash_png_file "$2" ;; text) hash_file "$2" ;; empty) echo "empty" ;; @@ -604,6 +1088,9 @@ last_local_hash="" last_server_hash="" last_server_seq="" clip_enabled="1" +clip_sync_files="1" +clip_direction="bidirectional" +clip_max_file_bytes="134217728" tick=0 TAB=$(printf '\t') @@ -621,38 +1108,69 @@ sync_clipboard() { cur_hash=$(local_clip_hash "$local_kind" "$clip_in") post_conflict=0 - if [ "$local_kind" != "empty" ] && [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then + if [ "$local_kind" != "empty" ] && [ "$local_kind" != "files_hosted" ] && + [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then + upload_file="$clip_in" + post_timeout=5 ct="text/plain; charset=utf-8" - [ "$local_kind" = "png" ] && ct="image/png" - set -- - if [ -n "$last_server_seq" ]; then - set -- -H "X-Clip-Base-Seq: $last_server_seq" + skip_upload=0 + if [ "$local_kind" = "files" ]; then + if [ "${clip_sync_files:-1}" != "1" ] || [ "${clip_direction:-bidirectional}" = "host-to-guest" ]; then + last_local_hash="$cur_hash" + skip_upload=1 + else + upload_file="$TMP_DIR/clip_upload.tar" + pack_rc=0 + pack_local_files_tar "$clip_in" "$upload_file" || pack_rc=$? + if [ "$pack_rc" -eq 2 ]; then + last_local_hash="$cur_hash" + skip_upload=1 + elif [ "$pack_rc" -ne 0 ]; then + skip_upload=1 + else + ct="application/x-tar" + post_timeout=60 + fi + fi + elif [ "$local_kind" = "png" ]; then + ct="image/png" + fi + if [ "$skip_upload" -eq 0 ]; then + set -- + if [ -n "$last_server_seq" ]; then + set -- -H "X-Clip-Base-Seq: $last_server_seq" + fi + code=$(curl -sS -m "$post_timeout" -X POST -D "$hdr_out" -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $REIMS_TOKEN" \ + -H "Content-Type: $ct" ${1+"$@"} \ + --data-binary "@$upload_file" \ + "$REIMS_HOST_URL/v1/clipboard" 2>/dev/null) || code=000 + [ "$local_kind" != "files" ] || rm -f "$upload_file" + case "$code" in + 200) + last_local_hash="$cur_hash" + last_server_hash=$(clip_header x-clip-hash) + last_server_seq=$(clip_header x-clip-seq) + return 0 + ;; + 204|413) + last_local_hash="$cur_hash" + ;; + 409) + post_conflict=1 + ;; + esac fi - code=$(curl -sS -m 5 -X POST -D "$hdr_out" -o /dev/null -w '%{http_code}' \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - -H "Content-Type: $ct" ${1+"$@"} \ - --data-binary "@$clip_in" \ - "$REIMS_HOST_URL/v1/clipboard" 2>/dev/null) || code=000 - case "$code" in - 200) - last_local_hash="$cur_hash" - last_server_hash=$(clip_header x-clip-hash) - last_server_seq=$(clip_header x-clip-seq) - return 0 - ;; - 204|413) - last_local_hash="$cur_hash" - ;; - 409) - post_conflict=1 - ;; - esac fi + accept_param="image" + if [ "${clip_sync_files:-1}" = "1" ]; then + accept_param="image,files" + fi # Long-poll up to 2s: host changes return immediately (~150ms), idle stays quiet. code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \ -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=image" 2>/dev/null) || code=000 + "$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=$accept_param" 2>/dev/null) || code=000 case "$code" in 200) new_hash=$(clip_header x-clip-hash) @@ -666,7 +1184,20 @@ sync_clipboard() { return 0 fi if [ "$new_hash" != "$cur_hash" ]; then - if [ "$new_kind" = "png" ]; then + if [ "$new_kind" = "files" ]; then + apply_rc=0 + apply_remote_clip_files "$clip_out" || apply_rc=$? + if [ "$apply_rc" -eq 2 ]; then + last_server_hash="$new_hash" + last_server_seq="$new_seq" + if [ -z "$last_local_hash" ]; then + last_local_hash="$cur_hash" + fi + return 0 + elif [ "$apply_rc" -ne 0 ]; then + return 0 + fi + elif [ "$new_kind" = "png" ]; then write_local_png "$clip_out" || return 0 else pbcopy <"$clip_out" 2>/dev/null || return 0 @@ -711,6 +1242,7 @@ text_input_loop() { hdr="$TMP_DIR/txt_hdr" body="$TMP_DIR/txt_body" bak="$TMP_DIR/txt_clip_bak" + bak_files="$TMP_DIR/txt_clip_files_bak" cur_chk="$TMP_DIR/txt_clip_chk" while :; do load_conf @@ -724,7 +1256,21 @@ text_input_loop() { if [ "$code" = "200" ]; then input_id=$(awk 'tolower($1)=="x-input-id:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr") : > "$INJECT_LOCK" - pbpaste >"$bak" 2>/dev/null || : >"$bak" + rm -f "$bak" "$bak_files" + bak_kind="other" + pre_info=$(osascript -e 'clipboard info' 2>/dev/null || true) + case "$pre_info" in + *furl*|*NSFilenamesPboardType*) + if backup_clip_files "$bak_files"; then + bak_kind="files" + fi + ;; + *utf8*|*"Unicode text"*|*string*) + if pbpaste >"$bak" 2>/dev/null && [ -s "$bak" ]; then + bak_kind="text" + fi + ;; + esac pbcopy <"$body" 2>/dev/null || true inj_hash=$(hash_file "$body") if [ -n "$input_id" ]; then @@ -732,13 +1278,17 @@ text_input_loop() { -H "Authorization: Bearer $REIMS_TOKEN" \ "$REIMS_HOST_URL/v1/text-input/ack?id=$input_id" >/dev/null 2>&1 || true fi - # Restore prior text clipboard unless user copied something else during paste. + # Restore prior clipboard (or clear temporary injected text) unless user copied something else during paste. pbpaste >"$cur_chk" 2>/dev/null || : >"$cur_chk" cur_after=$(hash_file "$cur_chk") - if [ "$cur_after" = "$inj_hash" ] && [ -s "$bak" ]; then - pbcopy <"$bak" 2>/dev/null || true + if [ "$cur_after" = "$inj_hash" ]; then + case "$bak_kind" in + files) restore_clip_files "$bak_files" ;; + text) pbcopy <"$bak" 2>/dev/null || true ;; + *) clear_local_clipboard ;; + esac fi - rm -f "$INJECT_LOCK" 2>/dev/null || true + rm -f "$bak_files" "$INJECT_LOCK" 2>/dev/null || true elif [ "$code" != "204" ]; then sleep 1 fi @@ -787,6 +1337,7 @@ FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" DESKTOP_LINK="$HOME/Desktop/ReimsShare" +CLIP_MOUNT="$APP_DIR/clip_mount" ` + guestIdentityHelpers + guestURLencode + folderMountHelpers + shareUnmountScript + ` if [ ! -f "$SRC/config" ] || [ ! -f "$SRC/guest-tools.sh" ]; then @@ -864,7 +1415,7 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST . "$APP_DIR/config" if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then echo "Reims Guest Tools installed and connected!" - echo "Clipboard: UTF-8 text + PNG screenshots (two-way)" + echo "Clipboard: UTF-8 text + PNG screenshots + files (two-way)" echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)" echo "Prevent-sleep: controlled live from Reims-Go host UI" else @@ -906,6 +1457,7 @@ DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" +CLIP_MOUNT="$APP_DIR/clip_mount" DNS_PLIST=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist DNS_DIR=/private/etc/reims-host-dns if [ -f "$DNS_PLIST" ] || [ -f "$DNS_DIR/dns-proxy.previous-dns" ]; then @@ -956,6 +1508,14 @@ const shareUnmountScript = ` unmount_reims_shares() ( unmount_failed=0 vm_route="/dav/$(urlencode "${REIMS_VM:-}")" + clip_route="/dav-clip/$(urlencode "${REIMS_VM:-}")" + if [ -n "${CLIP_MOUNT:-}" ] && is_reims_dav_mounted "$CLIP_MOUNT" "$clip_route/"; then + if unmount_shared_folder "$CLIP_MOUNT"; then + rmdir "$CLIP_MOUNT" 2>/dev/null || true + else + unmount_failed=1 + fi + fi if is_reims_dav_mounted "$SHARE_MOUNT" "$vm_route/"; then unmount_shared_folder "$SHARE_MOUNT" || unmount_failed=1 fi diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index cae340a..bda5f53 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -53,12 +53,14 @@ const ( ClipEmpty ClipKind = "" ClipText ClipKind = "text" ClipPNG ClipKind = "png" + ClipFiles ClipKind = "files" ) -// ClipPayload holds a single clipboard item (either UTF-8 text or PNG bytes). +// ClipPayload holds a single clipboard item (UTF-8 text, PNG bytes, or host file paths). type ClipPayload struct { - Kind ClipKind - Data []byte + Kind ClipKind + Data []byte + Files []string } // Clipboard abstracts host OS clipboard reads/writes for testing. @@ -299,6 +301,10 @@ type Server struct { onStatusChange func(vmName string) hostDNSConfig HostDNSConfig hostDNS hostDNS + clipStagingDir string + clipHostBatches map[string][]*clipHostBatch + clipGuestBatches map[string][]clipGuestBatch + clipDAVHandlers map[string]*clipDAVEntry } // NewServer constructs a Guest Tools HTTP bridge with clipboard active by default. @@ -317,8 +323,12 @@ func NewServer(clip Clipboard) *Server { vmClipPolicies: make(map[string]ClipboardPolicy), clipNotify: make(chan struct{}), hostDNS: defaultHostDNS, + clipHostBatches: make(map[string][]*clipHostBatch), + clipGuestBatches: make(map[string][]clipGuestBatch), + clipDAVHandlers: make(map[string]*clipDAVEntry), } s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard + s.dynamicRoutes["/dav-clip/"] = s.handleClipWebDAV return s } @@ -379,6 +389,7 @@ func (s *Server) Start(preferredPort int) (int, error) { mux.HandleFunc("/v1/file", s.handleFile) mux.HandleFunc("/dav/", s.handleWebDAV) mux.HandleFunc("/dav-folders/", s.handleFolderWebDAV) + mux.HandleFunc("/dav-clip/", s.dispatchDynamicRoute("/dav-clip/", "clipboard")) s.httpSrv = &http.Server{ Handler: localSecurityMiddleware(mux), ReadHeaderTimeout: 10 * time.Second, @@ -414,6 +425,8 @@ func (s *Server) watchClipboardLoop(ctx context.Context) { defer s.watcherCount.Add(-1) ticker := time.NewTicker(150 * time.Millisecond) defer ticker.Stop() + pruneTicker := time.NewTicker(1 * time.Minute) + defer pruneTicker.Stop() lastSeq := s.clip.SequenceNumber() for { select { @@ -425,6 +438,8 @@ func (s *Server) watchClipboardLoop(ctx context.Context) { lastSeq = seq s.broadcastClipChange() } + case now := <-pruneTicker.C: + s.pruneExpiredClipStaging(now) } } } @@ -469,6 +484,7 @@ func (s *Server) Close(ctx context.Context) error { if cancel != nil { cancel() } + s.clearAllClipFiles() s.broadcastClipChange() if srv == nil { return nil @@ -557,6 +573,9 @@ func (s *Server) RegisterVM(cfg VMConfig) { delete(s.davCache, davKey) } } + if cur.token != cfg.Token { + delete(s.clipDAVHandlers, key) + } cur.token = cfg.Token cur.sharedDir = cfg.SharedDir cur.sharedRoot = root @@ -589,6 +608,7 @@ func (s *Server) UnregisterVM(vmKey string) { } } s.mu.Unlock() + s.clearVMClipFiles(key) } // SetHostTextHandler registers a callback invoked when a host-side window hook @@ -876,6 +896,8 @@ func textHash(s string) string { func payloadHash(p ClipPayload) string { switch p.Kind { + case ClipFiles: + return clipFilesPayloadHash(p.Files) case ClipPNG: h := sha256.New() h.Write([]byte("png:")) @@ -900,6 +922,9 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) { if policy.SyncImages { caps = append([]string{"clipboard-png"}, caps...) } + if policy.SyncFiles { + caps = append([]string{"clipboard-files"}, caps...) + } } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ @@ -923,19 +948,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 + "/", + "clip_webdav_path": "/dav-clip/" + 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.SyncFiles, + "clipboard_max_file_bytes": policy.MaxFileBytes, }) } @@ -1003,7 +1031,12 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { } } -func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) { +func (s *Server) readClipboardState(wantImage, wantFiles bool) (ClipPayload, uint32, error) { + if clip, ok := s.clip.(interface { + readClipboardOpts(bool, bool) (ClipPayload, uint32, error) + }); ok { + return clip.readClipboardOpts(wantImage, wantFiles) + } if clip, ok := s.clip.(interface { readClipboard(bool) (ClipPayload, uint32, error) }); ok { @@ -1041,13 +1074,19 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { } func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) { + if batchID := strings.TrimSpace(r.URL.Query().Get("batch")); batchID != "" { + s.serveClipboardBatchTar(w, r, vmKey, batchID) + return + } waitSec, err := strconv.Atoi(r.URL.Query().Get("wait")) if err != nil { waitSec = 0 } deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second) - wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") || + acceptRaw := r.URL.Query().Get("accept") + wantsImage := acceptQueryHas(acceptRaw, "image") || strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png") + wantsFiles := acceptQueryHas(acceptRaw, "files") since := r.URL.Query().Get("since") for { @@ -1071,39 +1110,70 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri } wantImage := wantsImage && policy.SyncImages - payload, seq, err := s.readClipboardState(wantImage) + wantFiles := wantsFiles && policy.SyncFiles + payload, seq, err := s.readClipboardState(wantImage, wantFiles) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) return } - syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG && - wantImage && len(payload.Data) <= policy.MaxImageBytes) - if syncable { - h := payloadHash(payload) - if since != h || time.Until(deadline) <= 0 { - setClipboardSeq(w, seq) - w.Header().Set("X-Clip-Hash", h) - w.Header().Set("X-Clip-Kind", string(payload.Kind)) - s.touchLastSeen(vmKey) - if since == h { - w.WriteHeader(http.StatusNotModified) + if payload.Kind == ClipFiles && wantFiles { + if batch, ok := s.registerOrGetClipBatch(vmKey, payload.Files, policy.MaxFileBytes); ok { + h := batch.hash + if since != h || time.Until(deadline) <= 0 { + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Hash", h) + w.Header().Set("X-Clip-Kind", string(ClipFiles)) + s.touchLastSeen(vmKey) + if since == h { + w.WriteHeader(http.StatusNotModified) + return + } + atomic.AddUint64(&s.clipStatsH2G, 1) + w.Header().Set("Content-Type", "application/json; charset=utf-8") + _ = json.NewEncoder(w).Encode(clipBatchManifest{ + Batch: batch.id, + Items: batch.order, + TotalBytes: batch.totalBytes, + ExceedsTarLimit: batch.exceedsTarLimit, + }) return } - atomic.AddUint64(&s.clipStatsH2G, 1) - if payload.Kind == ClipPNG { - w.Header().Set("Content-Type", "image/png") - } else { - w.Header().Set("Content-Type", "text/plain; charset=utf-8") + } else if time.Until(deadline) <= 0 { + s.touchLastSeen(vmKey) + setClipboardSeq(w, seq) + w.WriteHeader(http.StatusNotModified) + return + } + } else { + syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG && + wantImage && len(payload.Data) <= policy.MaxImageBytes) + if syncable { + h := payloadHash(payload) + if since != h || time.Until(deadline) <= 0 { + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Hash", h) + w.Header().Set("X-Clip-Kind", string(payload.Kind)) + s.touchLastSeen(vmKey) + if since == h { + w.WriteHeader(http.StatusNotModified) + return + } + atomic.AddUint64(&s.clipStatsH2G, 1) + if payload.Kind == ClipPNG { + w.Header().Set("Content-Type", "image/png") + } else { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + } + _, _ = w.Write(payload.Data) + return } - _, _ = w.Write(payload.Data) + } else if time.Until(deadline) <= 0 { + s.touchLastSeen(vmKey) + setClipboardSeq(w, seq) + w.WriteHeader(http.StatusNotModified) return } - } else if time.Until(deadline) <= 0 { - s.touchLastSeen(vmKey) - setClipboardSeq(w, seq) - w.WriteHeader(http.StatusNotModified) - return } } else if time.Until(deadline) <= 0 { // Keep guest-to-host-only agents from busy-looping. @@ -1132,7 +1202,12 @@ func (s *Server) postClipboard(w http.ResponseWriter, r *http.Request, vmName st writeFeatureDisabled(w, "clipboard") return } - isImage := strings.Contains(strings.ToLower(r.Header.Get("Content-Type")), "image/png") + ct := strings.ToLower(r.Header.Get("Content-Type")) + if strings.Contains(ct, "application/x-tar") || strings.Contains(ct, "application/tar") { + s.postClipboardFiles(w, r, vmName, policy) + return + } + isImage := strings.Contains(ct, "image/png") if policy.Direction == ClipboardHostToGuest || (isImage && !policy.SyncImages) { w.WriteHeader(http.StatusNoContent) return @@ -1203,12 +1278,16 @@ func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint3 if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } - current, seq, err := s.readClipboardState(true) + current, seq, err := s.readClipboardState(true, true) if err == nil { if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } - if current.Kind == payload.Kind && bytes.Equal(current.Data, payload.Data) { + if payload.Kind == ClipFiles { + if clipPayloadEqual(current, payload) { + return seq, nil + } + } else if current.Kind == payload.Kind && bytes.Equal(current.Data, payload.Data) { return seq, nil } } @@ -1222,9 +1301,16 @@ func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint3 if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } - if payload.Kind == ClipPNG { + switch payload.Kind { + case ClipFiles: + if fc, ok := s.clip.(interface{ WriteFiles([]string) error }); ok { + err = fc.WriteFiles(payload.Files) + } else { + err = errors.New("clipboard does not support file payloads") + } + case ClipPNG: err = s.clip.WritePNG(payload.Data) - } else { + default: err = s.clip.WriteText(string(payload.Data)) } seq = s.clip.SequenceNumber() diff --git a/internal/guesttools/transport.go b/internal/guesttools/transport.go index 921fd68..95f370d 100644 --- a/internal/guesttools/transport.go +++ b/internal/guesttools/transport.go @@ -18,21 +18,32 @@ const ( ClipboardGuestToHost ClipboardDirection = "guest-to-host" ) +const ( + DefaultClipboardMaxFileBytes = 128 << 20 // 128 MiB + MinClipboardMaxFileMB = 1 + MaxClipboardMaxFileMB = 512 + MaxClipboardMaxFileBytes = MaxClipboardMaxFileMB << 20 // 512 MiB +) + // ClipboardPolicy configures clipboard sync globally or per VM (§5.4). type ClipboardPolicy struct { Enabled bool `json:"enabled"` 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"` } -// DefaultClipboardPolicy returns the default bidirectional text+image policy. +// DefaultClipboardPolicy returns the default bidirectional text+image+files policy. func DefaultClipboardPolicy() ClipboardPolicy { return ClipboardPolicy{ Enabled: true, Direction: ClipboardBidirectional, SyncImages: true, MaxImageBytes: MaxClipboardBytes, + SyncFiles: true, + MaxFileBytes: DefaultClipboardMaxFileBytes, } } @@ -51,6 +62,7 @@ func NewTransportServer(clip Clipboard) *Server { s := NewServer(clip) s.clipboardActive = false delete(s.dynamicRoutes, "/v1/clipboard") + delete(s.dynamicRoutes, "/dav-clip/") s.globalClipPolicy = DefaultClipboardPolicy() s.globalClipPolicy.Enabled = false return s @@ -92,6 +104,7 @@ func (s *Server) SetClipboardActive(active bool) { if active { s.globalClipPolicy.Enabled = true s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard + s.dynamicRoutes["/dav-clip/"] = s.handleClipWebDAV if s.listener != nil && s.watchCancel == nil { watchCtx, watchCancel := context.WithCancel(context.Background()) s.watchCancel = watchCancel @@ -103,6 +116,7 @@ func (s *Server) SetClipboardActive(active bool) { } s.globalClipPolicy.Enabled = false delete(s.dynamicRoutes, "/v1/clipboard") + delete(s.dynamicRoutes, "/dav-clip/") cancel := s.watchCancel s.watchCancel = nil s.mu.Unlock() @@ -110,6 +124,7 @@ func (s *Server) SetClipboardActive(active bool) { if cancel != nil { cancel() } + s.clearAllClipFiles() s.broadcastClipChange() } @@ -130,6 +145,13 @@ func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) { p = normalizeClipboardPolicy(p) s.mu.Lock() s.globalClipPolicy = p + if !p.Enabled || !p.SyncFiles || p.Direction == ClipboardGuestToHost { + for k := range s.clipHostBatches { + if ov, hasOv := s.vmClipPolicies[k]; !hasOv || !ov.Enabled || !ov.SyncFiles || ov.Direction == ClipboardGuestToHost { + delete(s.clipHostBatches, k) + } + } + } s.mu.Unlock() s.broadcastClipChange() } @@ -141,10 +163,15 @@ func (s *Server) SetVMClipboardPolicy(vmName string, p *ClipboardPolicy) { if s.vmClipPolicies == nil { s.vmClipPolicies = make(map[string]ClipboardPolicy) } + eff := s.globalClipPolicy if p == nil { delete(s.vmClipPolicies, vmName) } else { - s.vmClipPolicies[vmName] = normalizeClipboardPolicy(*p) + eff = normalizeClipboardPolicy(*p) + s.vmClipPolicies[vmName] = eff + } + if !eff.Enabled || !eff.SyncFiles || eff.Direction == ClipboardGuestToHost { + delete(s.clipHostBatches, vmName) } s.mu.Unlock() s.broadcastClipChange() @@ -186,6 +213,9 @@ func normalizeClipboardPolicy(p ClipboardPolicy) ClipboardPolicy { if p.MaxImageBytes <= 0 || p.MaxImageBytes > MaxClipboardBytes { p.MaxImageBytes = MaxClipboardBytes } + if p.MaxFileBytes <= 0 || p.MaxFileBytes > MaxClipboardMaxFileBytes { + p.MaxFileBytes = DefaultClipboardMaxFileBytes + } return p } diff --git a/internal/guesttools/transport_test.go b/internal/guesttools/transport_test.go index 68e05a4..b5a10e7 100644 --- a/internal/guesttools/transport_test.go +++ b/internal/guesttools/transport_test.go @@ -51,19 +51,24 @@ func TestTransportClipboardToggleZeroResidueAndPolicy(t *testing.T) { } // Initially disabled: zero route, zero watcher, 503 feature_disabled response. - if srv.HasRoute("/v1/clipboard") || srv.IsClipboardWatcherRunning() { - t.Fatal("expected clipboard route and watcher inactive on NewTransportServer") + if srv.HasRoute("/v1/clipboard") || srv.HasRoute("/dav-clip/") || srv.IsClipboardWatcherRunning() { + t.Fatal("expected clipboard routes and watcher inactive on NewTransportServer") } resp := doReq(http.MethodGet, "/v1/clipboard", nil, "") if resp.StatusCode != http.StatusServiceUnavailable { t.Fatalf("disabled clipboard status = %d, want 503", resp.StatusCode) } _ = resp.Body.Close() + resp = doReq("PROPFIND", "/dav-clip/mac1/", nil, "") + if resp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("disabled /dav-clip/ status = %d, want 503", resp.StatusCode) + } + _ = resp.Body.Close() // Enable clipboard live while server is running. srv.SetClipboardActive(true) - if !srv.HasRoute("/v1/clipboard") { - t.Fatal("expected /v1/clipboard route active") + if !srv.HasRoute("/v1/clipboard") || !srv.HasRoute("/dav-clip/") { + t.Fatal("expected /v1/clipboard and /dav-clip/ routes active") } // Verify /v1/config advertises clipboard_enabled=true. resp = doReq(http.MethodGet, "/v1/config", nil, "") @@ -89,8 +94,8 @@ func TestTransportClipboardToggleZeroResidueAndPolicy(t *testing.T) { // Disable clipboard live: route gone, watcher stops cleanly, 503 returned. srv.SetClipboardActive(false) - if srv.HasRoute("/v1/clipboard") { - t.Fatal("expected /v1/clipboard route removed after disable") + if srv.HasRoute("/v1/clipboard") || srv.HasRoute("/dav-clip/") { + t.Fatal("expected clipboard routes removed after disable") } deadline := time.Now().Add(2 * time.Second) for srv.IsClipboardWatcherRunning() && time.Now().Before(deadline) { diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index ec2854e..d63df78 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -8,6 +8,7 @@ package builtin import ( "context" "fmt" + "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/config" @@ -129,6 +130,11 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo srv = s } else { srv = guesttools.NewTransportServer(nil) + if cb.GetConfig != nil { + if cfg := cb.GetConfig(); cfg.DataRoot != "" { + srv.SetClipStagingDir(filepath.Join(cfg.TempDir(), "clip-files")) + } + } } sc.Provide(ServiceGuestToolsTransport, "1.0.0", srv) sc.OnDispose(func() { @@ -201,6 +207,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, @@ -208,8 +216,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", @@ -219,15 +227,15 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Settings: &plugin.SettingsSchema{ Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"}, Group: "collaboration", - Scope: "vm", - Order: []string{"enabled", "direction", "sync_images", "max_image_mb"}, + Scope: "both", + Order: []string{"enabled", "direction", "sync_images", "max_image_mb", "sync_files", "max_file_mb"}, Properties: map[string]plugin.SettingProperty{ "enabled": { Type: "boolean", Title: plugin.LocalizedText{ZhCN: "启用剪贴板互通", EnUS: "Enable clipboard sync"}, Default: true, Effect: "immediate", - Scope: "vm", + Scope: "both", Group: "collaboration", }, "direction": { @@ -241,7 +249,7 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo }, Default: "bidirectional", Effect: "immediate", - Scope: "vm", + Scope: "both", Group: "collaboration", }, "sync_images": { @@ -249,7 +257,7 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Title: plugin.LocalizedText{ZhCN: "同步剪贴板图片", EnUS: "Sync clipboard images"}, Default: true, Effect: "immediate", - Scope: "vm", + Scope: "both", Group: "collaboration", }, "max_image_mb": { @@ -259,7 +267,33 @@ func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) boo Minimum: &minMB, Maximum: &maxMB, Effect: "immediate", - Scope: "vm", + Scope: "both", + Group: "collaboration", + }, + "sync_files": { + Type: "boolean", + Title: plugin.LocalizedText{ZhCN: "同步剪贴板文件", EnUS: "Sync clipboard files"}, + Description: plugin.LocalizedText{ + ZhCN: "Windows 到 macOS 按需只读挂载免预拷贝,macOS 到 Windows 受单次大小上限约束", + EnUS: "On-demand read-only mount from Windows to macOS; macOS to Windows honors the size limit", + }, + Default: true, + Effect: "immediate", + Scope: "both", + Group: "collaboration", + }, + "max_file_mb": { + Type: "integer", + Title: plugin.LocalizedText{ZhCN: "客体文件大小上限 (MB)", EnUS: "Max guest file size (MB)"}, + Description: plugin.LocalizedText{ + ZhCN: "限制从 macOS 复制到 Windows 及 WebDAV 不可用时降级传输的单次总大小", + EnUS: "Maximum total size copied at once from macOS to Windows and WebDAV fallback", + }, + Default: 128, + Minimum: &minFileMB, + Maximum: &maxFileMB, + Effect: "immediate", + Scope: "both", Group: "collaboration", }, }, diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index 0de0e0a..4d52fd3 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -35,15 +35,15 @@ func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) { if !reg.IsActive(IDGuestTools) || !reg.IsActive(IDClipboard) { t.Fatalf("expected guest-tools and clipboard active") } - if !gtSrv.HasRoute("/v1/clipboard") || !gtSrv.IsClipboardActive() { - t.Fatal("expected clipboard route mounted while builtin.bridge.clipboard is active") + if !gtSrv.HasRoute("/v1/clipboard") || !gtSrv.HasRoute("/dav-clip/") || !gtSrv.IsClipboardActive() { + t.Fatal("expected clipboard routes mounted while builtin.bridge.clipboard is active") } // Disable clipboard live -> route removed, watcher stopped, zero residue! if err := reg.SetDesired(context.Background(), IDClipboard, false); err != nil { t.Fatal(err) } - if gtSrv.HasRoute("/v1/clipboard") || gtSrv.IsClipboardActive() { + if gtSrv.HasRoute("/v1/clipboard") || gtSrv.HasRoute("/dav-clip/") || gtSrv.IsClipboardActive() { t.Fatal("expected zero clipboard route residue after disabling builtin.bridge.clipboard") } deadline := time.Now().Add(2 * time.Second) @@ -193,3 +193,25 @@ func TestCorePluginHiddenFromVisibleList(t *testing.T) { t.Fatalf("Info(core) = %+v, %v", info, ok) } } + +func TestBuiltinClipboardFileSettingsSchema(t *testing.T) { + reg := plugin.NewRegistry(nil) + if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil { + t.Fatalf("RegisterAll: %v", err) + } + info, ok := reg.Info(IDClipboard) + if !ok || info.Settings == nil { + t.Fatalf("missing settings schema on %s", IDClipboard) + } + if info.Settings.Scope != "both" { + t.Fatalf("clipboard schema scope = %q, want both", info.Settings.Scope) + } + syncFiles, ok := info.Settings.Properties["sync_files"] + if !ok || syncFiles.Default != true || syncFiles.Scope != "both" { + t.Fatalf("unexpected sync_files property: %+v", syncFiles) + } + maxFileMB, ok := info.Settings.Properties["max_file_mb"] + if !ok || maxFileMB.Default != 128 || maxFileMB.Minimum == nil || *maxFileMB.Minimum != 1 || maxFileMB.Maximum == nil || *maxFileMB.Maximum != 512 { + t.Fatalf("unexpected max_file_mb property: %+v", maxFileMB) + } +} diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 87ed7fe..f4e95f9 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -926,13 +926,14 @@ 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 { - out[k] = v - } - } else if vmMap := rec.VMSettings[vmName]; vmMap != nil { - for k, v := range vmMap { - out[k] = v + for k, v := range rec.AppSettings { + out[k] = v + } + if vmName != "" { + if vmMap := rec.VMSettings[vmName]; vmMap != nil { + for k, v := range vmMap { + out[k] = v + } } } } @@ -1104,10 +1105,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 } From 8c823d98fb638d89b484c832a72fb704f6688d95 Mon Sep 17 00:00:00 2001 From: staytomorrow Date: Thu, 3 Dec 2026 00:03:23 +0800 Subject: [PATCH 2/3] fix(clipboard): align Guest Tools v14 changelog and rebind staging dir after setup --- changes/clipboard-file-sync.json | 6 +- internal/app/guesttools_flow.go | 8 +- internal/app/guesttools_toggle_test.go | 102 +++++++++++++++++++++++++ internal/guesttools/clipboard_files.go | 4 + internal/plugin/manager.go | 24 +++++- 5 files changed, 134 insertions(+), 10 deletions(-) diff --git a/changes/clipboard-file-sync.json b/changes/clipboard-file-sync.json index cafbbaf..77ed69b 100644 --- a/changes/clipboard-file-sync.json +++ b/changes/clipboard-file-sync.json @@ -1,7 +1,7 @@ { "group": "new", "order": 70, - "authors": ["yxc0915"], - "zh": "剪贴板互通支持在 Windows 与 macOS 之间双向复制粘贴文件与文件夹,宿主到虚拟机按需只读挂载免预拷贝,虚拟机到宿主默认限制单次 `128 MB`(可在插件设置中于 `1–512 MB` 间调节),已安装的虚拟机需更新至第 13 版 Guest Tools。", - "en": "Sync copied files and folders both ways in Clipboard Sync, mounting on demand from Windows to macOS without pre-copying and capping macOS-to-Windows transfers at `128 MB` by default (adjustable from `1` to `512 MB` in plugin settings); installed VMs require Guest Tools v13." + "authors": ["staytomorrow"], + "zh": "剪贴板互通支持在 Windows 与 macOS 之间双向复制粘贴文件与文件夹,宿主到虚拟机按需只读挂载免预拷贝,虚拟机到宿主默认限制单次 `128 MB`(可在插件设置中于 `1–512 MB` 间调节),已安装的虚拟机需更新至第 14 版 Guest Tools。", + "en": "Sync copied files and folders both ways in Clipboard Sync, mounting on demand from Windows to macOS without pre-copying and capping macOS-to-Windows transfers at `128 MB` by default (adjustable from `1` to `512 MB` in plugin settings); installed VMs require Guest Tools v14." } diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 68ba348..99cf6f7 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -108,9 +108,6 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created } else { srv = guesttools.NewServer(nil) } - if a.cfg != nil && a.cfg.DataRoot != "" && !a.needsSetup && !a.root.ReadOnly { - srv.SetClipStagingDir(filepath.Join(a.cfg.TempDir(), "clip-files")) - } srv.SetHostDropHandler(a.handleHostDrop) srv.SetDropAckHandler(a.handleHostDropAck) srv.SetDropPasteHandler(a.handleHostDropPaste) @@ -128,7 +125,12 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() }) created = true } + stagingDir := "" + if a.cfg != nil && a.cfg.DataRoot != "" && !a.needsSetup && !a.root.ReadOnly { + stagingDir = filepath.Join(a.cfg.TempDir(), "clip-files") + } a.mu.Unlock() + srv.SetClipStagingDir(stagingDir) port, err = srv.Start(guesttools.DefaultPort) if err != nil { diff --git a/internal/app/guesttools_toggle_test.go b/internal/app/guesttools_toggle_test.go index 51a8440..ea1fead 100644 --- a/internal/app/guesttools_toggle_test.go +++ b/internal/app/guesttools_toggle_test.go @@ -1,7 +1,13 @@ package app import ( + "archive/tar" + "bytes" "context" + "fmt" + "net/http" + "os" + "path/filepath" "strings" "testing" "time" @@ -73,3 +79,99 @@ func TestGuestToolsBridgeFollowsPluginSwitch(t *testing.T) { t.Fatal("plugin switched back off: Guest Tools still reported as available") } } + +type stubFileClip struct { + files []string + seq uint32 +} + +func (c *stubFileClip) ReadText() (string, error) { return "", nil } +func (c *stubFileClip) WriteText(string) error { c.seq++; return nil } +func (c *stubFileClip) WritePNG([]byte) error { c.seq++; return nil } +func (c *stubFileClip) SequenceNumber() uint32 { return c.seq } +func (c *stubFileClip) WriteFiles(p []string) error { c.files = p; c.seq++; return nil } +func (c *stubFileClip) Read() (guesttools.ClipPayload, error) { + if len(c.files) > 0 { + return guesttools.ClipPayload{Kind: guesttools.ClipFiles, Files: c.files}, nil + } + return guesttools.ClipPayload{}, nil +} + +// Completing first-run setup without restarting must bind the clipboard file +// staging directory on the existing Server so guest-to-host file uploads do not +// fail with 503. +func TestGuestToolsServerConfiguresClipStagingAfterSetup(t *testing.T) { + suggestedDir := t.TempDir() + chosenDir := t.TempDir() + cfg := config.Default() + cfg.DataRoot = suggestedDir + clip := &stubFileClip{seq: 1} + srv := guesttools.NewServer(clip) + 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) + } + tok := "tok-setup-transition-000000000000000" + srv.RegisterVM(guesttools.VMConfig{VMName: "mac", Token: tok}) + + var tarBuf bytes.Buffer + tw := tar.NewWriter(&tarBuf) + content := []byte("after-setup") + if err := tw.WriteHeader(&tar.Header{Name: "doc.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: int64(len(content))}); err != nil { + t.Fatal(err) + } + _, _ = tw.Write(content) + _ = tw.Close() + + postTar := func() int { + req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/v1/clipboard", port), bytes.NewReader(tarBuf.Bytes())) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("Content-Type", "application/x-tar") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + return resp.StatusCode + } + + if code := postTar(); code != http.StatusServiceUnavailable { + t.Fatalf("before setup completion: got %d, want 503", code) + } + if entries := dirEntries(t, suggestedDir); len(entries) != 0 { + t.Fatalf("suggested folder written before setup: %v", entries) + } + + // Simulate finishing first-run setup onto chosenDir without restarting. + a.mu.Lock() + a.cfg.DataRoot = chosenDir + a.needsSetup = false + a.root.ReadOnly = false + a.mu.Unlock() + if _, _, _, err := a.startGuestToolsServer(); err != nil { + t.Fatal(err) + } + + if code := postTar(); code != http.StatusOK { + t.Fatalf("after setup completion without restart: got %d, want 200", code) + } + if len(clip.files) != 1 { + t.Fatalf("expected 1 unpacked clipboard file, got %v", clip.files) + } + if got, err := os.ReadFile(clip.files[0]); err != nil || string(got) != "after-setup" { + t.Fatalf("unpacked file content = %q, err=%v", got, err) + } + if !strings.HasPrefix(clip.files[0], filepath.Join(chosenDir, "tmp", "clip-files")) { + t.Fatalf("unpacked file path %q outside chosen DataRoot", clip.files[0]) + } +} diff --git a/internal/guesttools/clipboard_files.go b/internal/guesttools/clipboard_files.go index 8843c08..b4b1684 100644 --- a/internal/guesttools/clipboard_files.go +++ b/internal/guesttools/clipboard_files.go @@ -86,6 +86,10 @@ func (s *Server) SetClipStagingDir(dir string) { } s.mu.Lock() old := s.clipStagingDir + if old == clean { + s.mu.Unlock() + return + } s.clipStagingDir = clean s.clipGuestBatches = make(map[string][]clipGuestBatch) s.mu.Unlock() diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index f4e95f9..e747b9e 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -908,6 +908,16 @@ func (m *Manager) stateNotLoadedErr() error { // --- Settings store (app-scoped & vm-scoped, hiding x-secret on readback) --- +func settingAllowsBothScopes(schema *SettingsSchema, key string) bool { + if schema == nil { + return false + } + if prop, ok := schema.Properties[key]; ok && 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,10 +936,16 @@ func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[str } if m.state != nil { if rec := m.state.Plugins[pluginID]; rec != nil { - for k, v := range rec.AppSettings { - out[k] = v - } - if vmName != "" { + if vmName == "" { + for k, v := range rec.AppSettings { + out[k] = v + } + } else { + for k, v := range rec.AppSettings { + if settingAllowsBothScopes(schema, k) { + out[k] = v + } + } if vmMap := rec.VMSettings[vmName]; vmMap != nil { for k, v := range vmMap { out[k] = v From 0dae99c3566a9771ea19e783cfc31f97fe11ddb9 Mon Sep 17 00:00:00 2001 From: staytomorrow Date: Thu, 3 Dec 2026 00:23:51 +0800 Subject: [PATCH 3/3] fix(clipboard): preserve active CF_HDROP staging batch during expiry prune --- internal/guesttools/clipboard_files.go | 49 ++++++++++++++++++++- internal/guesttools/clipboard_files_test.go | 33 ++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/internal/guesttools/clipboard_files.go b/internal/guesttools/clipboard_files.go index b4b1684..f2214ab 100644 --- a/internal/guesttools/clipboard_files.go +++ b/internal/guesttools/clipboard_files.go @@ -14,6 +14,7 @@ import ( "os" "path" "path/filepath" + "runtime" "slices" "strconv" "strings" @@ -135,13 +136,59 @@ func (s *Server) clearVMClipFiles(vmKey string) { } } +func batchDirOwnsAnyClipFile(batchDir string, clipFiles []string) bool { + if batchDir == "" || len(clipFiles) == 0 { + return false + } + cleanDir := filepath.Clean(batchDir) + prefix := cleanDir + string(filepath.Separator) + for _, f := range clipFiles { + cf := filepath.Clean(f) + if runtime.GOOS == "windows" { + if strings.EqualFold(cf, cleanDir) || (len(cf) > len(prefix) && strings.EqualFold(cf[:len(prefix)], prefix)) { + return true + } + } else if cf == cleanDir || strings.HasPrefix(cf, prefix) { + return true + } + } + return false +} + +func (s *Server) hasExpiredClipStaging(now time.Time) bool { + s.mu.RLock() + defer s.mu.RUnlock() + for _, list := range s.clipGuestBatches { + for _, b := range list { + if now.Sub(b.createdAt) > clipStagingMaxAge { + return true + } + } + } + return false +} + func (s *Server) pruneExpiredClipStaging(now time.Time) { + if !s.hasExpiredClipStaging(now) { + return + } + curPayload, _, err := s.readClipboardState(false, true) + if err != nil { + // If the host clipboard is transiently locked, defer pruning so we never + // delete a batch that is still referenced on CF_HDROP. + return + } + var activeFiles []string + if curPayload.Kind == ClipFiles { + activeFiles = curPayload.Files + } + var toRemove []string s.mu.Lock() for vmKey, list := range s.clipGuestBatches { kept := list[:0] for _, b := range list { - if now.Sub(b.createdAt) > clipStagingMaxAge { + if now.Sub(b.createdAt) > clipStagingMaxAge && !batchDirOwnsAnyClipFile(b.dir, activeFiles) { if b.dir != "" { toRemove = append(toRemove, b.dir) } diff --git a/internal/guesttools/clipboard_files_test.go b/internal/guesttools/clipboard_files_test.go index 1917982..abfda93 100644 --- a/internal/guesttools/clipboard_files_test.go +++ b/internal/guesttools/clipboard_files_test.go @@ -14,6 +14,7 @@ import ( "slices" "strings" "testing" + "time" ) func TestHDropEncodeDecodeRoundTrip(t *testing.T) { @@ -399,3 +400,35 @@ func TestClipboardGuestToHostTarUploadSecurityAndCleanup(t *testing.T) { t.Fatalf("expected staging dir %s removed on disable, stat err=%v", staging, err) } } + +func TestPruneExpiredClipStagingPreservesActiveClipboardBatch(t *testing.T) { + staging := filepath.Join(t.TempDir(), "tmp", "clip-files") + clip := &memClipboard{seq: 1} + srv := newClipboardTestServer(clip) + srv.SetClipStagingDir(staging) + + tarData := buildTestTar(t, []tarTestEntry{{name: "keep-me.txt", body: "still-on-clipboard"}}) + post := clipboardRequest(t, srv, http.MethodPost, "", "application/x-tar", "", tarData) + if post.Code != http.StatusOK { + t.Fatalf("tar POST = %d: %s", post.Code, post.Body.String()) + } + cur, _ := clip.Read() + if cur.Kind != ClipFiles || len(cur.Files) != 1 { + t.Fatalf("clipboard = %+v", cur) + } + activeFile := cur.Files[0] + + // Even past clipStagingMaxAge, pruning must keep the batch while it backs CF_HDROP. + future := time.Now().Add(clipStagingMaxAge + 5*time.Minute) + srv.pruneExpiredClipStaging(future) + if data, err := os.ReadFile(activeFile); err != nil || string(data) != "still-on-clipboard" { + t.Fatalf("active clipboard file removed prematurely: %q, err=%v", data, err) + } + + // Once the user copies something else, the expired batch is reclaimed cleanly. + _ = clip.WriteText("replaced") + srv.pruneExpiredClipStaging(future) + if _, err := os.Stat(filepath.Dir(activeFile)); !os.IsNotExist(err) { + t.Fatalf("expected expired inactive batch directory removed, stat err=%v", err) + } +}