796 lines
20 KiB
Go
796 lines
20 KiB
Go
package downloader
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/netproxy"
|
|
)
|
|
|
|
const (
|
|
DefaultConnections = 16
|
|
MaxConnections = 32
|
|
DefaultChunkSize = 8 << 20 // 8 MiB when no Apple CNKL chunklist is present
|
|
DefaultStallTimeout = 15 * time.Second
|
|
DefaultMaxRetries = 6
|
|
)
|
|
|
|
// ParallelOptions configures ParallelDownloader.
|
|
type ParallelOptions struct {
|
|
ID string
|
|
Connections int
|
|
ProxyMode string // "direct" | "auto" | "system"
|
|
ChunkSize int64
|
|
StallTimeout time.Duration
|
|
MaxRetries int
|
|
}
|
|
|
|
// ParallelDownloader is a pure-Go multi-connection HTTP Range downloader with
|
|
// dynamic chunk scheduling, stall detection, Apple CNKL per-chunk SHA-256
|
|
// verification, and instant bitmap resumability.
|
|
type ParallelDownloader struct {
|
|
optsFn func() ParallelOptions
|
|
}
|
|
|
|
// NewParallelDownloader creates a downloader whose options are resolved per
|
|
// download (so plugin setting changes take effect immediately on the next download).
|
|
func NewParallelDownloader(optsFn func() ParallelOptions) *ParallelDownloader {
|
|
return &ParallelDownloader{optsFn: optsFn}
|
|
}
|
|
|
|
func (p *ParallelDownloader) options() ParallelOptions {
|
|
var o ParallelOptions
|
|
if p.optsFn != nil {
|
|
o = p.optsFn()
|
|
}
|
|
if o.ID == "" {
|
|
o.ID = "builtin.downloader.parallel"
|
|
}
|
|
if o.Connections <= 0 {
|
|
o.Connections = DefaultConnections
|
|
}
|
|
if o.Connections > MaxConnections {
|
|
o.Connections = MaxConnections
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(o.ProxyMode)) {
|
|
case ProxyModeAuto:
|
|
o.ProxyMode = ProxyModeAuto
|
|
case ProxyModeSystem:
|
|
o.ProxyMode = ProxyModeSystem
|
|
default:
|
|
o.ProxyMode = ProxyModeDirect
|
|
}
|
|
if o.ChunkSize <= 0 {
|
|
o.ChunkSize = DefaultChunkSize
|
|
}
|
|
if o.StallTimeout <= 0 {
|
|
o.StallTimeout = DefaultStallTimeout
|
|
}
|
|
if o.MaxRetries <= 0 {
|
|
o.MaxRetries = DefaultMaxRetries
|
|
}
|
|
return o
|
|
}
|
|
|
|
func (p *ParallelDownloader) ID() string {
|
|
return p.options().ID
|
|
}
|
|
|
|
// buildHTTPClient creates a dedicated HTTP/1.1 multi-connection client so each
|
|
// worker gets its own independent TCP socket (avoiding HTTP/2 single-connection
|
|
// head-of-line throttling on CDN edge nodes) and respects the configured proxy mode.
|
|
func buildHTTPClient(o ParallelOptions, rawURL string, directHint bool) *http.Client {
|
|
useDirect := false
|
|
switch o.ProxyMode {
|
|
case ProxyModeDirect:
|
|
useDirect = true
|
|
case ProxyModeAuto:
|
|
useDirect = directHint || IsAppleCDNHost(rawURL)
|
|
case ProxyModeSystem:
|
|
useDirect = false
|
|
}
|
|
|
|
var tr *http.Transport
|
|
if useDirect {
|
|
tr = &http.Transport{
|
|
Proxy: nil, // Strict direct connection, bypassing env & Windows system proxy.
|
|
}
|
|
} else {
|
|
tr = netproxy.NewTransport()
|
|
}
|
|
tr.DialContext = (&net.Dialer{
|
|
Timeout: 20 * time.Second,
|
|
KeepAlive: 30 * time.Second,
|
|
}).DialContext
|
|
tr.TLSHandshakeTimeout = 20 * time.Second
|
|
tr.ResponseHeaderTimeout = 30 * time.Second
|
|
tr.MaxIdleConns = o.Connections + 8
|
|
tr.MaxIdleConnsPerHost = o.Connections + 8
|
|
tr.MaxConnsPerHost = o.Connections + 8
|
|
// Disable HTTP/2 multiplexing so concurrent range workers open distinct TCP connections.
|
|
tr.ForceAttemptHTTP2 = false
|
|
tr.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper)
|
|
return &http.Client{Transport: tr}
|
|
}
|
|
|
|
type resumeState struct {
|
|
URL string `json:"url"`
|
|
DestOffset int64 `json:"dest_offset"`
|
|
TotalSize int64 `json:"total_size"`
|
|
ChunkCount int `json:"chunk_count"`
|
|
Done []bool `json:"done"`
|
|
}
|
|
|
|
func statePath(destPath string) string {
|
|
return filepath.Join(filepath.Dir(destPath), "."+filepath.Base(destPath)+".reims-dl.json")
|
|
}
|
|
|
|
func loadResumeState(destPath, rawURL string, destOffset, totalSize int64, chunkCount int) []bool {
|
|
raw, err := os.ReadFile(statePath(destPath))
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var st resumeState
|
|
if json.Unmarshal(raw, &st) != nil {
|
|
return nil
|
|
}
|
|
if st.URL != rawURL || st.DestOffset != destOffset || st.TotalSize != totalSize || st.ChunkCount != chunkCount || len(st.Done) != chunkCount {
|
|
return nil
|
|
}
|
|
return st.Done
|
|
}
|
|
|
|
func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done []bool) {
|
|
st := resumeState{
|
|
URL: rawURL,
|
|
DestOffset: destOffset,
|
|
TotalSize: totalSize,
|
|
ChunkCount: len(done),
|
|
Done: done,
|
|
}
|
|
raw, err := json.Marshal(st)
|
|
if err != nil {
|
|
return
|
|
}
|
|
tmp := statePath(destPath) + ".tmp"
|
|
if os.WriteFile(tmp, raw, 0o644) == nil {
|
|
_ = os.Rename(tmp, statePath(destPath))
|
|
}
|
|
}
|
|
|
|
// Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent
|
|
// HTTP Range requests.
|
|
func (p *ParallelDownloader) Download(ctx context.Context, req Request, onProgress func(Progress)) error {
|
|
if strings.TrimSpace(req.URL) == "" {
|
|
return errors.New("download URL is empty")
|
|
}
|
|
if strings.TrimSpace(req.DestPath) == "" {
|
|
return errors.New("destination path is empty")
|
|
}
|
|
if onProgress == nil {
|
|
onProgress = func(Progress) {}
|
|
}
|
|
opts := p.options()
|
|
client := buildHTTPClient(opts, req.URL, req.DirectHint)
|
|
if req.SameOriginRedirects {
|
|
client.CheckRedirect = CheckSameOriginRedirect
|
|
}
|
|
defer client.CloseIdleConnections()
|
|
|
|
if err := os.MkdirAll(filepath.Dir(req.DestPath), 0o755); err != nil {
|
|
return err
|
|
}
|
|
|
|
var (
|
|
chunks []ChunkSpec
|
|
totalSize int64
|
|
)
|
|
if len(req.IntegrityBytes) > 0 {
|
|
cl, err := ParseCNKL(req.IntegrityBytes)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if req.ExpectedSize > 0 && cl.TotalSize != req.ExpectedSize {
|
|
return fmt.Errorf("chunklist size %d != expected size %d", cl.TotalSize, req.ExpectedSize)
|
|
}
|
|
chunks = cl.Chunks
|
|
totalSize = cl.TotalSize
|
|
} else if req.IntegrityURL != "" {
|
|
cl, err := FetchCNKL(ctx, client, req.IntegrityURL, req.Headers)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if req.ExpectedSize > 0 && cl.TotalSize != req.ExpectedSize {
|
|
return fmt.Errorf("chunklist size %d != expected size %d", cl.TotalSize, req.ExpectedSize)
|
|
}
|
|
chunks = cl.Chunks
|
|
totalSize = cl.TotalSize
|
|
} else {
|
|
sz, rangeOK, err := probeRangeSupport(ctx, client, req.URL, req.Headers)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if req.ExpectedSize > 0 && sz > 0 && sz != req.ExpectedSize {
|
|
return fmt.Errorf("remote size %d != expected size %d", sz, req.ExpectedSize)
|
|
}
|
|
if sz <= 0 {
|
|
sz = req.ExpectedSize
|
|
}
|
|
if !rangeOK || sz <= opts.ChunkSize || opts.Connections <= 1 {
|
|
return p.downloadSerial(ctx, client, req, sz, onProgress)
|
|
}
|
|
totalSize = sz
|
|
chunks = splitEqualChunks(totalSize, opts.ChunkSize)
|
|
}
|
|
|
|
flags := os.O_CREATE | os.O_RDWR
|
|
if !req.Resume && req.DestOffset == 0 {
|
|
flags |= os.O_TRUNC
|
|
}
|
|
f, err := os.OpenFile(req.DestPath, flags, 0o644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
// Ensure file is large enough for WriteAt across all offsets.
|
|
if st, err := f.Stat(); err == nil && st.Size() < req.DestOffset+totalSize {
|
|
if err := f.Truncate(req.DestOffset + totalSize); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
doneMask := make([]bool, len(chunks))
|
|
if req.Resume {
|
|
if loaded := loadResumeState(req.DestPath, req.URL, req.DestOffset, totalSize, len(chunks)); loaded != nil {
|
|
doneMask = loaded
|
|
} else if len(chunks) > 0 && chunks[0].HasHash {
|
|
// Scan existing sequential verified prefix (e.g. a .img.part started by reims-util).
|
|
scanVerifiedPrefix(ctx, f, req.DestOffset, chunks, doneMask)
|
|
}
|
|
}
|
|
|
|
var completedBytes atomic.Int64
|
|
pending := make([]ChunkSpec, 0, len(chunks))
|
|
for i, ch := range chunks {
|
|
if doneMask[i] {
|
|
completedBytes.Add(ch.Size)
|
|
} else {
|
|
pending = append(pending, ch)
|
|
}
|
|
}
|
|
|
|
workers := opts.Connections
|
|
if len(pending) < workers {
|
|
workers = len(pending)
|
|
}
|
|
if workers < 1 {
|
|
// Everything already verified on disk.
|
|
if req.ExpectedSHA256 != "" {
|
|
if err := verifyRegionSHA256(f, req.DestOffset, totalSize, req.ExpectedSHA256); err != nil {
|
|
_ = os.Remove(statePath(req.DestPath))
|
|
return err
|
|
}
|
|
}
|
|
_ = os.Remove(statePath(req.DestPath))
|
|
onProgress(Progress{Done: totalSize, Total: totalSize, Connections: 0})
|
|
return nil
|
|
}
|
|
|
|
var (
|
|
inflightBytes atomic.Int64
|
|
maskMu sync.Mutex
|
|
dirtyCount int
|
|
headersMu sync.RWMutex
|
|
curHeaders = cloneHeaders(req.Headers)
|
|
hdrGen uint64
|
|
)
|
|
getHeaders := func() (map[string]string, uint64) {
|
|
headersMu.RLock()
|
|
cp := cloneHeaders(curHeaders)
|
|
gen := hdrGen
|
|
headersMu.RUnlock()
|
|
return cp, gen
|
|
}
|
|
refreshHeaders := func(rctx context.Context, seenGen uint64) error {
|
|
if req.RefreshHeaders == nil {
|
|
return errors.New("no header refresher configured")
|
|
}
|
|
headersMu.Lock()
|
|
defer headersMu.Unlock()
|
|
if hdrGen != seenGen {
|
|
// Another worker already refreshed the headers while we waited.
|
|
return nil
|
|
}
|
|
next, err := req.RefreshHeaders(rctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for k, v := range next {
|
|
curHeaders[k] = v
|
|
}
|
|
hdrGen++
|
|
return nil
|
|
}
|
|
|
|
dlCtx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
queue := make(chan ChunkSpec, len(pending))
|
|
for _, ch := range pending {
|
|
queue <- ch
|
|
}
|
|
close(queue)
|
|
|
|
// Periodic progress + speed reporter.
|
|
stopReport := make(chan struct{})
|
|
reportDone := make(chan struct{})
|
|
go func() {
|
|
defer close(reportDone)
|
|
ticker := time.NewTicker(250 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
type sample struct {
|
|
at time.Time
|
|
bytes int64
|
|
}
|
|
var window []sample
|
|
startBytes := completedBytes.Load()
|
|
window = append(window, sample{at: time.Now(), bytes: startBytes})
|
|
onProgress(Progress{Done: startBytes, Total: totalSize, Connections: workers})
|
|
|
|
for {
|
|
select {
|
|
case <-stopReport:
|
|
return
|
|
case now := <-ticker.C:
|
|
cur := completedBytes.Load() + inflightBytes.Load()
|
|
if cur > totalSize {
|
|
cur = totalSize
|
|
}
|
|
window = append(window, sample{at: now, bytes: cur})
|
|
// Keep a 3-second sliding window for smooth, responsive MB/s readings.
|
|
cutoff := now.Add(-3 * time.Second)
|
|
for len(window) > 2 && window[1].at.Before(cutoff) {
|
|
window = window[1:]
|
|
}
|
|
var bps float64
|
|
if dt := now.Sub(window[0].at).Seconds(); dt > 0.15 {
|
|
delta := cur - window[0].bytes
|
|
if delta > 0 {
|
|
bps = float64(delta) / dt
|
|
}
|
|
}
|
|
onProgress(Progress{
|
|
Done: cur,
|
|
Total: totalSize,
|
|
SpeedBPS: bps,
|
|
Connections: workers,
|
|
})
|
|
}
|
|
}
|
|
}()
|
|
|
|
var (
|
|
wg sync.WaitGroup
|
|
firstErr error
|
|
errOnce sync.Once
|
|
)
|
|
setErr := func(err error) {
|
|
errOnce.Do(func() {
|
|
firstErr = err
|
|
cancel()
|
|
})
|
|
}
|
|
|
|
for w := 0; w < workers; w++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
buf := make([]byte, 0)
|
|
for ch := range queue {
|
|
if dlCtx.Err() != nil {
|
|
return
|
|
}
|
|
if int64(cap(buf)) < ch.Size {
|
|
buf = make([]byte, ch.Size)
|
|
} else {
|
|
buf = buf[:ch.Size]
|
|
}
|
|
if err := fetchChunkWithRetry(dlCtx, client, req, ch, buf, opts, &inflightBytes, getHeaders, refreshHeaders); err != nil {
|
|
setErr(err)
|
|
return
|
|
}
|
|
if _, err := f.WriteAt(buf, req.DestOffset+ch.Offset); err != nil {
|
|
setErr(fmt.Errorf("write chunk %d at %d: %w", ch.Index, req.DestOffset+ch.Offset, err))
|
|
return
|
|
}
|
|
completedBytes.Add(ch.Size)
|
|
maskMu.Lock()
|
|
doneMask[ch.Index] = true
|
|
dirtyCount++
|
|
if dirtyCount >= 4 {
|
|
cp := append([]bool(nil), doneMask...)
|
|
dirtyCount = 0
|
|
maskMu.Unlock()
|
|
saveResumeState(req.DestPath, req.URL, req.DestOffset, totalSize, cp)
|
|
} else {
|
|
maskMu.Unlock()
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
close(stopReport)
|
|
<-reportDone
|
|
|
|
if firstErr != nil {
|
|
// Persist progress so the next attempt resumes instantaneously.
|
|
maskMu.Lock()
|
|
cp := append([]bool(nil), doneMask...)
|
|
maskMu.Unlock()
|
|
saveResumeState(req.DestPath, req.URL, req.DestOffset, totalSize, cp)
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
return firstErr
|
|
}
|
|
if ctx.Err() != nil {
|
|
maskMu.Lock()
|
|
cp := append([]bool(nil), doneMask...)
|
|
maskMu.Unlock()
|
|
saveResumeState(req.DestPath, req.URL, req.DestOffset, totalSize, cp)
|
|
return ctx.Err()
|
|
}
|
|
|
|
if err := f.Sync(); err != nil {
|
|
return err
|
|
}
|
|
if req.ExpectedSHA256 != "" {
|
|
if err := verifyRegionSHA256(f, req.DestOffset, totalSize, req.ExpectedSHA256); err != nil {
|
|
_ = os.Remove(statePath(req.DestPath))
|
|
return err
|
|
}
|
|
}
|
|
_ = os.Remove(statePath(req.DestPath))
|
|
onProgress(Progress{Done: totalSize, Total: totalSize, Connections: workers})
|
|
return nil
|
|
}
|
|
|
|
var errAuthExpired = errors.New("HTTP 401/403 authorization expired")
|
|
|
|
func cloneHeaders(m map[string]string) map[string]string {
|
|
out := make(map[string]string, len(m))
|
|
for k, v := range m {
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func fetchChunkWithRetry(
|
|
ctx context.Context,
|
|
client *http.Client,
|
|
req Request,
|
|
ch ChunkSpec,
|
|
dst []byte,
|
|
opts ParallelOptions,
|
|
inflight *atomic.Int64,
|
|
getHeaders func() (map[string]string, uint64),
|
|
refreshHeaders func(context.Context, uint64) error,
|
|
) error {
|
|
var lastErr error
|
|
for attempt := 0; attempt < opts.MaxRetries; attempt++ {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
var added int64
|
|
hdrs, gen := getHeaders()
|
|
err := fetchChunkOnce(ctx, client, req, ch, dst, opts.StallTimeout, hdrs, func(n int64) {
|
|
added += n
|
|
inflight.Add(n)
|
|
})
|
|
// Always roll back inflight counter (caller adds ch.Size to completedBytes on success).
|
|
if added > 0 {
|
|
inflight.Add(-added)
|
|
}
|
|
if err == nil {
|
|
if ch.HasHash {
|
|
sum := sha256.Sum256(dst)
|
|
if sum != ch.SHA256 {
|
|
lastErr = fmt.Errorf("chunk %d SHA-256 mismatch", ch.Index)
|
|
continue
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if errors.Is(err, errAuthExpired) && req.RefreshHeaders != nil {
|
|
if rerr := refreshHeaders(ctx, gen); rerr == nil {
|
|
lastErr = err
|
|
continue
|
|
}
|
|
}
|
|
lastErr = err
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
// Exponential backoff capped at 3s.
|
|
backoff := time.Duration(250*(1<<min(attempt, 4))) * time.Millisecond
|
|
if backoff > 3*time.Second {
|
|
backoff = 3 * time.Second
|
|
}
|
|
select {
|
|
case <-time.After(backoff):
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
return fmt.Errorf("chunk %d failed after %d retries: %w", ch.Index, opts.MaxRetries, lastErr)
|
|
}
|
|
|
|
func fetchChunkOnce(
|
|
ctx context.Context,
|
|
client *http.Client,
|
|
req Request,
|
|
ch ChunkSpec,
|
|
dst []byte,
|
|
stallTimeout time.Duration,
|
|
headers map[string]string,
|
|
onBytes func(int64),
|
|
) error {
|
|
reqCtx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
hreq, err := http.NewRequestWithContext(reqCtx, http.MethodGet, req.URL, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
hreq.Header.Set("User-Agent", "reims-go")
|
|
for k, v := range headers {
|
|
hreq.Header.Set(k, v)
|
|
}
|
|
end := ch.Offset + ch.Size - 1
|
|
hreq.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", ch.Offset, end))
|
|
|
|
resp, err := client.Do(hreq)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
|
return fmt.Errorf("%w: HTTP %d", errAuthExpired, resp.StatusCode)
|
|
}
|
|
if resp.StatusCode != http.StatusPartialContent {
|
|
return fmt.Errorf("range request returned HTTP %d", resp.StatusCode)
|
|
}
|
|
if cr := resp.Header.Get("Content-Range"); cr != "" {
|
|
wantPrefix := fmt.Sprintf("bytes %d-%d/", ch.Offset, end)
|
|
if !strings.HasPrefix(cr, wantPrefix) {
|
|
return fmt.Errorf("unexpected Content-Range %q (want prefix %q)", cr, wantPrefix)
|
|
}
|
|
}
|
|
|
|
// Stall watchdog: cancel the request if no bytes arrive within stallTimeout.
|
|
var lastRead atomic.Int64
|
|
lastRead.Store(time.Now().UnixNano())
|
|
watchDone := make(chan struct{})
|
|
go func() {
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-watchDone:
|
|
return
|
|
case <-reqCtx.Done():
|
|
return
|
|
case now := <-ticker.C:
|
|
if now.Sub(time.Unix(0, lastRead.Load())) >= stallTimeout {
|
|
cancel()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
defer close(watchDone)
|
|
|
|
var off int
|
|
for off < len(dst) {
|
|
n, rerr := resp.Body.Read(dst[off:])
|
|
if n > 0 {
|
|
lastRead.Store(time.Now().UnixNano())
|
|
off += n
|
|
onBytes(int64(n))
|
|
}
|
|
if rerr != nil {
|
|
if errors.Is(rerr, io.EOF) && off == len(dst) {
|
|
break
|
|
}
|
|
if ctx.Err() == nil && reqCtx.Err() != nil {
|
|
return fmt.Errorf("chunk %d stalled for %v", ch.Index, stallTimeout)
|
|
}
|
|
return rerr
|
|
}
|
|
}
|
|
if int64(off) != ch.Size {
|
|
return fmt.Errorf("short read for chunk %d: got %d, want %d", ch.Index, off, ch.Size)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func probeRangeSupport(ctx context.Context, client *http.Client, rawURL string, headers map[string]string) (size int64, rangeOK bool, err error) {
|
|
hreq, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
return 0, false, err
|
|
}
|
|
hreq.Header.Set("User-Agent", "reims-go")
|
|
hreq.Header.Set("Range", "bytes=0-0")
|
|
for k, v := range headers {
|
|
hreq.Header.Set(k, v)
|
|
}
|
|
resp, err := client.Do(hreq)
|
|
if err != nil {
|
|
return 0, false, err
|
|
}
|
|
defer resp.Body.Close()
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
|
|
|
switch resp.StatusCode {
|
|
case http.StatusPartialContent:
|
|
if total := parseContentRangeTotal(resp.Header.Get("Content-Range")); total > 0 {
|
|
return total, true, nil
|
|
}
|
|
return 0, false, nil
|
|
case http.StatusOK:
|
|
return resp.ContentLength, false, nil
|
|
default:
|
|
return 0, false, fmt.Errorf("probe %s: HTTP %d", rawURL, resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func parseContentRangeTotal(v string) int64 {
|
|
_, after, ok := strings.Cut(strings.TrimSpace(v), "/")
|
|
if !ok || after == "*" {
|
|
return 0
|
|
}
|
|
n, err := strconv.ParseInt(strings.TrimSpace(after), 10, 64)
|
|
if err != nil || n <= 0 {
|
|
return 0
|
|
}
|
|
return n
|
|
}
|
|
|
|
func splitEqualChunks(total, chunkSize int64) []ChunkSpec {
|
|
var out []ChunkSpec
|
|
var off int64
|
|
for idx := 0; off < total; idx++ {
|
|
sz := chunkSize
|
|
if off+sz > total {
|
|
sz = total - off
|
|
}
|
|
out = append(out, ChunkSpec{Index: idx, Offset: off, Size: sz})
|
|
off += sz
|
|
}
|
|
return out
|
|
}
|
|
|
|
func scanVerifiedPrefix(ctx context.Context, f *os.File, destOffset int64, chunks []ChunkSpec, doneMask []bool) {
|
|
buf := make([]byte, 0)
|
|
for i, ch := range chunks {
|
|
if ctx.Err() != nil || !ch.HasHash {
|
|
return
|
|
}
|
|
if int64(cap(buf)) < ch.Size {
|
|
buf = make([]byte, ch.Size)
|
|
} else {
|
|
buf = buf[:ch.Size]
|
|
}
|
|
n, err := f.ReadAt(buf, destOffset+ch.Offset)
|
|
if err != nil || int64(n) != ch.Size {
|
|
return
|
|
}
|
|
if sha256.Sum256(buf) != ch.SHA256 {
|
|
// Stop at first unverified chunk for prefix scan (matches reims-util sequential layout).
|
|
return
|
|
}
|
|
doneMask[i] = true
|
|
}
|
|
}
|
|
|
|
func verifyRegionSHA256(f *os.File, offset, size int64, want string) error {
|
|
h := sha256.New()
|
|
r := io.NewSectionReader(f, offset, size)
|
|
if _, err := io.CopyBuffer(h, r, make([]byte, 256*1024)); err != nil {
|
|
return err
|
|
}
|
|
got := hex.EncodeToString(h.Sum(nil))
|
|
if !strings.EqualFold(got, strings.TrimSpace(want)) {
|
|
return fmt.Errorf("SHA-256 mismatch (expected %s, got %s)", want, got)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *ParallelDownloader) downloadSerial(ctx context.Context, client *http.Client, req Request, total int64, onProgress func(Progress)) error {
|
|
hreq, err := http.NewRequestWithContext(ctx, http.MethodGet, req.URL, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
hreq.Header.Set("User-Agent", "reims-go")
|
|
for k, v := range req.Headers {
|
|
hreq.Header.Set(k, v)
|
|
}
|
|
resp, err := client.Do(hreq)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("download %s: HTTP %d", req.URL, resp.StatusCode)
|
|
}
|
|
if total <= 0 && resp.ContentLength > 0 {
|
|
total = resp.ContentLength
|
|
}
|
|
flags := os.O_CREATE | os.O_RDWR
|
|
if req.DestOffset == 0 {
|
|
flags |= os.O_TRUNC
|
|
}
|
|
f, err := os.OpenFile(req.DestPath, flags, 0o644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
if req.DestOffset > 0 {
|
|
if _, err := f.Seek(req.DestOffset, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
buf := make([]byte, 256*1024)
|
|
var done int64
|
|
last := time.Now()
|
|
start := last
|
|
for {
|
|
n, rerr := resp.Body.Read(buf)
|
|
if n > 0 {
|
|
if _, werr := f.Write(buf[:n]); werr != nil {
|
|
return werr
|
|
}
|
|
done += int64(n)
|
|
if now := time.Now(); now.Sub(last) >= 200*time.Millisecond {
|
|
var bps float64
|
|
if dt := now.Sub(start).Seconds(); dt > 0 {
|
|
bps = float64(done) / dt
|
|
}
|
|
onProgress(Progress{Done: done, Total: total, SpeedBPS: bps, Connections: 1})
|
|
last = now
|
|
}
|
|
}
|
|
if rerr != nil {
|
|
if errors.Is(rerr, io.EOF) {
|
|
break
|
|
}
|
|
return rerr
|
|
}
|
|
}
|
|
if req.ExpectedSHA256 != "" {
|
|
if err := verifyRegionSHA256(f, req.DestOffset, done, req.ExpectedSHA256); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
onProgress(Progress{Done: done, Total: max(total, done), Connections: 1})
|
|
return nil
|
|
}
|