// Package download fetches vendor installers with retries and optional // checksum pinning. package download import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "mime" "net/http" "net/url" "os" "path" "path/filepath" "strings" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/logx" "git.starwarslab.us/ATOM_IT/Deployr/internal/version" ) // ErrChecksumMissing is returned when --require-checksum is set and the // catalog entry has no sha256. var ErrChecksumMissing = errors.New("no sha256 in catalog and checksum verification is required") // Options controls a download. type Options struct { URL string SHA256 string Dir string // destination directory Filename string // override the derived filename Timeout time.Duration // whole-transfer budget RequireChecksum bool Attempts int Log *logx.Logger } // Fetch downloads a file and returns its path on disk. The transfer lands in a // .part file and is renamed only after the checksum passes, so a killed run can // never leave a truncated installer that looks complete. func Fetch(ctx context.Context, o Options) (string, error) { if o.Attempts <= 0 { o.Attempts = 3 } if o.Timeout <= 0 { o.Timeout = 20 * time.Minute } if o.SHA256 == "" && o.RequireChecksum { return "", ErrChecksumMissing } if err := os.MkdirAll(o.Dir, 0o755); err != nil { return "", fmt.Errorf("create download dir: %w", err) } name := o.Filename if name == "" { name = filenameFromURL(o.URL) } dest := filepath.Join(o.Dir, name) // A cached copy is only trustworthy when the catalog pins a checksum. if o.SHA256 != "" { if sum, err := hashFile(dest); err == nil && strings.EqualFold(sum, o.SHA256) { if o.Log != nil { o.Log.Debugf("using cached download %s", dest) } return dest, nil } } var lastErr error for attempt := 1; attempt <= o.Attempts; attempt++ { if attempt > 1 { delay := time.Duration(attempt-1) * 3 * time.Second if o.Log != nil { o.Log.Debugf("retrying download in %s (attempt %d/%d)", delay, attempt, o.Attempts) } select { case <-ctx.Done(): return "", ctx.Err() case <-time.After(delay): } } p, err := fetchOnce(ctx, o, dest) if err == nil { return p, nil } lastErr = err if errors.Is(err, context.Canceled) { break } } return "", lastErr } func fetchOnce(ctx context.Context, o Options, dest string) (string, error) { ctx, cancel := context.WithTimeout(ctx, o.Timeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, o.URL, nil) if err != nil { return "", fmt.Errorf("bad url %q: %w", o.URL, err) } req.Header.Set("User-Agent", "deployr/"+version.Version) resp, err := http.DefaultClient.Do(req) if err != nil { return "", fmt.Errorf("download %s: %w", o.URL, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("download %s: HTTP %s", o.URL, resp.Status) } // Many vendors serve an evergreen URL that redirects to a versioned file; // prefer the real name so the cache directory stays readable. if o.Filename == "" { if n := filenameFromResponse(resp); n != "" { dest = filepath.Join(o.Dir, n) } } part := dest + ".part" f, err := os.Create(part) if err != nil { return "", fmt.Errorf("create %s: %w", part, err) } hasher := sha256.New() written, err := io.Copy(io.MultiWriter(f, hasher), resp.Body) closeErr := f.Close() if err != nil { os.Remove(part) return "", fmt.Errorf("download %s: %w", o.URL, err) } if closeErr != nil { os.Remove(part) return "", closeErr } if written == 0 { os.Remove(part) return "", fmt.Errorf("download %s: empty response", o.URL) } sum := hex.EncodeToString(hasher.Sum(nil)) if o.SHA256 != "" && !strings.EqualFold(sum, o.SHA256) { os.Remove(part) return "", fmt.Errorf("checksum mismatch for %s: expected %s, got %s", o.URL, o.SHA256, sum) } if err := os.Rename(part, dest); err != nil { os.Remove(part) return "", fmt.Errorf("finalise %s: %w", dest, err) } if o.Log != nil { o.Log.Debugf("downloaded %s (%.1f MB, sha256 %s)", dest, float64(written)/(1<<20), sum[:16]) } return dest, nil } func filenameFromResponse(resp *http.Response) string { if cd := resp.Header.Get("Content-Disposition"); cd != "" { if _, params, err := mime.ParseMediaType(cd); err == nil { if n := sanitize(params["filename"]); n != "" { return n } } } // resp.Request reflects the final URL after redirects. if resp.Request != nil && resp.Request.URL != nil { return filenameFromURL(resp.Request.URL.String()) } return "" } func filenameFromURL(raw string) string { u, err := url.Parse(raw) if err != nil { return "installer.bin" } name := sanitize(path.Base(u.Path)) if name == "" || name == "." || name == "/" { return "installer.bin" } return name } // sanitize strips any directory component so a hostile or sloppy // Content-Disposition header cannot write outside the cache directory. func sanitize(name string) string { name = strings.TrimSpace(name) name = strings.ReplaceAll(name, "\\", "/") name = path.Base(name) if name == "." || name == "/" || name == ".." { return "" } return name } func hashFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil }