github.com/damirazo/docker@v1.9.0/pkg/archive/diff.go (about)

     1  package archive
     2  
     3  import (
     4  	"archive/tar"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"path/filepath"
    10  	"runtime"
    11  	"strings"
    12  
    13  	"github.com/Sirupsen/logrus"
    14  	"github.com/docker/docker/pkg/idtools"
    15  	"github.com/docker/docker/pkg/pools"
    16  	"github.com/docker/docker/pkg/system"
    17  )
    18  
    19  // UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be
    20  // compressed or uncompressed.
    21  // Returns the size in bytes of the contents of the layer.
    22  func UnpackLayer(dest string, layer Reader, options *TarOptions) (size int64, err error) {
    23  	tr := tar.NewReader(layer)
    24  	trBuf := pools.BufioReader32KPool.Get(tr)
    25  	defer pools.BufioReader32KPool.Put(trBuf)
    26  
    27  	var dirs []*tar.Header
    28  
    29  	if options == nil {
    30  		options = &TarOptions{}
    31  	}
    32  	if options.ExcludePatterns == nil {
    33  		options.ExcludePatterns = []string{}
    34  	}
    35  	remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps)
    36  	if err != nil {
    37  		return 0, err
    38  	}
    39  
    40  	aufsTempdir := ""
    41  	aufsHardlinks := make(map[string]*tar.Header)
    42  
    43  	if options == nil {
    44  		options = &TarOptions{}
    45  	}
    46  	// Iterate through the files in the archive.
    47  	for {
    48  		hdr, err := tr.Next()
    49  		if err == io.EOF {
    50  			// end of tar archive
    51  			break
    52  		}
    53  		if err != nil {
    54  			return 0, err
    55  		}
    56  
    57  		size += hdr.Size
    58  
    59  		// Normalize name, for safety and for a simple is-root check
    60  		hdr.Name = filepath.Clean(hdr.Name)
    61  
    62  		// Windows does not support filenames with colons in them. Ignore
    63  		// these files. This is not a problem though (although it might
    64  		// appear that it is). Let's suppose a client is running docker pull.
    65  		// The daemon it points to is Windows. Would it make sense for the
    66  		// client to be doing a docker pull Ubuntu for example (which has files
    67  		// with colons in the name under /usr/share/man/man3)? No, absolutely
    68  		// not as it would really only make sense that they were pulling a
    69  		// Windows image. However, for development, it is necessary to be able
    70  		// to pull Linux images which are in the repository.
    71  		//
    72  		// TODO Windows. Once the registry is aware of what images are Windows-
    73  		// specific or Linux-specific, this warning should be changed to an error
    74  		// to cater for the situation where someone does manage to upload a Linux
    75  		// image but have it tagged as Windows inadvertently.
    76  		if runtime.GOOS == "windows" {
    77  			if strings.Contains(hdr.Name, ":") {
    78  				logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name)
    79  				continue
    80  			}
    81  		}
    82  
    83  		// Note as these operations are platform specific, so must the slash be.
    84  		if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
    85  			// Not the root directory, ensure that the parent directory exists.
    86  			// This happened in some tests where an image had a tarfile without any
    87  			// parent directories.
    88  			parent := filepath.Dir(hdr.Name)
    89  			parentPath := filepath.Join(dest, parent)
    90  
    91  			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
    92  				err = system.MkdirAll(parentPath, 0600)
    93  				if err != nil {
    94  					return 0, err
    95  				}
    96  			}
    97  		}
    98  
    99  		// Skip AUFS metadata dirs
   100  		if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) {
   101  			// Regular files inside /.wh..wh.plnk can be used as hardlink targets
   102  			// We don't want this directory, but we need the files in them so that
   103  			// such hardlinks can be resolved.
   104  			if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg {
   105  				basename := filepath.Base(hdr.Name)
   106  				aufsHardlinks[basename] = hdr
   107  				if aufsTempdir == "" {
   108  					if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil {
   109  						return 0, err
   110  					}
   111  					defer os.RemoveAll(aufsTempdir)
   112  				}
   113  				if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil); err != nil {
   114  					return 0, err
   115  				}
   116  			}
   117  
   118  			if hdr.Name != WhiteoutOpaqueDir {
   119  				continue
   120  			}
   121  		}
   122  		path := filepath.Join(dest, hdr.Name)
   123  		rel, err := filepath.Rel(dest, path)
   124  		if err != nil {
   125  			return 0, err
   126  		}
   127  
   128  		// Note as these operations are platform specific, so must the slash be.
   129  		if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
   130  			return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
   131  		}
   132  		base := filepath.Base(path)
   133  
   134  		if strings.HasPrefix(base, WhiteoutPrefix) {
   135  			dir := filepath.Dir(path)
   136  			if base == WhiteoutOpaqueDir {
   137  				fi, err := os.Lstat(dir)
   138  				if err != nil && !os.IsNotExist(err) {
   139  					return 0, err
   140  				}
   141  				if err := os.RemoveAll(dir); err != nil {
   142  					return 0, err
   143  				}
   144  				if err := os.Mkdir(dir, fi.Mode()&os.ModePerm); err != nil {
   145  					return 0, err
   146  				}
   147  			} else {
   148  				originalBase := base[len(WhiteoutPrefix):]
   149  				originalPath := filepath.Join(dir, originalBase)
   150  				if err := os.RemoveAll(originalPath); err != nil {
   151  					return 0, err
   152  				}
   153  			}
   154  		} else {
   155  			// If path exits we almost always just want to remove and replace it.
   156  			// The only exception is when it is a directory *and* the file from
   157  			// the layer is also a directory. Then we want to merge them (i.e.
   158  			// just apply the metadata from the layer).
   159  			if fi, err := os.Lstat(path); err == nil {
   160  				if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
   161  					if err := os.RemoveAll(path); err != nil {
   162  						return 0, err
   163  					}
   164  				}
   165  			}
   166  
   167  			trBuf.Reset(tr)
   168  			srcData := io.Reader(trBuf)
   169  			srcHdr := hdr
   170  
   171  			// Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
   172  			// we manually retarget these into the temporary files we extracted them into
   173  			if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) {
   174  				linkBasename := filepath.Base(hdr.Linkname)
   175  				srcHdr = aufsHardlinks[linkBasename]
   176  				if srcHdr == nil {
   177  					return 0, fmt.Errorf("Invalid aufs hardlink")
   178  				}
   179  				tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename))
   180  				if err != nil {
   181  					return 0, err
   182  				}
   183  				defer tmpFile.Close()
   184  				srcData = tmpFile
   185  			}
   186  
   187  			// if the options contain a uid & gid maps, convert header uid/gid
   188  			// entries using the maps such that lchown sets the proper mapped
   189  			// uid/gid after writing the file. We only perform this mapping if
   190  			// the file isn't already owned by the remapped root UID or GID, as
   191  			// that specific uid/gid has no mapping from container -> host, and
   192  			// those files already have the proper ownership for inside the
   193  			// container.
   194  			if srcHdr.Uid != remappedRootUID {
   195  				xUID, err := idtools.ToHost(srcHdr.Uid, options.UIDMaps)
   196  				if err != nil {
   197  					return 0, err
   198  				}
   199  				srcHdr.Uid = xUID
   200  			}
   201  			if srcHdr.Gid != remappedRootGID {
   202  				xGID, err := idtools.ToHost(srcHdr.Gid, options.GIDMaps)
   203  				if err != nil {
   204  					return 0, err
   205  				}
   206  				srcHdr.Gid = xGID
   207  			}
   208  			if err := createTarFile(path, dest, srcHdr, srcData, true, nil); err != nil {
   209  				return 0, err
   210  			}
   211  
   212  			// Directory mtimes must be handled at the end to avoid further
   213  			// file creation in them to modify the directory mtime
   214  			if hdr.Typeflag == tar.TypeDir {
   215  				dirs = append(dirs, hdr)
   216  			}
   217  		}
   218  	}
   219  
   220  	for _, hdr := range dirs {
   221  		path := filepath.Join(dest, hdr.Name)
   222  		if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil {
   223  			return 0, err
   224  		}
   225  	}
   226  
   227  	return size, nil
   228  }
   229  
   230  // ApplyLayer parses a diff in the standard layer format from `layer`,
   231  // and applies it to the directory `dest`. The stream `layer` can be
   232  // compressed or uncompressed.
   233  // Returns the size in bytes of the contents of the layer.
   234  func ApplyLayer(dest string, layer Reader) (int64, error) {
   235  	return applyLayerHandler(dest, layer, &TarOptions{}, true)
   236  }
   237  
   238  // ApplyUncompressedLayer parses a diff in the standard layer format from
   239  // `layer`, and applies it to the directory `dest`. The stream `layer`
   240  // can only be uncompressed.
   241  // Returns the size in bytes of the contents of the layer.
   242  func ApplyUncompressedLayer(dest string, layer Reader, options *TarOptions) (int64, error) {
   243  	return applyLayerHandler(dest, layer, options, false)
   244  }
   245  
   246  // do the bulk load of ApplyLayer, but allow for not calling DecompressStream
   247  func applyLayerHandler(dest string, layer Reader, options *TarOptions, decompress bool) (int64, error) {
   248  	dest = filepath.Clean(dest)
   249  
   250  	// We need to be able to set any perms
   251  	oldmask, err := system.Umask(0)
   252  	if err != nil {
   253  		return 0, err
   254  	}
   255  	defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform
   256  
   257  	if decompress {
   258  		layer, err = DecompressStream(layer)
   259  		if err != nil {
   260  			return 0, err
   261  		}
   262  	}
   263  	return UnpackLayer(dest, layer, options)
   264  }