pkg/archive/diff.go
318dd33f
 package archive
 
 import (
576985a1
 	"archive/tar"
6889cd9f
 	"fmt"
818c249b
 	"io"
6889cd9f
 	"io/ioutil"
318dd33f
 	"os"
f1127b93
 	"path/filepath"
3c177dc8
 	"runtime"
318dd33f
 	"strings"
9e51b7ab
 
442b4562
 	"github.com/docker/docker/pkg/idtools"
84d76e55
 	"github.com/docker/docker/pkg/pools"
2180aa4f
 	"github.com/docker/docker/pkg/system"
1009e6a4
 	"github.com/sirupsen/logrus"
318dd33f
 )
 
ba332b7d
 // UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be
 // compressed or uncompressed.
 // Returns the size in bytes of the contents of the layer.
aa2cc187
 func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) {
818c249b
 	tr := tar.NewReader(layer)
84d76e55
 	trBuf := pools.BufioReader32KPool.Get(tr)
 	defer pools.BufioReader32KPool.Put(trBuf)
318dd33f
 
818c249b
 	var dirs []*tar.Header
db3070ab
 	unpackedPaths := make(map[string]struct{})
6d71f277
 
 	if options == nil {
 		options = &TarOptions{}
 	}
 	if options.ExcludePatterns == nil {
 		options.ExcludePatterns = []string{}
 	}
df248d31
 	idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps)
3edb4af6
 
6889cd9f
 	aufsTempdir := ""
 	aufsHardlinks := make(map[string]*tar.Header)
 
818c249b
 	// Iterate through the files in the archive.
 	for {
 		hdr, err := tr.Next()
 		if err == io.EOF {
 			// end of tar archive
 			break
 		}
318dd33f
 		if err != nil {
35a22c9e
 			return 0, err
318dd33f
 		}
 
35a22c9e
 		size += hdr.Size
 
78c22c24
 		// Normalize name, for safety and for a simple is-root check
 		hdr.Name = filepath.Clean(hdr.Name)
 
3c177dc8
 		// Windows does not support filenames with colons in them. Ignore
 		// these files. This is not a problem though (although it might
 		// appear that it is). Let's suppose a client is running docker pull.
 		// The daemon it points to is Windows. Would it make sense for the
 		// client to be doing a docker pull Ubuntu for example (which has files
 		// with colons in the name under /usr/share/man/man3)? No, absolutely
 		// not as it would really only make sense that they were pulling a
 		// Windows image. However, for development, it is necessary to be able
 		// to pull Linux images which are in the repository.
 		//
 		// TODO Windows. Once the registry is aware of what images are Windows-
 		// specific or Linux-specific, this warning should be changed to an error
 		// to cater for the situation where someone does manage to upload a Linux
51462327
 		// image but have it tagged as Windows inadvertently.
3c177dc8
 		if runtime.GOOS == "windows" {
 			if strings.Contains(hdr.Name, ":") {
 				logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name)
 				continue
 			}
 		}
 
 		// Note as these operations are platform specific, so must the slash be.
 		if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
0fccf0f6
 			// Not the root directory, ensure that the parent directory exists.
78c22c24
 			// This happened in some tests where an image had a tarfile without any
0fccf0f6
 			// parent directories.
78c22c24
 			parent := filepath.Dir(hdr.Name)
 			parentPath := filepath.Join(dest, parent)
3c177dc8
 
78c22c24
 			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
ed10ac6e
 				err = system.MkdirAll(parentPath, 0600, "")
78c22c24
 				if err != nil {
35a22c9e
 					return 0, err
78c22c24
 				}
 			}
 		}
 
818c249b
 		// Skip AUFS metadata dirs
2fb5d0c3
 		if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) {
6889cd9f
 			// Regular files inside /.wh..wh.plnk can be used as hardlink targets
 			// We don't want this directory, but we need the files in them so that
 			// such hardlinks can be resolved.
2fb5d0c3
 			if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg {
6889cd9f
 				basename := filepath.Base(hdr.Name)
 				aufsHardlinks[basename] = hdr
 				if aufsTempdir == "" {
 					if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil {
35a22c9e
 						return 0, err
6889cd9f
 					}
 					defer os.RemoveAll(aufsTempdir)
 				}
617c352e
 				if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil, options.InUserNS); err != nil {
35a22c9e
 					return 0, err
6889cd9f
 				}
 			}
00e32771
 
2fb5d0c3
 			if hdr.Name != WhiteoutOpaqueDir {
00e32771
 				continue
 			}
318dd33f
 		}
818c249b
 		path := filepath.Join(dest, hdr.Name)
be5bfbe2
 		rel, err := filepath.Rel(dest, path)
 		if err != nil {
35a22c9e
 			return 0, err
be5bfbe2
 		}
3c177dc8
 
 		// Note as these operations are platform specific, so must the slash be.
 		if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
35a22c9e
 			return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
31d1d733
 		}
be5bfbe2
 		base := filepath.Base(path)
31d1d733
 
2fb5d0c3
 		if strings.HasPrefix(base, WhiteoutPrefix) {
00e32771
 			dir := filepath.Dir(path)
2fb5d0c3
 			if base == WhiteoutOpaqueDir {
db3070ab
 				_, err := os.Lstat(dir)
 				if err != nil {
00e32771
 					return 0, err
 				}
db3070ab
 				err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
 					if err != nil {
 						if os.IsNotExist(err) {
 							err = nil // parent was deleted
 						}
 						return err
 					}
 					if path == dir {
 						return nil
 					}
 					if _, exists := unpackedPaths[path]; !exists {
 						err := os.RemoveAll(path)
 						return err
 					}
 					return nil
 				})
 				if err != nil {
00e32771
 					return 0, err
 				}
 			} else {
2fb5d0c3
 				originalBase := base[len(WhiteoutPrefix):]
00e32771
 				originalPath := filepath.Join(dir, originalBase)
 				if err := os.RemoveAll(originalPath); err != nil {
 					return 0, err
 				}
3edb4af6
 			}
818c249b
 		} else {
0fccf0f6
 			// If path exits we almost always just want to remove and replace it.
818c249b
 			// The only exception is when it is a directory *and* the file from
 			// the layer is also a directory. Then we want to merge them (i.e.
 			// just apply the metadata from the layer).
 			if fi, err := os.Lstat(path); err == nil {
710d5a48
 				if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
818c249b
 					if err := os.RemoveAll(path); err != nil {
35a22c9e
 						return 0, err
818c249b
 					}
 				}
 			}
318dd33f
 
a3778449
 			trBuf.Reset(tr)
 			srcData := io.Reader(trBuf)
6889cd9f
 			srcHdr := hdr
 
 			// Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
 			// we manually retarget these into the temporary files we extracted them into
2fb5d0c3
 			if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) {
6889cd9f
 				linkBasename := filepath.Base(hdr.Linkname)
 				srcHdr = aufsHardlinks[linkBasename]
 				if srcHdr == nil {
35a22c9e
 					return 0, fmt.Errorf("Invalid aufs hardlink")
6889cd9f
 				}
 				tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename))
 				if err != nil {
35a22c9e
 					return 0, err
6889cd9f
 				}
 				defer tmpFile.Close()
 				srcData = tmpFile
 			}
 
df248d31
 			if err := remapIDs(idMappings, srcHdr); err != nil {
 				return 0, err
442b4562
 			}
df248d31
 
617c352e
 			if err := createTarFile(path, dest, srcHdr, srcData, true, nil, options.InUserNS); err != nil {
35a22c9e
 				return 0, err
3edb4af6
 			}
818c249b
 
710d5a48
 			// Directory mtimes must be handled at the end to avoid further
 			// file creation in them to modify the directory mtime
 			if hdr.Typeflag == tar.TypeDir {
 				dirs = append(dirs, hdr)
818c249b
 			}
db3070ab
 			unpackedPaths[path] = struct{}{}
318dd33f
 		}
 	}
3edb4af6
 
818c249b
 	for _, hdr := range dirs {
 		path := filepath.Join(dest, hdr.Name)
40b77af2
 		if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil {
35a22c9e
 			return 0, err
3edb4af6
 		}
 	}
35a22c9e
 
 	return size, nil
318dd33f
 }
7862f831
 
56bf275e
 // ApplyLayer parses a diff in the standard layer format from `layer`,
 // and applies it to the directory `dest`. The stream `layer` can be
 // compressed or uncompressed.
 // Returns the size in bytes of the contents of the layer.
aa2cc187
 func ApplyLayer(dest string, layer io.Reader) (int64, error) {
442b4562
 	return applyLayerHandler(dest, layer, &TarOptions{}, true)
56bf275e
 }
 
 // ApplyUncompressedLayer parses a diff in the standard layer format from
 // `layer`, and applies it to the directory `dest`. The stream `layer`
 // can only be uncompressed.
 // Returns the size in bytes of the contents of the layer.
aa2cc187
 func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) (int64, error) {
442b4562
 	return applyLayerHandler(dest, layer, options, false)
56bf275e
 }
 
 // do the bulk load of ApplyLayer, but allow for not calling DecompressStream
aa2cc187
 func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) {
7862f831
 	dest = filepath.Clean(dest)
 
 	// We need to be able to set any perms
 	oldmask, err := system.Umask(0)
 	if err != nil {
35a22c9e
 		return 0, err
7862f831
 	}
 	defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform
 
56bf275e
 	if decompress {
 		layer, err = DecompressStream(layer)
 		if err != nil {
 			return 0, err
 		}
7862f831
 	}
442b4562
 	return UnpackLayer(dest, layer, options)
7862f831
 }