// Package fetch is how devvm reaches the web: an HTTP client with a // timeout and a redirect policy, retries of the failures that may pass, // reads capped at a size, and downloads checked against their SHA-256. // It is the standard library only. package fetch import ( "context" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/hex" "errors" "fmt" "io" "net/http" "os" "strings" "time" ) // Client is the HTTP client devvm uses: other packages name this type, not // net/http's. Only NewClient makes one that works, so every request has its // timeout and its redirect policy; any other, such as &Client{}, fails // every request with ErrNoClient. type Client struct { hc *http.Client t *http.Transport } // Redirects is the redirects a client follows. type Redirects int const ( // HTTPSOnly follows redirects to https addresses only. HTTPSOnly Redirects = iota // SameScheme follows redirects on the first request's scheme only, so // a server can't send a client that reads file:// addresses to a file. SameScheme ) // maxRedirects is how many redirects a client follows, as net/http's own // client does. const maxRedirects = 10 var ( // ErrRedirect is a redirect refused: trying again won't help. ErrRedirect = errors.New("redirect refused") // ErrTooLarge is a body over its cap. ErrTooLarge = errors.New("too large") // ErrChecksum is a download whose SHA-256 isn't the one asked for. ErrChecksum = errors.New("the SHA-256 doesn't match") // ErrNoClient is a request on a Client that NewClient didn't make. ErrNoClient = errors.New("not a client NewClient made") // ErrProxy is a proxy its caller set (Transport's Proxy) that can't // be gone through, such as a company proxy whose password isn't // saved: trying again won't help. ErrProxy = errors.New("no proxy to go through") // errRequest is a request that can't be made, such as one for an // address that isn't one. errRequest = errors.New("no request") ) // NewClient returns a client whose every request, its body included, takes // at most timeout, following redirects as r says, on its own copy of // net/http's default transport (environment proxies included), which a // caller can change: config.toml's company proxy is its caller's to set // (settings.CompanyProxy.Route), as fetch reads no settings. func NewClient(timeout time.Duration, r Redirects) *Client { t := &http.Transport{} if d, ok := http.DefaultTransport.(*http.Transport); ok { t = d.Clone() } check := httpsOnly if r == SameScheme { check = sameScheme } return &Client{hc: &http.Client{Transport: t, Timeout: timeout, CheckRedirect: check}, t: t} } // Do sends req as net/http's Client.Do does, with the client's timeout and // redirect policy. func (c *Client) Do(req *http.Request) (*http.Response, error) { if c == nil || c.hc == nil { return nil, ErrNoClient } return c.hc.Do(req) } // Transport is the client's own transport, which a caller may change // before its first request: a dialer, a proxy, another scheme. It is nil // for a Client NewClient didn't make. func (c *Client) Transport() *http.Transport { if c == nil { return nil } return c.t } // Trust makes the client's TLS connections trust roots instead of the // system's roots, before its first request: nil keeps the system's. func (c *Client) Trust(roots *x509.CertPool) { if c == nil || c.t == nil || roots == nil { return } if c.t.TLSClientConfig == nil { c.t.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12} } c.t.TLSClientConfig.RootCAs = roots } func httpsOnly(req *http.Request, via []*http.Request) error { if len(via) >= maxRedirects { return fmt.Errorf("%w: too many", ErrRedirect) } if req.URL.Scheme != "https" { return fmt.Errorf("%w: to %s", ErrRedirect, req.URL.Scheme) } return nil } func sameScheme(req *http.Request, via []*http.Request) error { if len(via) >= maxRedirects { return fmt.Errorf("%w: too many", ErrRedirect) } if req.URL.Scheme != via[0].URL.Scheme { return fmt.Errorf("%w: from %s to %s", ErrRedirect, via[0].URL.Scheme, req.URL.Scheme) } return nil } // StatusError is an answer other than 200 OK. type StatusError struct { URL string Code int Status string // the status line's text, such as "404 Not Found" } func (e *StatusError) Error() string { return e.URL + ": " + e.Status } // TransientStatus reports whether an answer with this status code may be // different when asked again: 408, 429 or a server error. func TransientStatus(code int) bool { return code == http.StatusRequestTimeout || code == http.StatusTooManyRequests || code >= 500 } // Transient reports whether a request that failed with err may succeed // when tried again: one that got no answer or lost it partway, or got a // status TransientStatus names. A refused redirect, a request that can't // be made, a client NewClient didn't make, a proxy that can't be gone // through, a body over its cap, a SHA-256 that doesn't match, a download // that can't be written and a server's certificate that can't be // verified are not. func Transient(err error) bool { if _, unverified := Unverified(err); unverified { return false } var se *StatusError switch { case err == nil: return false case errors.As(err, &se): return TransientStatus(se.Code) case errors.Is(err, ErrRedirect), errors.Is(err, errRequest), errors.Is(err, ErrNoClient), errors.Is(err, ErrProxy), errors.Is(err, ErrTooLarge), errors.Is(err, ErrChecksum), errors.Is(err, ErrWrite): return false } return true } // The classes of failure callers say apart, each one that trying again // can't mend: the only place devvm reads a certificate's error, so every // download names the same cause for it. // Gone reports whether a server says a download's file is gone for good // (404, 410): a Resumable download's part is no use to a later run, and // trying again gets the same answer. func Gone(err error) bool { var se *StatusError return errors.As(err, &se) && (se.Code == http.StatusNotFound || se.Code == http.StatusGone) } // Untrusted reports whether err is a server's certificate that no CA this // machine trusts signed, as on a network that inspects TLS whose CA it // lacks: adding that CA mends it. func Untrusted(err error) bool { return errors.As(err, new(x509.UnknownAuthorityError)) } // BadCertificate reports whether err is a server's certificate that a CA // this machine trusts signed but that's for another host, out of date or // not valid yet: no CA mends it, as a wrong clock or another server // answering for the host is the cause. Any other failure to verify a // certificate, such as a weak signature or a CA's name constraints, is // neither this nor Untrusted, and Unverified names it. func BadCertificate(err error) bool { var invalid x509.CertificateInvalidError return errors.As(err, new(x509.HostnameError)) || errors.As(err, &invalid) && invalid.Reason == x509.Expired } // Unverified reports whether err is any failure to verify a server's // certificate, which trying again never mends, and returns why it failed, // in Go's words: for a failure neither Untrusted nor BadCertificate is, // the reason is the only cause to name. It holds every error those two // do, wrapped in TLS's error or bare. func Unverified(err error) (reason string, ok bool) { if err == nil { return "", false } if v, ok := errors.AsType[*tls.CertificateVerificationError](err); ok && v.Err != nil { return v.Err.Error(), true } if Untrusted(err) || BadCertificate(err) || errors.As(err, new(*tls.CertificateVerificationError)) { return err.Error(), true } return "", false } // Retry runs try until it succeeds, it fails and says not to try again, // the context ends, or it has been tried again retries times. It waits // delay before the first retry and twice as long before each one after. // It returns try's last error, or the context's once it has ended. func Retry(ctx context.Context, retries int, delay time.Duration, try func() (again bool, err error)) error { for n := 0; ; n++ { if err := ctx.Err(); err != nil { // file:// reads don't watch the context return err } again, err := try() if err == nil { return nil } if ctx.Err() != nil { return ctx.Err() } if !again || n == retries { return err } select { case <-ctx.Done(): return ctx.Err() case <-time.After(delay): } delay *= 2 } } // ReadCapped reads r to its end, failing with ErrTooLarge when it holds // more than limit bytes. func ReadCapped(r io.Reader, limit int64) ([]byte, error) { data, err := io.ReadAll(io.LimitReader(r, limit+1)) if err != nil { return nil, err } if int64(len(data)) > limit { return nil, fmt.Errorf("%w: more than %d bytes", ErrTooLarge, limit) } return data, nil } // Open GETs url and returns the body of a 200 OK answer, which the caller // closes; any other answer is a *StatusError. func Open(ctx context.Context, c *Client, url string) (io.ReadCloser, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) if err != nil { return nil, fmt.Errorf("%w: %w", errRequest, err) } resp, err := c.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { _ = resp.Body.Close() return nil, &StatusError{URL: url, Code: resp.StatusCode, Status: resp.Status} } return resp.Body, nil } // Resolve returns the address a HEAD of url ends at once the client has // followed its redirects, as GitHub's releases/latest goes to its newest // release's page, when the answer there is 200 OK; any other answer is a // *StatusError. func Resolve(ctx context.Context, c *Client, url string) (string, error) { req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, http.NoBody) if err != nil { return "", fmt.Errorf("%w: %w", errRequest, err) } resp, err := c.Do(req) if err != nil { return "", err } _ = resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", &StatusError{URL: url, Code: resp.StatusCode, Status: resp.Status} } return resp.Request.URL.String(), nil } // Get returns the body of a 200 OK answer to a GET of url, failing with // ErrTooLarge when it's more than limit bytes. func Get(ctx context.Context, c *Client, url string, limit int64) ([]byte, error) { body, err := Open(ctx, c, url) if err != nil { return nil, err } defer func() { _ = body.Close() }() data, err := ReadCapped(body, limit) if err != nil { return nil, fmt.Errorf("%s: %w", url, err) } return data, nil } // Download writes the body of a GET of url to path, mode 600, and keeps // it only when its SHA-256 is sum (hex): one that isn't fails with // ErrChecksum, before anything can use it, and one over limit bytes with // ErrTooLarge, before it fills the disk. On any failure nothing is left // at path. func Download(ctx context.Context, c *Client, url, path, sum string, limit int64) (err error) { body, err := Open(ctx, c, url) if err != nil { return err } defer func() { _ = body.Close() }() f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:forbidigo,gosec // the caller's own path, a download streamed into it, removed on any failure if err != nil { return err } defer func() { if err != nil { _ = os.Remove(path) } }() h := sha256.New() n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, limit+1)) if cerr := f.Close(); err == nil { err = cerr } if err != nil { return err } if n > limit { return fmt.Errorf("%s: %w: more than %d bytes", url, ErrTooLarge, limit) } if got := hex.EncodeToString(h.Sum(nil)); sum == "" || !strings.EqualFold(got, sum) { return fmt.Errorf("%s: %w: %s", url, ErrChecksum, got) } return nil }