diff --git a/.gitattributes b/.gitattributes index 30fbc8a..e3c3ab4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,7 @@ *.patch -text *.diff -text internal/guesttools/file_sync.sh text eol=lf +internal/guesttools/drop_agent.sh text eol=lf +internal/guesttools/drop_resolve.js text eol=lf internal/guesttools/*-Host-DNS.command text eol=lf internal/guesttools/dns-proxy.pl text eol=lf diff --git a/changes/window-drag-drop.json b/changes/window-drag-drop.json new file mode 100644 index 0000000..5a96a76 --- /dev/null +++ b/changes/window-drag-drop.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 0, + "authors": ["YinLiaoCo"], + "zh": "支持将 Windows 文件、文件夹、图片及文本或网址直接拖入 macOS 虚拟机窗口,提供宿主机零拷贝 WebDAV 映射、桌面直投、照片原生导入与跨应用隐身模拟粘贴。", + "en": "Support dragging Windows files, folders, images, and text or URLs directly into the macOS VM window with zero-copy host WebDAV shares, direct Desktop placement, native Photos import, and stealth cross-app paste." +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a262793..6ce29b9 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -194,6 +194,7 @@ export const App: React.FC = () => { logsOpenRef.current = logsOpen const [taskMap, setTaskMap] = useState>({}) const onTaskRef = useRef<(task: Task) => void>(() => {}) + const onHostDropAckRef = useRef<(ack: { status: string; error?: string }) => void>(() => {}) const notifiedTasks = useRef(new Map()) const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null) @@ -341,6 +342,15 @@ export const App: React.FC = () => { useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, []) const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const pushToast = toasts.push + useEffect(() => events.onHostDrop(({ delivered, mode }) => { + if (mode !== 'l1_share' || delivered.length === 0) return + const title = delivered.length === 1 + ? t(locale, 'toastFileDelivered', { name: delivered[0] }) + : t(locale, 'toastFilesDelivered', { n: delivered.length }) + pushToast({ kind: 'ok', title }) + }), [locale, pushToast]) + useEffect(() => events.onHostDropAck((ack) => onHostDropAckRef.current(ack)), []) const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime @@ -605,6 +615,9 @@ export const App: React.FC = () => { action: { label: tr('viewLogs'), onClick: () => openLogs('app') }, }) } + onHostDropAckRef.current = (ack) => { + if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '') + } const activeVMBusy = (name: string): VMAction | undefined => { const ops = busyOpsRef.current.get(name) diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index d0d70ee..b042fef 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 < 12 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 13 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/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index c1d00da..ee63db4 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -46,6 +46,7 @@ export const vmZh: Record = { "failCloneVM": "派生 CoW 副本失败", "failDelete": "删除失败", "failDiscardSuspend": "放弃挂起状态失败", + "failDrop": "拖放失败", "failEject": "弹出安装盘失败", "failEnterRecovery": "进入恢复模式失败", "failExportDiagnostics": "导出排障日志失败", @@ -274,6 +275,7 @@ export const vmEn: Record = { "failCloneVM": "Couldn’t create CoW clone", "failDelete": "Couldn’t delete", "failDiscardSuspend": "Couldn’t discard saved state", + "failDrop": "Couldn’t drop into the VM", "failEject": "Couldn’t eject the installer", "failEnterRecovery": "Couldn’t enter recovery mode", "failExportDiagnostics": "Couldn’t export diagnostics", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index fdf2d2e..c0e83fd 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -232,6 +232,7 @@ export type I18nKey = | "failDelete" | "failDiscardSuspend" | "failDownload" + | "failDrop" | "failEject" | "failEnterRecovery" | "failExportDiagnostics" diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 6eb8bd4..5964008 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -179,6 +179,8 @@ export interface MarketInstallProgress { } export const events = { + onHostDrop: (cb: (payload: { vm: string; drop_id: string; delivered: string[]; skipped?: string[]; mode: string }) => void) => eventsOn('reims:host-drop', cb), + onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb), onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb), onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb), onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb), diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index ada1fbf..65d49f8 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) } + srv.SetHostDropHandler(a.handleHostDrop) + srv.SetDropAckHandler(a.handleHostDropAck) + srv.SetDropPasteHandler(a.handleHostDropPaste) srv.SetHostTextHandler(func(vmKey, vmName, text string) { a.mu.Lock() mgr := a.pluginMgr @@ -182,6 +185,28 @@ func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string { } } +func (a *App) dropBridgeEnv(name, vmDir string, epoch uint64) []string { + if vmDir == "" { + return nil + } + srv, port, err := a.ensureGuestToolsBridge() + if err != nil || port <= 0 { + return nil + } + cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch) + if err != nil || cfg.Token == "" { + return nil + } + token := srv.HostDropToken(cfg.DriverID, name) + if token == "" { + return nil + } + return []string{ + fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port), + "REIMS_GO_DROP_TOKEN=" + token, + } +} + func (a *App) registerExistingGuestTools(ctx context.Context) { srv, port, err := a.ensureGuestToolsBridge() if err != nil { diff --git a/internal/app/host_drop.go b/internal/app/host_drop.go new file mode 100644 index 0000000..ad66949 --- /dev/null +++ b/internal/app/host_drop.go @@ -0,0 +1,359 @@ +package app + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/qmp" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +const MaxHostDropFileBytes int64 = 2 << 30 +const MaxHostDropTotalBytes int64 = 4 << 30 + +const MaxHostDropFolderFiles = 256 + +func dropSegment(s string) bool { + return filepath.IsLocal(s) && !strings.HasPrefix(s, ".") && + !strings.ContainsAny(s, "/\\\x00:\u003c\u003e|\"?*\r\n") +} + +var hostDropPublishMu sync.Mutex +var errDropSize = errors.New("host drop size limit exceeded") + +func validateHostDropPath(raw string) (string, error) { + if strings.TrimSpace(raw) == "" || strings.ContainsRune(raw, 0) || + strings.HasPrefix(strings.ReplaceAll(raw, "\\", "/"), "//") || !filepath.IsAbs(raw) { + return "", fmt.Errorf("%w: expected an absolute local path", guesttools.ErrInvalidHostDrop) + } + clean := filepath.Clean(raw) + st, err := os.Lstat(clean) + if err != nil { + return "", fmt.Errorf("%w: %v", guesttools.ErrInvalidHostDrop, err) + } + if guesttools.IsDropSymlink(st) { + return "", fmt.Errorf("%w: symbolic link", guesttools.ErrInvalidHostDrop) + } + return clean, nil +} + +func allocUniqueDropName(base string, splitExt bool, claim func(string) (bool, error)) (string, error) { + var ext string + if splitExt { + ext = filepath.Ext(base) + } + stem := strings.TrimSuffix(base, ext) + candidate := base + for n := 1; ; n++ { + claimed, err := claim(candidate) + if err != nil { + return "", err + } + if claimed { + return candidate, nil + } + candidate = fmt.Sprintf("%s (%d)%s", stem, n, ext) + } +} + +func uniqueDropEntryName(used map[string]struct{}, base string, isDir bool) string { + name, _ := allocUniqueDropName(base, !isDir, func(candidate string) (bool, error) { + if _, exists := used[candidate]; exists { + return false, nil + } + used[candidate] = struct{}{} + return true, nil + }) + return name +} + +func (a *App) handleHostDrop(vmKey, name string, req guesttools.HostDropRequest) (guesttools.HostDropResult, error) { + var id [16]byte + rand.Read(id[:]) + result := guesttools.HostDropResult{ + DropID: hex.EncodeToString(id[:]), Delivered: []string{}, + } + srv := a.currentGuestToolsServer() + hasListener := srv != nil && srv.HasDropEventListener(vmKey) + event := guesttools.DropEvent{ + DropID: result.DropID, DisplayIndex: req.DisplayIndex, NormX: req.NormX, + NormY: req.NormY, InImage: req.InImage, + } + if req.Text != "" { + result.Mode = "text_ignored" + event.Kind, event.Text = "text", req.Text + if hasListener && srv.EnqueueDropEvent(vmKey, event) { + result.Mode = "l2_text" + } + return result, nil + } + paths := make([]string, 0, len(req.Paths)) + for _, raw := range req.Paths { + path, err := validateHostDropPath(raw) + if err != nil { + return result, err + } + paths = append(paths, path) + } + if hasListener { + used := make(map[string]struct{}) + var entries []guesttools.DropShareEntry + for _, path := range paths { + st, err := os.Lstat(path) + if err != nil { + return result, err + } + base := filepath.Base(path) + if !dropSegment(base) || guesttools.IsDropSymlink(st) || (!st.IsDir() && !st.Mode().IsRegular()) { + result.Skipped = append(result.Skipped, base) + continue + } + alias := uniqueDropEntryName(used, base, st.IsDir()) + entries = append(entries, guesttools.DropShareEntry{Name: alias, HostPath: path, IsDir: st.IsDir()}) + result.Delivered = append(result.Delivered, alias) + } + if len(entries) > 0 { + if !srv.RegisterDropShare(vmKey, result.DropID, entries) { + result.Delivered = []string{} + return result, errors.New("could not register drop share") + } + event.Kind, event.WebDAVDrop = "files", true + event.Items, event.TargetPaths = result.Delivered, result.Delivered + if !srv.EnqueueDropEvent(vmKey, event) { + srv.RevokeDropShare(vmKey, result.DropID) + result.Delivered = []string{} + return result, errors.New("could not enqueue file drop") + } + result.Mode = "l2_webdav" + } + return result, nil + } + + result.Mode = "l1_share" + var total int64 + var fileCount int + sharedDir := a.vmSharedDir(name) + for _, path := range paths { + st, err := os.Lstat(path) + if err != nil { + return result, err + } + base := filepath.Base(path) + if !dropSegment(base) || guesttools.IsDropSymlink(st) || fileCount >= MaxHostDropFolderFiles { + result.Skipped = append(result.Skipped, base) + continue + } + if st.IsDir() { + folder, nested, size, err := stageDropFolder(sharedDir, path, MaxHostDropFolderFiles-fileCount, MaxHostDropTotalBytes-total) + if err != nil { + return result, err + } + if len(nested) == 0 { + result.Skipped = append(result.Skipped, base) + continue + } + total += size + result.Delivered = append(result.Delivered, folder) + fileCount += len(nested) + continue + } + if !st.Mode().IsRegular() { + result.Skipped = append(result.Skipped, base) + continue + } + delivered, size, err := a.deliverHostFileLimited(name, path, st, min(MaxHostDropFileBytes, MaxHostDropTotalBytes-total)) + if errors.Is(err, errDropSize) { + a.emitVMLog(name, fmt.Sprintf("Skipped %s: host drop size limit exceeded", base)) + result.Skipped = append(result.Skipped, base) + continue + } + if err != nil { + return result, err + } + total += size + fileCount++ + result.Delivered = append(result.Delivered, delivered) + } + a.emitVMLog(name, fmt.Sprintf("Host drop %s: delivered %d, skipped %d", result.DropID, len(result.Delivered), len(result.Skipped))) + if a.ctx != nil && len(result.Delivered) > 0 { + wailsRuntime.EventsEmit(a.ctx, "reims:host-drop", map[string]any{ + "vm": name, "drop_id": result.DropID, "delivered": result.Delivered, "skipped": result.Skipped, "mode": result.Mode, + }) + } + return result, nil +} + +func (a *App) currentGuestToolsServer() *guesttools.Server { + a.mu.Lock() + defer a.mu.Unlock() + return a.guestTools +} + +var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste + +func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error { + if _, running := a.currentVMPID(ctx, name); !running { + return fmt.Errorf("%s is not running", name) + } + d, err := a.GetVMDetail(name) + if err != nil { + return err + } + return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait) +} + +func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) { + revoke := ack.Status == "placed" || ack.Status == "cancelled" || ack.Status == "failed" + if srv := a.currentGuestToolsServer(); srv != nil && revoke { + srv.RevokeDropShare(vmKey, ack.DropID) + } + a.emitVMLog(name, fmt.Sprintf("Host drop %s: %s (%s)", ack.DropID, ack.Status, ack.TargetKind)) + if ack.Status != "cancelled" && a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:host-drop-ack", map[string]any{ + "vm": name, "drop_id": ack.DropID, "status": ack.Status, "target_kind": ack.TargetKind, + "target_label": ack.TargetLabel, "placed_names": ack.PlacedNames, "error": ack.Error, + }) + } +} + +func allocUniqueDir(parent, base string) (string, error) { + hostDropPublishMu.Lock() + defer hostDropPublishMu.Unlock() + return allocUniqueDropName(base, false, func(candidate string) (bool, error) { + err := os.Mkdir(filepath.Join(parent, candidate), 0o755) + if errors.Is(err, os.ErrExist) { + return false, nil + } + return err == nil, err + }) +} + +func stageDropFolder(shared, src string, count int, limit int64) (string, []string, int64, error) { + type entry struct { + rel string + st os.FileInfo + } + var files []entry + var estimated int64 + var walk func(string, int) error + walk = func(rel string, depth int) error { + dir := filepath.Join(src, rel) + children, err := os.ReadDir(dir) + if err != nil { + return err + } + for _, child := range children { + if len(files) == count { + break + } + if !dropSegment(child.Name()) { + continue + } + next := filepath.Join(rel, child.Name()) + st, err := os.Lstat(filepath.Join(src, next)) + if err != nil { + return err + } + if guesttools.IsDropSymlink(st) { + continue + } + if st.IsDir() && depth < guesttools.MaxSharedDepth { + if err := walk(next, depth+1); err != nil { + return err + } + } + if st.Mode().IsRegular() && st.Size() <= min(MaxHostDropFileBytes, limit-estimated) { + files = append(files, entry{next, st}) + estimated += st.Size() + } + } + return nil + } + if err := walk("", 2); err != nil || len(files) == 0 { + return "", nil, 0, err + } + if err := os.MkdirAll(shared, 0o755); err != nil { + return "", nil, 0, err + } + folder, err := allocUniqueDir(shared, filepath.Base(src)) + if err != nil { + return "", nil, 0, err + } + dest := filepath.Join(shared, folder) + var items []string + var total int64 + for _, f := range files { + parent := filepath.Dir(filepath.Join(dest, f.rel)) + base, size, err := deliverHostFileLimited(parent, filepath.Join(src, f.rel), f.st, min(MaxHostDropFileBytes, limit-total)) + if err != nil { + return "", nil, 0, errors.Join(err, os.RemoveAll(dest)) + } + items = append(items, filepath.ToSlash(filepath.Join(folder, filepath.Dir(f.rel), base))) + total += size + } + return folder, items, total, nil +} + +func (a *App) deliverHostFileLimited(name, path string, expected os.FileInfo, limit int64) (string, int64, error) { + return deliverHostFileLimited(a.vmSharedDir(name), path, expected, limit) +} + +func deliverHostFileLimited(dir, path string, expected os.FileInfo, limit int64) (string, int64, error) { + if expected.Size() > limit { + return "", 0, errDropSize + } + src, err := os.Open(path) + if err != nil { + return "", 0, err + } + defer src.Close() + st, err := src.Stat() + if err != nil { + return "", 0, err + } + if !st.Mode().IsRegular() || !os.SameFile(expected, st) { + return "", 0, fmt.Errorf("%w: source changed", guesttools.ErrInvalidHostDrop) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", 0, err + } + tmp, err := os.CreateTemp(dir, ".reims-deliver-*") + if err != nil { + return "", 0, err + } + defer os.Remove(tmp.Name()) + size, copyErr := io.Copy(tmp, io.LimitReader(src, limit+1)) + closeErr := tmp.Close() + if err := errors.Join(copyErr, closeErr); err != nil { + return "", 0, err + } + if size > limit { + return "", 0, errDropSize + } + base, err := deliverHostFileUnique(dir, filepath.Base(path), tmp.Name()) + return base, size, err +} + +// Link publishes the completed file atomically and fails if another writer +// already owns the name, including writers outside this process. +func deliverHostFileUnique(dir, base, tmp string) (string, error) { + hostDropPublishMu.Lock() + defer hostDropPublishMu.Unlock() + return allocUniqueDropName(base, true, func(candidate string) (bool, error) { + err := os.Link(tmp, filepath.Join(dir, candidate)) + if errors.Is(err, os.ErrExist) { + return false, nil + } + return err == nil, err + }) +} diff --git a/internal/app/host_drop_test.go b/internal/app/host_drop_test.go new file mode 100644 index 0000000..600bfe0 --- /dev/null +++ b/internal/app/host_drop_test.go @@ -0,0 +1,210 @@ +package app + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/guesttools" +) + +func TestValidateHostDropPath(t *testing.T) { + for _, raw := range []string{"", " ", "relative", `\\server\share`, "//server/share", `\\?\C:\foo`, `\\.\pipe\x`, "a\x00b"} { + if _, err := validateHostDropPath(raw); err == nil { + t.Errorf("accepted %q", raw) + } + } + t.Run("symlink", func(t *testing.T) { + dir := t.TempDir() + link := filepath.Join(dir, "link") + if err := os.Symlink(dir, link); err != nil { + t.Skipf("symlink unavailable: %v", err) + } + if _, err := validateHostDropPath(link); err == nil { + t.Fatal("accepted symlink") + } + }) +} + +func TestHostDropUniqueDelivery(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}} + dir := a.vmSharedDir("mac") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + write := func(path, contents string) { + t.Helper() + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + } + first := filepath.Join(t.TempDir(), "demo.txt") + second := filepath.Join(t.TempDir(), "demo.txt") + write(first, "one") + write(second, "two") + write(filepath.Join(dir, "demo.txt"), "original") + skip := t.TempDir() + res, err := a.handleHostDrop("mac", "mac", guesttools.HostDropRequest{Paths: []string{first, skip, second}}) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(res.Delivered, []string{"demo (1).txt", "demo (2).txt"}) || + !reflect.DeepEqual(res.Skipped, []string{filepath.Base(skip)}) || len(res.DropID) != 32 || res.Mode != "l1_share" { + t.Fatalf("unexpected result: %+v", res) + } + for name, want := range map[string]string{"demo.txt": "original", "demo (1).txt": "one", "demo (2).txt": "two"} { + data, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil || string(data) != want { + t.Errorf("%s: got %q, err %v", name, data, err) + } + } +} + +func TestHostDropL2QueueAndCleanup(t *testing.T) { + a, cfg, request := queuedDropFixture(t) + key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key() + src := filepath.Join(t.TempDir(), "demo.txt") + if err := os.WriteFile(src, []byte("new"), 0o600); err != nil { + t.Fatal(err) + } + for _, status := range []string{"pasted", "placed", "cancelled", "failed"} { + res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Paths: []string{src}}) + if err != nil || res.Mode != "l2_webdav" || !reflect.DeepEqual(res.Delivered, []string{"demo.txt"}) { + t.Fatalf("drop %+v: %v", res, err) + } + var ev guesttools.DropEvent + if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &ev); err != nil || + ev.DropID != res.DropID || ev.Kind != "files" || !ev.WebDAVDrop || + !reflect.DeepEqual(ev.Items, res.Delivered) || !reflect.DeepEqual(ev.TargetPaths, res.Delivered) { + t.Fatalf("event %+v: %v", ev, err) + } + requireEmptyDropDir(t, a.vmSharedDir(cfg.VMName)) + dav := "/dav-drop/mac/" + ev.DropID + "/demo.txt" + file := "/v1/drop-file?drop_id=" + ev.DropID + "&path=demo.txt" + for _, route := range []string{dav, file} { + if data := request("GET", route, "", 200); string(data) != "new" { + t.Fatalf("%s: %q", route, data) + } + } + body := fmt.Sprintf(`{"drop_id":%q,"status":%q,"target_kind":"share"}`, ev.DropID, status) + request("POST", "/v1/drop-events/ack", body, 200) + if status == "pasted" { + if data := request("GET", dav, "", 200); string(data) != "new" { + t.Fatalf("after paste: %q", data) + } + } else { + request("GET", dav, "", 404) + } + } +} + +func queuedDropFixture(t *testing.T) (*App, guesttools.VMConfig, func(string, string, string, int) []byte) { + t.Helper() + srv := guesttools.NewServer(nil) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { srv.Close(context.Background()) }) + cfg := guesttools.VMConfig{VMName: "mac", Token: "guest"} + srv.RegisterVM(cfg) + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, guestTools: srv} + srv.SetDropAckHandler(a.handleHostDropAck) + const path = "/v1/drop-events" + request := func(method, route, body string, status int) []byte { + t.Helper() + req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, route), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if strings.HasPrefix(route, "/dav-drop/") { + req.SetBasicAuth(cfg.VMName, cfg.Token) + } else { + req.Header.Set("Authorization", "Bearer "+cfg.Token) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != status { + t.Fatalf("response %d %q: %v", resp.StatusCode, data, err) + } + return data + } + request("GET", path+"?wait=0", "", 204) + return a, cfg, request +} + +func TestHostDropRecursiveFolder(t *testing.T) { + a, cfg, request := queuedDropFixture(t) + shared := a.vmSharedDir(cfg.VMName) + src := filepath.Join(t.TempDir(), "MyFolder") + empty := filepath.Join(t.TempDir(), "empty") + for _, dir := range []string{filepath.Join(src, "sub"), empty} { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + } + for _, file := range []string{filepath.Join(src, "a.txt"), filepath.Join(src, "sub", "b.txt")} { + if err := os.WriteFile(file, []byte(filepath.Base(file)), 0o600); err != nil { + t.Fatal(err) + } + } + key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key() + res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Paths: []string{src, empty}}) + want := []string{"MyFolder", "empty"} + if err != nil || res.Mode != "l2_webdav" || !reflect.DeepEqual(res.Delivered, want) { + t.Fatalf("result %+v: %v", res, err) + } + var event guesttools.DropEvent + if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &event); err != nil || + event.Kind != "files" || !event.WebDAVDrop || event.DropID != res.DropID || + !reflect.DeepEqual(event.Items, want) || !reflect.DeepEqual(event.TargetPaths, want) { + t.Fatalf("event %+v: %v", event, err) + } + requireEmptyDropDir(t, shared) + for _, item := range []string{"MyFolder/a.txt", "MyFolder/sub/b.txt"} { + for _, route := range []string{ + "/dav-drop/mac/" + res.DropID + "/" + item, + "/v1/drop-file?drop_id=" + res.DropID + "&path=" + item, + } { + if data := request("GET", route, "", 200); string(data) != filepath.Base(item) { + t.Fatalf("%s: %q", route, data) + } + } + } +} + +func requireEmptyDropDir(t *testing.T, dir string) { + t.Helper() + entries, err := os.ReadDir(dir) + if (err != nil && !os.IsNotExist(err)) || len(entries) != 0 { + t.Fatalf("unexpected ReimsShare contents %v: %v", entries, err) + } +} + +func TestHostDropText(t *testing.T) { + a, cfg, request := queuedDropFixture(t) + key := driver.NewVMRef(cfg.DriverID, cfg.VMName).Key() + const value = "https://example.com" + res, err := a.handleHostDrop(key, cfg.VMName, guesttools.HostDropRequest{Text: value}) + if err != nil || res.Mode != "l2_text" || len(res.Delivered) != 0 { + t.Fatalf("result %+v: %v", res, err) + } + var ev guesttools.DropEvent + if err := json.Unmarshal(request("GET", "/v1/drop-events?wait=0", "", 200), &ev); err != nil || + ev.DropID != res.DropID || ev.Kind != "text" || ev.Text != value { + t.Fatalf("event %+v: %v", ev, err) + } +} diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 15f81fd..56c41c7 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -288,6 +288,9 @@ func (a *App) startVMLegacy(name string) error { c.Env = append(c.Env, env...) } } + if prep.Runtime.Manifest.HasCapability("window-file-drop") { + c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...) + } prep.Prepare(context.Background(), name, rep, &curDetail) if rep.NeedsColdRebootWorkaround { sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name) diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 1702260..a3dd09d 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -102,8 +102,13 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error { var extraEnv []string if ref.DriverID == driver.BuiltinReimsMacOSDriverID { a.cancelRebootWatcherKey(key) - if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") { - extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory, a.vmDeleteEpoch(ref.Name))...) + if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil { + if active.Manifest.HasCapability("win32-unicode-input") { + extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory, a.vmDeleteEpoch(ref.Name))...) + } + if active.Manifest.HasCapability("window-file-drop") { + extraEnv = append(extraEnv, a.dropBridgeEnv(ref.Name, vm.Directory, a.vmDeleteEpoch(ref.Name))...) + } } } diff --git a/internal/guesttools/drop.go b/internal/guesttools/drop.go new file mode 100644 index 0000000..ff2077d --- /dev/null +++ b/internal/guesttools/drop.go @@ -0,0 +1,474 @@ +package guesttools + +import ( + "bytes" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "math" + "net/http" + "slices" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +const MaxHostDropBodyBytes = 256 << 10 +const MaxHostDropPaths = 64 + +var ErrInvalidHostDrop = errors.New("invalid host drop") + +type HostDropRequest struct { + DisplayIndex int `json:"display_index"` + NormX float64 `json:"norm_x"` + NormY float64 `json:"norm_y"` + InImage bool `json:"in_image"` + Paths []string `json:"paths"` + Text string `json:"text,omitempty"` +} + +type HostDropResult struct { + DropID string `json:"drop_id"` + Delivered []string `json:"delivered"` + Skipped []string `json:"skipped,omitempty"` + Mode string `json:"mode"` +} + +func (s *Server) HostDropToken(driverID, vmName string) string { + s.mu.RLock() + defer s.mu.RUnlock() + if vm := s.vms[vmRegistryKey(driverID, vmName)]; vm != nil { + return vm.hostDropToken + } + return "" +} + +func (s *Server) authenticateHostDrop(r *http.Request) (string, string) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok || len(token) != 64 { + return "", "" + } + s.mu.RLock() + defer s.mu.RUnlock() + for _, vm := range s.vms { + if subtle.ConstantTimeCompare([]byte(token), []byte(vm.hostDropToken)) == 1 { + return vm.key, vm.name + } + } + return "", "" +} + +func (s *Server) SetHostDropHandler(fn func(string, string, HostDropRequest) (HostDropResult, error)) { + s.mu.Lock() + defer s.mu.Unlock() + s.onHostDrop = fn +} + +func (s *Server) handleHostDrop(w http.ResponseWriter, r *http.Request) { + key, name := s.authenticateHostDrop(r) + if key == "" { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, MaxHostDropBodyBytes+1)) + if err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + if len(body) > MaxHostDropBodyBytes { + http.Error(w, "body too large", http.StatusRequestEntityTooLarge) + return + } + var req HostDropRequest + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + if dec.Decode(&req) != nil || dec.Decode(new(any)) != io.EOF || req.DisplayIndex < 0 || + math.IsNaN(req.NormX) || math.IsInf(req.NormX, 0) || math.IsNaN(req.NormY) || math.IsInf(req.NormY, 0) || + !((len(req.Paths) > 0 && len(req.Paths) <= MaxHostDropPaths && req.Text == "") || + (len(req.Paths) == 0 && req.Text != "" && len(req.Text) <= MaxTextInputBytes && utf8.Valid(body) && utf8.ValidString(req.Text))) { + http.Error(w, "invalid host drop", http.StatusBadRequest) + return + } + req.NormX = min(1, max(0, req.NormX)) + req.NormY = min(1, max(0, req.NormY)) + s.mu.RLock() + fn := s.onHostDrop + s.mu.RUnlock() + if fn == nil { + http.Error(w, "host drop unavailable", http.StatusServiceUnavailable) + return + } + result, err := fn(key, name, req) + if errors.Is(err, ErrInvalidHostDrop) { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err != nil { + http.Error(w, "host drop failed", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(result) +} + +const ( + DropEventTTL = 60 * time.Second + MaxPendingDropEvents = 32 + MaxDropAckBodyBytes = 64 << 10 +) + +type DropEvent struct { + Kind string `json:"kind,omitempty"` + Text string `json:"text,omitempty"` + WebDAVDrop bool `json:"webdav_drop,omitempty"` + DropID string `json:"drop_id"` + DisplayIndex int `json:"display_index"` + NormX float64 `json:"norm_x"` + NormY float64 `json:"norm_y"` + InImage bool `json:"in_image"` + Items []string `json:"items"` + TargetPaths []string `json:"target_paths,omitempty"` + CreatedAt time.Time `json:"-"` +} + +type DropEventAck struct { + DropID string `json:"drop_id"` + Status string `json:"status"` + TargetKind string `json:"target_kind"` + TargetLabel string `json:"target_label,omitempty"` + PlacedNames []string `json:"placed_names,omitempty"` + Error string `json:"error,omitempty"` +} + +func (s *Server) SetDropAckHandler(fn func(vmKey, vmName string, ack DropEventAck)) { + s.mu.Lock() + defer s.mu.Unlock() + s.onDropAck = fn +} + +func (s *Server) HasDropEventListener(vmKey string) bool { + s.mu.RLock() + defer s.mu.RUnlock() + cur := s.vms[normalizeVMRegistryKey(vmKey)] + return cur != nil && (cur.dropWaiters > 0 || (!cur.lastDropPoll.IsZero() && time.Since(cur.lastDropPoll) <= 35*time.Second)) +} + +func (vm *registeredVM) pruneDropEvents(now time.Time) { + vm.dropQueue = slices.DeleteFunc(vm.dropQueue, func(ev *DropEvent) bool { + return now.Sub(ev.CreatedAt) > DropEventTTL + }) + for id, ev := range vm.dropActive { + if now.Sub(ev.CreatedAt) > DropEventTTL { + delete(vm.dropActive, id) + } + } +} + +func (s *Server) EnqueueDropEvent(vmKey string, ev DropEvent) bool { + s.mu.Lock() + defer s.mu.Unlock() + vm := s.vms[normalizeVMRegistryKey(vmKey)] + if ev.Kind == "" { + ev.Kind = "files" + } + if vm == nil || ev.DropID == "" || !((ev.Kind == "files" && len(ev.Items) > 0) || (ev.Kind == "text" && ev.Text != "")) { + return false + } + now := time.Now() + if ev.CreatedAt.IsZero() { + ev.CreatedAt = now + } + ev.Items = slices.Clone(ev.Items) + if len(ev.TargetPaths) > 0 { + ev.TargetPaths = slices.Clone(ev.TargetPaths) + } + vm.pruneDropEvents(now) + if len(vm.dropQueue) >= MaxPendingDropEvents { + vm.dropQueue = slices.Delete(vm.dropQueue, 0, 1) + } + vm.dropQueue = append(vm.dropQueue, &ev) + close(vm.dropNotify) + vm.dropNotify = make(chan struct{}) + return true +} + +func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) { + vmSnap := s.authenticate(r) + if vmSnap == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + waitSec := MaxLongPollSec + if rawWait := r.URL.Query().Get("wait"); rawWait != "" { + if n, err := strconv.Atoi(rawWait); err == nil && n >= 0 { + if n > MaxLongPollSec { + n = MaxLongPollSec + } + waitSec = n + } + } + + s.mu.Lock() + vm := s.vms[vmSnap.key] + if vm == nil || vm.token != vmSnap.token { + s.mu.Unlock() + http.Error(w, "vm not found", http.StatusNotFound) + return + } + vm.dropWaiters++ + vm.lastDropPoll = time.Now() + s.mu.Unlock() + defer func() { + s.mu.Lock() + if cur := s.vms[vmSnap.key]; cur == vm && cur.token == vmSnap.token { + if cur.dropWaiters > 0 { + cur.dropWaiters-- + } + cur.lastDropPoll = time.Now() + } + s.mu.Unlock() + }() + + deadline := time.Now().Add(time.Duration(waitSec) * time.Second) + for { + s.mu.Lock() + cur := s.vms[vmSnap.key] + if cur != vm || cur.token != vmSnap.token { + s.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + } + cur.pruneDropEvents(time.Now()) + if len(cur.dropQueue) > 0 { + item := cur.dropQueue[0] + cur.dropQueue[0] = nil + cur.dropQueue = cur.dropQueue[1:] + cur.dropActive[item.DropID] = item + cur.lastSeen = time.Now() + cur.lastDropPoll = time.Now() + s.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(item) + return + } + ch := cur.dropNotify + s.mu.Unlock() + + rem := time.Until(deadline) + if waitSec <= 0 || rem <= 0 { + s.touchLastSeen(vmSnap.key) + w.WriteHeader(http.StatusNoContent) + return + } + timer := time.NewTimer(rem) + select { + case <-ch: + timer.Stop() + case <-timer.C: + s.touchLastSeen(vmSnap.key) + w.WriteHeader(http.StatusNoContent) + return + case <-r.Context().Done(): + timer.Stop() + return + } + } +} + +func (s *Server) handleDropEventsAck(w http.ResponseWriter, r *http.Request) { + vmSnap := s.authenticate(r) + if vmSnap == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, MaxDropAckBodyBytes+1)) + if err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + if len(body) > MaxDropAckBodyBytes { + http.Error(w, "body too large", http.StatusRequestEntityTooLarge) + return + } + var ack DropEventAck + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + if dec.Decode(&ack) != nil || dec.Decode(new(any)) != io.EOF || ack.DropID == "" || + !slices.Contains([]string{"placed", "pasted", "cancelled", "fallback_share", "failed"}, ack.Status) || + !slices.Contains([]string{"desktop", "finder_window", "finder_folder", "photos", "window", "share", "cancelled"}, ack.TargetKind) { + http.Error(w, "invalid drop acknowledgement", http.StatusBadRequest) + return + } + s.mu.Lock() + active := false + if cur := s.vms[vmSnap.key]; cur != nil && cur.token == vmSnap.token { + cur.pruneDropEvents(time.Now()) + _, active = cur.dropActive[ack.DropID] + delete(cur.dropActive, ack.DropID) + } + fn := s.onDropAck + s.mu.Unlock() + if active && fn != nil { + fn(vmSnap.key, vmSnap.name, ack) + } + w.WriteHeader(http.StatusOK) +} + +func (s *Server) RegisterDropShare(vmKey, dropID string, entries []DropShareEntry) bool { + s.mu.RLock() + defer s.mu.RUnlock() + vm := s.vms[normalizeVMRegistryKey(vmKey)] + return vm != nil && vm.dropShares.register(dropID, entries) +} + +func (s *Server) RevokeDropShare(vmKey, dropID string) { + s.mu.RLock() + defer s.mu.RUnlock() + if vm := s.vms[normalizeVMRegistryKey(vmKey)]; vm != nil { + vm.dropShares.revoke(dropID) + } +} + +func (s *Server) SetDropPasteHandler(fn func(ctx context.Context, vmKey, vmName, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error) { + s.mu.Lock() + defer s.mu.Unlock() + s.onDropPaste = fn +} + +func (s *Server) handleDropWebDAV(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + w.Header().Set("WWW-Authenticate", `Basic realm="ReimsDrop"`) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + trimmed := strings.TrimPrefix(r.URL.Path, "/dav-drop/") + vmPart, _, _ := strings.Cut(trimmed, "/") + if vmPart != vm.name { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + if !allowPROPFINDDepth(w, r) || !allowReadOnlyDAV(w, r) { + return + } + vm.dropDAVHandler.ServeHTTP(w, r) +} + +func (s *Server) handleDropFile(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + q := r.URL.Query() + (&dropWebDAVFS{store: vm.dropShares}).serveDropFile(w, r, q.Get("drop_id"), q.Get("path")) +} + +func (s *Server) handleDropEventsPaste(w http.ResponseWriter, r *http.Request) { + snap := s.authenticate(r) + if snap == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, MaxDropAckBodyBytes+1)) + if err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + if len(body) > MaxDropAckBodyBytes { + http.Error(w, "body too large", http.StatusRequestEntityTooLarge) + return + } + var req struct { + DropID string `json:"drop_id"` + ActivateClick bool `json:"activate_click,omitempty"` + CommandKey string `json:"command_key,omitempty"` + FocusWaitMS int `json:"focus_wait_ms,omitempty"` + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + if dec.Decode(&req) != nil || dec.Decode(new(any)) != io.EOF || req.DropID == "" || + req.FocusWaitMS < 0 || req.FocusWaitMS > 500 { + http.Error(w, "invalid paste request", http.StatusBadRequest) + return + } + switch req.CommandKey { + case "": + req.CommandKey = "meta_l" + case "meta_l", "meta_r", "alt", "alt_r", "ctrl", "ctrl_r", "shift", "shift_r", "caps_lock": + default: + http.Error(w, "invalid paste request", http.StatusBadRequest) + return + } + s.mu.RLock() + vm := s.vms[snap.key] + s.mu.RUnlock() + if vm == nil { + http.NotFound(w, r) + return + } + vm.injectMu.Lock() + defer vm.injectMu.Unlock() + + s.mu.Lock() + var ev *DropEvent + if s.vms[snap.key] == vm && vm.token == snap.token { + vm.pruneDropEvents(time.Now()) + ev = vm.dropActive[req.DropID] + } + fn, settle := s.onDropPaste, s.dropPasteSettle + s.mu.Unlock() + if ev == nil { + http.NotFound(w, r) + return + } + if fn == nil { + http.Error(w, "drop paste unavailable", http.StatusServiceUnavailable) + return + } + if r.Context().Err() != nil { + return + } + if err := fn(r.Context(), snap.key, snap.name, ev.DropID, ev.DisplayIndex, ev.NormX, ev.NormY, req.ActivateClick, req.CommandKey, time.Duration(req.FocusWaitMS)*time.Millisecond); err != nil { + http.Error(w, "drop paste failed", http.StatusInternalServerError) + return + } + if settle <= 0 { + settle = 500 * time.Millisecond + } + timer := time.NewTimer(settle) + defer timer.Stop() + select { + case <-r.Context().Done(): + case <-timer.C: + w.WriteHeader(http.StatusOK) + } +} diff --git a/internal/guesttools/drop_agent.sh b/internal/guesttools/drop_agent.sh new file mode 100644 index 0000000..4bb2634 --- /dev/null +++ b/internal/guesttools/drop_agent.sh @@ -0,0 +1,225 @@ + +drop_helper() { + osascript -l JavaScript "$APP_DIR/drop-resolve.js" "$@" +} + +place_drop_unique() ( + target_dir=$1 base=$2 part_file=$3 + stem=$base ext= + case "$base" in + ?*.*) stem=${base%.*}; ext=.${base##*.} ;; + esac + n=0 + while [ "$n" -le 999 ]; do + candidate=$base + if [ "$n" -gt 0 ]; then candidate="$stem ($n)$ext"; fi + dest="$target_dir/$candidate" + if [ ! -e "$dest" ] && [ ! -L "$dest" ]; then + if ln "$part_file" "$dest" 2>/dev/null; then + rm -f "$part_file" || return 1 + printf '%s\n' "$candidate" + return 0 + fi + if [ ! -e "$dest" ] && [ ! -L "$dest" ]; then + mv -n "$part_file" "$dest" 2>/dev/null || : + if [ ! -e "$part_file" ] && [ -f "$dest" ]; then + printf '%s\n' "$candidate" + return 0 + fi + [ -e "$dest" ] || [ -L "$dest" ] || return 1 + fi + fi + n=$((n + 1)) + done + return 1 +) + +alloc_drop_dir() ( + n=0 + while [ "$n" -le 999 ]; do + cand=$2 + if [ "$n" -gt 0 ]; then cand="$2 ($n)"; fi + if mkdir "$1/$cand" 2>/dev/null; then printf '%s\n' "$cand"; return 0; fi + [ -e "$1/$cand" ] || [ -L "$1/$cand" ] || return 1 + n=$((n + 1)) + done + return 1 +) + +copy_drop_tree() ( + src_path=$1 target_dir=$2 dst_name=$3 + if [ -d "$src_path" ]; then + mapped=$(alloc_drop_dir "$target_dir" "$dst_name") || return 1 + cp -R "$src_path/." "$target_dir/$mapped/" || return 1 + printf '%s\n' "$mapped" + elif [ -f "$src_path" ]; then + part_file="$target_dir/.reims-drop.$drop_id.$$.part" + (umask 077; set -C; : > "$part_file") || return 1 + trap 'rm -f "$part_file"' 0 + cp "$src_path" "$part_file" && place_drop_unique "$target_dir" "$dst_name" "$part_file" + else + return 1 + fi +) + +prune_drop_cache() { + if [ -d "${DROP_CACHE:-}" ]; then + find "$DROP_CACHE" -mindepth 1 -maxdepth 1 -type d -mmin +15 -exec rm -rf {} + 2>/dev/null || true + fi +} + +post_drop_ack() { + curl -fsS -m 10 -H "Authorization: Bearer $REIMS_TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$1" "$REIMS_HOST_URL/v1/drop-events/ack" >/dev/null +} + +process_drop_event() ( + umask 077 + dirmap="$TMP_DIR/drop_dirmap.$$" + # Regular-file flag checked with -f by clipboard sync; drop_events_loop runs serially. + lock=${DROP_INJECT_LOCK:-$TMP_DIR/drop-injecting} + held=false + trap 'rm -f "$dirmap"; if [ "$held" = true ]; then rm -f "$lock"; fi' 0 + trap 'exit 1' HUP INT TERM + touch "$lock" || return 1 + held=true + fast=$(REIMS_TOKEN="$REIMS_TOKEN" drop_helper run-drop "$1" "${DROP_MOUNT:-}" "$REIMS_HOST_URL/v1/drop-events/paste") || return 1 + rm -f "$lock" || return 1 + held=false + exec 3</dev/null 2>&1; then ensure_drop_webdav_mount || :; fi + if [ -d "$DROP_MOUNT/$drop_id" ] && { [ "$t_kind" = desktop ] || + drop_helper check-mount "$DROP_MOUNT" "$DROP_MOUNT/$drop_id" >/dev/null 2>&1; }; then + mount_dir="$DROP_MOUNT/$drop_id" + break + fi + [ "$attempt" = first ] && command -v unmount_shared_folder >/dev/null 2>&1 && + unmount_shared_folder "$DROP_MOUNT" >/dev/null 2>&1 || break + done + fi + if [ -z "$mount_dir" ]; then + DROP_CACHE=${DROP_CACHE:-$TMP_DIR/drop-cache} + prune_drop_cache + fi + : > "$dirmap" || return 1 + while IFS="$tab" read -r src_item dst_item <&3; do + case "/$src_item/$dst_item/" in *//*|*/./*|*/../*|*'\'*) error='Invalid item name'; break ;; esac + if [ -n "$mount_dir" ]; then + path="$mount_dir/$src_item" + [ -e "$path" ] || { error='Missing drop item'; break; } + else + path="$DROP_CACHE/$drop_id/$dst_item" + mkdir -p "${path%/*}" || { error='Cannot create cache'; break; } + query=$(urlencode "$src_item") || { error='Invalid source'; break; } + url="$REIMS_HOST_URL/v1/file?path=$query" + if [ "$webdav_drop" = true ]; then url="$REIMS_HOST_URL/v1/drop-file?drop_id=$drop_id&path=$query"; fi + if ! curl -fsS --max-time 120 -H "Authorization: Bearer $REIMS_TOKEN" -o "$path" "$url"; then + error='Download failed'; break + fi + fi + if [ "$t_kind" != desktop ]; then set -- "$@" "$path"; continue; fi + target_dir=$t_meta + dest_dir=$target_dir base=$dst_item mapped= + case "$dst_item" in + */*) + src_top=${src_item%%/*} top=${dst_item%%/*} rest=${dst_item#*/} + while IFS= read -r key && IFS= read -r value; do + if [ "$key" = "$src_top" ]; then mapped=$value; break; fi + done < "$dirmap" + if [ -z "$mapped" ]; then + mapped=$(alloc_drop_dir "$target_dir" "$top") || { error='Cannot create folder'; break; } + printf '%s\n%s\n' "$src_top" "$mapped" >> "$dirmap" || { error='Cannot record folder'; break; } + fi + dest_dir="$target_dir/$mapped" + while :; do + if [ -L "$dest_dir" ]; then error='Invalid folder'; break; fi + case "$rest" in + */*) dest_dir="$dest_dir/${rest%%/*}"; rest=${rest#*/} ;; + *) break ;; + esac + mkdir "$dest_dir" 2>/dev/null || [ -d "$dest_dir" ] || { error='Cannot create subfolder'; break; } + done + [ -z "$error" ] || break + base=$rest ;; + esac + placed=$(copy_drop_tree "$path" "$dest_dir" "$base") || { error='Placement failed'; break; } + placed=${mapped:-$placed} + seen=false + for existing do [ "$existing" != "$placed" ] || seen=true; done + if [ "$seen" = false ]; then set -- "$@" "$placed"; fi + done + if [ "$#" -eq 0 ] && [ -z "$error" ]; then error='No drop items'; fi ;; + *) status=cancelled ;; + esac + if [ -z "$error" ] && [ "$status" != cancelled ]; then + case "$t_kind" in + photos) + if photos_err=$(drop_helper import-photos "$@" 2>&1 >/dev/null); then :; else + case "$photos_err" in + *1743*|*[Nn]ot\ authorized*|*[Pp]ermission*|*[Pp]rivilege*) + error='Photos import blocked: allow Automation access to Photos in macOS Privacy & Security' ;; + *) error='Photos import failed' ;; + esac + fi + set -- ;; + window) + if touch "$lock"; then + held=true + if res=$(REIMS_TOKEN="$REIMS_TOKEN" drop_helper paste-drop "$display_index" "$norm_x" "$norm_y" \ + "$win_num" "$t_meta" "$kind" "$REIMS_HOST_URL/v1/drop-events/paste" "$drop_id" "$@"); then + case "$res" in pasted|cancelled) status=$res ;; *) error='Paste failed' ;; esac + else error='Paste failed'; fi + rm -f "$lock" || return 1 + held=false + else error='Cannot lock input'; fi + set -- ;; + esac + fi + if [ -n "$error" ]; then status=failed; if [ "$t_kind" != desktop ]; then set --; fi; fi + if [ "$status" = cancelled ]; then t_kind=cancelled; label=; fi + ack=$(drop_helper encode-ack "$drop_id" "$status" "$t_kind" "$label" "$error" "$@") || return 1 + post_drop_ack "$ack" +) + +drop_events_loop() { + ev_file="$TMP_DIR/drop_event" + while :; do + load_conf + if [ -z "$REIMS_HOST_URL" ] || [ -z "$REIMS_TOKEN" ]; then sleep 2; continue; fi + code=$(curl -sS -m 30 -o "$ev_file" -w '%{http_code}' -H "Authorization: Bearer $REIMS_TOKEN" \ + "$REIMS_HOST_URL/v1/drop-events?wait=25") || code=000 + case "$code" in + 200) + process_drop_event "$ev_file" || sleep 1 ;; + 204) ;; + *) sleep 1 ;; + esac + done +} diff --git a/internal/guesttools/drop_agent_test.go b/internal/guesttools/drop_agent_test.go new file mode 100644 index 0000000..3bf31c4 --- /dev/null +++ b/internal/guesttools/drop_agent_test.go @@ -0,0 +1,187 @@ +package guesttools + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestToolsDiskImageIncludesDropResolveJS(t *testing.T) { + t.Run("TestDropScriptsUseLF", func(t *testing.T) { + if bytes.Contains(GuestAgentScript(), []byte("\r")) || strings.Contains(guestDropResolveJS, "\r") { + t.Fatal("embedded drop scripts contain a carriage return") + } + }) + resolver := guestDropResolveJS + if !strings.Contains(resolver, "com.apple.finder") || strings.Contains(resolver, "'Finder'") { + t.Fatal("drop resolver must identify Finder by bundle ID") + } + path := filepath.Join(t.TempDir(), "tools.img") + if err := BuildToolsDiskImage(path, VMConfig{VMName: "mac"}); err != nil { + t.Fatal(err) + } + image, err := os.ReadFile(path) + if err != nil || !bytes.Contains(image, []byte(resolver)) { + t.Fatalf("missing resolver in image: %v", err) + } + install := string(GuestInstallScript()) + agent := string(GuestAgentScript()) + if !strings.Contains(install, `cp "$SRC/drop-resolve.js" "$APP_DIR/drop-resolve.js"`) || + !strings.Contains(install, `chmod 755 "$APP_DIR/drop-resolve.js"`) || + !strings.Contains(agent, "ensure_drop_webdav_mount") || + !strings.Contains(agent, "drop_events_loop &\nDROP_EVENTS_PID=$!") { + t.Fatal("missing resolver installation or drop agent startup") + } +} + +func TestDropAgentRoutes(t *testing.T) { + lockShellFixture(t) + sh, err := exec.LookPath("sh") + if runtime.GOOS == "windows" { + const gitSH = "C:/Program Files/Git/bin/sh.exe" + if _, statErr := os.Stat(gitSH); statErr == nil { + sh, err = gitSH, nil + } + } + if err != nil { + t.Fatal(err) + } + + const osascript = `#!/bin/sh +set -eu +[ "$1" = -l ] && [ "$2" = JavaScript ] && [ "$3" = "./drop-resolve.js" ] || exit 1 +shift 3 +echo "$1" >> osascript-calls +case "$1" in + run-drop) + [ "$#" = 4 ] && [ "$2" = event ] && [ "$3" = "$PWD/mount" ] && + [ "$4" = http://host/v1/drop-events/paste ] && [ -f "$DROP_INJECT_LOCK" ] && + [ "$REIMS_TOKEN" = fixture-secret ] || exit 1 + for arg do case "$arg" in *fixture-secret*) exit 1 ;; esac; done + case "$CASE" in + fast-window|fast-text|fast-photos|fast-cancelled) printf 'done\t%s\n' "$EXPECT"; exit 0 ;; + esac + printf 'fallback\nid\t%s\t%s\t0\t0.4\t0.6\ttrue\n' "$MODE" "$DAV" + case "$TARGET" in + desktop) printf 'desktop\tDesktop\t%s/Desktop\t0\n' "$PWD" ;; + photos) printf 'photos\tPhotos\tcom.apple.Photos\t31\n' ;; + window) printf 'window\tNotes\tcom.apple.Notes\t42\n' ;; + esac + printf 'file.txt\tfile.txt\n' + if [ "$CASE" = desktop ]; then printf 'Folder\tFolder\n'; fi ;; + check-mount) + [ "$#" = 3 ] && [ "$2" = "$PWD/mount" ] && [ "$3" = "$PWD/mount/id" ] || exit 1 + echo check >> mount-checks + case "$CASE" in + remount) [ -f remounted ] || exit 1 ;; + unhealthy-cache) exit 1 ;; + esac + echo ok ;; + import-photos) + [ "$#" = 2 ] && [ "$2" = "$PWD/mount/id/file.txt" ] || exit 1 + if [ "$CASE" = photos-denied ]; then + echo 'Error -1743: Not authorized to send Apple events to Photos.' >&2 + exit 1 + fi + touch imported + echo ok ;; + paste-drop) + [ "$#" = 10 ] && [ -f "$DROP_INJECT_LOCK" ] && [ "$REIMS_TOKEN" = fixture-secret ] || exit 1 + for arg do case "$arg" in *fixture-secret*) exit 1 ;; esac; done + [ "$2 $3 $4 $5 $6 $7 $8 $9" = "0 0.4 0.6 42 com.apple.Notes $MODE http://host/v1/drop-events/paste id" ] + touch attempted + if [ "$CASE" = cache ] || [ "$CASE" = unhealthy-cache ] || [ "$CASE" = legacy ]; then + [ "${10}" = "$PWD/cache/id/file.txt" ] && [ "$(cat "${10}")" = downloaded ] || exit 1 + else [ "${10}" = "$PWD/mount/id/file.txt" ]; fi + if [ "$CASE" = closed ]; then echo cancelled + else touch requested; echo pasted; fi ;; + encode-ack) printf '%s|%s|%s|%s|%s' "$2" "$3" "$4" "$5" "$6" ;; + *) exit 1 ;; +esac +` + for _, tc := range []struct{ name, mode, target, ack string }{ + {"desktop", "files", "desktop", "placed|desktop|Desktop|"}, + {"photos", "files", "photos", "placed|photos|Photos|"}, + {"photos-denied", "files", "photos", "failed|photos|Photos|Photos import blocked: allow Automation access to Photos in macOS Privacy & Security"}, + {"window", "files", "window", "pasted|window|Notes|"}, + {"closed", "files", "window", "cancelled|cancelled||"}, + {"fast-window", "files", "window", "pasted|window|Notes|"}, + {"fast-photos", "files", "photos", "placed|photos|Photos|"}, + {"fast-text", "text", "window", "pasted|window|Notes|"}, + {"fast-cancelled", "text", "desktop", "cancelled|cancelled||"}, + {"cache", "files", "window", "pasted|window|Notes|"}, + {"remount", "files", "window", "pasted|window|Notes|"}, + {"unhealthy-cache", "files", "window", "pasted|window|Notes|"}, + {"legacy", "files", "window", "pasted|window|Notes|"}, + } { + t.Run(tc.name, func(t *testing.T) { + work := t.TempDir() + if err := os.WriteFile(filepath.Join(work, "osascript"), []byte(osascript), 0o755); err != nil { + t.Fatal(err) + } + cmd := exec.Command(sh, "-s") + cmd.Dir = work + cmd.Env = append(os.Environ(), "CASE="+tc.name, "MODE="+tc.mode, "TARGET="+tc.target, "EXPECT=id|"+tc.ack) + cmd.Stdin = strings.NewReader(guestDropAgent + ` +set -eu +PATH="$PWD:$PATH" +APP_DIR=. TMP_DIR=. DROP_CACHE="$PWD/cache" DROP_MOUNT="$PWD/mount" +unset REIMS_TOKEN +REIMS_TOKEN=fixture-secret REIMS_HOST_URL=http://host +export DROP_INJECT_LOCK="$PWD/custom-lock" DAV=true +mkdir Desktop +case "$CASE" in + cache) ;; + legacy) DAV=false ;; + *) mkdir -p mount/id/Folder; echo file > mount/id/file.txt; echo nested > mount/id/Folder/child ;; +esac +ensure_drop_webdav_mount() { + touch mount-checked + if [ -f unmounted ]; then touch remounted; fi +} +unmount_shared_folder() { + [ "$1" = "$DROP_MOUNT" ] || return 1 + touch unmounted +} +urlencode() { printf '%s' "$1"; } +curl() { + case "$*" in + *'/v1/drop-events/ack') [ ! -e "$DROP_INJECT_LOCK" ] && [ "$8" = --data-binary ] && printf '%s' "$9" > ack ;; + *) case "$CASE:$*" in + cache:*'/v1/drop-file?drop_id=id&path=file.txt'|unhealthy-cache:*'/v1/drop-file?drop_id=id&path=file.txt'|legacy:*'/v1/file?path=file.txt') ;; + *) return 1 ;; + esac + [ "$6" = -o ] && echo downloaded > "$7" ;; + esac +} +process_drop_event event +[ "$(cat ack)" = "$EXPECT" ] +[ ! -e "$DROP_INJECT_LOCK" ] +[ ! -e "$TMP_DIR/drop_text.$$" ] +case "$CASE" in + fast-*) [ "$(wc -l < osascript-calls)" -eq 1 ] && [ "$(cat osascript-calls)" = run-drop ]; exit $? ;; +esac +if [ "$TARGET" = window ]; then [ -f attempted ]; else [ ! -e attempted ]; fi +if [ "$TARGET" = window ] && [ "$CASE" != closed ]; then [ -f requested ]; else [ ! -e requested ]; fi +if [ "$CASE" = photos ]; then [ -f imported ]; else [ ! -e imported ]; fi +if [ "$MODE" = files ] && [ "$DAV" = true ]; then [ -f mount-checked ]; fi +if [ "$CASE" = remount ] || [ "$CASE" = unhealthy-cache ]; then + [ -f unmounted ] && [ -f remounted ] || exit 1 + [ "$(wc -l < mount-checks)" -eq 2 ] +fi +if [ "$CASE" = desktop ]; then + [ "$(cat Desktop/file.txt)" = file ] + [ "$(cat Desktop/Folder/child)" = nested ] + [ ! -e "$DROP_CACHE" ] +fi +`) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("sh: %v\n%s", err, out) + } + }) + } +} diff --git a/internal/guesttools/drop_resolve.js b/internal/guesttools/drop_resolve.js new file mode 100644 index 0000000..487445d --- /dev/null +++ b/internal/guesttools/drop_resolve.js @@ -0,0 +1,359 @@ +ObjC.import('Cocoa') +ObjC.import('CoreGraphics') +ObjC.import('Foundation') + +const none = 'none\t\t\t0' +const browserBundles = new Set([ + 'com.google.Chrome', 'com.google.Chrome.canary', 'org.chromium.Chromium', + 'com.apple.Safari', 'com.apple.SafariTechnologyPreview', 'com.microsoft.edgemac', + 'org.mozilla.firefox', 'company.thebrowser.Browser', 'com.brave.Browser', + 'com.operasoftware.Opera', 'com.vivaldi.Vivaldi' +]) + +function contains(r, x, y) { + return x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height +} + +function globalRect(frame, mainH) { + return {X: frame.origin.x, Y: mainH - frame.origin.y - frame.size.height, + Width: frame.size.width, Height: frame.size.height} +} + +function hit(args) { + const [index, nx, ny] = args.slice(0, 3).map(v => v.trim() ? Number(v) : NaN) + const screens = $.NSScreen.screens + if (!Number.isInteger(index) || index < 0 || index >= screens.count || + !Number.isFinite(nx) || !Number.isFinite(ny) || nx < 0 || nx > 1 || ny < 0 || ny > 1) return {} + const mainH = screens.objectAtIndex(0).frame.size.height + const screen = screens.objectAtIndex(index) + const frame = globalRect(screen.frame, mainH) + const x = frame.X + nx * (frame.Width - 1) + const y = frame.Y + ny * (frame.Height - 1) + const options = $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements + const rawList = $.CGWindowListCopyWindowInfo(options, 0) + const allWindows = rawList ? (ObjC.deepUnwrap(ObjC.castRefToObject(rawList)) || []) : [] + const windows = allWindows.filter(w => w && w.kCGWindowBounds && + w.kCGWindowLayer === 0 && w.kCGWindowAlpha > 0.01 && + w.kCGWindowOwnerName !== 'Window Server' && w.kCGWindowBounds.Width > 1 && + w.kCGWindowBounds.Height > 1) + const top = windows.find(w => contains(w.kCGWindowBounds, x, y)) + return {top, windows, desktop: contains(globalRect(screen.visibleFrame, mainH), x, y)} +} + +function resolve(args) { + try { return resolveTarget(args) } catch (_) { return none } +} + +function resolveTarget(args) { + if (args[3] !== 'true') return none + const {top, desktop} = hit(args) + if (!top) { + const path = $.NSHomeDirectory().js + '/Desktop' + const dir = Ref() + const fm = $.NSFileManager.defaultManager + return desktop && fm.fileExistsAtPathIsDirectory(path, dir) && dir[0] && fm.isWritableFileAtPath(path) + ? ['desktop', 'Desktop', path, '0'].join('\t') : none + } + const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID) + const id = app && app.bundleIdentifier ? app.bundleIdentifier.js : '' + const label = ((app && app.localizedName && app.localizedName.js) || + top.kCGWindowOwnerName || id || 'App').replace(/[\t\r\n]/g, '') + return [id === 'com.apple.Photos' ? 'photos' : 'window', label, id, String(top.kCGWindowNumber || 0)].join('\t') +} + +function addStealth(item) { + for (const type of ['org.nspasteboard.TransientType', 'org.nspasteboard.AutoGeneratedType']) + if (!item.types.containsObject($(type)) && !item.setDataForType($.NSData.data, $(type))) throw Error('Cannot mark pasteboard item') + return item +} + +function readImagePNG(path) { + if (!/\.(png|jpe?g|webp|gif|bmp|heic|tiff?)$/i.test(path)) return null + try { + const attrs = $.NSFileManager.defaultManager.attributesOfItemAtPathError(path, null) + if (attrs.fileType.js !== $.NSFileTypeRegular.js || !(Number(attrs.fileSize) <= 32 * 1024 * 1024)) return null + if (/\.png$/i.test(path)) { + const png = $.NSData.dataWithContentsOfFile(path) + return png && !png.isNil() ? png : null + } + const img = $.NSImage.alloc.initWithContentsOfFile(path) + const rep = $.NSBitmapImageRep.imageRepWithData(img.TIFFRepresentation) + const png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({})) + return png && !png.isNil() ? png : null + } catch (_) { return null } +} + +function resolveCommandKey() { + const modifiers = [ + [0x7000000E3, 'meta_l'], [0x7000000E7, 'meta_r'], [0x7000000E2, 'alt'], + [0x7000000E6, 'alt_r'], [0x7000000E0, 'ctrl'], [0x7000000E4, 'ctrl_r'], + [0x700000039, 'caps_lock'], [0x7000000E1, 'shift'], [0x7000000E5, 'shift_r'], + ] + const map = new Map(modifiers.map(([usage]) => [usage, usage])) + function normUsage(v) { + if (typeof v !== 'number' && !(typeof v === 'string' && /^(?:0x[\da-f]+|\d+)$/i.test(v))) return NaN + const n = Number(v) + if (!Number.isSafeInteger(n)) return NaN + return n >= 0 && n < 0x10000 ? n + 0x700000000 : n + } + function apply(src, dst) { + src = normUsage(src) + dst = normUsage(dst) + if (map.has(src) && Number.isFinite(dst)) map.set(src, dst) + } + function preference(key) { + try { + const value = $.CFPreferencesCopyValue($(key), $.kCFPreferencesAnyApplication, + $.kCFPreferencesCurrentUser, $.kCFPreferencesCurrentHost) + const entries = value ? ObjC.deepUnwrap(ObjC.castRefToObject(value)) : null + if (Array.isArray(entries)) return entries + } catch (_) {} + return [] + } + let entries = preference('com.apple.keyboard.modifiermapping.1575-1-0') + if (!entries.length) entries = preference('com.apple.keyboard.modifiermapping.0-0-0') + for (const entry of entries) { + if (entry) apply(entry.HIDKeyboardModifierMappingSrc, entry.HIDKeyboardModifierMappingDst) + } + try { + const task = $.NSTask.alloc.init + const pipe = $.NSPipe.pipe + task.launchPath = '/usr/bin/hidutil' + task.arguments = $(['property', '--get', 'UserKeyMapping']) + task.standardOutput = pipe + task.standardError = $.NSFileHandle.fileHandleWithNullDevice + task.launch + const data = pipe.fileHandleForReading.readDataToEndOfFile + task.waitUntilExit + if (task.terminationStatus === 0) { + const output = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js + for (const block of output.match(/\{[^{}]*\}/g) || []) { + const src = /"?HIDKeyboardModifierMappingSrc"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block) + const dst = /"?HIDKeyboardModifierMappingDst"?\s*[:=]\s*(0x[\da-f]+|\d+)\b/i.exec(block) + if (src && dst) apply(src[1], dst[1]) + } + } + } catch (_) {} + for (const command of [0x7000000E3, 0x7000000E7]) { + for (const [usage, qcode] of modifiers) { + if (map.get(usage) === command) return qcode + } + } + return 'meta_l' +} + +function requestPaste(url, id, activateClick, commandKey, focusWaitMs) { + const rawTok = $.NSProcessInfo.processInfo.environment.objectForKey($('REIMS_TOKEN')) + const token = rawTok && !rawTok.isNil() ? rawTok.js : '' + if (!token || /[\r\n\0]/.test(url + token) || !/^[A-Za-z0-9_-]+$/.test(id)) throw Error('Invalid paste request') + const body = {drop_id: id} + if (activateClick) body.activate_click = true + if (commandKey && commandKey !== 'meta_l') body.command_key = commandKey + if (focusWaitMs > 0) body.focus_wait_ms = focusWaitMs + const config = ['url = ' + JSON.stringify(url), 'header = ' + JSON.stringify('Authorization: Bearer ' + token), + 'header = "Content-Type: application/json"', 'data-raw = ' + JSON.stringify(JSON.stringify(body))].join('\n') + '\n' + const task = $.NSTask.alloc.init + const input = $.NSPipe.pipe + task.launchPath = '/usr/bin/curl' + task.arguments = $(['-fsS', '-m', '10', '-X', 'POST', '-K', '-']) + task.standardInput = input + task.standardOutput = $.NSFileHandle.fileHandleWithNullDevice + task.launch + try { input.fileHandleForWriting.writeData($(config).dataUsingEncoding($.NSUTF8StringEncoding)) } + finally { input.fileHandleForWriting.closeFile } + task.waitUntilExit + if (task.terminationStatus !== 0) throw Error('Paste request failed') +} + +function pasteCore(hitArgs, expected, bundleId, mode, url, id, items) { + const {top, windows} = hit(hitArgs) + if (!top || String(top.kCGWindowNumber || 0) !== expected) return 'cancelled' + const ownerApp = top.kCGWindowOwnerPID + ? $.NSRunningApplication.runningApplicationWithProcessIdentifier(top.kCGWindowOwnerPID) : null + const isTopOfApp = windows.find(w => w.kCGWindowOwnerPID === top.kCGWindowOwnerPID)?.kCGWindowNumber === top.kCGWindowNumber + const fm0 = $.NSWorkspace.sharedWorkspace.frontmostApplication + const alreadyActive = !!(fm0 && !fm0.isNil() && fm0.processIdentifier === top.kCGWindowOwnerPID) + let activated = false + if (ownerApp && isTopOfApp) { + if (bundleId === 'com.apple.finder' && ownerApp.bundleURL && !ownerApp.bundleURL.isNil()) { + $.NSWorkspace.sharedWorkspace.openURL(ownerApp.bundleURL) + $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.15)) + activated = true + } else if (!alreadyActive) { + ownerApp.activateWithOptions($.NSApplicationActivateIgnoringOtherApps) + $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.12)) + activated = true + } + } + if (activated && !(hit(hitArgs).windows || []).some(w => String(w.kCGWindowNumber) === expected)) return 'cancelled' + const fm = $.NSWorkspace.sharedWorkspace.frontmostApplication + const activateClick = !!(top.kCGWindowOwnerPID && (!isTopOfApp || !fm || fm.isNil() || fm.processIdentifier !== top.kCGWindowOwnerPID)) + const pb = $.NSPasteboard.generalPasteboard + const savedItems = [] + const clipboardItems = pb.pasteboardItems + if (clipboardItems && !clipboardItems.isNil()) { + for (let i = 0; i < clipboardItems.count; i++) { + const item = clipboardItems.objectAtIndex(i) + const pairs = [] + const types = item.types + for (let j = 0; j < types.count; j++) { + const type = types.objectAtIndex(j) + if (type.js === 'org.nspasteboard.TransientType' || type.js === 'org.nspasteboard.AutoGeneratedType') continue + try { + const data = item.dataForType(type) + if (data && !data.isNil()) pairs.push({type, data}) + } catch (_) { /* The owner could not provide this promised flavor. */ } + } + if (pairs.length) savedItems.push(pairs) + } + } + let primaryErr = null + try { + pb.clearContents + const newItems = items.map(path => { + const item = $.NSPasteboardItem.alloc.init + if (mode === 'files') { + const png = items.length === 1 && bundleId !== 'com.apple.finder' ? readImagePNG(path) : null + if ((!png || !browserBundles.has(bundleId)) && + !item.setStringForType($.NSURL.fileURLWithPath(path).absoluteString, $.NSPasteboardTypeFileURL)) + throw Error('Cannot stage file') + if (png && !item.setDataForType(png, $.NSPasteboardTypePNG)) throw Error('Cannot stage PNG') + } else if (mode === 'text' || mode === 'text-raw') { + const value = mode === 'text-raw' ? $(path) : $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null) + if (!value || value.isNil() || !item.setStringForType(value, $.NSPasteboardTypeString)) + throw Error('Cannot stage text') + } else throw Error('Invalid paste mode') + return addStealth(item) + }) + if (!pb.writeObjects($(newItems))) throw Error('Cannot stage clipboard') + requestPaste(url, id, activateClick, resolveCommandKey(), bundleId === 'com.apple.finder' ? 220 : 0) + return 'pasted' + } catch (err) { + primaryErr = err + throw err + } finally { + pb.clearContents + const restored = savedItems.map(pairs => { + const item = $.NSPasteboardItem.alloc.init + for (const {type, data} of pairs) { + try { item.setDataForType(data, type) } catch (_) { /* Continue with the remaining flavors. */ } + } + return addStealth(item) + }) + if (restored.length && !pb.writeObjects($(restored)) && !primaryErr) throw Error('Cannot restore clipboard') + } +} + +function parseEventData(eventFile) { + const ev = JSON.parse($.NSString.stringWithContentsOfFileEncodingError(eventFile, $.NSUTF8StringEncoding, null).js) + if (!ev || typeof ev.drop_id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ev.drop_id)) throw Error('Invalid drop ID') + if (!Number.isInteger(ev.display_index) || ev.display_index < 0 || + ![ev.norm_x, ev.norm_y].every(n => Number.isFinite(n) && n >= 0 && n <= 1) || + [ev.webdav_drop, ev.in_image].some(v => v !== undefined && typeof v !== 'boolean')) throw Error('Invalid drop location') + if (ev.kind === undefined) ev.kind = 'files' + ev.webdav_drop = ev.webdav_drop === true + ev.in_image = ev.in_image === true + if (ev.kind === 'text') { + if (typeof ev.text !== 'string' || !ev.text.length) throw Error('Invalid drop text') + } else { + if (ev.kind !== 'files') throw Error('Invalid drop kind') + const safePath = n => typeof n === 'string' && !/[\\\n\r\0\t]/.test(n) && + n.split('/').every(segment => segment && segment !== '.' && segment !== '..') + if (!Array.isArray(ev.items) || !ev.items.length || !ev.items.every(safePath)) throw Error('Invalid drop item') + ev.targets = ev.target_paths === undefined ? ev.items : ev.target_paths + if (!Array.isArray(ev.targets) || ev.targets.length !== ev.items.length || !ev.targets.every(safePath)) + throw Error('Invalid drop target path') + } + return ev +} + +function eventLines(ev) { + const header = [ev.drop_id, ev.kind, ev.webdav_drop, ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].join('\t') + return [header].concat(ev.kind === 'files' ? ev.items.map((src, i) => src + '\t' + ev.targets[i]) : []) +} + +function encodeAck(drop_id, status, target_kind, label, error, names) { + return JSON.stringify({drop_id, status, target_kind, target_label: label || undefined, + error: error || undefined, placed_names: names.length ? names : undefined}) +} + +function mountHealthy(paths) { + try { + return paths.length > 0 && paths.every(p => { + const ref = $.NSURL.fileURLWithPath(p).fileReferenceURL + return ref && (typeof ref.isNil !== 'function' || !ref.isNil()) + }) + } catch (_) { return false } +} + +function importPhotos(paths) { + Application('com.apple.Photos').import(paths.map(p => Path(p)), {skipCheckDuplicates: false}) + return 'ok' +} + +function photosError(err) { + const msg = String(err && err.message || err || '').replace(/[\r\n\t]+/g, ' ').trim() + if (/1743|not authorized|permission|privilege/i.test(msg)) return 'Photos import blocked: allow Automation access to Photos in macOS Privacy & Security' + return msg ? 'Photos import failed: ' + msg.slice(0, 140) : 'Photos import failed' +} + +function runDrop(eventFile, mount, url) { + const ev = parseEventData(eventFile) + const hitArgs = [ev.display_index, ev.norm_x, ev.norm_y, ev.in_image].map(String) + const target = resolve(hitArgs) + const [kind, label, meta, expected] = target.split('\t') + function done(status) { + return 'done\t' + encodeAck(ev.drop_id, status, status === 'cancelled' ? 'cancelled' : kind, + status === 'cancelled' ? '' : label, '', []) + } + function perform(mode, paths) { + try { + if (kind === 'photos') { + importPhotos(paths) + return done('placed') + } + return done(pasteCore(hitArgs, expected, meta, mode, url, ev.drop_id, paths)) + } catch (err) { + return 'done\t' + encodeAck(ev.drop_id, 'failed', kind, label, + kind === 'photos' ? photosError(err) : 'Paste failed', []) + } + } + if (kind === 'none' || (ev.kind === 'text' && kind !== 'window')) return done('cancelled') + if (ev.kind === 'text') return perform('text-raw', [ev.text]) + if ((kind === 'window' || kind === 'photos') && ev.webdav_drop && mount) { + const dir = mount + '/' + ev.drop_id + const fm = $.NSFileManager.defaultManager + const dirRef = Ref() + const paths = ev.items.map(src => dir + '/' + src) + if (fm.fileExistsAtPathIsDirectory(dir, dirRef) && dirRef[0] && mountHealthy([mount, dir]) && + paths.every(p => fm.fileExistsAtPath(p))) { + return perform('files', paths) + } + } + const [header, ...items] = eventLines(ev) + return ['fallback', header, target].concat(items).join('\n') +} + +function run(argv) { + const [mode, ...args] = argv + if (mode === 'run-drop') return runDrop(...args) + if (mode === 'resolve') return resolve(args) + if (mode === 'check-mount') { + if (!mountHealthy(args)) throw Error('Unreachable mount') + return 'ok' + } + if (mode === 'paste-drop') { + const [, , , expected, bundleId, kind, url, id, ...paths] = args + return pasteCore(args.slice(0, 3), expected, bundleId, kind, url, id, paths) + } + if (mode === 'import-photos') return importPhotos(args) + if (mode === 'parse-event') { + const ev = parseEventData(args[0]) + if (ev.kind === 'text' && (!args[1] || + !$.NSString.stringWithString(ev.text).writeToFileAtomicallyEncodingError(args[1], true, $.NSUTF8StringEncoding, null))) + throw Error('Invalid drop text') + return eventLines(ev).join('\n') + } + if (mode === 'encode-ack') return encodeAck(...args.slice(0, 5), args.slice(5)) + throw Error('Unknown drop command') +} diff --git a/internal/guesttools/drop_test.go b/internal/guesttools/drop_test.go new file mode 100644 index 0000000..747ea90 --- /dev/null +++ b/internal/guesttools/drop_test.go @@ -0,0 +1,255 @@ +package guesttools + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func TestHostDropEndpoint(t *testing.T) { + s := NewServer(nil) + port, err := s.Start(-1) + if err != nil { + t.Fatal(err) + } + defer s.Close(context.Background()) + cfg := VMConfig{VMName: "mac", Token: strings.Repeat("g", 64)} + s.RegisterVM(cfg) + host := s.HostDropToken(cfg.DriverID, cfg.VMName) + if len(host) != 64 || host == cfg.Token { + t.Fatal("invalid host-only credential") + } + request := func(method, path, token, body string, status int) *http.Response { + t.Helper() + req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { resp.Body.Close() }) + if resp.StatusCode != status { + t.Fatalf("%s %s: got %d, want %d", method, path, resp.StatusCode, status) + } + return resp + } + const path = "/v1/host-drop" + const valid = `{"display_index":2,"norm_x":-1,"norm_y":2,"in_image":true,"paths":["demo"]}` + request("POST", path, "", valid, 401) + request("POST", path, cfg.Token, valid, 401) + request("GET", "/v1/config", host, "", 401) + request("GET", "/v1/files", host, "", 401) + request("GET", path, host, "", 405) + for _, invalid := range []string{"{", `{"paths":[]}`, `{"paths":["a"],"display_index":-1}`, + `{"paths":["a"],"norm_x":NaN}`, `{"paths":["a"],"extra":0}`, valid + "{}", + `{"paths":[` + strings.Repeat(`"a",`, MaxHostDropPaths) + `"a"]}`} { + request("POST", path, host, invalid, 400) + } + request("POST", path, host, strings.Repeat(" ", MaxHostDropBodyBytes+1), 413) + request("POST", path, host, valid, 503) + want := HostDropResult{DropID: "id", Mode: "l1_share", Delivered: []string{"demo"}} + s.SetHostDropHandler(func(key, name string, req HostDropRequest) (HostDropResult, error) { + if key != vmRegistryKey(cfg.DriverID, cfg.VMName) || name != cfg.VMName || + req.NormX != 0 || req.NormY != 1 || req.DisplayIndex != 2 || !req.InImage || !reflect.DeepEqual(req.Paths, []string{"demo"}) { + t.Error("unexpected drop callback arguments") + } + return want, nil + }) + resp := request("POST", path, host, valid, 200) + var result HostDropResult + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || !reflect.DeepEqual(result, want) { + t.Fatalf("result = %+v, err = %v", result, err) + } + s.SetHostDropHandler(func(_, _ string, req HostDropRequest) (HostDropResult, error) { + if req.Text != "你好" || len(req.Paths) != 0 { + t.Errorf("unexpected text drop %+v", req) + } + return want, nil + }) + request("POST", path, host, `{"text":"你好"}`, 200) + request("POST", path, host, `{"paths":["demo"],"text":"你好"}`, 400) + if s.IsConnected(cfg.VMName, time.Minute) { + t.Fatal("host drop marked the guest connected") + } + + key := vmRegistryKey(cfg.DriverID, cfg.VMName) + file := filepath.Join(t.TempDir(), "demo") + if err := os.WriteFile(file, []byte("before"), 0600); err != nil { + t.Fatal(err) + } + if !s.RegisterDropShare(key, "one", []DropShareEntry{{Name: "demo", HostPath: file}}) { + t.Fatal("register failed") + } + if err := os.WriteFile(file, []byte("after"), 0600); err != nil { + t.Fatal(err) + } + other := VMConfig{VMName: "other", Token: "other-token"} + s.RegisterVM(other) + const dav = "/dav-drop/mac/one/demo" + const direct = "/v1/drop-file?drop_id=one&path=demo" + request("GET", dav, other.Token, "", 403) + request("GET", direct, other.Token, "", 404) + for _, url := range []string{dav, direct} { + request("GET", url, host, "", 401) + request("HEAD", url, cfg.Token, "", 200) + resp := request("GET", url, cfg.Token, "", 200) + if b, err := io.ReadAll(resp.Body); err != nil || string(b) != "after" { + t.Fatalf("%s returned %q, err %v", url, b, err) + } + } + request("PUT", direct, cfg.Token, "", 405) + req := httptest.NewRequest("PUT", dav, nil) + req.SetBasicAuth("guest", cfg.Token) + w := httptest.NewRecorder() + s.handleDropWebDAV(w, req) + if w.Code != 403 && w.Code != 405 { + t.Fatalf("DAV PUT returned %d", w.Code) + } + s.RevokeDropShare(key, "one") + request("GET", direct, cfg.Token, "", 404) +} + +func TestDropEventsQueueAndAck(t *testing.T) { + s := NewServer(nil) + cfg := VMConfig{VMName: "mac", Token: "guest"} + s.RegisterVM(cfg) + key := vmRegistryKey(cfg.DriverID, cfg.VMName) + host := s.HostDropToken(cfg.DriverID, cfg.VMName) + const path = "/v1/drop-events" + call := func(method, url, token, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, url, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + switch req.URL.Path { + case path: + s.handleDropEvents(w, req) + case path + "/paste": + s.handleDropEventsPaste(w, req) + case path + "/ack": + s.handleDropEventsAck(w, req) + } + return w + } + check := func(w *httptest.ResponseRecorder, status int) { + t.Helper() + if w.Code != status { + t.Fatalf("got %d (%s), want %d", w.Code, w.Body.String(), status) + } + } + check(call("GET", path, host, ""), 401) + check(call("POST", path+"/ack", host, ""), 401) + check(call("POST", path, cfg.Token, ""), 405) + check(call("GET", path+"/ack", cfg.Token, ""), 405) + if s.HasDropEventListener(key) { + t.Fatal("unexpected listener before first poll") + } + done := make(chan *httptest.ResponseRecorder, 1) + go func() { done <- call("GET", path+"?wait=3", cfg.Token, "") }() + deadline := time.Now().Add(2 * time.Second) + for !s.HasDropEventListener(key) { + if time.Now().After(deadline) { + t.Fatal("poll did not start") + } + time.Sleep(time.Millisecond) + } + ev := DropEvent{DropID: "one", DisplayIndex: 2, NormX: .2, NormY: .7, InImage: true, Items: []string{"demo"}} + if !s.EnqueueDropEvent(key, ev) { + t.Fatal("enqueue failed") + } + w := <-done + check(w, 200) + var got DropEvent + ev.Kind = "files" + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || !reflect.DeepEqual(got, ev) { + t.Fatalf("event %+v, error %v", got, err) + } + const paste = `{"drop_id":"one","activate_click":true}` + check(call("POST", path+"/paste", host, paste), 401) + check(call("POST", path+"/paste", "invalid", paste), 401) + check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"missing"}`), 404) + check(call("POST", path+"/paste", cfg.Token, paste), 503) + s.dropPasteSettle = 5 * time.Millisecond + calls := 0 + wantKey := "meta_l" + var wantFocusWait time.Duration + s.SetDropPasteHandler(func(_ context.Context, k, n, id string, display int, x, y float64, activateClick bool, commandKey string, focusWait time.Duration) error { + calls++ + if k != key || n != cfg.VMName || id != ev.DropID || display != ev.DisplayIndex || x != ev.NormX || y != ev.NormY || !activateClick || commandKey != wantKey || focusWait != wantFocusWait { + t.Error("unexpected paste arguments") + } + return nil + }) + start := time.Now() + check(call("POST", path+"/paste", cfg.Token, paste), 200) + if calls != 1 || time.Since(start) < s.dropPasteSettle { + t.Fatal("paste handshake returned before completion") + } + wantKey = "alt" + wantFocusWait = 220 * time.Millisecond + check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","activate_click":true,"command_key":"alt","focus_wait_ms":220}`), 200) + check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","command_key":"ret"}`), 400) + check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","focus_wait_ms":-1}`), 400) + check(call("POST", path+"/paste", cfg.Token, `{"drop_id":"one","focus_wait_ms":501}`), 400) + if calls != 2 { + t.Fatalf("got %d paste calls, want 2", calls) + } + const valid = `{"drop_id":"one","status":"placed","target_kind":"desktop"}` + count := 0 + s.SetDropAckHandler(func(k, n string, ack DropEventAck) { + count++ + if k != key || n != cfg.VMName || ack.DropID != ev.DropID { + t.Errorf("unexpected callback %s %s %+v", k, n, ack) + } + }) + for _, body := range []string{"{", "{}", valid + "{}", strings.Replace(valid, "placed", "other", 1), + strings.Replace(valid, "desktop", "other", 1), strings.Replace(valid, "{", `{"extra":0,`, 1)} { + check(call("POST", path+"/ack", cfg.Token, body), 400) + } + check(call("POST", path+"/ack", cfg.Token, strings.Repeat(" ", MaxDropAckBodyBytes+1)), 413) + for i := 0; i < 2; i++ { + check(call("POST", path+"/ack", cfg.Token, valid), 200) + } + check(call("POST", path+"/paste", cfg.Token, paste), 404) + ev.CreatedAt = time.Now().Add(-2 * DropEventTTL) + s.EnqueueDropEvent(key, ev) + check(call("GET", path+"?wait=0", cfg.Token, ""), 204) + ev.CreatedAt = time.Time{} + s.EnqueueDropEvent(key, ev) + check(call("GET", path+"?wait=0", cfg.Token, ""), 200) + s.mu.Lock() + s.vms[key].dropActive[ev.DropID].CreatedAt = time.Now().Add(-2 * DropEventTTL) + s.mu.Unlock() + check(call("POST", path+"/ack", cfg.Token, valid), 200) + if count != 1 || !s.HasDropEventListener(key) { + t.Fatalf("callbacks %d, recent listener %v", count, s.HasDropEventListener(key)) + } + for _, pair := range [][2]string{{"pasted", "window"}, {"placed", "photos"}, {"cancelled", "cancelled"}} { + ev := DropEvent{DropID: "one", Kind: "text", Text: "hello", WebDAVDrop: true} + if !s.EnqueueDropEvent(key, ev) { + t.Fatal("text enqueue failed") + } + w := call("GET", path+"?wait=0", cfg.Token, "") + check(w, 200) + var got DropEvent + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || !reflect.DeepEqual(got, ev) { + t.Fatalf("text event %+v, err %v", got, err) + } + body := fmt.Sprintf(`{"drop_id":"one","status":%q,"target_kind":%q}`, pair[0], pair[1]) + check(call("POST", path+"/ack", cfg.Token, body), 200) + } + if count != 4 { + t.Fatalf("got %d ack callbacks", count) + } +} diff --git a/internal/guesttools/drop_webdav.go b/internal/guesttools/drop_webdav.go new file mode 100644 index 0000000..c3a52e4 --- /dev/null +++ b/internal/guesttools/drop_webdav.go @@ -0,0 +1,428 @@ +package guesttools + +import ( + "context" + "errors" + "io" + "net/http" + "os" + "path" + "path/filepath" + "reflect" + "regexp" + "runtime" + "sort" + "strings" + "sync" + "time" + "unicode" + + "golang.org/x/net/webdav" +) + +const ( + DropWebDAVTTL = 10 * time.Minute + DropWebDAVMaxLifetime = 60 * time.Minute + MaxDropWebDAVEntries = 64 +) + +var dropIDPattern = regexp.MustCompile("^[A-Za-z0-9_-]+$") + +type DropShareEntry struct { + Name string + HostPath string + IsDir bool +} + +type dropShareRecord struct { + id string + entries map[string]DropShareEntry + order []string + createdAt time.Time + expiresAt time.Time +} + +type dropShareStore struct { + mu sync.RWMutex + now func() time.Time + modTime time.Time + records map[string]*dropShareRecord +} + +func newDropShareStore() *dropShareStore { + return &dropShareStore{now: time.Now, modTime: time.Now(), records: make(map[string]*dropShareRecord)} +} + +func (s *dropShareStore) touchRootLocked(now time.Time) { + if next := s.modTime.Truncate(time.Second).Add(time.Second); now.Before(next) { + now = next + } + s.modTime = now +} + +func (s *dropShareStore) register(id string, entries []DropShareEntry) bool { + if !dropIDPattern.MatchString(id) || len(entries) == 0 { + return false + } + rec := &dropShareRecord{id: id, entries: make(map[string]DropShareEntry, len(entries))} + for _, e := range entries { + if e.Name == "" || e.Name == "." || e.Name == ".." || strings.ContainsAny(e.Name, "/\\") || + strings.IndexFunc(e.Name, unicode.IsControl) >= 0 || !filepath.IsAbs(e.HostPath) { + return false + } + if _, exists := rec.entries[e.Name]; exists { + return false + } + e.HostPath = filepath.Clean(e.HostPath) + rec.entries[e.Name] = e + rec.order = append(rec.order, e.Name) + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + s.prune(now) + delete(s.records, id) + for len(s.records) >= MaxDropWebDAVEntries { + var oldest *dropShareRecord + for _, r := range s.records { + if oldest == nil || r.createdAt.Before(oldest.createdAt) || (r.createdAt.Equal(oldest.createdAt) && r.id < oldest.id) { + oldest = r + } + } + delete(s.records, oldest.id) + } + rec.createdAt, rec.expiresAt = now, now.Add(DropWebDAVTTL) + s.records[id] = rec + s.touchRootLocked(now) + return true +} + +// prune runs with the store locked. +func (s *dropShareStore) prune(now time.Time) { + count := len(s.records) + for id, rec := range s.records { + if !now.Before(rec.expiresAt) { + delete(s.records, id) + } + } + if len(s.records) != count { + s.touchRootLocked(now) + } +} + +func (s *dropShareStore) touch(id string) *dropShareRecord { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + rec := s.records[id] + if rec == nil { + return nil + } + if !now.Before(rec.expiresAt) { + delete(s.records, id) + s.touchRootLocked(now) + return nil + } + rec.expiresAt = now.Add(DropWebDAVTTL) + if limit := rec.createdAt.Add(DropWebDAVMaxLifetime); limit.Before(rec.expiresAt) { + rec.expiresAt = limit + } + snapshot := *rec // entries and order are immutable after registration. + return &snapshot +} + +func (s *dropShareStore) rootSnapshot() (time.Time, []virtualFileInfo) { + s.mu.Lock() + defer s.mu.Unlock() + s.prune(s.now()) + entries := make([]virtualFileInfo, 0, len(s.records)) + for id, rec := range s.records { + entries = append(entries, virtualFileInfo{name: id, when: rec.createdAt}) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].name < entries[j].name }) + return s.modTime, entries +} + +func (s *dropShareStore) revoke(id string) { + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.records[id]; ok { + delete(s.records, id) + s.touchRootLocked(s.now()) + } +} + +func (s *dropShareStore) clear() { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.records) > 0 { + clear(s.records) + s.touchRootLocked(s.now()) + } +} + +type dropWebDAVFS struct{ store *dropShareStore } + +var _ webdav.FileSystem = (*dropWebDAVFS)(nil) + +func (*dropWebDAVFS) Mkdir(context.Context, string, os.FileMode) error { return os.ErrPermission } +func (*dropWebDAVFS) RemoveAll(context.Context, string) error { return os.ErrPermission } +func (*dropWebDAVFS) Rename(context.Context, string, string) error { return os.ErrPermission } + +type virtualFileInfo struct { + name string + when time.Time +} + +func (i virtualFileInfo) Name() string { return i.name } +func (i virtualFileInfo) Size() int64 { return 0 } +func (i virtualFileInfo) Mode() os.FileMode { return os.ModeDir | 0555 } +func (i virtualFileInfo) ModTime() time.Time { return i.when } +func (i virtualFileInfo) IsDir() bool { return true } +func (i virtualFileInfo) Sys() any { return nil } + +type virtualDAVDir struct { + info virtualFileInfo + entries []os.FileInfo +} + +func (d *virtualDAVDir) Stat() (os.FileInfo, error) { return d.info, nil } +func (*virtualDAVDir) Close() error { return nil } +func (*virtualDAVDir) Read([]byte) (int, error) { return 0, os.ErrInvalid } +func (*virtualDAVDir) Seek(int64, int) (int64, error) { return 0, os.ErrInvalid } +func (*virtualDAVDir) Write([]byte) (int, error) { return 0, os.ErrPermission } + +func (d *virtualDAVDir) Readdir(n int) ([]os.FileInfo, error) { + if n > 0 && len(d.entries) == 0 { + return nil, io.EOF + } + if n <= 0 || n > len(d.entries) { + n = len(d.entries) + } + out := d.entries[:n] + d.entries = d.entries[n:] + return out, nil +} + +type dropNamedInfo struct { + os.FileInfo + name string +} + +func (i dropNamedInfo) Name() string { return i.name } + +// IsDropSymlink reports whether a drop entry is a symlink, irregular file, or Windows reparse point. +func IsDropSymlink(st os.FileInfo) bool { + if st.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 { + return true + } + if runtime.GOOS == "windows" { + v := reflect.Indirect(reflect.ValueOf(st.Sys())) + if v.Kind() == reflect.Struct { + attr := v.FieldByName("FileAttributes") + return attr.CanUint() && attr.Uint()&0x400 != 0 + } + } + return false +} + +func dropEntryInfo(e DropShareEntry) (os.FileInfo, error) { + st, err := os.Lstat(e.HostPath) + if err != nil { + return nil, err + } + if IsDropSymlink(st) || st.IsDir() != e.IsDir || (!e.IsDir && !st.Mode().IsRegular()) { + return nil, os.ErrPermission + } + return st, nil +} + +func (f *dropWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.FileMode) (webdav.File, error) { + const writeFlags = os.O_WRONLY | os.O_RDWR | os.O_CREATE | os.O_TRUNC | os.O_APPEND | os.O_EXCL + if flag&writeFlags != 0 { + return nil, os.ErrPermission + } + if strings.Contains("/"+name+"/", "/../") { + return nil, os.ErrInvalid + } + rel, err := davRelativePath(name) + if err != nil { + return nil, err + } + if rel == "." { + when, entries := f.store.rootSnapshot() + d := &virtualDAVDir{info: virtualFileInfo{name: ".", when: when}} + for _, entry := range entries { + d.entries = append(d.entries, entry) + } + return d, nil + } + id, rest, hasRest := strings.Cut(rel, "/") + rec := f.store.touch(id) + if rec == nil { + return nil, os.ErrNotExist + } + if !hasRest { + d := &virtualDAVDir{info: virtualFileInfo{name: id, when: rec.createdAt}} + for _, alias := range rec.order { + if st, err := dropEntryInfo(rec.entries[alias]); err == nil { + d.entries = append(d.entries, dropNamedInfo{st, alias}) + } + } + return d, nil + } + alias, sub, hasSub := strings.Cut(rest, "/") + e, ok := rec.entries[alias] + if !ok || (hasSub && !e.IsDir) { + return nil, os.ErrNotExist + } + expected, err := dropEntryInfo(e) + if err != nil { + return nil, err + } + dir, target := filepath.Dir(e.HostPath), filepath.Base(e.HostPath) + if e.IsDir { + dir, target = e.HostPath, "." + } + root, err := os.OpenRoot(dir) + if err != nil { + return nil, err + } + // Pin each checked directory before looking up its child. + defer func() { + if root != nil { + root.Close() + } + }() + if e.IsDir { + st, err := statDAVEntry(root, ".") + if err != nil { + return nil, err + } + if IsDropSymlink(st) || !os.SameFile(expected, st) { + return nil, os.ErrPermission + } + } + if hasSub { + alias = path.Base(sub) + for { + part, tail, more := strings.Cut(sub, "/") + expected, err = statDAVEntry(root, part) + if err != nil { + return nil, err + } + if IsDropSymlink(expected) || (!expected.IsDir() && !expected.Mode().IsRegular()) { + return nil, os.ErrPermission + } + if !more { + target = part + break + } + next, err := root.OpenRoot(part) + if err != nil { + return nil, err + } + root.Close() + root = next + st, err := root.Stat(".") + if err != nil { + return nil, err + } + if !os.SameFile(expected, st) { + return nil, os.ErrPermission + } + sub = tail + } + } + file, err := root.Open(target) + if err != nil { + return nil, err + } + st, err := file.Stat() + if err != nil || !os.SameFile(expected, st) { + file.Close() + if err != nil { + return nil, err + } + return nil, os.ErrPermission + } + handle := &dropRootFile{File: file, root: root, name: alias} + root = nil + return handle, nil +} + +type dropRootFile struct { + *os.File + root *os.Root + name string +} + +func (f *dropRootFile) Close() error { return errors.Join(f.File.Close(), f.root.Close()) } + +func (f *dropRootFile) Stat() (os.FileInfo, error) { + st, err := f.File.Stat() + if err != nil { + return nil, err + } + return dropNamedInfo{st, f.name}, nil +} + +func (f *dropRootFile) Readdir(n int) ([]os.FileInfo, error) { + var out []os.FileInfo + for { + count := n + if n > 0 { + count -= len(out) + } + batch, err := f.File.Readdir(count) + for _, st := range batch { + if !IsDropSymlink(st) && (st.IsDir() || st.Mode().IsRegular()) { + out = append(out, st) + } + } + if err != nil || n <= 0 || len(out) == n { + return out, err + } + } +} + +func (f *dropWebDAVFS) Stat(ctx context.Context, name string) (os.FileInfo, error) { + file, err := f.OpenFile(ctx, name, os.O_RDONLY, 0) + if err != nil { + return nil, err + } + defer file.Close() + return file.Stat() +} + +func (f *dropWebDAVFS) serveDropFile(w http.ResponseWriter, r *http.Request, dropID, relPath string) { + rel, err := davRelativePath(relPath) + if !dropIDPattern.MatchString(dropID) || err != nil || rel != relPath || rel == "." { + http.Error(w, "invalid drop path", http.StatusBadRequest) + return + } + file, err := f.OpenFile(r.Context(), path.Join("/", dropID, rel), os.O_RDONLY, 0) + if err == nil { + defer file.Close() + var st os.FileInfo + st, err = file.Stat() + if err == nil { + if st.IsDir() { + http.Error(w, "expected a file", http.StatusBadRequest) + return + } + http.ServeContent(w, r, st.Name(), st.ModTime(), file) + return + } + } + status := http.StatusInternalServerError + switch { + case errors.Is(err, os.ErrNotExist): + status = http.StatusNotFound + case errors.Is(err, os.ErrPermission): + status = http.StatusForbidden + case errors.Is(err, os.ErrInvalid): + status = http.StatusBadRequest + } + http.Error(w, http.StatusText(status), status) +} diff --git a/internal/guesttools/drop_webdav_test.go b/internal/guesttools/drop_webdav_test.go new file mode 100644 index 0000000..3611121 --- /dev/null +++ b/internal/guesttools/drop_webdav_test.go @@ -0,0 +1,144 @@ +package guesttools + +import ( + "errors" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/net/webdav" +) + +func TestDropWebDAV(t *testing.T) { + f := &dropWebDAVFS{store: newDropShareStore()} + now := time.Unix(1700000000, 0) + start := now + f.store.now = func() time.Time { return now } + dir := t.TempDir() + host := filepath.Join(dir, "host.txt") + if err := os.WriteFile(host, []byte("host content"), 0600); err != nil { + t.Fatal(err) + } + entries := []DropShareEntry{{"alias.txt", host, false}, {"folder", dir, true}} + rootTime := func() time.Time { + t.Helper() + info, err := f.Stat(t.Context(), "/") + if err != nil { + t.Fatal(err) + } + return info.ModTime().Truncate(time.Second) + } + last := rootTime() + checkAdvance := func() { + t.Helper() + next := rootTime() + if !next.After(last) { + t.Fatalf("root modtime %v did not advance past %v", next, last) + } + last = next + } + if !f.store.register("drop", entries) { + t.Fatal("registration failed") + } + checkAdvance() + root, err := f.OpenFile(t.Context(), ".", os.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + defer root.Close() + children, err := root.Readdir(-1) + if err != nil || len(children) != 1 { + t.Fatalf("root children %v, err %v", children, err) + } + child, err := f.OpenFile(t.Context(), "/drop", os.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + defer child.Close() + info, err := child.Stat() + if err != nil || children[0].Name() != "drop" || !children[0].ModTime().Equal(info.ModTime()) { + t.Fatalf("listed child %v, opened child %v, err %v", children[0], info, err) + } + const prefix = "/dav-drop/mac" + h := &webdav.Handler{Prefix: prefix, FileSystem: f, LockSystem: webdav.NewMemLS()} + request := func(method, name string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, prefix+name, nil) + r.Header.Set("Depth", "1") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + direct := func(id, rel string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + f.serveDropFile(w, httptest.NewRequest("GET", "/", nil), id, rel) + return w + } + for name, child := range map[string]string{"/": "/drop", "/drop": "/alias.txt", "/drop/folder": "/host.txt"} { + if w := request("OPTIONS", name); w.Code != 200 || w.Header().Get("DAV") == "" { + t.Errorf("OPTIONS %s: %d %v", name, w.Code, w.Header()) + } + if w := request("PROPFIND", name); w.Code != 207 || !strings.Contains(w.Body.String(), prefix+strings.TrimSuffix(name, "/")+child) { + t.Errorf("PROPFIND %s: %d %s", name, w.Code, w.Body) + } + } + for _, rel := range []string{"alias.txt", "folder/host.txt"} { + for _, w := range []*httptest.ResponseRecorder{request("GET", "/drop/"+rel), direct("drop", rel)} { + if w.Code != 200 || w.Body.String() != "host content" { + t.Errorf("GET %s: %d %s", rel, w.Code, w.Body) + } + } + } + for method, name := range map[string]string{"PUT": "/drop/alias.txt", "DELETE": "/drop/alias.txt", "MKCOL": "/drop/folder/new"} { + if w := request(method, name); w.Code < 400 { + t.Errorf("%s succeeded: %d", method, w.Code) + } + } + if w := direct("unknown", "alias.txt"); w.Code != 404 { + t.Errorf("unknown drop: %d", w.Code) + } + for _, rel := range []string{"folder/../alias.txt", "/alias.txt", ".", "", "folder"} { + if w := direct("drop", rel); w.Code != 400 { + t.Errorf("direct path %q: %d", rel, w.Code) + } + } + if _, err := f.Stat(t.Context(), "/drop/folder/../alias.txt"); !errors.Is(err, os.ErrInvalid) { + t.Errorf("traversal: %v", err) + } + t.Run("symlink", func(t *testing.T) { + link := filepath.Join(dir, "link") + if err := os.Symlink(dir, link); err != nil { + t.Skipf("cannot create symlink: %v", err) + } + if w := request("PROPFIND", "/drop/folder"); w.Code != 207 || strings.Contains(w.Body.String(), "/folder/link") { + t.Errorf("symlink listing: %d %s", w.Code, w.Body) + } + for _, rel := range []string{"folder/link", "folder/link/host.txt"} { + if w := direct("drop", rel); w.Code != 403 { + t.Errorf("symlink %s: %d", rel, w.Code) + } + } + }) + for elapsed := DropWebDAVTTL - time.Minute; elapsed < DropWebDAVMaxLifetime; elapsed += DropWebDAVTTL - time.Minute { + now = start.Add(elapsed) + if w := direct("drop", "alias.txt"); w.Code != 200 { + t.Fatalf("read at %v: %d", elapsed, w.Code) + } + } + now = start.Add(DropWebDAVMaxLifetime) + if w := direct("drop", "alias.txt"); w.Code != 404 { + t.Errorf("maximum lifetime: %d", w.Code) + } + checkAdvance() + if !f.store.register("drop", entries) { + t.Fatal("re-registration failed") + } + checkAdvance() + f.store.revoke("drop") + checkAdvance() + if w := direct("drop", "alias.txt"); w.Code != 404 { + t.Errorf("revoked drop: %d", w.Code) + } +} diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 453fac3..4173485 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -43,8 +43,8 @@ func TestGuestAgentFolderMounts(t *testing.T) { "/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command", ) uninstall = dnsPaths.Replace(uninstall) - if CurrentAgentVersion != HostDNSAgentVersion { - t.Fatalf("CurrentAgentVersion = %d, want Host DNS version %d", CurrentAgentVersion, HostDNSAgentVersion) + if CurrentAgentVersion != WindowDropAgentVersion { + t.Fatalf("CurrentAgentVersion = %d, want window drop version %d", CurrentAgentVersion, WindowDropAgentVersion) } 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 dc2460f..177799f 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -17,7 +17,8 @@ const SharedFolderAgentVersion = 9 const KeymapAgentVersion = 10 const TimezoneAgentVersion = 11 const HostDNSAgentVersion = 12 -const CurrentAgentVersion = HostDNSAgentVersion +const WindowDropAgentVersion = 13 +const CurrentAgentVersion = WindowDropAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 9622677..8f50352 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -25,6 +25,12 @@ const ( //go:embed file_sync.sh var guestFileSync string +//go:embed drop_resolve.js +var guestDropResolveJS string + +//go:embed drop_agent.sh +var guestDropAgent string + //go:embed dns-proxy.pl var guestDNSProxy []byte @@ -44,6 +50,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL='http://10.0.2.2:%d'\nREIMS_HOST_PORT='%d'\nREIMS_TOKEN=%s\nREIMS_VM=%s\n", cfg.Port, cfg.Port, shellSingleQuote(cfg.Token), shellSingleQuote(cfg.VMName))) agentBytes := GuestAgentScript() + dropResolveJS := strings.ReplaceAll(guestDropResolveJS, "\r\n", "\n") installBytes := GuestInstallScript() uninstallBytes := GuestUninstallScript() pmsetBytes := GuestPmsetScript() @@ -55,6 +62,12 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { Size: int64(len(confBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(confBytes)), nil }, }, + { + Name: "drop-resolve.js", + Mode: 0o100755, + Size: int64(len(dropResolveJS)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(dropResolveJS)), nil }, + }, { Name: "guest-tools.sh", Mode: 0o100755, @@ -131,6 +144,8 @@ APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" CONF="$APP_DIR/config" SHARE_SYNC="$HOME/ReimsShare" SHARE_MOUNT="$HOME/ReimsShareMount" +DROP_MOUNT="$HOME/Library/Caches/ReimsDropMount" +DROP_CACHE="$HOME/Library/Caches/ReimsDropCache" DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" @@ -138,11 +153,13 @@ FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" DESKTOP_LINK="$HOME/Desktop/ReimsShare" TMP_DIR="$APP_DIR/tmp" INJECT_LOCK="$TMP_DIR/injecting" -mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR" -rm -f "$INJECT_LOCK" 2>/dev/null || true +DROP_INJECT_LOCK="$TMP_DIR/drop-injecting" +mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR" "$DROP_MOUNT" +rm -f "$INJECT_LOCK" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true CAFFEINATE_PID="" TEXT_INPUT_PID="" +DROP_EVENTS_PID="" keymap_active="false" keymap_applied="false" ` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` @@ -155,10 +172,13 @@ cleanup() { if [ -n "$CAFFEINATE_PID" ]; then kill "$CAFFEINATE_PID" 2>/dev/null || true fi + if [ -n "${DROP_EVENTS_PID:-}" ]; then + kill "$DROP_EVENTS_PID" 2>/dev/null || true + fi if [ -n "$TEXT_INPUT_PID" ]; then kill "$TEXT_INPUT_PID" 2>/dev/null || true fi - rm -f "$INJECT_LOCK" 2>/dev/null || true + rm -f "$INJECT_LOCK" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true } trap cleanup EXIT trap 'exit 0' INT TERM @@ -225,7 +245,8 @@ ensure_webdav_mount() { host_addr=${host_addr%/} dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/$(urlencode "$REIMS_VM")/" mkdir -p "$SHARE_MOUNT" - if mount_webdav -v "ReimsShare" "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1 || \ + if mount_authenticated_webdav -v "ReimsShare" "${REIMS_HOST_URL%/}/dav/$(urlencode "$REIMS_VM")/" "$SHARE_MOUNT" >/dev/null 2>&1 || \ + mount_webdav -v "ReimsShare" "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1 || \ mount_webdav "$dav_url" "$SHARE_MOUNT" >/dev/null 2>&1; then mount_mode="webdav" update_desktop_link "$SHARE_MOUNT" @@ -263,6 +284,22 @@ mount_authenticated_webdav() ( } 3<"$auth_file" 4>"$auth_file" ) +ensure_drop_webdav_mount() { + [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] && [ -n "$REIMS_VM" ] || return 0 + if is_reims_dav_mounted "$DROP_MOUNT" "/dav-drop/$(urlencode "$REIMS_VM")/"; then + mount 2>/dev/null | awk -v mp="$DROP_MOUNT" ' + index($0, " on " mp " (") && /[(,] *nobrowse *[,)]/ { found=1 } + END { exit !found }' || return 0 + unmount_shared_folder "$DROP_MOUNT" >/dev/null 2>&1 || return 0 + fi + if [ -L "$DROP_MOUNT" ] || is_drive_mounted "$DROP_MOUNT" || ! command -v mount_webdav >/dev/null 2>&1; then + return 0 + fi + mkdir -p "$DROP_MOUNT" 2>/dev/null || return 0 + drop_dav_url="${REIMS_HOST_URL%/}/dav-drop/$(urlencode "$REIMS_VM")/" + mount_authenticated_webdav -o rdonly -v "ReimsDrop" "$drop_dav_url" "$DROP_MOUNT" >/dev/null 2>&1 || true +} + mount_drive_readonly() ( drive="$1" target="$2" @@ -572,7 +609,7 @@ TAB=$(printf '\t') sync_clipboard() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - if [ -f "$INJECT_LOCK" ]; then + if [ -f "$INJECT_LOCK" ] || { [ -n "${DROP_INJECT_LOCK:-}" ] && [ -f "$DROP_INJECT_LOCK" ]; }; then sleep 1 return 0 fi @@ -668,7 +705,7 @@ sync_clipboard() { esac } -` + guestFileSync + ` +` + strings.ReplaceAll(guestFileSync+guestDropAgent, "\r\n", "\n") + ` text_input_loop() { hdr="$TMP_DIR/txt_hdr" @@ -710,11 +747,14 @@ text_input_loop() { text_input_loop & TEXT_INPUT_PID=$! +drop_events_loop & +DROP_EVENTS_PID=$! while :; do if [ $((tick % 5)) -eq 0 ]; then load_conf ensure_webdav_mount + ensure_drop_webdav_mount apply_host_config report_status fi @@ -774,6 +814,10 @@ fi mkdir -p "$APP_DIR" "$HOME/Library/LaunchAgents" "$SHARE_SYNC" "$SHARE_MOUNT" cp "$SRC/config" "$APP_DIR/config" cp "$SRC/guest-tools.sh" "$APP_DIR/guest-tools.sh" +if [ -f "$SRC/drop-resolve.js" ]; then + cp "$SRC/drop-resolve.js" "$APP_DIR/drop-resolve.js" + chmod 755 "$APP_DIR/drop-resolve.js" +fi chmod 600 "$APP_DIR/config" chmod 755 "$APP_DIR/guest-tools.sh" [ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE_SYNC" "$HOME/Desktop/ReimsShare" 2>/dev/null || true @@ -856,6 +900,8 @@ APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" CONF="$APP_DIR/config" PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist" SHARE_MOUNT="$HOME/ReimsShareMount" +DROP_MOUNT="$HOME/Library/Caches/ReimsDropMount" +DROP_CACHE="$HOME/Library/Caches/ReimsDropCache" DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" @@ -887,6 +933,8 @@ if owns_folder_link; then fi rm -f "$PLIST" rm -rf "$APP_DIR" +rm -rf "$DROP_CACHE" +rmdir "$DROP_MOUNT" 2>/dev/null || true ` + guestTimezoneUninstall + ` echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept." `) @@ -911,6 +959,9 @@ unmount_reims_shares() ( if is_reims_dav_mounted "$SHARE_MOUNT" "$vm_route/"; then unmount_shared_folder "$SHARE_MOUNT" || unmount_failed=1 fi + if [ -n "${DROP_MOUNT:-}" ] && is_reims_dav_mounted "$DROP_MOUNT" "/dav-drop/$(urlencode "${REIMS_VM:-}")/"; then + unmount_shared_folder "$DROP_MOUNT" || unmount_failed=1 + fi for mount_point in "$DRIVE_MOUNT_ROOT"/*; do [ -d "$mount_point" ] && [ ! -L "$mount_point" ] || continue letter=${mount_point##*/} diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 49e32a1..cae340a 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -25,6 +25,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" + "golang.org/x/net/webdav" ) const ( @@ -221,6 +222,7 @@ type pendingClipOverride struct { type registeredVM struct { key string name string + hostDropToken string token string sharedDir string sharedRoot sharedRoot @@ -247,6 +249,14 @@ type registeredVM struct { agentVersion int lastSeen time.Time + dropShares *dropShareStore + dropDAVHandler *webdav.Handler + dropQueue []*DropEvent + dropActive map[string]*DropEvent + dropNotify chan struct{} + dropWaiters int + lastDropPoll time.Time + injectMu sync.Mutex textSeq uint64 textQueue []*pendingTextInput @@ -281,6 +291,10 @@ type Server struct { httpSrv *http.Server watchCancel context.CancelFunc clipNotify chan struct{} + dropPasteSettle time.Duration + onDropPaste func(ctx context.Context, vmKey, vmName, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error + onDropAck func(vmKey, vmName string, ack DropEventAck) + onHostDrop func(vmKey, vmName string, req HostDropRequest) (HostDropResult, error) onHostText func(vmKey, vmName, text string) onStatusChange func(vmName string) hostDNSConfig HostDNSConfig @@ -354,6 +368,12 @@ func (s *Server) Start(preferredPort int) (int, error) { mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard")) mux.HandleFunc("/v1/text-input", s.handleTextInput) mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck) + mux.HandleFunc("/v1/drop-events", s.handleDropEvents) + mux.HandleFunc("/v1/drop-events/ack", s.handleDropEventsAck) + mux.HandleFunc("/v1/drop-events/paste", s.handleDropEventsPaste) + mux.HandleFunc("/v1/drop-file", s.handleDropFile) + mux.HandleFunc("/dav-drop/", s.handleDropWebDAV) + mux.HandleFunc("/v1/host-drop", s.handleHostDrop) mux.HandleFunc("/v1/host-text", s.handleHostText) mux.HandleFunc("/v1/files", s.handleListFiles) mux.HandleFunc("/v1/file", s.handleFile) @@ -489,12 +509,23 @@ func (s *Server) RegisterVM(cfg VMConfig) { } } if cur == nil { + var secret [32]byte + rand.Read(secret[:]) cur = ®isteredVM{ + hostDropToken: hex.EncodeToString(secret[:]), key: key, name: cfg.VMName, + dropShares: newDropShareStore(), + dropActive: make(map[string]*DropEvent), + dropNotify: make(chan struct{}), textActive: make(map[string]*pendingTextInput), textNotify: make(chan struct{}), } + cur.dropDAVHandler = &webdav.Handler{ + Prefix: "/dav-drop/" + cur.name, + FileSystem: &dropWebDAVFS{store: cur.dropShares}, + LockSystem: webdav.NewMemLS(), + } s.vms[key] = cur } folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders)) @@ -547,6 +578,9 @@ func (s *Server) UnregisterVM(vmKey string) { s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() + if vm := s.vms[key]; vm != nil && vm.dropShares != nil { + vm.dropShares.clear() + } delete(s.vms, key) delete(s.davCache, key) for davKey := range s.davCache { @@ -812,6 +846,8 @@ func (s *Server) authenticateToken(tok string) *registeredVM { key: vm.key, name: vm.name, token: vm.token, + dropShares: vm.dropShares, + dropDAVHandler: vm.dropDAVHandler, sharedDir: vm.sharedDir, sharedRoot: vm.sharedRoot, preventSleep: vm.preventSleep, @@ -858,7 +894,7 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) { http.Error(w, "unauthorized", http.StatusUnauthorized) return } - caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "keymap-carrier"} + caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "keymap-carrier", "drop-events", "drop-webdav", "drop-paste"} if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled { caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...) if policy.SyncImages { @@ -890,6 +926,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { "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 + "/", diff --git a/internal/macos/installer/hfs_image.go b/internal/macos/installer/hfs_image.go index f84ec37..711817e 100644 --- a/internal/macos/installer/hfs_image.go +++ b/internal/macos/installer/hfs_image.go @@ -28,7 +28,8 @@ const ( hfsSector = 512 hfsBlock = 4096 hfsNode = 4096 - hfsCatalogNodes = 128 + hfsCatalogNode = 2 * hfsNode + hfsCatalogNodes = 64 hfsExtentsNodes = 128 hfsAttributesNodes = 64 hfsFirstLBA = 2048 @@ -54,7 +55,7 @@ func BuildHFSPlusDiskImage(destPath, label string, files []HFSFile) error { fileBlocks += uint64((f.Size + hfsBlock - 1) / hfsBlock) } } - metaBlocks := uint64(1 + 4 + hfsExtentsNodes + 2*hfsAttributesNodes + hfsCatalogNodes + 1) + metaBlocks := uint64(1 + 4 + hfsExtentsNodes + 2*hfsAttributesNodes + 2*hfsCatalogNodes + 1) // Add 16 MiB headroom and align partition size to 1 MiB. partBytes := (metaBlocks + fileBlocks) * hfsBlock partBytes += 16 << 20 @@ -245,7 +246,7 @@ func writeHFSPlusVolume(out *os.File, partOff int64, totalBlocks uint32, label s if err != nil { return err } - catalogFork, err := alloc(uint64(hfsCatalogNodes) * hfsNode) + catalogFork, err := alloc(uint64(hfsCatalogNodes) * hfsCatalogNode) if err != nil { return err } @@ -322,15 +323,15 @@ func writeHFSPlusVolume(out *os.File, partOff int64, totalBlocks uint32, label s recs = append(recs, append(hfsKey(e.id, nil), hfsThreadRecord(4, 2, e.name)...)) } - leaf, err := hfsLeafNode(recs) + leaf, err := hfsLeafNode(hfsCatalogNode, recs) if err != nil { return err } - catHdr := hfsHeaderNode(hfsNode, hfsCatalogNodes, 516, 2|4, 0xcf, uint32(len(recs))) + catHdr := hfsHeaderNode(hfsCatalogNode, hfsCatalogNodes, 516, 2|4, 0xcf, uint32(len(recs))) if _, err := out.WriteAt(catHdr, partOff+int64(catalogFork.first)*hfsBlock); err != nil { return err } - if _, err := out.WriteAt(leaf, partOff+int64(catalogFork.first)*hfsBlock+hfsNode); err != nil { + if _, err := out.WriteAt(leaf, partOff+int64(catalogFork.first)*hfsBlock+hfsCatalogNode); err != nil { return err } @@ -421,15 +422,15 @@ func hfsHeaderNode(nodeSize int, nodes uint32, maxKey uint16, attrs uint32, comp return n } -func hfsLeafNode(recs [][]byte) ([]byte, error) { - n := make([]byte, hfsNode) +func hfsLeafNode(nodeSize int, recs [][]byte) ([]byte, error) { + n := make([]byte, nodeSize) n[8] = 0xff // kBTLeafNode n[9] = 1 binary.BigEndian.PutUint16(n[10:12], uint16(len(recs))) offsets := make([]uint16, 0, len(recs)+1) at := 14 for _, r := range recs { - if at+len(r)+2*(len(recs)+1) > hfsNode { + if at+len(r)+2*(len(recs)+1) > nodeSize { return nil, fmt.Errorf("HFS+ catalog records exceed one leaf node") } offsets = append(offsets, uint16(at)) @@ -438,7 +439,7 @@ func hfsLeafNode(recs [][]byte) ([]byte, error) { } offsets = append(offsets, uint16(at)) for i, off := range offsets { - binary.BigEndian.PutUint16(n[hfsNode-2-2*i:hfsNode-2*i], off) + binary.BigEndian.PutUint16(n[nodeSize-2-2*i:nodeSize-2*i], off) } return n, nil } diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index 9a8d948..a07d203 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -163,6 +163,12 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo } gtCfg, err := cb.LoadAndRegisterGuestTools(s, port, p.VMDir, p.VMName) if err == nil && gtCfg.Token != "" { + if hasCap(p.RuntimeCaps, "window-file-drop") { + if token := s.HostDropToken(gtCfg.DriverID, p.VMName); token != "" { + intent.Env["REIMS_GO_DROP_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", port) + intent.Env["REIMS_GO_DROP_TOKEN"] = token + } + } if sc.Registry().IsActive(IDInput) && hasCap(p.RuntimeCaps, "win32-unicode-input") { intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port) intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index ae82369..0de0e0a 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -2,6 +2,7 @@ package builtin import ( "context" + "fmt" "testing" "time" @@ -136,6 +137,19 @@ func TestGuestToolsInputBridgeEnvGating(t *testing.T) { t.Fatalf("without capability: unexpected input bridge env %v", env) } + if env := dispatch([]string{"win32-unicode-input"}); env["REIMS_GO_DROP_URL"] != "" || env["REIMS_GO_DROP_TOKEN"] != "" { + t.Fatal("drop environment injected without window-file-drop") + } + checkDrop := func() { + t.Helper() + env := dispatch([]string{"window-file-drop"}) + want := gtSrv.HostDropToken("", "mac") + if want == "" || env["REIMS_GO_DROP_TOKEN"] != want || env["REIMS_GO_DROP_URL"] != fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", gtSrv.Port()) { + t.Fatal("incorrect host drop environment") + } + } + checkDrop() + // Fixed runtime + active builtin.input plugin -> env vars injected. env := dispatch([]string{"win32-unicode-input"}) if env["REIMS_GO_INPUT_URL"] == "" || env["REIMS_GO_INPUT_TOKEN"] == "" { @@ -146,6 +160,7 @@ func TestGuestToolsInputBridgeEnvGating(t *testing.T) { if err := reg.SetDesired(context.Background(), IDInput, false); err != nil { t.Fatal(err) } + checkDrop() if env := dispatch([]string{"win32-unicode-input"}); env["REIMS_GO_INPUT_URL"] != "" || env["REIMS_GO_INPUT_TOKEN"] != "" { t.Fatalf("with input plugin disabled: unexpected input bridge env %v", env) } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index 369278e..13bbff5 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -43,6 +43,8 @@ var BuiltinOnlyQEMUOptionFamilies = map[string]bool{ // AllowedHostEnvVars lists non-namespaced environment variables permitted in // builtin/plugin StartIntents. var AllowedHostEnvVars = map[string]bool{ + "REIMS_GO_DROP_URL": true, + "REIMS_GO_DROP_TOKEN": true, "REIMS_GO_INPUT_URL": true, "REIMS_GO_INPUT_TOKEN": true, "REIMS_VGPU_LOG": true, diff --git a/internal/qmp/keys.go b/internal/qmp/keys.go index 0e17c27..74da21a 100644 --- a/internal/qmp/keys.go +++ b/internal/qmp/keys.go @@ -3,6 +3,7 @@ package qmp import ( "context" "fmt" + "math" "path/filepath" "strings" "time" @@ -206,6 +207,97 @@ func SendPasteShortcut(ctx context.Context, vmDir string) error { return PressCombo(ctx, q, 25*time.Millisecond, "v", "meta_l") } +func absEvent(axis string, value int) map[string]any { + return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}} +} + +func btnEvent(button string, down bool) map[string]any { + return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}} +} + +func clampAbsCoord(norm float64) int { + switch { + case math.IsNaN(norm), math.IsInf(norm, 0), norm <= 0: + return 0 + case norm >= 1: + return 32767 + default: + return int(math.Round(norm * 32767)) + } +} + +// ClickAndPaste clicks at normalized absolute coordinates and presses Command+V. +func ClickAndPaste(ctx context.Context, q Executor, normX, normY float64, clickHold, focusWait, keyHold time.Duration) error { + return ClickAndPasteWithActivate(ctx, q, normX, normY, false, 0, clickHold, focusWait, keyHold, "") +} + +// ClickAndPasteWithActivate optionally activates the window before clicking the paste target. +func ClickAndPasteWithActivate(ctx context.Context, q Executor, normX, normY float64, activateClick bool, activateGap, clickHold, focusWait, keyHold time.Duration, commandKey string) error { + if err := ctx.Err(); err != nil { + return err + } + if err := q.Execute("input-send-event", map[string]any{"events": []map[string]any{ + absEvent("x", clampAbsCoord(normX)), absEvent("y", clampAbsCoord(normY)), + }}); err != nil { + return err + } + sleep(ctx, 15*time.Millisecond) + if activateClick { + if err := leftClick(ctx, q, clickHold); err != nil { + return err + } + sleep(ctx, activateGap) + } + if err := leftClick(ctx, q, clickHold); err != nil { + return err + } + sleep(ctx, focusWait) + if commandKey == "" { + commandKey = "meta_l" + } + return PressCombo(ctx, q, keyHold, "v", commandKey) +} + +func leftClick(ctx context.Context, q Executor, clickHold time.Duration) error { + send := func(events ...map[string]any) error { + return q.Execute("input-send-event", map[string]any{"events": events}) + } + if err := ctx.Err(); err != nil { + return err + } + if err := send(btnEvent("left", true)); err != nil { + return err + } + btnDown := true + defer func() { + if btnDown { + _ = send(btnEvent("left", false)) + } + }() + sleep(ctx, clickHold) + if err := ctx.Err(); err != nil { + return err + } + if err := send(btnEvent("left", false)); err != nil { + return err + } + btnDown = false + return nil +} + +// SendAbsoluteClickAndPaste clicks and pastes through the VM's QMP socket. +func SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error { + q, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer q.Close() + if focusWait <= 0 { + focusWait = 120 * time.Millisecond + } + return ClickAndPasteWithActivate(ctx, q, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey) +} + // TypeIntoVM types text into a running VM through its QMP socket and returns // how many keys it pressed. func TypeIntoVM(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) { diff --git a/internal/qmp/keys_test.go b/internal/qmp/keys_test.go index 800d647..01a7327 100644 --- a/internal/qmp/keys_test.go +++ b/internal/qmp/keys_test.go @@ -6,9 +6,12 @@ import ( "encoding/json" "errors" "fmt" + "math" "net" + "reflect" "strings" "testing" + "time" ) func TestStrokesMapsUSLayout(t *testing.T) { @@ -110,6 +113,99 @@ func TestPressComboAndCleanup(t *testing.T) { } } +func TestClampAbsCoord(t *testing.T) { + for _, tc := range []struct { + norm float64 + want int + }{ + {-1, 0}, {0, 0}, {0.5, 16384}, {1, 32767}, {2, 32767}, + {math.NaN(), 0}, {math.Inf(-1), 0}, {math.Inf(1), 0}, + } { + if got := clampAbsCoord(tc.norm); got != tc.want { + t.Errorf("clampAbsCoord(%v) = %d, want %d", tc.norm, got, tc.want) + } + } +} + +type clickRecorder struct { + batches [][]map[string]any + times []time.Time + cancel context.CancelFunc +} + +func (r *clickRecorder) Execute(command string, args any) error { + if command != "input-send-event" { + return fmt.Errorf("unexpected command %q", command) + } + events := args.(map[string]any)["events"].([]map[string]any) + r.times = append(r.times, time.Now()) + r.batches = append(r.batches, events) + if r.cancel != nil && len(r.batches) == 2 { + r.cancel() + } + return nil +} + +func TestClickAndPaste(t *testing.T) { + want := [][]map[string]any{ + { + {"type": "abs", "data": map[string]any{"axis": "x", "value": 16384}}, + {"type": "abs", "data": map[string]any{"axis": "y", "value": 32767}}, + }, + {{"type": "btn", "data": map[string]any{"button": "left", "down": true}}}, + {{"type": "btn", "data": map[string]any{"button": "left", "down": false}}}, + {keyEvent("meta_l", true)}, {keyEvent("v", true)}, + {keyEvent("v", false)}, {keyEvent("meta_l", false)}, + } + t.Run("click then paste", func(t *testing.T) { + r := &clickRecorder{} + if err := ClickAndPaste(context.Background(), r, 0.5, 1, 0, 0, 0); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(r.batches, want) { + t.Fatalf("got %v, want %v", r.batches, want) + } + }) + t.Run("alt", func(t *testing.T) { + r := &clickRecorder{} + if err := ClickAndPasteWithActivate(context.Background(), r, 0.5, 1, false, 0, 0, 0, 0, "alt"); err != nil { + t.Fatal(err) + } + wantAlt := append(want[:3:3], [][]map[string]any{ + {keyEvent("alt", true)}, {keyEvent("v", true)}, + {keyEvent("v", false)}, {keyEvent("alt", false)}, + }...) + if !reflect.DeepEqual(r.batches, wantAlt) { + t.Fatalf("got %v, want %v", r.batches, wantAlt) + } + }) + t.Run("activate then click and paste", func(t *testing.T) { + const gap = 20 * time.Millisecond + r := &clickRecorder{} + if err := ClickAndPasteWithActivate(context.Background(), r, 0.5, 1, true, gap, 0, 0, 0, ""); err != nil { + t.Fatal(err) + } + wantActive := append(want[:3:3], want[1:]...) + if !reflect.DeepEqual(r.batches, wantActive) { + t.Fatalf("got %v, want %v", r.batches, wantActive) + } + if elapsed := r.times[3].Sub(r.times[2]); elapsed < gap { + t.Fatalf("clicks spaced %v apart, want at least %v", elapsed, gap) + } + }) + t.Run("cancel while button held", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r := &clickRecorder{cancel: cancel} + if err := ClickAndPaste(ctx, r, 0.5, 1, time.Second, 0, 0); !errors.Is(err, context.Canceled) { + t.Fatalf("got %v, want context.Canceled", err) + } + if !reflect.DeepEqual(r.batches, want[:3]) { + t.Fatalf("got %v, want %v", r.batches, want[:3]) + } + }) +} + func TestDialAndExecuteAgainstMockQMP(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index d00a14b..8e750cc 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -169,6 +169,7 @@ "failExportDiagnostics": "Couldn’t export diagnostics", "failCloneVM": "Couldn’t create CoW clone", "failType": "Couldn’t type into the VM", + "failDrop": "Couldn’t drop into the VM", "failDelete": "Couldn’t delete", "failOpenFolder": "Couldn’t open the folder", "deleteTitle": "Delete \"{name}\"?", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 9068040..c14c88b 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -169,6 +169,7 @@ "failExportDiagnostics": "导出排障日志失败", "failCloneVM": "派生 CoW 副本失败", "failType": "键入失败", + "failDrop": "拖放失败", "failDelete": "删除失败", "failOpenFolder": "无法打开文件夹", "deleteTitle": "删除「{name}」?",