package guesttools import ( "bytes" "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/hex" "encoding/json" "errors" "fmt" "io" "maps" "mime" "net" "net/http" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "unicode" "unicode/utf8" "github.com/Nwflower/reims-go/internal/atomicfile" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "golang.org/x/net/webdav" ) const ( DefaultPort = 19847 MaxPort = 19860 MaxClipboardBytes = 16 << 20 // 16 MiB (supports Retina PNG screenshots) MaxClipboardFiles = 256 MaxTextInputBytes = 1 << 20 // 1 MiB per injected text payload MaxUploadBytes = 256 << 20 // 256 MiB MaxSharedFiles = 2000 MaxSharedDepth = 8 MaxLongPollSec = 25 ConfigFileName = ".reims-go-tools.json" ) const bridgeProtocolVersion = 4 // ErrGuestToolsNotConnected is returned when a guest-assisted operation // requires a live Guest Tools agent inside macOS. var ErrGuestToolsNotConnected = errors.New("guest tools not connected") // ClipKind identifies the format carried in a clipboard payload. type ClipKind string const ( ClipEmpty ClipKind = "" ClipText ClipKind = "text" ClipFiles ClipKind = "files" ClipPNG ClipKind = "png" ) // ClipPayload holds a single clipboard item. type ClipPayload struct { Kind ClipKind Data []byte Files []string // A text or image format read alongside Files while the clipboard was locked. companion *ClipPayload } func withClipboardFiles(files []string, content ClipPayload) ClipPayload { if len(files) == 0 { return content } payload := ClipPayload{Kind: ClipFiles, Files: files} if content.Kind != ClipEmpty { payload.companion = &content } return payload } // Clipboard abstracts host OS clipboard reads/writes for testing. type Clipboard interface { ReadText() (string, error) WriteText(text string) error Read() (ClipPayload, error) WritePNG(pngBytes []byte) error SequenceNumber() uint32 } // VMConfig is persisted per VM in /.reims-go-tools.json (0600) so the // guest's Bearer token survives reims-go restarts without reinstalling Guest Tools. type VMConfig struct { VMName string `json:"vm_name"` DriverID string `json:"driver_id,omitempty"` Token string `json:"token"` Port int `json:"port"` SharedDir string `json:"shared_dir"` PreventSleep bool `json:"prevent_sleep"` HostDNSEnabled bool `json:"host_dns_enabled,omitempty"` DriveSharingEnabled bool `json:"drive_sharing_enabled"` SharedDrives []string `json:"shared_drives,omitempty"` DriveVolumes map[string]string `json:"drive_volumes,omitempty"` SharedFolders []SharedFolderConfig `json:"shared_folders,omitempty"` GuestTimezone string `json:"guest_timezone,omitempty"` ManagementOutPort int `json:"management_out_port,omitempty"` ManagementInPort int `json:"management_in_port,omitempty"` ManagementOutSock string `json:"management_out_sock,omitempty"` ManagementInSock string `json:"management_in_sock,omitempty"` // Runtime-only peer verification context for management relay connections (never persisted). VMDir string `json:"-"` QEMUPath string `json:"-"` // DriveRoots is a runtime-only test/platform override keyed by NormalizeDriveLetter. // Persisted configuration stores drive letters only, never arbitrary host roots. DriveRoots map[string]string `json:"-"` VerifyDriveRoot func(*os.Root, string, string) error `json:"-"` ResolvedFolders []ResolvedSharedFolder `json:"-"` VerifyFolderRoot func(*os.Root, ResolvedSharedFolder) error `json:"-"` } // GuestStatus summarizes live Guest Tools connection and capability state. type GuestStatus struct { Connected bool `json:"connected"` MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" DropMountDenied bool `json:"drop_mount_denied"` PreventSleep bool `json:"prevent_sleep"` SleepActive bool `json:"sleep_active"` AgentVersion int `json:"agent_version,omitempty"` LastSeen time.Time `json:"last_seen,omitempty"` TimezoneApplied string `json:"timezone_applied,omitempty"` TimezoneHelperReady bool `json:"timezone_helper_ready,omitempty"` TimezoneError string `json:"timezone_error,omitempty"` HostDNSEnabled bool `json:"host_dns_enabled"` HostDNSActive bool `json:"host_dns_active"` HostDNSReported bool `json:"host_dns_reported"` HostDNSConfigStale bool `json:"host_dns_config_stale"` } // LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates // a fresh 256-bit cryptographically random Bearer token. func LoadOrCreateVMConfig(vmDir, vmName, sharedDir string, port int) (VMConfig, error) { if _, err := os.Stat(vmDir); err != nil { return VMConfig{}, err } cfg, configured, err := ReadVMConfigStrict(vmDir) if err != nil { return VMConfig{}, err } if configured { oldName, oldDir, oldPort := cfg.VMName, cfg.SharedDir, cfg.Port cfg.VMName = vmName if sharedDir != "" { cfg.SharedDir = sharedDir } if port > 0 { cfg.Port = port } if oldName != cfg.VMName || oldDir != cfg.SharedDir || oldPort != cfg.Port { if err := SaveVMConfig(vmDir, cfg); err != nil { return VMConfig{}, err } } return cfg, nil } var raw [32]byte if _, err := rand.Read(raw[:]); err != nil { return VMConfig{}, fmt.Errorf("generate guest tools token: %w", err) } if port <= 0 { port = DefaultPort } cfg = VMConfig{ VMName: vmName, Token: hex.EncodeToString(raw[:]), Port: port, SharedDir: sharedDir, PreventSleep: true, } if err := SaveVMConfig(vmDir, cfg); err != nil { return VMConfig{}, err } return cfg, nil } // ReadVMConfig returns the saved Guest Tools config for a VM if configured. func ReadVMConfig(vmDir string) (VMConfig, bool) { cfg, configured, _ := ReadVMConfigStrict(vmDir) return cfg, configured } // ReadVMConfigStrict distinguishes missing configuration from unreadable or invalid data. func ReadVMConfigStrict(vmDir string) (VMConfig, bool, error) { if vmDir == "" { return VMConfig{}, false, nil } b, err := os.ReadFile(filepath.Join(vmDir, ConfigFileName)) if errors.Is(err, os.ErrNotExist) { return VMConfig{}, false, nil } if err != nil { return VMConfig{}, false, fmt.Errorf("read Guest Tools config: %w", err) } var cfg VMConfig if err := json.Unmarshal(b, &cfg); err != nil { return VMConfig{}, false, fmt.Errorf("decode Guest Tools config: %w", err) } if len(cfg.Token) < 32 { return VMConfig{}, false, errors.New("Guest Tools config is missing a valid token") } return cfg, true, nil } // SaveVMConfig persists cfg with restricted permissions. func SaveVMConfig(vmDir string, cfg VMConfig) error { if _, err := os.Stat(vmDir); err != nil { return err } return atomicfile.WriteJSON(filepath.Join(vmDir, ConfigFileName), cfg, 0o600) } type pendingTextInput struct { id string text string ackCh chan struct{} doneCh chan struct{} } type pendingClipOverride struct { text string hash string servedCh chan struct{} } type registeredVM struct { key string name string hostDropToken string regGen uint64 token string sharedDir string sharedRoot sharedRoot preventSleep bool hostDNSEnabled bool hostDNSActive bool hostDNSReported bool hostDNSConfigStale bool guestTimezone string timezoneApplied string timezoneHelperReady bool timezoneError string driveSharingEnabled bool sharedDriveRoots map[string]string driveVolumeGUIDs map[string]string verifyDriveRoot func(*os.Root, string, string) error resolvedFolders map[string]ResolvedSharedFolder verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error lastStatus time.Time mountMode string dropMountDenied bool sleepActive bool agentVersion int lastSeen time.Time windowReportGen uint64 windowReport windowReport clipboardDelivery guestClipboardDelivery fileClipboardReceipt fileClipboardReceipt 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 textActive map[string]*pendingTextInput textNotify chan struct{} textWaiters int lastTextPoll time.Time clipOverride *pendingClipOverride } // Server serves the token-authenticated host ↔ guest bridge over 127.0.0.1 // (reachable from QEMU SLIRP guests as http://10.0.2.2:). type Server struct { mu sync.RWMutex management map[string]*managementRelay fileMu sync.Mutex clipWriteMu sync.Mutex clipArchiveMu sync.Mutex clip Clipboard clipFileStaging clipFileStaging vms map[string]*registeredVM // keyed by driver.VMRef.Key() davCache map[string]davCacheEntry folderAccessMu sync.RWMutex folderGeneration uint64 registrationGen uint64 nextWindowGen uint64 dynamicRoutes map[string]http.HandlerFunc clipboardActive bool globalClipPolicy ClipboardPolicy vmClipPolicies map[string]ClipboardPolicy watcherCount atomic.Int32 clipStatsH2G uint64 clipFilesApplied atomic.Uint64 clipStatsG2H uint64 clipStatsErr uint64 port int listener net.Listener 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) hostDNSConfig HostDNSConfig hostDNS hostDNS } // NewServer constructs a Guest Tools HTTP bridge with clipboard active by default. // Pass nil for clip to use the host OS clipboard. func NewServer(clip Clipboard) *Server { if clip == nil { clip = &OSClipboard{} } s := &Server{ clip: clip, vms: make(map[string]*registeredVM), davCache: make(map[string]davCacheEntry), dynamicRoutes: make(map[string]http.HandlerFunc), clipboardActive: true, globalClipPolicy: DefaultClipboardPolicy(), vmClipPolicies: make(map[string]ClipboardPolicy), clipNotify: make(chan struct{}), hostDNS: defaultHostDNS, } s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard s.dynamicRoutes[fileClipboardAppliedPath] = s.handleFileClipboardApplied return s } // Start binds the bridge on 127.0.0.1 starting from preferredPort (default // 19847..19860, or ephemeral 0 when preferredPort == -1 for tests). func (s *Server) Start(preferredPort int) (int, error) { s.mu.Lock() defer s.mu.Unlock() if s.listener != nil { return s.port, nil } var ln net.Listener var err error if preferredPort < 0 { ln, err = net.Listen("tcp", "127.0.0.1:0") } else { start := preferredPort if start == 0 { start = DefaultPort } for p := start; p <= MaxPort; p++ { ln, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p)) if err == nil { break } } if ln == nil { ln, err = net.Listen("tcp", "127.0.0.1:0") } } if err != nil { return 0, fmt.Errorf("listen guest tools server: %w", err) } tcpAddr, ok := ln.Addr().(*net.TCPAddr) if !ok { _ = ln.Close() return 0, errors.New("unexpected listener addr") } s.listener = ln s.port = tcpAddr.Port mux := http.NewServeMux() mux.HandleFunc("/v1/ping", s.handlePing) mux.HandleFunc("/v1/config", s.handleConfig) mux.HandleFunc(activeWindowPath, s.handleActiveWindow) mux.HandleFunc("/v1/folders", s.handleFolders) mux.HandleFunc("/v1/status", s.handleStatus) mux.HandleFunc("/v1/dns-query", s.handleDNSQuery) mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard")) mux.HandleFunc(clipboardAppliedPath, s.handleClipboardApplied) mux.HandleFunc(fileClipboardAppliedPath, s.dispatchDynamicRoute(fileClipboardAppliedPath, "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) mux.HandleFunc("/dav/", s.handleWebDAV) mux.HandleFunc("/dav-folders/", s.handleFolderWebDAV) s.httpSrv = &http.Server{ Handler: localSecurityMiddleware(mux), ReadHeaderTimeout: 10 * time.Second, } if s.clipboardActive { watchCtx, watchCancel := context.WithCancel(context.Background()) s.watchCancel = watchCancel s.watcherCount.Add(1) go s.watchClipboardLoop(watchCtx) } // Close may clear s.httpSrv before this goroutine runs; serve the copy. hs := s.httpSrv go func() { _ = hs.Serve(ln) }() return s.port, nil } func (s *Server) dispatchDynamicRoute(routePath, feature string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { s.mu.RLock() h := s.dynamicRoutes[routePath] s.mu.RUnlock() if h == nil { writeFeatureDisabled(w, feature) return } h(w, r) } } func (s *Server) watchClipboardLoop(ctx context.Context) { defer s.watcherCount.Add(-1) ticker := time.NewTicker(150 * time.Millisecond) defer ticker.Stop() pruneTicker := time.NewTicker(time.Minute) defer pruneTicker.Stop() lastSeq := s.clip.SequenceNumber() for { select { case <-ctx.Done(): return case now := <-pruneTicker.C: s.pruneExpiredClipStaging(now) case <-ticker.C: seq := s.clip.SequenceNumber() if seq != lastSeq { lastSeq = seq s.broadcastClipChange() } } } } func (s *Server) clipNotifyChan() <-chan struct{} { s.mu.RLock() ch := s.clipNotify s.mu.RUnlock() return ch } func (s *Server) broadcastClipChange() { s.mu.Lock() old := s.clipNotify s.clipNotify = make(chan struct{}) s.mu.Unlock() if old != nil { close(old) } } // NotifyClipboardChanged explicitly wakes any pending long-poll clipboard waiters. func (s *Server) NotifyClipboardChanged() { s.broadcastClipChange() } func (s *Server) Port() int { s.mu.RLock() defer s.mu.RUnlock() return s.port } func (s *Server) Close(ctx context.Context) error { s.mu.Lock() srv := s.httpSrv cancel := s.watchCancel s.httpSrv = nil s.listener = nil s.port = 0 s.watchCancel = nil relays := s.management s.management = nil s.clearAllClipFilesLocked() for _, vm := range s.vms { vm.windowReportGen = 0 vm.windowReport = windowReport{} vm.clipboardDelivery = guestClipboardDelivery{} vm.fileClipboardReceipt = fileClipboardReceipt{} } s.mu.Unlock() s.cleanupClipFiles() for _, relay := range relays { relay.close() } if cancel != nil { cancel() } s.broadcastClipChange() if srv == nil { return nil } return srv.Shutdown(ctx) } func vmRegistryKey(driverID, name string) string { return driver.NewVMRef(driverID, name).Key() } func normalizeVMRegistryKey(key string) string { if ref, ok := driver.ParseVMRef(key); ok { return ref.Key() } return vmRegistryKey("", key) } // RegisterVM publishes the VM's current Guest Tools configuration. func (s *Server) RegisterVM(cfg VMConfig) { if cfg.VMName == "" || cfg.Token == "" { return } driveRoots := configuredDriveRoots(cfg) key := vmRegistryKey(cfg.DriverID, cfg.VMName) defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() defer s.mu.Unlock() cur := s.vms[key] var root sharedRoot if cfg.SharedDir != "" { if cur != nil && cur.sharedDir == cfg.SharedDir && cur.sharedRoot.err == nil { root = cur.sharedRoot } else { root = configureSharedRoot(cfg.SharedDir) } if opened, err := openSharedRoot(root, true); err == nil { opened.Close() } } 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, allowClipboard: func() bool { return s.EffectiveClipboardPolicy(key).allowsHostToGuestFiles() }, }, LockSystem: webdav.NewMemLS(), } s.vms[key] = cur } else if cur.token != cfg.Token { cur.dropShares.revokeClipboard() s.clearVMClipFilesLocked(key) cur.windowReportGen = 0 cur.windowReport = windowReport{} cur.clipboardDelivery = guestClipboardDelivery{} } folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders)) for _, folder := range cfg.ResolvedFolders { id, ok := NormalizeFolderID(folder.ID) folder.Name = SanitizeFolderName(folder.Name) if !ok || id != folder.ID || folder.Name == "" || folder.RootPath == "" { continue } old, exists := cur.resolvedFolders[id] folder.Generation = old.Generation if !exists || old != folder || cur.token != cfg.Token { s.folderGeneration++ folder.Generation = s.folderGeneration } folders[id] = folder } if entry, ok := s.davCache[key]; ok && entry.root != cfg.SharedDir { delete(s.davCache, key) } for davKey, entry := range s.davCache { if drive, ok := strings.CutPrefix(davKey, key+"/drives/"); ok && (!cfg.DriveSharingEnabled || driveRoots[drive] != entry.root || !strings.EqualFold(cfg.DriveVolumes[drive], cur.driveVolumeGUIDs[drive]) || cfg.Token != cur.token) { delete(s.davCache, davKey) } if id, ok := strings.CutPrefix(davKey, key+"/folders/"); ok && folders[id].Generation != entry.generation { delete(s.davCache, davKey) } } s.registrationGen++ cur.regGen = s.registrationGen cur.fileClipboardReceipt = fileClipboardReceipt{} cur.token = cfg.Token cur.sharedDir = cfg.SharedDir cur.sharedRoot = root cur.preventSleep = cfg.PreventSleep cur.hostDNSEnabled = cfg.HostDNSEnabled cur.guestTimezone = cfg.GuestTimezone cur.driveSharingEnabled = cfg.DriveSharingEnabled cur.sharedDriveRoots = driveRoots cur.driveVolumeGUIDs = cloneStringMap(cfg.DriveVolumes) cur.verifyDriveRoot = cfg.VerifyDriveRoot cur.resolvedFolders = folders cur.verifyFolderRoot = cfg.VerifyFolderRoot } // HasVM reports whether vmKey is registered with the bridge. func (s *Server) HasVM(vmKey string) bool { return s.RegistrationGen(vmKey) > 0 } // RegistrationGen returns the current registration generation for vmKey, or 0 if unregistered. func (s *Server) RegistrationGen(vmKey string) uint64 { s.mu.RLock() defer s.mu.RUnlock() if vm := s.vms[normalizeVMRegistryKey(vmKey)]; vm != nil { return vm.regGen } return 0 } // UnregisterVMIfGen unregisters vmKey only when its current registration generation matches gen. func (s *Server) UnregisterVMIfGen(vmKey string, gen uint64) bool { if gen == 0 { return false } key := normalizeVMRegistryKey(vmKey) defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() defer s.mu.Unlock() vm := s.vms[key] if vm == nil || vm.regGen != gen { return false } s.unregisterVMLocked(key) return true } // UnregisterVM releases all host-side state owned by a deleted VM. In-flight // requests retain only their own snapshot and fail authentication on retry. func (s *Server) UnregisterVM(vmKey string) { key := normalizeVMRegistryKey(vmKey) defer s.cleanupClipFiles() s.folderAccessMu.Lock() defer s.folderAccessMu.Unlock() s.mu.Lock() relay := s.management[key] delete(s.management, key) s.unregisterVMLocked(key) s.mu.Unlock() if relay != nil { relay.close() } } func (s *Server) unregisterVMLocked(key string) { s.clearVMClipFilesLocked(key) 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 { if strings.HasPrefix(davKey, key+"/") { delete(s.davCache, davKey) } } } // SetHostTextHandler registers a callback invoked when a host-side window hook // (e.g. reims-vgpu-window WM_CHAR bridge) submits Unicode text to POST /v1/host-text. func (s *Server) SetHostTextHandler(fn func(vmKey, vmName, text string)) { s.mu.Lock() s.onHostText = fn s.mu.Unlock() } // InjectText delivers arbitrary UTF-8 text (including CJK/emoji) into a running // macOS VM without Accessibility permissions: // - Guest Tools v3 (preferred): pushes text over /v1/text-input, waits for // the guest to stage the text and POST /v1/text-input/ack, invokes pasteFn // (QMP Command+V), waits briefly for the focused app to consume NSPasteboard, // then unblocks the ack so the guest restores its previous clipboard. // - Guest Tools v2 (fallback): serves a one-shot clipboard override on // /v1/clipboard without mutating the Windows clipboard, wakes the v2 // long-poll immediately, waits for pbcopy, then invokes pasteFn. func (s *Server) InjectText(ctx context.Context, vmName, text string, pasteFn func(context.Context) error) (string, error) { if text == "" { return "", errors.New("empty text") } if len(text) > MaxTextInputBytes { return "", fmt.Errorf("text exceeds %d byte limit", MaxTextInputBytes) } if !utf8.ValidString(text) { return "", errors.New("text must be valid UTF-8") } text = strings.ReplaceAll(text, "\r\n", "\n") text = strings.ReplaceAll(text, "\r", "\n") vmName = normalizeVMRegistryKey(vmName) s.mu.RLock() vm := s.vms[vmName] s.mu.RUnlock() if vm == nil { return "", ErrGuestToolsNotConnected } // Serialize per-VM injections so staging one phrase cannot interrupt another paste. vm.injectMu.Lock() defer vm.injectMu.Unlock() s.mu.Lock() v3Ready := vm.textWaiters > 0 || (!vm.lastTextPoll.IsZero() && time.Since(vm.lastTextPoll) <= 35*time.Second) connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= 15*time.Second if v3Ready { vm.textSeq++ id := strconv.FormatUint(vm.textSeq, 10) item := &pendingTextInput{ id: id, text: text, ackCh: make(chan struct{}), doneCh: make(chan struct{}), } vm.textQueue = append(vm.textQueue, item) if vm.textNotify != nil { close(vm.textNotify) } vm.textNotify = make(chan struct{}) s.mu.Unlock() defer func() { s.mu.Lock() delete(vm.textActive, item.id) for i, q := range vm.textQueue { if q == item { vm.textQueue = append(vm.textQueue[:i], vm.textQueue[i+1:]...) break } } s.mu.Unlock() select { case <-item.doneCh: default: close(item.doneCh) } }() timer := time.NewTimer(4 * time.Second) defer timer.Stop() select { case <-item.ackCh: case <-timer.C: return "v3", errors.New("timed out waiting for guest tools to receive text") case <-ctx.Done(): return "v3", ctx.Err() } var pasteErr error if pasteFn != nil { pasteErr = pasteFn(ctx) } if pasteErr == nil { select { case <-time.After(120 * time.Millisecond): case <-ctx.Done(): } } return "v3", pasteErr } if !connected { s.mu.Unlock() return "", ErrGuestToolsNotConnected } // Guest Tools v2 fallback: serve one-shot override via /v1/clipboard. ov := &pendingClipOverride{ text: text, hash: textHash(text), servedCh: make(chan struct{}), } vm.clipOverride = ov s.mu.Unlock() defer func() { s.mu.Lock() if vm.clipOverride == ov { vm.clipOverride = nil } s.mu.Unlock() }() s.broadcastClipChange() timer := time.NewTimer(4 * time.Second) defer timer.Stop() select { case <-ov.servedCh: case <-timer.C: return "v2", errors.New("timed out waiting for guest tools v2 clipboard poll") case <-ctx.Done(): return "v2", ctx.Err() } // Give macOS guest-tools.sh time to finish `pbcopy < "$clip_out"`. select { case <-time.After(110 * time.Millisecond): case <-ctx.Done(): return "v2", ctx.Err() } if pasteFn != nil { return "v2", pasteFn(ctx) } return "v2", nil } // SetPreventSleep updates the desired prevent-sleep state for a registered VM. func (s *Server) SetPreventSleep(vmName string, enabled bool) { vmName = normalizeVMRegistryKey(vmName) s.mu.Lock() if vm := s.vms[vmName]; vm != nil { vm.preventSleep = enabled } s.mu.Unlock() } // IsConnected reports whether the guest agent has authenticated within maxAge. func (s *Server) IsConnected(vmName string, maxAge time.Duration) bool { return s.Status(vmName, maxAge).Connected } // Status returns the live connection, mount mode, and prevent-sleep status of vmName. func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { vmName = normalizeVMRegistryKey(vmName) s.mu.RLock() defer s.mu.RUnlock() vm := s.vms[vmName] if vm == nil { return GuestStatus{} } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge freshStatus := connected && time.Since(vm.lastStatus) <= maxAge var timezone, timezoneError string if freshStatus { timezone = vm.timezoneApplied timezoneError = vm.timezoneError } dnsReported := freshStatus && vm.hostDNSReported return GuestStatus{ HostDNSEnabled: vm.hostDNSEnabled, HostDNSActive: dnsReported && vm.hostDNSActive, HostDNSReported: dnsReported, HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale, Connected: connected, MountMode: vm.mountMode, DropMountDenied: freshStatus && vm.dropMountDenied, PreventSleep: vm.preventSleep, SleepActive: connected && vm.sleepActive, AgentVersion: vm.agentVersion, LastSeen: vm.lastSeen, TimezoneApplied: timezone, TimezoneHelperReady: freshStatus && vm.timezoneHelperReady, TimezoneError: timezoneError, } } func (s *Server) touchLastSeen(vmName string) { vmName = normalizeVMRegistryKey(vmName) s.mu.Lock() if vm := s.vms[vmName]; vm != nil { vm.lastSeen = time.Now() } s.mu.Unlock() } func bearerToken(r *http.Request) string { auth := strings.TrimSpace(r.Header.Get("Authorization")) token, ok := strings.CutPrefix(auth, "Bearer ") if !ok { return "" } return strings.TrimSpace(token) } func (s *Server) authenticate(r *http.Request) *registeredVM { tok := bearerToken(r) if tok == "" { _, pass, _ := r.BasicAuth() tok = strings.TrimSpace(pass) } return s.authenticateToken(tok) } func (s *Server) authenticateToken(tok string) *registeredVM { if tok == "" { return nil } s.mu.Lock() defer s.mu.Unlock() for _, vm := range s.vms { if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 { vm.lastSeen = time.Now() // A snapshot of the plain fields only: copying *vm would copy // injectMu and alias the text queues. Handlers that need the // queues look the live VM up again by name under s.mu. cp := registeredVM{ key: vm.key, name: vm.name, token: vm.token, regGen: vm.regGen, dropDAVHandler: vm.dropDAVHandler, sharedDir: vm.sharedDir, sharedRoot: vm.sharedRoot, preventSleep: vm.preventSleep, hostDNSEnabled: vm.hostDNSEnabled, guestTimezone: vm.guestTimezone, driveSharingEnabled: vm.driveSharingEnabled, sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs), resolvedFolders: maps.Clone(vm.resolvedFolders), mountMode: vm.mountMode, sleepActive: vm.sleepActive, agentVersion: vm.agentVersion, lastSeen: vm.lastSeen, windowReportGen: vm.windowReportGen, } return &cp } } return nil } func textHash(s string) string { sum := sha256.Sum256([]byte(s)) return hex.EncodeToString(sum[:]) } func payloadHash(p ClipPayload) string { switch p.Kind { case ClipPNG: h := sha256.New() h.Write([]byte("png:")) h.Write(p.Data) return hex.EncodeToString(h.Sum(nil)) case ClipText: return textHash(string(p.Data)) default: return textHash("") } } func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) { vm := s.authenticate(r) if vm == nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "drop-events", "drop-webdav", "drop-paste"} if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled { if policy.allowsHostToGuestFiles() { caps = append(caps, "clipboard-files") } caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...) if policy.SyncImages { caps = append([]string{"clipboard-png"}, caps...) } } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "ok": true, "vm": vm.name, "version": bridgeProtocolVersion, "capabilities": caps, }) } func (s *Server) handleConfig(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 { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } policy := s.EffectiveClipboardPolicy(vm.key) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "vm": vm.name, "window_report_generation": vm.windowReportGen, "prevent_sleep": vm.preventSleep, "webdav_drop_path": "/dav-drop/" + vm.name + "/", "host_dns_enabled": vm.hostDNSEnabled, "timezone": effectiveTimezone(vm.guestTimezone), "webdav_path": "/dav/" + vm.name + "/", "shared_drives": enabledDriveLetters(vm), "shared_folders_count": len(vm.resolvedFolders), "clipboard_enabled": policy.Enabled, "clipboard_direction": policy.Direction, "clipboard_sync_images": policy.SyncImages, "clipboard_max_bytes": policy.MaxImageBytes, "clipboard_sync_files": policy.Enabled && policy.SyncFiles, "clipboard_max_file_bytes": policy.MaxFileBytes, "clipboard_upload_files": policy.allowsGuestToHostFiles() && s.clipboardFileUploadsAvailable(), }) } func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { vm := s.authenticate(r) if vm == nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } if r.Method != http.MethodPost && r.Method != http.MethodPut { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } var req struct { MountMode string `json:"mount_mode"` DropMountDenied bool `json:"drop_mount_denied"` SleepActive bool `json:"sleep_active"` AgentVersion int `json:"agent_version"` TimezoneApplied string `json:"timezone_applied"` TimezoneHelperReady bool `json:"timezone_helper_ready"` TimezoneError string `json:"timezone_error"` HostDNSActive *bool `json:"host_dns_active"` HostDNSConfigStale bool `json:"host_dns_config_stale"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } mode := strings.ToLower(strings.TrimSpace(req.MountMode)) if mode != "webdav" && mode != "sync" { mode = "" } if !host.ValidateIANATimezone(req.TimezoneApplied) { req.TimezoneApplied = "" } s.mu.Lock() if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token { now := time.Now() cur.lastSeen = now cur.lastStatus = now if mode != "" { cur.mountMode = mode } cur.dropMountDenied = req.DropMountDenied cur.sleepActive = req.SleepActive cur.hostDNSReported = req.HostDNSActive != nil cur.hostDNSActive = cur.hostDNSReported && *req.HostDNSActive cur.hostDNSConfigStale = req.HostDNSConfigStale cur.timezoneApplied = req.TimezoneApplied cur.timezoneHelperReady = req.TimezoneHelperReady cur.timezoneError = req.TimezoneError if req.AgentVersion > 0 { cur.agentVersion = req.AgentVersion } } s.mu.Unlock() w.WriteHeader(http.StatusOK) } func (s *Server) readClipboardState(wantImage, wantFiles bool) (ClipPayload, uint32, error) { if clip, ok := s.clip.(interface { readClipboard(bool, bool) (ClipPayload, uint32, error) }); ok { return clip.readClipboard(wantImage, wantFiles) } // A clipboard without atomic snapshots can return a newer payload with // this sequence, which is safe for a subsequent conditional write. seq := s.clip.SequenceNumber() payload, err := s.clip.Read() return payload, seq, err } func (s *Server) readClipboardForSync(wantImage, wantFiles bool) (ClipPayload, uint32, string, error) { if clip, ok := s.clip.(interface { // The returned data is immutable and can be passed to io.Writer. // For files, the cached hash describes the companion, if present. readClipboardForSync(bool, bool) (ClipPayload, uint32, string, error) }); ok { return clip.readClipboardForSync(wantImage, wantFiles) } payload, seq, err := s.readClipboardState(wantImage, wantFiles) return payload, seq, "", err } func setClipboardSeq(w http.ResponseWriter, seq uint32) { w.Header().Set("X-Clip-Seq", strconv.FormatUint(uint64(seq), 10)) } func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { vm := s.authenticate(r) if vm == nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } switch r.Method { case http.MethodGet: if r.URL.Query().Get("format") == "tar" { s.serveClipboardArchive(w, r, vm) return } s.getClipboard(w, r, vm) case http.MethodPost, http.MethodPut: mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if mediaType == "application/x-tar" { if err != nil { http.Error(w, "invalid clipboard content type", http.StatusBadRequest) return } s.postClipboardFiles(w, r, vm, s.EffectiveClipboardPolicy(vm.key)) return } s.postClipboard(w, r, vm.key) default: if !s.EffectiveClipboardPolicy(vm.key).Enabled { writeFeatureDisabled(w, "clipboard") return } http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func acceptsClipFormat(raw, want string) bool { for _, part := range strings.Split(raw, ",") { if strings.EqualFold(strings.TrimSpace(part), want) { return true } } return false } func prepareClipboardFiles(rawPaths []string) []DropShareEntry { if len(rawPaths) > MaxClipboardFiles { return nil } used := make(map[string]bool) var entries []DropShareEntry for _, raw := range rawPaths { if raw == "" || strings.ContainsRune(raw, '\x00') || strings.HasPrefix(strings.ReplaceAll(raw, "\\", "/"), "//") || !filepath.IsAbs(raw) { continue } clean := filepath.Clean(raw) st, err := statDropPath(clean, true) if err != nil { continue } base := filepath.Base(clean) if !filepath.IsLocal(base) || base == "." || base == ".." || strings.ContainsAny(base, "/\\\x00:<>|\"?*\r\n") || strings.IndexFunc(base, unicode.IsControl) >= 0 { continue } ext := "" if !st.IsDir() { ext = filepath.Ext(base) } alias := base for i := 1; used[strings.ToLower(alias)]; i++ { alias = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(base, ext), i, ext) } used[strings.ToLower(alias)] = true entries = append(entries, DropShareEntry{Name: alias, HostPath: clean, IsDir: st.IsDir()}) } return entries } func (s *Server) clipboardFileManifest(vmKey string, seq uint32, entries []DropShareEntry) (ClipPayload, string) { // A new copy needs a fresh WebDAV URL even if the guest last synced the // same paths. On-disk edits alone must leave the clipboard untouched. h := sha256.New() fmt.Fprintf(h, "files:%d\x00", seq) items := make([]string, len(entries)) for i, entry := range entries { items[i] = entry.Name fmt.Fprintf(h, "%s\x00%s\x00", entry.HostPath, entry.Name) } hash := hex.EncodeToString(h.Sum(nil)) dropID := "clip-" + hash[:16] if !s.ensureClipboardShare(vmKey, dropID, entries) { return ClipPayload{}, "" } body, _ := json.Marshal(struct { DropID string `json:"drop_id"` Items []string `json:"items"` }{dropID, items}) return ClipPayload{Kind: ClipFiles, Data: body}, hash } func (s *Server) clipboardForGuest(vmKey string, payload ClipPayload, seq uint32, hash string, wantFiles, wantImage bool, maxImageBytes int) (ClipPayload, string) { if payload.Kind == ClipFiles { if wantFiles && !s.isStagedClipboardFiles(payload.Files) { if entries := prepareClipboardFiles(payload.Files); len(entries) > 0 { return s.clipboardFileManifest(vmKey, seq, entries) } } if payload.companion == nil { return ClipPayload{}, "" } payload = *payload.companion } if payload.Kind == ClipText || (payload.Kind == ClipPNG && wantImage && len(payload.Data) <= maxImageBytes) { if hash == "" { hash = payloadHash(payload) } return payload, hash } return ClipPayload{}, "" } func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vm *registeredVM) { vmKey := vm.key waitSec, err := strconv.Atoi(r.URL.Query().Get("wait")) if err != nil { waitSec = 0 } wait := time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second ackCapable := r.Header.Get(clipboardAckHeader) == "1" start := time.Now() wantsImage := acceptsClipFormat(r.URL.Query().Get("accept"), "image") || strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png") wantsFiles := acceptsClipFormat(r.URL.Query().Get("accept"), "files") since := r.URL.Query().Get("since") sinceSeq, seqErr := strconv.ParseUint(r.URL.Query().Get("since_seq"), 10, 32) hasSinceSeq := seqErr == nil for { ch := s.clipNotifyChan() deadline := start.Add(wait) if ackCapable && s.windowClipboardActive(vm) { deadline = start.Add(min(wait, 250*time.Millisecond)) } policy := s.EffectiveClipboardPolicy(vmKey) if !policy.Enabled { writeFeatureDisabled(w, "clipboard") return } if policy.allowsHostToGuest() { if ov := s.takeClipOverride(vmKey); ov != nil { s.touchLastSeen(vmKey) atomic.AddUint64(&s.clipStatsH2G, 1) setClipboardSeq(w, s.clip.SequenceNumber()) w.Header().Set("X-Clip-Hash", ov.hash) w.Header().Set("X-Clip-Kind", string(ClipText)) w.Header().Set("Content-Type", "text/plain; charset=utf-8") _, _ = w.Write([]byte(ov.text)) close(ov.servedCh) return } wantImage := wantsImage && policy.SyncImages wantFiles := wantsFiles && policy.allowsHostToGuestFiles() payload, seq, h, err := s.readClipboardForSync(wantImage, wantFiles) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) return } payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantFiles, wantImage, policy.MaxImageBytes) if h != "" { unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq)) expired := !time.Now().Before(deadline) if ackCapable { recheck := unchanged && hasSinceSeq if offer := s.offerGuestClipboard(vm, seq, h, recheck, expired); offer.ticket != "" { w.Header().Set(clipboardAckHeader, "1") w.Header().Set(clipboardWindowHeader, strconv.FormatUint(offer.window, 10)) w.Header().Set(clipboardRequestHeader, offer.ticket) if recheck { w.Header().Set(clipboardRecheckHeader, "1") } unchanged = false } } if !unchanged || expired { setClipboardSeq(w, seq) w.Header().Set("X-Clip-Hash", h) w.Header().Set("X-Clip-Kind", string(payload.Kind)) s.touchLastSeen(vmKey) if unchanged { w.WriteHeader(http.StatusNotModified) return } atomic.AddUint64(&s.clipStatsH2G, 1) if payload.Kind == ClipFiles { w.Header().Set("Content-Type", "application/json") if r.Header.Get(fileClipboardReceiptHeader) == "1" && w.Header().Get(clipboardRecheckHeader) == "" { if request := s.offerFileClipboardReceipt(vm, seq, h); request != "" { w.Header().Set(fileClipboardRequestHeader, request) } } } else if payload.Kind == ClipPNG { w.Header().Set("Content-Type", "image/png") } else { w.Header().Set("Content-Type", "text/plain; charset=utf-8") } _, _ = w.Write(payload.Data) return } } else if time.Until(deadline) <= 0 { s.touchLastSeen(vmKey) setClipboardSeq(w, seq) w.WriteHeader(http.StatusNotModified) return } } else if time.Until(deadline) <= 0 { // Keep guest-to-host-only agents from busy-looping. setClipboardSeq(w, s.clip.SequenceNumber()) w.WriteHeader(http.StatusNoContent) return } timer := time.NewTimer(time.Until(deadline)) select { case <-ch: timer.Stop() case <-timer.C: // Re-read after the timeout in case the watcher has yet to notify us. case <-r.Context().Done(): timer.Stop() return } } } var errClipboardConflict = errors.New("host clipboard changed") func (s *Server) postClipboard(w http.ResponseWriter, r *http.Request, vmName string) { policy := s.EffectiveClipboardPolicy(vmName) if !policy.Enabled { writeFeatureDisabled(w, "clipboard") return } isImage := strings.Contains(strings.ToLower(r.Header.Get("Content-Type")), "image/png") if policy.Direction == ClipboardHostToGuest || (isImage && !policy.SyncImages) { w.WriteHeader(http.StatusNoContent) return } var baseSeq *uint32 if raw := r.Header.Get("X-Clip-Base-Seq"); policy.Direction != ClipboardGuestToHost && raw != "" { n, err := strconv.ParseUint(raw, 10, 32) if err != nil { http.Error(w, "invalid X-Clip-Base-Seq", http.StatusBadRequest) return } base := uint32(n) baseSeq = &base } limit := MaxClipboardBytes if isImage { limit = policy.MaxImageBytes } body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1)) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusBadRequest) return } if len(body) > limit { http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge) return } payload := ClipPayload{Kind: ClipText, Data: body} if isImage { png, ok := TrimPNG(body) if !ok { http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest) return } payload = ClipPayload{Kind: ClipPNG, Data: png} } else { if !utf8.Valid(body) { http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest) return } payload.Data = []byte(strings.ReplaceAll(string(body), "\r\n", "\n")) } h := payloadHash(payload) seq, err := s.applyClipboardPost(payload, baseSeq) if errors.Is(err, errClipboardConflict) { setClipboardSeq(w, seq) http.Error(w, errClipboardConflict.Error(), http.StatusConflict) return } if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) return } setClipboardSeq(w, seq) w.Header().Set("X-Clip-Kind", string(payload.Kind)) w.Header().Set("X-Clip-Hash", h) w.WriteHeader(http.StatusOK) } func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint32, error) { s.clipWriteMu.Lock() defer s.clipWriteMu.Unlock() seq := s.clip.SequenceNumber() if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } current, seq, err := s.readClipboardState(true, false) if err == nil { if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } if current.Kind == payload.Kind && bytes.Equal(current.Data, payload.Data) { return seq, nil } } if clip, ok := s.clip.(interface { writeClipboard(ClipPayload, *uint32) (uint32, error) }); ok { seq, err = clip.writeClipboard(payload, baseSeq) } else { seq = s.clip.SequenceNumber() if baseSeq != nil && seq != *baseSeq { return seq, errClipboardConflict } if payload.Kind == ClipPNG { err = s.clip.WritePNG(payload.Data) } else { err = s.clip.WriteText(string(payload.Data)) } seq = s.clip.SequenceNumber() } if err == nil { atomic.AddUint64(&s.clipStatsG2H, 1) s.broadcastClipChange() } return seq, err } func (s *Server) takeClipOverride(vmName string) *pendingClipOverride { s.mu.Lock() defer s.mu.Unlock() vm := s.vms[vmName] if vm == nil || vm.clipOverride == nil { return nil } ov := vm.clipOverride vm.clipOverride = nil return ov } func (s *Server) handleTextInput(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 { s.mu.Unlock() http.Error(w, "vm not found", http.StatusNotFound) return } vm.textWaiters++ vm.lastTextPoll = time.Now() s.mu.Unlock() defer func() { s.mu.Lock() if cur := s.vms[vmSnap.key]; cur != nil { if cur.textWaiters > 0 { cur.textWaiters-- } cur.lastTextPoll = 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 == nil { s.mu.Unlock() w.WriteHeader(http.StatusNoContent) return } if len(cur.textQueue) > 0 { item := cur.textQueue[0] cur.textQueue = cur.textQueue[1:] cur.textActive[item.id] = item cur.lastSeen = time.Now() cur.lastTextPoll = time.Now() s.mu.Unlock() w.Header().Set("X-Input-Id", item.id) w.Header().Set("Content-Type", "text/plain; charset=utf-8") _, _ = w.Write([]byte(item.text)) return } ch := cur.textNotify 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) handleTextInputAck(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 && r.Method != http.MethodPut { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } id := strings.TrimSpace(r.URL.Query().Get("id")) if id == "" { http.Error(w, "missing id", http.StatusBadRequest) return } s.mu.Lock() vm := s.vms[vmSnap.key] var item *pendingTextInput if vm != nil { item = vm.textActive[id] } s.mu.Unlock() if item == nil { w.WriteHeader(http.StatusOK) return } select { case <-item.ackCh: default: close(item.ackCh) } // Block until host finishes QMP Command+V + settle so the guest does not // restore its previous clipboard before macOS reads NSPasteboard. timer := time.NewTimer(5 * time.Second) defer timer.Stop() select { case <-item.doneCh: case <-timer.C: case <-r.Context().Done(): } w.WriteHeader(http.StatusOK) } func (s *Server) handleHostText(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 { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } body, err := io.ReadAll(io.LimitReader(r.Body, MaxTextInputBytes+1)) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if len(body) == 0 || len(body) > MaxTextInputBytes || !utf8.Valid(body) { http.Error(w, "invalid utf-8 text", http.StatusBadRequest) return } s.mu.RLock() fn := s.onHostText s.mu.RUnlock() if fn != nil { fn(vmSnap.key, vmSnap.name, string(body)) } w.WriteHeader(http.StatusAccepted) }