跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

downloader.go

1088 行 · 31.6 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package downloader
5
6import (
7 "bytes"
8 "compress/gzip"
9 "context"
10 "crypto/sha256"
11 "errors"
12 "fmt"
13 "io"
14 "net/http"
15 "os"
16 "os/exec"
17 "path"
18 "path/filepath"
19 "slices"
20 "strings"
21 "sync/atomic"
22 "time"
23
24 "github.com/cheggaaa/pb/v3"
25 "github.com/containerd/continuity/fs"
26 "github.com/lima-vm/go-qcow2reader/image/raw"
27 "github.com/opencontainers/go-digest"
28 "github.com/sirupsen/logrus"
29
30 "github.com/lima-vm/lima/v2/pkg/httpclientutil"
31 "github.com/lima-vm/lima/v2/pkg/imgutil/nativeimgutil"
32 "github.com/lima-vm/lima/v2/pkg/imgutil/proxyimgutil"
33 "github.com/lima-vm/lima/v2/pkg/iso9660util"
34 "github.com/lima-vm/lima/v2/pkg/localpathutil"
35 "github.com/lima-vm/lima/v2/pkg/lockutil"
36 "github.com/lima-vm/lima/v2/pkg/progressbar"
37)
38
39// HideProgress is used only for testing.
40var HideProgress bool
41
42// hideBar is used only for testing.
43func hideBar(bar *progressbar.ProgressBar) {
44 bar.Set(pb.Static, true)
45}
46
47type Status = string
48
49const (
50 StatusUnknown Status = ""
51 StatusDownloaded Status = "downloaded"
52 StatusSkipped Status = "skipped"
53 StatusUsedCache Status = "used-cache"
54)
55
56type Result struct {
57 Status Status
58 CachePath string // "/Users/foo/Library/Caches/lima/download/by-url-sha256/<SHA256_OF_URL>/data"
59 LastModified time.Time
60 ContentType string
61 ValidatedDigest bool
62}
63
64type options struct {
65 cacheDir string // default: empty (disables caching)
66 decompress bool // default: false (keep compression)
67 description string // default: url
68 expectedDigest digest.Digest
69 supportedImageFormats []string
70}
71
72func (o *options) apply(opts []Opt) error {
73 for _, f := range opts {
74 if err := f(o); err != nil {
75 return err
76 }
77 }
78 return nil
79}
80
81type Opt func(*options) error
82
83// WithCache uses Cage's environment volume when configured, or the user's Lima cache.
84func WithCache() Opt {
85 return func(o *options) error {
86 if dir := os.Getenv("CAGE_LIMA_CACHE_DIR"); dir != "" {
87 if !filepath.IsAbs(dir) {
88 return fmt.Errorf("CAGE_LIMA_CACHE_DIR must be absolute")
89 }
90 return WithCacheDir(dir)(o)
91 }
92 ucd, err := os.UserCacheDir()
93 if err != nil {
94 return err
95 }
96 cacheDir := filepath.Join(ucd, "lima")
97 return WithCacheDir(cacheDir)(o)
98 }
99}
100
101// WithCacheDir enables caching using the specified dir.
102// Empty value disables caching.
103func WithCacheDir(cacheDir string) Opt {
104 return func(o *options) error {
105 o.cacheDir = cacheDir
106 return nil
107 }
108}
109
110// WithDescription adds a user description of the download.
111func WithDescription(description string) Opt {
112 return func(o *options) error {
113 o.description = description
114 return nil
115 }
116}
117
118// WithDecompress decompress the download from the cache.
119func WithDecompress(decompress bool) Opt {
120 return func(o *options) error {
121 o.decompress = decompress
122 return nil
123 }
124}
125
126func WithImageFormats(supportedImageFormats []string) Opt {
127 return func(o *options) error {
128 o.supportedImageFormats = supportedImageFormats
129 return nil
130 }
131}
132
133// WithExpectedDigest is used to validate the downloaded file against the expected digest.
134//
135// The digest is not verified in the following cases:
136// - The digest was not specified.
137// - The file already exists in the local target path.
138//
139// When the `data` file exists in the cache dir with `<ALGO>.digest` file,
140// the digest is verified by comparing the content of `<ALGO>.digest` with the expected
141// digest string. So, the actual digest of the `data` file is not computed.
142func WithExpectedDigest(expectedDigest digest.Digest) Opt {
143 return func(o *options) error {
144 if expectedDigest != "" {
145 if err := expectedDigest.Validate(); err != nil {
146 return err
147 }
148 }
149
150 o.expectedDigest = expectedDigest
151 return nil
152 }
153}
154
155func readFile(path string) string {
156 if path == "" {
157 return ""
158 }
159 if _, err := os.Stat(path); err != nil {
160 return ""
161 }
162 b, err := os.ReadFile(path)
163 if err != nil {
164 return ""
165 }
166 return string(b)
167}
168
169func readTime(path string) time.Time {
170 if path == "" {
171 return time.Time{}
172 }
173 if _, err := os.Stat(path); err != nil {
174 return time.Time{}
175 }
176 b, err := os.ReadFile(path)
177 if err != nil {
178 return time.Time{}
179 }
180 t, err := time.Parse(http.TimeFormat, string(b))
181 if err != nil {
182 return time.Time{}
183 }
184 return t
185}
186
187// Download downloads the remote resource into the local path.
188//
189// Download caches the remote resource if WithCache or WithCacheDir option is specified.
190// Local files are not cached.
191//
192// When the local path already exists, Download returns Result with StatusSkipped.
193// (So, the local path cannot be set to /dev/null for "caching only" mode.)
194//
195// The local path can be an empty string for "caching only" mode.
196func Download(ctx context.Context, local, remote string, opts ...Opt) (*Result, error) {
197 var o options
198 if err := o.apply(opts); err != nil {
199 return nil, err
200 }
201
202 var localPath string
203 if local == "" {
204 if o.cacheDir == "" {
205 return nil, errors.New("caching-only mode requires the cache directory to be specified")
206 }
207 } else {
208 var err error
209 localPath, err = canonicalLocalPath(local)
210 if err != nil {
211 return nil, err
212 }
213 if _, err := os.Stat(localPath); err == nil {
214 logrus.Debugf("file %#q already exists, skipping downloading from %#q (and skipping digest validation)", localPath, remote)
215 res := &Result{
216 Status: StatusSkipped,
217 ValidatedDigest: false,
218 }
219 return res, nil
220 } else if !errors.Is(err, os.ErrNotExist) {
221 return nil, err
222 }
223
224 localPathDir := filepath.Dir(localPath)
225 if err := os.MkdirAll(localPathDir, 0o755); err != nil {
226 return nil, err
227 }
228 }
229
230 ext := path.Ext(remote)
231 if IsLocal(remote) {
232 if err := copyLocal(ctx, localPath, remote, ext, o.decompress, o.description, o.expectedDigest); err != nil {
233 return nil, err
234 }
235 res := &Result{
236 Status: StatusDownloaded,
237 ValidatedDigest: o.expectedDigest != "",
238 }
239 return res, nil
240 }
241
242 if o.cacheDir == "" {
243 if err := downloadHTTP(ctx, localPath, "", "", remote, o.description, o.expectedDigest); err != nil {
244 return nil, err
245 }
246 res := &Result{
247 Status: StatusDownloaded,
248 ValidatedDigest: o.expectedDigest != "",
249 }
250 return res, nil
251 }
252
253 shad := cacheDirectoryPath(o.cacheDir, remote)
254 if err := os.MkdirAll(shad, 0o700); err != nil {
255 return nil, err
256 }
257
258 var res *Result
259 err := lockutil.WithDirLock(shad, func() error {
260 var err error
261 res, err = getCached(ctx, localPath, remote, o)
262 if err != nil {
263 return err
264 }
265 if res != nil {
266 return nil
267 }
268 res, err = fetch(ctx, localPath, remote, o)
269 return err
270 })
271 return res, err
272}
273
274// getCached tries to copy the file from the cache to local path. Return result,
275// nil if the file was copied, nil, nil if the file is not in the cache or the
276// cache needs update, or nil, error on fatal error.
277func getCached(ctx context.Context, localPath, remote string, o options) (*Result, error) {
278 shad := cacheDirectoryPath(o.cacheDir, remote)
279 shadData := filepath.Join(shad, "data")
280 shadTime := filepath.Join(shad, "time")
281 shadType := filepath.Join(shad, "type")
282 shadDigest, err := cacheDigestPath(shad, o.expectedDigest)
283 if err != nil {
284 return nil, err
285 }
286 if _, err := os.Stat(shadData); err != nil {
287 return nil, nil
288 }
289 if _, err := os.Stat(shadDigest); err == nil {
290 if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil {
291 return nil, err
292 }
293 } else if match, lmCached, lmRemote, err := matchLastModified(ctx, shadTime, remote); err != nil {
294 logrus.WithError(err).Info("Failed to retrieve last-modified for cached digest-less image; using cached image.")
295 } else if !match {
296 logrus.Infof("Re-downloading digest-less image: last-modified mismatch (cached: %#q, remote: %#q)", lmCached, lmRemote)
297 return nil, nil
298 }
299
300 // Some drivers (e.g. vz) can only boot raw images. When the driver tells us
301 // which formats it supports and the cached image is not one of them, we save
302 // a converted raw copy next to the original at <shad>/imgconv/raw. See
303 // website/content/en/docs/dev/internals.md for the layout.
304 if len(o.supportedImageFormats) > 0 {
305 isISO, err := iso9660util.IsISO9660(shadData)
306 if err != nil {
307 logrus.WithError(err).Debugf("Skipping cache image conversion for %q (unable to check ISO9660)", shadData)
308 } else if !isISO {
309 imageFormat, err := nativeimgutil.DetectFormat(shadData)
310 if err != nil {
311 logrus.WithError(err).Debugf("Skipping cache image conversion for %q (unable to detect format)", shadData)
312 } else if !slices.Contains(o.supportedImageFormats, imageFormat) {
313 rawImgConvPath := filepath.Join(shad, "imgconv", "raw")
314 rawImgConvDigestPath := filepath.Join(shad, "imgconv", "raw.digest")
315
316 // The raw copy has a digest of its own, so o.expectedDigest is replaced
317 // below and the check at the end of this function then compares
318 // imgconv/raw.digest against a value read from that same file. When the
319 // cache entry carries no recorded digest there is nothing that has
320 // compared the caller's digest against any bytes yet, so do it here.
321 if o.expectedDigest != "" {
322 if _, err := os.Stat(shadDigest); err != nil {
323 if err := validateLocalFileDigest(shadData, o.expectedDigest); err != nil {
324 return nil, err
325 }
326 }
327 }
328
329 needConvert := false
330 if rawStat, err := os.Stat(rawImgConvPath); err != nil {
331 if errors.Is(err, os.ErrNotExist) {
332 needConvert = true
333 } else {
334 return nil, err
335 }
336 } else {
337 origStat, err := os.Stat(shadData)
338 if err != nil {
339 return nil, err
340 }
341 if origStat.ModTime().After(rawStat.ModTime()) {
342 needConvert = true
343 }
344 }
345
346 if needConvert {
347 logrus.Infof("Converted raw image is missing or stale; (re)converting now.")
348 converted, rawDigest, err := ensureRawInCache(ctx, shadData, imageFormat, o.expectedDigest)
349 if err != nil {
350 return nil, err
351 }
352 shadData = converted
353 if o.expectedDigest != "" {
354 o.expectedDigest = rawDigest
355 shadDigest = rawImgConvDigestPath
356 }
357 } else {
358 shadData = rawImgConvPath
359 if o.expectedDigest != "" {
360 if currentDigestData, err := os.ReadFile(rawImgConvDigestPath); err == nil {
361 currentDigest := strings.TrimSpace(string(currentDigestData))
362 if d, err := digest.Parse(currentDigest); err == nil {
363 o.expectedDigest = d
364 shadDigest = rawImgConvDigestPath
365 } else {
366 return nil, fmt.Errorf("invalid digest in raw digest file %q: %w", rawImgConvDigestPath, err)
367 }
368 } else {
369 return nil, fmt.Errorf("failed to read raw digest file %q: %w", rawImgConvDigestPath, err)
370 }
371 }
372 }
373 }
374 }
375 }
376
377 ext := path.Ext(remote)
378 logrus.Debugf("file %#q is cached as %#q", localPath, shadData)
379 if _, err := os.Stat(shadDigest); err == nil {
380 logrus.Debugf("Comparing digest %#q with the cached digest file %#q, not computing the actual digest of %#q",
381 o.expectedDigest, shadDigest, shadData)
382 if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil {
383 return nil, err
384 }
385 if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, "", ""); err != nil {
386 return nil, err
387 }
388 } else {
389 if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, o.description, o.expectedDigest); err != nil {
390 return nil, err
391 }
392 }
393 res := &Result{
394 Status: StatusUsedCache,
395 CachePath: shadData,
396 LastModified: readTime(shadTime),
397 ContentType: readFile(shadType),
398 ValidatedDigest: o.expectedDigest != "",
399 }
400 return res, nil
401}
402
403// fetch downloads remote to the cache and copy the cached file to local path.
404func fetch(ctx context.Context, localPath, remote string, o options) (*Result, error) {
405 shad := cacheDirectoryPath(o.cacheDir, remote)
406 shadData := filepath.Join(shad, "data")
407 shadTime := filepath.Join(shad, "time")
408 shadType := filepath.Join(shad, "type")
409 shadDigest, err := cacheDigestPath(shad, o.expectedDigest)
410 if err != nil {
411 return nil, err
412 }
413 ext := path.Ext(remote)
414 shadURL := filepath.Join(shad, "url")
415 if err := os.WriteFile(shadURL, []byte(remote), 0o644); err != nil {
416 return nil, err
417 }
418 // A cache entry is locked by Download. Only digest-pinned downloads may
419 // retain and resume partial bytes across processes and setup retries.
420 download := downloadHTTP
421 if o.expectedDigest != "" {
422 download = downloadHTTPResumable
423 }
424 if err := download(ctx, shadData, shadTime, shadType, remote, o.description, o.expectedDigest); err != nil {
425 return nil, err
426 }
427 if shadDigest != "" && o.expectedDigest != "" {
428 if err := os.WriteFile(shadDigest, []byte(o.expectedDigest.String()), 0o644); err != nil {
429 return nil, err
430 }
431 }
432
433 // If the driver cannot use the format we just downloaded, save a converted
434 // raw copy at <shad>/imgconv/raw, keeping the original <shad>/data as-is.
435 //
436 // Gated on WithImageFormats() (the caller's signal that this is a VM disk
437 // image) and on the file not being an ISO 9660 image.
438 if len(o.supportedImageFormats) > 0 {
439 isISO, err := iso9660util.IsISO9660(shadData)
440 if err != nil {
441 logrus.WithError(err).Debugf("Skipping cache image conversion for %q (unable to check ISO9660)", shadData)
442 } else if !isISO {
443 format, err := nativeimgutil.DetectFormat(shadData)
444 if err != nil {
445 logrus.WithError(err).Debugf("Skipping cache image conversion for %q (unable to detect format)", shadData)
446 } else if !slices.Contains(o.supportedImageFormats, format) {
447 converted, rawDigest, err := ensureRawInCache(ctx, shadData, format, o.expectedDigest)
448 if err != nil {
449 return nil, fmt.Errorf("failed to convert image to raw: %w", err)
450 } else if converted != "" {
451 shadData = converted
452 if o.expectedDigest != "" {
453 o.expectedDigest = rawDigest
454 }
455 }
456 }
457 }
458 }
459
460 // no need to pass the digest to copyLocal(), as we already verified the digest
461 if err := copyLocal(ctx, localPath, shadData, ext, o.decompress, "", ""); err != nil {
462 return nil, err
463 }
464 res := &Result{
465 Status: StatusDownloaded,
466 CachePath: shadData,
467 LastModified: readTime(shadTime),
468 ContentType: readFile(shadType),
469 ValidatedDigest: o.expectedDigest != "",
470 }
471 return res, nil
472}
473
474// ensureRawInCache converts any image to raw and places it in the cache(imgconv/raw). It also creates a
475// digest file for the raw image(imgconv/raw.digest). Returns the converted image path, the raw digest, and any error.
476func ensureRawInCache(ctx context.Context, imagePath, format string, originalDigest digest.Digest) (string, digest.Digest, error) {
477 imgConvPath := filepath.Join(filepath.Dir(imagePath), "imgconv")
478 if err := os.MkdirAll(imgConvPath, 0o700); err != nil {
479 return "", "", err
480 }
481 rawImgConvPath := filepath.Join(imgConvPath, "raw")
482
483 logrus.Infof("Converting %s image to raw sparse format in cache: %q", format, rawImgConvPath)
484 rawPathTmp := filepath.Join(imgConvPath, "raw.tmp")
485 defer os.Remove(rawPathTmp)
486 diskUtil := proxyimgutil.NewDiskUtil(ctx)
487 if err := diskUtil.Convert(ctx, raw.Type, imagePath, rawPathTmp, nil, false); err != nil {
488 return "", "", fmt.Errorf("failed to convert %q to raw: %w", imagePath, err)
489 }
490
491 // Ensure the image is sparse to save cache space.
492 rawTmpF, err := os.OpenFile(rawPathTmp, os.O_RDWR, 0o644)
493 if err != nil {
494 return "", "", fmt.Errorf("failed to open raw tmp file %q: %w", rawPathTmp, err)
495 }
496 fi, err := rawTmpF.Stat()
497 if err != nil {
498 _ = rawTmpF.Close()
499 return "", "", fmt.Errorf("failed to stat raw tmp file %q: %w", rawPathTmp, err)
500 }
501 if err := diskUtil.MakeSparse(ctx, rawTmpF, fi.Size()); err != nil {
502 logrus.WithError(err).Warnf("Failed to make %q sparse (non-fatal)", rawPathTmp)
503 }
504 if err := rawTmpF.Close(); err != nil {
505 return "", "", fmt.Errorf("failed to close raw tmp file %q: %w", rawPathTmp, err)
506 }
507
508 if err := os.Remove(rawImgConvPath); err != nil && !errors.Is(err, os.ErrNotExist) {
509 return "", "", fmt.Errorf("failed to remove stale raw image %q: %w", rawImgConvPath, err)
510 }
511 if err := os.Rename(rawPathTmp, rawImgConvPath); err != nil {
512 return "", "", fmt.Errorf("failed to replace original with raw image: %w", err)
513 }
514
515 algo := digest.Canonical
516 if originalDigest != "" {
517 algo = originalDigest.Algorithm()
518 }
519 rawDigest, err := calculateFileDigest(rawImgConvPath, algo)
520 if err != nil {
521 return "", "", fmt.Errorf("failed to calculate digest of raw image: %w", err)
522 }
523
524 rawDigestPath := filepath.Join(imgConvPath, "raw.digest")
525 rawDigestPathTmp := rawDigestPath + ".tmp"
526 defer os.Remove(rawDigestPathTmp)
527 if err := os.WriteFile(rawDigestPathTmp, []byte(rawDigest.String()), 0o644); err != nil {
528 return "", "", fmt.Errorf("failed to write raw digest file: %w", err)
529 }
530 if err := os.Remove(rawDigestPath); err != nil && !errors.Is(err, os.ErrNotExist) {
531 return "", "", fmt.Errorf("failed to remove stale raw digest file %q: %w", rawDigestPath, err)
532 }
533 if err := os.Rename(rawDigestPathTmp, rawDigestPath); err != nil {
534 return "", "", fmt.Errorf("failed to rename raw digest file: %w", err)
535 }
536
537 return rawImgConvPath, rawDigest, nil
538}
539
540func calculateFileDigest(path string, algo digest.Algorithm) (digest.Digest, error) {
541 f, err := os.Open(path)
542 if err != nil {
543 return "", err
544 }
545 defer f.Close()
546
547 return algo.FromReader(f)
548}
549
550// Cached checks if the remote resource is in the cache.
551//
552// Download caches the remote resource if WithCache or WithCacheDir option is specified.
553// Local files are not cached.
554//
555// When the cache path already exists, Cached returns Result with StatusUsedCache.
556func Cached(remote string, opts ...Opt) (*Result, error) {
557 var o options
558 if err := o.apply(opts); err != nil {
559 return nil, err
560 }
561 if o.cacheDir == "" {
562 return nil, errors.New("caching-only mode requires the cache directory to be specified")
563 }
564 if IsLocal(remote) {
565 return nil, errors.New("local files are not cached")
566 }
567
568 shad := cacheDirectoryPath(o.cacheDir, remote)
569 shadData := filepath.Join(shad, "data")
570 shadTime := filepath.Join(shad, "time")
571 shadType := filepath.Join(shad, "type")
572 shadDigest, err := cacheDigestPath(shad, o.expectedDigest)
573 if err != nil {
574 return nil, err
575 }
576
577 // Checking if data file exists is safe without locking.
578 if _, err := os.Stat(shadData); err != nil {
579 return nil, err
580 }
581
582 // But validating the digest or the data file must take the lock to avoid races
583 // with parallel downloads.
584 if err := os.MkdirAll(shad, 0o700); err != nil {
585 return nil, err
586 }
587 err = lockutil.WithDirLock(shad, func() error {
588 if _, err := os.Stat(shadDigest); err != nil {
589 if err := validateCachedDigest(shadDigest, o.expectedDigest); err != nil {
590 return err
591 }
592 } else {
593 if err := validateLocalFileDigest(shadData, o.expectedDigest); err != nil {
594 return err
595 }
596 }
597 return nil
598 })
599 if err != nil {
600 return nil, err
601 }
602
603 res := &Result{
604 Status: StatusUsedCache,
605 CachePath: shadData,
606 LastModified: readTime(shadTime),
607 ContentType: readFile(shadType),
608 ValidatedDigest: o.expectedDigest != "",
609 }
610 return res, nil
611}
612
613// cacheDirectoryPath returns the cache subdirectory path.
614// - "url" file contains the url
615// - "data" file contains the data
616// - "time" file contains the time (Last-Modified header)
617// - "type" file contains the type (Content-Type header)
618func cacheDirectoryPath(cacheDir, remote string) string {
619 return filepath.Join(cacheDir, "download", "by-url-sha256", CacheKey(remote))
620}
621
622// cacheDigestPath returns the cache digest file path.
623// - "<ALGO>.digest" contains the digest
624func cacheDigestPath(shad string, expectedDigest digest.Digest) (string, error) {
625 shadDigest := ""
626 if expectedDigest != "" {
627 algo := expectedDigest.Algorithm().String()
628 if strings.Contains(algo, "/") || strings.Contains(algo, "\\") {
629 return "", fmt.Errorf("invalid digest algorithm %#q", algo)
630 }
631 shadDigest = filepath.Join(shad, algo+".digest")
632 }
633 return shadDigest, nil
634}
635
636func IsLocal(s string) bool {
637 return !strings.Contains(s, "://") || strings.HasPrefix(s, "file://")
638}
639
640// canonicalLocalPath canonicalizes the local path string.
641// - Make sure the file has no scheme, or the `file://` scheme
642// - If it has the `file://` scheme, strip the scheme and make sure the filename is absolute
643// - Expand a leading `~`, or convert relative to absolute name
644func canonicalLocalPath(s string) (string, error) {
645 if s == "" {
646 return "", errors.New("got empty path")
647 }
648 if !IsLocal(s) {
649 return "", fmt.Errorf("got non-local path: %#q", s)
650 }
651 if res, ok := strings.CutPrefix(s, "file://"); ok {
652 if !filepath.IsAbs(res) {
653 return "", fmt.Errorf("got non-absolute path %#q", res)
654 }
655 return res, nil
656 }
657 return localpathutil.Expand(s)
658}
659
660func copyLocal(ctx context.Context, dst, src, ext string, decompress bool, description string, expectedDigest digest.Digest) error {
661 srcPath, err := canonicalLocalPath(src)
662 if err != nil {
663 return err
664 }
665
666 if expectedDigest != "" {
667 logrus.Debugf("verifying digest of local file %#q (%s)", srcPath, expectedDigest)
668 }
669 if err := validateLocalFileDigest(srcPath, expectedDigest); err != nil {
670 return err
671 }
672
673 if dst == "" {
674 // empty dst means caching-only mode
675 return nil
676 }
677 dstPath, err := canonicalLocalPath(dst)
678 if err != nil {
679 return err
680 }
681 if decompress {
682 command := decompressor(ext)
683 if command != "" {
684 return decompressLocal(ctx, command, dstPath, srcPath, ext, description)
685 }
686 commandByMagic := decompressorByMagic(srcPath)
687 if commandByMagic != "" {
688 return decompressLocal(ctx, commandByMagic, dstPath, srcPath, ext, description)
689 }
690 }
691 // TODO: progress bar for copy
692 return fs.CopyFile(dstPath, srcPath)
693}
694
695func decompressor(ext string) string {
696 switch ext {
697 case ".gz":
698 return "gzip"
699 case ".bz2":
700 return "bzip2"
701 case ".xz":
702 return "xz"
703 case ".zst":
704 return "zstd"
705 default:
706 return ""
707 }
708}
709
710func decompressorByMagic(file string) string {
711 f, err := os.Open(file)
712 if err != nil {
713 return ""
714 }
715 defer f.Close()
716 header := make([]byte, 6)
717 if _, err := f.Read(header); err != nil {
718 return ""
719 }
720 if _, err := f.Seek(0, io.SeekStart); err != nil {
721 return ""
722 }
723 if bytes.HasPrefix(header, []byte{0x1f, 0x8b}) {
724 return "gzip"
725 }
726 if bytes.HasPrefix(header, []byte{0x42, 0x5a}) {
727 return "bzip2"
728 }
729 if bytes.HasPrefix(header, []byte{0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00}) {
730 return "xz"
731 }
732 if bytes.HasPrefix(header, []byte{0x28, 0xb5, 0x2f, 0xfd}) {
733 return "zstd"
734 }
735 return ""
736}
737
738func decompressLocal(ctx context.Context, decompressCmd, dst, src, ext, description string) error {
739 st, err := os.Stat(src)
740 if err != nil {
741 return err
742 }
743 bar, err := progressbar.New(st.Size())
744 if err != nil {
745 return err
746 }
747 if HideProgress {
748 hideBar(bar)
749 }
750
751 in, err := os.Open(src)
752 if err != nil {
753 return err
754 }
755 defer in.Close()
756 out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0o644)
757 if err != nil {
758 return err
759 }
760 defer out.Close()
761 if !HideProgress {
762 if description == "" {
763 description = filepath.Base(src)
764 }
765 logrus.Infof("Decompressing %s", description)
766 }
767 bar.Start()
768 defer bar.Finish()
769 reader := bar.NewProxyReader(in)
770
771 // Prefer the external decompressor; fall back to a built-in pure-Go
772 // gzip decoder only when the binary is missing, so a plain Windows
773 // host with no gzip can still unpack a .tar.gz image. xz, bzip2, and
774 // zstd stay external-only.
775 if _, lookErr := exec.LookPath(decompressCmd); lookErr != nil {
776 var r io.Reader
777 switch decompressCmd {
778 case "gzip":
779 gz, err := gzip.NewReader(reader)
780 if err != nil {
781 return err
782 }
783 defer gz.Close()
784 r = gz
785 default:
786 return fmt.Errorf("decompressor %q not found and no built-in fallback: %w", decompressCmd, lookErr)
787 }
788 logrus.Infof("decompressing %s with built-in %s (external %q not found)", ext, decompressCmd, decompressCmd)
789 _, err = io.Copy(out, &ctxReader{ctx: ctx, r: r})
790 return err
791 }
792
793 logrus.Infof("decompressing %s with external %q", ext, decompressCmd)
794 buf := new(bytes.Buffer)
795 cmd := exec.CommandContext(ctx, decompressCmd, "-d")
796 cmd.Stdin = reader
797 cmd.Stdout = out
798 cmd.Stderr = buf
799 err = cmd.Run()
800 if err != nil {
801 if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
802 exitErr.Stderr = buf.Bytes()
803 }
804 }
805 return err
806}
807
808// ctxReader makes an uninterruptible in-process decode cancellable: once ctx
809// is cancelled each Read returns its error, unwinding the io.Copy that drives
810// the decoder.
811type ctxReader struct {
812 ctx context.Context
813 r io.Reader
814}
815
816func (c *ctxReader) Read(p []byte) (int, error) {
817 if err := c.ctx.Err(); err != nil {
818 return 0, err
819 }
820 return c.r.Read(p)
821}
822
823func validateCachedDigest(shadDigest string, expectedDigest digest.Digest) error {
824 if expectedDigest == "" {
825 return nil
826 }
827 shadDigestB, err := os.ReadFile(shadDigest)
828 if err != nil {
829 return err
830 }
831 shadDigestS := strings.TrimSpace(string(shadDigestB))
832 if shadDigestS != expectedDigest.String() {
833 return fmt.Errorf("expected digest %#q, got %#q", expectedDigest, shadDigestS)
834 }
835 return nil
836}
837
838func validateLocalFileDigest(localPath string, expectedDigest digest.Digest) error {
839 if localPath == "" {
840 return errors.New("validateLocalFileDigest: got empty localPath")
841 }
842 if expectedDigest == "" {
843 return nil
844 }
845 algo := expectedDigest.Algorithm()
846 if !algo.Available() {
847 return fmt.Errorf("expected digest algorithm %#q is not available", algo)
848 }
849 r, err := os.Open(localPath)
850 if err != nil {
851 return err
852 }
853 defer r.Close()
854 actualDigest, err := algo.FromReader(r)
855 if err != nil {
856 return err
857 }
858 if actualDigest != expectedDigest {
859 return fmt.Errorf("expected digest %#q, got %#q", expectedDigest, actualDigest)
860 }
861 return nil
862}
863
864// mathLastModified takes params:
865// - ctx: context for calling httpclientutil.Head
866// - lastModifiedPath: path of the cached last-modified time file
867// - url: URL to fetch the last-modified time
868//
869// returns:
870// - matched: whether the last-modified time matches
871// - lmCached: last-modified time string from the lastModifiedPath
872// - lmRemote: last-modified time string from the URL
873// - err: error if fetching the last-modified time from the URL fails
874func matchLastModified(ctx context.Context, lastModifiedPath, url string) (matched bool, lmCached, lmRemote string, err error) {
875 lmCached = readFile(lastModifiedPath)
876 if lmCached == "" {
877 return false, "<not cached>", "<not checked>", nil
878 }
879 resp, err := httpclientutil.Head(ctx, http.DefaultClient, url)
880 if err != nil {
881 return false, lmCached, "<failed to fetch remote>", err
882 }
883 defer resp.Body.Close()
884 lmRemote = resp.Header.Get("Last-Modified")
885 if lmRemote == "" {
886 return false, lmCached, "<missing Last-Modified header>", nil
887 }
888 lmCachedTime, errParsingCachedTime := time.Parse(http.TimeFormat, lmCached)
889 lmRemoteTime, errParsingRemoteTime := time.Parse(http.TimeFormat, lmRemote)
890 if errParsingCachedTime != nil && errParsingRemoteTime != nil {
891 // both time strings are failed to parse, so compare them as strings
892 return lmCached == lmRemote, lmCached, lmRemote, nil
893 } else if errParsingCachedTime == nil && errParsingRemoteTime == nil {
894 // both time strings are successfully parsed, so compare them as times
895 return lmRemoteTime.Equal(lmCachedTime), lmCached, lmRemote, nil
896 }
897 // ignore parsing errors for either time string and assume they are different
898 return false, lmCached, lmRemote, nil
899}
900
901func downloadHTTP(ctx context.Context, localPath, lastModified, contentType, url, description string, expectedDigest digest.Digest) error {
902 if localPath == "" {
903 return errors.New("downloadHTTP: got empty localPath")
904 }
905 logrus.Debugf("downloading %#q into %#q", url, localPath)
906
907 resp, err := httpclientutil.Get(ctx, http.DefaultClient, url)
908 if err != nil {
909 return err
910 }
911 if lastModified != "" {
912 lm := resp.Header.Get("Last-Modified")
913 if err := os.WriteFile(lastModified, []byte(lm), 0o644); err != nil {
914 return err
915 }
916 }
917 if contentType != "" {
918 ct := resp.Header.Get("Content-Type")
919 if err := os.WriteFile(contentType, []byte(ct), 0o644); err != nil {
920 return err
921 }
922 }
923 defer resp.Body.Close()
924 bar, err := progressbar.New(resp.ContentLength)
925 if err != nil {
926 return err
927 }
928 if HideProgress {
929 hideBar(bar)
930 }
931
932 localPathTmp := perProcessTempfile(localPath)
933 fileWriter, err := os.Create(localPathTmp)
934 if err != nil {
935 return err
936 }
937 defer fileWriter.Close()
938 defer os.RemoveAll(localPathTmp)
939
940 writers := []io.Writer{fileWriter}
941 var digester digest.Digester
942 if expectedDigest != "" {
943 algo := expectedDigest.Algorithm()
944 if !algo.Available() {
945 return fmt.Errorf("unsupported digest algorithm %#q", algo)
946 }
947 digester = algo.Digester()
948 hasher := digester.Hash()
949 writers = append(writers, hasher)
950 }
951 multiWriter := io.MultiWriter(writers...)
952
953 if !HideProgress {
954 if description == "" {
955 description = url
956 }
957 // stderr corresponds to the progress bar output
958 fmt.Fprintf(os.Stderr, "Downloading %s\n", description)
959 }
960 bar.Start()
961 if _, err := io.Copy(multiWriter, bar.NewProxyReader(resp.Body)); err != nil {
962 return err
963 }
964 bar.Finish()
965
966 if digester != nil {
967 actualDigest := digester.Digest()
968 if actualDigest != expectedDigest {
969 return fmt.Errorf("expected digest %#q, got %#q", expectedDigest, actualDigest)
970 }
971 }
972
973 if err := fileWriter.Sync(); err != nil {
974 return err
975 }
976 if err := fileWriter.Close(); err != nil {
977 return err
978 }
979
980 return os.Rename(localPathTmp, localPath)
981}
982
983var tempfileCount atomic.Uint64
984
985// To allow parallel download we use a per-process unique suffix for temporary
986// files. Renaming the temporary file to the final file is safe without
987// synchronization on posix.
988// To make it easy to test we also include a counter ensuring that each
989// temporary file is unique in the same process.
990// https://github.com/lima-vm/lima/issues/2722
991func perProcessTempfile(path string) string {
992 return fmt.Sprintf("%s.tmp.%d.%d", path, os.Getpid(), tempfileCount.Add(1))
993}
994
995// CacheEntries returns a map of cache entries.
996// The key is the SHA256 of the URL.
997// The value is the path to the cache entry.
998func CacheEntries(opts ...Opt) (map[string]string, error) {
999 entries := make(map[string]string)
1000 var o options
1001 if err := o.apply(opts); err != nil {
1002 return nil, err
1003 }
1004 if o.cacheDir == "" {
1005 return entries, nil
1006 }
1007 downloadDir := filepath.Join(o.cacheDir, "download", "by-url-sha256")
1008 _, err := os.Stat(downloadDir)
1009 if err != nil {
1010 if errors.Is(err, os.ErrNotExist) {
1011 return entries, nil
1012 }
1013 return nil, err
1014 }
1015 cacheEntries, err := os.ReadDir(downloadDir)
1016 if err != nil {
1017 return nil, err
1018 }
1019 for _, entry := range cacheEntries {
1020 entries[entry.Name()] = filepath.Join(downloadDir, entry.Name())
1021 }
1022 return entries, nil
1023}
1024
1025// CacheKey returns the key for a cache entry of the remote URL.
1026func CacheKey(remote string) string {
1027 return fmt.Sprintf("%x", sha256.Sum256([]byte(remote)))
1028}
1029
1030// RemoveAllCacheDir removes the cache directory.
1031func RemoveAllCacheDir(opts ...Opt) error {
1032 var o options
1033 if err := o.apply(opts); err != nil {
1034 return err
1035 }
1036 if o.cacheDir == "" {
1037 return nil
1038 }
1039 logrus.Infof("Pruning %#q", o.cacheDir)
1040 return os.RemoveAll(o.cacheDir)
1041}
1042
1043// RemoveStaleTempFiles removes leftover partial-download files ("data.part" and
1044// legacy "data.tmp.*") from the cache, keeping the completed "data" files.
1045// Each cache entry is locked before its partial files are removed, so a download
1046// currently in progress is never disturbed.
1047func RemoveStaleTempFiles(opts ...Opt) error {
1048 var o options
1049 if err := o.apply(opts); err != nil {
1050 return err
1051 }
1052 if o.cacheDir == "" {
1053 return nil
1054 }
1055 entries, err := CacheEntries(opts...)
1056 if err != nil {
1057 return err
1058 }
1059 for _, dir := range entries {
1060 if err := removeStaleTempFilesInDir(dir); err != nil {
1061 return err
1062 }
1063 }
1064 return nil
1065}
1066
1067func removeStaleTempFilesInDir(dir string) error {
1068 return lockutil.WithDirLock(dir, func() error {
1069 patterns := []string{
1070 filepath.Join(dir, "data.part"),
1071 filepath.Join(dir, "data.part.digest"),
1072 filepath.Join(dir, "data.tmp.*"),
1073 }
1074 for _, pattern := range patterns {
1075 matches, err := filepath.Glob(pattern)
1076 if err != nil {
1077 return err
1078 }
1079 for _, m := range matches {
1080 logrus.Debugf("Removing stale partial download %#q", m)
1081 if err := os.Remove(m); err != nil && !errors.Is(err, os.ErrNotExist) {
1082 return err
1083 }
1084 }
1085 }
1086 return nil
1087 })
1088}