Files
NanoKVM-MIRROR/server/utils/http.go
2026-08-05 11:50:39 +08:00

116 lines
2.9 KiB
Go

package utils
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
const maxDownloadSize = int64(1024 * 1024 * 1024)
var downloadClient = NewUpdateHTTPClient(15 * time.Minute)
func NewAuthenticatedRequest(method string, rawURL string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, rawURL, body)
if err != nil {
return nil, err
}
if req.URL.User != nil {
username := req.URL.User.Username()
password, _ := req.URL.User.Password()
req.SetBasicAuth(username, password)
// Keep credentials out of the request URL after copying them to the header.
req.URL.User = nil
}
return req, nil
}
func NewUpdateHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
CheckRedirect: preserveBasicAuthRedirect,
}
}
func preserveBasicAuthRedirect(req *http.Request, via []*http.Request) error {
if len(via) == 0 {
return nil
}
previous := via[len(via)-1]
authorization := previous.Header.Get("Authorization")
if authorization == "" {
return nil
}
if !sameUpdateHost(previous.URL, req.URL) ||
(previous.URL.Scheme == "https" && req.URL.Scheme != "https") {
return http.ErrUseLastResponse
}
req.Header.Set("Authorization", authorization)
return nil
}
func sameUpdateHost(left *url.URL, right *url.URL) bool {
return strings.EqualFold(left.Host, right.Host)
}
func Download(req *http.Request, target string) error {
log.Debugf("downloading %s to %s", req.URL.Redacted(), target)
err := os.MkdirAll(filepath.Dir(target), 0o755)
if err != nil {
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
return err
}
out, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
log.Errorf("cannot create file '%s', error: %s", target, err)
return err
}
defer func() {
_ = out.Close()
}()
resp, err := downloadClient.Do(req)
if err != nil {
log.Errorf("request to %s failed", req.URL.Redacted())
return errors.New("update website is inaccessible right now")
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
log.Errorf("request failed, status code: %d", resp.StatusCode)
return errors.New("update website is inaccessible right now")
}
contentType := resp.Header.Get("Content-Type")
if contentType != "application/octet-stream" && contentType != "application/zip" && contentType != "application/gzip" {
log.Debugf("unexpected content-type, it should be either octet-stream or (g)zip, but got: %s", contentType)
return errors.New("unsupported content type")
}
written, err := io.Copy(out, io.LimitReader(resp.Body, maxDownloadSize+1))
if err != nil {
log.Errorf("download file to %s err: %s", target, err)
return err
}
if written > maxDownloadSize {
return fmt.Errorf("download exceeds %d bytes", maxDownloadSize)
}
return nil
}