File: fetch.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (175 lines) | stat: -rw-r--r-- 4,833 bytes parent folder | download
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// Copyright (c) 2019-2023, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package ociimage

import (
	"archive/tar"
	"bufio"
	"compress/gzip"
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/containers/image/v5/copy"
	ocilayout "github.com/containers/image/v5/oci/layout"
	"github.com/containers/image/v5/types"
	"github.com/opencontainers/go-digest"
	"github.com/sylabs/singularity/v4/internal/pkg/cache"
	"github.com/sylabs/singularity/v4/pkg/sylog"
	"golang.org/x/term"
)

// FetchLayout will fetch the OCI image specified by imageRef to a containers/image OCI layout in layoutDir.
// An ImageReference to the image that was fetched into layoutDir is returned on success.
// If imgCache is non-nil, and enabled, the image will be pulled through the cache.
func FetchLayout(ctx context.Context, sysCtx *types.SystemContext, imgCache *cache.Handle, imageRef, layoutDir string) (types.ImageReference, digest.Digest, error) {
	policyCtx, err := defaultPolicy()
	if err != nil {
		return nil, "", err
	}

	srcRef, err := ParseImageRef(imageRef)
	if err != nil {
		return nil, "", fmt.Errorf("invalid image source: %v", err)
	}

	// oci-archive direct handling by containers/image can fail as non-root.
	// Perform a tar extraction first, and handle as an oci layout.
	if os.Geteuid() != 0 && srcRef.Transport().Name() == "oci-archive" {
		var tmpDir string
		tmpDir, err = os.MkdirTemp(sysCtx.BigFilesTemporaryDir, "temp-oci-")
		if err != nil {
			return nil, "", fmt.Errorf("could not create temporary oci directory: %v", err)
		}
		defer os.RemoveAll(tmpDir)

		archiveParts := strings.SplitN(srcRef.StringWithinTransport(), ":", 2)
		sylog.Debugf("Extracting oci-archive %q to %q", archiveParts[0], tmpDir)
		err = extractArchive(archiveParts[0], tmpDir)
		if err != nil {
			return nil, "", fmt.Errorf("error extracting the OCI archive file: %v", err)
		}
		// We may or may not have had a ':tag' in the source to handle
		if len(archiveParts) == 2 {
			srcRef, err = ocilayout.ParseReference(tmpDir + ":" + archiveParts[1])
		} else {
			srcRef, err = ocilayout.ParseReference(tmpDir)
		}
		if err != nil {
			return nil, "", err
		}
	}

	var imgDigest digest.Digest

	if imgCache != nil && !imgCache.IsDisabled() {
		// Grab the modified source ref from the cache
		srcRef, imgDigest, err = CacheReference(ctx, sysCtx, imgCache, srcRef)
		if err != nil {
			return nil, "", err
		}
	}

	lr, err := ocilayout.ParseReference(layoutDir + ":" + imgDigest.String())
	if err != nil {
		return nil, "", err
	}

	copyOpts := copy.Options{
		ReportWriter: os.Stdout,
		SourceCtx:    sysCtx,
	}
	if (sylog.GetLevel() <= -1) || !term.IsTerminal(2) {
		copyOpts.ReportWriter = io.Discard
	}
	_, err = copy.Image(ctx, policyCtx, lr, srcRef, &copyOpts)
	if err != nil {
		return nil, "", err
	}

	return lr, imgDigest, nil
}

// Perform a dumb tar(gz) extraction with no chown, id remapping etc.
// This is needed for non-root handling of `oci-archive` as the extraction
// by containers/archive is failing when uid/gid don't match local machine
// and we're not root
func extractArchive(src string, dst string) error {
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()

	r := bufio.NewReader(f)
	header, err := r.Peek(10) // read a few bytes without consuming
	if err != nil {
		return err
	}
	gzipped := strings.Contains(http.DetectContentType(header), "x-gzip")

	if gzipped {
		r, err := gzip.NewReader(f)
		if err != nil {
			return err
		}
		defer r.Close()
	}

	tr := tar.NewReader(r)

	for {
		header, err := tr.Next()
		switch {
		// if no more files are found return
		case err == io.EOF:
			return nil

		// return any other error
		case err != nil:
			return err

		// if the header is nil, just skip it (not sure how this happens)
		case header == nil:
			continue
		}

		// ZipSlip protection - don't escape from dst
		//#nosec G305
		target := filepath.Join(dst, header.Name)
		if !strings.HasPrefix(target, filepath.Clean(dst)+string(os.PathSeparator)) {
			return fmt.Errorf("%s: illegal extraction path", target)
		}

		// check the file type
		switch header.Typeflag {
		// if its a dir and it doesn't exist create it
		case tar.TypeDir:
			if _, err := os.Stat(target); err != nil {
				if err := os.MkdirAll(target, 0o755); err != nil {
					return err
				}
			}
		// if it's a file create it
		case tar.TypeReg:
			f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
			if err != nil {
				return err
			}
			defer f.Close()

			// copy over contents
			//#nosec G110
			if _, err := io.Copy(f, tr); err != nil {
				return err
			}
		}
	}
}