Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,13 @@ archive into a temp directory. Nothing is downloaded when a check fails.
it ad hoc. On a terminal the download line shows a progress bar. Elsewhere it
is a single line.

Every `Update` call first removes a stale `<target>.new` left by an install
that was interrupted between writing the file and renaming it into place.
The cleanup runs before the release check, so the file disappears the next
time the user runs the command even when nothing new is available or the
network is down. Only a regular file by that name is removed.
Replacement binaries are written through an exclusively created temporary
file beside the target, then atomically renamed into place. Existing
`<target>.new` files and symlinks are left untouched. Temporary replacement
files are removed on ordinary failures; a crash can leave a hidden
`.<target>.new-*` file behind. Automatic sweeping is disabled because a
leftover cannot safely be distinguished from another update's active file.
The installation directory must be trusted against modification by other users.

Linux and macOS with `.tar.gz` assets are supported. Windows is not.
Verification proves the download matches what the release page lists. It
Expand Down
15 changes: 6 additions & 9 deletions archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,13 @@ func (a *ArchiveInstaller) Prepare(ctx context.Context, rel Release) (Staged, er
return staged, nil
}

// Sweep removes a <target>.new left behind when an earlier install was
// interrupted between writing the file and renaming it into place. The
// name sits beside the binary in tab completion otherwise. Only a regular
// file is removed; a missing file is not an error.
// Sweep is retained for compatibility and does nothing. Replacement files
// have unique names and are removed on ordinary failures. Files left by a
// crash cannot safely be distinguished from another update's active files.
//
// Deprecated: ArchiveInstaller no longer requires sweeping.
func (a *ArchiveInstaller) Sweep() error {
target, err := a.target()
if err != nil {
return err
}
return removeStaleNew(target)
return nil
}

// stage downloads asset into staged.dir, verifies it unless SkipChecksum,
Expand Down
16 changes: 9 additions & 7 deletions archive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,22 +327,24 @@ func TestArchiveInstaller_DefaultClientHeaderTimeout(t *testing.T) {
}
}

func TestArchiveInstaller_SweepRemovesStaleNew(t *testing.T) {
func TestArchiveInstaller_SweepLeavesLegacyNewAlone(t *testing.T) {
target := writeTarget(t, contentOld)
writeStaleNew(t, target)
if err := newTestInstaller(target, io.Discard).Sweep(); err != nil {
t.Fatal(err)
}
assertNoLeftovers(t, target)
if got := readTarget(t, target); got != contentOld {
t.Fatalf("Sweep must not touch the target: %q", got)
if readTarget(t, target+".new") != "partial" {
t.Fatal("Sweep changed the legacy file")
}
if readTarget(t, target) != contentOld {
t.Fatal("Sweep changed the target")
}
}

func TestArchiveInstaller_SweepMissingTargetIsError(t *testing.T) {
func TestArchiveInstaller_SweepMissingTargetIsNoOp(t *testing.T) {
missing := filepath.Join(t.TempDir(), "gone")
if err := newTestInstaller(missing, io.Discard).Sweep(); err == nil {
t.Fatal("a target that cannot be resolved must be reported")
if err := newTestInstaller(missing, io.Discard).Sweep(); err != nil {
t.Fatal(err)
}
}

Expand Down
6 changes: 2 additions & 4 deletions installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@ type Staged interface {

// Sweeper is implemented by installers that can remove leftovers of an
// interrupted install without a release in hand. Updater.Update calls it
// on every run, so a stale <target>.new left by a crash disappears the
// next time the user runs the update command, even when nothing new is
// available. A Sweep failure is reported as a warning and never blocks
// the update.
// on every run, even when nothing new is available. A Sweep failure is
// reported as a warning and never blocks the update.
type Sweeper interface {
Sweep() error
}
Expand Down
11 changes: 10 additions & 1 deletion internal/e2e/scenarios_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,23 @@ const (
dlChecksumsTxt = "/dl/checksums.txt"
)

// assertNoLeftovers fails when a .new or .old file sits beside path.
// assertNoLeftovers checks both legacy and unique replacement file names.
func assertNoLeftovers(t *testing.T, path string) {
t.Helper()
for _, leftover := range []string{path + ".new", path + ".old"} {
if _, err := os.Stat(leftover); !errors.Is(err, os.ErrNotExist) {
t.Errorf("%s must not exist after an update (stat err %v)", leftover, err)
}
}
entries, err := os.ReadDir(filepath.Dir(path))
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), "."+filepath.Base(path)+".new-") {
t.Errorf("temporary replacement left behind: %s", entry.Name())
}
}
}

// assertMode0755 fails when path is not executable by everyone.
Expand Down
73 changes: 22 additions & 51 deletions replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,72 +31,43 @@ func preflightWritable(dir string) error {
return os.Remove(name)
}

// replaceFile installs src at target. It writes <target>.new beside the
// target and renames it over target. rename(2) replaces the file in one
// step on Linux and macOS, so a failed rename leaves the original in
// place and a crash at any point leaves the target present. The running
// process keeps its unlinked inode and is unaffected.
// replaceFile installs src at target using an exclusively created temporary
// file beside target. Writing through its original handle avoids following
// pre-existing symlinks. A single rename replaces target on Linux and macOS;
// failures before the rename leave the original binary in place.
func replaceFile(target string, src io.Reader, mode os.FileMode) error {
newPath := target + ".new"
if err := removeStaleNew(target); err != nil {
return err
dir := filepath.Dir(target)
f, err := os.CreateTemp(dir, "."+filepath.Base(target)+".new-*")
if err != nil {
if errors.Is(err, os.ErrPermission) {
return fmt.Errorf("%w: %s", ErrTargetNotWritable, dir)
}
return fmt.Errorf("selfupdate: create replacement in %s: %w", dir, err)
}
if err := writeFile(newPath, src, mode); err != nil {
newPath := f.Name()
defer func() { _ = os.Remove(newPath) }()
if err := writeReplacement(f, src, mode); err != nil {
return err
}
if err := renameFile(newPath, target); err != nil {
_ = os.Remove(newPath)
return fmt.Errorf("selfupdate: install new binary: %w", err)
}
return nil
}

// removeStaleNew deletes <target>.new when it is a regular file. An
// interrupted install can leave one behind. The .new suffix is ours only
// by convention, so a directory or symlink by that name is left alone and
// writeFile reports it.
func removeStaleNew(target string) error {
newPath := target + ".new"
info, err := os.Lstat(newPath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("selfupdate: inspect %s: %w", newPath, err)
}
if !info.Mode().IsRegular() {
return nil
}
if err := os.Remove(newPath); err != nil {
return fmt.Errorf("selfupdate: remove stale %s: %w", newPath, err)
}
return nil
}

// writeFile streams src into path with mode, removing the file on failure.
// The mode is applied with Chmod after creation so the process umask cannot
// narrow it.
func writeFile(path string, src io.Reader, mode os.FileMode) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
if errors.Is(err, os.ErrPermission) {
return fmt.Errorf("%w: %s", ErrTargetNotWritable, filepath.Dir(path))
}
return fmt.Errorf("selfupdate: create %s: %w", path, err)
}
if err := f.Chmod(mode); err != nil {
// writeReplacement writes and closes the already-open temporary file. Chmod
// applies the final mode after writing so the process umask cannot narrow it.
func writeReplacement(f *os.File, src io.Reader, mode os.FileMode) error {
if _, err := io.Copy(f, src); err != nil {
_ = f.Close()
_ = os.Remove(path)
return fmt.Errorf("selfupdate: set mode on %s: %w", path, err)
return fmt.Errorf("selfupdate: write %s: %w", f.Name(), err)
}
if _, err := io.Copy(f, src); err != nil {
if err := f.Chmod(mode); err != nil {
_ = f.Close()
_ = os.Remove(path)
return fmt.Errorf("selfupdate: write %s: %w", path, err)
return fmt.Errorf("selfupdate: set mode on %s: %w", f.Name(), err)
}
if err := f.Close(); err != nil {
_ = os.Remove(path)
return fmt.Errorf("selfupdate: close %s: %w", path, err)
return fmt.Errorf("selfupdate: close %s: %w", f.Name(), err)
}
return nil
}
Loading
Loading