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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ The zero value works for a goreleaser project with default archive names.
| `ChecksumAsset` | `checksums.txt` | goreleaser checksum file |
| `SkipChecksum` | `false` | set when the repo publishes no checksum file |
| `TargetPath` | running executable, symlinks resolved | file to replace |
| `Managed` | Homebrew Cellar, `/usr/bin`, `/usr/lib`, Nix store | locations owned by a package manager |
| `Managed` | Homebrew Cellar, `/usr/{s,}bin`, `/usr/lib{,64,exec}`, Nix store | locations owned by a package manager |
| `Client` | default transport with a 30s response header timeout | HTTP client |
| `Out` | `os.Stdout` | progress lines |

Expand Down
40 changes: 33 additions & 7 deletions archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -37,10 +38,15 @@ type ArchiveInstaller struct {
SkipChecksum bool // disable verification for repos that publish no checksum file
TargetPath string // default: os.Executable(); symlinks are always resolved
Managed []ManagedInstall // nil means DefaultManagedInstalls; empty slice disables the check
Client *http.Client // default: DefaultTransport clone with a 30s ResponseHeaderTimeout
Client *http.Client // default: a shared DefaultTransport clone with a 30s ResponseHeaderTimeout
Out io.Writer // progress lines; default os.Stdout
}

// defaultClient is built on first use and shared by every ArchiveInstaller
// without an explicit Client. Prepare never writes to the installer, so one
// value may serve concurrent goroutines.
var defaultClient = sync.OnceValue(newDefaultClient)

// archiveStaged holds a verified, extracted binary waiting to be renamed
// over the target.
type archiveStaged struct {
Expand Down Expand Up @@ -103,7 +109,8 @@ func (a *ArchiveInstaller) stage(
}

// download streams asset.URL to path, drawing a progress bar on a
// terminal, and returns the SHA-256 of the bytes written.
// terminal, and returns the SHA-256 of the bytes written. When the release
// lists a size the body must match it exactly.
func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path string) ([]byte, error) {
a.printf("Downloading %s (%s)...\n", asset.Name, formatMB(asset.Size))
hash := sha256.New()
Expand All @@ -113,7 +120,7 @@ func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path strin
return fmt.Errorf("selfupdate: create download: %w", err)
}
progress := newProgressWriter(a.out(), resp.ContentLength)
_, copyErr := io.Copy(io.MultiWriter(f, hash, progress), resp.Body)
copyErr := copyBounded(io.MultiWriter(f, hash, progress), resp.Body, asset.Size)
progress.Finish()
if closeErr := f.Close(); copyErr == nil {
copyErr = closeErr
Expand All @@ -129,6 +136,25 @@ func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path strin
return hash.Sum(nil), nil
}

// copyBounded streams body into dst. A positive size caps the read one
// byte past it, so a hostile payload cannot fill the temp dir before the
// checksum rejects it, and a body of any other length is an error. A zero
// or negative size means the release listed none and the body is unbounded.
func copyBounded(dst io.Writer, body io.Reader, size int64) error {
if size <= 0 {
_, err := io.Copy(dst, body)
return err
}
n, err := io.Copy(dst, io.LimitReader(body, size+1))
if err != nil {
return err
}
if n != size {
return fmt.Errorf("body is %d bytes, release lists %d", n, size)
}
return nil
}

// verify downloads the checksum asset and checks sum against assetName's entry.
func (a *ArchiveInstaller) verify(ctx context.Context, rel Release, assetName string, sum []byte) error {
checksums, err := selectAsset(rel, a.checksumAsset())
Expand Down Expand Up @@ -243,12 +269,12 @@ func (a *ArchiveInstaller) checksumAsset() string {
return DefaultChecksumAsset
}

// client returns Client, creating the default one on first use.
// client returns Client, or the shared default. It never writes to a.
func (a *ArchiveInstaller) client() *http.Client {
if a.Client == nil {
a.Client = newDefaultClient()
if a.Client != nil {
return a.Client
}
return a.Client
return defaultClient()
}

// newDefaultClient clones the default transport and bounds the wait for
Expand Down
75 changes: 70 additions & 5 deletions archive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ var (
_ Staged = (*archiveStaged)(nil)
)

const newBinary = "#!/bin/sh\necho new\n"
const (
newBinary = "#!/bin/sh\necho new\n"
checksumsPath = "/checksums.txt"
)

// archiveFixture serves one release: a tarball for the running platform,
// a checksums.txt, and decoys that must never be selected.
Expand Down Expand Up @@ -67,7 +70,7 @@ func newArchiveFixture(t *testing.T, body string, tamper bool) *archiveFixture {
w.Header().Set("Content-Length", strconv.Itoa(len(archive)))
_, _ = w.Write(archive)
})
mux.HandleFunc("/checksums.txt", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc(checksumsPath, func(w http.ResponseWriter, r *http.Request) {
fx.record(r.URL.Path)
_, _ = io.WriteString(w, checksums)
})
Expand All @@ -82,7 +85,7 @@ func newArchiveFixture(t *testing.T, body string, tamper bool) *archiveFixture {
{Name: fx.assetName + ".sig", URL: fx.srv.URL + "/never.sig", Size: 1},
{Name: "tool_1.2.3_linux_amd64.deb", URL: fx.srv.URL + "/never.deb", Size: 1},
{Name: fx.assetName, URL: fx.srv.URL + "/" + fx.assetName, Size: int64(len(archive))},
{Name: DefaultChecksumAsset, URL: fx.srv.URL + "/checksums.txt", Size: int64(len(checksums))},
{Name: DefaultChecksumAsset, URL: fx.srv.URL + checksumsPath, Size: int64(len(checksums))},
}}
return fx
}
Expand Down Expand Up @@ -110,7 +113,7 @@ func TestArchiveInstaller_PrepareThenCommit(t *testing.T) {
if got := readTarget(t, target); got != contentOld {
t.Fatalf("Prepare must not touch the target, got %q", got)
}
if got := fx.requested(); len(got) != 2 || got[0] != "/"+fx.assetName || got[1] != "/checksums.txt" {
if got := fx.requested(); len(got) != 2 || got[0] != "/"+fx.assetName || got[1] != checksumsPath {
t.Fatalf("requests %v", got)
}

Expand Down Expand Up @@ -194,7 +197,7 @@ func TestArchiveInstaller_SkipChecksum(t *testing.T) {
}
defer func() { _ = staged.Close() }()
for _, p := range fx.requested() {
if p == "/checksums.txt" {
if p == checksumsPath {
t.Fatal("checksums must not be fetched when SkipChecksum is set")
}
}
Expand Down Expand Up @@ -322,3 +325,65 @@ func TestArchiveInstaller_DefaultClientHeaderTimeout(t *testing.T) {
t.Fatal("an explicit Client must be used as is")
}
}

// TestArchiveInstaller_ClientIsConcurrencySafe runs under -race: a shared
// installer must not be mutated by client().
func TestArchiveInstaller_ClientIsConcurrencySafe(t *testing.T) {
inst := &ArchiveInstaller{}
var wg sync.WaitGroup
for range 8 {
wg.Go(func() { _ = inst.client() })
}
wg.Wait()
if inst.Client != nil {
t.Fatal("client() must leave the exported field untouched")
}
}

func TestArchiveInstaller_DownloadSizeMismatchIsRejected(t *testing.T) {
fx := newArchiveFixture(t, newBinary, false)
declared := fx.rel.Assets[2].Size
cases := []struct {
name string
size int64
}{
{"body longer than listed", declared - 1},
{"body shorter than listed", declared + 10},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assets := append([]Asset(nil), fx.rel.Assets...)
assets[2].Size = tc.size
rel := Release{Tag: fx.rel.Tag, Assets: assets}
target := writeTarget(t, contentOld)
staged, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel)
if err == nil || !strings.Contains(err.Error(), "release lists") {
t.Fatalf("got %v", err)
}
if staged != nil {
t.Fatal("no staged update may be returned on failure")
}
if got := readTarget(t, target); got != contentOld {
t.Fatalf("target changed: %q", got)
}
})
}
for _, path := range fx.requested() {
if path == checksumsPath {
t.Fatal("the size check must fail before the checksum file is fetched")
}
}
}

func TestArchiveInstaller_UnknownSizeIsUnbounded(t *testing.T) {
fx := newArchiveFixture(t, newBinary, false)
assets := append([]Asset(nil), fx.rel.Assets...)
assets[2].Size = 0
rel := Release{Tag: fx.rel.Tag, Assets: assets}
target := writeTarget(t, contentOld)
staged, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel)
if err != nil {
t.Fatal(err)
}
_ = staged.Close()
}
16 changes: 11 additions & 5 deletions managed.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,23 @@ type ManagedInstall struct {
Hint string // "{name}" is replaced with the binary name
}

// DefaultManagedInstalls covers Homebrew (any /Cellar/ path), system
// package directories (/usr/bin, /usr/lib) and the Nix store.
// /usr/local/bin and ~/.local/bin are not managed.
// DefaultManagedInstalls covers Homebrew and Linuxbrew (a Cellar formula
// directory), system package directories (/usr/bin, /usr/sbin, /usr/lib,
// /usr/lib64, /usr/libexec) and the Nix store. /usr/local/bin and
// ~/.local/bin are not managed. Patterns are case-sensitive; the target
// comes from EvalSymlinks and so carries on-disk casing.
var DefaultManagedInstalls = []ManagedInstall{
{
Pattern: regexp.MustCompile(`/Cellar/`),
// <prefix>/Cellar/<formula>/<version>/... Anything below the
// version directory is Homebrew's, whether bin, sbin or libexec.
// Requiring the two segments keeps a project directory that
// happens to be named Cellar from being refused.
Pattern: regexp.MustCompile(`/Cellar/[^/]+/[^/]+/`),
Manager: "Homebrew",
Hint: "brew upgrade {name}",
},
{
Pattern: regexp.MustCompile(`^/usr/(bin|lib)/`),
Pattern: regexp.MustCompile(`^/usr/(s?bin|lib(64|exec)?)/`),
Manager: "dpkg/rpm",
Hint: "upgrade {name} with your system package manager (apt, dnf, pacman)",
},
Expand Down
22 changes: 17 additions & 5 deletions managed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ import (
"testing"
)

// managerHomebrew names the literal repeated across the fixtures below so
// its reuse doesn't trip goconst.
const managerHomebrew = "Homebrew"
// managerHomebrew and managerSystem name the literals repeated across the
// fixtures below so their reuse doesn't trip goconst.
const (
managerHomebrew = "Homebrew"
managerSystem = "dpkg/rpm"
)

func TestDetectManaged_Defaults(t *testing.T) {
cases := []struct {
Expand All @@ -19,12 +22,21 @@ func TestDetectManaged_Defaults(t *testing.T) {
}{
{"/opt/homebrew/Cellar/arc/0.15.0/bin/arc", managerHomebrew},
{"/usr/local/Cellar/arc/0.15.0/bin/arc", managerHomebrew},
{"/usr/bin/arc", "dpkg/rpm"},
{"/usr/lib/arc/arc", "dpkg/rpm"},
{"/home/linuxbrew/.linuxbrew/Cellar/arc/0.15.0/bin/arc", managerHomebrew},
{"/opt/homebrew/Cellar/arc/0.15.0/sbin/arc", managerHomebrew},
{"/opt/homebrew/Cellar/arc/0.15.0/libexec/bin/arc", managerHomebrew},
{"/usr/bin/arc", managerSystem},
{"/usr/sbin/arc", managerSystem},
{"/usr/lib/arc/arc", managerSystem},
{"/usr/lib64/arc/arc", managerSystem},
{"/usr/libexec/arc/arc", managerSystem},
{"/nix/store/abc123-arc-0.15.0/bin/arc", "Nix"},
{"/usr/local/bin/arc", ""},
{"/usr/local/lib/arc/arc", ""},
{"/usr/libx/arc", ""},
{"/home/u/.local/bin/arc", ""},
{"/home/u/go/bin/arc", ""},
{"/home/u/projects/Cellar/bin/arc", ""},
{"/opt/arc/bin/arc", ""},
}
for _, tc := range cases {
Expand Down
35 changes: 6 additions & 29 deletions replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,6 @@ var ErrTargetNotWritable = errors.New("selfupdate: target directory is not writa
// renameFile is os.Rename. Tests swap it to simulate a failed install.
var renameFile = os.Rename

// RollbackError reports that the update failed and the original binary
// could not be restored. The install directory needs manual repair.
type RollbackError struct {
Update error
Rollback error
}

func (e *RollbackError) Error() string {
return fmt.Sprintf("selfupdate: update failed (%v) and rollback failed (%v)", e.Update, e.Rollback)
}

// Unwrap exposes the update error to errors.Is and errors.As.
func (e *RollbackError) Unwrap() error { return e.Update }

// preflightWritable creates and removes a temp file in dir. A permission
// error is wrapped with ErrTargetNotWritable so callers can print a
// specific hint. Other errors are returned as they are.
Expand All @@ -45,29 +31,20 @@ func preflightWritable(dir string) error {
return os.Remove(name)
}

// replaceFile installs src at target. It writes <target>.new, renames
// target to <target>.old, renames .new over target and removes .old. When
// the final rename fails it moves .old back and returns the rename error.
// If that restore fails too it returns a *RollbackError.
// 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.
func replaceFile(target string, src io.Reader, mode os.FileMode) error {
newPath, oldPath := target+".new", target+".old"
newPath := target + ".new"
if err := writeFile(newPath, src, mode); err != nil {
return err
}
if err := renameFile(target, oldPath); err != nil {
_ = os.Remove(newPath)
return fmt.Errorf("selfupdate: move old binary aside: %w", err)
}
if err := renameFile(newPath, target); err != nil {
_ = os.Remove(newPath)
if rbErr := renameFile(oldPath, target); rbErr != nil {
return &RollbackError{Update: err, Rollback: rbErr}
}
return fmt.Errorf("selfupdate: install new binary: %w", err)
}
if err := os.Remove(oldPath); err != nil {
return fmt.Errorf("selfupdate: binary was updated but %s could not be removed: %w", oldPath, err)
}
return nil
}

Expand Down
Loading
Loading