Files
Reims-Go/internal/runtime/selection.go

208 lines
6.0 KiB
Go

package runtime
import (
"context"
"errors"
"fmt"
"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, 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, 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 := loadSelection(cfg)
if err != nil {
return err
}
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
return nil
}
// SavePreferences keeps an unrelated GUI edit from overwriting a CLI switch.
func SavePreferences(cfg *config.Config) error {
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return err
}
defer release()
if err := RefreshSelection(cfg); err != nil {
return err
}
return config.Save("", cfg)
}
func QEMUASLRPath(cfg *config.Config) (string, error) {
if !cfg.QEMUASLR {
return "", nil
}
active, err := ResolveActive(cfg)
if errors.Is(err, ErrNoActiveRuntime) {
return "", nil // The first runtime install will apply the preference.
}
if err != nil {
return "", err
}
return active.QemuPath(), nil
}
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 config.Config{}, err
}
saved.DataRoot = cfg.DataRoot
return *saved, nil
}
func requestedSelection(next config.Config, commit string, aslr *bool) (config.Config, error) {
if aslr != nil {
next.QEMUASLR = *aslr
} else {
installed, err := List(&next)
if err != nil {
return next, err
}
if !slices.ContainsFunc(installed, func(r Installed) bool {
return r.Commit == commit || r.Kind+"/"+r.Commit == commit
}) {
return next, fmt.Errorf("%w: %s", ErrNotFound, commit)
}
next.ActiveRuntime = commit
}
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))
}