Files
Reims-Go/internal/guesttools/server.go
T

1218 lines
32 KiB
Go

package guesttools
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"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"
)
// 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"`
Token string `json:"token"`
Port int `json:"port"`
SharedDir string `json:"shared_dir"`
PreventSleep bool `json:"prevent_sleep"`
DriveSharingEnabled bool `json:"drive_sharing_enabled"`
SharedDrives []string `json:"shared_drives,omitempty"`
DriveVolumes map[string]string `json:"drive_volumes,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:"-"`
}
// GuestStatus summarizes live Guest Tools connection and capability state.
type GuestStatus struct {
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"`
}
// 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) {
cfgPath := filepath.Join(vmDir, ConfigFileName)
var cfg VMConfig
if b, err := os.ReadFile(cfgPath); err == nil {
if json.Unmarshal(b, &cfg) == nil && len(cfg.Token) >= 32 {
cfg.VMName = vmName
if sharedDir != "" {
cfg.SharedDir = sharedDir
}
if port > 0 {
cfg.Port = port
}
_ = SaveVMConfig(vmDir, cfg)
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) {
if vmDir == "" {
return VMConfig{}, false
}
b, err := os.ReadFile(filepath.Join(vmDir, ConfigFileName))
if err != nil {
return VMConfig{}, false
}
var cfg VMConfig
if json.Unmarshal(b, &cfg) != nil || len(cfg.Token) < 32 {
return VMConfig{}, false
}
return cfg, true
}
// SaveVMConfig persists cfg with restricted permissions.
func SaveVMConfig(vmDir string, cfg VMConfig) error {
if err := os.MkdirAll(vmDir, 0o755); err != nil {
return err
}
b, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(vmDir, ConfigFileName), b, 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 {
name string
token string
sharedDir string
preventSleep bool
driveSharingEnabled bool
sharedDriveRoots map[string]string
mountMode string
sleepActive bool
agentVersion int
lastSeen 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
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
}
// NewServer constructs a Guest Tools HTTP bridge. Pass nil for clip to use the
// host OS clipboard.
func NewServer(clip Clipboard) *Server {
if clip == nil {
clip = &OSClipboard{}
}
return &Server{
clip: clip,
vms: make(map[string]*registeredVM),
davHandlers: make(map[string]*webdav.Handler),
davRoots: make(map[string]string),
clipNotify: make(chan struct{}),
}
}
// 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/status", s.handleStatus)
mux.HandleFunc("/v1/clipboard", s.handleClipboard)
mux.HandleFunc("/v1/text-input", s.handleTextInput)
mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck)
mux.HandleFunc("/v1/host-text", s.handleHostText)
mux.HandleFunc("/v1/files", s.handleListFiles)
mux.HandleFunc("/v1/file", s.handleFile)
mux.HandleFunc("/dav/", s.handleWebDAV)
s.httpSrv = &http.Server{
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
watchCtx, watchCancel := context.WithCancel(context.Background())
s.watchCancel = watchCancel
go s.watchClipboardLoop(watchCtx)
go func() {
_ = s.httpSrv.Serve(ln)
}()
return s.port, nil
}
func (s *Server) watchClipboardLoop(ctx context.Context) {
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.watchCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.broadcastClipChange()
if srv == nil {
return nil
}
return srv.Shutdown(ctx)
}
// RegisterVM registers or updates a VM's token, shared directory, and read-only drive selection.
func (s *Server) RegisterVM(cfg VMConfig) {
if cfg.VMName == "" || cfg.Token == "" {
return
}
if cfg.SharedDir != "" {
_ = os.MkdirAll(cfg.SharedDir, 0o755)
}
driveRoots := configuredDriveRoots(cfg)
s.mu.Lock()
if cur := s.vms[cfg.VMName]; cur != nil {
cur.token = cfg.Token
cur.sharedDir = cfg.SharedDir
cur.preventSleep = cfg.PreventSleep
cur.driveSharingEnabled = cfg.DriveSharingEnabled
cur.sharedDriveRoots = driveRoots
s.mu.Unlock()
return
}
s.vms[cfg.VMName] = &registeredVM{
name: cfg.VMName,
token: cfg.Token,
sharedDir: cfg.SharedDir,
preventSleep: cfg.PreventSleep,
driveSharingEnabled: cfg.DriveSharingEnabled,
sharedDriveRoots: driveRoots,
textActive: make(map[string]*pendingTextInput),
textNotify: make(chan struct{}),
}
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(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")
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) {
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 {
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
return GuestStatus{
Connected: connected,
MountMode: vm.mountMode,
PreventSleep: vm.preventSleep,
SleepActive: connected && vm.sleepActive,
AgentVersion: vm.agentVersion,
LastSeen: vm.lastSeen,
}
}
func (s *Server) touchLastSeen(vmName string) {
s.mu.Lock()
if vm := s.vms[vmName]; vm != nil {
vm.lastSeen = time.Now()
}
s.mu.Unlock()
}
func (s *Server) authenticate(r *http.Request) *registeredVM {
var tok string
auth := strings.TrimSpace(r.Header.Get("Authorization"))
const bearerPrefix = "Bearer "
if strings.HasPrefix(auth, bearerPrefix) {
tok = strings.TrimSpace(auth[len(bearerPrefix):])
} else if _, pass, ok := r.BasicAuth(); ok {
tok = strings.TrimSpace(pass)
}
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{
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
preventSleep: vm.preventSleep,
driveSharingEnabled: vm.driveSharingEnabled,
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
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
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": true,
"vm": vm.name,
"version": DriveShareAgentVersion,
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input", "drive-shares-readonly"},
})
}
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
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
})
}
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"`
SleepActive bool `json:"sleep_active"`
AgentVersion int `json:"agent_version"`
}
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 = ""
}
s.mu.Lock()
if cur := s.vms[vm.name]; cur != nil {
if mode != "" {
cur.mountMode = mode
}
cur.sleepActive = req.SleepActive
if req.AgentVersion > 0 {
cur.agentVersion = req.AgentVersion
}
cur.lastSeen = time.Now()
}
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
}
func (s *Server) readClipboardPayload(acceptImage bool) (ClipPayload, error) {
if acceptImage {
return s.clip.Read()
}
text, err := s.clip.ReadText()
if err != nil {
return ClipPayload{}, err
}
return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil
}
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:
acceptImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
since := r.URL.Query().Get("since")
waitSec := 0
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
}
}
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
for {
if ov := s.takeClipOverride(vm.name); ov != nil {
s.touchLastSeen(vm.name)
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
}
payload, err := s.readClipboardPayload(acceptImage)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h := payloadHash(payload)
if since == "" || since != h {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
if payload.Kind == ClipPNG {
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(payload.Data)
} else {
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write(payload.Data)
}
return
}
if waitSec <= 0 {
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
}
rem := time.Until(deadline)
if rem <= 0 {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
}
ch := s.clipNotifyChan()
timer := time.NewTimer(rem)
select {
case <-ch:
timer.Stop()
case <-timer.C:
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
case <-r.Context().Done():
timer.Stop()
return
}
}
case http.MethodPost, http.MethodPut:
body, err := io.ReadAll(io.LimitReader(r.Body, MaxClipboardBytes+1))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body) > MaxClipboardBytes {
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
return
}
ct := strings.ToLower(r.Header.Get("Content-Type"))
if strings.Contains(ct, "image/png") {
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
}
h := payloadHash(ClipPayload{Kind: ClipPNG, Data: body})
if cur, err := s.clip.Read(); err != nil || payloadHash(cur) != h {
if err := s.clip.WritePNG(body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
return
}
if !utf8.Valid(body) {
http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest)
return
}
text := strings.ReplaceAll(string(body), "\r\n", "\n")
h := textHash(text)
if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h {
if err := s.clip.WriteText(text); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
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.name]
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.name]; 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.name]
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.name)
w.WriteHeader(http.StatusNoContent)
return
}
timer := time.NewTimer(rem)
select {
case <-ch:
timer.Stop()
case <-timer.C:
s.touchLastSeen(vmSnap.name)
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.name]
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 {
go fn(vmSnap.name, string(body))
}
w.WriteHeader(http.StatusAccepted)
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._")
}
// resolveSharedPath validates a relative slash path and ensures the resulting
// path stays strictly inside rootDir (no .., absolute paths, drive letters, or
// symlink escapes).
func resolveSharedPath(rootDir, rel string) (string, error) {
if rootDir == "" {
return "", errors.New("shared directory not configured")
}
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) {
return "", errors.New("invalid path")
}
trimmed := strings.TrimSpace(rel)
if trimmed == "" || strings.HasPrefix(trimmed, "/") {
return "", errors.New("invalid relative path")
}
for _, rawSeg := range strings.Split(trimmed, "/") {
if rawSeg == ".." || rawSeg == "." {
return "", errors.New("path traversal not allowed")
}
}
clean := path.Clean("/" + trimmed)
clean = strings.TrimPrefix(clean, "/")
if clean == "" || clean == "." || strings.HasPrefix(clean, "..") {
return "", errors.New("invalid relative path")
}
parts := strings.Split(clean, "/")
if len(parts) > MaxSharedDepth {
return "", errors.New("path too deep")
}
for _, seg := range parts {
if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) {
return "", errors.New("invalid path segment")
}
}
rootAbs, err := filepath.Abs(rootDir)
if err != nil {
return "", err
}
full := filepath.Join(append([]string{rootAbs}, parts...)...)
relBack, err := filepath.Rel(rootAbs, full)
if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) {
return "", errors.New("path escapes shared root")
}
return full, nil
}
func (s *Server) handleListFiles(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
}
if vm.sharedDir == "" {
w.WriteHeader(http.StatusOK)
return
}
if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rootAbs, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
type entry struct {
mtime int64
size int64
rel string
}
var list []entry
_ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if p == rootAbs {
return nil
}
name := d.Name()
if isIgnoredSharedName(name) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.Type()&os.ModeSymlink != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
rel, err := filepath.Rel(rootAbs, p)
if err != nil {
return nil
}
slash := filepath.ToSlash(rel)
if strings.Count(slash, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes {
return nil
}
if len(list) >= MaxSharedFiles {
return fs.SkipAll
}
list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash})
return nil
})
sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
for _, e := range list {
_, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel)
}
}
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
rel := r.URL.Query().Get("path")
full, err := resolveSharedPath(vm.sharedDir, rel)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch r.Method {
case http.MethodGet:
info, err := os.Lstat(full)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !info.Mode().IsRegular() {
http.Error(w, "not a regular file", http.StatusBadRequest)
return
}
f, err := os.Open(full)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.Copy(w, f)
case http.MethodPut, http.MethodPost:
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpName := tmp.Name()
n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1))
closeErr := tmp.Close()
if copyErr != nil || closeErr != nil || n > MaxUploadBytes {
_ = os.Remove(tmpName)
if n > MaxUploadBytes {
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "write failed", http.StatusInternalServerError)
return
}
if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" {
if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 {
t := time.Unix(ts, 0)
_ = os.Chtimes(tmpName, t, t)
}
}
if err := os.Rename(tmpName, full); err != nil {
_ = os.Remove(tmpName)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}