194 lines
5.6 KiB
Go
194 lines
5.6 KiB
Go
//go:build windows
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/atomicfile"
|
|
)
|
|
|
|
const (
|
|
activeFile = "session.json"
|
|
stateFile = "state.json"
|
|
cancelFile = "cancel.request"
|
|
)
|
|
|
|
type sessionRecord struct {
|
|
Dir string `json:"dir"`
|
|
VM vmEntry `json:"vm"`
|
|
Device usbEntry `json:"device"`
|
|
PID int `json:"pid"`
|
|
Started time.Time `json:"started"`
|
|
}
|
|
|
|
type helperState struct {
|
|
Phase string `json:"phase"`
|
|
Message string `json:"message"`
|
|
PID int `json:"pid"`
|
|
DescriptorRead bool `json:"descriptor_read"`
|
|
}
|
|
|
|
type sessionUI struct {
|
|
VM vmEntry `json:"vm"`
|
|
Device usbEntry `json:"device"`
|
|
Active bool `json:"active"`
|
|
CancelRequested bool `json:"cancel_requested"`
|
|
helperState
|
|
record sessionRecord
|
|
}
|
|
|
|
func readJSON(path string, out any) error {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
const limit = 256 * 1024
|
|
raw, err := io.ReadAll(io.LimitReader(f, limit+1))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(raw) > limit {
|
|
return errors.New("USB plugin state file is too large")
|
|
}
|
|
return json.Unmarshal(raw, out)
|
|
}
|
|
|
|
func sessionDir(data, name string) (string, error) {
|
|
if filepath.Base(name) != name || !strings.HasPrefix(name, "usb-session-") || strings.ContainsAny(name, ":\\/") {
|
|
return "", errors.New("invalid USB session folder")
|
|
}
|
|
return filepath.Join(data, name), nil
|
|
}
|
|
|
|
func requestRelease(data, name string) error {
|
|
dir, err := sessionDir(data, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
file, err := os.OpenFile(filepath.Join(dir, cancelFile), os.O_CREATE|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return file.Close()
|
|
}
|
|
|
|
func terminal(phase string) bool {
|
|
return phase == "released" || phase == "error"
|
|
}
|
|
|
|
func (p *plugin) sessionStatus(ctx context.Context, data string) (*sessionUI, error) {
|
|
var saved sessionRecord
|
|
if err := readJSON(filepath.Join(data, activeFile), &saved); err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
dir, err := sessionDir(data, saved.Dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result := &sessionUI{VM: saved.VM, Device: saved.Device, record: saved}
|
|
if err := readJSON(filepath.Join(dir, stateFile), &result.helperState); err != nil {
|
|
if !errors.Is(err, os.ErrNotExist) {
|
|
return nil, err
|
|
}
|
|
result.Phase = "starting"
|
|
}
|
|
_, markerErr := os.Stat(filepath.Join(dir, cancelFile))
|
|
result.CancelRequested = markerErr == nil
|
|
pid := saved.PID
|
|
if pid == 0 {
|
|
pid = result.PID
|
|
}
|
|
if pid > 0 {
|
|
running, err := p.host.IsVMProcessRunning(ctx, pid)
|
|
result.Active = running || err != nil
|
|
} else {
|
|
// A process launch and its PID receipt are separate operations. The
|
|
// state file can identify a helper that starts across a sidecar restart.
|
|
result.Active = !terminal(result.Phase) && time.Since(saved.Started) < 30*time.Second
|
|
}
|
|
if !result.Active && !terminal(result.Phase) {
|
|
result.Phase = "error"
|
|
result.Message = p.text("The helper stopped before reporting a release. Check Windows driver recovery.",
|
|
"助手退出前未报告释放结果,检查 Windows 驱动恢复状态。")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (p *plugin) attach(ctx context.Context, root, data string, tools helperBundle, args commandArgs,
|
|
previous *sessionUI) (*sessionUI, error) {
|
|
vm, vmDir, monitor, err := p.resolveVM(ctx, root, args.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if p.scan == nil || p.scan.root != tools.Root || p.scan.failed {
|
|
return nil, errors.New(p.text("Refresh the Windows USB device list and try again.", "刷新 Windows USB 设备列表后重试。"))
|
|
}
|
|
var device usbEntry
|
|
for _, item := range p.scan.devices {
|
|
if item.Key != args.Key || item.Key == "" || !item.Eligible {
|
|
continue
|
|
}
|
|
if device.Key != "" {
|
|
return nil, errors.New(p.text("USB device selection is ambiguous.", "无法唯一确定所选 USB 设备。"))
|
|
}
|
|
device = item
|
|
}
|
|
if device.Key == "" {
|
|
return nil, errors.New(p.text("The selected USB device is unavailable.", "所选 USB 设备已不可用。"))
|
|
}
|
|
dir, err := os.MkdirTemp(data, "usb-session-")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
saved := sessionRecord{Dir: filepath.Base(dir), VM: vm, Device: device, Started: time.Now()}
|
|
receipt := filepath.Join(data, activeFile)
|
|
if err := atomicfile.WriteJSON(receipt, saved, 0o600); err != nil {
|
|
_ = os.Remove(dir)
|
|
return nil, err
|
|
}
|
|
argv := []string{"-B", tools.Script, "--vm-dir", vmDir, "--qmp", monitor, "--relay", tools.Relay,
|
|
"--driver-dir", tools.Driver, "--device=" + device.Key, "--session-dir", dir}
|
|
pid, err := p.host.SpawnVMProcess(ctx, saved.Dir, tools.Python, argv, tools.Root, tools.env())
|
|
if err != nil || pid <= 0 {
|
|
// Cancel by file in case the launch succeeded but its reply was lost.
|
|
// Keep the record available to the panel while the helper settles.
|
|
return nil, errors.Join(fmt.Errorf("%s", p.text("Could not start the Windows USB helper.", "无法启动 Windows USB 助手。")),
|
|
requestRelease(data, saved.Dir))
|
|
}
|
|
saved.PID = pid
|
|
if err := atomicfile.WriteJSON(receipt, saved, 0o600); err != nil {
|
|
return nil, errors.Join(err, requestRelease(data, saved.Dir))
|
|
}
|
|
if previous != nil {
|
|
removeFinishedSession(data, previous.record.Dir)
|
|
}
|
|
return &sessionUI{VM: vm, Device: device, Active: true,
|
|
helperState: helperState{Phase: "starting", PID: pid}, record: saved}, nil
|
|
}
|
|
|
|
func removeFinishedSession(data, name string) {
|
|
dir, err := sessionDir(data, name)
|
|
if err != nil {
|
|
return
|
|
}
|
|
for _, file := range []string{stateFile, cancelFile} {
|
|
_ = os.Remove(filepath.Join(dir, file))
|
|
}
|
|
_ = os.Remove(dir)
|
|
}
|