91 lines
2.6 KiB
Go
91 lines
2.6 KiB
Go
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
|
|
}
|