292 lines
9.8 KiB
Go
292 lines
9.8 KiB
Go
//go:build windows
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
|
"github.com/rvbox/rvbox/internal/client/windowstray"
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
const (
|
|
installerInfoIcon = 0x00000040
|
|
installerErrorIcon = 0x00000010
|
|
)
|
|
|
|
var (
|
|
installerUser32 = syscall.NewLazyDLL("user32.dll")
|
|
installerMessageBox = installerUser32.NewProc("MessageBoxW")
|
|
installerShellExecute = windows.NewLazySystemDLL("shell32.dll").NewProc("ShellExecuteExW")
|
|
installerCOMInitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoInitializeEx")
|
|
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.
|
|
func runInteractiveInstaller(_ io.Writer, _ io.Writer) error {
|
|
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)
|
|
if err != nil {
|
|
showInstallerMessage(err.Error(), installerErrorIcon)
|
|
return err
|
|
}
|
|
showInstallerMessage("RVBox is installed and its Windows service has started.\n\nThe notification-area icon is available now; no sign-out or reboot is needed. Windows may place it under the hidden-icons arrow.", installerInfoIcon)
|
|
return nil
|
|
}
|
|
|
|
// shellExecuteInfo matches SHELLEXECUTEINFOW, including pointer-sized fields
|
|
// and native alignment on the supported Windows amd64 build.
|
|
type shellExecuteInfo struct {
|
|
Size uint32
|
|
Mask uint32
|
|
Window uintptr
|
|
Verb *uint16
|
|
File *uint16
|
|
Parameters *uint16
|
|
Directory *uint16
|
|
Show int32
|
|
Instance uintptr
|
|
IDList uintptr
|
|
Class *uint16
|
|
ClassKey uintptr
|
|
HotKey uint32
|
|
Icon uintptr
|
|
Process windows.Handle
|
|
}
|
|
|
|
func runElevatedInstaller(executable string) error {
|
|
runtime.LockOSThread()
|
|
defer runtime.UnlockOSThread()
|
|
// Shell extensions may require COM. Balance both S_OK and S_FALSE, while
|
|
// allowing a caller whose thread is already initialized in another mode.
|
|
hr, _, _ := installerCOMInitialize.Call(0, 2|4) // STA, disable OLE1 DDE.
|
|
if int32(hr) >= 0 {
|
|
defer installerCOMUninitialize.Call()
|
|
} else if uint32(hr) != 0x80010106 { // RPC_E_CHANGED_MODE
|
|
return fmt.Errorf("initialize setup shell: HRESULT %#x", uint32(hr))
|
|
}
|
|
file, err := windows.UTF16PtrFromString(executable)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
info := shellExecuteInfo{
|
|
Size: uint32(unsafe.Sizeof(shellExecuteInfo{})),
|
|
Mask: 0x40 | 0x100, // SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC.
|
|
Verb: installerUTF16("runas"), File: file,
|
|
Parameters: installerUTF16("--install-default"), Show: windows.SW_SHOWNORMAL,
|
|
}
|
|
result, _, callErr := installerShellExecute.Call(uintptr(unsafe.Pointer(&info)))
|
|
if result == 0 {
|
|
return fmt.Errorf("request installer elevation: %w", callErr)
|
|
}
|
|
if info.Process == 0 {
|
|
return errors.New("elevated setup did not return a process handle")
|
|
}
|
|
defer windows.CloseHandle(info.Process)
|
|
if _, err := windows.WaitForSingleObject(info.Process, windows.INFINITE); err != nil {
|
|
return fmt.Errorf("wait for elevated setup: %w", err)
|
|
}
|
|
var exitCode uint32
|
|
if err := windows.GetExitCodeProcess(info.Process, &exitCode); err != nil {
|
|
return fmt.Errorf("read elevated setup result: %w", err)
|
|
}
|
|
if exitCode != 0 {
|
|
return fmt.Errorf("elevated setup failed (exit code %d)", exitCode)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func packagedInstallPaths() (string, string) {
|
|
programFiles := os.Getenv("ProgramFiles")
|
|
if programFiles == "" {
|
|
programFiles = `C:\Program Files`
|
|
}
|
|
programData := os.Getenv("ProgramData")
|
|
if programData == "" {
|
|
programData = `C:\ProgramData`
|
|
}
|
|
return filepath.Join(programFiles, "RVBox", "rvbox.exe"), filepath.Join(programData, "RVBox", "client.toml")
|
|
}
|
|
|
|
func startInstalledTray() error {
|
|
executable, configPath := packagedInstallPaths()
|
|
command := exec.Command(executable, "--tray", "--config", configPath)
|
|
if err := command.Start(); err != nil {
|
|
return err
|
|
}
|
|
_ = command.Process.Release()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
return windowstray.WaitReady(ctx)
|
|
}
|
|
|
|
// installPackagedDefault executes only in the UAC-elevated child. It preserves
|
|
// a pre-existing operator configuration, atomically updates the executable,
|
|
// installs/updates the SCM service, and starts it.
|
|
func installPackagedDefault(_ io.Writer) error {
|
|
err := installPackagedDefaultFiles()
|
|
if err != nil {
|
|
showInstallerMessage("RVBox could not be installed.\n\n"+err.Error()+"\n\nNo existing configuration was replaced.", installerErrorIcon)
|
|
return err
|
|
}
|
|
// The original interactive process waits for this child to exit, starts the
|
|
// tray with its own user token, then shows the single success message.
|
|
return nil
|
|
}
|
|
|
|
func installPackagedDefaultFiles() error {
|
|
if strings.TrimSpace(bootstrapServerURL) == "" {
|
|
return errors.New("this RVBox package was built without a bootstrap server URL")
|
|
}
|
|
source, err := os.Executable()
|
|
if err != nil {
|
|
return fmt.Errorf("locate installer executable: %w", err)
|
|
}
|
|
targetExecutable, configPath := packagedInstallPaths()
|
|
targetDirectory, configDirectory := filepath.Dir(targetExecutable), filepath.Dir(configPath)
|
|
trayCtx, cancelTray := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancelTray()
|
|
if err := windowstray.CloseCurrent(trayCtx); err != nil {
|
|
return fmt.Errorf("close existing notification-area frontend: %w", err)
|
|
}
|
|
|
|
// A running service can keep the prior executable open. Stop it before the
|
|
// atomic replacement; a missing service is already a successful first run.
|
|
if err := windowsservice.Stop(30); err != nil {
|
|
return fmt.Errorf("stop existing RVBox service: %w", err)
|
|
}
|
|
if err := os.MkdirAll(targetDirectory, 0o755); err != nil {
|
|
return fmt.Errorf("create installation directory: %w", err)
|
|
}
|
|
if !sameWindowsPath(source, targetExecutable) {
|
|
if err := copyInstallerExecutable(source, targetExecutable); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := os.MkdirAll(configDirectory, 0o700); err != nil {
|
|
return fmt.Errorf("create configuration directory: %w", err)
|
|
}
|
|
if _, err := os.Stat(configPath); errors.Is(err, os.ErrNotExist) {
|
|
hostname, hostnameErr := os.Hostname()
|
|
if hostnameErr != nil {
|
|
hostname = "rvbox-client"
|
|
}
|
|
content, configErr := packagedClientConfig(bootstrapServerURL, hostname)
|
|
if configErr != nil {
|
|
return configErr
|
|
}
|
|
if err := writeMachineConfig(configPath, content); err != nil {
|
|
return err
|
|
}
|
|
} else if err != nil {
|
|
return fmt.Errorf("inspect existing configuration: %w", err)
|
|
}
|
|
if err := windowsservice.Install(windowsservice.InstallSpec{ExecutablePath: targetExecutable, ConfigPath: configPath, Startup: windowsservice.StartupAutomatic}); err != nil {
|
|
return fmt.Errorf("install and start RVBox service: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func copyInstallerExecutable(source, target string) error {
|
|
input, err := os.Open(source)
|
|
if err != nil {
|
|
return fmt.Errorf("open installer executable: %w", err)
|
|
}
|
|
defer input.Close()
|
|
temporary := target + ".new"
|
|
_ = os.Remove(temporary)
|
|
output, err := os.OpenFile(temporary, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o755)
|
|
if err != nil {
|
|
return fmt.Errorf("create replacement executable: %w", err)
|
|
}
|
|
_, copyErr := io.Copy(output, input)
|
|
if syncErr := output.Sync(); copyErr == nil {
|
|
copyErr = syncErr
|
|
}
|
|
if closeErr := output.Close(); copyErr == nil {
|
|
copyErr = closeErr
|
|
}
|
|
if copyErr != nil {
|
|
_ = 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 {
|
|
_ = 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 nil
|
|
}
|
|
|
|
func writeMachineConfig(path string, content []byte) error {
|
|
temporary := path + ".new"
|
|
_ = os.Remove(temporary)
|
|
if err := os.WriteFile(temporary, content, 0o600); err != nil {
|
|
return fmt.Errorf("write default configuration: %w", err)
|
|
}
|
|
from, fromErr := windows.UTF16PtrFromString(temporary)
|
|
to, toErr := windows.UTF16PtrFromString(path)
|
|
if fromErr != nil || toErr != nil {
|
|
_ = os.Remove(temporary)
|
|
return errors.New("encode configuration path")
|
|
}
|
|
if err := windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH); err != nil {
|
|
_ = os.Remove(temporary)
|
|
return fmt.Errorf("activate default configuration: %w", err)
|
|
}
|
|
return protectMachineConfig(path)
|
|
}
|
|
|
|
func protectMachineConfig(path string) error {
|
|
descriptor, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;SY)(A;;FA;;;BA)")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dacl, _, err := descriptor.DACL()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil {
|
|
return fmt.Errorf("protect generated configuration: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func sameWindowsPath(first, second string) bool {
|
|
return strings.EqualFold(filepath.Clean(first), filepath.Clean(second))
|
|
}
|
|
|
|
func installerUTF16(value string) *uint16 {
|
|
encoded, _ := windows.UTF16PtrFromString(value)
|
|
return encoded
|
|
}
|
|
|
|
func showInstallerMessage(message string, icon uintptr) {
|
|
caption := installerUTF16("RVBox Setup")
|
|
text := installerUTF16(message)
|
|
_, _, _ = installerMessageBox.Call(0, uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(caption)), icon)
|
|
}
|