227 lines
6.9 KiB
Go
227 lines
6.9 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync/atomic"
|
|
)
|
|
|
|
// ClipboardDirection controls which way host <-> guest clipboard sync flows (§5.4).
|
|
type ClipboardDirection string
|
|
|
|
const (
|
|
ClipboardBidirectional ClipboardDirection = "bidirectional"
|
|
ClipboardHostToGuest ClipboardDirection = "host-to-guest"
|
|
ClipboardGuestToHost ClipboardDirection = "guest-to-host"
|
|
)
|
|
|
|
// ClipboardPolicy configures clipboard sync globally or per VM (§5.4).
|
|
type ClipboardPolicy struct {
|
|
Enabled bool `json:"enabled"`
|
|
Direction ClipboardDirection `json:"direction"`
|
|
SyncImages bool `json:"sync_images"`
|
|
MaxImageBytes int `json:"max_image_bytes"`
|
|
}
|
|
|
|
// DefaultClipboardPolicy returns the default bidirectional text+image policy.
|
|
func DefaultClipboardPolicy() ClipboardPolicy {
|
|
return ClipboardPolicy{
|
|
Enabled: true,
|
|
Direction: ClipboardBidirectional,
|
|
SyncImages: true,
|
|
MaxImageBytes: MaxClipboardBytes,
|
|
}
|
|
}
|
|
|
|
// ClipboardStats tracks privacy-safe counters (never clipboard content, §5.4).
|
|
type ClipboardStats struct {
|
|
HostToGuestCount uint64 `json:"host_to_guest_count"`
|
|
GuestToHostCount uint64 `json:"guest_to_host_count"`
|
|
ErrorCount uint64 `json:"error_count"`
|
|
Active bool `json:"active"`
|
|
WatcherRunning bool `json:"watcher_running"`
|
|
}
|
|
|
|
// NewTransportServer constructs a Guest Tools HTTP transport server with
|
|
// clipboard disabled until the builtin.bridge.clipboard extension activates it (§5.4).
|
|
func NewTransportServer(clip Clipboard) *Server {
|
|
s := NewServer(clip)
|
|
s.clipboardActive = false
|
|
delete(s.dynamicRoutes, "/v1/clipboard")
|
|
s.globalClipPolicy = DefaultClipboardPolicy()
|
|
s.globalClipPolicy.Enabled = false
|
|
return s
|
|
}
|
|
|
|
// RegisterRoute dynamically mounts an HTTP handler on the Guest Tools bridge
|
|
// and returns an unregister function for Scope.OnDispose (§5.4).
|
|
func (s *Server) RegisterRoute(routePath string, handler http.HandlerFunc) func() {
|
|
s.mu.Lock()
|
|
if s.dynamicRoutes == nil {
|
|
s.dynamicRoutes = make(map[string]http.HandlerFunc)
|
|
}
|
|
s.dynamicRoutes[routePath] = handler
|
|
s.mu.Unlock()
|
|
return func() {
|
|
s.mu.Lock()
|
|
delete(s.dynamicRoutes, routePath)
|
|
s.mu.Unlock()
|
|
}
|
|
}
|
|
|
|
// HasRoute reports whether routePath is currently registered on the bridge.
|
|
func (s *Server) HasRoute(routePath string) bool {
|
|
s.mu.RLock()
|
|
_, ok := s.dynamicRoutes[routePath]
|
|
s.mu.RUnlock()
|
|
return ok
|
|
}
|
|
|
|
// SetClipboardActive enables or disables the clipboard extension on this bridge.
|
|
// Enabling registers /v1/clipboard and starts the host clipboard watcher;
|
|
// disabling removes the route and stops the watcher with zero residue (§5.4).
|
|
func (s *Server) SetClipboardActive(active bool) {
|
|
s.mu.Lock()
|
|
s.clipboardActive = active
|
|
if s.dynamicRoutes == nil {
|
|
s.dynamicRoutes = make(map[string]http.HandlerFunc)
|
|
}
|
|
if active {
|
|
s.globalClipPolicy.Enabled = true
|
|
s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard
|
|
if s.listener != nil && s.watchCancel == nil {
|
|
watchCtx, watchCancel := context.WithCancel(context.Background())
|
|
s.watchCancel = watchCancel
|
|
s.watcherCount.Add(1)
|
|
go s.watchClipboardLoop(watchCtx)
|
|
}
|
|
s.mu.Unlock()
|
|
return
|
|
}
|
|
s.globalClipPolicy.Enabled = false
|
|
delete(s.dynamicRoutes, "/v1/clipboard")
|
|
cancel := s.watchCancel
|
|
s.watchCancel = nil
|
|
s.mu.Unlock()
|
|
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
s.broadcastClipChange()
|
|
}
|
|
|
|
// IsClipboardActive reports whether the clipboard feature is currently active.
|
|
func (s *Server) IsClipboardActive() bool {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.clipboardActive
|
|
}
|
|
|
|
// IsClipboardWatcherRunning reports whether the host clipboard polling goroutine is active.
|
|
func (s *Server) IsClipboardWatcherRunning() bool {
|
|
return s.watcherCount.Load() > 0
|
|
}
|
|
|
|
// SetGlobalClipboardPolicy updates the global clipboard policy immediately.
|
|
func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) {
|
|
p = normalizeClipboardPolicy(p)
|
|
s.mu.Lock()
|
|
s.globalClipPolicy = p
|
|
s.mu.Unlock()
|
|
s.broadcastClipChange()
|
|
}
|
|
|
|
// SetVMClipboardPolicy sets or clears a per-VM clipboard policy override immediately.
|
|
func (s *Server) SetVMClipboardPolicy(vmName string, p *ClipboardPolicy) {
|
|
s.mu.Lock()
|
|
if s.vmClipPolicies == nil {
|
|
s.vmClipPolicies = make(map[string]ClipboardPolicy)
|
|
}
|
|
if p == nil {
|
|
delete(s.vmClipPolicies, vmName)
|
|
} else {
|
|
s.vmClipPolicies[vmName] = normalizeClipboardPolicy(*p)
|
|
}
|
|
s.mu.Unlock()
|
|
s.broadcastClipChange()
|
|
}
|
|
|
|
// EffectiveClipboardPolicy returns the resolved policy for vmName.
|
|
func (s *Server) EffectiveClipboardPolicy(vmName string) ClipboardPolicy {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
if !s.clipboardActive {
|
|
p := s.globalClipPolicy
|
|
p.Enabled = false
|
|
return p
|
|
}
|
|
if ov, ok := s.vmClipPolicies[vmName]; ok {
|
|
return ov
|
|
}
|
|
return s.globalClipPolicy
|
|
}
|
|
|
|
// ClipboardDiagnostics returns privacy-safe clipboard metrics (counts/errors only, §5.4).
|
|
func (s *Server) ClipboardDiagnostics() ClipboardStats {
|
|
return ClipboardStats{
|
|
HostToGuestCount: atomic.LoadUint64(&s.clipStatsH2G),
|
|
GuestToHostCount: atomic.LoadUint64(&s.clipStatsG2H),
|
|
ErrorCount: atomic.LoadUint64(&s.clipStatsErr),
|
|
Active: s.IsClipboardActive(),
|
|
WatcherRunning: s.IsClipboardWatcherRunning(),
|
|
}
|
|
}
|
|
|
|
func normalizeClipboardPolicy(p ClipboardPolicy) ClipboardPolicy {
|
|
switch p.Direction {
|
|
case ClipboardBidirectional, ClipboardHostToGuest, ClipboardGuestToHost:
|
|
default:
|
|
p.Direction = ClipboardBidirectional
|
|
}
|
|
if p.MaxImageBytes <= 0 || p.MaxImageBytes > MaxClipboardBytes {
|
|
p.MaxImageBytes = MaxClipboardBytes
|
|
}
|
|
return p
|
|
}
|
|
|
|
func writeFeatureDisabled(w http.ResponseWriter, feature string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Retry-After", "5")
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"error": "feature_disabled",
|
|
"feature": feature,
|
|
})
|
|
}
|
|
|
|
// localSecurityMiddleware blocks sandboxed iframes and cross-origin web pages
|
|
// from calling the local Guest Tools HTTP API (docs/plugin-architecture.md §7.3).
|
|
func localSecurityMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if strings.EqualFold(strings.TrimSpace(r.Header.Get("Sec-Fetch-Dest")), "iframe") {
|
|
http.Error(w, "forbidden: iframe access denied", http.StatusForbidden)
|
|
return
|
|
}
|
|
if origin := strings.TrimSpace(r.Header.Get("Origin")); origin != "" {
|
|
if strings.EqualFold(origin, "null") {
|
|
http.Error(w, "forbidden: null origin denied", http.StatusForbidden)
|
|
return
|
|
}
|
|
u, err := url.Parse(origin)
|
|
if err != nil || !strings.EqualFold(u.Scheme, "http") || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
|
|
http.Error(w, "forbidden: cross-origin denied", http.StatusForbidden)
|
|
return
|
|
}
|
|
host := strings.ToLower(u.Hostname())
|
|
if host != "127.0.0.1" && host != "localhost" && host != "10.0.2.2" {
|
|
http.Error(w, "forbidden: cross-origin denied", http.StatusForbidden)
|
|
return
|
|
}
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|