Files
Reims-Go/internal/guesttools/server.go
T
ShroapandShroap 7f4cbbe911 feat(guesttools): support Windows-to-macOS window drag-and-drop (zero-copy WebDAV + stealth paste) (#82)
* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image

* feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13)

---------

Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
2026-12-02 21:35:59 +08:00

1408 lines
40 KiB
Go

package guesttools
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"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)
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"
ClipPNG ClipKind = "png"
)
// ClipPayload holds a single clipboard item (either UTF-8 text or PNG bytes).
type ClipPayload struct {
Kind ClipKind
Data []byte
}
// 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 <vmDir>/.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"`
// 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 {
KeymapActive bool `json:"keymap_active"`
Connected bool `json:"connected"`
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
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
}
b, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
f, err := os.CreateTemp(vmDir, ConfigFileName+"-*")
if err != nil {
return err
}
defer os.Remove(f.Name())
_, writeErr := f.Write(b)
if err := errors.Join(writeErr, f.Close()); err != nil {
return err
}
return os.Rename(f.Name(), filepath.Join(vmDir, ConfigFileName))
}
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
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
keymapCarrierEnabled bool
keymapActive bool
lastStatus time.Time
mountMode string
sleepActive bool
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
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:<port>).
type Server struct {
mu sync.RWMutex
fileMu sync.Mutex
clipWriteMu sync.Mutex
clip Clipboard
vms map[string]*registeredVM // keyed by driver.VMRef.Key()
davCache map[string]davCacheEntry
folderAccessMu sync.RWMutex
folderGeneration uint64
dynamicRoutes map[string]http.HandlerFunc
clipboardActive bool
globalClipPolicy ClipboardPolicy
vmClipPolicies map[string]ClipboardPolicy
watcherCount atomic.Int32
clipStatsH2G 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)
onStatusChange func(vmName 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
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("/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("/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()
lastSeq := s.clip.SequenceNumber()
for {
select {
case <-ctx.Done():
return
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
s.mu.Unlock()
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)
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 = &registeredVM{
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))
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)
}
}
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
}
// 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)
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 {
if strings.HasPrefix(davKey, key+"/") {
delete(s.davCache, davKey)
}
}
s.mu.Unlock()
}
// 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 run pbcopy 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 two phrases never overlap pbcopy/Cmd+V.
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,
KeymapActive: freshStatus && vm.keymapCarrierEnabled && vm.keymapActive,
Connected: connected,
MountMode: vm.mountMode,
PreventSleep: vm.preventSleep,
SleepActive: connected && vm.sleepActive,
AgentVersion: vm.agentVersion,
LastSeen: vm.lastSeen,
TimezoneApplied: timezone,
TimezoneHelperReady: freshStatus && vm.timezoneHelperReady,
TimezoneError: timezoneError,
}
}
func (s *Server) SetKeymapCarrier(vmName string, enabled bool) {
vmName = normalizeVMRegistryKey(vmName)
s.mu.Lock()
defer s.mu.Unlock()
if vm := s.vms[vmName]; vm != nil && vm.keymapCarrierEnabled != enabled {
vm.keymapCarrierEnabled = enabled
vm.keymapActive = false
}
}
func (s *Server) SetStatusChangeHandler(fn func(vmName string)) {
s.mu.Lock()
defer s.mu.Unlock()
s.onStatusChange = fn
}
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,
dropShares: vm.dropShares,
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),
keymapCarrierEnabled: vm.keymapCarrierEnabled,
mountMode: vm.mountMode,
sleepActive: vm.sleepActive,
agentVersion: vm.agentVersion,
lastSeen: vm.lastSeen,
}
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", "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 {
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,
"keymap_carrier_enabled": vm.keymapCarrierEnabled,
"prevent_sleep": vm.preventSleep,
"webdav_drop_path": "/dav-drop/" + vm.name + "/",
"host_dns_enabled": vm.hostDNSEnabled,
"timezone": effectiveTimezone(vm.guestTimezone),
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
"shared_folders_count": len(vm.resolvedFolders),
"clipboard_enabled": policy.Enabled,
"clipboard_direction": policy.Direction,
"clipboard_sync_images": policy.SyncImages,
"clipboard_max_bytes": policy.MaxImageBytes,
})
}
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 {
KeymapActive bool `json:"keymap_active"`
MountMode string `json:"mount_mode"`
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()
var notify func(string)
if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token {
now := time.Now()
active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= KeymapAgentVersion
if cur.keymapActive != active || now.Sub(cur.lastStatus) > 30*time.Second {
notify = s.onStatusChange
}
cur.keymapActive = active
cur.lastStatus = now
if mode != "" {
cur.mountMode = mode
}
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
}
cur.lastSeen = time.Now()
}
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
if notify != nil {
notify(vm.name)
}
}
func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) {
if clip, ok := s.clip.(interface {
readClipboard(bool) (ClipPayload, uint32, error)
}); ok {
return clip.readClipboard(wantImage)
}
// 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 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:
s.getClipboard(w, r, vm.key)
case http.MethodPost, http.MethodPut:
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 (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) {
waitSec, err := strconv.Atoi(r.URL.Query().Get("wait"))
if err != nil {
waitSec = 0
}
deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second)
wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
since := r.URL.Query().Get("since")
for {
ch := s.clipNotifyChan()
policy := s.EffectiveClipboardPolicy(vmKey)
if !policy.Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
if policy.Direction != ClipboardGuestToHost {
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
payload, seq, err := s.readClipboardState(wantImage)
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG &&
wantImage && len(payload.Data) <= policy.MaxImageBytes)
if syncable {
h := payloadHash(payload)
if since != h || time.Until(deadline) <= 0 {
setClipboardSeq(w, seq)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
s.touchLastSeen(vmKey)
if since == h {
w.WriteHeader(http.StatusNotModified)
return
}
atomic.AddUint64(&s.clipStatsH2G, 1)
if payload.Kind == ClipPNG {
w.Header().Set("Content-Type", "image/png")
} else {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
_, _ = w.Write(payload.Data)
return
}
} 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.
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 {
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
}
payload.Kind = ClipPNG
} 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)
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)
}