483 lines
13 KiB
Go
483 lines
13 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const MaxHostDropBodyBytes = 256 << 10
|
|
const MaxHostDropPaths = 64
|
|
|
|
var ErrInvalidHostDrop = errors.New("invalid host drop")
|
|
|
|
type HostDropRequest struct {
|
|
DisplayIndex int `json:"display_index"`
|
|
NormX float64 `json:"norm_x"`
|
|
NormY float64 `json:"norm_y"`
|
|
InImage bool `json:"in_image"`
|
|
Paths []string `json:"paths"`
|
|
Text string `json:"text,omitempty"`
|
|
}
|
|
|
|
type HostDropResult struct {
|
|
DropID string `json:"drop_id"`
|
|
Delivered []string `json:"delivered"`
|
|
Skipped []string `json:"skipped,omitempty"`
|
|
Mode string `json:"mode"`
|
|
}
|
|
|
|
func (s *Server) HostDropToken(driverID, vmName string) string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if vm := s.vms[vmRegistryKey(driverID, vmName)]; vm != nil {
|
|
return vm.hostDropToken
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (s *Server) authenticateHostDrop(r *http.Request) (string, string) {
|
|
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if !ok || len(token) != 64 {
|
|
return "", ""
|
|
}
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
for _, vm := range s.vms {
|
|
if subtle.ConstantTimeCompare([]byte(token), []byte(vm.hostDropToken)) == 1 {
|
|
return vm.key, vm.name
|
|
}
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
func (s *Server) SetHostDropHandler(fn func(string, string, HostDropRequest) (HostDropResult, error)) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.onHostDrop = fn
|
|
}
|
|
|
|
func (s *Server) handleHostDrop(w http.ResponseWriter, r *http.Request) {
|
|
key, name := s.authenticateHostDrop(r)
|
|
if key == "" {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, MaxHostDropBodyBytes+1))
|
|
if err != nil {
|
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if len(body) > MaxHostDropBodyBytes {
|
|
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
|
|
return
|
|
}
|
|
var req HostDropRequest
|
|
dec := json.NewDecoder(bytes.NewReader(body))
|
|
dec.DisallowUnknownFields()
|
|
if dec.Decode(&req) != nil || dec.Decode(new(any)) != io.EOF || req.DisplayIndex < 0 ||
|
|
math.IsNaN(req.NormX) || math.IsInf(req.NormX, 0) || math.IsNaN(req.NormY) || math.IsInf(req.NormY, 0) ||
|
|
!((len(req.Paths) > 0 && len(req.Paths) <= MaxHostDropPaths && req.Text == "") ||
|
|
(len(req.Paths) == 0 && req.Text != "" && len(req.Text) <= MaxTextInputBytes && utf8.Valid(body) && utf8.ValidString(req.Text))) {
|
|
http.Error(w, "invalid host drop", http.StatusBadRequest)
|
|
return
|
|
}
|
|
req.NormX = min(1, max(0, req.NormX))
|
|
req.NormY = min(1, max(0, req.NormY))
|
|
s.mu.RLock()
|
|
fn := s.onHostDrop
|
|
s.mu.RUnlock()
|
|
if fn == nil {
|
|
http.Error(w, "host drop unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
result, err := fn(key, name, req)
|
|
if errors.Is(err, ErrInvalidHostDrop) {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err != nil {
|
|
http.Error(w, "host drop failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(result)
|
|
}
|
|
|
|
const (
|
|
DropEventTTL = 60 * time.Second
|
|
MaxPendingDropEvents = 32
|
|
MaxDropAckBodyBytes = 64 << 10
|
|
)
|
|
|
|
type DropEvent struct {
|
|
Kind string `json:"kind,omitempty"`
|
|
Text string `json:"text,omitempty"`
|
|
WebDAVDrop bool `json:"webdav_drop,omitempty"`
|
|
DropID string `json:"drop_id"`
|
|
DisplayIndex int `json:"display_index"`
|
|
NormX float64 `json:"norm_x"`
|
|
NormY float64 `json:"norm_y"`
|
|
InImage bool `json:"in_image"`
|
|
Items []string `json:"items"`
|
|
TargetPaths []string `json:"target_paths,omitempty"`
|
|
CreatedAt time.Time `json:"-"`
|
|
}
|
|
|
|
type DropEventAck struct {
|
|
DropID string `json:"drop_id"`
|
|
Status string `json:"status"`
|
|
TargetKind string `json:"target_kind"`
|
|
TargetLabel string `json:"target_label,omitempty"`
|
|
PlacedNames []string `json:"placed_names,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
func (s *Server) SetDropAckHandler(fn func(vmKey, vmName string, ack DropEventAck)) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.onDropAck = fn
|
|
}
|
|
|
|
func (s *Server) HasDropEventListener(vmKey string) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
cur := s.vms[normalizeVMRegistryKey(vmKey)]
|
|
return cur != nil && (cur.dropWaiters > 0 || (!cur.lastDropPoll.IsZero() && time.Since(cur.lastDropPoll) <= 35*time.Second))
|
|
}
|
|
|
|
func (vm *registeredVM) pruneDropEvents(now time.Time) {
|
|
vm.dropQueue = slices.DeleteFunc(vm.dropQueue, func(ev *DropEvent) bool {
|
|
return now.Sub(ev.CreatedAt) > DropEventTTL
|
|
})
|
|
for id, ev := range vm.dropActive {
|
|
if now.Sub(ev.CreatedAt) > DropEventTTL {
|
|
delete(vm.dropActive, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) EnqueueDropEvent(vmKey string, ev DropEvent) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
vm := s.vms[normalizeVMRegistryKey(vmKey)]
|
|
if ev.Kind == "" {
|
|
ev.Kind = "files"
|
|
}
|
|
if vm == nil || ev.DropID == "" || !((ev.Kind == "files" && len(ev.Items) > 0) || (ev.Kind == "text" && ev.Text != "")) {
|
|
return false
|
|
}
|
|
now := time.Now()
|
|
if ev.CreatedAt.IsZero() {
|
|
ev.CreatedAt = now
|
|
}
|
|
ev.Items = slices.Clone(ev.Items)
|
|
if len(ev.TargetPaths) > 0 {
|
|
ev.TargetPaths = slices.Clone(ev.TargetPaths)
|
|
}
|
|
vm.pruneDropEvents(now)
|
|
if len(vm.dropQueue) >= MaxPendingDropEvents {
|
|
vm.dropQueue = slices.Delete(vm.dropQueue, 0, 1)
|
|
}
|
|
vm.dropQueue = append(vm.dropQueue, &ev)
|
|
close(vm.dropNotify)
|
|
vm.dropNotify = make(chan struct{})
|
|
return true
|
|
}
|
|
|
|
func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) {
|
|
vmSnap := s.authenticate(r)
|
|
if vmSnap == nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
waitSec := MaxLongPollSec
|
|
if rawWait := r.URL.Query().Get("wait"); rawWait != "" {
|
|
if n, err := strconv.Atoi(rawWait); err == nil && n >= 0 {
|
|
if n > MaxLongPollSec {
|
|
n = MaxLongPollSec
|
|
}
|
|
waitSec = n
|
|
}
|
|
}
|
|
|
|
s.mu.Lock()
|
|
vm := s.vms[vmSnap.key]
|
|
if vm == nil || vm.token != vmSnap.token {
|
|
s.mu.Unlock()
|
|
http.Error(w, "vm not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
vm.dropWaiters++
|
|
vm.lastDropPoll = time.Now()
|
|
s.mu.Unlock()
|
|
defer func() {
|
|
s.mu.Lock()
|
|
if cur := s.vms[vmSnap.key]; cur == vm && cur.token == vmSnap.token {
|
|
if cur.dropWaiters > 0 {
|
|
cur.dropWaiters--
|
|
}
|
|
cur.lastDropPoll = time.Now()
|
|
}
|
|
s.mu.Unlock()
|
|
}()
|
|
|
|
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
|
|
for {
|
|
s.mu.Lock()
|
|
cur := s.vms[vmSnap.key]
|
|
if cur != vm || cur.token != vmSnap.token {
|
|
s.mu.Unlock()
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
cur.pruneDropEvents(time.Now())
|
|
if len(cur.dropQueue) > 0 {
|
|
item := cur.dropQueue[0]
|
|
cur.dropQueue[0] = nil
|
|
cur.dropQueue = cur.dropQueue[1:]
|
|
cur.dropActive[item.DropID] = item
|
|
cur.markSeen(time.Now())
|
|
cur.lastDropPoll = time.Now()
|
|
s.mu.Unlock()
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(item)
|
|
return
|
|
}
|
|
ch := cur.dropNotify
|
|
s.mu.Unlock()
|
|
|
|
rem := time.Until(deadline)
|
|
if waitSec <= 0 || rem <= 0 {
|
|
s.touchLastSeen(vmSnap.key)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
timer := time.NewTimer(rem)
|
|
select {
|
|
case <-ch:
|
|
timer.Stop()
|
|
case <-timer.C:
|
|
s.touchLastSeen(vmSnap.key)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
case <-r.Context().Done():
|
|
timer.Stop()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) handleDropEventsAck(w http.ResponseWriter, r *http.Request) {
|
|
vmSnap := s.authenticate(r)
|
|
if vmSnap == nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, MaxDropAckBodyBytes+1))
|
|
if err != nil {
|
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if len(body) > MaxDropAckBodyBytes {
|
|
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
|
|
return
|
|
}
|
|
var ack DropEventAck
|
|
dec := json.NewDecoder(bytes.NewReader(body))
|
|
dec.DisallowUnknownFields()
|
|
if dec.Decode(&ack) != nil || dec.Decode(new(any)) != io.EOF || ack.DropID == "" ||
|
|
!slices.Contains([]string{"placed", "pasted", "cancelled", "fallback_share", "failed"}, ack.Status) ||
|
|
!slices.Contains([]string{"desktop", "finder_window", "finder_folder", "photos", "window", "share", "cancelled"}, ack.TargetKind) {
|
|
http.Error(w, "invalid drop acknowledgement", http.StatusBadRequest)
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
active := false
|
|
if cur := s.vms[vmSnap.key]; cur != nil && cur.token == vmSnap.token {
|
|
cur.pruneDropEvents(time.Now())
|
|
_, active = cur.dropActive[ack.DropID]
|
|
delete(cur.dropActive, ack.DropID)
|
|
}
|
|
fn := s.onDropAck
|
|
s.mu.Unlock()
|
|
if active && fn != nil {
|
|
fn(vmSnap.key, vmSnap.name, ack)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *Server) RegisterDropShare(vmKey, dropID string, entries []DropShareEntry) bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
vm := s.vms[normalizeVMRegistryKey(vmKey)]
|
|
return vm != nil && vm.dropShares.register(dropID, entries)
|
|
}
|
|
|
|
func (s *Server) ensureClipboardShare(vmKey, dropID string, entries []DropShareEntry) bool {
|
|
key := normalizeVMRegistryKey(vmKey)
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
vm := s.vms[key]
|
|
return vm != nil && s.effectiveClipboardPolicyLocked(key).allowsHostToGuestFiles() && vm.dropShares.ensure(dropID, entries)
|
|
}
|
|
|
|
func (s *Server) RevokeDropShare(vmKey, dropID string) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if vm := s.vms[normalizeVMRegistryKey(vmKey)]; vm != nil {
|
|
vm.dropShares.revoke(dropID)
|
|
}
|
|
}
|
|
|
|
func (s *Server) SetDropPasteHandler(fn func(ctx context.Context, vmKey, vmName, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.onDropPaste = fn
|
|
}
|
|
|
|
func (s *Server) handleDropWebDAV(w http.ResponseWriter, r *http.Request) {
|
|
vm := s.authenticate(r)
|
|
if vm == nil {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="ReimsDrop"`)
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
trimmed := strings.TrimPrefix(r.URL.Path, "/dav-drop/")
|
|
vmPart, _, _ := strings.Cut(trimmed, "/")
|
|
if vmPart != vm.name {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
if !allowPROPFINDDepth(w, r) || !allowReadOnlyDAV(w, r) {
|
|
return
|
|
}
|
|
vm.dropDAVHandler.ServeHTTP(w, r)
|
|
}
|
|
|
|
func (s *Server) handleDropFile(w http.ResponseWriter, r *http.Request) {
|
|
vm := s.authenticate(r)
|
|
if vm == nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
w.Header().Set("Allow", "GET, HEAD")
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
serveDropFile(vm.dropDAVHandler.FileSystem, w, r, q.Get("drop_id"), q.Get("path"))
|
|
}
|
|
|
|
func (s *Server) handleDropEventsPaste(w http.ResponseWriter, r *http.Request) {
|
|
snap := s.authenticate(r)
|
|
if snap == nil {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, MaxDropAckBodyBytes+1))
|
|
if err != nil {
|
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if len(body) > MaxDropAckBodyBytes {
|
|
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
|
|
return
|
|
}
|
|
var req struct {
|
|
DropID string `json:"drop_id"`
|
|
ActivateClick bool `json:"activate_click,omitempty"`
|
|
CommandKey string `json:"command_key,omitempty"`
|
|
FocusWaitMS int `json:"focus_wait_ms,omitempty"`
|
|
}
|
|
dec := json.NewDecoder(bytes.NewReader(body))
|
|
dec.DisallowUnknownFields()
|
|
if dec.Decode(&req) != nil || dec.Decode(new(any)) != io.EOF || req.DropID == "" ||
|
|
req.FocusWaitMS < 0 || req.FocusWaitMS > 500 {
|
|
http.Error(w, "invalid paste request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
switch req.CommandKey {
|
|
case "":
|
|
req.CommandKey = "meta_l"
|
|
case "meta_l", "meta_r", "alt", "alt_r", "ctrl", "ctrl_r", "shift", "shift_r", "caps_lock":
|
|
default:
|
|
http.Error(w, "invalid paste request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
s.mu.RLock()
|
|
vm := s.vms[snap.key]
|
|
s.mu.RUnlock()
|
|
if vm == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
vm.injectMu.Lock()
|
|
defer vm.injectMu.Unlock()
|
|
|
|
s.mu.Lock()
|
|
var ev *DropEvent
|
|
if s.vms[snap.key] == vm && vm.token == snap.token {
|
|
vm.pruneDropEvents(time.Now())
|
|
ev = vm.dropActive[req.DropID]
|
|
}
|
|
fn, settle := s.onDropPaste, s.dropPasteSettle
|
|
s.mu.Unlock()
|
|
if ev == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if fn == nil {
|
|
http.Error(w, "drop paste unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
if r.Context().Err() != nil {
|
|
return
|
|
}
|
|
if err := fn(r.Context(), snap.key, snap.name, ev.DropID, ev.DisplayIndex, ev.NormX, ev.NormY, req.ActivateClick, req.CommandKey, time.Duration(req.FocusWaitMS)*time.Millisecond); err != nil {
|
|
http.Error(w, "drop paste failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if settle <= 0 {
|
|
settle = 500 * time.Millisecond
|
|
}
|
|
timer := time.NewTimer(settle)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-r.Context().Done():
|
|
case <-timer.C:
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
}
|