fix(windows): make installer upgrades version aware
This commit is contained in:
1 parent
6906ed52f2
commit
ee7844cb40
14 files changed
+824
-51
No files matched your search
@@ -1,6 +1,50 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
||||
)
|
||||
|
||||
type installerSnapshot struct {
|
||||
Installed bool
|
||||
SameVersion bool
|
||||
ServiceState windowsservice.State
|
||||
TrayReady bool
|
||||
}
|
||||
|
||||
type installerActions struct {
|
||||
Inspect func() (installerSnapshot, error)
|
||||
Install func() error
|
||||
StartService func() error
|
||||
StartTray func() error
|
||||
}
|
||||
|
||||
// A true result means a fresh install/upgrade completed and may show its one
|
||||
// success dialog. Same-version activation and the healthy no-op stay silent.
|
||||
func ensureInstallerRunning(actions installerActions) (bool, error) {
|
||||
state, err := actions.Inspect()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("inspect installed RVBox: %w", err)
|
||||
}
|
||||
if !state.Installed || !state.SameVersion {
|
||||
if err := runInstallerSteps(actions.Install, actions.StartTray); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if state.ServiceState != windowsservice.StateRunning {
|
||||
if err := actions.StartService(); err != nil {
|
||||
return false, fmt.Errorf("start installed RVBox service: %w", err)
|
||||
}
|
||||
}
|
||||
if !state.TrayReady {
|
||||
if err := actions.StartTray(); err != nil {
|
||||
return false, fmt.Errorf("start installed notification-area icon: %w", err)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Keep the original (normally unelevated) interactive process alive while its
|
||||
// UAC child installs. Only successful installation may start the user frontend.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
||||
)
|
||||
|
||||
func TestInstallerVersionAwareLifecycle_HP_WINCLI_10(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
state installerSnapshot
|
||||
want []string
|
||||
installed bool
|
||||
}{
|
||||
{"fresh", installerSnapshot{}, []string{"inspect", "install", "tray"}, true},
|
||||
{"upgrade", installerSnapshot{Installed: true, ServiceState: windowsservice.StateRunning, TrayReady: true}, []string{"inspect", "install", "tray"}, true},
|
||||
{"healthy same version", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateRunning, TrayReady: true}, []string{"inspect"}, false},
|
||||
{"missing tray only", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateRunning}, []string{"inspect", "tray"}, false},
|
||||
{"stopped with tray", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateStopped, TrayReady: true}, []string{"inspect", "start"}, false},
|
||||
{"stopped without tray", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateStopped}, []string{"inspect", "start", "tray"}, false},
|
||||
{"starting", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateStartPending, TrayReady: true}, []string{"inspect", "start"}, false},
|
||||
{"stopping", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StateStopPending}, []string{"inspect", "start", "tray"}, false},
|
||||
{"paused", installerSnapshot{Installed: true, SameVersion: true, ServiceState: windowsservice.StatePaused}, []string{"inspect", "start", "tray"}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var calls []string
|
||||
installed, err := ensureInstallerRunning(installerActions{
|
||||
Inspect: func() (installerSnapshot, error) { calls = append(calls, "inspect"); return tc.state, nil },
|
||||
Install: func() error { calls = append(calls, "install"); return nil },
|
||||
StartService: func() error { calls = append(calls, "start"); return nil },
|
||||
StartTray: func() error { calls = append(calls, "tray"); return nil },
|
||||
})
|
||||
if err != nil || installed != tc.installed || !reflect.DeepEqual(calls, tc.want) {
|
||||
t.Fatalf("installed=%v calls=%v err=%v", installed, calls, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerActivationFailureStopsBeforeTray_BH_WINCLI_03(t *testing.T) {
|
||||
want := errors.New("UAC cancelled")
|
||||
trayCalled := false
|
||||
_, err := ensureInstallerRunning(installerActions{
|
||||
Inspect: func() (installerSnapshot, error) { return installerSnapshot{Installed: true, SameVersion: true}, nil },
|
||||
StartService: func() error { return want },
|
||||
StartTray: func() error { trayCalled = true; return nil },
|
||||
})
|
||||
if !errors.Is(err, want) || trayCalled {
|
||||
t.Fatalf("err=%v trayCalled=%v", err, trayCalled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerInspectionFailureDoesNotMutate_BH_WINCLI_04(t *testing.T) {
|
||||
want := errors.New("cannot inspect service")
|
||||
mutated := false
|
||||
mutate := func() error { mutated = true; return nil }
|
||||
_, err := ensureInstallerRunning(installerActions{Inspect: func() (installerSnapshot, error) { return installerSnapshot{}, want }, Install: mutate, StartService: mutate, StartTray: mutate})
|
||||
if !errors.Is(err, want) || mutated {
|
||||
t.Fatalf("err=%v mutated=%v", err, mutated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerVersionMetadataAndHashFallback_HP_WINCLI_11(t *testing.T) {
|
||||
source, target := filepath.Join(t.TempDir(), "source.exe"), filepath.Join(t.TempDir(), "target.exe")
|
||||
if err := os.WriteFile(source, []byte("candidate"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, sourceVersion, targetVersion, body string
|
||||
metadataErr bool
|
||||
want bool
|
||||
}{
|
||||
{"same release", "1.2.3", "1.2.3", "signed differently", false, true},
|
||||
{"different release", "1.2.4", "1.2.3", "candidate", false, false},
|
||||
{"missing metadata identical", "", "", "candidate", true, true},
|
||||
{"missing metadata differs", "", "", "old binary", true, false},
|
||||
{"dev identical", "dev", "dev", "candidate", false, true},
|
||||
{"dev differs", "dev", "dev", "old binary", false, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := os.WriteFile(target, []byte(tc.body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same, err := sameInstallerVersion(source, target, func(path string) (string, error) {
|
||||
if tc.metadataErr {
|
||||
return "", errors.New("no version resource")
|
||||
}
|
||||
if path == source {
|
||||
return tc.sourceVersion, nil
|
||||
}
|
||||
return tc.targetVersion, nil
|
||||
})
|
||||
if err != nil || same != tc.want {
|
||||
t.Fatalf("same=%v err=%v", same, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := os.Remove(target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if same, err := sameInstallerVersion(source, target, func(string) (string, error) { t.Fatal("missing file metadata read"); return "", nil }); err != nil || same {
|
||||
t.Fatalf("missing file same=%v err=%v", same, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
||||
"github.com/rvbox/rvbox/internal/client/windowstray"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func installedClientPaths(status windowsservice.Status) (string, string, error) {
|
||||
if !status.Installed {
|
||||
executable, config := packagedInstallPaths()
|
||||
return executable, config, nil
|
||||
}
|
||||
spec := windowsservice.InstallSpec{ExecutablePath: status.ExecutablePath, ConfigPath: status.ConfigPath, Startup: windowsservice.StartupAutomatic}
|
||||
if err := spec.Validate(); err != nil {
|
||||
return "", "", fmt.Errorf("installed service image/config paths: %w", err)
|
||||
}
|
||||
return status.ExecutablePath, status.ConfigPath, nil
|
||||
}
|
||||
|
||||
func inspectInstalledClient(source string) (installerSnapshot, error) {
|
||||
status, err := windowsservice.Query()
|
||||
if err != nil {
|
||||
return installerSnapshot{}, err
|
||||
}
|
||||
executable, configPath, err := installedClientPaths(status)
|
||||
if err != nil {
|
||||
return installerSnapshot{}, err
|
||||
}
|
||||
state := installerSnapshot{Installed: status.Installed, ServiceState: status.State, TrayReady: windowstray.IsReady()}
|
||||
if !status.Installed {
|
||||
return state, nil
|
||||
}
|
||||
if _, err := os.Stat(configPath); errors.Is(err, os.ErrNotExist) {
|
||||
state.Installed = false
|
||||
return state, nil
|
||||
} else if err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.SameVersion, err = sameInstallerVersion(source, executable, installerProductVersion)
|
||||
return state, err
|
||||
}
|
||||
|
||||
func startInstalledService() error {
|
||||
if err := windowsservice.Start(); err == nil {
|
||||
return nil
|
||||
} else if !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||
return err
|
||||
}
|
||||
status, err := windowsservice.Query()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
executable, _, err := installedClientPaths(status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runElevatedSetup(executable, "--start-service")
|
||||
}
|
||||
|
||||
// This parent-only mutex spans inspection and the UAC child, not its result
|
||||
// dialog. A second double-click exits quietly while the first setup is active.
|
||||
func acquireInstallerMutex() (func(), bool, error) {
|
||||
descriptor, err := windows.SecurityDescriptorFromString("D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x00100001;;;IU)")
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
attributes := &windows.SecurityAttributes{Length: uint32(unsafe.Sizeof(windows.SecurityAttributes{})), SecurityDescriptor: descriptor}
|
||||
name, _ := windows.UTF16PtrFromString(`Global\RVBoxInteractiveInstallerV1`)
|
||||
handle, err := windows.CreateMutexEx(attributes, name, 0, windows.SYNCHRONIZE|windows.MUTEX_MODIFY_STATE)
|
||||
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
|
||||
return nil, false, err
|
||||
}
|
||||
result, err := windows.WaitForSingleObject(handle, 0)
|
||||
if err != nil {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return nil, false, err
|
||||
}
|
||||
if result == uint32(windows.WAIT_TIMEOUT) {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return func() {}, false, nil
|
||||
}
|
||||
if result != windows.WAIT_OBJECT_0 && result != windows.WAIT_ABANDONED {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return nil, false, fmt.Errorf("installer mutex wait: %d", result)
|
||||
}
|
||||
return func() { _ = windows.ReleaseMutex(handle); _ = windows.CloseHandle(handle) }, true, nil
|
||||
}
|
||||
|
||||
// Read the string resource so prerelease labels remain distinct even when
|
||||
// their numeric VS_FIXEDFILEINFO versions match. Never execute the old binary.
|
||||
func installerProductVersion(path string) (string, error) {
|
||||
size, err := windows.GetFileVersionInfoSize(path, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if size == 0 || size > 1<<20 {
|
||||
return "", errors.New("invalid executable version resource size")
|
||||
}
|
||||
buffer := make([]byte, size)
|
||||
if err := windows.GetFileVersionInfo(path, 0, size, unsafe.Pointer(&buffer[0])); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var translations *byte
|
||||
var length uint32
|
||||
if err := windows.VerQueryValue(unsafe.Pointer(&buffer[0]), `\VarFileInfo\Translation`, unsafe.Pointer(&translations), &length); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if translations == nil || length < 4 || length%4 != 0 || length > size {
|
||||
return "", errors.New("invalid executable version translations")
|
||||
}
|
||||
values := unsafe.Slice(translations, length)
|
||||
for i := 0; i < len(values); i += 4 {
|
||||
lang, page := binary.LittleEndian.Uint16(values[i:]), binary.LittleEndian.Uint16(values[i+2:])
|
||||
query := fmt.Sprintf(`\StringFileInfo\%04x%04x\ProductVersion`, lang, page)
|
||||
var value *uint16
|
||||
var units uint32
|
||||
if err := windows.VerQueryValue(unsafe.Pointer(&buffer[0]), query, unsafe.Pointer(&value), &units); err != nil {
|
||||
continue
|
||||
}
|
||||
if value != nil && units > 0 && uint64(units)*2 <= uint64(size) {
|
||||
if result := strings.TrimSpace(windows.UTF16ToString(unsafe.Slice(value, units))); result != "" {
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", errors.New("executable has no ProductVersion")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Version resources identify packaged releases without starting the installed
|
||||
// executable. Builds without usable metadata fall back to exact file identity,
|
||||
// so two different unversioned/development binaries are never mistaken as equal.
|
||||
func sameInstallerVersion(source, target string, version func(string) (string, error)) (bool, error) {
|
||||
if _, err := os.Stat(target); errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
sourceVersion, sourceErr := version(source)
|
||||
targetVersion, targetErr := version(target)
|
||||
if sourceErr == nil && targetErr == nil && sourceVersion != "" && sourceVersion != "dev" && targetVersion != "" && targetVersion != "dev" {
|
||||
return sourceVersion == targetVersion, nil
|
||||
}
|
||||
sourceHash, err := installerFileHash(source)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
targetHash, err := installerFileHash(target)
|
||||
return err == nil && sourceHash == targetHash, err
|
||||
}
|
||||
|
||||
func installerFileHash(path string) ([32]byte, error) {
|
||||
var digest [32]byte
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return digest, err
|
||||
}
|
||||
defer file.Close()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return digest, err
|
||||
}
|
||||
copy(digest[:], hash.Sum(nil))
|
||||
return digest, nil
|
||||
}
|
||||
+144
-19
@@ -34,21 +34,49 @@ var (
|
||||
installerCOMUninitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoUninitialize")
|
||||
)
|
||||
|
||||
// runInteractiveInstaller is the double-click entry point. It does no
|
||||
// machine-wide mutation itself: ShellExecute's runas verb causes Windows to
|
||||
// show the standard UAC consent prompt before the elevated child installs.
|
||||
// runInteractiveInstaller is the double-click entry point. It inspects first,
|
||||
// requesting UAC only for installation/replacement or protected service start.
|
||||
func runInteractiveInstaller(_ io.Writer, _ io.Writer) error {
|
||||
runtime.LockOSThread() // Named mutex ownership is tied to this OS thread.
|
||||
defer runtime.UnlockOSThread()
|
||||
release, acquired, err := acquireInstallerMutex()
|
||||
if err != nil {
|
||||
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||
return err
|
||||
}
|
||||
if !acquired {
|
||||
return nil
|
||||
}
|
||||
defer func() { release() }()
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
showInstallerMessage("RVBox setup could not locate its executable.", installerErrorIcon)
|
||||
return err
|
||||
}
|
||||
err = runInstallerSteps(func() error { return runElevatedInstaller(executable) }, startInstalledTray)
|
||||
installed, err := ensureInstallerRunning(installerActions{
|
||||
Inspect: func() (installerSnapshot, error) { return inspectInstalledClient(executable) },
|
||||
Install: func() error { return runElevatedInstaller(executable) },
|
||||
StartService: startInstalledService, StartTray: startInstalledTray,
|
||||
})
|
||||
release()
|
||||
release = func() {}
|
||||
if err != nil {
|
||||
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||
return err
|
||||
}
|
||||
if !installed {
|
||||
return nil
|
||||
}
|
||||
status, err := windowsservice.Query()
|
||||
if err != nil {
|
||||
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||
return err
|
||||
}
|
||||
_, configPath, err := installedClientPaths(status)
|
||||
if err != nil {
|
||||
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||
return err
|
||||
}
|
||||
_, configPath := packagedInstallPaths()
|
||||
message, err := installerSuccessMessage(configPath)
|
||||
if err != nil {
|
||||
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||
@@ -83,6 +111,10 @@ func runElevatedInstaller(executable string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("identify installing user: %w", err)
|
||||
}
|
||||
return runElevatedSetup(executable, "--install-default --config-user-sid "+userSID.String())
|
||||
}
|
||||
|
||||
func runElevatedSetup(executable, parameters string) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
// Shell extensions may require COM. Balance both S_OK and S_FALSE, while
|
||||
@@ -101,7 +133,7 @@ func runElevatedInstaller(executable string) error {
|
||||
Size: uint32(unsafe.Sizeof(shellExecuteInfo{})),
|
||||
Mask: 0x40 | 0x100, // SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC.
|
||||
Verb: installerUTF16("runas"), File: file,
|
||||
Parameters: installerUTF16("--install-default --config-user-sid " + userSID.String()), Show: windows.SW_SHOWNORMAL,
|
||||
Parameters: installerUTF16(parameters), Show: windows.SW_SHOWNORMAL,
|
||||
}
|
||||
result, _, callErr := installerShellExecute.Call(uintptr(unsafe.Pointer(&info)))
|
||||
if result == 0 {
|
||||
@@ -137,7 +169,17 @@ func packagedInstallPaths() (string, string) {
|
||||
}
|
||||
|
||||
func startInstalledTray() error {
|
||||
executable, configPath := packagedInstallPaths()
|
||||
if windowstray.IsReady() {
|
||||
return nil
|
||||
}
|
||||
status, err := windowsservice.Query()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
executable, configPath, err := installedClientPaths(status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
command := exec.Command(executable, "--tray", "--config", configPath)
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
@@ -162,7 +204,7 @@ func installPackagedDefault(userSID string, _ io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func installPackagedDefaultFiles(userSID string) error {
|
||||
func installPackagedDefaultFiles(userSID string) (resultErr error) {
|
||||
if strings.TrimSpace(bootstrapServerURL) == "" {
|
||||
return errors.New("this RVBox package was built without a bootstrap server URL")
|
||||
}
|
||||
@@ -174,9 +216,68 @@ func installPackagedDefaultFiles(userSID string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("locate installer executable: %w", err)
|
||||
}
|
||||
targetExecutable, configPath := packagedInstallPaths()
|
||||
status, err := windowsservice.Query()
|
||||
if err != nil {
|
||||
return fmt.Errorf("inspect existing RVBox service: %w", err)
|
||||
}
|
||||
targetExecutable, configPath, err := installedClientPaths(status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Recheck after UAC: another setup may have completed before elevation.
|
||||
if status.Installed {
|
||||
same, versionErr := sameInstallerVersion(source, targetExecutable, installerProductVersion)
|
||||
if versionErr != nil {
|
||||
return versionErr
|
||||
}
|
||||
if same {
|
||||
if _, err := os.Stat(configPath); err == nil {
|
||||
return windowsservice.Start()
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
// Validate an existing operator config with this candidate's parser before
|
||||
// stopping the old service. A new/removed key must not strand a working install.
|
||||
if _, err := os.Stat(configPath); err == nil {
|
||||
if _, err := loadClientConfig(configPath); err != nil {
|
||||
return fmt.Errorf("existing configuration is incompatible with this version: %w", err)
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("inspect existing configuration: %w", err)
|
||||
}
|
||||
startup := status.Startup
|
||||
if startup != windowsservice.StartupManual && startup != windowsservice.StartupAutomatic {
|
||||
startup = windowsservice.StartupAutomatic
|
||||
}
|
||||
targetDirectory, configDirectory := filepath.Dir(targetExecutable), filepath.Dir(configPath)
|
||||
trayCtx, cancelTray := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
backup := targetExecutable + ".previous"
|
||||
backupReady, replaced := false, false
|
||||
defer func() {
|
||||
if resultErr == nil {
|
||||
if backupReady {
|
||||
_ = os.Remove(backup)
|
||||
}
|
||||
return
|
||||
}
|
||||
if replaced && backupReady {
|
||||
if err := windowsservice.Stop(30); err != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("stop failed upgrade before rollback: %w", err))
|
||||
return
|
||||
}
|
||||
if err := activateInstallerExecutable(backup, targetExecutable); err != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("restore previous executable: %w", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
if status.Installed && status.State == windowsservice.StateRunning {
|
||||
if err := windowsservice.Start(); err != nil {
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("restart previous service: %w", err))
|
||||
}
|
||||
}
|
||||
}()
|
||||
trayCtx, cancelTray := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancelTray()
|
||||
if err := windowstray.CloseCurrent(trayCtx); err != nil {
|
||||
return fmt.Errorf("close existing notification-area frontend: %w", err)
|
||||
@@ -191,9 +292,20 @@ func installPackagedDefaultFiles(userSID string) error {
|
||||
return fmt.Errorf("create installation directory: %w", err)
|
||||
}
|
||||
if !sameWindowsPath(source, targetExecutable) {
|
||||
if status.Installed {
|
||||
if _, err := os.Stat(targetExecutable); err == nil {
|
||||
if err := copyInstallerExecutable(targetExecutable, backup); err != nil {
|
||||
return fmt.Errorf("preserve previous executable: %w", err)
|
||||
}
|
||||
backupReady = true
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := copyInstallerExecutable(source, targetExecutable); err != nil {
|
||||
return err
|
||||
}
|
||||
replaced = true
|
||||
}
|
||||
if err := os.MkdirAll(configDirectory, 0o700); err != nil {
|
||||
return fmt.Errorf("create configuration directory: %w", err)
|
||||
@@ -218,7 +330,7 @@ func installPackagedDefaultFiles(userSID string) error {
|
||||
if err := protectMachineConfig(configPath, configUser); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: targetExecutable, ConfigPath: configPath, Startup: windowsservice.StartupAutomatic}); err != nil {
|
||||
if err := windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: targetExecutable, ConfigPath: configPath, Startup: startup}); err != nil {
|
||||
return fmt.Errorf("install and start RVBox service: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -247,19 +359,32 @@ func copyInstallerExecutable(source, target string) error {
|
||||
_ = os.Remove(temporary)
|
||||
return fmt.Errorf("copy installer executable: %w", copyErr)
|
||||
}
|
||||
from, fromErr := windows.UTF16PtrFromString(temporary)
|
||||
to, toErr := windows.UTF16PtrFromString(target)
|
||||
if fromErr != nil || toErr != nil {
|
||||
if err := activateInstallerExecutable(temporary, target); err != nil {
|
||||
_ = os.Remove(temporary)
|
||||
return errors.New("encode replacement executable path")
|
||||
}
|
||||
if err := windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH); err != nil {
|
||||
_ = os.Remove(temporary)
|
||||
return fmt.Errorf("activate replacement executable: %w", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func activateInstallerExecutable(source, target string) error {
|
||||
from, fromErr := windows.UTF16PtrFromString(source)
|
||||
to, toErr := windows.UTF16PtrFromString(target)
|
||||
if fromErr != nil || toErr != nil {
|
||||
return errors.New("encode replacement executable path")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
err := windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !time.Now().Before(deadline) || (!errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED) && !errors.Is(err, windows.ERROR_LOCK_VIOLATION)) {
|
||||
return fmt.Errorf("activate replacement executable: %w", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func writeMachineConfig(path string, content []byte) error {
|
||||
temporary := path + ".new"
|
||||
_ = os.Remove(temporary)
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
||||
)
|
||||
|
||||
func TestInstallerShellExecuteInfoLayout_HP_WINCLI_07(t *testing.T) {
|
||||
@@ -71,3 +73,90 @@ func TestInstallerConfigUserSIDValidation_BH_WINCLI_02(t *testing.T) {
|
||||
t.Fatalf("original user SID lost across elevation: %v, %v", user, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerRetainsSCMInstallationPaths_HP_WINCLI_12(t *testing.T) {
|
||||
status := windowsservice.Status{Installed: true, ExecutablePath: `D:\Apps\RVBox\rvbox.exe`, ConfigPath: `D:\Data\RVBox\client.toml`, Startup: windowsservice.StartupManual}
|
||||
executable, config, err := installedClientPaths(status)
|
||||
if err != nil || executable != status.ExecutablePath || config != status.ConfigPath {
|
||||
t.Fatalf("paths=%q %q err=%v", executable, config, err)
|
||||
}
|
||||
status.ConfigPath = "relative.toml"
|
||||
if _, _, err := installedClientPaths(status); err == nil {
|
||||
t.Fatal("relative installed config accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerReadsPackagedVersionWithoutExecution_HP_WINCLI_13(t *testing.T) {
|
||||
path := os.Getenv("RVBOX_NATIVE_RELEASE_EXE")
|
||||
if path == "" {
|
||||
t.Skip("requires a packaged release executable")
|
||||
}
|
||||
want := os.Getenv("RVBOX_NATIVE_RELEASE_VERSION")
|
||||
if want == "" {
|
||||
t.Fatal("RVBOX_NATIVE_RELEASE_VERSION is required")
|
||||
}
|
||||
got, err := installerProductVersion(path)
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("ProductVersion=%q want=%q err=%v", got, want, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallerMutexExcludesConcurrentLaunch_HP_WINCLI_14(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
release, acquired, err := acquireInstallerMutex()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !acquired {
|
||||
t.Skip("another installer is active")
|
||||
}
|
||||
defer func() { release() }()
|
||||
type outcome struct {
|
||||
acquired bool
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 1)
|
||||
go func() {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
unlock, acquired, err := acquireInstallerMutex()
|
||||
if acquired {
|
||||
unlock()
|
||||
}
|
||||
done <- outcome{acquired, err}
|
||||
}()
|
||||
result := <-done
|
||||
if result.err != nil || result.acquired {
|
||||
t.Fatalf("concurrent acquisition=%v err=%v", result.acquired, result.err)
|
||||
}
|
||||
release()
|
||||
release = func() {}
|
||||
again, acquired, err := acquireInstallerMutex()
|
||||
if err != nil || !acquired {
|
||||
t.Fatalf("released mutex did not reopen: acquired=%v err=%v", acquired, err)
|
||||
}
|
||||
again()
|
||||
}
|
||||
|
||||
func TestInstallerReplacementPreservesOtherFiles_HP_WINCLI_15(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
source, target, config := filepath.Join(directory, "setup.exe"), filepath.Join(directory, "rvbox.exe"), filepath.Join(directory, "client.toml")
|
||||
for path, data := range map[string]string{source: "new executable", target: "old executable", config: "preserved configuration"} {
|
||||
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := copyInstallerExecutable(source, target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data, err := os.ReadFile(target); err != nil || string(data) != "new executable" {
|
||||
t.Fatalf("replacement=%q err=%v", data, err)
|
||||
}
|
||||
if data, err := os.ReadFile(config); err != nil || string(data) != "preserved configuration" {
|
||||
t.Fatalf("configuration=%q err=%v", data, err)
|
||||
}
|
||||
if _, err := os.Stat(target + ".new"); !os.IsNotExist(err) {
|
||||
t.Fatalf("staging file remains: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user