diff --git a/internal/update/com.go b/internal/update/com.go index 44779b372..fad88918a 100644 --- a/internal/update/com.go +++ b/internal/update/com.go @@ -20,7 +20,8 @@ import ( // // 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. The app writes it again as it starts +// 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 @@ -107,7 +108,15 @@ func EnsureCompanion(exe string) error { return nil } dir := filepath.Dir(exe) - if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) { + 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) diff --git a/internal/update/com_test.go b/internal/update/com_test.go index 71e58db20..0ec251125 100644 --- a/internal/update/com_test.go +++ b/internal/update/com_test.go @@ -88,8 +88,11 @@ func TestComOwner(t *testing.T) { // EnsureCompanion writes where a terminal runs magpie from, and nowhere // else: a downloads folder off PATH gets nothing. func TestEnsureCompanion(t *testing.T) { - old := comLauncher - t.Cleanup(func() { comLauncher = old }) + old, wasDL := comLauncher, downloadFolder + t.Cleanup(func() { comLauncher, downloadFolder = old, wasDL }) + // on Windows a temporary folder counts as a download folder, which + // gets one only from Add (TestNoCompanionPutBackOnTheDesktop) + downloadFolder = func(string) bool { return false } sep := string(os.PathListSeparator) comLauncher = nil diff --git a/internal/update/desktop_stage_other_test.go b/internal/update/desktop_stage_other_test.go new file mode 100644 index 000000000..af6e23322 --- /dev/null +++ b/internal/update/desktop_stage_other_test.go @@ -0,0 +1,10 @@ +//go:build !windows + +package update + +import ( + "path/filepath" + "strings" +) + +func hiddenForTest(p string) bool { return strings.HasPrefix(filepath.Base(p), ".") } diff --git a/internal/update/desktop_stage_test.go b/internal/update/desktop_stage_test.go new file mode 100644 index 000000000..014d7dcb1 --- /dev/null +++ b/internal/update/desktop_stage_test.go @@ -0,0 +1,209 @@ +package update + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" +) + +// desktopFixture is magpie.exe on a Desktop, with magpie's cache +// elsewhere and a release asset to download. +type desktopFixture struct { + desktop, exe, cache string + asset Asset + body []byte +} + +func newDesktopFixture(t *testing.T) *desktopFixture { + t.Helper() + root := t.TempDir() + f := &desktopFixture{ + desktop: filepath.Join(root, "Desktop"), + cache: filepath.Join(root, "Local", "magpie"), + body: []byte("MZ the next version"), + } + f.exe = filepath.Join(f.desktop, "magpie.exe") + if err := os.MkdirAll(f.desktop, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.exe, []byte("MZ this version"), 0o755); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(f.body) })) + t.Cleanup(srv.Close) + sum := sha256.Sum256(f.body) + f.asset = Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])} + was, wasStart := stageCache, canStart + t.Cleanup(func() { stageCache, canStart = was, wasStart }) + stageCache = func() (string, error) { return f.cache, nil } + canStart = func(string) error { return nil } + return f +} + +// what is in the Desktop besides magpie.exe and what an update moved +// aside (removed at the next start, RemoveOld) +func (f *desktopFixture) beside(t *testing.T) []string { + t.Helper() + es, err := os.ReadDir(f.desktop) + if err != nil { + t.Fatal(err) + } + var out []string + for _, e := range es { + if n := e.Name(); n != "magpie.exe" && n != "magpie.exe.old" { + out = append(out, n) + } + } + return out +} + +// An update waiting for the next restart is downloaded to magpie's cache, +// not beside the program as magpie.exe.new, which showed on a Desktop and +// came back after it was deleted (nianshou5 on Discord). The swap still +// puts it in, and leaves nothing of the download behind. +func TestUpdateStagedOutOfTheProgramsFolder(t *testing.T) { + f := newDesktopFixture(t) + staged, err := stageBinaryFor(context.Background(), f.asset, f.exe) + if err != nil { + t.Fatal(err) + } + if got := f.beside(t); len(got) != 0 { + t.Fatalf("beside magpie.exe while the update waits: %v", got) + } + if !inFolder(staged, f.cache) { + t.Fatalf("staged at %s, not in the cache %s", staged, f.cache) + } + if _, err := InstallBinaryAside(staged, f.exe); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(f.exe); string(b) != string(f.body) { + t.Fatalf("magpie.exe after the swap: %q", b) + } + if got := f.beside(t); len(got) != 0 { + t.Fatalf("beside magpie.exe after the swap: %v", got) + } + if es, _ := os.ReadDir(filepath.Join(f.cache, "update")); len(es) != 0 { + t.Fatalf("left in the cache: %v", es) + } +} + +// With no cache a rename reaches (another volume), the download goes into +// a hidden folder beside the program, which the swap removes. +func TestUpdateStagedHiddenWithoutTheCache(t *testing.T) { + f := newDesktopFixture(t) + stageCache = func() (string, error) { return "", errors.New("no cache") } + staged, err := stageBinaryFor(context.Background(), f.asset, f.exe) + if err != nil { + t.Fatal(err) + } + if want := filepath.Join(f.desktop, besideStage, "magpie.exe.new"); staged != want { + t.Fatalf("staged at %s, want %s", staged, want) + } + if got := f.beside(t); !slices.Equal(got, []string{besideStage}) { + t.Fatalf("beside magpie.exe while the update waits: %v", got) + } + if !hiddenForTest(filepath.Join(f.desktop, besideStage)) { + t.Fatal(besideStage + " isn't hidden") + } + if _, err := InstallBinaryAside(staged, f.exe); err != nil { + t.Fatal(err) + } + if got := f.beside(t); len(got) != 0 { + t.Fatalf("beside magpie.exe after the swap: %v", got) + } +} + +// A download a failed restart keeps for the next try stays where it was +// staged, out of sight; a failed download leaves nothing. +func TestFailedDownloadLeavesNothing(t *testing.T) { + f := newDesktopFixture(t) + quickRetries(t) + f.asset.SHA256 = "00" + if _, err := stageBinaryFor(context.Background(), f.asset, f.exe); err == nil { + t.Fatal("a download that doesn't match its checksum was staged") + } + if got := f.beside(t); len(got) != 0 { + t.Fatalf("beside magpie.exe: %v", got) + } + if es, _ := os.ReadDir(filepath.Join(f.cache, "update")); len(es) != 0 { + t.Fatalf("left in the cache: %v", es) + } +} + +// What an earlier version downloaded beside the program (magpie.exe.new) +// goes at the next start once it is no newer than the program: an older +// version, or this one over again. A newer one, which a magpie still +// running may put in, stays. +func TestStartClearsAnOlderDownloadBeside(t *testing.T) { + f := newDesktopFixture(t) + saved := fileVersion + t.Cleanup(func() { fileVersion = saved }) + versions := map[string]uint64{f.exe: 5} + fileVersion = func(p string) uint64 { return versions[p] } + left := f.exe + ".new" + os.WriteFile(left, []byte("MZ an older one"), 0o755) + versions[left] = 4 + RemoveStaleNew(f.exe) + if exists(left) { + t.Fatal("an older magpie.exe.new was kept") + } + os.WriteFile(left, []byte("MZ a newer one"), 0o755) + versions[left] = 6 + RemoveStaleNew(f.exe) + if !exists(left) { + t.Fatal("a newer magpie.exe.new was removed") + } + // the same in the cache + staged, err := stageBinaryFor(context.Background(), f.asset, f.exe) + if err != nil { + t.Fatal(err) + } + versions[staged] = 5 + RemoveStaleNew(f.exe) + if exists(staged) || exists(filepath.Dir(staged)) { + t.Fatal("a download of this version was kept in the cache") + } +} + +// A start of a magpie on the Desktop doesn't put magpie.com back there +// once deleted, though the Desktop is on PATH; one there is kept up to +// date, and Add (cliPlace's writeCom) still writes it. +func TestNoCompanionPutBackOnTheDesktop(t *testing.T) { + f := newDesktopFixture(t) + was, wasDL, wasTo := comLauncher, downloadFolder, installTarget + t.Cleanup(func() { comLauncher, downloadFolder, installTarget = was, wasDL, wasTo }) + comLauncher = []byte("MZ launcher") + downloadFolder = func(dir string) bool { return samePath(dir, f.desktop) } + installTarget = func() string { return "" } // runs where it is (portable, MAGPIE_NO_INSTALL) + t.Setenv("PATH", f.desktop) + com := filepath.Join(f.desktop, comName) + if err := EnsureCompanion(f.exe); err != nil || exists(com) { + t.Fatalf("magpie.com written on the Desktop: %v", err) + } + if _, err := writeCom([]byte("MZ older launcher"), f.exe); err != nil { + t.Fatal(err) + } + if err := EnsureCompanion(f.exe); err != nil || !comRuns(com, f.exe) { + t.Fatalf("magpie.com there not kept: %v", err) + } + if b, _ := os.ReadFile(com); string(b) != string(comText(comLauncher, f.exe)) { + t.Fatal("magpie.com there not brought up to date") + } + os.Remove(com) + if err := EnsureCompanion(f.exe); err != nil || exists(com) { + t.Fatalf("a deleted magpie.com came back: %v", err) + } + // a folder of the user's own on PATH is as before + other := filepath.Join(t.TempDir(), "magpie.exe") + t.Setenv("PATH", filepath.Dir(other)) + if err := EnsureCompanion(other); err != nil || !exists(filepath.Join(filepath.Dir(other), comName)) { + t.Fatalf("magpie.com not written in a folder of the user's on PATH: %v", err) + } +} diff --git a/internal/update/desktop_stage_windows_test.go b/internal/update/desktop_stage_windows_test.go new file mode 100644 index 000000000..805fdf836 --- /dev/null +++ b/internal/update/desktop_stage_windows_test.go @@ -0,0 +1,12 @@ +package update + +import "golang.org/x/sys/windows" + +func hiddenForTest(p string) bool { + u, err := windows.UTF16PtrFromString(p) + if err != nil { + return false + } + a, err := windows.GetFileAttributes(u) + return err == nil && a&windows.FILE_ATTRIBUTE_HIDDEN != 0 +} diff --git a/internal/update/install.go b/internal/update/install.go index ea3ebf474..1f900d400 100644 --- a/internal/update/install.go +++ b/internal/update/install.go @@ -210,7 +210,7 @@ func Forward(from, to string) error { // Settled clears, in the installed magpie Forward opened, what magpie left // beside the exe it was installed from: what updates moved aside there, -// and the magpie.com or magpie.cmd magpie wrote there to run it, which +// an update downloaded for it (magpie.exe.new), and the magpie.com or magpie.cmd magpie wrote there to run it, which // the `magpie` on PATH is now. A file it didn't write, or wrote for // another program, is left. func Settled() { @@ -224,6 +224,9 @@ func Settled() { func clearBeside(from string) { RemoveOld(from) + // an update the download had fetched is never put in now: the + // installed one updates itself + removeStaged(from) dir := filepath.Dir(from) if p := filepath.Join(dir, comName); comRuns(p, from) { RemoveOld(p) diff --git a/internal/update/install_other.go b/internal/update/install_other.go index f4c1fbbf5..fb7f9509d 100644 --- a/internal/update/install_other.go +++ b/internal/update/install_other.go @@ -7,3 +7,6 @@ func installPath() string { return "" } func isDownloadFolder(string) bool { return false } func exeVersion(string) uint64 { return 0 } func webViewDefault(string) string { return "" } + +// hide does nothing: a name starting with a dot is hidden already. +func hide(string) {} diff --git a/internal/update/install_test.go b/internal/update/install_test.go index b19cef28f..43fe8099b 100644 --- a/internal/update/install_test.go +++ b/internal/update/install_test.go @@ -249,9 +249,13 @@ func TestSettledClearsOnlyMagpiesFiles(t *testing.T) { if err := os.WriteFile(f.exe+".old", []byte("MZ"), 0o755); err != nil { t.Fatal(err) } + // an update an older magpie downloaded beside it, never put in now + if err := os.WriteFile(f.exe+".new", []byte("MZ newer"), 0o755); err != nil { + t.Fatal(err) + } t.Setenv(installedFromEnv, f.exe) Settled() - for _, p := range []string{com, filepath.Join(dir, shimName), f.exe + ".old"} { + for _, p := range []string{com, filepath.Join(dir, shimName), f.exe + ".old", f.exe + ".new"} { if exists(p) { t.Fatalf("%s left", filepath.Base(p)) } @@ -356,8 +360,10 @@ func TestNoCompanionBesideAForwardingDownload(t *testing.T) { if err := EnsureCompanion(f.exe); err != nil { t.Fatal(err) } - if got := exists(filepath.Join(f.downloads, comName)); got == forwards(f.exe) { - t.Fatalf("magpie.com beside the download: %v, forwarding: %v", got, forwards(f.exe)) + // nor one that runs where it is: a download folder gets one only from + // Add (TestNoCompanionPutBackOnTheDesktop) + if exists(filepath.Join(f.downloads, comName)) { + t.Fatalf("magpie.com beside the download, forwarding: %v", forwards(f.exe)) } } diff --git a/internal/update/install_windows.go b/internal/update/install_windows.go index 01c17c445..1b4b5ac6f 100644 --- a/internal/update/install_windows.go +++ b/internal/update/install_windows.go @@ -80,3 +80,14 @@ func webViewDefault(exe string) string { } return filepath.Join(a, filepath.Base(exe)) } + +// hide gives p the hidden attribute, which Explorer leaves out of view. +func hide(p string) { + u, err := windows.UTF16PtrFromString(p) + if err != nil { + return + } + if a, err := windows.GetFileAttributes(u); err == nil { + windows.SetFileAttributes(u, a|windows.FILE_ATTRIBUTE_HIDDEN) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index fea043973..6af4149ea 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -526,8 +526,8 @@ func ReplaceBinary(ctx context.Context, rel *Release) error { return err } -// StageBinary downloads the release's build for this binary next to it (or -// to the cache, where magpie may not write there), ready for InstallBinary. +// StageBinary downloads the release's build for this binary out of sight +// (binaryStage), ready for InstallBinary. func StageBinary(ctx context.Context, rel *Release) (string, error) { a, ok := rel.Assets[BinaryAsset()] if !ok { @@ -537,24 +537,119 @@ func StageBinary(ctx context.Context, rel *Release) (string, error) { if err != nil { return "", err } - tmp := exe + ".new" - if !Writable(filepath.Dir(exe)) { - dir := stageDir(filepath.Dir(exe)) - if err := os.MkdirAll(dir, 0o755); err != nil { - return "", err - } - tmp = filepath.Join(dir, filepath.Base(exe)+".new") + return stageBinaryFor(ctx, a, exe) +} + +func stageBinaryFor(ctx context.Context, a Asset, exe string) (string, error) { + tmp, err := binaryStage(exe) + if err != nil { + return "", err } if err := download(ctx, a, tmp); err != nil { + dropStage(tmp) return "", err } if err := os.Chmod(tmp, 0o755); err != nil { os.Remove(tmp) + dropStage(tmp) return "", err } return tmp, nil } +// The GUI downloads an update when it is out and swaps it in at the next +// restart, which may be days later. It was downloaded beside the program +// as magpie.exe.new, so a magpie kept on the Desktop showed the download +// there, and deleted, it came back with the next check (nianshou5 on +// Discord). It is downloaded to magpie's cache now, in a folder of this +// program's own, whenever a rename from there reaches the program's +// folder, which is what puts it in; else (the cache on another volume) +// into a hidden .magpie-update folder beside the program. Where magpie may +// not write beside the program, it goes to the cache as before, to be +// moved in with the administrator's password. + +// besideStage is the hidden folder beside the program an update is +// downloaded into when no rename from the cache reaches the program. +const besideStage = ".magpie-update" + +// stageCache is magpie's cache folder; tests set it. +var stageCache = appdir.SystemCache + +// binaryStage is the file StageBinary downloads exe's new build to, its +// folder made. +func binaryStage(exe string) (string, error) { + dir, name := filepath.Dir(exe), filepath.Base(exe)+".new" + if !Writable(dir) { + d := stageDir(dir) + if err := os.MkdirAll(d, 0o755); err != nil { + return "", err + } + return filepath.Join(d, name), nil + } + if d := cacheStage(exe); d != "" && os.MkdirAll(d, 0o755) == nil { + if renamesInto(d, dir) { + return filepath.Join(d, name), nil + } + os.Remove(d) + } + d := filepath.Join(dir, besideStage) + if err := os.MkdirAll(d, 0o755); err != nil { + return "", err + } + hide(d) + return filepath.Join(d, name), nil +} + +// cacheStage is exe's own folder in the cache for its downloads, "" with +// no cache: two copies of magpie (a portable one and the installed one) +// never share one. +func cacheStage(exe string) string { + cache, err := stageCache() + if err != nil || cache == "" { + return "" + } + sum := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(exe)))) + return filepath.Join(cache, "update", hex.EncodeToString(sum[:6])) +} + +// renamesInto says whether a file in from can be renamed into dir: the +// same volume, which a move that can't fail half way needs. +func renamesInto(from, dir string) bool { + f, err := os.CreateTemp(from, ".magpie-update-*") + if err != nil { + return false + } + f.Close() + to := filepath.Join(dir, filepath.Base(f.Name())) + if err := os.Rename(f.Name(), to); err != nil { + os.Remove(f.Name()) + return false + } + os.Remove(to) + return true +} + +// dropStage removes the folder a staged download was in once it is empty, +// when it is one binaryStage made. +func dropStage(staged string) { + d := filepath.Dir(staged) + if filepath.Base(d) == besideStage || (len(filepath.Base(d)) == 12 && filepath.Base(filepath.Dir(d)) == "update") { + os.Remove(d) + } +} + +// stagedFiles are the places a download of exe's next build may be: where +// binaryStage puts it, and beside exe as exe.new, where earlier versions +// put it. +func stagedFiles(exe string) []string { + name := filepath.Base(exe) + ".new" + out := []string{exe + ".new", filepath.Join(filepath.Dir(exe), besideStage, name)} + if d := cacheStage(exe); d != "" { + out = append(out, filepath.Join(d, name)) + } + return out +} + // InstallBinary swaps a staged binary in for exe, the running one, which // keeps going until it exits. func InstallBinary(staged, exe string) error { @@ -576,6 +671,7 @@ func InstallBinaryAside(staged, exe string) (string, error) { if !trialled.passed(staged) { if err := canStart(staged); err != nil { os.Remove(staged) + dropStage(staged) return "", &BlockedError{Err: err} } trialled.note(staged) @@ -603,9 +699,11 @@ func InstallBinaryAside(staged, exe string) (string, error) { } } else if !NeedsAdmin(err) { // kept for InstallBinaryAsAdmin os.Remove(staged) + dropStage(staged) } return "", err } + dropStage(staged) return old, nil } @@ -786,17 +884,30 @@ func Replaced(exe string, started os.FileInfo) bool { return err == nil && started != nil && (now.Size() != started.Size() || !now.ModTime().Equal(started.ModTime())) } -// RemoveStaleNew removes exe.new when it is exe over again: the update a -// magpie left running from before it downloaded once more. +// RemoveStaleNew removes a download of exe's next build (stagedFiles) +// that is no newer than exe: exe over again (the update a magpie left +// running from before it downloaded once more), or an older version a +// swap never put in. A newer one, which a magpie still running may yet +// put in, stays. func RemoveStaleNew(exe string) { - staged := exe + ".new" - a, err1 := os.Stat(exe) - b, err2 := os.Stat(staged) - if err1 != nil || err2 != nil || a.Size() != b.Size() { - return + mine := fileVersion(exe) + for _, staged := range stagedFiles(exe) { + if !exists(staged) { + continue + } + if v := fileVersion(staged); sameBytes(exe, staged) || (mine != 0 && v != 0 && v <= mine) { + os.Remove(staged) + } + dropStage(staged) } - if ha, hb := fileHash(exe), fileHash(staged); ha != "" && ha == hb { +} + +// removeStaged removes every download of exe's next build: what nothing +// will put in. +func removeStaged(exe string) { + for _, staged := range stagedFiles(exe) { os.Remove(staged) + dropStage(staged) } }