* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
300 lines
9.2 KiB
Go
300 lines
9.2 KiB
Go
package app
|
|
|
|
// In-app update: download the new release's Windows executable as a tracked
|
|
// task, check it against GitHub's assets[].digest SHA-256, then swap it in and
|
|
// restart (internal/selfupdate). Running VMs are separate processes and keep
|
|
// running; Guest Tools reconnects once the new window is up.
|
|
|
|
import (
|
|
"archive/zip"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/cli"
|
|
"github.com/Nwflower/reims-go/internal/fetch"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/netproxy"
|
|
"github.com/Nwflower/reims-go/internal/selfupdate"
|
|
"github.com/Nwflower/reims-go/internal/version"
|
|
)
|
|
|
|
// appUpdateTaskKind is the task kind the frontend watches for update host.
|
|
const appUpdateTaskKind = "app-update"
|
|
|
|
// appUpdateReady is the verified download InstallAppUpdate swaps in.
|
|
var appUpdateReady struct {
|
|
sync.Mutex
|
|
version string
|
|
path string
|
|
sha256 string
|
|
}
|
|
|
|
func (a *App) locale() i18n.Locale {
|
|
a.mu.Lock()
|
|
raw := a.cfg.Locale
|
|
a.mu.Unlock()
|
|
return i18n.EffectiveLocale(raw)
|
|
}
|
|
|
|
func (a *App) updateErr(key string, args ...any) error {
|
|
return errors.New(i18n.T(a.locale(), key, args...))
|
|
}
|
|
|
|
func (a *App) updateSupported() error {
|
|
if err := selfupdate.Supported(); err != nil {
|
|
if errors.Is(err, selfupdate.ErrDevBuild) {
|
|
return a.updateErr("err.update_dev_build")
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func appUpdateDir(dataRoot string) string {
|
|
return filepath.Join(dataRoot, "downloads", "app")
|
|
}
|
|
|
|
// DownloadAppUpdate downloads the newest eligible release on the selected
|
|
// update channel in the background and returns the task ID ("app-update",
|
|
// subject = the release tag). Canceling keeps the partial file so the next
|
|
// download resumes from there.
|
|
func (a *App) DownloadAppUpdate() (string, error) {
|
|
if err := a.updateSupported(); err != nil {
|
|
return "", err
|
|
}
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return "", err
|
|
}
|
|
a.mu.Lock()
|
|
dataRoot := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
|
|
info, err := a.CheckAppUpdate(false)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
switch {
|
|
case !info.HasUpdate:
|
|
return "", a.updateErr("err.update_none")
|
|
case info.DownloadURL == "" || info.AssetName == "":
|
|
return "", a.updateErr("err.update_no_asset")
|
|
case info.AssetSHA256 == "":
|
|
return "", a.updateErr("err.update_no_sums")
|
|
}
|
|
for _, t := range tasks.list() {
|
|
if t.Kind == appUpdateTaskKind && t.Status == TaskRunning {
|
|
return t.ID, nil
|
|
}
|
|
}
|
|
|
|
a.ensureTaskEmitter()
|
|
ctx, cancel := context.WithCancel(a.baseCtx())
|
|
id := tasks.start(appUpdateTaskKind, info.Latest, "", cancel)
|
|
go func() {
|
|
defer cancel()
|
|
path, sum, err := downloadAppUpdate(ctx, info, appUpdateDir(dataRoot), func(done, total int64) {
|
|
tasks.update(id, host.Update{
|
|
Kind: host.KindProgress, Step: "downloading " + info.AssetName,
|
|
Done: done, Total: total, Percent: percent(done, total),
|
|
})
|
|
})
|
|
switch {
|
|
case err == nil:
|
|
appUpdateReady.Lock()
|
|
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = info.Latest, path, sum
|
|
appUpdateReady.Unlock()
|
|
a.emitLog("app", fmt.Sprintf("Update %s downloaded and verified (SHA-256 %s)", info.Latest, sum))
|
|
tasks.finish(id, info.Latest, nil)
|
|
case ctx.Err() != nil:
|
|
tasks.finish(id, "", context.Canceled)
|
|
default:
|
|
a.emitLog("app", "Update download error: "+err.Error())
|
|
tasks.finish(id, "", err)
|
|
}
|
|
}()
|
|
return id, nil
|
|
}
|
|
|
|
// downloadAppUpdate fetches info's release asset (.zip or .exe) into dir,
|
|
// checks it against GitHub's assets[].digest SHA-256, extracts the executable
|
|
// when a .zip archive was downloaded, and returns the executable path and its
|
|
// SHA-256 hash.
|
|
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
|
|
want := strings.ToLower(strings.TrimSpace(info.AssetSHA256))
|
|
if len(want) != 64 {
|
|
return "", "", errors.New("missing or invalid release asset SHA-256 digest")
|
|
}
|
|
client := netproxy.NewClient()
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return "", "", err
|
|
}
|
|
path, err := fetch.Resume(ctx, client, info.DownloadURL, filepath.Join(dir, info.AssetName), info.AssetSize, want, onProgress)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
if strings.HasSuffix(strings.ToLower(path), ".zip") {
|
|
exePath, exeSum, err := extractAppUpdateZip(path, dir)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
return exePath, exeSum, nil
|
|
}
|
|
return path, want, nil
|
|
}
|
|
|
|
// extractAppUpdateZip extracts the single Windows executable from a verified
|
|
// release .zip into dir and returns its path and SHA-256 digest.
|
|
func extractAppUpdateZip(zipPath, dir string) (string, string, error) {
|
|
zr, err := zip.OpenReader(zipPath)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("open update archive: %w", err)
|
|
}
|
|
defer zr.Close()
|
|
|
|
const maxUpdateExeBytes = 256 << 20 // 256 MiB safety cap against zip bombs
|
|
for _, f := range zr.File {
|
|
if f.FileInfo().IsDir() {
|
|
continue
|
|
}
|
|
base := filepath.Base(f.Name)
|
|
if base == "." || base == ".." || strings.ContainsAny(f.Name, `/\`) {
|
|
continue
|
|
}
|
|
lower := strings.ToLower(base)
|
|
if !strings.HasSuffix(lower, ".exe") || strings.Contains(lower, "-cli-") {
|
|
continue
|
|
}
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("read %s from update archive: %w", base, err)
|
|
}
|
|
dest := filepath.Join(dir, base)
|
|
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
|
if err != nil {
|
|
_ = rc.Close()
|
|
return "", "", fmt.Errorf("create extracted update %s: %w", base, err)
|
|
}
|
|
h := sha256.New()
|
|
n, copyErr := io.Copy(io.MultiWriter(out, h), io.LimitReader(rc, maxUpdateExeBytes+1))
|
|
closeErr := errors.Join(rc.Close(), out.Close())
|
|
if copyErr != nil || closeErr != nil {
|
|
_ = os.Remove(dest)
|
|
return "", "", fmt.Errorf("extract %s from update archive: %w", base, errors.Join(copyErr, closeErr))
|
|
}
|
|
if n > maxUpdateExeBytes {
|
|
_ = os.Remove(dest)
|
|
return "", "", fmt.Errorf("extracted update %s exceeds %d byte limit", base, maxUpdateExeBytes)
|
|
}
|
|
return dest, hex.EncodeToString(h.Sum(nil)), nil
|
|
}
|
|
return "", "", errors.New("update archive does not contain a Windows executable")
|
|
}
|
|
|
|
// InstallAppUpdate swaps the downloaded update in for the running executable,
|
|
// starts it, and quits this window. The new window waits for this process to
|
|
// exit before it opens. Running VMs are not touched.
|
|
func (a *App) InstallAppUpdate() error {
|
|
if err := a.updateSupported(); err != nil {
|
|
return err
|
|
}
|
|
appUpdateReady.Lock()
|
|
ver, path, want := appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256
|
|
appUpdateReady.Unlock()
|
|
if path == "" {
|
|
return a.updateErr("err.update_not_ready")
|
|
}
|
|
// The file sat in the data folder since the download: check it again.
|
|
if got, err := fetch.FileSHA256(path); err != nil || !strings.EqualFold(got, want) {
|
|
appUpdateReady.Lock()
|
|
appUpdateReady.path = ""
|
|
appUpdateReady.Unlock()
|
|
return a.updateErr("err.update_changed")
|
|
}
|
|
|
|
exe, err := selfupdate.Executable()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := selfupdate.Writable(filepath.Dir(exe)); err != nil {
|
|
return a.updateErr("err.update_not_writable", filepath.Dir(exe))
|
|
}
|
|
// A file still named after a release takes the new release's name.
|
|
a.mu.Lock()
|
|
channel := version.ChannelStable
|
|
if a.cfg != nil {
|
|
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
|
|
}
|
|
a.mu.Unlock()
|
|
target := selfupdate.Target(exe, filepath.Base(path))
|
|
if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
|
|
return err
|
|
}
|
|
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
|
|
|
|
a.uiHealth.mu.Lock()
|
|
hidden := a.uiHealth.windowHidden
|
|
a.uiHealth.mu.Unlock()
|
|
args := cli.WindowArgs{Background: hidden, WaitPID: uint32(os.Getpid())}.Args()
|
|
if err := selfupdate.Launch(target, args); err != nil {
|
|
a.emitLog("app", "Could not start the updated Reims-Go: "+err.Error())
|
|
return a.updateErr("err.update_relaunch")
|
|
}
|
|
// Return to the frontend first, then quit for real (not to the tray).
|
|
go func() {
|
|
time.Sleep(300 * time.Millisecond)
|
|
a.QuitApp()
|
|
}()
|
|
return nil
|
|
}
|
|
|
|
// finishAppUpdate runs at startup: on the stable channel it removes what an
|
|
// earlier swap left next to the executable and, after an update restart, the
|
|
// downloaded installer files. On alpha/dev channels those old executables and
|
|
// downloaded installers are preserved for safe manual rollback.
|
|
func (a *App) finishAppUpdate() {
|
|
exe, err := selfupdate.Executable()
|
|
if err != nil {
|
|
return
|
|
}
|
|
a.finishAppUpdateWithExe(exe)
|
|
}
|
|
|
|
func (a *App) finishAppUpdateWithExe(exe string) {
|
|
a.mu.Lock()
|
|
dataRoot := ""
|
|
channel := version.ChannelStable
|
|
if a.cfg != nil {
|
|
dataRoot = a.cfg.DataRoot
|
|
channel = version.NormalizeChannel(a.cfg.AppUpdateChannel)
|
|
}
|
|
a.mu.Unlock()
|
|
|
|
keepOld := version.KeepsPreviousInstall(channel)
|
|
if keepOld {
|
|
selfupdate.CleanupStaging(exe)
|
|
} else {
|
|
selfupdate.Cleanup(exe)
|
|
}
|
|
if a.launch.WaitPID == 0 {
|
|
return
|
|
}
|
|
if !keepOld && dataRoot != "" && a.dataRootUsable() {
|
|
_ = os.RemoveAll(appUpdateDir(dataRoot))
|
|
}
|
|
if keepOld {
|
|
a.emitLog("app", fmt.Sprintf("Reims-Go updated to %s (%s channel; previous executable and downloaded installers preserved)", version.Version, channel))
|
|
} else {
|
|
a.emitLog("app", "Reims-Go updated to "+version.Version)
|
|
}
|
|
}
|