291 lines
9.4 KiB
Go
291 lines
9.4 KiB
Go
//go:build windows
|
|
|
|
package selfupdate
|
|
|
|
import (
|
|
"context"
|
|
"debug/buildinfo"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"runtime/debug"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/tray"
|
|
"github.com/Nwflower/reims-go/internal/version"
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
// LockDesktopStartup serializes replacement and Wails lock acquisition across
|
|
// launches. A dedicated OS thread owns the mutex until the window is ready.
|
|
func LockDesktopStartup(instanceID string) (func(), error) {
|
|
ready := make(chan error, 1)
|
|
released := make(chan struct{})
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
runtime.LockOSThread()
|
|
defer runtime.UnlockOSThread()
|
|
h, err := windows.CreateMutex(nil, false, windows.StringToUTF16Ptr(instanceID+"-desktop-startup"))
|
|
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
|
|
ready <- err
|
|
return
|
|
}
|
|
defer windows.CloseHandle(h)
|
|
event, err := windows.WaitForSingleObject(h, 45_000)
|
|
if err == nil && event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
|
|
err = fmt.Errorf("could not acquire the Reims-Go startup mutex (%#x)", event)
|
|
}
|
|
ready <- err
|
|
if err == nil {
|
|
<-released
|
|
_ = windows.ReleaseMutex(h)
|
|
}
|
|
}()
|
|
if err := <-ready; err != nil {
|
|
return nil, err
|
|
}
|
|
return sync.OnceFunc(func() {
|
|
close(released)
|
|
<-done
|
|
}), nil
|
|
}
|
|
|
|
// Takeover replaces the running client's executable at the exact path used by
|
|
// its shortcuts. The caller holds the desktop startup lock.
|
|
func Takeover(pid uint32, relaunchArgs []string, windowPID func() uint32) (bool, error) {
|
|
// The compatibility probe runs the old client's version command. Never
|
|
// launch that executable with elevated privileges inherited from this one.
|
|
if pid == 0 || pid == uint32(os.Getpid()) || windows.GetCurrentProcessToken().IsElevated() {
|
|
return false, nil
|
|
}
|
|
process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, pid)
|
|
if err != nil {
|
|
return false, nil
|
|
}
|
|
defer windows.CloseHandle(process)
|
|
if !sameUser(process) {
|
|
return false, nil
|
|
}
|
|
|
|
buf := make([]uint16, 32768)
|
|
size := uint32(len(buf))
|
|
if err := windows.QueryFullProcessImageName(process, 0, &buf[0], &size); err != nil {
|
|
return false, nil
|
|
}
|
|
target := windows.UTF16ToString(buf[:size])
|
|
source, err := Executable()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
oldFile, err := os.Stat(target)
|
|
if err != nil || !oldFile.Mode().IsRegular() {
|
|
return false, nil
|
|
}
|
|
if current, err := os.Stat(source); err != nil || os.SameFile(current, oldFile) {
|
|
return false, err
|
|
}
|
|
oldBuild, err := buildinfo.ReadFile(target)
|
|
newBuild, ok := debug.ReadBuildInfo()
|
|
if err != nil || !ok || oldBuild.Path != newBuild.Path || oldBuild.Main.Path != newBuild.Main.Path {
|
|
return false, nil
|
|
}
|
|
oldVersion, err := probeVersion(target)
|
|
if err != nil || !isNewerClient(version.Version, newBuild, oldVersion, oldBuild) {
|
|
return false, nil
|
|
}
|
|
|
|
// Stage the copy first so a read-only install folder leaves the old
|
|
// client running. The unique name also avoids the in-app updater's .new.
|
|
staged, err := stageExecutable(source, target, ".reims-go-takeover-*")
|
|
if err != nil {
|
|
return false, fmt.Errorf("stage update next to %s: %w", target, err)
|
|
}
|
|
defer os.Remove(staged)
|
|
if !fileMatches(target, oldFile) {
|
|
return false, nil
|
|
}
|
|
if err := closeClient(process, pid); err != nil {
|
|
return false, fmt.Errorf("close old Reims-Go: %w", err)
|
|
}
|
|
if !fileMatches(target, oldFile) {
|
|
return false, nil // the old client may have completed an in-app update
|
|
}
|
|
|
|
backup, err := stageExecutable(target, target, filepath.Base(target)+".old-*")
|
|
if err != nil {
|
|
return false, fmt.Errorf("back up %s: %w", target, err)
|
|
}
|
|
if !fileMatches(target, oldFile) {
|
|
_ = os.Remove(backup)
|
|
return false, nil
|
|
}
|
|
if err := replaceExecutable(staged, target); err != nil {
|
|
_ = os.Remove(backup)
|
|
return false, fmt.Errorf("replace %s: %w", target, err)
|
|
}
|
|
if err := launchReplacement(target, relaunchArgs, windowPID); err != nil {
|
|
if restoreErr := replaceExecutable(backup, target); restoreErr != nil {
|
|
err = errors.Join(err, fmt.Errorf("restore the old client from %s: %w", backup, restoreErr))
|
|
}
|
|
return false, fmt.Errorf("reopen %s: %w", target, err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// Keep the startup mutex until the replacement owns the Wails lock. Otherwise
|
|
// a concurrent launch can acquire the lock from its copy in Downloads first.
|
|
func launchReplacement(target string, args []string, windowPID func() uint32) error {
|
|
process, err := startDetached(target, args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer process.Release()
|
|
var startupErr error
|
|
err = process.WithHandle(func(handle uintptr) {
|
|
h := windows.Handle(handle)
|
|
deadline := time.Now().Add(12 * time.Second)
|
|
for time.Now().Before(deadline) {
|
|
if windowPID() == uint32(process.Pid) {
|
|
return
|
|
}
|
|
event, err := windows.WaitForSingleObject(h, 50)
|
|
if err != nil {
|
|
startupErr = errors.Join(err, terminateClient(h))
|
|
return
|
|
}
|
|
if event == windows.WAIT_OBJECT_0 {
|
|
startupErr = errors.New("the updated client exited before opening its window")
|
|
return
|
|
}
|
|
}
|
|
startupErr = errors.Join(errors.New("the updated client did not open its window"), terminateClient(h))
|
|
})
|
|
return errors.Join(err, startupErr)
|
|
}
|
|
|
|
func sameUser(process windows.Handle) bool {
|
|
var token windows.Token
|
|
if windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) != nil {
|
|
return false
|
|
}
|
|
defer token.Close()
|
|
user, err := token.GetTokenUser()
|
|
current, currentErr := windows.GetCurrentProcessToken().GetTokenUser()
|
|
return err == nil && currentErr == nil && !token.IsElevated() && user.User.Sid.Equals(current.User.Sid)
|
|
}
|
|
|
|
func probeVersion(exe string) (string, error) {
|
|
// Older releases expose their version through the CLI. Give the probe
|
|
// its own data directory since their CLI loads config before dispatch.
|
|
dir, err := os.MkdirTemp("", "reims-go-version-*")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, exe, "--data-root="+dir, "version")
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), "REIMS_GO_LOCATION_FILE="+filepath.Join(dir, "location.json"))
|
|
cmd.WaitDelay = time.Second
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: windows.CREATE_NO_WINDOW}
|
|
out, err := cmd.Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
fields := strings.Fields(string(out))
|
|
if len(fields) != 2 || fields[0] != "reims-go" || version.Compare(fields[1], "") <= 0 {
|
|
return "", errors.New("could not identify the client version")
|
|
}
|
|
return fields[1], nil
|
|
}
|
|
|
|
func isNewerClient(newVersion string, newBuild *debug.BuildInfo, oldVersion string, oldBuild *debug.BuildInfo) bool {
|
|
newBase, _, newDev := strings.Cut(newVersion, "-dev-")
|
|
oldBase, _, oldDev := strings.Cut(oldVersion, "-dev-")
|
|
if newDev && oldDev && newBase == oldBase {
|
|
// Rolling release version suffixes are commit IDs, which have no
|
|
// meaningful order. Use the source commit timestamps when available.
|
|
previous := buildTime(oldBuild)
|
|
return newVersion != oldVersion && !previous.IsZero() && buildTime(newBuild).After(previous)
|
|
}
|
|
return version.Compare(newVersion, oldVersion) > 0
|
|
}
|
|
|
|
func buildTime(info *debug.BuildInfo) time.Time {
|
|
for _, setting := range info.Settings {
|
|
if setting.Key == "vcs.time" {
|
|
stamp, _ := time.Parse(time.RFC3339, setting.Value)
|
|
return stamp
|
|
}
|
|
}
|
|
return time.Time{}
|
|
}
|
|
|
|
func fileMatches(path string, expected os.FileInfo) bool {
|
|
current, err := os.Stat(path)
|
|
return err == nil && os.SameFile(current, expected)
|
|
}
|
|
|
|
func closeClient(process windows.Handle, pid uint32) error {
|
|
// The Wails instance window can appear before startup creates the tray.
|
|
// A successful post only requests exit. Wait for all shutdown hooks.
|
|
for i := 0; i < 20; i++ {
|
|
if event, err := windows.WaitForSingleObject(process, 100); event == windows.WAIT_OBJECT_0 || err != nil {
|
|
return err
|
|
}
|
|
if tray.RequestQuit(pid) {
|
|
event, err := windows.WaitForSingleObject(process, 15_000)
|
|
if event == windows.WAIT_OBJECT_0 || err != nil {
|
|
return err
|
|
}
|
|
return errors.New("the older client did not finish closing")
|
|
}
|
|
}
|
|
return errors.New("the older client's tray window is unavailable")
|
|
}
|
|
|
|
func terminateClient(process windows.Handle) error {
|
|
terminateErr := windows.TerminateProcess(process, 0)
|
|
event, err := windows.WaitForSingleObject(process, 3000)
|
|
if event == windows.WAIT_OBJECT_0 {
|
|
return nil
|
|
}
|
|
return errors.Join(errors.New("the client process did not exit"), terminateErr, err)
|
|
}
|
|
|
|
func stageExecutable(src, target, pattern string) (string, error) {
|
|
file, err := os.CreateTemp(filepath.Dir(target), pattern)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := errors.Join(writeExecutable(src, file), file.Close()); err != nil {
|
|
_ = os.Remove(file.Name())
|
|
return "", err
|
|
}
|
|
return file.Name(), nil
|
|
}
|
|
|
|
func replaceExecutable(from, to string) error {
|
|
return windows.MoveFileEx(windows.StringToUTF16Ptr(from), windows.StringToUTF16Ptr(to),
|
|
windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
|
|
}
|
|
|
|
func ReportTakeoverError(err error) {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
message := "Reims-Go couldn't replace the older client."
|
|
if i18n.Detect() == i18n.ZhCN {
|
|
message = "Reims-Go 未能替换旧版客户端。"
|
|
}
|
|
_, _ = windows.MessageBox(0, windows.StringToUTF16Ptr(message+"\n\n"+err.Error()),
|
|
windows.StringToUTF16Ptr("Reims-Go"), windows.MB_OK|windows.MB_ICONWARNING)
|
|
}
|