package fetch import ( "context" "errors" "fmt" "net/http" "os" "strconv" "strings" "time" "github.com/Nwflower/reims-go/internal/atomicfile" ) // InvalidDownloadError marks a validation failure that proves the bytes are bad. // Other validation failures leave the staged bytes and ETag available for retry. type InvalidDownloadError struct{ Err error } func (e *InvalidDownloadError) Error() string { return e.Err.Error() } func (e *InvalidDownloadError) Unwrap() error { return e.Err } // ResumeValidated downloads directly from the supplied client. A strong ETag // binds a partial to the same representation; only a complete, consumer-validated // file is published. The validator checks any consumer-specific integrity data. func ResumeValidated(ctx context.Context, client *http.Client, url, final, part string, maxBytes int64, onProgress Progress, validate func(context.Context, string) error) error { if onProgress == nil { onProgress = func(int64, int64) {} } for _, path := range []string{part, part + ".etag"} { if _, err := plainDownloadFile(path); err != nil { return err } } info, err := plainDownloadFile(final) if err != nil { return err } if info != nil { if info.Size() <= 0 || info.Size() > maxBytes { return errors.New("cached download has an invalid size; delete it before retrying") } onProgress(info.Size(), info.Size()) return validate(ctx, final) } if err := streamValidated(ctx, client, url, part, maxBytes, onProgress); err != nil { return err } if err := validate(ctx, part); err != nil { if ctx.Err() != nil { return ctx.Err() // Keep the partial so validation can be retried. } var invalid *InvalidDownloadError if errors.As(err, &invalid) { return errors.Join(err, removeDownloadPart(part+".etag"), removeDownloadPart(part)) } return err } if err := ctx.Err(); err != nil { return err } if err := removeDownloadPart(part + ".etag"); err != nil { return err } return os.Rename(part, final) } func plainDownloadFile(path string) (os.FileInfo, error) { info, err := os.Lstat(path) if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return nil, err } if !info.Mode().IsRegular() { return nil, fmt.Errorf("download path is not a regular file: %s", path) } return info, nil } func removeDownloadPart(path string) error { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return err } return nil } func streamValidated(ctx context.Context, client *http.Client, url, part string, maxBytes int64, progress Progress) error { info, err := plainDownloadFile(part) if err != nil { return err } var have int64 var validator string if info != nil && info.Size() > 0 && info.Size() <= maxBytes { if tag, err := plainDownloadFile(part + ".etag"); err != nil { return err } else if tag != nil && tag.Size() <= 1024 { data, err := os.ReadFile(part + ".etag") if err != nil { return err } if strongETag(string(data)) { validator, have = string(data), info.Size() } } } retry, err := transferValidated(ctx, client, url, part, validator, have, maxBytes, progress) if retry && err == nil { _, err = transferValidated(ctx, client, url, part, "", 0, maxBytes, progress) } return err } func transferValidated(ctx context.Context, client *http.Client, url, part, validator string, have, maxBytes int64, progress Progress) (bool, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() req, err := NewRequest(ctx, url) if err != nil { return false, err } req.Header.Set("Accept-Encoding", "identity") if have > 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have)) req.Header.Set("If-Range", validator) } resp, err := client.Do(req) if err != nil { return false, err } if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && have > 0 { // A 416 body is not image data; close it before any follow-up request. resp.Body.Close() if !confirmedCompleteRange(client, req, resp, validator, have) { return true, nil } if err := checkValidatedSize(part, have); err != nil { return false, err } progress(have, have) return false, nil } defer resp.Body.Close() tag := singleHeader(resp.Header, "ETag") contentRange := singleHeader(resp.Header, "Content-Range") flags, total := os.O_CREATE|os.O_WRONLY, resp.ContentLength switch resp.StatusCode { case http.StatusPartialContent: if have == 0 || tag != validator || !validTailRange(contentRange, have, resp.ContentLength) { if have > 0 { return true, nil } return false, errors.New("download returned an unsolicited partial response") } flags, total = flags|os.O_APPEND, have+resp.ContentLength case http.StatusOK: have, flags = 0, flags|os.O_TRUNC default: return false, fmt.Errorf("download: HTTP %d", resp.StatusCode) } if !identityEncoding(resp) { return false, errors.New("download returned an unexpected content encoding") } if total <= 0 || total > maxBytes { return false, fmt.Errorf("download has an invalid content length: %d", total) } if have == 0 { if err := resetDownloadValidator(part, tag); err != nil { return false, err } } if err := copyBody(resp.Body, cancel, part, flags, have, total, total, 45*time.Second, "restore image", progress); err != nil { return false, err } return false, checkValidatedSize(part, total) } func confirmedCompleteRange(client *http.Client, req *http.Request, resp *http.Response, validator string, have int64) bool { if !completeRange(singleHeader(resp.Header, "Content-Range"), have) { return false } if tags := resp.Header.Values("ETag"); len(tags) != 0 { return len(tags) == 1 && tags[0] == validator } // Some servers do not send ETag on 416. Confirm the same unencoded // representation via a bounded conditional HEAD, never from length alone. ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second) defer cancel() head := req.Clone(ctx) head.Method = http.MethodHead head.Header.Del("Range") head.Header.Del("If-Range") head.Header.Set("If-Match", validator) meta, err := client.Do(head) if err != nil { return false } defer meta.Body.Close() return meta.StatusCode == http.StatusOK && meta.Request != nil && resp.Request != nil && meta.Request.URL.String() == resp.Request.URL.String() && singleHeader(meta.Header, "ETag") == validator && meta.ContentLength == have && identityEncoding(meta) } func identityEncoding(resp *http.Response) bool { encodings := resp.Header.Values("Content-Encoding") return !resp.Uncompressed && (len(encodings) == 0 || len(encodings) == 1 && strings.EqualFold(encodings[0], "identity")) } func checkValidatedSize(part string, total int64) error { if info, err := plainDownloadFile(part); err != nil || info == nil || info.Size() != total { return errors.Join(errors.New("restore image download is incomplete"), err) } return nil } func resetDownloadValidator(part, tag string) error { if err := removeDownloadPart(part + ".etag"); err != nil { return err } if err := removeDownloadPart(part); err != nil { return err } if !strongETag(tag) { return nil } return atomicfile.Write(part+".etag", []byte(tag), 0o600) } func singleHeader(header http.Header, name string) string { if values := header.Values(name); len(values) == 1 { return values[0] } return "" } func strongETag(tag string) bool { if len(tag) < 2 || len(tag) > 1024 || tag[0] != '"' || tag[len(tag)-1] != '"' { return false } for i := 1; i < len(tag)-1; i++ { if b := tag[i]; b <= ' ' || b == '"' || b == '\x7f' { return false } } return true } func completeRange(header string, have int64) bool { length, ok := strings.CutPrefix(header, "bytes */") return ok && strings.TrimLeft(length, "0") == strconv.FormatInt(have, 10) } func validTailRange(header string, have, length int64) bool { span, totalRaw, ok := strings.Cut(strings.TrimPrefix(header, "bytes "), "/") firstRaw, lastRaw, found := strings.Cut(span, "-") first, e1 := strconv.ParseInt(firstRaw, 10, 64) last, e2 := strconv.ParseInt(lastRaw, 10, 64) total, e3 := strconv.ParseInt(totalRaw, 10, 64) return strings.HasPrefix(header, "bytes ") && ok && found && e1 == nil && e2 == nil && e3 == nil && length > 0 && first == have && last >= first && last < total && total-last == 1 && last-first+1 == length }