github.com/rentongzhang/docker@v1.8.2-rc1/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  	"syscall"
    13  
    14  	"github.com/Sirupsen/logrus"
    15  	"github.com/docker/docker/pkg/pools"
    16  	"github.com/docker/docker/pkg/system"
    17  )
    18  
    19  func UnpackLayer(dest string, layer ArchiveReader) (size int64, err error) {
    20  	tr := tar.NewReader(layer)
    21  	trBuf := pools.BufioReader32KPool.Get(tr)
    22  	defer pools.BufioReader32KPool.Put(trBuf)
    23  
    24  	var dirs []*tar.Header
    25  
    26  	aufsTempdir := ""
    27  	aufsHardlinks := make(map[string]*tar.Header)
    28  
    29  	// Iterate through the files in the archive.
    30  	for {
    31  		hdr, err := tr.Next()
    32  		if err == io.EOF {
    33  			// end of tar archive
    34  			break
    35  		}
    36  		if err != nil {
    37  			return 0, err
    38  		}
    39  
    40  		size += hdr.Size
    41  
    42  		// Normalize name, for safety and for a simple is-root check
    43  		hdr.Name = filepath.Clean(hdr.Name)
    44  
    45  		// Windows does not support filenames with colons in them. Ignore
    46  		// these files. This is not a problem though (although it might
    47  		// appear that it is). Let's suppose a client is running docker pull.
    48  		// The daemon it points to is Windows. Would it make sense for the
    49  		// client to be doing a docker pull Ubuntu for example (which has files
    50  		// with colons in the name under /usr/share/man/man3)? No, absolutely
    51  		// not as it would really only make sense that they were pulling a
    52  		// Windows image. However, for development, it is necessary to be able
    53  		// to pull Linux images which are in the repository.
    54  		//
    55  		// TODO Windows. Once the registry is aware of what images are Windows-
    56  		// specific or Linux-specific, this warning should be changed to an error
    57  		// to cater for the situation where someone does manage to upload a Linux
    58  		// image but have it tagged as Windows inadvertantly.
    59  		if runtime.GOOS == "windows" {
    60  			if strings.Contains(hdr.Name, ":") {
    61  				logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name)
    62  				continue
    63  			}
    64  		}
    65  
    66  		// Note as these operations are platform specific, so must the slash be.
    67  		if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
    68  			// Not the root directory, ensure that the parent directory exists.
    69  			// This happened in some tests where an image had a tarfile without any
    70  			// parent directories.
    71  			parent := filepath.Dir(hdr.Name)
    72  			parentPath := filepath.Join(dest, parent)
    73  
    74  			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
    75  				err = system.MkdirAll(parentPath, 0600)
    76  				if err != nil {
    77  					return 0, err
    78  				}
    79  			}
    80  		}
    81  
    82  		// Skip AUFS metadata dirs
    83  		if strings.HasPrefix(hdr.Name, ".wh..wh.") {
    84  			// Regular files inside /.wh..wh.plnk can be used as hardlink targets
    85  			// We don't want this directory, but we need the files in them so that
    86  			// such hardlinks can be resolved.
    87  			if strings.HasPrefix(hdr.Name, ".wh..wh.plnk") && hdr.Typeflag == tar.TypeReg {
    88  				basename := filepath.Base(hdr.Name)
    89  				aufsHardlinks[basename] = hdr
    90  				if aufsTempdir == "" {
    91  					if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil {
    92  						return 0, err
    93  					}
    94  					defer os.RemoveAll(aufsTempdir)
    95  				}
    96  				if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil); err != nil {
    97  					return 0, err
    98  				}
    99  			}
   100  			continue
   101  		}
   102  		path := filepath.Join(dest, hdr.Name)
   103  		rel, err := filepath.Rel(dest, path)
   104  		if err != nil {
   105  			return 0, err
   106  		}
   107  
   108  		// Note as these operations are platform specific, so must the slash be.
   109  		if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
   110  			return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
   111  		}
   112  		base := filepath.Base(path)
   113  
   114  		if strings.HasPrefix(base, ".wh.") {
   115  			originalBase := base[len(".wh."):]
   116  			originalPath := filepath.Join(filepath.Dir(path), originalBase)
   117  			if err := os.RemoveAll(originalPath); err != nil {
   118  				return 0, err
   119  			}
   120  		} else {
   121  			// If path exits we almost always just want to remove and replace it.
   122  			// The only exception is when it is a directory *and* the file from
   123  			// the layer is also a directory. Then we want to merge them (i.e.
   124  			// just apply the metadata from the layer).
   125  			if fi, err := os.Lstat(path); err == nil {
   126  				if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
   127  					if err := os.RemoveAll(path); err != nil {
   128  						return 0, err
   129  					}
   130  				}
   131  			}
   132  
   133  			trBuf.Reset(tr)
   134  			srcData := io.Reader(trBuf)
   135  			srcHdr := hdr
   136  
   137  			// Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
   138  			// we manually retarget these into the temporary files we extracted them into
   139  			if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), ".wh..wh.plnk") {
   140  				linkBasename := filepath.Base(hdr.Linkname)
   141  				srcHdr = aufsHardlinks[linkBasename]
   142  				if srcHdr == nil {
   143  					return 0, fmt.Errorf("Invalid aufs hardlink")
   144  				}
   145  				tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename))
   146  				if err != nil {
   147  					return 0, err
   148  				}
   149  				defer tmpFile.Close()
   150  				srcData = tmpFile
   151  			}
   152  
   153  			if err := createTarFile(path, dest, srcHdr, srcData, true, nil); err != nil {
   154  				return 0, err
   155  			}
   156  
   157  			// Directory mtimes must be handled at the end to avoid further
   158  			// file creation in them to modify the directory mtime
   159  			if hdr.Typeflag == tar.TypeDir {
   160  				dirs = append(dirs, hdr)
   161  			}
   162  		}
   163  	}
   164  
   165  	for _, hdr := range dirs {
   166  		path := filepath.Join(dest, hdr.Name)
   167  		ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
   168  		if err := syscall.UtimesNano(path, ts); err != nil {
   169  			return 0, err
   170  		}
   171  	}
   172  
   173  	return size, nil
   174  }
   175  
   176  // ApplyLayer parses a diff in the standard layer format from `layer`,
   177  // and applies it to the directory `dest`. The stream `layer` can be
   178  // compressed or uncompressed.
   179  // Returns the size in bytes of the contents of the layer.
   180  func ApplyLayer(dest string, layer ArchiveReader) (int64, error) {
   181  	return applyLayerHandler(dest, layer, true)
   182  }
   183  
   184  // ApplyUncompressedLayer parses a diff in the standard layer format from
   185  // `layer`, and applies it to the directory `dest`. The stream `layer`
   186  // can only be uncompressed.
   187  // Returns the size in bytes of the contents of the layer.
   188  func ApplyUncompressedLayer(dest string, layer ArchiveReader) (int64, error) {
   189  	return applyLayerHandler(dest, layer, false)
   190  }
   191  
   192  // do the bulk load of ApplyLayer, but allow for not calling DecompressStream
   193  func applyLayerHandler(dest string, layer ArchiveReader, decompress bool) (int64, error) {
   194  	dest = filepath.Clean(dest)
   195  
   196  	// We need to be able to set any perms
   197  	oldmask, err := system.Umask(0)
   198  	if err != nil {
   199  		return 0, err
   200  	}
   201  	defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform
   202  
   203  	if decompress {
   204  		layer, err = DecompressStream(layer)
   205  		if err != nil {
   206  			return 0, err
   207  		}
   208  	}
   209  	return UnpackLayer(dest, layer)
   210  }