Files
magpie/internal/update/com.go
T
yetone 482e883142 update: a Windows magpie on the Desktop leaves no magpie.exe.new or magpie.com there
nianshou5 on Discord (#help, Windows): magpie.com and magpie.exe.new
showed on the Desktop and came back after being deleted. Both were
written beside magpie.exe:

- magpie.exe.new is the update the GUI downloads as soon as it is out
  and swaps in at the next restart. StageBinary put it beside the
  program whenever that folder was writable, so it sat on the Desktop
  until a restart, and a deleted one was downloaded again by the next
  check.
- magpie.com (#3737) is written at every start while the app's folder
  is on PATH, and Settings > Command line's Add puts that folder on
  PATH, so deleting it on the Desktop lasted until the next start.

Now:

- StageBinary downloads into magpie's cache, in a folder of this
  program's own (update/<hash of the exe path>), when a rename from
  there reaches the program's folder (renamesInto, a real probe: the
  swap must stay one rename on one volume). With the cache on another
  volume it goes into a hidden .magpie-update folder beside the program
  (FILE_ATTRIBUTE_HIDDEN on Windows). A folder magpie may not write is
  unchanged (cache, moved in as administrator). The stage folder is
  removed after the swap or a failed download.
- At start RemoveStaleNew looks in every place a download may be,
  magpie.exe.new beside the program included, and removes one no newer
  than the running version (same bytes, or an older file version); a
  newer one stays, as before.
- Settled (the installed copy opened from a Desktop/Downloads one)
  also removes the update downloaded for that one, which nothing will
  put in now.
- In a download folder (Desktop, Downloads, a temp folder, as
  isDownloadFolder already says) a start only keeps an existing
  magpie.com up to date and never writes a missing one; Add still
  writes it. Any other folder on PATH is as before. A Desktop
  magpie.exe that opens the installed one (Settle) already wrote none.

Run:
- Windows (win-run, xiaomi-gpu, sandbox HOME from testenv), a repro
  test with the running test binary standing for magpie.exe on a
  Desktop on PATH: at origin/main 72ed121fd StageBinary staged
  test.test.exe.new beside it, and magpie.com came back after delete +
  start; with this change the download was in
  AppData\Local\magpie\update\<hash>\ and magpie.com stayed gone.
- Windows: a real program (whoami.exe) staged into the cache passed the
  real trial start (canStart) and was swapped in for a Desktop
  magpie.exe with the real moveAside/moveIn; the stage folder was gone
  after.
- At the pushed head (rebased on d6beb9975): go test ./internal/update
  on mote and on Windows: ok. Before the rebase also on Linux (wsl-run). gofmt, go vet ./internal/update (darwin, linux, windows),
  GOOS=windows go vet ./internal/gui ./internal/cli: clean.
- go test ./internal/gui ./internal/cli on Windows: TestUpdateThatWontStart,
  TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
  TestAionUiImportRow (#4115), TestGatewayHeldByAContainer (#2107,
  #3649) and TestLibraryMCPHub (#4140) red, the same 6 when run at
  origin/main 72ed121fd.
- Full suite on mote (-timeout 45m): started at the pre-rebase tree
  (same update changes, base 72ed121fd) and still running at push; its
  result and any red go in a follow-up.

Broken by hand: staging back beside the exe, the download-folder rule
in EnsureCompanion off, removeStaged out of Settled: the new tests
(TestUpdateStagedOutOfTheProgramsFolder, TestUpdateStagedHiddenWithoutTheCache,
TestStartClearsAnOlderDownloadBeside, TestNoCompanionPutBackOnTheDesktop,
TestSettledClearsOnlyMagpiesFiles, TestNoCompanionBesideAForwardingDownload)
went red.

Not tried: a real GUI self-update of a release build on the Windows
desktop, a cache and Desktop on separate real volumes (the hidden
fallback was tested with no cache), the reporter's own machine, and a
real terminal's `magpie` (unchanged code outside download folders).
2026-10-31 00:21:26 +08:00

176 lines
6.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package update
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
)
// The Windows app is linked as a GUI program, so a double click opens no
// console window; but a shell doesn't wait for a GUI program either. In
// PowerShell or cmd, `magpie plugin login` gave the prompt back at once,
// printed after it, and the shell and magpie both read the keys typed:
// a hidden password never reached magpie (TomXPRIME, #3737). A shell looks
// for `magpie` by PATHEXT, which lists .COM before .EXE, so magpie writes
// magpie.com beside the app: a small console program (./launcher) that
// the shell waits for, which runs the app with its console and exits with
// the app's code. Double clicks and the Start menu still open magpie.exe.
//
// It is written wherever a terminal runs magpie from: when the app's
// folder is on PATH, where Settings › Command line puts it, or a magpie.com
// or magpie.cmd is there already. On the Desktop or in Downloads only Add
// writes it, and a start only keeps one there up to date. The app writes it again as it starts
// when its bytes differ, so an update brings it along. They differ only
// when the launcher does: it is built without the release's commit in it
// (the Makefile's -buildvcs=false), or every update wrote a new magpie.com
// (lucky_eagle_38410 on Discord, TestLauncherSameAtEveryCommit).
// ComEnv is set by magpie.com for the app it runs: the standard handles it
// hands over are the terminal's console or a redirection, and its console
// is the one to borrow (cli's console_windows.go).
const ComEnv = "MAGPIE_COM"
// comName is the companion's file name; it runs as `magpie`.
const comName = "magpie.com"
// comMagic ends magpie.com; the app it runs is named just before it,
// after a NUL (launcher's targetName).
const comMagic = "\x00magpie-com-target"
// comLauncher is the launcher program, built for this system and put in
// the Windows app by `make release-windows` (com_embed_windows_*.go); nil
// in any other build, which writes no magpie.com.
var comLauncher []byte
// comText is the magpie.com that runs the program exe in its folder.
func comText(launcher []byte, exe string) []byte {
name := filepath.Base(strings.ReplaceAll(exe, `\`, "/"))
out := make([]byte, 0, len(launcher)+1+len(name)+len(comMagic))
out = append(out, launcher...)
out = append(out, 0)
out = append(out, name...)
return append(out, comMagic...)
}
// comTarget is the program name in a magpie.com's last bytes, "" when it
// has none.
func comTarget(b []byte) string {
if !bytes.HasSuffix(b, []byte(comMagic)) {
return ""
}
b = b[:len(b)-len(comMagic)]
return string(b[bytes.LastIndexByte(b, 0)+1:])
}
// comRuns says whether cmd is a magpie.com beside exe that runs it.
func comRuns(cmd, exe string) bool {
if !strings.EqualFold(filepath.Base(cmd), comName) || !strings.EqualFold(filepath.Dir(cmd), filepath.Dir(exe)) {
return false
}
f, err := os.Open(cmd)
if err != nil {
return false
}
defer f.Close()
st, err := f.Stat()
if err != nil || st.Size() < int64(len(comMagic)) {
return false
}
n := min(st.Size(), 1024)
b := make([]byte, n)
if _, err := f.ReadAt(b, st.Size()-n); err != nil {
return false
}
return strings.EqualFold(comTarget(b), filepath.Base(exe))
}
// comOwner says whether exe is the program a magpie.com in its folder
// should run: a magpie.exe there is what `magpie` ran before, so another
// copy beside it (magpie-windows-amd64 (1).exe) leaves it be.
func comOwner(exe string) bool {
if strings.EqualFold(filepath.Base(exe), "magpie.exe") {
return true
}
st, err := os.Stat(filepath.Join(filepath.Dir(exe), "magpie.exe"))
return err != nil || st.IsDir()
}
// EnsureCompanion writes the magpie.com that runs exe beside it when a
// terminal runs magpie from that folder (on PATH, or a magpie.com or
// magpie.cmd there), or brings one there up to this version. Nothing in
// a build without the launcher, or when it is as it should be already.
func EnsureCompanion(exe string) error {
// a download that opens the installed magpie (Settle) leaves the
// command to that one, in its folder on PATH
if comLauncher == nil || !comOwner(exe) || forwards(exe) {
return nil
}
dir := filepath.Dir(exe)
if downloadFolder(dir) {
// the Desktop or Downloads, which the user sees: one there is
// kept up to date, never put back once deleted (nianshou5 on
// Discord: it came back on every start, the Desktop being on
// PATH). Settings › Command line's Add still writes it.
if !exists(filepath.Join(dir, comName)) {
return nil
}
} else if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) {
return nil
}
_, err := writeCom(comLauncher, exe)
return err
}
// writeCom writes the magpie.com that runs exe beside it, unless it is
// there already, and is its path. A magpie.com running now (a `magpie
// serve` in a terminal) can't be written over, but can be moved aside,
// as an update moves the running app; the next run clears it.
func writeCom(launcher []byte, exe string) (string, error) {
p := filepath.Join(filepath.Dir(exe), comName)
want := comText(launcher, exe)
// the one moved aside last time, running then, is let go of now
RemoveOld(p)
if b, err := os.ReadFile(p); err == nil && bytes.Equal(b, want) {
return p, nil
}
f, err := os.CreateTemp(filepath.Dir(p), ".magpie-com-*")
if err != nil {
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
tmp := f.Name()
_, err = f.Write(want)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
if err = os.Rename(tmp, p); err != nil && exists(p) {
if aerr := os.Rename(p, oldName(p)); aerr == nil {
err = os.Rename(tmp, p)
}
}
}
if err != nil {
os.Remove(tmp)
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
return p, nil
}
// onPath is whether dir is one of path's (Windows', ;-separated) folders.
func onPath(dir, path string) bool {
dir = strings.TrimRight(dir, `\/`)
for _, d := range strings.Split(path, string(os.PathListSeparator)) {
if d = strings.TrimRight(strings.TrimSpace(d), `\/`); d != "" && strings.EqualFold(d, dir) {
return true
}
}
return false
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}