551 lines
17 KiB
Go
551 lines
17 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/installer"
|
|
)
|
|
|
|
type memClipboard struct {
|
|
mu sync.Mutex
|
|
kind ClipKind
|
|
data []byte
|
|
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.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}, nil
|
|
}
|
|
|
|
func (m *memClipboard) WritePNG(b []byte) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.kind = ClipPNG
|
|
m.data = append([]byte(nil), b...)
|
|
m.seq++
|
|
return nil
|
|
}
|
|
|
|
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 TestServerAuthClipboardAndSharedFiles(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
vmDir := filepath.Join(tmp, "vm")
|
|
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. Config & Status endpoints (prevent-sleep + mount mode).
|
|
srv.SetPreventSleep("macos-tahoe", true)
|
|
r = doReq("GET", "/v1/config", "", nil)
|
|
var cfgResp struct {
|
|
PreventSleep bool `json:"prevent_sleep"`
|
|
WebDAVPath string `json:"webdav_path"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&cfgResp)
|
|
r.Body.Close()
|
|
if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" {
|
|
t.Fatalf("unexpected /v1/config: %+v", cfgResp)
|
|
}
|
|
r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":2}`))
|
|
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 != 2 {
|
|
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()}
|
|
srv.RegisterVM(cfg)
|
|
if _, err := srv.getOrCreateDAVHandler(cfg.VMName, cfg.SharedDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv.mu.Lock()
|
|
srv.davHandlers[cfg.VMName+"/drives/C"] = srv.davHandlers[cfg.VMName]
|
|
srv.davRoots[cfg.VMName+"/drives/C"] = `C:\`
|
|
srv.mu.Unlock()
|
|
|
|
srv.UnregisterVM(cfg.VMName)
|
|
srv.mu.RLock()
|
|
defer srv.mu.RUnlock()
|
|
if len(srv.vms) != 0 || len(srv.davHandlers) != 0 || len(srv.davRoots) != 0 {
|
|
t.Fatalf("VM state remains: vms=%d davHandlers=%d davRoots=%d", len(srv.vms), len(srv.davHandlers), len(srv.davRoots))
|
|
}
|
|
}
|
|
|
|
func TestServerWebDAVAuthAndOperations(t *testing.T) {
|
|
tmp := t.TempDir()
|
|
vmDir := filepath.Join(tmp, "vm")
|
|
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()
|
|
imgPath := filepath.Join(tmp, "reims-tools.img")
|
|
cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true}
|
|
if err := BuildToolsDiskImage(imgPath, cfg); err != nil {
|
|
t.Fatalf("BuildToolsDiskImage: %v", err)
|
|
}
|
|
f, err := os.Open(imgPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer f.Close()
|
|
for _, name := range []string{
|
|
"config",
|
|
"guest-tools.sh",
|
|
"Install-Reims-Tools.command",
|
|
"Uninstall-Reims-Tools.command",
|
|
"Apply-Prevent-Sleep-pmset.command",
|
|
} {
|
|
if _, sz, err := installer.FindFileInHFSPlusImage(f, name); err != nil || sz == 0 {
|
|
t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", name, err, sz)
|
|
}
|
|
}
|
|
|
|
// Syntax check every generated POSIX script if sh is available.
|
|
shBin, err := exec.LookPath("sh")
|
|
if err != nil {
|
|
for _, cand := range []string{`C:\Program Files\Git\bin\sh.exe`, `D:\DevTools\msys64\usr\bin\sh.exe`} {
|
|
if _, serr := os.Stat(cand); serr == nil {
|
|
shBin = cand
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if shBin == "" {
|
|
return
|
|
}
|
|
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(),
|
|
} {
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
|
|
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())
|
|
|
|
cfg, err := LoadOrCreateVMConfig(filepath.Join(tmp, "vm"), "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")
|
|
}
|
|
}
|