fix(runtime): keep QEMU ASLR in sync across runtime and data folder changes
This commit is contained in:
1 parent
7049f3e388
commit
a8b7894208
35 files changed
+1021
-186
No files matched your search
@@ -459,6 +459,17 @@ export const App: React.FC = () => {
|
||||
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const pushToast = toasts.push
|
||||
useEffect(() => events.onRuntimeWarning((message) => {
|
||||
const { summary, code, rawDetail } = parseAppError(message)
|
||||
pushToast({
|
||||
kind: 'warning',
|
||||
title: summary,
|
||||
errorCode: code,
|
||||
rawDetail,
|
||||
detailsLabel: t(locale, 'errRawDetailsToggle'),
|
||||
copyDetailsLabel: t(locale, 'errCopyDetails'),
|
||||
})
|
||||
}), [locale, pushToast])
|
||||
useEffect(() => events.onHostDrop(({ delivered, mode }) => {
|
||||
if (mode !== 'l1_share' || delivered.length === 0) return
|
||||
const title = delivered.length === 1
|
||||
|
||||
@@ -1007,6 +1007,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
|
||||
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
|
||||
.toast.ok .toast-main-row > svg { color: var(--status-running); }
|
||||
.toast.warning .toast-main-row > svg { color: var(--status-busy); }
|
||||
.toast.error .toast-main-row > svg { color: var(--status-error); }
|
||||
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
|
||||
.toast-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import * as RToast from '@radix-ui/react-toast'
|
||||
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import { AlertTriangle, Check, CircleCheck, CircleX, X } from 'lucide-react'
|
||||
import { HostIcon } from './themeVisuals'
|
||||
import { emitThemeEvent } from '../lib/themeEngine'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import { IconButton } from './controls'
|
||||
|
||||
export interface ToastInput {
|
||||
kind: 'ok' | 'error'
|
||||
kind: 'ok' | 'warning' | 'error'
|
||||
title: string
|
||||
description?: string
|
||||
errorCode?: string
|
||||
@@ -63,7 +63,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
<RToast.Root
|
||||
className={`toast rg-p-toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
|
||||
data-tone={item.kind}
|
||||
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
|
||||
duration={expanded ? 600_000 : item.kind !== 'ok' ? 10_000 : item.action ? 8000 : 3000}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onRemove(item.id)
|
||||
}}
|
||||
@@ -71,6 +71,8 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
|
||||
<div className="toast-main-row">
|
||||
{item.kind === 'ok' ? (
|
||||
<CircleCheck size={16} aria-hidden="true" />
|
||||
) : item.kind === 'warning' ? (
|
||||
<HostIcon name="warning"><AlertTriangle size={16} aria-hidden="true" /></HostIcon>
|
||||
) : (
|
||||
<HostIcon name="error"><CircleX size={16} aria-hidden="true" /></HostIcon>
|
||||
)}
|
||||
|
||||
@@ -189,6 +189,7 @@ export const events = {
|
||||
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
|
||||
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
|
||||
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
|
||||
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
|
||||
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
|
||||
onPluginInstall: (cb: (p: MarketInstallProgress) => void) => eventsOn('reims:plugin-install', cb),
|
||||
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
|
||||
|
||||
+115
-46
@@ -103,6 +103,7 @@ type App struct {
|
||||
ctx context.Context
|
||||
mu sync.Mutex
|
||||
configMu sync.Mutex // serializes config writes and data root changes
|
||||
selectionMu sync.Mutex // keeps a GUI selection in its data root across UAC
|
||||
cfg *config.Config
|
||||
transitions map[string]string
|
||||
pendingChanges map[string][]PendingChange
|
||||
@@ -891,9 +892,9 @@ func (a *App) startTray() {
|
||||
OnVMAction: a.trayVMAction,
|
||||
OnQuit: a.QuitApp,
|
||||
GetSnapshot: func() tray.Snapshot {
|
||||
cfgCopy := a.runtimeConfig()
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
loc := a.cfg.Locale
|
||||
loc := cfgCopy.Locale
|
||||
cached := append([]driver.VMListItem(nil), a.lastVMs...)
|
||||
transitions := make(map[string]string, len(a.transitions))
|
||||
for k, v := range a.transitions {
|
||||
@@ -1012,38 +1013,40 @@ func (a *App) resetDataRootCaches() {
|
||||
}
|
||||
|
||||
func (a *App) SetDataRoot(dir string) error {
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
return a.setDataRoot(dir, host.SyncQEMUASLR)
|
||||
}
|
||||
|
||||
func (a *App) checkDataRootSwitch(loc i18n.Locale) error {
|
||||
a.mu.Lock()
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
prev := a.cfg.DataRoot
|
||||
curLocalePref := a.cfg.Locale
|
||||
curAutoPin := a.cfg.AutoPinPCores
|
||||
curRuntimeChannel := a.cfg.RuntimeChannel
|
||||
curAppUpdateChannel := a.cfg.AppUpdateChannel
|
||||
curMinToTray := a.cfg.MinimizeToTray
|
||||
curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS
|
||||
curEnableHvSwitch := a.cfg.EnableHypervisorSwitch
|
||||
curHostDNS := a.hostDNSConfigLocked()
|
||||
defer a.mu.Unlock()
|
||||
for _, v := range a.lastVMs {
|
||||
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
|
||||
a.mu.Unlock()
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
|
||||
}
|
||||
}
|
||||
for _, tr := range a.transitions {
|
||||
if tr != "" {
|
||||
a.mu.Unlock()
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
// Plugin tasks do not block the switch; resetDataRootCaches cancels them.
|
||||
if hostTaskRunning() {
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, string) error) (err error) {
|
||||
a.selectionMu.Lock()
|
||||
defer a.selectionMu.Unlock()
|
||||
a.mu.Lock()
|
||||
prev := *a.cfg
|
||||
wasReadOnly, setup := a.root.ReadOnly, a.needsSetup
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(prev.Locale)
|
||||
if err := a.checkDataRootSwitch(loc); err != nil {
|
||||
return err
|
||||
}
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir != "" {
|
||||
dir = filepath.Clean(dir)
|
||||
@@ -1056,39 +1059,93 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
return dataroot.Error(loc, st)
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
if _, statErr := os.Stat(cfgPath); statErr != nil {
|
||||
nextCfg.Locale = curLocalePref
|
||||
nextCfg.AutoPinPCores = curAutoPin
|
||||
nextCfg.RuntimeChannel = curRuntimeChannel
|
||||
nextCfg.AppUpdateChannel = curAppUpdateChannel
|
||||
nextCfg.MinimizeToTray = curMinToTray
|
||||
nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS
|
||||
nextCfg.EnableHypervisorSwitch = curEnableHvSwitch
|
||||
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL
|
||||
}
|
||||
if err := nextCfg.EnsureDirs(); err != nil {
|
||||
target := config.Config{DataRoot: dir}
|
||||
if err := target.EnsureDirs(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writable(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
if st.ReadOnly {
|
||||
return dataroot.Error(loc, st)
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
changed := !sameDataFolder(prev.DataRoot, dir)
|
||||
source := ""
|
||||
if changed && !setup && !wasReadOnly {
|
||||
if _, err := os.Stat(prev.DataRoot); err == nil {
|
||||
source = prev.RuntimesDir()
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
release, err := lockDataRootSelections(ctx, source, target.RuntimesDir())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if changed && !setup && !wasReadOnly {
|
||||
if err := rt.RefreshSelection(&prev); err != nil {
|
||||
// A damaged source config must still allow switching to a healthy folder.
|
||||
a.emitLog("runtime", "Read previous runtime selection: "+err.Error())
|
||||
}
|
||||
}
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.LoadExisting(cfgPath)
|
||||
fresh := errors.Is(err, os.ErrNotExist)
|
||||
if fresh {
|
||||
nextCfg = config.Default()
|
||||
nextCfg.Locale = prev.Locale
|
||||
nextCfg.QEMUASLR = prev.QEMUASLR
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
if changed && !setup {
|
||||
restore, policyErr := a.moveDataRootASLR(ctx, &prev, nextCfg, fresh, syncPolicy)
|
||||
if policyErr != nil {
|
||||
return policyErr
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
err = errors.Join(err, restore())
|
||||
}
|
||||
}()
|
||||
}
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
if err := a.checkDataRootSwitch(loc); err != nil {
|
||||
return err
|
||||
}
|
||||
if fresh {
|
||||
// Keep preference edits made while Windows was asking for consent.
|
||||
a.mu.Lock()
|
||||
cur := *a.cfg
|
||||
a.mu.Unlock()
|
||||
nextCfg.Locale = cur.Locale
|
||||
nextCfg.AutoPinPCores = cur.AutoPinPCores
|
||||
nextCfg.RuntimeChannel = cur.RuntimeChannel
|
||||
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
|
||||
nextCfg.MinimizeToTray = cur.MinimizeToTray
|
||||
nextCfg.SyncHostMemorySMBIOS = cur.SyncHostMemorySMBIOS
|
||||
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
|
||||
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
|
||||
} else {
|
||||
// Preserve independent preference saves in the destination during UAC.
|
||||
nextCfg, err = config.LoadExisting(cfgPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
}
|
||||
if err := rt.SavePreferences(nextCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
// A folder created just now gets its version stamp here.
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
|
||||
a.mu.Lock()
|
||||
wasReadOnly := a.root.ReadOnly
|
||||
a.cfg = nextCfg
|
||||
if a.guestTools != nil {
|
||||
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
|
||||
@@ -1100,7 +1157,7 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
|
||||
// Leaving a read-only folder starts the plugins and polling it held back,
|
||||
// even when the user picked the same folder again after fixing it.
|
||||
if filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly {
|
||||
if changed || wasReadOnly {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
@@ -1177,28 +1234,40 @@ func (a *App) activateInstalledRuntime(cfg *config.Config, commit string) error
|
||||
}
|
||||
|
||||
func (a *App) activateRuntime(dataRoot, commit string) error {
|
||||
return a.updateConfig(nil, func(cfg *config.Config) error {
|
||||
return a.updateSelection(func(cfg *config.Config) error {
|
||||
if dataRoot != "" && cfg.DataRoot != dataRoot {
|
||||
return errors.New("data folder changed during runtime install")
|
||||
}
|
||||
return rt.Activate(a.baseCtx(), cfg, commit)
|
||||
return rt.Activate(a.baseCtx(), cfg, commit, a.warnRuntime)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) warnRuntime(warning error) {
|
||||
message := warning.Error()
|
||||
a.emitLog("runtime", message)
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:runtime-warning", message)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) SetQEMUASLR(enabled bool) error {
|
||||
return a.updateConfig(nil, func(cfg *config.Config) error {
|
||||
return a.updateSelection(func(cfg *config.Config) error {
|
||||
return rt.SetQEMUASLR(a.baseCtx(), cfg, enabled)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) RemoveRuntime(commit string) error {
|
||||
a.mu.Lock()
|
||||
cfg := a.cfg
|
||||
loc := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
if err := a.requireWritableDataRootLocked(); err != nil {
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
cfg := *a.cfg
|
||||
loc := i18n.EffectiveLocale(cfg.Locale)
|
||||
ctx := a.ctx
|
||||
a.mu.Unlock()
|
||||
|
||||
inst, err := rt.Remove(cfg, commit)
|
||||
inst, err := rt.Remove(&cfg, commit)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, rt.ErrNotFound):
|
||||
|
||||
@@ -40,9 +40,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
if opts.NetworkMode == "bridge" {
|
||||
opts.SSHPort = 0
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfgCopy := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func sameDataFolder(a, b string) bool {
|
||||
if rel, err := filepath.Rel(a, b); err == nil && rel == "." {
|
||||
return true
|
||||
}
|
||||
left, errA := os.Stat(a)
|
||||
right, errB := os.Stat(b)
|
||||
return errA == nil && errB == nil && os.SameFile(left, right)
|
||||
}
|
||||
|
||||
// Order both selection locks so simultaneous switches in opposite directions
|
||||
// cannot deadlock. Ordinary preference saves can finish during the switch.
|
||||
func lockDataRootSelections(ctx context.Context, source, target string) (func(), error) {
|
||||
if source == "" || sameDataFolder(source, target) {
|
||||
return rt.LockSelection(ctx, target)
|
||||
}
|
||||
if strings.ToLower(source) > strings.ToLower(target) {
|
||||
source, target = target, source
|
||||
}
|
||||
first, err := rt.LockSelection(ctx, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
second, err := rt.LockSelection(ctx, target)
|
||||
if err != nil {
|
||||
first()
|
||||
return nil, err
|
||||
}
|
||||
return func() {
|
||||
second()
|
||||
first()
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Return a rollback for a later config or location save failure. Existing
|
||||
// destination preferences already authorize their own rule.
|
||||
func (a *App) moveDataRootASLR(ctx context.Context, prev, next *config.Config, fresh bool, syncPolicy func(context.Context, string, string) error) (func() error, error) {
|
||||
path, err := rt.QEMUASLRPath(next)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
restoreSource := func() error {
|
||||
oldPath, err := rt.QEMUASLRPath(prev)
|
||||
if err != nil || oldPath == "" {
|
||||
return err
|
||||
}
|
||||
return syncPolicy(context.WithoutCancel(ctx), prev.RuntimesDir(), oldPath)
|
||||
}
|
||||
if err := syncPolicy(ctx, prev.RuntimesDir(), ""); err != nil {
|
||||
report := rt.QEMUASLRPolicyError(prev, err)
|
||||
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
|
||||
return nil, report
|
||||
}
|
||||
return nil, errors.Join(report, restoreSource())
|
||||
}
|
||||
if path == "" {
|
||||
return restoreSource, nil
|
||||
}
|
||||
restore := func() error {
|
||||
var err error
|
||||
if fresh {
|
||||
err = syncPolicy(context.WithoutCancel(ctx), next.RuntimesDir(), "")
|
||||
}
|
||||
return errors.Join(err, restoreSource())
|
||||
}
|
||||
if err := syncPolicy(ctx, next.RuntimesDir(), path); err != nil {
|
||||
if errors.Is(err, host.ErrQEMUASLRImagePolicy) {
|
||||
a.warnRuntime(rt.QEMUASLRPolicyError(next, err))
|
||||
return restoreSource, nil
|
||||
}
|
||||
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
|
||||
return nil, errors.Join(rt.QEMUASLRPolicyError(next, err), restoreSource())
|
||||
}
|
||||
return nil, errors.Join(err, restore())
|
||||
}
|
||||
return restore, nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
func TestDataRootSwitchCarriesASLRAndCleansSource(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
|
||||
old := config.Config{DataRoot: filepath.Join(dir, "old")}
|
||||
a := &App{cfg: &old}
|
||||
saved := old
|
||||
saved.QEMUASLR = true // The CLI enabled it after the desktop opened.
|
||||
if err := config.Save("", &saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := filepath.Join(dir, "new")
|
||||
calls := 0
|
||||
err := a.setDataRoot(target, func(_ context.Context, root, path string) error {
|
||||
calls++
|
||||
if root != old.RuntimesDir() || path != "" {
|
||||
t.Fatalf("unexpected policy update %q, %q", root, path)
|
||||
}
|
||||
// A preference save must finish while the Windows consent prompt is open.
|
||||
return a.SetSyncHostMemorySMBIOS(true)
|
||||
})
|
||||
if err != nil || calls != 1 {
|
||||
t.Fatalf("switch: calls=%d err=%v", calls, err)
|
||||
}
|
||||
stored, err := config.LoadExisting(filepath.Join(target, "reims-go.json"))
|
||||
if err != nil || !stored.QEMUASLR || !stored.SyncHostMemorySMBIOS || a.cfg.DataRoot != target {
|
||||
t.Fatalf("new config: %+v, %v", stored, err)
|
||||
}
|
||||
if err := a.setDataRoot(target, func(context.Context, string, string) error {
|
||||
t.Fatal("same directory must retain its rule")
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataRootSwitchUsesDestinationPolicy(t *testing.T) {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
|
||||
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: !enabled}
|
||||
next := config.Config{DataRoot: filepath.Join(dir, "next"), QEMUASLR: enabled, ActiveRuntime: "new"}
|
||||
if err := config.Save("", &next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtimeDir := folderTestDir(t, next.RuntimesDir(), "new")
|
||||
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := &App{cfg: &old}
|
||||
var updates [][2]string
|
||||
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
|
||||
updates = append(updates, [2]string{root, path})
|
||||
return nil
|
||||
})
|
||||
want := [][2]string{{old.RuntimesDir(), ""}}
|
||||
if enabled {
|
||||
runtime := rt.Installed{Dir: runtimeDir}
|
||||
want = append(want, [2]string{next.RuntimesDir(), runtime.QemuPath()})
|
||||
}
|
||||
if err != nil || a.cfg.QEMUASLR != enabled || !reflect.DeepEqual(updates, want) {
|
||||
t.Fatalf("destination enabled=%v: cfg=%+v updates=%v err=%v", enabled, a.cfg, updates, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataRootSwitchRestoresSourceOnPublishFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
|
||||
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "old"}
|
||||
if err := config.SaveLocation(old.DataRoot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtimeDir := folderTestDir(t, old.RuntimesDir(), "old")
|
||||
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := filepath.Join(dir, "next")
|
||||
// config.Save will fail after the previous policy was cleared.
|
||||
folderTestDir(t, next, "reims-go.json.tmp")
|
||||
a := &App{cfg: &old}
|
||||
var paths []string
|
||||
err := a.setDataRoot(next, func(_ context.Context, root, path string) error {
|
||||
if root != old.RuntimesDir() {
|
||||
return errors.New("unexpected registry root")
|
||||
}
|
||||
paths = append(paths, path)
|
||||
return nil
|
||||
})
|
||||
runtime := rt.Installed{Dir: runtimeDir}
|
||||
location, ok := config.ReadLocation()
|
||||
if err == nil || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot || !reflect.DeepEqual(paths, []string{"", runtime.QemuPath()}) {
|
||||
t.Fatalf("failed switch: cfg=%+v, location=%s, updates=%v err=%v", a.cfg, location, paths, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataRootSwitchRollsBackPartialPolicyWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
|
||||
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "installed"}
|
||||
next := config.Config{DataRoot: filepath.Join(dir, "next")}
|
||||
if err := config.SaveLocation(old.DataRoot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, cfg := range []config.Config{old, next} {
|
||||
dir := folderTestDir(t, cfg.RuntimesDir(), "installed")
|
||||
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
oldRuntime := rt.Installed{Dir: filepath.Join(old.RuntimesDir(), "installed")}
|
||||
nextRuntime := rt.Installed{Dir: filepath.Join(next.RuntimesDir(), "installed")}
|
||||
clearOld := [2]string{old.RuntimesDir(), ""}
|
||||
restoreOld := [2]string{old.RuntimesDir(), oldRuntime.QemuPath()}
|
||||
enableNext := [2]string{next.RuntimesDir(), nextRuntime.QemuPath()}
|
||||
clearNext := [2]string{next.RuntimesDir(), ""}
|
||||
partial := errors.New("incomplete registry write")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failAt [2]string
|
||||
err error
|
||||
want [][2]string
|
||||
}{
|
||||
{"source", clearOld, partial, [][2]string{clearOld, restoreOld}},
|
||||
{"target", enableNext, partial, [][2]string{clearOld, enableNext, clearNext, restoreOld}},
|
||||
{"declined", clearOld, host.ErrElevationDeclined, [][2]string{clearOld}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var updates [][2]string
|
||||
a := &App{cfg: &old}
|
||||
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
|
||||
operation := [2]string{root, path}
|
||||
updates = append(updates, operation)
|
||||
if operation == tc.failAt {
|
||||
return tc.err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
location, ok := config.ReadLocation()
|
||||
if !errors.Is(err, tc.err) || !reflect.DeepEqual(updates, tc.want) || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot {
|
||||
t.Fatalf("updates=%v, location=%q, cfg=%+v, err=%v", updates, location, a.cfg, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -67,12 +67,6 @@ func (a *App) requireWritableDataRootLocked() error {
|
||||
}
|
||||
|
||||
func (a *App) setPreference(edit func(*config.Config)) error {
|
||||
return a.updateConfig(edit, rt.SavePreferences)
|
||||
}
|
||||
|
||||
// Settings can be edited in memory before setup. Runtime actions (no edit)
|
||||
// need a writable data root. Disk locks and UAC never run under a.mu.
|
||||
func (a *App) updateConfig(edit func(*config.Config), persist func(*config.Config) error) error {
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
a.mu.Lock()
|
||||
@@ -80,14 +74,12 @@ func (a *App) updateConfig(edit func(*config.Config), persist func(*config.Confi
|
||||
setup := a.needsSetup
|
||||
err := a.requireWritableDataRootLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil && !(setup && edit != nil) {
|
||||
if err != nil && !setup {
|
||||
return err
|
||||
}
|
||||
if edit != nil {
|
||||
edit(&cfg)
|
||||
}
|
||||
edit(&cfg)
|
||||
if !setup {
|
||||
if err := persist(&cfg); err != nil {
|
||||
if err := rt.SavePreferences(&cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -97,6 +89,31 @@ func (a *App) updateConfig(edit func(*config.Config), persist func(*config.Confi
|
||||
return nil
|
||||
}
|
||||
|
||||
// Runtime policy may wait for UAC. Publish only its two fields over the
|
||||
// current settings once the disk transaction has finished.
|
||||
func (a *App) updateSelection(persist func(*config.Config) error) error {
|
||||
a.selectionMu.Lock()
|
||||
defer a.selectionMu.Unlock()
|
||||
a.mu.Lock()
|
||||
err := a.requireWritableDataRootLocked()
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := persist(&cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
a.mu.Lock()
|
||||
latest := *a.cfg
|
||||
latest.ActiveRuntime, latest.QEMUASLR = cfg.ActiveRuntime, cfg.QEMUASLR
|
||||
a.cfg = &latest
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// runtimeConfig includes the last selection made by either the GUI or CLI.
|
||||
func (a *App) runtimeConfig() config.Config {
|
||||
a.mu.Lock()
|
||||
@@ -120,6 +137,8 @@ func (a *App) runtimeConfig() config.Config {
|
||||
// a damaged version record on the user's request. When the folder becomes
|
||||
// writable, the parts that were held back start.
|
||||
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
|
||||
a.selectionMu.Lock()
|
||||
defer a.selectionMu.Unlock()
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
a.mu.Lock()
|
||||
|
||||
@@ -138,8 +138,8 @@ func (a *App) ExportDiagnosticsWithDriver(driverID, name string) (string, error)
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
cfgCopy := a.runtimeConfig()
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
appLogs := append([]string(nil), a.recentLogs...)
|
||||
a.mu.Unlock()
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
|
||||
@@ -13,9 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func (a *App) installerClient() (*installer.Client, error) {
|
||||
a.mu.Lock()
|
||||
cfg := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfg := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -559,9 +559,7 @@ func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbri
|
||||
}
|
||||
|
||||
func (a *App) ensurePacketBridge(d reims.VMDetail, adapter packetbridge.Adapter, mac, socketPath string, port int) (*packetbridge.Bridge, error) {
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfgCopy := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -44,9 +44,7 @@ func (a *App) GetVMSMBIOS(name string) (opencore.SMBIOSIdentity, error) {
|
||||
if err := a.requireMacOSEnabled(); err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfgCopy := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
@@ -84,9 +82,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
}
|
||||
a.mu.Lock()
|
||||
cfgCopy := *a.cfg
|
||||
a.mu.Unlock()
|
||||
cfgCopy := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfgCopy)
|
||||
if err != nil {
|
||||
return opencore.SMBIOSIdentity{}, err
|
||||
|
||||
@@ -144,28 +144,33 @@ func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
|
||||
resume := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
go func() {
|
||||
results <- a.updateConfig(nil, func(cfg *config.Config) error {
|
||||
results <- a.updateSelection(func(cfg *config.Config) error {
|
||||
<-resume
|
||||
cfg.ActiveRuntime, cfg.QEMUASLR = "backup", true
|
||||
return config.Save("", cfg)
|
||||
// Model the registry operation returning and committing over
|
||||
// the preferences saved while consent was pending.
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
saved.ActiveRuntime, saved.QEMUASLR = "backup", true
|
||||
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
|
||||
return config.Save("", saved)
|
||||
})
|
||||
}()
|
||||
synctest.Wait()
|
||||
started := make(chan struct{})
|
||||
go func() {
|
||||
close(started)
|
||||
results <- a.SetSyncHostMemorySMBIOS(true)
|
||||
}()
|
||||
<-started
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close(resume)
|
||||
for range 2 {
|
||||
if err := <-results; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-results; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
|
||||
t.Fatalf("concurrent updates lost: %+v, %v", saved, err)
|
||||
}
|
||||
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || !a.cfg.SyncHostMemorySMBIOS {
|
||||
t.Fatalf("in-memory settings diverged: %+v", a.cfg)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -103,6 +103,8 @@ func (a *App) CheckDataRoot(dir string) DataRootCheck {
|
||||
// existing reims-go config there (its runtimes and VMs), records the choice for
|
||||
// the next launch and leaves first-launch setup.
|
||||
func (a *App) CompleteSetup(dir string) error {
|
||||
a.selectionMu.Lock()
|
||||
defer a.selectionMu.Unlock()
|
||||
a.configMu.Lock()
|
||||
defer a.configMu.Unlock()
|
||||
a.mu.Lock()
|
||||
|
||||
@@ -350,12 +350,9 @@ func fileSizeBytes(path string) int64 {
|
||||
}
|
||||
|
||||
func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Report, qmpAddr string) {
|
||||
a.mu.Lock()
|
||||
rawLoc := a.cfg.Locale
|
||||
rtCommit := a.cfg.ActiveRuntime
|
||||
pinPCores := a.cfg.AutoPinPCores
|
||||
a.mu.Unlock()
|
||||
loc := i18n.EffectiveLocale(rawLoc)
|
||||
cfg := a.runtimeConfig()
|
||||
rtCommit := cfg.ActiveRuntime
|
||||
loc := i18n.EffectiveLocale(cfg.Locale)
|
||||
if rtCommit == "" {
|
||||
rtCommit = "auto"
|
||||
}
|
||||
@@ -367,7 +364,7 @@ func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Repor
|
||||
case strings.Contains(lowExtra, "kernel-irqchip=on"):
|
||||
irqMode = "on"
|
||||
}
|
||||
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
|
||||
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, cfg.AutoPinPCores, detail.CPUs)
|
||||
coldStr := i18n.T(loc, "monitor.start.off")
|
||||
if qmpAddr != "" {
|
||||
coldStr = i18n.T(loc, "monitor.start.on")
|
||||
|
||||
+8
-2
@@ -283,6 +283,12 @@ func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
|
||||
}
|
||||
}
|
||||
|
||||
func activateRuntime(ctx context.Context, cfg *config.Config, loc i18n.Locale, commit string) error {
|
||||
return rt.Activate(ctx, cfg, commit, func(warning error) {
|
||||
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, warning))
|
||||
})
|
||||
}
|
||||
|
||||
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use|remove>")
|
||||
@@ -299,7 +305,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := rt.Activate(context.Background(), cfg, inst.Commit); err != nil {
|
||||
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
|
||||
@@ -334,7 +340,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
if len(args) < 2 {
|
||||
return fmt.Errorf("usage: reims-go runtime use <commit>")
|
||||
}
|
||||
if err := rt.Activate(context.Background(), cfg, args[1]); err != nil {
|
||||
if err := activateRuntime(context.Background(), cfg, loc, args[1]); err != nil {
|
||||
if errors.Is(err, rt.ErrNotFound) {
|
||||
return errors.New(i18n.T(loc, "runtime.not_found", args[1]))
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
_ = os.Remove(path)
|
||||
r.Commit = inst.Commit
|
||||
}
|
||||
if err := rt.Activate(ctx, cfg, r.Commit); err != nil {
|
||||
if err := activateRuntime(ctx, cfg, loc, r.Commit); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(i18n.T(loc, "runtime.activated", r.Commit))
|
||||
|
||||
@@ -215,7 +215,12 @@ func Load(path string) (*Config, error) {
|
||||
|
||||
// LoadExisting reads an existing config and reports a missing file to the caller.
|
||||
func LoadExisting(path string) (*Config, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
var raw []byte
|
||||
err := retryFileConflict(func() error {
|
||||
var readErr error
|
||||
raw, readErr = os.ReadFile(path)
|
||||
return readErr
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -257,16 +262,16 @@ func Save(path string, cfg *Config) error {
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
return retryFileConflict(func() error { return os.Rename(tmp, path) })
|
||||
}
|
||||
|
||||
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
|
||||
func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") }
|
||||
func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") }
|
||||
func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") }
|
||||
func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") }
|
||||
func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") }
|
||||
func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") }
|
||||
func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") }
|
||||
func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") }
|
||||
func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") }
|
||||
|
||||
func (c *Config) EnsureDirs() error {
|
||||
for _, d := range []string{
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !windows
|
||||
|
||||
package config
|
||||
|
||||
func retryFileConflict(op func() error) error { return op() }
|
||||
@@ -0,0 +1,23 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// A reader can briefly deny replacement, and an overlapping replacement
|
||||
// can briefly deny a new read. A persistent permission error must surface.
|
||||
func retryFileConflict(op func() error) error {
|
||||
err := op()
|
||||
for delay := 5 * time.Millisecond; delay <= 80*time.Millisecond; delay *= 2 {
|
||||
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) && !errors.Is(err, windows.ERROR_SHARING_VIOLATION) &&
|
||||
!errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
|
||||
break
|
||||
}
|
||||
time.Sleep(delay)
|
||||
err = op()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestConfigRecoversFromWindowsSharingConflict(t *testing.T) {
|
||||
for _, operation := range []string{"load", "save"} {
|
||||
t.Run(operation, func(t *testing.T) {
|
||||
cfg := Config{DataRoot: t.TempDir(), ActiveRuntime: "first"}
|
||||
path := filepath.Join(cfg.DataRoot, "reims-go.json")
|
||||
if err := Save(path, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name, err := windows.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handle, err := windows.CreateFile(name, windows.GENERIC_READ, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
if operation == "load" {
|
||||
_, err := LoadExisting(path)
|
||||
result <- err
|
||||
return
|
||||
}
|
||||
cfg.ActiveRuntime = "second"
|
||||
result <- Save(path, &cfg)
|
||||
}()
|
||||
synctest.Wait() // The operation has reached its first retry.
|
||||
if err := windows.CloseHandle(handle); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
got, err := LoadExisting(path)
|
||||
if err != nil || got.ActiveRuntime != cfg.ActiveRuntime {
|
||||
t.Fatalf("load after %s: got %+v, err %v", operation, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
package host
|
||||
|
||||
import "errors"
|
||||
|
||||
const QEMUASLRHelperArg = "--apply-qemu-aslr"
|
||||
|
||||
// The elevated helper has no output channel back to the GUI.
|
||||
const QEMUASLRImagePolicyExitCode = 78
|
||||
|
||||
var ErrQEMUASLRImagePolicy = errors.New("a QEMU path filter would shadow an image-wide Windows setting")
|
||||
@@ -42,10 +42,17 @@ func SyncQEMUASLR(ctx context.Context, runtimesDir, qemuPath string) error {
|
||||
// Once authorized, wait for the helper to finish before the caller commits
|
||||
// or rolls back the corresponding runtime preference.
|
||||
code, err := runElevatedWait(context.WithoutCancel(ctx), exe, args)
|
||||
if err == nil && code != 0 {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch code {
|
||||
case 0:
|
||||
return nil
|
||||
case QEMUASLRImagePolicyExitCode:
|
||||
return ErrQEMUASLRImagePolicy
|
||||
default:
|
||||
return fmt.Errorf("apply QEMU ASLR: helper exited with code %d", code)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func ApplyQEMUASLR(runtimesDir, qemuPath string) error {
|
||||
@@ -188,7 +195,7 @@ func enableASLRPathFilters(image registry.Key, createdImage, newPath bool, filte
|
||||
}
|
||||
for _, v := range values {
|
||||
if !strings.EqualFold(v, "UseFilter") && !strings.EqualFold(v, filterMode) {
|
||||
return fmt.Errorf("a QEMU path filter would shadow the image-wide Windows setting %q", v)
|
||||
return fmt.Errorf("%w: %q", ErrQEMUASLRImagePolicy, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package host
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -208,11 +209,31 @@ func TestQEMUASLRRestoresImageKey(t *testing.T) {
|
||||
t.Fatalf("restored UseFilter = %v, %v", mode, err)
|
||||
}
|
||||
|
||||
if err := image.SetBinaryValue("MitigationOptions", []byte{1, 0, 0}); err != nil {
|
||||
if err := update(target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := update(target); err == nil {
|
||||
t.Fatal("unexpectedly shadowed image-wide mitigations")
|
||||
imagePolicy := []byte{1, 0, 0}
|
||||
if err := image.SetBinaryValue("MitigationOptions", imagePolicy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := filepath.Join(root, "upgrade", "qemu", "bin", qemuImage)
|
||||
for _, canWrite := range []bool{false, true} {
|
||||
if err := reconcileQEMUASLR(hive, imagePath, root, next, canWrite); !errors.Is(err, ErrQEMUASLRImagePolicy) {
|
||||
t.Fatalf("expected image-wide conflict (write %v), got %v", canWrite, err)
|
||||
}
|
||||
}
|
||||
if got, _, err := image.GetBinaryValue("MitigationOptions"); err != nil || !bytes.Equal(got, imagePolicy) {
|
||||
t.Fatalf("image policy changed: %x, %v", got, err)
|
||||
}
|
||||
names, err := image.ReadSubKeyNames(-1)
|
||||
if err != nil || len(names) != 1 {
|
||||
t.Fatalf("unexpected path filters after conflict: %v, %v", names, err)
|
||||
}
|
||||
if path, owned, err := readASLRFilter(image, names[0]); err != nil || !owned || path != target {
|
||||
t.Fatalf("previous filter changed: %q, owned %v, %v", path, owned, err)
|
||||
}
|
||||
if err := update(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := image.DeleteValue("MitigationOptions"); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -178,9 +178,10 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.plugin.safe_mode": "当前处于安全模式,已暂停加载和变更第三方插件",
|
||||
"err.plugin.system_locked": "系统核心组件「{id}」不可停用或卸载",
|
||||
"err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样",
|
||||
"err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR",
|
||||
"err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。",
|
||||
"err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。",
|
||||
"err.runtime_changed": "启动期间运行时已切换,再次启动即可使用所选版本。",
|
||||
"err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。",
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.snapshot.name_empty": "请输入恢复点名称",
|
||||
"err.snapshot.name_invalid": "恢复点名称包含不支持的控制字符或引号",
|
||||
@@ -872,9 +873,10 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.plugin.safe_mode": "Safe mode is active; third-party plugin changes are paused",
|
||||
"err.plugin.system_locked": "Core system component “{id}” cannot be disabled or removed",
|
||||
"err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied",
|
||||
"err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.",
|
||||
"err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.",
|
||||
"err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.",
|
||||
"err.runtime_changed": "The runtime changed while the VM was starting. Start the VM again to use the selected version.",
|
||||
"err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.",
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.snapshot.name_empty": "Enter a restore point name",
|
||||
"err.snapshot.name_invalid": "Restore point name contains unsupported characters or quotes",
|
||||
|
||||
@@ -2,9 +2,11 @@ package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
@@ -21,31 +23,83 @@ func CheckLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, wa
|
||||
}
|
||||
|
||||
func checkLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, warnings io.Writer, apply func(string, string) error) error {
|
||||
if err := RefreshSelection(&cfg); err != nil || !cfg.QEMUASLR {
|
||||
warn := func(err error) error {
|
||||
if warnings != nil {
|
||||
fmt.Fprintln(warnings, i18n.T(i18n.EffectiveLocale(cfg.Locale), "runtime.qemu_aslr.warning"), err)
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
|
||||
if err != nil {
|
||||
if err := RefreshSelection(&cfg); err != nil {
|
||||
// The client already holds a runtime. Launch it without changing a
|
||||
// registry rule whose current owner we could not verify.
|
||||
return warn(err)
|
||||
}
|
||||
if !cfg.QEMUASLR {
|
||||
return ctx.Err()
|
||||
}
|
||||
release, lockErr := lockLaunchPolicy(ctx, cfg.RuntimesDir())
|
||||
if lockErr != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !errors.Is(lockErr, context.DeadlineExceeded) {
|
||||
return lockErr
|
||||
}
|
||||
// Without the lock, only an explicit selection read from disk can
|
||||
// establish that the client's runtime has been superseded.
|
||||
cfg.ActiveRuntime = ""
|
||||
} else {
|
||||
defer release()
|
||||
}
|
||||
if err := RefreshSelection(&cfg); err != nil {
|
||||
return warn(err)
|
||||
}
|
||||
if !cfg.QEMUASLR {
|
||||
return ctx.Err()
|
||||
}
|
||||
active, err := ResolveActive(&cfg)
|
||||
if lockErr != nil && (err != nil || !active.Active) {
|
||||
return warn(lockErr)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrNoActiveRuntime) {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if err := RefreshSelection(&cfg); err != nil || !cfg.QEMUASLR {
|
||||
return err
|
||||
}
|
||||
activePath, err := qemuASLRPath(&cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if activePath == "" || !samePath(activePath, qemuPath) {
|
||||
if active == nil || !samePath(active.QemuPath(), qemuPath) {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
|
||||
}
|
||||
if lockErr != nil {
|
||||
return warn(lockErr)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Opening the VM must not prompt for elevation. Explicitly applying the
|
||||
// preference or activating a runtime remains the authorized repair path.
|
||||
if err := apply(cfg.RuntimesDir(), activePath); err != nil && warnings != nil {
|
||||
fmt.Fprintln(warnings, i18n.T(i18n.EffectiveLocale(cfg.Locale), "runtime.qemu_aslr.warning"), err)
|
||||
if err := apply(cfg.RuntimesDir(), active.QemuPath()); err != nil {
|
||||
return warn(QEMUASLRPolicyError(&cfg, err))
|
||||
}
|
||||
return nil
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func lockLaunchPolicy(ctx context.Context, root string) (func(), error) {
|
||||
// Repair is optional. A pending consent dialog can keep the selection
|
||||
// busy indefinitely, and an install can briefly hold the directory lock.
|
||||
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
defer cancel()
|
||||
releaseSelection, err := LockSelection(ctx, root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
releaseDir, err := lockRuntimeDirectoriesContext(ctx, root)
|
||||
if err != nil {
|
||||
releaseSelection()
|
||||
return nil, err
|
||||
}
|
||||
return func() {
|
||||
releaseDir()
|
||||
releaseSelection()
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestLaunchPolicyUnreadableSelection(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current"}
|
||||
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
|
||||
for _, enabled := range []bool{false, true} {
|
||||
cfg.QEMUASLR = enabled
|
||||
var warning bytes.Buffer
|
||||
err := checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error {
|
||||
t.Fatal("policy applied without a confirmed selection")
|
||||
return nil
|
||||
})
|
||||
if err != nil || warning.Len() == 0 {
|
||||
t.Fatalf("ASLR enabled=%t: launch error %v, warning %q", enabled, err, &warning)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchPolicyBusy(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
lock func(context.Context, string) (func(), error)
|
||||
}{
|
||||
{"pending selection", LockSelection},
|
||||
{"runtime directory in use", lockRuntimeDirectoriesContext},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
|
||||
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
|
||||
writeFakeRuntime(t, current.Dir, Manifest{Commit: cfg.ActiveRuntime})
|
||||
release, err := tc.lock(t.Context(), cfg.RuntimesDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer release()
|
||||
var warning bytes.Buffer
|
||||
err = checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error {
|
||||
t.Fatal("policy applied while its lock was in use")
|
||||
return nil
|
||||
})
|
||||
if err != nil || warning.Len() == 0 {
|
||||
t.Fatalf("busy policy: launch error %v, warning %q", err, &warning)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchPolicyReturnsCallerCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err := checkLaunchASLR(ctx, config.Config{}, "", nil, nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancelled launch returned %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyLaunchPolicyRejectsSupersededRuntime(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
|
||||
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
|
||||
writeFakeRuntime(t, old.Dir, Manifest{Commit: "old"})
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "new"), Manifest{Commit: "new"})
|
||||
published := cfg
|
||||
published.ActiveRuntime = "new"
|
||||
if err := config.Save("", &published); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release, err := LockSelection(t.Context(), cfg.RuntimesDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer release()
|
||||
err = checkLaunchASLR(t.Context(), cfg, old.QemuPath(), nil, func(_, _ string) error {
|
||||
t.Fatal("policy applied to a superseded runtime")
|
||||
return nil
|
||||
})
|
||||
var coded *i18n.CodedError
|
||||
if !errors.As(err, &coded) || coded.Code != "E_RUNTIME_CHANGED" {
|
||||
t.Fatalf("superseded launch while policy busy: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,61 @@ func TestRemoveRuntime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveAfterExternalActivation(t *testing.T) {
|
||||
for _, selected := range []string{"next", DefaultKind + "/next", "other/next"} {
|
||||
t.Run(selected, func(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old"}
|
||||
oldDir := filepath.Join(cfg.RuntimesDir(), "old")
|
||||
nextDir := filepath.Join(cfg.RuntimesDir(), "next")
|
||||
writeFakeRuntime(t, oldDir, Manifest{Commit: "old"})
|
||||
if selected == "other/next" {
|
||||
nextDir = filepath.Join(cfg.RuntimesDir(), "other", "next")
|
||||
// Keep the default kind's implicit single-runtime fallback out of this case.
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "spare"), Manifest{Commit: "spare"})
|
||||
}
|
||||
writeFakeRuntime(t, nextDir, Manifest{Commit: "next"})
|
||||
cli := cfg
|
||||
if err := Activate(t.Context(), &cli, selected, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := List(&cli)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, item := range list {
|
||||
if item.Active != (item.Dir == nextDir) {
|
||||
t.Fatalf("runtime %s active = %t after selecting %s", item.Dir, item.Active, selected)
|
||||
}
|
||||
}
|
||||
if _, err := Remove(&cfg, selected); !errors.Is(err, ErrRemoveActive) {
|
||||
t.Fatalf("removing the newly active runtime returned %v", err)
|
||||
}
|
||||
if _, err := os.Stat(nextDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Remove(&cfg, "old"); err != nil {
|
||||
t.Fatalf("removing the formerly selected runtime: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveWithUnreadableSelection(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old"}
|
||||
nextDir := filepath.Join(cfg.RuntimesDir(), "next")
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "old"), Manifest{Commit: "old"})
|
||||
writeFakeRuntime(t, nextDir, Manifest{Commit: "next"})
|
||||
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Remove(&cfg, "next"); err == nil {
|
||||
t.Fatal("removed a runtime without a readable selection")
|
||||
}
|
||||
if _, err := os.Stat(nextDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveRuntimeInUseWindows(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("Windows file locking semantics only")
|
||||
|
||||
@@ -167,7 +167,7 @@ func List(cfg *config.Config) ([]Installed, error) {
|
||||
Kind: kind,
|
||||
Commit: commit,
|
||||
Dir: dir,
|
||||
Active: specForKind(kind).Builtin && commit == cfg.ActiveRuntime,
|
||||
Active: (specForKind(kind).Builtin && commit == cfg.ActiveRuntime) || kind+"/"+commit == cfg.ActiveRuntime,
|
||||
Manifest: m,
|
||||
Spec: specForKind(kind),
|
||||
})
|
||||
@@ -240,7 +240,13 @@ func Remove(cfg *config.Config, commit string) (*Installed, error) {
|
||||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
list, err := List(cfg)
|
||||
// Activation takes the same directory lock. Include any selection published
|
||||
// while this process waited, and leave both runtimes intact upon read errors.
|
||||
current := *cfg
|
||||
if err := RefreshSelection(¤t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list, err := List(¤t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -260,7 +266,11 @@ func Remove(cfg *config.Config, commit string) (*Installed, error) {
|
||||
if match.Active {
|
||||
return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit)
|
||||
}
|
||||
if active, err := ResolveActive(cfg); err == nil && active != nil && samePath(active.Dir, match.Dir) {
|
||||
active, err := ResolveActive(¤t)
|
||||
if err != nil && !errors.Is(err, ErrNoActiveRuntime) {
|
||||
return nil, err
|
||||
}
|
||||
if active != nil && samePath(active.Dir, match.Dir) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit)
|
||||
}
|
||||
baseAbs, err := filepath.Abs(cfg.RuntimesDir())
|
||||
@@ -444,10 +454,14 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err
|
||||
}
|
||||
|
||||
func lockRuntimeDirectories(runtimesDir string) (func(), error) {
|
||||
return lockRuntimeDirectoriesContext(context.Background(), runtimesDir)
|
||||
}
|
||||
|
||||
func lockRuntimeDirectoriesContext(ctx context.Context, runtimesDir string) (func(), error) {
|
||||
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-runtime.lock"), 0)
|
||||
}
|
||||
|
||||
+130
-49
@@ -7,27 +7,41 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func Activate(ctx context.Context, cfg *config.Config, commit string) error {
|
||||
return saveSelection(ctx, cfg, commit, nil, host.SyncQEMUASLR)
|
||||
func Activate(ctx context.Context, cfg *config.Config, commit string, warn func(error)) error {
|
||||
return saveSelection(ctx, cfg, commit, nil, host.SyncQEMUASLR, warn)
|
||||
}
|
||||
|
||||
func SetQEMUASLR(ctx context.Context, cfg *config.Config, enabled bool) error {
|
||||
return saveSelection(ctx, cfg, "", &enabled, host.SyncQEMUASLR)
|
||||
return saveSelection(ctx, cfg, "", &enabled, host.SyncQEMUASLR, nil)
|
||||
}
|
||||
|
||||
// LockSelection serializes changes to the published selection and its host
|
||||
// policy across processes. Downloads and preference saves use the directory
|
||||
// lock separately, so they can finish while Windows waits for consent.
|
||||
func LockSelection(ctx context.Context, runtimesDir string) (func(), error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-selection.lock"), 0)
|
||||
}
|
||||
|
||||
// RefreshSelection reads the last atomically published selection, without
|
||||
// waiting for a concurrent install or a pending Windows consent prompt.
|
||||
func RefreshSelection(cfg *config.Config) error {
|
||||
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
saved, err := loadSelection(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -48,7 +62,7 @@ func SavePreferences(cfg *config.Config) error {
|
||||
return config.Save("", cfg)
|
||||
}
|
||||
|
||||
func qemuASLRPath(cfg *config.Config) (string, error) {
|
||||
func QEMUASLRPath(cfg *config.Config) (string, error) {
|
||||
if !cfg.QEMUASLR {
|
||||
return "", nil
|
||||
}
|
||||
@@ -62,65 +76,132 @@ func qemuASLRPath(cfg *config.Config) (string, error) {
|
||||
return active.QemuPath(), nil
|
||||
}
|
||||
|
||||
func saveSelection(ctx context.Context, cfg *config.Config, commit string, aslr *bool, syncPolicy func(context.Context, string, string) error) error {
|
||||
root := cfg.RuntimesDir()
|
||||
release, err := lockRuntimeDirectories(root)
|
||||
func loadSelection(cfg *config.Config) (config.Config, error) {
|
||||
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return *cfg, nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
return config.Config{}, err
|
||||
}
|
||||
defer release()
|
||||
saved.DataRoot = cfg.DataRoot
|
||||
return *saved, nil
|
||||
}
|
||||
|
||||
// Another client may have selected a runtime or changed ASLR since startup.
|
||||
path := filepath.Join(cfg.DataRoot, "reims-go.json")
|
||||
prev := *cfg
|
||||
if saved, err := config.LoadExisting(path); err == nil {
|
||||
prev = *saved
|
||||
prev.DataRoot = cfg.DataRoot
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
next := prev
|
||||
func requestedSelection(next config.Config, commit string, aslr *bool) (config.Config, error) {
|
||||
if aslr != nil {
|
||||
next.QEMUASLR = *aslr
|
||||
} else {
|
||||
installed, err := List(&prev)
|
||||
installed, err := List(&next)
|
||||
if err != nil {
|
||||
return err
|
||||
return next, err
|
||||
}
|
||||
if !slices.ContainsFunc(installed, func(r Installed) bool {
|
||||
return r.Commit == commit || r.Kind+"/"+r.Commit == commit
|
||||
}) {
|
||||
return fmt.Errorf("%w: %s", ErrNotFound, commit)
|
||||
return next, fmt.Errorf("%w: %s", ErrNotFound, commit)
|
||||
}
|
||||
next.ActiveRuntime = commit
|
||||
}
|
||||
managePolicy := aslr != nil || next.QEMUASLR
|
||||
if managePolicy {
|
||||
target, pathErr := qemuASLRPath(&next)
|
||||
if pathErr != nil {
|
||||
return pathErr
|
||||
}
|
||||
err = syncPolicy(ctx, root, target)
|
||||
if errors.Is(err, host.ErrElevationDeclined) {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_QEMU_ASLR_CANCELLED", "err.qemu_aslr.cancelled", nil, err)
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = config.Save(path, &next)
|
||||
}
|
||||
if err != nil && managePolicy {
|
||||
previousPath, restoreErr := qemuASLRPath(&prev)
|
||||
if restoreErr == nil {
|
||||
restoreErr = syncPolicy(context.WithoutCancel(ctx), root, previousPath)
|
||||
}
|
||||
return errors.Join(err, restoreErr)
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func QEMUASLRPolicyError(cfg *config.Config, err error) error {
|
||||
loc := i18n.EffectiveLocale(cfg.Locale)
|
||||
switch {
|
||||
case errors.Is(err, host.ErrQEMUASLRImagePolicy):
|
||||
return i18n.NewCodedError(loc, "E_QEMU_ASLR_IMAGE_POLICY", "err.qemu_aslr.image_policy", nil, err)
|
||||
case errors.Is(err, host.ErrElevationDeclined):
|
||||
return i18n.NewCodedError(loc, "E_QEMU_ASLR_CANCELLED", "err.qemu_aslr.cancelled", nil, err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func saveSelection(ctx context.Context, cfg *config.Config, commit string, aslr *bool, syncPolicy func(context.Context, string, string) error, warn func(error)) error {
|
||||
root := cfg.RuntimesDir()
|
||||
unlock, err := LockSelection(ctx, root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock()
|
||||
prev, err := loadSelection(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next, err := requestedSelection(prev, commit, aslr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
managePolicy := aslr != nil || next.QEMUASLR
|
||||
var warning error
|
||||
var target string
|
||||
if managePolicy {
|
||||
target, err = QEMUASLRPath(&next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = syncPolicy(ctx, root, target)
|
||||
switch {
|
||||
case errors.Is(err, host.ErrQEMUASLRImagePolicy) && aslr == nil:
|
||||
// An existing image-wide policy takes precedence. This conflict is
|
||||
// detected before writing any rules.
|
||||
warning = QEMUASLRPolicyError(&next, err)
|
||||
case errors.Is(err, host.ErrQEMUASLRImagePolicy), errors.Is(err, host.ErrElevationDeclined), errors.Is(err, context.Canceled):
|
||||
return QEMUASLRPolicyError(&next, err)
|
||||
case err != nil:
|
||||
return restoreSelectionPolicy(ctx, &prev, syncPolicy, err)
|
||||
}
|
||||
}
|
||||
|
||||
// UAC may have been pending while preferences were saved or the candidate
|
||||
// was deleted. Re-read and validate under the same lock used by both.
|
||||
err = func() error {
|
||||
release, err := lockRuntimeDirectoriesContext(ctx, root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
current, err := loadSelection(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.ActiveRuntime != prev.ActiveRuntime || current.QEMUASLR != prev.QEMUASLR {
|
||||
prev = current
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(current.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
|
||||
}
|
||||
next, err = requestedSelection(current, commit, aslr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if next.QEMUASLR {
|
||||
latestPath, err := QEMUASLRPath(&next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !samePath(latestPath, target) {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(current.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
|
||||
}
|
||||
}
|
||||
return config.Save("", &next)
|
||||
}()
|
||||
if err != nil {
|
||||
if managePolicy && warning == nil {
|
||||
return restoreSelectionPolicy(ctx, &prev, syncPolicy, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
cfg.ActiveRuntime, cfg.QEMUASLR = next.ActiveRuntime, next.QEMUASLR
|
||||
if warning != nil && warn != nil {
|
||||
warn(warning)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreSelectionPolicy(ctx context.Context, prev *config.Config, syncPolicy func(context.Context, string, string) error, cause error) error {
|
||||
target, err := QEMUASLRPath(prev)
|
||||
if err == nil {
|
||||
err = syncPolicy(context.WithoutCancel(ctx), prev.RuntimesDir(), target)
|
||||
}
|
||||
return errors.Join(cause, QEMUASLRPolicyError(prev, err))
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
func TestSelectionFollowsRuntimeAndToggle(t *testing.T) {
|
||||
@@ -26,7 +27,7 @@ func TestSelectionFollowsRuntimeAndToggle(t *testing.T) {
|
||||
}
|
||||
selectRuntime := func(client *config.Config, commit string, toggle *bool) {
|
||||
t.Helper()
|
||||
if err := saveSelection(context.Background(), client, commit, toggle, sync); err != nil {
|
||||
if err := saveSelection(context.Background(), client, commit, toggle, sync, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -64,7 +65,7 @@ func TestSelectionFailureKeepsPreviousRuntime(t *testing.T) {
|
||||
err := saveSelection(context.Background(), cfg, "new", nil, func(context.Context, string, string) error {
|
||||
calls++
|
||||
return host.ErrElevationDeclined
|
||||
})
|
||||
}, nil)
|
||||
if !errors.Is(err, host.ErrElevationDeclined) || calls != 1 {
|
||||
t.Fatalf("declined activation: calls = %d, error = %v", calls, err)
|
||||
}
|
||||
@@ -76,7 +77,7 @@ func TestSelectionFailureKeepsPreviousRuntime(t *testing.T) {
|
||||
err = saveSelection(context.Background(), cfg, "new", nil, func(_ context.Context, _, path string) error {
|
||||
applied = append(applied, path)
|
||||
return nil
|
||||
})
|
||||
}, nil)
|
||||
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
|
||||
next := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "new")}
|
||||
if err == nil || !slices.Equal(applied, []string{next.QemuPath(), old.QemuPath()}) {
|
||||
@@ -88,6 +89,61 @@ func TestSelectionFailureKeepsPreviousRuntime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectionRevalidatesAfterConsent(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
|
||||
for _, id := range []string{"old", "new"} {
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), id), Manifest{Commit: id})
|
||||
}
|
||||
if err := config.Save("", &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var paths []string
|
||||
err := saveSelection(t.Context(), &cfg, "new", nil, func(_ context.Context, _, path string) error {
|
||||
paths = append(paths, path)
|
||||
if len(paths) == 1 {
|
||||
prefs := cfg
|
||||
prefs.SyncHostMemorySMBIOS = true
|
||||
if err := SavePreferences(&prefs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := Remove(&prefs, "new")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}, nil)
|
||||
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
|
||||
if !errors.Is(err, ErrNotFound) || len(paths) != 2 || paths[1] != old.QemuPath() {
|
||||
t.Fatalf("removed during consent: paths = %q, err = %v", paths, err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "old" || !saved.SyncHostMemorySMBIOS {
|
||||
t.Fatalf("lost settings while awaiting consent: %+v, %v", saved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivationWarnsOnImagePolicyConflict(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), QEMUASLR: true}
|
||||
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "new"), Manifest{Commit: "new"})
|
||||
conflict := func(context.Context, string, string) error { return host.ErrQEMUASLRImagePolicy }
|
||||
var warning error
|
||||
if err := saveSelection(t.Context(), &cfg, "new", nil, conflict, func(err error) { warning = err }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var coded *i18n.CodedError
|
||||
if !errors.As(warning, &coded) || coded.Code != "E_QEMU_ASLR_IMAGE_POLICY" {
|
||||
t.Fatalf("activation warning = %v", warning)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "new" || !saved.QEMUASLR {
|
||||
t.Fatalf("conflicted activation = %+v, %v", saved, err)
|
||||
}
|
||||
on := true
|
||||
err = saveSelection(t.Context(), &cfg, "", &on, conflict, nil)
|
||||
if !errors.As(err, &coded) || coded.Code != "E_QEMU_ASLR_IMAGE_POLICY" {
|
||||
t.Fatalf("explicit repair error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchPolicyRejectsSupersededRuntime(t *testing.T) {
|
||||
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "backup", QEMUASLR: true}
|
||||
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
|
||||
@@ -122,7 +178,7 @@ func TestNonWindowsIgnoresSavedQEMUASLR(t *testing.T) {
|
||||
if err := config.Save("", &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Activate(t.Context(), &cfg, "backup"); err != nil {
|
||||
if err := Activate(t.Context(), &cfg, "backup", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
|
||||
|
||||
@@ -305,7 +305,8 @@
|
||||
},
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied",
|
||||
"err.runtime_changed": "The runtime changed while the VM was starting. Start the VM again to use the selected version.",
|
||||
"err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.",
|
||||
"err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.",
|
||||
"runtime.qemu_aslr.warning": "Starting without confirmed QEMU ASLR settings. To retry, turn ASLR off and on in Engine.",
|
||||
"err.macos.disabled": "macOS VM Support is disabled; enable it on the Plugins page first",
|
||||
"err.vm_not_running": "VM {name} is not running",
|
||||
|
||||
@@ -305,7 +305,8 @@
|
||||
},
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样",
|
||||
"err.runtime_changed": "启动期间运行时已切换,再次启动即可使用所选版本。",
|
||||
"err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR",
|
||||
"err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。",
|
||||
"runtime.qemu_aslr.warning": "本次启动未能确认 QEMU 的 ASLR 设置。可在「内核」页关闭再开启 ASLR 以重试。",
|
||||
"err.macos.disabled": "「macOS 虚拟机支持」插件已停用,请先在插件页启用",
|
||||
"err.vm_not_running": "虚拟机 {name} 未运行",
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
@@ -35,6 +36,9 @@ func main() {
|
||||
if len(args) == 3 && args[0] == host.QEMUASLRHelperArg {
|
||||
if err := host.ApplyQEMUASLR(args[1], args[2]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
if errors.Is(err, host.ErrQEMUASLRImagePolicy) {
|
||||
os.Exit(host.QEMUASLRImagePolicyExitCode)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user