1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
package util
import (
"context"
"errors"
"fmt"
"hash"
"io"
"net/http"
"github.com/lxc/incus/v6/shared/cancel"
"github.com/lxc/incus/v6/shared/ioprogress"
"github.com/lxc/incus/v6/shared/units"
)
// ErrNotFound is used to explicitly signal error cases, where a resource
// can not be found (404 HTTP status code).
var ErrNotFound = errors.New("resource not found")
func DownloadFileHash(ctx context.Context, httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.HTTPRequestCanceller, filename string, url string, hash string, hashFunc hash.Hash, target io.WriteSeeker) (int64, error) {
// Always seek to the beginning
_, _ = target.Seek(0, io.SeekStart)
var req *http.Request
var err error
// Prepare the download request
if ctx != nil {
req, err = http.NewRequestWithContext(ctx, "GET", url, nil)
} else {
req, err = http.NewRequest("GET", url, nil)
}
if err != nil {
return -1, err
}
if useragent != "" {
req.Header.Set("User-Agent", useragent)
}
// Perform the request
r, doneCh, err := cancel.CancelableDownload(canceler, httpClient.Do, req)
if err != nil {
return -1, err
}
defer func() { _ = r.Body.Close() }()
defer close(doneCh)
if r.StatusCode != http.StatusOK {
if r.StatusCode == http.StatusNotFound {
return -1, fmt.Errorf("Unable to fetch %s: %w", url, ErrNotFound)
}
return -1, fmt.Errorf("Unable to fetch %s: %s", url, r.Status)
}
// Handle the data
body := r.Body
if progress != nil {
body = &ioprogress.ProgressReader{
ReadCloser: r.Body,
Tracker: &ioprogress.ProgressTracker{
Length: r.ContentLength,
Handler: func(percent int64, speed int64) {
if filename != "" {
progress(ioprogress.ProgressData{Text: fmt.Sprintf("%s: %d%% (%s/s)", filename, percent, units.GetByteSizeString(speed, 2))})
} else {
progress(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, units.GetByteSizeString(speed, 2))})
}
},
},
}
}
var size int64
if hashFunc != nil {
size, err = io.Copy(io.MultiWriter(target, hashFunc), body)
if err != nil {
return -1, err
}
result := fmt.Sprintf("%x", hashFunc.Sum(nil))
if result != hash {
return -1, fmt.Errorf("Hash mismatch for %s: %s != %s", url, result, hash)
}
} else {
size, err = io.Copy(target, body)
if err != nil {
return -1, err
}
}
return size, nil
}
|