Files
w3cjandClaude Opus 5.5 a8f0517579 feat(lima): devvm downloads Ubuntu's cloud image itself
Lima's download of the cloud image neither retries nor times out: one cut
in its 900 MB fails base's build, and a stall hangs it. devvm now
downloads the pinned image itself through fetch.Resumable
(ubuntu.Download), into images/ubuntu/<sha256>.img (Dirs.UbuntuImage),
resuming across cuts, stalls and runs, and gives Lima that file. Lima
2.3 checks a local file against the digest before it copies it.

- Before downloading, it takes the image from Lima's own download cache
  when that holds it with the pin's SHA-256: copied into a new file of
  devvm's own, mode 600, hashed as it's written, capped, stopped by the
  context, and kept only once it checks out. Lima's cache is never
  changed, and a base whose dated release Ubuntu may have removed still
  builds again.
- One devvm downloads at a time (images/locks/ubuntu-image), another
  waiting under ubuntu_image_waiting and looking again under the lock
  (TestUbuntuImageAfterWait, which fails without that second look).
- The download goes through the company proxy and trusts the user's CAs
  (Lima.Roots, from trust.Pool, which internal/cli passes through the
  registry), as do the Finder's lookups (TestNewTrustsRoots, and the
  registry's TestOverrides). An untrusted certificate is
  ubuntu_untrusted, naming the CAs' folder, one from a trusted CA
  that's for another host, out of date or not valid yet
  ubuntu_bad_certificate (check the clock and what answers for the
  host), and any other that fails to verify (a SHA-1 signature, a CA's
  name constraints, a key for clients alone) ubuntu_certificate_invalid,
  naming Go's reason, for the lookups (the listing, the checksums, their
  signature: TestLookupCertificates) and the download alike
  (TestLocalImageFailsFor), and a release Ubuntu removed (404, 410)
  ubuntu_release_gone, which names devvm rebuild base; none is retried.
  ubuntu_download_failed no longer starts with devvm.
- fetch.Untrusted, fetch.BadCertificate (an x509.HostnameError, or a
  CertificateInvalidError that's Expired) and fetch.Unverified (any
  failure to verify, with its reason, so every error the other two
  name), beside fetch.Gone, are the one
  place that tells a certificate's failures apart: Transient asks
  Unverified, the lookups and the download ask all three, host mise
  asks Untrusted, and a forbidigo rule keeps x509's and tls's
  verification errors in internal/fetch (TestCertificateClasses,
  TestTransient, testdata/lint, the owners doc's row).
- An https address, or a test build's file:// DEVVM_UBUNTU_URL, read
  from disk the same way; anything else is refused. The CLI tests'
  sandbox has a stand-in of this host's image in the store.
- Base's record keeps the image's address, and the key is as it was: it
  hashes the pin (release, file, digest), not the location.
- devvm gc --caches frees devvm's copies that no record names and that
  aren't pinned now, unchanged for an hour, a stopped .part and a killed
  import's .import included, and those of a kept image once its .img is
  there. A pin it can't read fails it.
- Of Lima's cache, it frees only an entry that devvm's own state shows a
  build of devvm's left: a base record names its address, devvm has its
  own copy of the image, and the installed Lima's own templates
  (share/lima/templates beside limactl, Lima.Templates) don't name it.
  An entry no record names may be the user's own Lima's, so it stays,
  and none is freed when the templates can't be read, with a line in
  the run log naming the folder and why. A test build's
  DEVVM_LIMA_TEMPLATES stands in for the templates folder.
- ubuntu.ParseImage reads a record's image as Image.String writes it,
  and ubuntu.IsSHA256 is the one check of a cloud image's SHA-256, in
  place of Lima's own regex.
- devvm space shows the copies as a cloud images row, freed by gc
  --caches, kept as state, as a release Ubuntu removed can't be
  downloaded again.

0.1.0's frozen state runs the new commands (fixture_v010_cloud_image):
devvm looks in Lima's cache under the SHA-256 of the address 0.1.0's
base record keeps and never changes the entry, base builds from devvm's
own copy, and gc --caches keeps that copy, frees Lima's entry the
record names and devvm's own stale copies, and keeps an older entry no
record names.

Docs: images.md (the download, its failures, the import, gc's rules),
space.md, backends/lima.md, settings.md (the lookups and the download
trust your CAs), troubleshooting.md, overview.md, testing.md,
tests.md, structure.md's internal/fetch row; the CHANGELOG's two Fixed
lines, which later commits make highlights, What to do 5 and 6, and the
release page's Ubuntu's cloud image in devvm's folder.

New messages: downloading_ubuntu, importing_ubuntu, ubuntu_image_waiting,
ubuntu_download_failed, ubuntu_release_gone, ubuntu_bad_certificate,
ubuntu_certificate_invalid, ubuntu_image_checksum, ubuntu_untrusted.
Lima.LocalImage is the seam, Lima.ImageClient the client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 22:53:34 -07:00

350 lines
11 KiB
Go

// 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
}