From ee7844cb4036fb89242dd91a215c1725786259f4 Mon Sep 17 00:00:00 2001 From: cabbage Date: Tue, 27 Oct 2026 15:17:52 +0000 Subject: [PATCH] fix(windows): make installer upgrades version aware --- cmd/rvbox/installer_flow.go | 46 ++++- cmd/rvbox/installer_lifecycle_test.go | 109 ++++++++++++ cmd/rvbox/installer_probe_windows.go | 137 +++++++++++++++ cmd/rvbox/installer_version.go | 45 +++++ cmd/rvbox/installer_windows.go | 163 ++++++++++++++++-- cmd/rvbox/installer_windows_test.go | 89 ++++++++++ docs/implementation-plan.v1.md | 40 +++++ docs/platform-and-operations.md | 24 +++ docs/testing.md | 32 ++++ internal/client/windowsservice/service.go | 8 +- .../client/windowsservice/service_windows.go | 59 ++++++- internal/client/windowstray/service_other.go | 2 + internal/client/windowstray/tray_windows.go | 73 +++++--- test/coverage.toml | 48 ++++++ 14 files changed, 824 insertions(+), 51 deletions(-) create mode 100644 cmd/rvbox/installer_lifecycle_test.go create mode 100644 cmd/rvbox/installer_probe_windows.go create mode 100644 cmd/rvbox/installer_version.go diff --git a/cmd/rvbox/installer_flow.go b/cmd/rvbox/installer_flow.go index ea2522e..9ad9787 100644 --- a/cmd/rvbox/installer_flow.go +++ b/cmd/rvbox/installer_flow.go @@ -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. diff --git a/cmd/rvbox/installer_lifecycle_test.go b/cmd/rvbox/installer_lifecycle_test.go new file mode 100644 index 0000000..ddf9ae9 --- /dev/null +++ b/cmd/rvbox/installer_lifecycle_test.go @@ -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) + } +} diff --git a/cmd/rvbox/installer_probe_windows.go b/cmd/rvbox/installer_probe_windows.go new file mode 100644 index 0000000..c9bd7b9 --- /dev/null +++ b/cmd/rvbox/installer_probe_windows.go @@ -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") +} diff --git a/cmd/rvbox/installer_version.go b/cmd/rvbox/installer_version.go new file mode 100644 index 0000000..94d62f3 --- /dev/null +++ b/cmd/rvbox/installer_version.go @@ -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 +} diff --git a/cmd/rvbox/installer_windows.go b/cmd/rvbox/installer_windows.go index 0f5793e..2118827 100644 --- a/cmd/rvbox/installer_windows.go +++ b/cmd/rvbox/installer_windows.go @@ -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) diff --git a/cmd/rvbox/installer_windows_test.go b/cmd/rvbox/installer_windows_test.go index 278dc59..3f50aee 100644 --- a/cmd/rvbox/installer_windows_test.go +++ b/cmd/rvbox/installer_windows_test.go @@ -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) + } +} diff --git a/docs/implementation-plan.v1.md b/docs/implementation-plan.v1.md index 8378ded..eec9b1c 100644 --- a/docs/implementation-plan.v1.md +++ b/docs/implementation-plan.v1.md @@ -2318,6 +2318,46 @@ equality check against `S_OK`: Explorer can return `S_FALSE` with valid icon coordinates. A failed/cancelled installation must not start a tray; failure to start the tray must explicitly report the already-installed service rather than claiming complete success. No sign-out or reboot is required. + +The interactive installer must inspect before mutating. Read the installed SCM +image command line with Windows argument decomposition, retaining its exact +executable and absolute config paths. Read the PE string `ProductVersion` +through `GetFileVersionInfo`/`VerQueryValue`, preserving prerelease labels; use +streamed SHA-256 equality when metadata is absent or `dev`. Never execute the +installed binary to query its version. Different release labels select the +replacement path; this is not a semantic version ordering/downgrade policy. + +- Same version, running service, registered tray on this desktop: return quietly + without UAC, dialogs, file changes, or service restart. +- Same version with a missing component: start the service only if not running, + requesting UAC only on access denied; start the tray only if its icon is + missing. Wait up to 30 seconds for SCM pending states to settle/start/resume. + Do not reinstall, change Automatic/Manual, or show installation success. +- Fresh/different version: hold an ACL-protected global installer mutex in the + original parent on its locked OS thread through inspection/UAC/tray readiness. + A concurrent interactive installer returns quietly; the elevated child never + reacquires the parent's mutex. Release it before showing a result dialog. + Recheck installed identity after UAC. Validate any existing TOML with the + candidate parser before stopping the old service. Send the old current-desktop + tray `WM_CLOSE` and wait up to ten seconds for process exit, then stop SCM. + Preserve the actual installed paths and Automatic/Manual setting. Stage/fsync + the new binary beside the target and activate with `MoveFileEx` replacement + plus write-through; retry sharing/access/lock errors for at most five seconds. + Preserve a `.previous` binary before replacement. If replacement/startup fails, + stop the failed service, restore that binary, and restart the prior service + when it was running. Surface rollback errors; do not claim schema rollback or + forcibly kill unrelated processes/other sessions' trays. Preserve TOML contents + and spool/history. Remove the backup after successful service installation, + start the user tray, then show the single minimal success message. + +Cover lifecycle decisions and failure short-circuiting in portable unit tests, +and SCM path preservation, actual version resources, concurrent mutex ownership, +and Win32 file replacement in native tests. Native acceptance must cover real +UAC, stopped/missing-tray activation, PID stability on a healthy same-version +launch, and upgrading an older package with existing data. When the fixture +host is offline, cross-compile these tests and explicitly leave native execution +for physical Windows/fixture testing; cross-compilation is not an acceptance pass. + Run its Win32 message pump on one locked OS thread, recreate the icon after `TaskbarCreated`, and use bounded nonblocking IPC/UI channels. Show a disabled `Status: ...` banner first in the context menu, with diff --git a/docs/platform-and-operations.md b/docs/platform-and-operations.md index adf95e8..2d52b02 100644 --- a/docs/platform-and-operations.md +++ b/docs/platform-and-operations.md @@ -91,6 +91,30 @@ not inject a tray into another session. One tray may run in each logged-in session; its exit, failure, disablement, or Explorer restart does not stop the service or commands. +Double-clicking an already-installed package first checks SCM and the current +desktop's tray. With the same version, a healthy service and visible tray cause +a silent no-op; otherwise it starts only the missing components. Starting a +stopped service requests UAC when required, while restoring just the tray does +not. Pending service transitions are bounded to 30 seconds. These activation +paths do not replace files, rewrite configuration, change startup mode, or show +an installation-success dialog. + +A different package version requests UAC, validates the existing TOML with the +candidate's config parser, gracefully closes this desktop's old tray and waits +for its process to exit, stops the SCM service, and atomically replaces its +executable. It preserves the actual SCM executable/config paths, TOML contents, +spool/history, and Automatic/Manual setting, then starts the service and tray. +Version identity uses the PE `ProductVersion` string, including prerelease +labels; missing/dev metadata falls back to SHA-256 file identity. A different +version is an explicit replacement, not an automatic newer-version comparison. +Concurrent interactive setup launches are serialized by a parent-owned global +mutex; another launch during setup exits quietly. Replacement retries transient +file locks for five seconds. A `.previous` executable backup enables best-effort +rollback if replacement/startup fails; an originally running service is restarted +with the prior binary. This is executable rollback, not a spool/schema downgrade +guarantee. Other sessions' trays are not forcibly terminated. Successful fresh +installation/upgrade shows only `Installed and is running on server `. + The executable uses the Windows GUI subsystem so service, tray, and internal helpers do not flash consoles. Human-invoked console modes such as `--check-config`, install, uninstall, and service configuration first call diff --git a/docs/testing.md b/docs/testing.md index e952864..e827b88 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -263,6 +263,38 @@ visible/responsive when its service is absent or its IPC peer stalls. Windows may put a new application icon under its hidden-icons arrow; do not rewrite the user's global notification-area preferences to force pinning. +Installer lifecycle regressions `HP-WINCLI-10/11` and `BH-WINCLI-03/04` run on +Linux: fresh/upgrade ordering, healthy same-version no-op, stopped/paused/pending +SCM states, missing tray, cancellation/inspection failure without subsequent +mutations, and version-string/hash identity. Native `HP-WINCLI-12..15` cover +SCM path retention, packaged PE version strings, concurrent installer exclusion, +and real Win32 executable replacement while retaining adjacent config contents. +Build `./cmd/rvbox` with `GOOS=windows GOARCH=amd64 go test -c` as a distinct +console test executable. To exercise the actual release resource, set +`RVBOX_NATIVE_RELEASE_EXE` to the package path and +`RVBOX_NATIVE_RELEASE_VERSION` to its full release label before running it; +otherwise that one case explicitly skips. + +On an interactive physical machine or disposable Windows fixture, test: + +1. Upgrade an older installed package. Confirm UAC, exactly one service and tray, + the new executable version, unchanged custom config/client identity/history + and Automatic/Manual setting, and the minimal success dialog. +2. Run that same package again with both components running. Require no UAC or + dialog and unchanged service/tray PIDs. It must not reinstall or rewrite files. +3. Exit only the tray and relaunch setup. Require a new tray with unchanged + service PID and no UAC. Stop the service and repeat with/without the tray; + require service start (UAC when necessary) and only a missing tray to start. +4. Cancel the service-start/upgrade UAC prompt. Require no replacement/new tray. + Launch two setups during UAC; the second must exit quietly. On a disposable + fixture, reject invalid existing TOML before stopping the working service and + exercise replacement/startup failure plus best-effort prior-binary recovery. + +These native lifecycle checks are pending for the new version-aware installer +while Helium is offline; passing portable tests and Windows cross-compilation +does not prove them. Retain the previous installer for recovery during physical +testing, and collect `service-startup.log` if service start fails. + Regression `BH-WINTRAY-06` checks successful HRESULTs (`S_OK` and `S_FALSE`) versus actual failures. On the Windows 10 fixture, the installed, responsive tray returned `S_FALSE` (`1`) with valid icon coordinates; a readiness check diff --git a/internal/client/windowsservice/service.go b/internal/client/windowsservice/service.go index b60d22e..502a193 100644 --- a/internal/client/windowsservice/service.go +++ b/internal/client/windowsservice/service.go @@ -70,9 +70,11 @@ const ( // Status is read-only SCM state. Query never requests service mutation rights. type Status struct { - Installed bool - State State - Startup StartupMode + Installed bool + State State + Startup StartupMode + ExecutablePath string + ConfigPath string } type Command uint8 diff --git a/internal/client/windowsservice/service_windows.go b/internal/client/windowsservice/service_windows.go index eeac0fc..a8c3e1e 100644 --- a/internal/client/windowsservice/service_windows.go +++ b/internal/client/windowsservice/service_windows.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "strings" "syscall" "time" @@ -62,7 +63,21 @@ func queryNative() (Status, error) { } else if configuration.StartType == mgr.StartManual { startup = StartupManual } - return Status{Installed: true, State: state, Startup: startup}, nil + result := Status{Installed: true, State: state, Startup: startup} + if args, err := windows.DecomposeCommandLine(configuration.BinaryPathName); err == nil && len(args) > 0 { + result.ExecutablePath = args[0] + for i := 1; i < len(args); i++ { + if args[i] == "--config" && i+1 < len(args) { + result.ConfigPath = args[i+1] + break + } + if strings.HasPrefix(args[i], "--config=") { + result.ConfigPath = strings.TrimPrefix(args[i], "--config=") + break + } + } + } + return result, nil } func installNative(spec InstallSpec) error { @@ -111,7 +126,7 @@ func installNative(spec InstallSpec) error { } } defer service.Close() - if err := service.Start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { + if err := ensureServiceRunning(service, 30*time.Second); err != nil { return fmt.Errorf("start %s service: %w", Name, err) } if err := registerTray(spec); err != nil { @@ -224,10 +239,44 @@ func startNative() error { return err } defer service.Close() - if err := service.Start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { - return err + return ensureServiceRunning(service, 30*time.Second) +} + +func ensureServiceRunning(service *mgr.Service, timeout time.Duration) error { + deadline := time.Now().Add(timeout) + issued := false + for { + status, err := service.Query() + if err != nil { + return err + } + switch status.State { + case svc.Running: + return nil + case svc.Stopped: + if issued { + return errors.New("RVBox service stopped while starting; inspect service-startup.log") + } + if err := service.Start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { + return err + } + issued = true + case svc.Paused: + if !issued { + if _, err := service.Control(svc.Continue); err != nil { + return err + } + issued = true + } + case svc.StartPending, svc.StopPending, svc.ContinuePending, svc.PausePending: + default: + return errors.New("RVBox service is in an unsupported startup state") + } + if !time.Now().Before(deadline) { + return errors.New("timed out waiting for RVBox service to run") + } + time.Sleep(100 * time.Millisecond) } - return nil } func stopNative(timeoutSeconds uint32) error { diff --git a/internal/client/windowstray/service_other.go b/internal/client/windowstray/service_other.go index 8f07f89..92b2062 100644 --- a/internal/client/windowstray/service_other.go +++ b/internal/client/windowstray/service_other.go @@ -21,4 +21,6 @@ func Run(context.Context, string, io.Writer) error { return ErrUnsupported } func WaitReady(context.Context) error { return ErrUnsupported } +func IsReady() bool { return false } + func CloseCurrent(context.Context) error { return ErrUnsupported } diff --git a/internal/client/windowstray/tray_windows.go b/internal/client/windowstray/tray_windows.go index bf13dbc..d73d1c5 100644 --- a/internal/client/windowstray/tray_windows.go +++ b/internal/client/windowstray/tray_windows.go @@ -493,25 +493,11 @@ func (window *trayWindow) applyResponse() { // session. It confirms Shell has accepted an actual icon, not merely that a // child process was spawned. It never opens daemon config or state. func WaitReady(ctx context.Context) error { - class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1") - type identifier struct { - Size uint32 - HWnd uintptr - UID uint32 - GUID [16]byte - } - type rectangle struct{ Left, Top, Right, Bottom int32 } timer := time.NewTicker(50 * time.Millisecond) defer timer.Stop() for { - hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0) - if hwnd != 0 { - id := identifier{Size: uint32(unsafe.Sizeof(identifier{})), HWnd: hwnd, UID: trayIconID} - var rect rectangle - result, _, _ := procShellIconRect.Call(uintptr(unsafe.Pointer(&id)), uintptr(unsafe.Pointer(&rect))) - if iconQuerySucceeded(result) { - return nil - } + if IsReady() { + return nil } select { case <-ctx.Done(): @@ -521,23 +507,64 @@ func WaitReady(ctx context.Context) error { } } +// IsReady probes this desktop once; it neither contacts SCM nor starts a tray. +func IsReady() bool { + class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1") + type identifier struct { + Size uint32 + HWnd uintptr + UID uint32 + GUID [16]byte + } + type rectangle struct{ Left, Top, Right, Bottom int32 } + hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0) + if hwnd != 0 { + id := identifier{Size: uint32(unsafe.Sizeof(identifier{})), HWnd: hwnd, UID: trayIconID} + var rect rectangle + result, _, _ := procShellIconRect.Call(uintptr(unsafe.Pointer(&id)), uintptr(unsafe.Pointer(&rect))) + if iconQuerySucceeded(result) { + return true + } + } + return false +} + // CloseCurrent lets an elevated installer update the canonical executable // without leaving this desktop's old frontend holding the image open. It is -// deliberately a same-session window message, not service session injection. +// a same-session window message followed by waiting for process exit. func CloseCurrent(ctx context.Context) error { class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1") - timer := time.NewTicker(50 * time.Millisecond) - defer timer.Stop() for { + if err := ctx.Err(); err != nil { + return err + } hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0) if hwnd == 0 { return nil } + var pid uint32 + _, _, _ = user32Tray.NewProc("GetWindowThreadProcessId").Call(hwnd, uintptr(unsafe.Pointer(&pid))) + process, err := winapi.OpenProcess(winapi.SYNCHRONIZE, false, pid) + if err != nil { + if errors.Is(err, winapi.ERROR_INVALID_PARAMETER) { + continue + } + return fmt.Errorf("wait for old tray process: %w", err) + } _, _, _ = procPostMessage.Call(hwnd, wmClose, 0, 0) - select { - case <-ctx.Done(): - return ctx.Err() - case <-timer.C: + for { + result, waitErr := winapi.WaitForSingleObject(process, 50) + if waitErr != nil || result == winapi.WAIT_OBJECT_0 { + _ = winapi.CloseHandle(process) + if waitErr != nil { + return waitErr + } + break + } + if ctx.Err() != nil { + _ = winapi.CloseHandle(process) + return ctx.Err() + } } } } diff --git a/test/coverage.toml b/test/coverage.toml index 39791c5..7392caf 100644 --- a/test/coverage.toml +++ b/test/coverage.toml @@ -1,5 +1,53 @@ version = 1 +[[requirements]] +id = "HP-WINCLI-10" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_lifecycle_test.go:TestInstallerVersionAwareLifecycle_HP_WINCLI_10"] + +[[requirements]] +id = "HP-WINCLI-11" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_lifecycle_test.go:TestInstallerVersionMetadataAndHashFallback_HP_WINCLI_11"] + +[[requirements]] +id = "BH-WINCLI-03" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_lifecycle_test.go:TestInstallerActivationFailureStopsBeforeTray_BH_WINCLI_03"] + +[[requirements]] +id = "BH-WINCLI-04" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_lifecycle_test.go:TestInstallerInspectionFailureDoesNotMutate_BH_WINCLI_04"] + +[[requirements]] +id = "HP-WINCLI-12" +layer = "unit" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerRetainsSCMInstallationPaths_HP_WINCLI_12"] + +[[requirements]] +id = "HP-WINCLI-13" +layer = "integration" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerReadsPackagedVersionWithoutExecution_HP_WINCLI_13"] + +[[requirements]] +id = "HP-WINCLI-14" +layer = "integration" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerMutexExcludesConcurrentLaunch_HP_WINCLI_14"] + +[[requirements]] +id = "HP-WINCLI-15" +layer = "integration" +status = "implemented" +tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerReplacementPreservesOtherFiles_HP_WINCLI_15"] + [[requirements]] id = "HP-WINTRAY-05" layer = "unit"