* 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>
360 lines
11 KiB
Go
360 lines
11 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/qmp"
|
|
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
|
)
|
|
|
|
const MaxHostDropFileBytes int64 = 2 << 30
|
|
const MaxHostDropTotalBytes int64 = 4 << 30
|
|
|
|
const MaxHostDropFolderFiles = 256
|
|
|
|
func dropSegment(s string) bool {
|
|
return filepath.IsLocal(s) && !strings.HasPrefix(s, ".") &&
|
|
!strings.ContainsAny(s, "/\\\x00:\u003c\u003e|\"?*\r\n")
|
|
}
|
|
|
|
var hostDropPublishMu sync.Mutex
|
|
var errDropSize = errors.New("host drop size limit exceeded")
|
|
|
|
func validateHostDropPath(raw string) (string, error) {
|
|
if strings.TrimSpace(raw) == "" || strings.ContainsRune(raw, 0) ||
|
|
strings.HasPrefix(strings.ReplaceAll(raw, "\\", "/"), "//") || !filepath.IsAbs(raw) {
|
|
return "", fmt.Errorf("%w: expected an absolute local path", guesttools.ErrInvalidHostDrop)
|
|
}
|
|
clean := filepath.Clean(raw)
|
|
st, err := os.Lstat(clean)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: %v", guesttools.ErrInvalidHostDrop, err)
|
|
}
|
|
if guesttools.IsDropSymlink(st) {
|
|
return "", fmt.Errorf("%w: symbolic link", guesttools.ErrInvalidHostDrop)
|
|
}
|
|
return clean, nil
|
|
}
|
|
|
|
func allocUniqueDropName(base string, splitExt bool, claim func(string) (bool, error)) (string, error) {
|
|
var ext string
|
|
if splitExt {
|
|
ext = filepath.Ext(base)
|
|
}
|
|
stem := strings.TrimSuffix(base, ext)
|
|
candidate := base
|
|
for n := 1; ; n++ {
|
|
claimed, err := claim(candidate)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if claimed {
|
|
return candidate, nil
|
|
}
|
|
candidate = fmt.Sprintf("%s (%d)%s", stem, n, ext)
|
|
}
|
|
}
|
|
|
|
func uniqueDropEntryName(used map[string]struct{}, base string, isDir bool) string {
|
|
name, _ := allocUniqueDropName(base, !isDir, func(candidate string) (bool, error) {
|
|
if _, exists := used[candidate]; exists {
|
|
return false, nil
|
|
}
|
|
used[candidate] = struct{}{}
|
|
return true, nil
|
|
})
|
|
return name
|
|
}
|
|
|
|
func (a *App) handleHostDrop(vmKey, name string, req guesttools.HostDropRequest) (guesttools.HostDropResult, error) {
|
|
var id [16]byte
|
|
rand.Read(id[:])
|
|
result := guesttools.HostDropResult{
|
|
DropID: hex.EncodeToString(id[:]), Delivered: []string{},
|
|
}
|
|
srv := a.currentGuestToolsServer()
|
|
hasListener := srv != nil && srv.HasDropEventListener(vmKey)
|
|
event := guesttools.DropEvent{
|
|
DropID: result.DropID, DisplayIndex: req.DisplayIndex, NormX: req.NormX,
|
|
NormY: req.NormY, InImage: req.InImage,
|
|
}
|
|
if req.Text != "" {
|
|
result.Mode = "text_ignored"
|
|
event.Kind, event.Text = "text", req.Text
|
|
if hasListener && srv.EnqueueDropEvent(vmKey, event) {
|
|
result.Mode = "l2_text"
|
|
}
|
|
return result, nil
|
|
}
|
|
paths := make([]string, 0, len(req.Paths))
|
|
for _, raw := range req.Paths {
|
|
path, err := validateHostDropPath(raw)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
paths = append(paths, path)
|
|
}
|
|
if hasListener {
|
|
used := make(map[string]struct{})
|
|
var entries []guesttools.DropShareEntry
|
|
for _, path := range paths {
|
|
st, err := os.Lstat(path)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
base := filepath.Base(path)
|
|
if !dropSegment(base) || guesttools.IsDropSymlink(st) || (!st.IsDir() && !st.Mode().IsRegular()) {
|
|
result.Skipped = append(result.Skipped, base)
|
|
continue
|
|
}
|
|
alias := uniqueDropEntryName(used, base, st.IsDir())
|
|
entries = append(entries, guesttools.DropShareEntry{Name: alias, HostPath: path, IsDir: st.IsDir()})
|
|
result.Delivered = append(result.Delivered, alias)
|
|
}
|
|
if len(entries) > 0 {
|
|
if !srv.RegisterDropShare(vmKey, result.DropID, entries) {
|
|
result.Delivered = []string{}
|
|
return result, errors.New("could not register drop share")
|
|
}
|
|
event.Kind, event.WebDAVDrop = "files", true
|
|
event.Items, event.TargetPaths = result.Delivered, result.Delivered
|
|
if !srv.EnqueueDropEvent(vmKey, event) {
|
|
srv.RevokeDropShare(vmKey, result.DropID)
|
|
result.Delivered = []string{}
|
|
return result, errors.New("could not enqueue file drop")
|
|
}
|
|
result.Mode = "l2_webdav"
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
result.Mode = "l1_share"
|
|
var total int64
|
|
var fileCount int
|
|
sharedDir := a.vmSharedDir(name)
|
|
for _, path := range paths {
|
|
st, err := os.Lstat(path)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
base := filepath.Base(path)
|
|
if !dropSegment(base) || guesttools.IsDropSymlink(st) || fileCount >= MaxHostDropFolderFiles {
|
|
result.Skipped = append(result.Skipped, base)
|
|
continue
|
|
}
|
|
if st.IsDir() {
|
|
folder, nested, size, err := stageDropFolder(sharedDir, path, MaxHostDropFolderFiles-fileCount, MaxHostDropTotalBytes-total)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
if len(nested) == 0 {
|
|
result.Skipped = append(result.Skipped, base)
|
|
continue
|
|
}
|
|
total += size
|
|
result.Delivered = append(result.Delivered, folder)
|
|
fileCount += len(nested)
|
|
continue
|
|
}
|
|
if !st.Mode().IsRegular() {
|
|
result.Skipped = append(result.Skipped, base)
|
|
continue
|
|
}
|
|
delivered, size, err := a.deliverHostFileLimited(name, path, st, min(MaxHostDropFileBytes, MaxHostDropTotalBytes-total))
|
|
if errors.Is(err, errDropSize) {
|
|
a.emitVMLog(name, fmt.Sprintf("Skipped %s: host drop size limit exceeded", base))
|
|
result.Skipped = append(result.Skipped, base)
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
total += size
|
|
fileCount++
|
|
result.Delivered = append(result.Delivered, delivered)
|
|
}
|
|
a.emitVMLog(name, fmt.Sprintf("Host drop %s: delivered %d, skipped %d", result.DropID, len(result.Delivered), len(result.Skipped)))
|
|
if a.ctx != nil && len(result.Delivered) > 0 {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop", map[string]any{
|
|
"vm": name, "drop_id": result.DropID, "delivered": result.Delivered, "skipped": result.Skipped, "mode": result.Mode,
|
|
})
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (a *App) currentGuestToolsServer() *guesttools.Server {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
return a.guestTools
|
|
}
|
|
|
|
var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste
|
|
|
|
func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
|
|
if _, running := a.currentVMPID(ctx, name); !running {
|
|
return fmt.Errorf("%s is not running", name)
|
|
}
|
|
d, err := a.GetVMDetail(name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
|
|
}
|
|
|
|
func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) {
|
|
revoke := ack.Status == "placed" || ack.Status == "cancelled" || ack.Status == "failed"
|
|
if srv := a.currentGuestToolsServer(); srv != nil && revoke {
|
|
srv.RevokeDropShare(vmKey, ack.DropID)
|
|
}
|
|
a.emitVMLog(name, fmt.Sprintf("Host drop %s: %s (%s)", ack.DropID, ack.Status, ack.TargetKind))
|
|
if ack.Status != "cancelled" && a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop-ack", map[string]any{
|
|
"vm": name, "drop_id": ack.DropID, "status": ack.Status, "target_kind": ack.TargetKind,
|
|
"target_label": ack.TargetLabel, "placed_names": ack.PlacedNames, "error": ack.Error,
|
|
})
|
|
}
|
|
}
|
|
|
|
func allocUniqueDir(parent, base string) (string, error) {
|
|
hostDropPublishMu.Lock()
|
|
defer hostDropPublishMu.Unlock()
|
|
return allocUniqueDropName(base, false, func(candidate string) (bool, error) {
|
|
err := os.Mkdir(filepath.Join(parent, candidate), 0o755)
|
|
if errors.Is(err, os.ErrExist) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
})
|
|
}
|
|
|
|
func stageDropFolder(shared, src string, count int, limit int64) (string, []string, int64, error) {
|
|
type entry struct {
|
|
rel string
|
|
st os.FileInfo
|
|
}
|
|
var files []entry
|
|
var estimated int64
|
|
var walk func(string, int) error
|
|
walk = func(rel string, depth int) error {
|
|
dir := filepath.Join(src, rel)
|
|
children, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, child := range children {
|
|
if len(files) == count {
|
|
break
|
|
}
|
|
if !dropSegment(child.Name()) {
|
|
continue
|
|
}
|
|
next := filepath.Join(rel, child.Name())
|
|
st, err := os.Lstat(filepath.Join(src, next))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if guesttools.IsDropSymlink(st) {
|
|
continue
|
|
}
|
|
if st.IsDir() && depth < guesttools.MaxSharedDepth {
|
|
if err := walk(next, depth+1); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if st.Mode().IsRegular() && st.Size() <= min(MaxHostDropFileBytes, limit-estimated) {
|
|
files = append(files, entry{next, st})
|
|
estimated += st.Size()
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := walk("", 2); err != nil || len(files) == 0 {
|
|
return "", nil, 0, err
|
|
}
|
|
if err := os.MkdirAll(shared, 0o755); err != nil {
|
|
return "", nil, 0, err
|
|
}
|
|
folder, err := allocUniqueDir(shared, filepath.Base(src))
|
|
if err != nil {
|
|
return "", nil, 0, err
|
|
}
|
|
dest := filepath.Join(shared, folder)
|
|
var items []string
|
|
var total int64
|
|
for _, f := range files {
|
|
parent := filepath.Dir(filepath.Join(dest, f.rel))
|
|
base, size, err := deliverHostFileLimited(parent, filepath.Join(src, f.rel), f.st, min(MaxHostDropFileBytes, limit-total))
|
|
if err != nil {
|
|
return "", nil, 0, errors.Join(err, os.RemoveAll(dest))
|
|
}
|
|
items = append(items, filepath.ToSlash(filepath.Join(folder, filepath.Dir(f.rel), base)))
|
|
total += size
|
|
}
|
|
return folder, items, total, nil
|
|
}
|
|
|
|
func (a *App) deliverHostFileLimited(name, path string, expected os.FileInfo, limit int64) (string, int64, error) {
|
|
return deliverHostFileLimited(a.vmSharedDir(name), path, expected, limit)
|
|
}
|
|
|
|
func deliverHostFileLimited(dir, path string, expected os.FileInfo, limit int64) (string, int64, error) {
|
|
if expected.Size() > limit {
|
|
return "", 0, errDropSize
|
|
}
|
|
src, err := os.Open(path)
|
|
if err != nil {
|
|
return "", 0, err
|
|
}
|
|
defer src.Close()
|
|
st, err := src.Stat()
|
|
if err != nil {
|
|
return "", 0, err
|
|
}
|
|
if !st.Mode().IsRegular() || !os.SameFile(expected, st) {
|
|
return "", 0, fmt.Errorf("%w: source changed", guesttools.ErrInvalidHostDrop)
|
|
}
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return "", 0, err
|
|
}
|
|
tmp, err := os.CreateTemp(dir, ".reims-deliver-*")
|
|
if err != nil {
|
|
return "", 0, err
|
|
}
|
|
defer os.Remove(tmp.Name())
|
|
size, copyErr := io.Copy(tmp, io.LimitReader(src, limit+1))
|
|
closeErr := tmp.Close()
|
|
if err := errors.Join(copyErr, closeErr); err != nil {
|
|
return "", 0, err
|
|
}
|
|
if size > limit {
|
|
return "", 0, errDropSize
|
|
}
|
|
base, err := deliverHostFileUnique(dir, filepath.Base(path), tmp.Name())
|
|
return base, size, err
|
|
}
|
|
|
|
// Link publishes the completed file atomically and fails if another writer
|
|
// already owns the name, including writers outside this process.
|
|
func deliverHostFileUnique(dir, base, tmp string) (string, error) {
|
|
hostDropPublishMu.Lock()
|
|
defer hostDropPublishMu.Unlock()
|
|
return allocUniqueDropName(base, true, func(candidate string) (bool, error) {
|
|
err := os.Link(tmp, filepath.Join(dir, candidate))
|
|
if errors.Is(err, os.ErrExist) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
})
|
|
}
|