* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
872 lines
29 KiB
Go
872 lines
29 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
)
|
|
|
|
type memClipboard struct {
|
|
mu sync.Mutex
|
|
kind ClipKind
|
|
data []byte
|
|
files []string
|
|
seq uint32
|
|
}
|
|
|
|
func (m *memClipboard) SequenceNumber() uint32 {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.seq
|
|
}
|
|
|
|
func (m *memClipboard) ReadText() (string, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.kind != ClipText && m.kind != "" {
|
|
return "", nil
|
|
}
|
|
return string(m.data), nil
|
|
}
|
|
|
|
func (m *memClipboard) WriteText(s string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.files = nil
|
|
m.kind = ClipText
|
|
m.data = []byte(s)
|
|
m.seq++
|
|
return nil
|
|
}
|
|
|
|
func (m *memClipboard) Read() (ClipPayload, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
cp := make([]byte, len(m.data))
|
|
copy(cp, m.data)
|
|
k := m.kind
|
|
if k == "" && len(cp) > 0 {
|
|
k = ClipText
|
|
}
|
|
return ClipPayload{Kind: k, Data: cp, Files: append([]string(nil), m.files...)}, nil
|
|
}
|
|
|
|
func (m *memClipboard) WritePNG(b []byte) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.files = nil
|
|
m.kind = ClipPNG
|
|
m.data = append([]byte(nil), b...)
|
|
m.seq++
|
|
return nil
|
|
}
|
|
|
|
func (m *memClipboard) WriteFiles(paths []string) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.kind = ClipFiles
|
|
m.data = nil
|
|
m.files = append([]string(nil), paths...)
|
|
m.seq++
|
|
}
|
|
|
|
func makeSamplePNG(t *testing.T, r, g, b uint8) []byte {
|
|
t.Helper()
|
|
img := image.NewNRGBA(image.Rect(0, 0, 4, 3))
|
|
for y := 0; y < 3; y++ {
|
|
for x := 0; x < 4; x++ {
|
|
img.SetNRGBA(x, y, color.NRGBA{R: r, G: g, B: b, A: 255})
|
|
}
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := png.Encode(&buf, img); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return buf.Bytes()
|
|
}
|
|
|
|
func TestDIBPNGRoundTrip(t *testing.T) {
|
|
origPNG := makeSamplePNG(t, 0x12, 0x34, 0x56)
|
|
dib, err := EncodePNGToDIB(origPNG)
|
|
if err != nil {
|
|
t.Fatalf("EncodePNGToDIB: %v", err)
|
|
}
|
|
roundPNG, err := DecodeDIBToPNG(dib)
|
|
if err != nil {
|
|
t.Fatalf("DecodeDIBToPNG: %v", err)
|
|
}
|
|
img, err := png.Decode(bytes.NewReader(roundPNG))
|
|
if err != nil {
|
|
t.Fatalf("png.Decode: %v", err)
|
|
}
|
|
got := color.NRGBAModel.Convert(img.At(2, 1)).(color.NRGBA)
|
|
if got.R != 0x12 || got.G != 0x34 || got.B != 0x56 || got.A != 255 {
|
|
t.Fatalf("pixel = %+v, want {18 52 86 255}", got)
|
|
}
|
|
}
|
|
|
|
func TestReadVMConfigStrictPreservesInvalidConfig(t *testing.T) {
|
|
vmDir := t.TempDir()
|
|
if _, configured, err := ReadVMConfigStrict(vmDir); configured || err != nil {
|
|
t.Fatalf("missing config: configured=%v err=%v", configured, err)
|
|
}
|
|
path := filepath.Join(vmDir, ConfigFileName)
|
|
for _, invalid := range []string{`{"token":`, `{"vm_name":"mac"}`} {
|
|
if err := os.WriteFile(path, []byte(invalid), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, configured, err := ReadVMConfigStrict(vmDir); configured || err == nil {
|
|
t.Fatalf("invalid config: configured=%v err=%v", configured, err)
|
|
}
|
|
if _, err := LoadOrCreateVMConfig(vmDir, "mac", "", 0); err == nil {
|
|
t.Fatal("initialization succeeded with invalid config")
|
|
}
|
|
if contents, err := os.ReadFile(path); err != nil || string(contents) != invalid {
|
|
t.Fatalf("invalid config was replaced: %q, %v", contents, err)
|
|
}
|
|
}
|
|
if err := os.Remove(path); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(path, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, configured, err := ReadVMConfigStrict(vmDir); configured || err == nil {
|
|
t.Fatalf("unreadable config: configured=%v err=%v", configured, err)
|
|
}
|
|
removed := filepath.Join(vmDir, "deleted")
|
|
if err := SaveVMConfig(removed, VMConfig{}); !os.IsNotExist(err) {
|
|
t.Fatalf("save into a deleted VM directory: %v", err)
|
|
}
|
|
if _, err := os.Stat(removed); !os.IsNotExist(err) {
|
|
t.Fatalf("deleted VM directory reappeared: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestServerAuthClipboardAndSharedFiles(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
vmDir := filepath.Join(tmp, "vm")
|
|
if err := os.Mkdir(vmDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sharedDir := filepath.Join(tmp, "shared")
|
|
clip := &memClipboard{kind: ClipText, data: []byte("hello from windows")}
|
|
|
|
srv := NewServer(clip)
|
|
port, err := srv.Start(-1)
|
|
if err != nil {
|
|
t.Fatalf("Start: %v", err)
|
|
}
|
|
defer srv.Close(context.Background())
|
|
|
|
cfg, err := LoadOrCreateVMConfig(vmDir, "macos-tahoe", sharedDir, port)
|
|
if err != nil {
|
|
t.Fatalf("LoadOrCreateVMConfig: %v", err)
|
|
}
|
|
srv.RegisterVM(cfg)
|
|
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
|
|
|
// 1. Rejects missing or wrong Bearer token.
|
|
resp, err := http.Get(base + "/v1/ping")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resp.Body.Close()
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("unauthenticated ping: got %d, want 401", resp.StatusCode)
|
|
}
|
|
|
|
doReq := func(method, reqPath string, contentType string, body io.Reader) *http.Response {
|
|
req, err := http.NewRequest(method, base+reqPath, body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
|
if contentType != "" {
|
|
req.Header.Set("Content-Type", contentType)
|
|
}
|
|
r, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// 2. Authenticated ping marks VM connected.
|
|
r := doReq("GET", "/v1/ping", "", nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusOK {
|
|
t.Fatalf("ping status=%d", r.StatusCode)
|
|
}
|
|
if !srv.IsConnected("macos-tahoe", 5*time.Second) {
|
|
t.Fatalf("expected VM to be marked connected after ping")
|
|
}
|
|
|
|
// 3. Clipboard text GET -> 200, then GET with since=<hash> -> 304, then POST updates host clipboard.
|
|
r = doReq("GET", "/v1/clipboard", "", nil)
|
|
b, _ := io.ReadAll(r.Body)
|
|
h := r.Header.Get("X-Clip-Hash")
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 || string(b) != "hello from windows" || h == "" {
|
|
t.Fatalf("clipboard GET: status=%d body=%q hash=%q", r.StatusCode, string(b), h)
|
|
}
|
|
r = doReq("GET", "/v1/clipboard?since="+h, "", nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusNotModified {
|
|
t.Fatalf("clipboard unchanged: status=%d, want 304", r.StatusCode)
|
|
}
|
|
r = doReq("POST", "/v1/clipboard", "text/plain; charset=utf-8", strings.NewReader("你好 macOS"))
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 {
|
|
t.Fatalf("clipboard POST: status=%d", r.StatusCode)
|
|
}
|
|
// Reject invalid non-UTF-8 (e.g. raw GBK bytes) instead of corrupting host clipboard.
|
|
r = doReq("POST", "/v1/clipboard", "text/plain; charset=utf-8", bytes.NewReader([]byte{0xB6, 0xE0, 0xBA, 0xCB}))
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("non-UTF-8 clipboard POST: got %d, want 400", r.StatusCode)
|
|
}
|
|
if got, _ := clip.ReadText(); got != "你好 macOS" {
|
|
t.Fatalf("host clipboard = %q, want %q", got, "你好 macOS")
|
|
}
|
|
|
|
// 4. Image (PNG) clipboard POST + GET with accept=image + long-poll immediate wake.
|
|
samplePNG := makeSamplePNG(t, 200, 100, 50)
|
|
r = doReq("POST", "/v1/clipboard", "image/png", bytes.NewReader(samplePNG))
|
|
pngHash := r.Header.Get("X-Clip-Hash")
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 || pngHash == "" {
|
|
t.Fatalf("PNG clipboard POST: status=%d hash=%q", r.StatusCode, pngHash)
|
|
}
|
|
r = doReq("GET", "/v1/clipboard?accept=image", "", nil)
|
|
gotPNG, _ := io.ReadAll(r.Body)
|
|
gotKind := r.Header.Get("X-Clip-Kind")
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 || gotKind != "png" || !bytes.Equal(gotPNG, samplePNG) {
|
|
t.Fatalf("PNG clipboard GET: status=%d kind=%q len=%d", r.StatusCode, gotKind, len(gotPNG))
|
|
}
|
|
|
|
// Long-poll wakes up immediately when host clipboard changes.
|
|
doneCh := make(chan string, 1)
|
|
go func() {
|
|
lr := doReq("GET", "/v1/clipboard?since="+pngHash+"&wait=5&accept=image", "", nil)
|
|
body, _ := io.ReadAll(lr.Body)
|
|
lr.Body.Close()
|
|
doneCh <- fmt.Sprintf("%d:%s", lr.StatusCode, string(body))
|
|
}()
|
|
time.Sleep(100 * time.Millisecond)
|
|
_ = clip.WriteText("woken immediately")
|
|
srv.NotifyClipboardChanged()
|
|
select {
|
|
case got := <-doneCh:
|
|
if got != "200:woken immediately" {
|
|
t.Fatalf("long-poll result = %q, want 200:woken immediately", got)
|
|
}
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatalf("long-poll timed out instead of waking on change")
|
|
}
|
|
|
|
// 5. A version 22 agent can keep using prevent-sleep and WebDAV after a host upgrade.
|
|
srv.SetPreventSleep("macos-tahoe", true)
|
|
r = doReq("GET", "/v1/config", "", nil)
|
|
var cfgResp struct {
|
|
PreventSleep bool `json:"prevent_sleep"`
|
|
WebDAVPath string `json:"webdav_path"`
|
|
KeymapEnabled bool `json:"keymap_carrier_enabled"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&cfgResp)
|
|
r.Body.Close()
|
|
if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" || cfgResp.KeymapEnabled {
|
|
t.Fatalf("unexpected /v1/config: %+v", cfgResp)
|
|
}
|
|
r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":22,"keymap_active":true}`))
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 {
|
|
t.Fatalf("/v1/status POST: status=%d", r.StatusCode)
|
|
}
|
|
st := srv.Status("macos-tahoe", 5*time.Second)
|
|
if !st.Connected || st.MountMode != "webdav" || !st.SleepActive || st.AgentVersion != 22 {
|
|
t.Fatalf("unexpected status: %+v", st)
|
|
}
|
|
|
|
// 6. Legacy shared files: reject path traversal, allow upload & download with UTF-8/spaces.
|
|
r = doReq("GET", "/v1/file?path="+url.QueryEscape("../secret.txt"), "", nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("traversal must be 400, got %d", r.StatusCode)
|
|
}
|
|
r = doReq("PUT", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt")+"&mtime=1700000100", "", bytes.NewBufferString("shared payload"))
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusOK {
|
|
t.Fatalf("file PUT status=%d", r.StatusCode)
|
|
}
|
|
r = doReq("GET", "/v1/files", "", nil)
|
|
listBytes, _ := io.ReadAll(r.Body)
|
|
r.Body.Close()
|
|
if !strings.Contains(string(listBytes), "1700000100\t14\tnotes/测试 file.txt") {
|
|
t.Fatalf("unexpected /v1/files listing:\n%s", string(listBytes))
|
|
}
|
|
r = doReq("GET", "/v1/file?path="+url.QueryEscape("notes/测试 file.txt"), "", nil)
|
|
dlBytes, _ := io.ReadAll(r.Body)
|
|
r.Body.Close()
|
|
if r.StatusCode != 200 || string(dlBytes) != "shared payload" {
|
|
t.Fatalf("file GET: status=%d body=%q", r.StatusCode, string(dlBytes))
|
|
}
|
|
}
|
|
|
|
func TestUnregisterVMReleasesVMState(t *testing.T) {
|
|
srv := NewServer(&memClipboard{})
|
|
cfg := VMConfig{
|
|
VMName: "deleted-vm", Token: strings.Repeat("a", 64), SharedDir: t.TempDir(),
|
|
DriveSharingEnabled: true, SharedDrives: []string{"C"}, DriveRoots: map[string]string{"C": t.TempDir()},
|
|
}
|
|
srv.RegisterVM(cfg)
|
|
key := vmRegistryKey("", cfg.VMName)
|
|
for _, drive := range []string{"", "C"} {
|
|
if _, err := srv.getOrCreateDAVHandler(srv.vms[key], drive); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
srv.UnregisterVM(cfg.VMName)
|
|
srv.mu.RLock()
|
|
defer srv.mu.RUnlock()
|
|
if len(srv.vms) != 0 || len(srv.davCache) != 0 {
|
|
t.Fatalf("VM state remains: vms=%d davCache=%d", len(srv.vms), len(srv.davCache))
|
|
}
|
|
}
|
|
|
|
func TestRegisterVMCleansChangedDAVCacheEntries(t *testing.T) {
|
|
srv := NewServer(&memClipboard{})
|
|
cfg := VMConfig{
|
|
VMName: "mac", Token: "token", SharedDir: t.TempDir(), DriveSharingEnabled: true,
|
|
SharedDrives: []string{"C", "D"}, DriveRoots: map[string]string{"C": t.TempDir(), "D": t.TempDir()},
|
|
}
|
|
srv.RegisterVM(cfg)
|
|
r := httptest.NewRequest(http.MethodOptions, "/dav/mac/", nil)
|
|
r.Header.Set("Authorization", "Bearer token")
|
|
oldVM := srv.authenticate(r)
|
|
for _, drive := range []string{"", "C", "D"} {
|
|
if _, err := srv.getOrCreateDAVHandler(oldVM, drive); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
key := vmRegistryKey("", cfg.VMName)
|
|
oldC := srv.davCache[key+"/drives/C"]
|
|
cfg.SharedDir = t.TempDir()
|
|
cfg.SharedDrives = []string{"C"}
|
|
srv.RegisterVM(cfg)
|
|
if len(srv.davCache) != 1 || srv.davCache[key+"/drives/C"] != oldC || !oldC.readOnly {
|
|
t.Fatalf("cache after directory change and drive removal: %v", srv.davCache)
|
|
}
|
|
for _, drive := range []string{"", "D"} {
|
|
if _, err := srv.getOrCreateDAVHandler(oldVM, drive); err == nil {
|
|
t.Errorf("stale registration recreated cache for drive %q", drive)
|
|
}
|
|
}
|
|
if len(srv.davCache) != 1 {
|
|
t.Fatalf("stale registration changed cache: %v", srv.davCache)
|
|
}
|
|
cfg.DriveRoots["C"] = t.TempDir()
|
|
srv.RegisterVM(cfg)
|
|
if len(srv.davCache) != 0 {
|
|
t.Fatalf("cache after drive root replacement: %v", srv.davCache)
|
|
}
|
|
if _, err := srv.getOrCreateDAVHandler(srv.authenticate(r), "C"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg.DriveSharingEnabled = false
|
|
srv.RegisterVM(cfg)
|
|
if len(srv.davCache) != 0 {
|
|
t.Fatalf("cache after disabling drive sharing: %v", srv.davCache)
|
|
}
|
|
}
|
|
|
|
func TestServerWebDAVTransferBoundaries(t *testing.T) {
|
|
root, driveC, driveD := t.TempDir(), t.TempDir(), t.TempDir()
|
|
if err := os.Mkdir(filepath.Join(root, "a"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, file := range []string{filepath.Join(root, "a", "original.txt"), filepath.Join(driveC, "drive.txt")} {
|
|
if err := os.WriteFile(file, []byte("original"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
srv := NewServer(&memClipboard{})
|
|
srv.RegisterVM(VMConfig{
|
|
VMName: "mac", Token: "token", SharedDir: root, DriveSharingEnabled: true,
|
|
SharedDrives: []string{"C", "D"}, DriveRoots: map[string]string{"C": driveC, "D": driveD},
|
|
})
|
|
transfer := func(method, src, dst string, want int) {
|
|
t.Helper()
|
|
r := httptest.NewRequest(method, src, nil)
|
|
r.Header.Set("Authorization", "Bearer token")
|
|
r.Header.Set("Destination", dst)
|
|
w := httptest.NewRecorder()
|
|
srv.handleWebDAV(w, r)
|
|
if w.Code != want {
|
|
t.Errorf("%s %q to %q: status=%d, want %d", method, src, dst, w.Code, want)
|
|
}
|
|
}
|
|
for _, method := range []string{"COPY", "MOVE"} {
|
|
for _, dst := range []string{
|
|
"/dav/mac/drives/C/copied", "/dav/mac/drives/", "/dav/mac/tmp/../%64rives/C/copied",
|
|
"/dav/macos/copied", "/dav/mac/../other/copied", "http://example.com/dav/other/copied",
|
|
"/dav/mac/a/", "/dav/mac/%61", "/dav/mac/a/sub", "/dav/mac/tmp/../a/sub",
|
|
} {
|
|
transfer(method, "/dav/mac/a/", dst, http.StatusForbidden)
|
|
}
|
|
if runtime.GOOS == "windows" {
|
|
transfer(method, "/dav/mac/a", "/dav/mac/A/sub", http.StatusForbidden)
|
|
}
|
|
for _, dst := range []string{"/dav/mac/copied", "/dav/mac/drives/D/copied", "/dav/other/drives/C/copied"} {
|
|
transfer(method, "/dav/mac/drives/C/drive.txt", dst, http.StatusForbidden)
|
|
}
|
|
transfer(method, "/dav/mac/drives/C/drive.txt", "/dav/mac/drives/C/copied", http.StatusMethodNotAllowed)
|
|
}
|
|
for dir, count := range map[string]int{root: 1, filepath.Join(root, "a"): 1, driveC: 1, driveD: 0} {
|
|
if entries, err := os.ReadDir(dir); err != nil || len(entries) != count {
|
|
t.Errorf("unexpected contents in %q: %v, %v", dir, entries, err)
|
|
}
|
|
}
|
|
transfer("COPY", "/dav/mac/a/", "http://example.com/dav/mac/ab/", http.StatusCreated)
|
|
transfer("MOVE", "/dav/mac/ab/", "/dav/mac/renamed/", http.StatusCreated)
|
|
for _, dir := range []string{"a", "renamed"} {
|
|
if data, err := os.ReadFile(filepath.Join(root, dir, "original.txt")); err != nil || string(data) != "original" {
|
|
t.Errorf("content of %q: %q, %v", dir, data, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDefaultWebDAVPreflightsOverwrite(t *testing.T) {
|
|
root := t.TempDir()
|
|
dir := filepath.Join(root, "parent")
|
|
if err := os.Mkdir(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
file := filepath.Join(dir, "source.txt")
|
|
if err := os.WriteFile(file, []byte("original"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := NewServer(&memClipboard{})
|
|
srv.RegisterVM(VMConfig{VMName: "mac", Token: "token", SharedDir: root})
|
|
for _, tc := range []struct {
|
|
method, src, dst string
|
|
status int
|
|
}{
|
|
{"MOVE", "missing.txt", "parent/source.txt", http.StatusNotFound},
|
|
{"COPY", "missing.txt", "parent/source.txt", http.StatusNotFound},
|
|
{"MOVE", "parent/source.txt", "parent", http.StatusForbidden},
|
|
{"COPY", "parent/source.txt", "parent", http.StatusForbidden},
|
|
{"MOVE", "parent/source.txt", "parent/../parent", http.StatusForbidden},
|
|
} {
|
|
req := httptest.NewRequest(tc.method, "/dav/mac/"+tc.src, nil)
|
|
req.Header.Set("Authorization", "Bearer token")
|
|
req.Header.Set("Destination", "/dav/mac/"+tc.dst)
|
|
req.Header.Set("Overwrite", "T")
|
|
w := httptest.NewRecorder()
|
|
srv.handleWebDAV(w, req)
|
|
if w.Code != tc.status {
|
|
t.Errorf("%s %s to %s: status=%d, want %d", tc.method, tc.src, tc.dst, w.Code, tc.status)
|
|
}
|
|
if data, err := os.ReadFile(file); err != nil || string(data) != "original" {
|
|
t.Fatalf("%s %s to %s changed existing file: %q, %v", tc.method, tc.src, tc.dst, data, err)
|
|
}
|
|
}
|
|
if runtime.GOOS == "windows" {
|
|
fs, err := newRootWebDAVFS(configureSharedRoot(root), false, true, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !errors.Is(fs.checkTransfer("parent/source.txt", "PARENT"), os.ErrPermission) {
|
|
t.Error("ancestor identity did not recognize a differently cased path")
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDefaultWebDAVPropfindDepth(t *testing.T) {
|
|
root := t.TempDir()
|
|
if err := os.Mkdir(filepath.Join(root, "child"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(root, "child", "grandchild.txt"), nil, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := NewServer(&memClipboard{})
|
|
srv.RegisterVM(VMConfig{VMName: "mac", Token: "token", SharedDir: root})
|
|
for _, tc := range []struct {
|
|
depth string
|
|
status int
|
|
wantChild bool
|
|
}{
|
|
{"", http.StatusMultiStatus, true},
|
|
{"0", http.StatusMultiStatus, false},
|
|
{"1", http.StatusMultiStatus, true},
|
|
{"infinity", http.StatusBadRequest, false},
|
|
{"2", http.StatusBadRequest, false},
|
|
} {
|
|
r := httptest.NewRequest("PROPFIND", "/dav/mac/", nil)
|
|
r.Header.Set("Authorization", "Bearer token")
|
|
if tc.depth != "" {
|
|
r.Header.Set("Depth", tc.depth)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
srv.handleWebDAV(w, r)
|
|
body := w.Body.String()
|
|
if w.Code != tc.status || strings.Contains(body, "/child/") != tc.wantChild || strings.Contains(body, "grandchild.txt") {
|
|
t.Errorf("Depth %q: status=%d, body=%s", tc.depth, w.Code, body)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestServerWebDAVAuthAndOperations(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
vmDir := filepath.Join(tmp, "vm")
|
|
if err := os.Mkdir(vmDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sharedDir := filepath.Join(tmp, "shared")
|
|
srv := NewServer(&memClipboard{})
|
|
port, err := srv.Start(-1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer srv.Close(context.Background())
|
|
|
|
cfg, err := LoadOrCreateVMConfig(vmDir, "dev-mac", sharedDir, port)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv.RegisterVM(cfg)
|
|
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
|
|
|
doDAV := func(method, reqPath string, auth bool, body io.Reader) *http.Response {
|
|
req, err := http.NewRequest(method, base+reqPath, body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if auth {
|
|
req.SetBasicAuth("reims", cfg.Token)
|
|
}
|
|
if method == "PROPFIND" {
|
|
req.Header.Set("Depth", "1")
|
|
}
|
|
r, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// Unauthenticated request gets 401 with Basic challenge.
|
|
r := doDAV("PROPFIND", "/dav/dev-mac/", false, nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusUnauthorized || !strings.Contains(r.Header.Get("WWW-Authenticate"), "Basic") {
|
|
t.Fatalf("unauth WebDAV: status=%d www-auth=%q", r.StatusCode, r.Header.Get("WWW-Authenticate"))
|
|
}
|
|
|
|
// Cross-VM path is forbidden even with valid token.
|
|
r = doDAV("PROPFIND", "/dav/other-vm/", true, nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusForbidden {
|
|
t.Fatalf("cross-VM WebDAV: status=%d, want 403", r.StatusCode)
|
|
}
|
|
|
|
// PUT -> GET -> PROPFIND -> DELETE over WebDAV Basic auth.
|
|
r = doDAV("PUT", "/dav/dev-mac/hello.txt", true, strings.NewReader("webdav live data"))
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusCreated && r.StatusCode != http.StatusOK && r.StatusCode != http.StatusNoContent {
|
|
t.Fatalf("WebDAV PUT status=%d", r.StatusCode)
|
|
}
|
|
if diskBytes, err := os.ReadFile(filepath.Join(sharedDir, "hello.txt")); err != nil || string(diskBytes) != "webdav live data" {
|
|
t.Fatalf("host shared file mismatch: err=%v body=%q", err, string(diskBytes))
|
|
}
|
|
r = doDAV("PROPFIND", "/dav/dev-mac/", true, nil)
|
|
propBody, _ := io.ReadAll(r.Body)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusMultiStatus || !strings.Contains(string(propBody), "hello.txt") {
|
|
t.Fatalf("WebDAV PROPFIND: status=%d body=%s", r.StatusCode, string(propBody))
|
|
}
|
|
r = doDAV("DELETE", "/dav/dev-mac/hello.txt", true, nil)
|
|
r.Body.Close()
|
|
if r.StatusCode != http.StatusNoContent && r.StatusCode != http.StatusOK {
|
|
t.Fatalf("WebDAV DELETE status=%d", r.StatusCode)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(sharedDir, "hello.txt")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected file to be deleted on host")
|
|
}
|
|
}
|
|
|
|
func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true, GuestTimezone: "Etc/GMT+8"}
|
|
diskFiles := map[string][]byte{}
|
|
for _, tf := range ToolsDiskFiles(cfg) {
|
|
rc, err := tf.Open()
|
|
if err != nil {
|
|
t.Fatalf("open %s: %v", tf.Name, err)
|
|
}
|
|
data, err := io.ReadAll(rc)
|
|
_ = rc.Close()
|
|
if err != nil {
|
|
t.Fatalf("read %s: %v", tf.Name, err)
|
|
}
|
|
if int64(len(data)) != tf.Size {
|
|
t.Fatalf("%s size mismatch: got %d, declared %d", tf.Name, len(data), tf.Size)
|
|
}
|
|
diskFiles[tf.Name] = data
|
|
}
|
|
for _, file := range []struct{ name, content string }{
|
|
{"config", "REIMS_VM='macos-tahoe'\n"},
|
|
{"guest-tools.sh", fmt.Sprintf(`\"agent_version\":%d,`, CurrentAgentVersion)},
|
|
{"Install-Reims-Tools.command", "Apply-Timezone.command"},
|
|
{"Uninstall-Reims-Tools.command", guestTimezoneSudoers},
|
|
{"Apply-Prevent-Sleep-pmset.command", ""},
|
|
{"set-timezone.sh", guestTimezoneHelper},
|
|
{"Apply-Timezone.command", guestApplyTimezone},
|
|
} {
|
|
data, ok := diskFiles[file.name]
|
|
if !ok || len(data) == 0 {
|
|
t.Fatalf("missing %s in REIMSTOOLS files", file.name)
|
|
}
|
|
if !strings.Contains(string(data), file.content) {
|
|
t.Errorf("unexpected %s contents", file.name)
|
|
}
|
|
if file.name == "config" && strings.Contains(string(data), "REIMS_TIMEZONE=") {
|
|
t.Error("tools image config contains a build-time timezone")
|
|
}
|
|
}
|
|
for name, script := range map[string][]byte{
|
|
"dns-proxy.pl": guestDNSProxy,
|
|
"Apply-Host-DNS.command": guestApplyHostDNS,
|
|
"Disable-Host-DNS.command": guestDisableHostDNS,
|
|
"active-window-reporter.js": guestWindowReporter,
|
|
} {
|
|
got, ok := diskFiles[name]
|
|
if !ok {
|
|
t.Fatalf("missing %s in REIMSTOOLS files", name)
|
|
}
|
|
if !bytes.Equal(got, bytes.ReplaceAll(script, []byte("\r\n"), []byte("\n"))) {
|
|
t.Fatalf("unexpected content in %s on REIMSTOOLS", name)
|
|
}
|
|
}
|
|
|
|
// Syntax check every generated POSIX script if sh is available.
|
|
shBin, err := exec.LookPath("sh")
|
|
if runtime.GOOS == "windows" {
|
|
const gitSH = "C:/Program Files/Git/bin/sh.exe"
|
|
if _, statErr := os.Stat(gitSH); statErr == nil {
|
|
shBin, err = gitSH, nil
|
|
}
|
|
}
|
|
if err != nil {
|
|
const msysSH = `D:\DevTools\msys64\usr\bin\sh.exe`
|
|
if _, statErr := os.Stat(msysSH); statErr == nil {
|
|
shBin = msysSH
|
|
}
|
|
}
|
|
if shBin == "" {
|
|
return
|
|
}
|
|
lockShellFixture(t)
|
|
_, rootScript, _ := strings.Cut(guestApplyTimezone, "<<'ROOT'\n")
|
|
rootScript, _, _ = strings.Cut(rootScript, "\nROOT\n")
|
|
for name, content := range map[string][]byte{
|
|
"guest-tools.sh": GuestAgentScript(),
|
|
"Install-Reims-Tools.command": GuestInstallScript(),
|
|
"Uninstall-Reims-Tools.command": GuestUninstallScript(),
|
|
"Apply-Prevent-Sleep-pmset.command": GuestPmsetScript(),
|
|
"Apply-Host-DNS.command": guestApplyHostDNS,
|
|
"Disable-Host-DNS.command": guestDisableHostDNS,
|
|
"set-timezone.sh": []byte(guestTimezoneHelper),
|
|
"Apply-Timezone.command": []byte(guestApplyTimezone),
|
|
"apply-timezone-root.sh": []byte(rootScript),
|
|
} {
|
|
p := filepath.Join(tmp, name)
|
|
if err := os.WriteFile(p, content, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if out, err := exec.Command(shBin, "-n", p).CombinedOutput(); err != nil {
|
|
t.Fatalf("sh -n %s failed: %v\n%s", name, err, out)
|
|
}
|
|
}
|
|
for _, tc := range []struct {
|
|
tz string
|
|
valid bool
|
|
}{
|
|
{"UTC", true}, {"Asia/Shanghai", true}, {"America/Argentina/Buenos_Aires", true}, {"Etc/GMT+8", true},
|
|
{"", false}, {"../UTC", false}, {"-UTC", false}, {"/UTC", false}, {"UTC/", false}, {"a/b/c/d", false},
|
|
{"America/New York", false}, {"UTC\nUTC", false}, {"UTC;date", false}, {strings.Repeat("A", 65), false},
|
|
} {
|
|
cmd := exec.Command(shBin, "-s")
|
|
cmd.Stdin = strings.NewReader(guestTimezoneValidation + "valid_timezone \"$REIMS_TEST_TIMEZONE\"\n")
|
|
cmd.Env = append(os.Environ(), "REIMS_TEST_TIMEZONE="+tc.tz)
|
|
if out, err := cmd.CombinedOutput(); (err == nil) != tc.valid {
|
|
t.Errorf("shell validation for %q = %v, want %v: %s", tc.tz, err == nil, tc.valid, out)
|
|
}
|
|
}
|
|
for _, tc := range []struct {
|
|
config, want string
|
|
present bool
|
|
}{
|
|
{`{"timezone":"America/Argentina/Buenos_Aires","vm":"mac"}`, "America/Argentina/Buenos_Aires", true},
|
|
{`{"timezone":"","vm":"mac"}`, "", true},
|
|
{`{"vm":"\"timezone\":\"UTC\""}`, "", false},
|
|
} {
|
|
cmd := exec.Command(shBin, "-s")
|
|
cmd.Stdin = strings.NewReader(guestTimezoneConfig + "config_timezone \"$REIMS_TEST_CONFIG\"\n")
|
|
cmd.Env = append(os.Environ(), "REIMS_TEST_CONFIG="+tc.config)
|
|
if out, err := cmd.CombinedOutput(); (err == nil) != tc.present || strings.TrimSpace(string(out)) != tc.want {
|
|
t.Errorf("shell timezone from %s = %q, %v, want %q", tc.config, out, err, tc.want)
|
|
}
|
|
}
|
|
testTimezoneScripts(t, shBin, rootScript)
|
|
}
|
|
|
|
func TestTextInputV3HandshakeAndV2Fallback(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
srv := NewServer(&memClipboard{kind: ClipText, data: []byte("host-clip")})
|
|
port, err := srv.Start(-1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer srv.Close(context.Background())
|
|
|
|
vmDir := filepath.Join(tmp, "vm")
|
|
if err := os.Mkdir(vmDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg, err := LoadOrCreateVMConfig(vmDir, "mac", filepath.Join(tmp, "share"), port)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv.RegisterVM(cfg)
|
|
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
|
|
|
// Disconnected VM returns ErrGuestToolsNotConnected.
|
|
if _, err := srv.InjectText(context.Background(), "mac", "你好", nil); err != ErrGuestToolsNotConnected {
|
|
t.Fatalf("disconnected InjectText err = %v, want ErrGuestToolsNotConnected", err)
|
|
}
|
|
|
|
// Simulate Guest Tools v2 (only polls /v1/clipboard, never /v1/text-input).
|
|
v2Done := make(chan string, 1)
|
|
go func() {
|
|
req, _ := http.NewRequest("GET", base+"/v1/clipboard?since="+textHash("host-clip")+"&wait=5", nil)
|
|
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
b, _ := io.ReadAll(resp.Body)
|
|
v2Done <- string(b)
|
|
}()
|
|
// Wait briefly until v2 long-poll authenticates and marks lastSeen.
|
|
deadline := time.Now().Add(2 * time.Second)
|
|
for !srv.IsConnected("mac", 5*time.Second) && time.Now().Before(deadline) {
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
pastedV2 := false
|
|
mode, err := srv.InjectText(context.Background(), "mac", "远程中文v2", func(context.Context) error {
|
|
pastedV2 = true
|
|
return nil
|
|
})
|
|
if err != nil || mode != "v2" || !pastedV2 {
|
|
t.Fatalf("v2 fallback: mode=%q pasted=%v err=%v", mode, pastedV2, err)
|
|
}
|
|
if got := <-v2Done; got != "远程中文v2" {
|
|
t.Fatalf("v2 guest received %q, want 远程中文v2", got)
|
|
}
|
|
|
|
// Simulate Guest Tools v3 worker on /v1/text-input + /v1/text-input/ack.
|
|
var order []string
|
|
var orderMu sync.Mutex
|
|
record := func(step string) {
|
|
orderMu.Lock()
|
|
order = append(order, step)
|
|
orderMu.Unlock()
|
|
}
|
|
v3Err := make(chan error, 1)
|
|
go func() {
|
|
req, _ := http.NewRequest("GET", base+"/v1/text-input?wait=5", nil)
|
|
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
v3Err <- err
|
|
return
|
|
}
|
|
body, _ := io.ReadAll(resp.Body)
|
|
resp.Body.Close()
|
|
id := resp.Header.Get("X-Input-Id")
|
|
if string(body) != "你好世界🎉" || id == "" {
|
|
v3Err <- fmt.Errorf("unexpected v3 payload=%q id=%q", string(body), id)
|
|
return
|
|
}
|
|
record("guest-pbcopy")
|
|
ackReq, _ := http.NewRequest("POST", base+"/v1/text-input/ack?id="+id, nil)
|
|
ackReq.Header.Set("Authorization", "Bearer "+cfg.Token)
|
|
ackResp, err := http.DefaultClient.Do(ackReq)
|
|
if err != nil {
|
|
v3Err <- err
|
|
return
|
|
}
|
|
ackResp.Body.Close()
|
|
record("guest-restore")
|
|
v3Err <- nil
|
|
}()
|
|
time.Sleep(40 * time.Millisecond)
|
|
mode, err = srv.InjectText(context.Background(), "mac", "你好世界🎉", func(context.Context) error {
|
|
record("host-cmd-v")
|
|
return nil
|
|
})
|
|
if err != nil || mode != "v3" {
|
|
t.Fatalf("v3 InjectText: mode=%q err=%v", mode, err)
|
|
}
|
|
if err := <-v3Err; err != nil {
|
|
t.Fatalf("v3 guest worker: %v", err)
|
|
}
|
|
wantOrder := "guest-pbcopy,host-cmd-v,guest-restore"
|
|
if got := strings.Join(order, ","); got != wantOrder {
|
|
t.Fatalf("handshake order = %s, want %s", got, wantOrder)
|
|
}
|
|
|
|
// Test POST /v1/host-text callback.
|
|
hostTextCh := make(chan string, 1)
|
|
srv.SetHostTextHandler(func(_, vmName, text string) {
|
|
hostTextCh <- vmName + ":" + text
|
|
})
|
|
req, _ := http.NewRequest("POST", base+"/v1/host-text", strings.NewReader("语音输入测试"))
|
|
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil || resp.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("host-text: status=%v err=%v", resp, err)
|
|
}
|
|
resp.Body.Close()
|
|
select {
|
|
case got := <-hostTextCh:
|
|
if got != "mac:语音输入测试" {
|
|
t.Fatalf("host-text callback got %q", got)
|
|
}
|
|
case <-time.After(time.Second):
|
|
t.Fatal("host-text callback not called")
|
|
}
|
|
}
|