From 00d456944e8c3f7db6cca447a6aeb08015b58643 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 11:28:38 +0800 Subject: [PATCH] fix(update): resume an interrupted download Download and DownloadPatch wrote to a fresh temporary file and removed it on any failure, so a dropped connection threw away everything that had arrived and the next call started from byte zero. Nothing bounded a transfer that went silent either: the archive client has no total timeout, so a connection that stopped delivering held the call until the caller's context ended. Keep the bytes in a hidden file named by the feed's digest, and continue it with a Range request on the next call. A 206 is appended only when its Content-Range is exactly the bytes asked for; a 200 starts the file over, and a 206 for another part or a 416 asks once more for the whole file. The whole file is hashed again before it is kept, and a resumed file that fails the check is fetched once from scratch, so a partial a crash left behind cannot end up in the archive. A refusal still leaves no file behind. A transfer that stops part way now wraps the new ErrInterrupted: a failed connection, nothing arriving for a minute, 408, 429 or 5xx, or the end of ctx (wrapping its error too). An untrusted certificate and a redirect off HTTPS are not interruptions. A directory that already holds the verified file is returned without a request, and calls for the same file in one process take turns instead of writing the same partial. --- docs/updating.md | 18 +- update/client.go | 15 +- update/doc.go | 6 +- update/download.go | 418 +++++++++++++++++++++++++++---- update/download_resume_test.go | 439 +++++++++++++++++++++++++++++++++ 5 files changed, 839 insertions(+), 57 deletions(-) create mode 100644 update/download_resume_test.go diff --git a/docs/updating.md b/docs/updating.md index 54ba6414d..201f88740 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -260,6 +260,19 @@ err = update.Install(update.InstallOptions{ }, application.Quit) ``` +A download that stops part way returns an error wrapping +`update.ErrInterrupted`: the connection failed, nothing arrived for a minute, +the host answered with a temporary status (408, 429 or 5xx), or `ctx` ended (the +error then wraps `context.Canceled` or `context.DeadlineExceeded` as well). The +bytes that arrived stay in `downloadDir`, and calling `Download` again with the +same directory sends a `Range` request for the rest; a host that ignores it +sends the whole file, which is fine. When the directory already holds the +verified file, `Download` returns it without a request. Keep `downloadDir` per +release and remove it once the release is installed or skipped. Two processes +must not download the same asset into the same directory at once. +`DownloadPatch` behaves the same way, so a cut-off patch is worth resuming +before falling back to the full archive. + `Install` returns only after it has started the helper that replaces the application; the helper waits for this process to exit. If `Install` returns an error nothing has been changed and `quit` was not called. @@ -294,7 +307,10 @@ installer are per-user by default and need no elevation. another operating system or architecture. - **Exact bytes.** A download is written while it is hashed and is kept only when both its length and SHA-256 match the feed (`ErrSize`, `ErrChecksum`). - A refused download leaves no file behind. `Install` hashes the file again + A refused download leaves no file behind. An interrupted one keeps its bytes + in a hidden file named by the feed's digest, so they are only ever continued + with the rest of the same file, and the whole file is hashed again before it + is kept. `Install` hashes the file again immediately before handing it to the platform, because the file sits on disk between the two calls. - **Bounded.** `latest.json` is limited to 1 MiB, its signature to 4 KiB, an diff --git a/update/client.go b/update/client.go index 8f53172f9..fac858d89 100644 --- a/update/client.go +++ b/update/client.go @@ -49,6 +49,13 @@ var ( // ErrChecksum reports a download whose SHA-256 is not the one the feed // declared. ErrChecksum = errors.New("update: download does not match its checksum") + // ErrInterrupted reports a download that stopped before the file was + // complete: the connection failed, nothing arrived for a minute, the host + // answered with a temporary error, or the caller's context ended (the error + // then wraps the context's error too). The bytes that arrived stay in the + // directory, and calling Download or DownloadPatch again with the same + // directory asks the host only for the rest. + ErrInterrupted = errors.New("update: download interrupted") ) // Config configures a Client. FeedURL, PublicKeys and Current are required. @@ -69,7 +76,8 @@ type Config struct { // HTTP overrides the client used for the feed and its signature. Nil uses a // client with a 30 second timeout. The archive download always uses a client // with no total timeout, because a large installer may take longer than any - // sensible request timeout; the context passed to Download cancels it. + // sensible request timeout; the context passed to Download cancels it, and + // a connection that delivers nothing for a minute ends with ErrInterrupted. HTTP *http.Client // MaxAssetBytes bounds Download. Zero means DefaultMaxAssetBytes. MaxAssetBytes int64 @@ -91,7 +99,9 @@ type Client struct { assetHTTP *http.Client maxAsset int64 maxManifest int64 - now func() time.Time + // stall ends a download that has received nothing for this long. + stall time.Duration + now func() time.Time } // New validates config and returns a Client. @@ -147,6 +157,7 @@ func New(config Config) (*Client, error) { assetHTTP: assetHTTP, maxAsset: maxAsset, maxManifest: DefaultMaxManifestBytes, + stall: stallTimeout, now: now, }, nil } diff --git a/update/doc.go b/update/doc.go index 8860f1a63..28c43886a 100644 --- a/update/doc.go +++ b/update/doc.go @@ -24,8 +24,10 @@ // it is newer than the running version: a check that finds nothing newer // returns (nil, nil). Download streams the archive for the running platform, // hashing as it writes, and refuses a file whose size or digest is not the one -// the feed declared. Neither function sends an identifier, telemetry or -// anything else the caller did not configure. +// the feed declared. A transfer that is cut off, goes silent for a minute or is +// cancelled reports ErrInterrupted and keeps what arrived, so calling Download +// again with the same directory asks only for the rest. Neither function sends +// an identifier, telemetry or anything else the caller did not configure. // // # What this package does not do // diff --git a/update/download.go b/update/download.go index 0d0fe95ec..2f78a9098 100644 --- a/update/download.go +++ b/update/download.go @@ -3,8 +3,11 @@ package update import ( "context" "crypto/sha256" + "crypto/tls" "encoding/hex" + "errors" "fmt" + "hash" "io" "math" "net/http" @@ -12,21 +15,48 @@ import ( "os" "path" "path/filepath" + "strconv" "strings" + "sync" + "time" ) +// stallTimeout ends a download that has received nothing for this long. A +// slow connection still delivers something every few seconds; one that is +// silent for a minute has gone away without saying so. +const stallTimeout = time.Minute + +// errStalled is the cause a download's context is cancelled with when nothing +// arrived for the stall timeout. +var errStalled = errors.New("update: download stalled") + // Download streams asset into dir and returns the file's path. The bytes are -// hashed as they arrive and the call fails without keeping a file unless the -// length and SHA-256 are exactly the ones the feed declared; a partially -// written download is removed. +// hashed as they arrive and the file is kept under its own name only when its +// length and SHA-256 are exactly the ones the feed declared. +// +// A transfer that stops part way, because the connection failed, went silent +// for a minute, the host answered with a temporary error or ctx ended, returns +// an error wrapping ErrInterrupted and keeps the bytes that arrived in a hidden +// file in dir. Calling Download again with the same asset and dir asks the host +// only for the rest; the whole file is still checked against the feed's digest +// before it is kept, and a file that fails that check is fetched again from the +// start once. When dir already holds the verified file, Download returns it +// without a request. +// +// dir must belong to the application: another user who can write to it could +// put a link where the partial file goes. Two processes must not download the +// same asset into the same dir at once; calls within one process wait for each +// other. // // progress, when not nil, is called while the file arrives with the bytes -// written so far and the total the feed declared. It runs on the goroutine -// calling Download, so it may update state directly but must not block. +// written so far and the total the feed declared; a resumed download starts at +// the bytes it kept. It runs on the goroutine calling Download, so it may update +// state directly but must not block. // // An archive is not unpacked or installed here: this method only guarantees // the file is the one the signed feed named. A refusal wraps ErrChecksum, -// ErrSize, ErrTooLarge, ErrInsecureURL or ErrManifest. +// ErrSize, ErrTooLarge, ErrInsecureURL or ErrManifest, and leaves no partial +// file behind. func (client *Client) Download(ctx context.Context, asset Asset, dir string, progress func(done, total int64)) (string, error) { if err := asset.validate(); err != nil { return "", fmt.Errorf("%w: %w", ErrManifest, err) @@ -38,10 +68,10 @@ func (client *Client) Download(ctx context.Context, asset Asset, dir string, pro } // DownloadPatch streams a delta update into dir and returns the patch file's -// path. It checks the bytes exactly as Download does, against the size and -// SHA-256 the signed feed declared for the patch. The patch is not applied -// here: ReadPatch and PatchReader.Apply do that, after the caller has checked the -// patch names the running application and version. +// path. It checks, keeps and resumes the bytes exactly as Download does, against +// the size and SHA-256 the signed feed declared for the patch. The patch is not +// applied here: ReadPatch and PatchReader.Apply do that, after the caller has +// checked the patch names the running application and version. func (client *Client) DownloadPatch(ctx context.Context, asset Asset, patch Patch, dir string, progress func(done, total int64)) (string, error) { if err := asset.validate(); err != nil { return "", fmt.Errorf("%w: %w", ErrManifest, err) @@ -56,8 +86,8 @@ func (client *Client) DownloadPatch(ctx context.Context, asset Asset, patch Patc return client.download(ctx, patch.URL, patch.Size, patch.SHA256, name, dir, progress) } -// download fetches one file and keeps it only when its length and digest are -// the declared ones. +// download fetches one file, resuming what an earlier call kept, and keeps it +// under name only when its length and digest are the declared ones. func (client *Client) download(ctx context.Context, rawURL string, size int64, digest string, name, dir string, progress func(done, total int64)) (string, error) { if size >= math.MaxInt64 { return "", fmt.Errorf("%w: file is %d bytes", ErrTooLarge, size) @@ -65,68 +95,295 @@ func (client *Client) download(ctx context.Context, rawURL string, size int64, d if err := os.MkdirAll(dir, 0o755); err != nil { return "", fmt.Errorf("update: %w", err) } - request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + partial := filepath.Join(dir, partialName(digest)) + unlock, err := transfers.lock(ctx, partial) if err != nil { - return "", fmt.Errorf("update: %w", err) + return "", err + } + defer unlock() + + destination := filepath.Join(dir, name) + if holds(destination, size, digest) { + report(progress, size, size) + return destination, nil + } + resumed, err := client.fetchFile(ctx, rawURL, size, digest, partial, progress) + if err != nil && resumed && (errors.Is(err, ErrChecksum) || errors.Is(err, ErrSize)) { + // The kept bytes were not the start of this file: a crash wrote less than + // it reported, or the host was serving something else then. The partial is + // gone, so this asks for the whole file. + _, err = client.fetchFile(ctx, rawURL, size, digest, partial, progress) } - request.Header.Set("User-Agent", "viva-update/1") - response, err := client.assetHTTP.Do(request) if err != nil { - return "", fmt.Errorf("update: %w", err) + return "", err } - defer response.Body.Close() - if response.Request != nil && response.Request.URL != nil && response.Request.URL.Scheme != "https" { - return "", fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, rawURL, response.Request.URL) + if err := os.Chmod(partial, 0o644); err != nil { + return "", fmt.Errorf("update: %w", err) } - if response.StatusCode != http.StatusOK { - return "", fmt.Errorf("update: %s: %s", rawURL, response.Status) + if err := os.Rename(partial, destination); err != nil { + return "", fmt.Errorf("update: %w", err) } + report(progress, size, size) + return destination, nil +} - file, err := os.CreateTemp(dir, ".viva-update-*") +// fetchFile brings partial up to size bytes, asking the host only for what it does +// not hold yet, and checks the whole file against digest. resumed reports that +// the bytes it checked include some kept from before this call. A refusal +// removes partial; an interruption keeps it for the next call. +func (client *Client) fetchFile(ctx context.Context, rawURL string, size int64, digest, partial string, progress func(done, total int64)) (resumed bool, err error) { + file, offset, hasher, err := openPartial(partial, size) if err != nil { - return "", fmt.Errorf("update: %w", err) + return false, err } - temporary := file.Name() - keep := false + refused := false defer func() { _ = file.Close() - if !keep { - _ = os.Remove(temporary) + if refused { + _ = os.Remove(partial) + } else if info, statErr := os.Lstat(partial); statErr == nil && info.Size() == 0 { + _ = os.Remove(partial) } }() + resumed = offset > 0 + report(progress, offset, size) - hasher := sha256.New() - writer := io.MultiWriter(file, hasher) - if progress != nil { - progress(0, size) - } - counter := &progressWriter{writer: writer, total: size, progress: progress} - written, err := io.Copy(counter, io.LimitReader(response.Body, size+1)) - if err != nil { - return "", fmt.Errorf("update: reading %s: %w", rawURL, err) + if offset < size { + written, err := client.transfer(ctx, rawURL, size, offset, file, hasher, progress) + offset, resumed = written.size, written.resumed + if err != nil { + return resumed, err + } } - if written != size { - return "", fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, written, size) + if offset != size { + refused = true + return resumed, fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, offset, size) } if err := file.Close(); err != nil { - return "", fmt.Errorf("update: %w", err) + return resumed, fmt.Errorf("update: %w", err) } sum := hex.EncodeToString(hasher.Sum(nil)) if !strings.EqualFold(sum, digest) { - return "", fmt.Errorf("%w: %s", ErrChecksum, sum) + refused = true + return resumed, fmt.Errorf("%w: %s", ErrChecksum, sum) } - if err := os.Chmod(temporary, 0o644); err != nil { - return "", fmt.Errorf("update: %w", err) + return resumed, nil +} + +// transferred is what a transfer left in the partial file: its length, and +// whether that still starts with bytes kept from an earlier call. +type transferred struct { + size int64 + resumed bool +} + +// transfer asks the host for the bytes from offset on and appends them to file +// and hasher. A host that ignores the range, or answers for another part of the +// file, makes it start over from the first byte. Nothing arriving for the +// client's stall timeout ends it with ErrInterrupted, as does a failed +// connection, a temporary status or the end of ctx. +func (client *Client) transfer(ctx context.Context, rawURL string, size, offset int64, file *os.File, hasher hash.Hash, progress func(done, total int64)) (transferred, error) { + state := transferred{size: offset, resumed: offset > 0} + watched, stop := context.WithCancelCause(ctx) + defer stop(nil) + stall := client.stall + if stall <= 0 { + stall = stallTimeout } - destination := filepath.Join(dir, name) - if err := os.Rename(temporary, destination); err != nil { - return "", fmt.Errorf("update: %w", err) + watchdog := time.AfterFunc(stall, func() { stop(errStalled) }) + defer watchdog.Stop() + alive := func() { watchdog.Reset(stall) } + interrupted := func(err error) error { + if ctx.Err() != nil { + return fmt.Errorf("%w: %w", ErrInterrupted, ctx.Err()) + } + if errors.Is(context.Cause(watched), errStalled) { + return fmt.Errorf("%w: %s: nothing arrived for %s", ErrInterrupted, rawURL, stall) + } + return fmt.Errorf("%w: %s: %w", ErrInterrupted, rawURL, err) + } + startOver := func() error { + state = transferred{} + hasher.Reset() + if err := file.Truncate(0); err != nil { + return fmt.Errorf("update: %w", err) + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("update: %w", err) + } + report(progress, 0, size) + return nil + } + + var response *http.Response + for { + var err error + response, err = client.requestFrom(watched, rawURL, state.size) + if err != nil { + if errors.Is(err, ErrInsecureURL) || !transient(err) { + return state, err + } + return state, interrupted(err) + } + alive() + status := response.StatusCode + if status == http.StatusPartialContent && state.size > 0 && rangeFrom(response.Header.Get("Content-Range"), state.size, size) { + break + } + if status == http.StatusOK { + if state.size > 0 { + // The host ignored the range and sent the whole file. + if err := startOver(); err != nil { + _ = response.Body.Close() + return state, err + } + } + break + } + _ = response.Body.Close() + if state.size > 0 && (status == http.StatusPartialContent || status == http.StatusRequestedRangeNotSatisfiable) { + // An answer for another part of the file, or none: the kept bytes + // cannot be continued, so ask once more for all of it. + if err := startOver(); err != nil { + return state, err + } + continue + } + failure := fmt.Errorf("update: %s: %s", rawURL, response.Status) + if temporaryStatus(status) { + return state, interrupted(failure) + } + return state, failure } - keep = true + defer response.Body.Close() + + body := &watchedReader{reader: response.Body, alive: alive} + counter := &progressWriter{writer: io.MultiWriter(file, hasher), total: size, done: state.size, progress: progress} + written, err := io.Copy(counter, io.LimitReader(body, size-state.size+1)) + state.size += written + if err != nil { + if body.failed { + return state, interrupted(err) + } + return state, fmt.Errorf("update: writing %s: %w", file.Name(), err) + } + return state, nil +} + +// requestFrom asks for rawURL, from byte offset on when offset is not zero. +func (client *Client) requestFrom(ctx context.Context, rawURL string, offset int64) (*http.Response, error) { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, fmt.Errorf("update: %w", err) + } + request.Header.Set("User-Agent", "viva-update/1") + if offset > 0 { + request.Header.Set("Range", "bytes="+strconv.FormatInt(offset, 10)+"-") + } + response, err := client.assetHTTP.Do(request) + if err != nil { + return nil, fmt.Errorf("update: %w", err) + } + if response.Request != nil && response.Request.URL != nil && response.Request.URL.Scheme != "https" { + _ = response.Body.Close() + return nil, fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, rawURL, response.Request.URL) + } + return response, nil +} + +// openPartial opens the file a download is kept in while it arrives and hashes +// what it already holds. Anything there that is not a regular file is removed, +// and a file longer than size is emptied: neither can be the start of this one. +func openPartial(partial string, size int64) (*os.File, int64, hash.Hash, error) { + if info, err := os.Lstat(partial); err == nil && !info.Mode().IsRegular() { + if err := os.Remove(partial); err != nil { + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + } + file, err := os.OpenFile(partial, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + hasher := sha256.New() + offset, err := io.Copy(hasher, io.LimitReader(file, size+1)) + if err == nil && offset > size { + offset = 0 + hasher.Reset() + err = file.Truncate(0) + } + if err == nil { + _, err = file.Seek(offset, io.SeekStart) + } + if err != nil { + _ = file.Close() + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + return file, offset, hasher, nil +} + +// partialName is the hidden file a download is kept in until it is complete. +// It is named by the digest, so bytes are only ever continued with the rest of +// the same file. +func partialName(digest string) string { + return ".viva-update-" + strings.ToLower(digest) + ".part" +} + +// holds reports whether path is a regular file of exactly size bytes whose +// SHA-256 is digest. +func holds(path string, size int64, digest string) bool { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() != size { + return false + } + file, err := os.Open(path) + if err != nil { + return false + } + defer file.Close() + hasher := sha256.New() + if written, err := io.Copy(hasher, io.LimitReader(file, size+1)); err != nil || written != size { + return false + } + return strings.EqualFold(hex.EncodeToString(hasher.Sum(nil)), digest) +} + +// rangeFrom reports whether a Content-Range header answers a request for the +// bytes from offset to the end of a file of size bytes, and nothing else. +func rangeFrom(header string, offset, size int64) bool { + spec, ok := strings.CutPrefix(header, "bytes ") + if !ok { + return false + } + span, complete, ok := strings.Cut(spec, "/") + if !ok || (complete != "*" && complete != strconv.FormatInt(size, 10)) { + return false + } + first, last, ok := strings.Cut(span, "-") + return ok && first == strconv.FormatInt(offset, 10) && last == strconv.FormatInt(size-1, 10) +} + +// temporaryStatus reports a status a host answers with while it is busy or +// restarting, after which the same request may succeed. +func temporaryStatus(status int) bool { + switch status { + case http.StatusRequestTimeout, http.StatusTooManyRequests, http.StatusInternalServerError, + http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + return true + } + return false +} + +// transient reports whether a failed request may succeed when tried again. A +// certificate the system does not trust will not start being trusted. +func transient(err error) bool { + var certificate *tls.CertificateVerificationError + return !errors.As(err, &certificate) +} + +func report(progress func(done, total int64), done, total int64) { if progress != nil { - progress(size, size) + progress(done, total) } - return destination, nil } type progressWriter struct { @@ -139,12 +396,69 @@ type progressWriter struct { func (writer *progressWriter) Write(data []byte) (int, error) { written, err := writer.writer.Write(data) writer.done += int64(written) - if writer.progress != nil { - writer.progress(writer.done, writer.total) - } + report(writer.progress, writer.done, writer.total) return written, err } +// watchedReader tells alive whenever bytes arrive and remembers that the +// connection, rather than the file being written, failed. +type watchedReader struct { + reader io.Reader + alive func() + failed bool +} + +func (reader *watchedReader) Read(data []byte) (int, error) { + n, err := reader.reader.Read(data) + if n > 0 { + reader.alive() + } + if err != nil && err != io.EOF { + reader.failed = true + } + return n, err +} + +// transfers lets one download at a time use a partial file, so two calls in +// this process for the same file in the same directory take turns; the second +// then finds the first one's verified file. +var transfers keyedLock + +type keyedLock struct { + mu sync.Mutex + held map[string]chan struct{} +} + +func (locks *keyedLock) lock(ctx context.Context, key string) (func(), error) { + if absolute, err := filepath.Abs(key); err == nil { + key = absolute + } + for { + locks.mu.Lock() + wait, busy := locks.held[key] + if !busy { + if locks.held == nil { + locks.held = make(map[string]chan struct{}) + } + done := make(chan struct{}) + locks.held[key] = done + locks.mu.Unlock() + return func() { + locks.mu.Lock() + delete(locks.held, key) + locks.mu.Unlock() + close(done) + }, nil + } + locks.mu.Unlock() + select { + case <-wait: + case <-ctx.Done(): + return nil, fmt.Errorf("%w: %w", ErrInterrupted, ctx.Err()) + } + } +} + // assetFileName is the name an archive is saved under: the last element of // its URL path, or a fixed name when that is not a plain file name. A backslash // is a path separator on Windows even when the URL wrote "%5C", so the name is diff --git a/update/download_resume_test.go b/update/download_resume_test.go new file mode 100644 index 000000000..cb06783e4 --- /dev/null +++ b/update/download_resume_test.go @@ -0,0 +1,439 @@ +package update + +import ( + "bytes" + "context" + "crypto/ed25519" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// resumeServer answers each request with the handler for its number, counting +// from zero, and records the Range header every request carried. +type resumeServer struct { + *httptest.Server + mu sync.Mutex + ranges []string +} + +func (server *resumeServer) requests() []string { + server.mu.Lock() + defer server.mu.Unlock() + return append([]string(nil), server.ranges...) +} + +func newResumeServer(t *testing.T, handlers ...func(http.ResponseWriter, *http.Request)) (*resumeServer, *Client) { + t.Helper() + server := &resumeServer{} + server.Server = httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server.mu.Lock() + index := len(server.ranges) + server.ranges = append(server.ranges, request.Header.Get("Range")) + server.mu.Unlock() + if index >= len(handlers) { + t.Errorf("unexpected request %d", index+1) + http.Error(writer, "unexpected", http.StatusInternalServerError) + return + } + handlers[index](writer, request) + })) + t.Cleanup(server.Close) + client, err := New(Config{ + FeedURL: server.URL + "/latest.json", + PublicKeys: []ed25519.PublicKey{make(ed25519.PublicKey, ed25519.PublicKeySize)}, + Current: "1.0.0", + HTTP: server.Client(), + }) + if err != nil { + t.Fatal(err) + } + return server, client +} + +// cutAfter declares the whole file, sends its first n bytes and drops the +// connection, the way a network that fails mid-transfer does. +func cutAfter(content []byte, n int) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:n]) + writer.(http.Flusher).Flush() + panic(http.ErrAbortHandler) + } +} + +// serveRanges answers with the file, honouring a Range header as a release +// host does. +func serveRanges(content []byte) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + http.ServeContent(writer, request, "app.zip", time.Time{}, bytes.NewReader(content)) + } +} + +// serveWhole answers with the whole file and ignores any Range header. +func serveWhole(content []byte) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + _, _ = writer.Write(content) + } +} + +func resumeContent() []byte { + return bytes.Repeat([]byte("0123456789abcdef"), 4096) // 64 KiB +} + +func assertFileHolds(t *testing.T, path string, want []byte) { + t.Helper() + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s holds %d bytes that are not the file's %d", filepath.Base(path), len(got), len(want)) + } +} + +func assertOnlyEntry(t *testing.T, dir, name string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != name { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("directory holds %v, want only %s", names, name) + } +} + +func TestDownloadResumesAnInterruptedTransfer(t *testing.T) { + content := resumeContent() + half := len(content) / 2 + server, client := newResumeServer(t, cutAfter(content, half), serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + _, err := client.Download(context.Background(), asset, dir, nil) + if !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + if errors.Is(err, context.Canceled) { + t.Fatalf("a dropped connection reads as a cancel: %v", err) + } + partial := filepath.Join(dir, partialName(asset.SHA256)) + info, err := os.Stat(partial) + if err != nil { + t.Fatalf("the bytes that arrived were not kept: %v", err) + } + if info.Size() != int64(half) { + t.Fatalf("kept %d bytes, want %d", info.Size(), half) + } + + var first [2]int64 + calls := 0 + path, err := client.Download(context.Background(), asset, dir, func(done, total int64) { + if calls == 0 { + first = [2]int64{done, total} + } + calls++ + }) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[0] != "" || got[1] != fmt.Sprintf("bytes=%d-", half) { + t.Fatalf("Range headers = %q, want none then bytes=%d-", got, half) + } + if first != [2]int64{int64(half), int64(len(content))} { + t.Errorf("a resumed download first reports %v, want what was kept", first) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenTheServerIgnoresTheRange(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, cutAfter(content, 1000), serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=1000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenTheRangeAnswerIsAnotherPart(t *testing.T) { + content := resumeContent() + wrongRange := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(content)-1, len(content))) + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusPartialContent) + _, _ = writer.Write(content) + } + server, client := newResumeServer(t, cutAfter(content, 1000), wrongRange, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 3 || got[1] != "bytes=1000-" || got[2] != "" { + t.Fatalf("Range headers = %q, want a range and then the whole file", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadStartsOverWhenTheRangeIsRefused(t *testing.T) { + content := resumeContent() + refuse := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(content))) + writer.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + } + server, client := newResumeServer(t, cutAfter(content, 1000), refuse, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 3 || got[1] != "bytes=1000-" || got[2] != "" { + t.Fatalf("Range headers = %q, want a range and then the whole file", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenKeptBytesAreNotTheFile(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveRanges(content), serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + // What a crash can leave: a file of the right length so far, but zeros. + stale := make([]byte, 5000) + if err := os.WriteFile(filepath.Join(dir, partialName(asset.SHA256)), stale, 0o600); err != nil { + t.Fatal(err) + } + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[0] != "bytes=5000-" || got[1] != "" { + t.Fatalf("Range headers = %q, want a resume and then the whole file", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadRefusesTheWholeFileOnceAfterAResumeFails(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveRanges(content), serveRanges(content)) + asset := testAsset(server.Server, content) + asset.SHA256 = testDigest("another file") + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, partialName(asset.SHA256)), content[:5000], 0o600); err != nil { + t.Fatal(err) + } + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrChecksum) { + t.Fatalf("Download: %v, want ErrChecksum", err) + } + if got := server.requests(); len(got) != 2 { + t.Fatalf("made %d requests, want the resume and one fresh attempt", len(got)) + } + assertEmptyDirectory(t, dir) +} + +func TestDownloadReusesAVerifiedFile(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("first Download: %v", err) + } + var last [2]int64 + again, err := client.Download(context.Background(), asset, dir, func(done, total int64) { last = [2]int64{done, total} }) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if again != path { + t.Errorf("second Download returned %q, want %q", again, path) + } + if got := server.requests(); len(got) != 1 { + t.Errorf("made %d requests, want the file on disk reused", len(got)) + } + if last != [2]int64{int64(len(content)), int64(len(content))} { + t.Errorf("progress = %v, want complete", last) + } +} + +func TestDownloadReplacesAFileThatIsNotTheRelease(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "app.zip"), []byte("an older release"), 0o644); err != nil { + t.Fatal(err) + } + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("Download: %v", err) + } + if got := server.requests(); len(got) != 1 { + t.Fatalf("made %d requests, want one", len(got)) + } + assertFileHolds(t, path, content) +} + +func TestDownloadEndsAStalledTransfer(t *testing.T) { + content := resumeContent() + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + stall := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:2000]) + writer.(http.Flusher).Flush() + select { + case <-request.Context().Done(): + case <-release: + } + } + server, client := newResumeServer(t, stall, serveRanges(content)) + client.stall = 50 * time.Millisecond + asset := testAsset(server.Server, content) + dir := t.TempDir() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Download(ctx, asset, dir, nil) + if !errors.Is(err, ErrInterrupted) { + t.Fatalf("stalled Download: %v, want ErrInterrupted", err) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a stall reads as the caller's cancel or deadline: %v", err) + } + if ctx.Err() != nil { + t.Fatal("the stall was not detected before the test's own deadline") + } + path, err := client.Download(ctx, asset, dir, nil) + if err != nil { + t.Fatalf("resumed Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=2000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadKeepsTheBytesWhenCancelled(t *testing.T) { + content := resumeContent() + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + hold := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:3000]) + writer.(http.Flusher).Flush() + select { + case <-request.Context().Done(): + case <-release: + } + } + server, client := newResumeServer(t, hold, serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + ctx, cancel := context.WithCancel(context.Background()) + _, err := client.Download(ctx, asset, dir, func(done, total int64) { + if done >= 3000 { + cancel() + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled Download: %v, want context.Canceled", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("resumed Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=3000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadPatchResumesAnInterruptedTransfer(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, cutAfter(content, 4096), serveRanges(content)) + asset := testAsset(server.Server, []byte("the full archive")) + patch := Patch{ + FromVersion: "0.9.0", URL: server.URL + "/downloads/app.patch", + Size: int64(len(content)), SHA256: testDigest(string(content)), + } + asset.Patches = []Patch{patch} + dir := t.TempDir() + + if _, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first DownloadPatch: %v, want ErrInterrupted", err) + } + path, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil) + if err != nil { + t.Fatalf("second DownloadPatch: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=4096-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadCallsAServerErrorAnInterruption(t *testing.T) { + content := resumeContent() + unavailable := func(writer http.ResponseWriter, request *http.Request) { + http.Error(writer, "busy", http.StatusServiceUnavailable) + } + missing := func(writer http.ResponseWriter, request *http.Request) { + http.NotFound(writer, request) + } + server, client := newResumeServer(t, unavailable, missing) + asset := testAsset(server.Server, content) + + if _, err := client.Download(context.Background(), asset, t.TempDir(), nil); !errors.Is(err, ErrInterrupted) { + t.Errorf("503: %v, want ErrInterrupted", err) + } + _, err := client.Download(context.Background(), asset, t.TempDir(), nil) + if err == nil || errors.Is(err, ErrInterrupted) || !strings.Contains(err.Error(), "404") { + t.Errorf("404: %v, want a status error that is not an interruption", err) + } +}