Debian Codegraph @

image/manifest.go

raw symbols SCIP
1 // Copyright 2016 The Linux Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package image
16
17 import (
18 "archive/tar"
19 "bufio"
20 "bytes"
21 "compress/bzip2"
22 "compress/gzip"
23 "encoding/json"
24 "fmt"
25 "io"
26 "io/ioutil"
27 "os"
28 "path/filepath"
29 "strings"
30 "time"
31
32 "github.com/opencontainers/image-spec/schema"
33 "github.com/opencontainers/image-spec/specs-go/v1"
34 "github.com/pkg/errors"
35 "github.com/sirupsen/logrus"
36 )
37
38 func findManifest(w walker, d *v1.Descriptor) (*v1.Manifest, error) {
39 var m v1.Manifest
40 mpath := filepath.Join("blobs", string(d.Digest.Algorithm()), d.Digest.Hex())
41
42 switch err := w.find(mpath, func(path string, r io.Reader) error {
43 buf, err := ioutil.ReadAll(r)
44 if err != nil {
45 return errors.Wrapf(err, "%s: error reading manifest", path)
46 }
47
48 if err := schema.ValidatorMediaTypeManifest.Validate(bytes.NewReader(buf)); err != nil {
49 return errors.Wrapf(err, "%s: manifest validation failed", path)
50 }
51
52 if err := json.Unmarshal(buf, &m); err != nil {
53 return err
54 }
55
56 return errEOW
57 }); err {
58 case nil:
59 return nil, fmt.Errorf("%s: manifest not found", mpath)
60 case errEOW:
61 return &m, nil
62 default:
63 return nil, err
64 }
65 }
66
67 func validateManifest(m *v1.Manifest, w walker) error {
68 if err := validateDescriptor(&m.Config, w, []string{v1.MediaTypeImageConfig}); err != nil {
69 return errors.Wrap(err, "config validation failed")
70 }
71
72 validLayerMediaTypes := []string{
73 v1.MediaTypeImageLayer,
74 v1.MediaTypeImageLayerGzip,
75 v1.MediaTypeImageLayerNonDistributable,
76 v1.MediaTypeImageLayerNonDistributableGzip,
77 }
78
79 for _, d := range m.Layers {
80 if err := validateDescriptor(&d, w, validLayerMediaTypes); err != nil {
81 return errors.Wrap(err, "layer validation failed")
82 }
83 }
84
85 return nil
86 }
87
88 func unpackManifest(m *v1.Manifest, w walker, dest string) (retErr error) {
89 // error out if the dest directory is not empty
90 s, err := ioutil.ReadDir(dest)
91 if err != nil && !os.IsNotExist(err) { // We'll create the dir later
92 return errors.Wrap(err, "unpack: unable to open dest") // err contains dest
93 }
94 if len(s) > 0 {
95 return fmt.Errorf("%s is not empty", dest)
96 }
97 defer func() {
98 // if we encounter error during unpacking
99 // clean up the partially-unpacked destination
100 if retErr != nil {
101 if err := os.RemoveAll(dest); err != nil {
102 fmt.Printf("Error: failed to remove partially-unpacked destination %v", err)
103 }
104 }
105 }()
106 for _, d := range m.Layers {
107 lpath := filepath.Join("blobs", string(d.Digest.Algorithm()), d.Digest.Hex())
108 switch err := w.find(lpath, func(path string, r io.Reader) error {
109 if err := unpackLayer(d.MediaType, path, dest, r); err != nil {
110 return errors.Wrap(err, "unpack: error extracting layer")
111 }
112
113 return errEOW
114 }); err {
115 case nil:
116 return fmt.Errorf("%s: layer not found", dest)
117 case errEOW:
118 default:
119 return err
120 }
121 }
122 return nil
123 }
124
125 func getReader(path, mediaType, comp string, buf io.Reader) (io.Reader, error) {
126 switch comp {
127 case "gzip":
128 if !strings.HasSuffix(mediaType, "+gzip") {
129 logrus.Debugf("%q: %s media type with non-%s file", path, comp, comp)
130 }
131
132 return gzip.NewReader(buf)
133 case "bzip2":
134 if !strings.HasSuffix(mediaType, "+bzip2") {
135 logrus.Debugf("%q: %s media type with non-%s file", path, comp, comp)
136 }
137
138 return bzip2.NewReader(buf), nil
139 case "xz":
140 return nil, errors.New("xz layers are not supported")
141 default:
142 if strings.Contains(mediaType, "+") {
143 logrus.Debugf("%q: %s media type with non-%s file", path, comp, comp)
144 }
145
146 return buf, nil
147 }
148 }
149
150 // DetectCompression detects the compression algorithm of the source.
151 func DetectCompression(r *bufio.Reader) (string, error) {
152 source, err := r.Peek(10)
153 if err != nil {
154 return "", err
155 }
156
157 for compression, m := range map[string][]byte{
158 "bzip2": {0x42, 0x5A, 0x68},
159 "gzip": {0x1F, 0x8B, 0x08},
160 // FIXME needs decompression support
161 // "xz": {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
162 } {
163 if len(source) < len(m) {
164 logrus.Debug("Len too short")
165 continue
166 }
167 if bytes.Equal(m, source[:len(m)]) {
168 return compression, nil
169 }
170 }
171 return "plain", nil
172 }
173
174 func unpackLayer(mediaType, path, dest string, r io.Reader) error {
175 entries := make(map[string]bool)
176
177 buf := bufio.NewReader(r)
178
179 comp, err := DetectCompression(buf)
180 if err != nil {
181 return err
182 }
183
184 reader, err := getReader(path, mediaType, comp, buf)
185 if err != nil {
186 return err
187 }
188
189 var dirs []*tar.Header
190 tr := tar.NewReader(reader)
191
192 loop:
193 for {
194 hdr, err := tr.Next()
195 switch err {
196 case io.EOF:
197 break loop
198 case nil:
199 // success, continue below
200 default:
201 return errors.Wrapf(err, "error advancing tar stream")
202 }
203
204 var whiteout bool
205 whiteout, err = unpackLayerEntry(dest, hdr, tr, &entries)
206 if err != nil {
207 return err
208 }
209 if whiteout {
210 continue loop
211 }
212
213 // Directory mtimes must be handled at the end to avoid further
214 // file creation in them to modify the directory mtime
215 if hdr.Typeflag == tar.TypeDir {
216 dirs = append(dirs, hdr)
217 }
218 }
219 for _, hdr := range dirs {
220 path := filepath.Join(dest, hdr.Name)
221
222 finfo := hdr.FileInfo()
223 // I believe the old version was using time.Now().UTC() to overcome an
224 // invalid error from chtimes.....but here we lose hdr.AccessTime like this...
225 if err := os.Chtimes(path, time.Now().UTC(), finfo.ModTime()); err != nil {
226 return errors.Wrap(err, "error changing time")
227 }
228 }
229 return nil
230 }
231
232 // unpackLayerEntry unpacks a single entry from a layer.
233 func unpackLayerEntry(dest string, header *tar.Header, reader io.Reader, entries *map[string]bool) (whiteout bool, err error) {
234 header.Name = filepath.Clean(header.Name)
235 if !strings.HasSuffix(header.Name, string(os.PathSeparator)) {
236 // Not the root directory, ensure that the parent directory exists
237 parent := filepath.Dir(header.Name)
238 parentPath := filepath.Join(dest, parent)
239 if _, err2 := os.Lstat(parentPath); err2 != nil && os.IsNotExist(err2) {
240 if err3 := os.MkdirAll(parentPath, 0755); err3 != nil {
241 return false, err3
242 }
243 }
244 }
245 path := filepath.Join(dest, header.Name)
246 if (*entries)[path] {
247 return false, fmt.Errorf("duplicate entry for %s", path)
248 }
249 (*entries)[path] = true
250 rel, err := filepath.Rel(dest, path)
251 if err != nil {
252 return false, err
253 }
254 info := header.FileInfo()
255 if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
256 return false, fmt.Errorf("%q is outside of %q", header.Name, dest)
257 }
258
259 if strings.HasPrefix(info.Name(), ".wh.") {
260 path = strings.Replace(path, ".wh.", "", 1)
261
262 if err = os.RemoveAll(path); err != nil {
263 return true, errors.Wrap(err, "unable to delete whiteout path")
264 }
265
266 return true, nil
267 }
268
269 if header.Typeflag != tar.TypeDir {
270 err = os.RemoveAll(path)
271 if err != nil && !os.IsNotExist(err) {
272 return false, err
273 }
274 }
275
276 switch header.Typeflag {
277 case tar.TypeDir:
278 fi, err := os.Lstat(path)
279 if err != nil && !os.IsNotExist(err) {
280 return false, err
281 }
282 if os.IsNotExist(err) || !fi.IsDir() {
283 err = os.RemoveAll(path)
284 if err != nil && !os.IsNotExist(err) {
285 return false, err
286 }
287 err = os.MkdirAll(path, info.Mode())
288 if err != nil {
289 return false, err
290 }
291 }
292
293 case tar.TypeReg, tar.TypeRegA:
294 f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, info.Mode())
295 if err != nil {
296 return false, errors.Wrap(err, "unable to open file")
297 }
298
299 if _, err := io.Copy(f, reader); err != nil {
300 f.Close()
301 return false, errors.Wrap(err, "unable to copy")
302 }
303 f.Close()
304
305 case tar.TypeLink:
306 target := filepath.Join(dest, header.Linkname)
307
308 if !strings.HasPrefix(target, dest) {
309 return false, fmt.Errorf("invalid hardlink %q -> %q", target, header.Linkname)
310 }
311
312 if err := os.Link(target, path); err != nil {
313 return false, err
314 }
315
316 case tar.TypeSymlink:
317 target := filepath.Join(filepath.Dir(path), header.Linkname)
318
319 if !strings.HasPrefix(target, dest) {
320 return false, fmt.Errorf("invalid symlink %q -> %q", path, header.Linkname)
321 }
322
323 if err := os.Symlink(header.Linkname, path); err != nil {
324 return false, err
325 }
326 case tar.TypeXGlobalHeader:
327 return false, nil
328 }
329
330 return false, nil
331 }