Files
Reims-Go/plugins/usb-redir/host.go
T

289 lines
8.0 KiB
Go

//go:build windows
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/pelletier/go-toml/v2"
"golang.org/x/sys/windows"
)
const reimsDriver = "builtin.driver.reims-macos"
type vmEntry struct {
ID string `json:"vm"`
Name string `json:"name"`
Driver string `json:"driver_id"`
State string `json:"state"`
}
func (p *plugin) listVMs(ctx context.Context, root string) ([]vmEntry, error) {
var reply struct {
VMs []vmEntry `json:"vms"`
}
if err := p.host.CallHost(ctx, "host/vm.list", struct{}{}, &reply); err != nil {
if strings.Contains(err.Error(), "method not found: host/vm.list") {
return listRegisteredVMs(root)
}
return nil, err
}
vms := make([]vmEntry, 0, len(reply.VMs))
for _, vm := range reply.VMs {
if vm.Driver == reimsDriver && vm.ID != "" && vm.Name != "" {
vms = append(vms, vm)
}
}
return vms, nil
}
func (p *plugin) resolveVM(ctx context.Context, root, id string) (vmEntry, string, string, error) {
vms, err := p.listVMs(ctx, root)
if err != nil {
return vmEntry{}, "", "", err
}
for _, vm := range vms {
if vm.ID != id || vm.State != "running" {
continue
}
dir, err := registeredVMDir(root, vm.Name)
if err != nil {
return vmEntry{}, "", "", errors.New(p.text("Could not locate the running VM's monitor.",
"无法定位这台运行中虚拟机的控制接口。"))
}
return vm, dir, qmp.SocketPathForVM(dir, vm.Name, filepath.Join(root, "tmp")), nil
}
return vmEntry{}, "", "", errors.New(p.text("Choose a running Reims virtual machine.", "选择一台运行中的 Reims 虚拟机。"))
}
type registeredVM struct {
Name string `toml:"name"`
Dir string `toml:"dir"`
}
func readRegistry(root string) ([]registeredVM, error) {
var registry struct {
VMs []registeredVM `toml:"vm"`
}
raw, err := os.ReadFile(filepath.Join(root, "config", "reims-ctl", "vms.toml"))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
if err := toml.Unmarshal(raw, &registry); err != nil {
return nil, err
}
return registry.VMs, nil
}
func listRegisteredVMs(root string) ([]vmEntry, error) {
registered, err := readRegistry(root)
if err != nil {
return nil, err
}
vms := make([]vmEntry, 0, len(registered))
for _, vm := range registered {
if vm.Name == "" || !filepath.IsAbs(vm.Dir) {
continue
}
state := "stopped"
if liveQEMU(vm.Dir) {
state = "running"
}
vms = append(vms, vmEntry{ID: "reims-ctl:" + vm.Name, Name: vm.Name, Driver: reimsDriver, State: state})
}
return vms, nil
}
func registeredVMDir(root, name string) (string, error) {
registered, err := readRegistry(root)
if err != nil {
return "", err
}
var dir string
for _, vm := range registered {
if vm.Name != name {
continue
}
if dir != "" || !filepath.IsAbs(vm.Dir) {
return "", errors.New("ambiguous or relative VM path")
}
dir = filepath.Clean(vm.Dir)
}
if dir == "" {
return "", errors.New("VM not registered")
}
raw, err := os.ReadFile(filepath.Join(dir, "qemu.pid"))
if err != nil {
return "", err
}
if pid, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 32); err != nil || pid == 0 {
return "", errors.New("VM has no valid QEMU PID")
}
return dir, nil
}
// CLI plugin managers do not inject the application's VM list handler.
// Verify the registered VM's PID on Windows before allowing a fallback row
// to be used for attach. A stale PID may have been assigned to another task.
func liveQEMU(dir string) bool {
pidFile := filepath.Join(dir, "qemu.pid")
raw, err := os.ReadFile(pidFile)
if err != nil {
return false
}
pid, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 32)
if err != nil || pid == 0 {
return false
}
info, err := os.Stat(pidFile)
if err != nil {
return false
}
proc, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(proc)
var exit uint32
if windows.GetExitCodeProcess(proc, &exit) != nil || exit != 259 {
return false
}
var created, exited, kernel, user windows.Filetime
if windows.GetProcessTimes(proc, &created, &exited, &kernel, &user) != nil ||
time.Unix(0, created.Nanoseconds()).After(info.ModTime().Add(time.Second)) {
return false
}
image := make([]uint16, 32768)
size := uint32(len(image))
if windows.QueryFullProcessImageName(proc, 0, &image[0], &size) != nil {
return false
}
return strings.EqualFold(filepath.Base(windows.UTF16ToString(image[:size])), "qemu-system-x86_64.exe")
}
type helperBundle struct {
Root, Python, PowerShell, Script, Relay, Driver string
}
func resolveBundle(path string) (helperBundle, error) {
path = strings.Trim(strings.TrimSpace(path), `"`)
volume := filepath.VolumeName(path)
if !filepath.IsAbs(path) || len(volume) != 2 || volume[1] != ':' || strings.Contains(path[len(volume):], ":") {
return helperBundle{}, errors.New("expected an absolute local path")
}
for _, root := range []string{filepath.Clean(path), filepath.Join(path, "Windows-USB")} {
b := helperBundle{
Root: root, Python: filepath.Join(root, "deps", "python", "python.exe"),
PowerShell: filepath.Join(root, "deps", "powershell", "pwsh.exe"),
Script: filepath.Join(root, "scripts", "attach.py"), Relay: filepath.Join(root, "scripts", "qmp-relay.exe"),
Driver: filepath.Join(root, "deps", "libusb-win32", "bin", "amd64"),
}
if !filesExist(filepath.Join(b.Driver, "libusb0.sys"), filepath.Join(b.Driver, "libusb0.dll")) {
b.Driver = filepath.Join(root, "deps", "libusb-win32")
}
if filesExist(b.Python, b.PowerShell, b.Script, b.Relay, filepath.Join(b.Driver, "libusb0.sys"),
filepath.Join(b.Driver, "libusb0.dll")) {
return b, nil
}
}
return helperBundle{}, errors.New("Windows USB helper bundle is incomplete")
}
func filesExist(paths ...string) bool {
for _, path := range paths {
if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() {
return false
}
}
return true
}
func (b helperBundle) env() []string {
return []string{"PATH=" + filepath.Dir(b.PowerShell) + string(os.PathListSeparator) + os.Getenv("PATH")}
}
type usbEntry struct {
Key string `json:"key"`
Name string `json:"name"`
VID string `json:"vid"`
PID string `json:"pid"`
Port int `json:"port"`
Eligible bool `json:"eligible"`
Reason string `json:"reason"`
}
type inventory struct {
root string
devices []usbEntry
running bool
failed bool
}
// Let the bounded Windows inventory outlive this RPC. PnP enumeration can
// take longer than the panel can hold an interactive command open.
func (p *plugin) startScan(tools helperBundle) {
scan := &inventory{root: tools.Root, running: true}
if p.scan != nil && p.scan.root == tools.Root {
if p.scan.running {
return
}
scan.devices = p.scan.devices
}
p.scan = scan
go func() {
devices, err := tools.list(context.Background())
p.mu.Lock()
defer p.mu.Unlock()
scan.running = false
scan.devices = devices
scan.failed = err != nil
}()
}
func (b helperBundle) list(ctx context.Context) ([]usbEntry, error) {
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, b.Python, "-B", b.Script, "--list-json")
cmd.Dir = b.Root
cmd.Env = append(os.Environ(), b.env()...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
bytes, readErr := io.ReadAll(io.LimitReader(stdout, 1024*1024+1))
if len(bytes) > 1024*1024 || readErr != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
return nil, errors.New("invalid USB inventory size")
}
if err := cmd.Wait(); err != nil {
return nil, err
}
var entries []usbEntry
if err := json.Unmarshal(bytes, &entries); err != nil {
return nil, fmt.Errorf("decode USB inventory: %w", err)
}
return entries, nil
}