diff --git a/CHANGELOG.md b/CHANGELOG.md index d925cfe..c93a827 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ All notable changes to ODM are documented here. The format is based on ## [Unreleased] +### Added + +- Range requests send the file's `ETag` (only a strong one) or + `Last-Modified` as `If-Range`, and a resume checks them first. When the + file on the server has changed, the partial file is discarded and the + download starts again from the first byte. A `200` response whose range + already covers the whole file is kept when that validator still matches. + ## [0.4.3] - 2026-10-19 ### Added diff --git a/README.md b/README.md index 5c5ab21..b7b3509 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,11 @@ queues. It runs as a desktop app, or headless with a JSON API. - A response that ends before its chunk is finished continues from the last byte written. One that brings no bytes at all is retried with a pause and gives up after the retry limit. +- Every range request carries the file's `ETag` (a strong one) or + `Last-Modified` as `If-Range`, and a resume checks them first. If the file + on the server has changed, the partial download is discarded and started + again from the first byte. A `200` for a range that already covers the + whole file is kept when that validator still matches. - Servers that do not support ranges are fetched on a single stream. - Global and per-download speed limits, plus an optional data cap per time window. @@ -209,8 +214,14 @@ only. build the file before it answers. The other connections keep going. 4. **Finish.** The `.odmpart` file is renamed to the final name. -Each chunk's progress (`{id,start,end,done}`) is saved as JSON, so a restart -continues from the exact byte. Segmented ranges, byte-offset resume and chunk +Each chunk's progress (`{id,start,end,done}`) is saved as JSON, together with +the `ETag` and `Last-Modified` from the probe, so a restart continues from +the exact byte while the file on the server is unchanged. If `If-Range` fails +(a `200` with another validator), or a later probe reports a different +validator or size, ODM deletes the partial file and downloads the new one. A +`200` with the same validator is a server ignoring `Range`: it is kept when +the range already covers the whole file. A weak `ETag` is never sent as +`If-Range`. Segmented ranges, byte-offset resume and chunk splitting are standard download-manager techniques. ODM implements them in its own code. diff --git a/internal/engine/download.go b/internal/engine/download.go index 1447097..85ed714 100644 --- a/internal/engine/download.go +++ b/internal/engine/download.go @@ -96,6 +96,15 @@ type Download struct { // DefaultHeaderTimeout when set. Tests use short values; a zero value // means the default. stallTimeout, headerTimeout time.Duration + // ETag and LastModified identify the representation on the server. + // A resume sends one of them as If-Range and starts over when it no + // longer matches. + ETag string + LastModified string + + discardPart bool + changed bool + transferCancel context.CancelFunc } // New creates a queued download. Probing happens on the first Start. @@ -222,58 +231,89 @@ func (d *Download) Start(parent context.Context) { return } - if err := d.prepare(ctx); err != nil { - // A cancelled context means pause (or shutdown) during the probe, not - // a failure; same rule as the ctx.Err() check after the workers. - if ctx.Err() != nil { - d.mu.Lock() - d.Status = StatusPaused - d.mu.Unlock() - } else { - d.fail(err) + // One extra pass covers a representation that changes after the probe: + // the first pass stops, the partial file is dropped, and the second + // pass fetches the new file. A further change is reported as an error. + for pass := 0; pass < 2; pass++ { + if err := d.prepare(ctx); err != nil { + // A cancelled context means pause (or shutdown) during the probe, not + // a failure; same rule as the ctx.Err() check after the workers. + if ctx.Err() != nil { + d.mu.Lock() + d.Status = StatusPaused + d.mu.Unlock() + } else { + d.fail(err) + } + d.notify(true) + return } - d.notify(true) - return - } - workers := d.Connections - if !d.RangeOK { - workers = 1 - } - if workers < 1 { - workers = 1 - } - - var wg sync.WaitGroup - for i := 0; i < workers; i++ { - wg.Add(1) - go func() { defer wg.Done(); d.worker(ctx) }() - } - wg.Wait() + transferCtx, transferCancel := context.WithCancel(ctx) + d.mu.Lock() + d.transferCancel = transferCancel + d.mu.Unlock() - d.mu.Lock() - paused := ctx.Err() != nil - complete := d.allCompleteLocked() - status := d.Status - d.mu.Unlock() + workers := d.Connections + d.mu.Lock() + if !d.RangeOK { + workers = 1 + } + d.mu.Unlock() + if workers < 1 { + workers = 1 + } + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { defer wg.Done(); d.worker(transferCtx) }() + } + wg.Wait() + transferCancel() + d.mu.Lock() + d.transferCancel = nil + paused := ctx.Err() != nil + complete := d.allCompleteLocked() + status := d.Status + changed := d.changed + d.changed = false + d.mu.Unlock() - switch { - case complete: - if err := d.finish(); err != nil { - d.fail(err) - } else { + if paused { d.mu.Lock() - d.Status = StatusComplete + d.Status = StatusPaused d.mu.Unlock() + d.notify(true) + return } - case paused: - d.mu.Lock() - d.Status = StatusPaused - d.mu.Unlock() - case status != StatusError: - d.fail(errors.New("transfer ended with unfinished chunks")) + if changed { + if pass == 1 { + d.fail(errRepresentationChanged) + d.notify(true) + return + } + d.mu.Lock() + d.Status = StatusDownloading + d.Err = "" + d.mu.Unlock() + continue + } + + switch { + case complete: + if err := d.finish(); err != nil { + d.fail(err) + } else { + d.mu.Lock() + d.Status = StatusComplete + d.mu.Unlock() + } + case status != StatusError: + d.fail(errors.New("transfer ended with unfinished chunks")) + } + d.notify(true) + return } - d.notify(true) } func (d *Download) prepare(ctx context.Context) error { @@ -287,28 +327,127 @@ func (d *Download) prepare(ctx context.Context) error { if err != nil { return err } - d.mu.Lock() - d.FinalURL = p.FinalURL - if d.FileName == "" { - d.FileName = p.FileName - } - d.Total = p.Total - d.RangeOK = p.RangeOK - if d.Connections <= 0 { - d.Connections = DefaultConnections - } - if d.SpeedLimit != 0 && d.limiter == nil { - d.limiter = NewLimiter(d.SpeedLimit) + d.applyProbe(p) + } else if err := d.revalidate(ctx); err != nil { + return err + } + return d.openTarget(needProbe) +} + +// applyProbe stores a first probe and builds the chunk plan. The caller +// does not hold d.mu. +func (d *Download) applyProbe(p *Probe) { + d.mu.Lock() + defer d.mu.Unlock() + d.FinalURL = p.FinalURL + if d.FileName == "" { + d.FileName = p.FileName + } + d.Total = p.Total + d.RangeOK = p.RangeOK + d.ETag = p.ETag + d.LastModified = p.LastModified + d.cookies = p.Cookies + if d.Connections <= 0 { + d.Connections = DefaultConnections + } + if d.SpeedLimit != 0 && d.limiter == nil { + d.limiter = NewLimiter(d.SpeedLimit) + } + d.planLocked(p) +} + +// revalidate runs before a resume. When the saved ETag, Last-Modified or +// size no longer matches, the partial file is discarded and planned again. +// +// It asks the address the transfer itself uses (FinalURL, with the cookies +// the first probe got), as a resume did before this check existed: a +// short-lived redirect or token link may no longer work from d.URL. A probe +// that fails is not fatal for the same reason; the resume goes on as it +// used to, and If-Range on every ranged request still catches a changed +// file. A refusal by the local-network guard is final, as everywhere. +func (d *Download) revalidate(ctx context.Context) error { + d.mu.Lock() + rawURL := d.FinalURL + if rawURL == "" { + rawURL = d.URL + } + headers := make(map[string]string, len(d.Headers)+1) + for k, v := range d.Headers { + headers[k] = v + } + if len(d.cookies) > 0 { + headers["Cookie"] = cookieHeader(d.cookies) + } + etag, modified, total, ranged := d.ETag, d.LastModified, d.Total, d.RangeOK + done := d.doneLocked() + d.mu.Unlock() + + p, err := Inspect(ctx, d.guardedClient(), rawURL, headers) + if err != nil { + if ctx.Err() != nil || errors.Is(err, errLocalNetwork) { + return err } + return nil + } + d.mu.Lock() + defer d.mu.Unlock() + // A probe that sets no cookie leaves the saved ones in place. + if len(p.Cookies) > 0 { d.cookies = p.Cookies - if p.RangeOK { - d.Chunks = NewPlan(p.Total, d.Connections) - } else { - d.Chunks = []*Chunk{{ID: 0, Start: 0, End: p.Total - 1}} + } + if p.FinalURL != "" { + d.FinalURL = p.FinalURL + } + if !representationDiffers(etag, modified, total, ranged, done, p) { + if p.ETag != "" { + d.ETag = p.ETag } - d.mu.Unlock() + if p.LastModified != "" { + d.LastModified = p.LastModified + } + return nil } - return d.openTarget(needProbe) + d.ETag = p.ETag + d.LastModified = p.LastModified + d.Total = p.Total + d.RangeOK = p.RangeOK + d.planLocked(p) + d.discardPart = true + return nil +} + +// planLocked replaces the chunk list from a probe. The caller holds d.mu. +func (d *Download) planLocked(p *Probe) { + conns := d.Connections + if conns < 1 { + conns = 1 + } + if p.RangeOK { + d.Chunks = NewPlan(p.Total, conns) + return + } + d.Chunks = []*Chunk{{ID: 0, Start: 0, End: p.Total - 1}} +} + +// representationDiffers reports whether p is a different file from the one +// already partly stored. A missing saved validator does not count, so state +// written before validators were kept still resumes. A different size, or a +// ranged download whose server no longer accepts ranges, does. +func representationDiffers(etag, modified string, total int64, ranged bool, done int64, p *Probe) bool { + if total > 0 && p.Total > 0 && total != p.Total { + return true + } + if etag != "" && p.ETag != "" && etag != p.ETag { + return true + } + if modified != "" && p.LastModified != "" && modified != p.LastModified { + return true + } + if ranged && !p.RangeOK && done > 0 { + return true + } + return false } // openTarget opens the .odmpart file. A fresh download (first probe) claims @@ -320,6 +459,9 @@ func (d *Download) openTarget(fresh bool) error { if d.FileName == "" { d.FileName = "download.bin" } + discard := d.discardPart + d.discardPart = false + existing := d.file dir := d.BaseDir if dir == "" { dir = d.Dir @@ -343,6 +485,18 @@ func (d *Download) openTarget(fresh bool) error { rangeOK, total := d.RangeOK && d.Stream == nil, d.Total d.mu.Unlock() + if existing != nil && !fresh { + if discard { + if err := existing.Truncate(0); err != nil { + return err + } + } + if rangeOK && total > 0 { + return existing.Truncate(total) + } + return nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { return err } @@ -363,6 +517,12 @@ func (d *Download) openTarget(fresh bool) error { return err } } + if discard { + if err := f.Truncate(0); err != nil { + _ = f.Close() + return err + } + } if rangeOK && total > 0 { if err := f.Truncate(total); err != nil { _ = f.Close() @@ -388,6 +548,13 @@ func (d *Download) worker(ctx context.Context) { return } err := d.fetchWithRetry(ctx, ch) + if errors.Is(err, errRepresentationChanged) { + d.noteChanged() + d.mu.Lock() + ch.claimed = false + d.mu.Unlock() + return + } d.mu.Lock() ch.claimed = false if err != nil { @@ -436,6 +603,9 @@ func (d *Download) fetchWithRetry(ctx context.Context, ch *Chunk) error { if err == nil { return nil } + if errors.Is(err, errRepresentationChanged) { + return err + } if ctx.Err() != nil { return ctx.Err() } @@ -465,7 +635,10 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { finalURL := d.FinalURL headers := d.Headers cookies := d.cookies + etag, modified := d.ETag, d.LastModified + total := d.Total d.mu.Unlock() + validator, isETag := ifRangeValidator(etag, modified) req, err := http.NewRequestWithContext(ctx, http.MethodGet, finalURL, nil) if err != nil { @@ -479,6 +652,9 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { // an Accept-Encoding set on the download, which would ask for the // very compressed bytes that cannot be written here. req.Header.Set("Accept-Encoding", "identity") + if validator != "" { + req.Header.Set("If-Range", validator) + } req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end)) } if d.auth != nil { @@ -499,10 +675,22 @@ func (d *Download) fetch(ctx context.Context, ch *Chunk) error { defer resp.Body.Close() if rangeOK { - if resp.StatusCode != http.StatusPartialContent { + // A 200 to a request with If-Range is either a changed file (the + // validator no longer matches, so the server sends the new one + // whole) or a server that ignores Range. The 200's own validator + // tells them apart: a different one restarts the download, the same + // one is the old file, kept when the range already covered all of + // it and otherwise reported as an ignored Range, as without If-Range. + if resp.StatusCode == http.StatusOK && validator != "" { + if !sameValidator(validator, isETag, resp) { + return errRepresentationChanged + } + if !wholeFileOK(start, end, total, resp) { + return fmt.Errorf("server ignored Range (status %s)", resp.Status) + } + } else if resp.StatusCode != http.StatusPartialContent { return fmt.Errorf("server ignored Range (status %s)", resp.Status) - } - if cs, _, _, ok := ParseContentRange(resp.Header.Get("Content-Range")); ok && cs != start { + } else if cs, _, _, ok := ParseContentRange(resp.Header.Get("Content-Range")); ok && cs != start { return fmt.Errorf("range mismatch: asked %d, got %d", start, cs) } } else if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { @@ -684,6 +872,55 @@ func (d *Download) retryDelay() time.Duration { return 300 * time.Millisecond } +// errRepresentationChanged means the server no longer serves the bytes this +// download has partly stored. The partial file is discarded and fetched again. +var errRepresentationChanged = errors.New("file on the server changed") + +// wholeFileOK reports whether a 200 response is the file this request already +// asked for in full. Some servers answer 200, not 206, when the range covers +// every byte and the validator still matches. +func wholeFileOK(start, end, total int64, resp *http.Response) bool { + if total <= 0 || start != 0 || end != total-1 { + return false + } + if n := resp.ContentLength; n >= 0 && n != total { + return false + } + return true +} + +// ifRangeValidator is what a ranged request sends as If-Range, and whether +// it is an ETag: the ETag when it is strong, else Last-Modified, else +// nothing. A weak ETag ("W/") is not allowed there (RFC 9110, 13.1.5), and +// servers such as Go's own http.ServeContent answer it with a full 200: +// every ranged request of a fresh download would look like a changed file. +func ifRangeValidator(etag, modified string) (string, bool) { + if etag != "" && !strings.HasPrefix(etag, "W/") { + return etag, true + } + return modified, false +} + +// sameValidator reports whether resp carries the validator that was sent +// as If-Range. A 200 without it cannot show the file is the same, so it +// counts as changed. +func sameValidator(validator string, isETag bool, resp *http.Response) bool { + if isETag { + return resp.Header.Get("ETag") == validator + } + return resp.Header.Get("Last-Modified") == validator +} + +func (d *Download) noteChanged() { + d.mu.Lock() + d.changed = true + cancel := d.transferCancel + d.mu.Unlock() + if cancel != nil { + cancel() + } +} + func (d *Download) finish() error { d.mu.Lock() f := d.file @@ -871,6 +1108,8 @@ type State struct { OpenWhenDone bool `json:"open_when_done,omitempty"` Total int64 `json:"total"` RangeOK bool `json:"range_ok"` + ETag string `json:"etag,omitempty"` + LastModified string `json:"last_modified,omitempty"` CategoryName string `json:"category_name,omitempty"` Queue string `json:"queue,omitempty"` Description string `json:"description,omitempty"` @@ -910,7 +1149,8 @@ func (d *Download) State() State { BaseDir: d.BaseDir, Headers: d.Headers, Connections: d.Connections, SpeedLimit: d.SpeedLimit, OpenWhenDone: d.OpenWhenDone, CategoryName: d.CategoryName, Queue: d.Queue, Description: d.Description, Order: d.Order, - Total: d.Total, RangeOK: d.RangeOK, Status: status, Err: d.Err, + Total: d.Total, RangeOK: d.RangeOK, ETag: d.ETag, LastModified: d.LastModified, + Status: status, Err: d.Err, Chunks: chunks, Stream: stream, TrustFrom: d.TrustFrom, CreatedAt: d.CreatedAt, UpdatedAt: time.Now(), } } @@ -930,6 +1170,8 @@ func Restore(s State, client *http.Client) *Download { d.Dir = s.Dir d.Total = s.Total d.RangeOK = s.RangeOK + d.ETag = s.ETag + d.LastModified = s.LastModified d.OpenWhenDone = s.OpenWhenDone d.CategoryName = s.CategoryName d.Queue = s.Queue diff --git a/internal/engine/if_range_test.go b/internal/engine/if_range_test.go new file mode 100644 index 0000000..a70a077 --- /dev/null +++ b/internal/engine/if_range_test.go @@ -0,0 +1,480 @@ +package engine + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestRepresentationDiffers(t *testing.T) { + same := &Probe{ETag: `"a"`, LastModified: "Mon, 1 Jan 2024 00:00:00 GMT", Total: 100, RangeOK: true} + if representationDiffers(`"a"`, same.LastModified, 100, true, 10, same) { + t.Fatal("identical probe reported as a different file") + } + if representationDiffers("", "", 100, true, 10, same) { + t.Fatal("a download saved before validators existed must still resume") + } + if !representationDiffers(`"a"`, "", 100, true, 10, &Probe{ETag: `"b"`, Total: 100, RangeOK: true}) { + t.Fatal("etag change was ignored") + } + if !representationDiffers("", same.LastModified, 100, true, 10, &Probe{LastModified: "Tue, 2 Jan 2024 00:00:00 GMT", Total: 100, RangeOK: true}) { + t.Fatal("modification time change was ignored") + } + if !representationDiffers(`"a"`, "", 100, true, 10, &Probe{ETag: `"a"`, Total: 80, RangeOK: true}) { + t.Fatal("size change was ignored") + } + if !representationDiffers("", "", 100, true, 10, &Probe{Total: 100, RangeOK: false}) { + t.Fatal("losing range support with bytes on disk was ignored") + } +} + +func TestResumeSendsIfRangeAndKeepsProgress(t *testing.T) { + data := payload(256 * 1024) + const etag = `"same"` + var sawIfRange atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-Range") == etag { + sawIfRange.Store(true) + } + writeRanged(w, r, data, etag, "Wed, 1 Jan 2025 00:00:00 GMT") + })) + defer srv.Close() + + dir := t.TempDir() + const half = 128 * 1024 + if err := os.WriteFile(filepath.Join(dir, "keep.bin.odmpart"), append(append([]byte{}, data[:half]...), make([]byte, len(data)-half)...), 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "keep", URL: srv.URL + "/keep.bin", FinalURL: srv.URL + "/keep.bin", + FileName: "keep.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if !sawIfRange.Load() { + t.Fatal("resume did not send If-Range") + } + got, err := os.ReadFile(filepath.Join(dir, "keep.bin")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("resumed file does not match") + } + if d.State().ETag != etag { + t.Fatalf("saved etag = %q", d.State().ETag) + } +} + +func TestResumeRestartsWhenETagChanges(t *testing.T) { + oldData := payload(192 * 1024) + newData := make([]byte, len(oldData)) + for i := range newData { + newData[i] = byte(255 - oldData[i]) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeRanged(w, r, newData, `"v2"`, "") + })) + defer srv.Close() + + dir := t.TempDir() + const half = 96 * 1024 + partial := make([]byte, len(oldData)) + copy(partial, oldData[:half]) + if err := os.WriteFile(filepath.Join(dir, "changed.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "changed", URL: srv.URL + "/changed.bin", FinalURL: srv.URL + "/changed.bin", + FileName: "changed.bin", Dir: dir, Connections: 1, Total: int64(len(oldData)), RangeOK: true, + ETag: `"v1"`, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(oldData)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + got, err := os.ReadFile(filepath.Join(dir, "changed.bin")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, newData) { + t.Fatal("file was not replaced after the etag changed") + } + if d.State().ETag != `"v2"` { + t.Fatalf("etag after restart = %q", d.State().ETag) + } +} + +func TestIfRangeFailureRestartsMidTransfer(t *testing.T) { + first := payload(128 * 1024) + second := make([]byte, len(first)) + for i := range second { + second[i] = first[len(first)-1-i] + } + var generation atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + explicit := strings.Contains(r.Header.Get("Range"), "-") && !strings.HasSuffix(r.Header.Get("Range"), "-") + if explicit && r.Header.Get("If-Range") == `"v1"` { + generation.Store(1) + w.Header().Set("ETag", `"v2"`) + w.Header().Set("Content-Length", strconv.Itoa(len(second))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(second) + return + } + data, etag := first, `"v1"` + if generation.Load() > 0 { + data, etag = second, `"v2"` + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + d := New("flip", srv.URL+"/flip.bin", dir, 1, nil, 0, srv.Client()) + d.Start(context.Background()) + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, second) { + t.Fatal("download kept the first representation after If-Range failed") + } +} + +func TestWholeFileOK(t *testing.T) { + resp := &http.Response{Header: make(http.Header), ContentLength: 100} + if !wholeFileOK(0, 99, 100, resp) { + t.Fatal("a full-file 200 was rejected") + } + if wholeFileOK(10, 99, 100, resp) { + t.Fatal("a 200 for a subrange was accepted") + } + resp.ContentLength = 90 + if wholeFileOK(0, 99, 100, resp) { + t.Fatal("a different length was accepted") + } + resp.ContentLength = -1 + if !wholeFileOK(0, 99, 100, resp) { + t.Fatal("unknown length was rejected") + } +} + +func TestIfRangeValidator(t *testing.T) { + const date = "Mon, 01 Jan 2024 00:00:00 GMT" + for _, c := range []struct { + etag, modified, want string + isETag bool + }{ + {`"a"`, date, `"a"`, true}, + {`W/"a"`, date, date, false}, // weak: never sent as If-Range + {`W/"a"`, "", "", false}, + {"", date, date, false}, + {"", "", "", false}, + } { + got, isETag := ifRangeValidator(c.etag, c.modified) + if got != c.want || isETag != c.isETag { + t.Errorf("ifRangeValidator(%q, %q) = %q, %v; want %q, %v", c.etag, c.modified, got, isETag, c.want, c.isETag) + } + } +} + +func TestSameValidator(t *testing.T) { + const date = "Mon, 01 Jan 2024 00:00:00 GMT" + h := make(http.Header) + h.Set("ETag", `"a"`) + h.Set("Last-Modified", date) + resp := &http.Response{Header: h} + if !sameValidator(`"a"`, true, resp) || sameValidator(`"b"`, true, resp) { + t.Fatal("ETag comparison") + } + if !sameValidator(date, false, resp) || sameValidator("Tue, 02 Jan 2024 00:00:00 GMT", false, resp) { + t.Fatal("Last-Modified comparison") + } + // An unquoted (non-standard) ETag is still compared as an ETag. + h.Set("ETag", "abc") + if !sameValidator("abc", true, resp) { + t.Fatal("unquoted ETag") + } + h.Del("ETag") + if sameValidator(`"a"`, true, resp) { + t.Fatal("a 200 without the ETag counted as the same file") + } +} + +// A weak ETag must not go into If-Range: Go's http.ServeContent (like +// RFC 9110) answers it with a full 200, which made every sub-range of a +// fresh multi-connection download look like a changed file. +func TestWeakETagFreshMultiConnection(t *testing.T) { + data := payload(512 * 1024) + var ifRange atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-Range") != "" { + ifRange.Add(1) + } + w.Header().Set("ETag", `W/"weak"`) + http.ServeContent(w, r, "weak.bin", time.Time{}, bytes.NewReader(data)) + })) + defer srv.Close() + + dir := t.TempDir() + d := New("weak", srv.URL+"/weak.bin", dir, 4, nil, 0, srv.Client()) + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := ifRange.Load(); n != 0 { + t.Fatalf("%d requests sent If-Range with a weak ETag and no Last-Modified", n) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") + } +} + +// With a weak ETag and a Last-Modified, the date goes into If-Range, and +// http.ServeContent honours it with 206s. +func TestWeakETagFallsBackToLastModified(t *testing.T) { + data := payload(512 * 1024) + mod := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) + var sent atomic.Value + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if v := r.Header.Get("If-Range"); v != "" { + sent.Store(v) + } + w.Header().Set("ETag", `W/"weak"`) + http.ServeContent(w, r, "weak.bin", mod, bytes.NewReader(data)) + })) + defer srv.Close() + + dir := t.TempDir() + d := New("weak-date", srv.URL+"/weak.bin", dir, 4, nil, 0, srv.Client()) + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if v, _ := sent.Load().(string); v != mod.Format(http.TimeFormat) { + t.Fatalf("If-Range = %q, want the Last-Modified date", v) + } +} + +// A resume checks the file at the address the transfer uses, with the +// cookies the first probe got: a token link that only works there (and +// a server that wants its cookie) resumes as it did before. +func TestResumeRevalidatesFinalURLWithCookies(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + var original atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/start" { + original.Add(1) + http.Error(w, "token expired", http.StatusGone) + return + } + if c, err := r.Cookie("session"); err != nil || c.Value != "s1" { + http.Error(w, "no session", http.StatusForbidden) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + const half = 64 * 1024 + dir := t.TempDir() + partial := make([]byte, len(data)) + copy(partial, data[:half]) + if err := os.WriteFile(filepath.Join(dir, "tok.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + d := Restore(State{ + ID: "tok", URL: srv.URL + "/start", FinalURL: srv.URL + "/file?token=1", + FileName: "tok.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{{ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}}, + }, srv.Client()) + d.cookies = []*http.Cookie{{Name: "session", Value: "s1"}} + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := original.Load(); n != 0 { + t.Fatalf("the original address was probed %d times on resume", n) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") + } +} + +func TestFullFileOKWithSameETagCompletes(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + full := fmt.Sprintf("bytes=0-%d", len(data)-1) + var fullOK atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Range") == full && r.Header.Get("If-Range") == etag { + fullOK.Add(1) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("ETag", etag) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + d := New("full-ok", srv.URL+"/file.bin", dir, 1, nil, 0, srv.Client()) + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusComplete { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if n := fullOK.Load(); n != 1 { + t.Fatalf("full-file 200 responses = %d, want 1", n) + } + got, err := os.ReadFile(filepath.Join(dir, info.FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatal("downloaded bytes do not match the source") + } +} + +// A 200 that carries the same ETag is the old file from a server that +// ignored Range: reported as such, not as a changed file, and nothing is +// written over the bytes already stored. +func TestSubrangeOKWithSameETagDoesNotWrite(t *testing.T) { + data := payload(128 * 1024) + const etag = `"same"` + const half = 64 * 1024 + remainder := fmt.Sprintf("bytes=%d-", half) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Header.Get("Range"), remainder) && r.Header.Get("If-Range") == etag { + w.Header().Set("ETag", etag) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) + return + } + writeRanged(w, r, data, etag, "") + })) + defer srv.Close() + + dir := t.TempDir() + partial := make([]byte, len(data)) + copy(partial, data[:half]) + if err := os.WriteFile(filepath.Join(dir, "part.bin.odmpart"), partial, 0o644); err != nil { + t.Fatal(err) + } + st := State{ + ID: "part", URL: srv.URL + "/part.bin", FinalURL: srv.URL + "/part.bin", + FileName: "part.bin", Dir: dir, Connections: 1, Total: int64(len(data)), RangeOK: true, + ETag: etag, Status: StatusPaused, + Chunks: []*Chunk{ + {ID: 0, Start: 0, End: int64(len(data)) - 1, Done: half}, + }, + } + d := Restore(st, srv.Client()) + d.retryBase = time.Millisecond + t.Cleanup(func() { closeEngineFile(d) }) + d.Start(context.Background()) + + info := d.Info() + if info.Status != StatusError { + t.Fatalf("status=%s err=%q", info.Status, info.Error) + } + if !strings.HasPrefix(info.Error, "server ignored Range") { + t.Fatalf("error=%q, want server ignored Range", info.Error) + } + if _, err := os.Stat(filepath.Join(dir, "part.bin")); !os.IsNotExist(err) { + t.Fatal("partial file was renamed after a subrange 200") + } + got, err := os.ReadFile(filepath.Join(dir, "part.bin.odmpart")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got[:half], data[:half]) { + t.Fatal("bytes already stored were overwritten") + } +} + +func writeRanged(w http.ResponseWriter, r *http.Request, data []byte, etag, modified string) { + w.Header().Set("Accept-Ranges", "bytes") + if etag != "" { + w.Header().Set("ETag", etag) + } + if modified != "" { + w.Header().Set("Last-Modified", modified) + } + spec := strings.TrimPrefix(r.Header.Get("Range"), "bytes=") + parts := strings.SplitN(spec, "-", 2) + start := 0 + if parts[0] != "" { + start, _ = strconv.Atoi(parts[0]) + } + end := len(data) - 1 + if len(parts) == 2 && parts[1] != "" { + if v, err := strconv.Atoi(parts[1]); err == nil { + end = v + } + } + if start < 0 || start >= len(data) || end < start { + http.Error(w, "bad range", http.StatusRequestedRangeNotSatisfiable) + return + } + if end >= len(data) { + end = len(data) - 1 + } + body := data[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data))) + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write(body) +} diff --git a/internal/engine/manager.go b/internal/engine/manager.go index 18bbac3..1bdcf36 100644 --- a/internal/engine/manager.go +++ b/internal/engine/manager.go @@ -808,6 +808,7 @@ func (m *Manager) Readdress(ctx context.Context, id, newURL string) error { d.mu.Lock() d.URL, d.FinalURL, d.cookies = newURL, p.FinalURL, p.Cookies d.TrustFrom = "" // the user gave this address + d.ETag, d.LastModified = p.ETag, p.LastModified if d.Status == StatusError { d.Status, d.Err = StatusPaused, "" }