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

106 lines
3.0 KiB
Go

package runtime
import (
"context"
"errors"
"fmt"
"io"
"runtime"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
// CheckLaunchASLR repairs the selected runtime's rule after a data folder
// move and avoids reactivating a version superseded during launch prep.
func CheckLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, warnings io.Writer) error {
if runtime.GOOS != "windows" {
return ctx.Err()
}
return checkLaunchASLR(ctx, cfg, qemuPath, warnings, host.ApplyQEMUASLR)
}
func checkLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, warnings io.Writer, apply func(string, string) error) error {
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
}
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
}
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(), active.QemuPath()); err != nil {
return warn(QEMUASLRPolicyError(&cfg, err))
}
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
}