github.com/mheon/docker@v0.11.2-0.20150922122814-44f47903a831/pkg/archive/archive.go (about)

     1  package archive
     2  
     3  import (
     4  	"archive/tar"
     5  	"bufio"
     6  	"bytes"
     7  	"compress/bzip2"
     8  	"compress/gzip"
     9  	"errors"
    10  	"fmt"
    11  	"io"
    12  	"io/ioutil"
    13  	"os"
    14  	"os/exec"
    15  	"path/filepath"
    16  	"runtime"
    17  	"strings"
    18  	"syscall"
    19  
    20  	"github.com/Sirupsen/logrus"
    21  	"github.com/docker/docker/pkg/fileutils"
    22  	"github.com/docker/docker/pkg/pools"
    23  	"github.com/docker/docker/pkg/promise"
    24  	"github.com/docker/docker/pkg/system"
    25  )
    26  
    27  type (
    28  	// Archive is a type of io.ReadCloser which has two interfaces Read and Closer.
    29  	Archive io.ReadCloser
    30  	// Reader is a type of io.Reader.
    31  	Reader io.Reader
    32  	// Compression is the state represtents if compressed or not.
    33  	Compression int
    34  	// TarChownOptions wraps the chown options UID and GID.
    35  	TarChownOptions struct {
    36  		UID, GID int
    37  	}
    38  	// TarOptions wraps the tar options.
    39  	TarOptions struct {
    40  		IncludeFiles     []string
    41  		ExcludePatterns  []string
    42  		Compression      Compression
    43  		NoLchown         bool
    44  		ChownOpts        *TarChownOptions
    45  		IncludeSourceDir bool
    46  		// When unpacking, specifies whether overwriting a directory with a
    47  		// non-directory is allowed and vice versa.
    48  		NoOverwriteDirNonDir bool
    49  		// For each include when creating an archive, the included name will be
    50  		// replaced with the matching name from this map.
    51  		RebaseNames map[string]string
    52  	}
    53  
    54  	// Archiver allows the reuse of most utility functions of this package
    55  	// with a pluggable Untar function.
    56  	Archiver struct {
    57  		Untar func(io.Reader, string, *TarOptions) error
    58  	}
    59  
    60  	// breakoutError is used to differentiate errors related to breaking out
    61  	// When testing archive breakout in the unit tests, this error is expected
    62  	// in order for the test to pass.
    63  	breakoutError error
    64  )
    65  
    66  var (
    67  	// ErrNotImplemented is the error message of function not implemented.
    68  	ErrNotImplemented = errors.New("Function not implemented")
    69  	defaultArchiver   = &Archiver{Untar}
    70  )
    71  
    72  const (
    73  	// Uncompressed represents the uncompressed.
    74  	Uncompressed Compression = iota
    75  	// Bzip2 is bzip2 compression algorithm.
    76  	Bzip2
    77  	// Gzip is gzip compression algorithm.
    78  	Gzip
    79  	// Xz is xz compression algorithm.
    80  	Xz
    81  )
    82  
    83  // IsArchive checks if it is a archive by the header.
    84  func IsArchive(header []byte) bool {
    85  	compression := DetectCompression(header)
    86  	if compression != Uncompressed {
    87  		return true
    88  	}
    89  	r := tar.NewReader(bytes.NewBuffer(header))
    90  	_, err := r.Next()
    91  	return err == nil
    92  }
    93  
    94  // DetectCompression detects the compression algorithm of the source.
    95  func DetectCompression(source []byte) Compression {
    96  	for compression, m := range map[Compression][]byte{
    97  		Bzip2: {0x42, 0x5A, 0x68},
    98  		Gzip:  {0x1F, 0x8B, 0x08},
    99  		Xz:    {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
   100  	} {
   101  		if len(source) < len(m) {
   102  			logrus.Debugf("Len too short")
   103  			continue
   104  		}
   105  		if bytes.Compare(m, source[:len(m)]) == 0 {
   106  			return compression
   107  		}
   108  	}
   109  	return Uncompressed
   110  }
   111  
   112  func xzDecompress(archive io.Reader) (io.ReadCloser, error) {
   113  	args := []string{"xz", "-d", "-c", "-q"}
   114  
   115  	return CmdStream(exec.Command(args[0], args[1:]...), archive)
   116  }
   117  
   118  // DecompressStream decompress the archive and returns a ReaderCloser with the decompressed archive.
   119  func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
   120  	p := pools.BufioReader32KPool
   121  	buf := p.Get(archive)
   122  	bs, err := buf.Peek(10)
   123  	if err != nil {
   124  		return nil, err
   125  	}
   126  
   127  	compression := DetectCompression(bs)
   128  	switch compression {
   129  	case Uncompressed:
   130  		readBufWrapper := p.NewReadCloserWrapper(buf, buf)
   131  		return readBufWrapper, nil
   132  	case Gzip:
   133  		gzReader, err := gzip.NewReader(buf)
   134  		if err != nil {
   135  			return nil, err
   136  		}
   137  		readBufWrapper := p.NewReadCloserWrapper(buf, gzReader)
   138  		return readBufWrapper, nil
   139  	case Bzip2:
   140  		bz2Reader := bzip2.NewReader(buf)
   141  		readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader)
   142  		return readBufWrapper, nil
   143  	case Xz:
   144  		xzReader, err := xzDecompress(buf)
   145  		if err != nil {
   146  			return nil, err
   147  		}
   148  		readBufWrapper := p.NewReadCloserWrapper(buf, xzReader)
   149  		return readBufWrapper, nil
   150  	default:
   151  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   152  	}
   153  }
   154  
   155  // CompressStream compresses the dest with specified compression algorithm.
   156  func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) {
   157  	p := pools.BufioWriter32KPool
   158  	buf := p.Get(dest)
   159  	switch compression {
   160  	case Uncompressed:
   161  		writeBufWrapper := p.NewWriteCloserWrapper(buf, buf)
   162  		return writeBufWrapper, nil
   163  	case Gzip:
   164  		gzWriter := gzip.NewWriter(dest)
   165  		writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter)
   166  		return writeBufWrapper, nil
   167  	case Bzip2, Xz:
   168  		// archive/bzip2 does not support writing, and there is no xz support at all
   169  		// However, this is not a problem as docker only currently generates gzipped tars
   170  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   171  	default:
   172  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   173  	}
   174  }
   175  
   176  // Extension returns the extension of a file that uses the specified compression algorithm.
   177  func (compression *Compression) Extension() string {
   178  	switch *compression {
   179  	case Uncompressed:
   180  		return "tar"
   181  	case Bzip2:
   182  		return "tar.bz2"
   183  	case Gzip:
   184  		return "tar.gz"
   185  	case Xz:
   186  		return "tar.xz"
   187  	}
   188  	return ""
   189  }
   190  
   191  type tarAppender struct {
   192  	TarWriter *tar.Writer
   193  	Buffer    *bufio.Writer
   194  
   195  	// for hardlink mapping
   196  	SeenFiles map[uint64]string
   197  }
   198  
   199  // canonicalTarName provides a platform-independent and consistent posix-style
   200  //path for files and directories to be archived regardless of the platform.
   201  func canonicalTarName(name string, isDir bool) (string, error) {
   202  	name, err := CanonicalTarNameForPath(name)
   203  	if err != nil {
   204  		return "", err
   205  	}
   206  
   207  	// suffix with '/' for directories
   208  	if isDir && !strings.HasSuffix(name, "/") {
   209  		name += "/"
   210  	}
   211  	return name, nil
   212  }
   213  
   214  func (ta *tarAppender) addTarFile(path, name string) error {
   215  	fi, err := os.Lstat(path)
   216  	if err != nil {
   217  		return err
   218  	}
   219  
   220  	link := ""
   221  	if fi.Mode()&os.ModeSymlink != 0 {
   222  		if link, err = os.Readlink(path); err != nil {
   223  			return err
   224  		}
   225  	}
   226  
   227  	hdr, err := tar.FileInfoHeader(fi, link)
   228  	if err != nil {
   229  		return err
   230  	}
   231  	hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
   232  
   233  	name, err = canonicalTarName(name, fi.IsDir())
   234  	if err != nil {
   235  		return fmt.Errorf("tar: cannot canonicalize path: %v", err)
   236  	}
   237  	hdr.Name = name
   238  
   239  	nlink, inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys())
   240  	if err != nil {
   241  		return err
   242  	}
   243  
   244  	// if it's a regular file and has more than 1 link,
   245  	// it's hardlinked, so set the type flag accordingly
   246  	if fi.Mode().IsRegular() && nlink > 1 {
   247  		// a link should have a name that it links too
   248  		// and that linked name should be first in the tar archive
   249  		if oldpath, ok := ta.SeenFiles[inode]; ok {
   250  			hdr.Typeflag = tar.TypeLink
   251  			hdr.Linkname = oldpath
   252  			hdr.Size = 0 // This Must be here for the writer math to add up!
   253  		} else {
   254  			ta.SeenFiles[inode] = name
   255  		}
   256  	}
   257  
   258  	capability, _ := system.Lgetxattr(path, "security.capability")
   259  	if capability != nil {
   260  		hdr.Xattrs = make(map[string]string)
   261  		hdr.Xattrs["security.capability"] = string(capability)
   262  	}
   263  
   264  	if err := ta.TarWriter.WriteHeader(hdr); err != nil {
   265  		return err
   266  	}
   267  
   268  	if hdr.Typeflag == tar.TypeReg {
   269  		file, err := os.Open(path)
   270  		if err != nil {
   271  			return err
   272  		}
   273  
   274  		ta.Buffer.Reset(ta.TarWriter)
   275  		defer ta.Buffer.Reset(nil)
   276  		_, err = io.Copy(ta.Buffer, file)
   277  		file.Close()
   278  		if err != nil {
   279  			return err
   280  		}
   281  		err = ta.Buffer.Flush()
   282  		if err != nil {
   283  			return err
   284  		}
   285  	}
   286  
   287  	return nil
   288  }
   289  
   290  func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions) error {
   291  	// hdr.Mode is in linux format, which we can use for sycalls,
   292  	// but for os.Foo() calls we need the mode converted to os.FileMode,
   293  	// so use hdrInfo.Mode() (they differ for e.g. setuid bits)
   294  	hdrInfo := hdr.FileInfo()
   295  
   296  	switch hdr.Typeflag {
   297  	case tar.TypeDir:
   298  		// Create directory unless it exists as a directory already.
   299  		// In that case we just want to merge the two
   300  		if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
   301  			if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
   302  				return err
   303  			}
   304  		}
   305  
   306  	case tar.TypeReg, tar.TypeRegA:
   307  		// Source is regular file
   308  		file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
   309  		if err != nil {
   310  			return err
   311  		}
   312  		if _, err := io.Copy(file, reader); err != nil {
   313  			file.Close()
   314  			return err
   315  		}
   316  		file.Close()
   317  
   318  	case tar.TypeBlock, tar.TypeChar, tar.TypeFifo:
   319  		// Handle this is an OS-specific way
   320  		if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
   321  			return err
   322  		}
   323  
   324  	case tar.TypeLink:
   325  		targetPath := filepath.Join(extractDir, hdr.Linkname)
   326  		// check for hardlink breakout
   327  		if !strings.HasPrefix(targetPath, extractDir) {
   328  			return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname))
   329  		}
   330  		if err := os.Link(targetPath, path); err != nil {
   331  			return err
   332  		}
   333  
   334  	case tar.TypeSymlink:
   335  		// 	path 				-> hdr.Linkname = targetPath
   336  		// e.g. /extractDir/path/to/symlink 	-> ../2/file	= /extractDir/path/2/file
   337  		targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname)
   338  
   339  		// the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because
   340  		// that symlink would first have to be created, which would be caught earlier, at this very check:
   341  		if !strings.HasPrefix(targetPath, extractDir) {
   342  			return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname))
   343  		}
   344  		if err := os.Symlink(hdr.Linkname, path); err != nil {
   345  			return err
   346  		}
   347  
   348  	case tar.TypeXGlobalHeader:
   349  		logrus.Debugf("PAX Global Extended Headers found and ignored")
   350  		return nil
   351  
   352  	default:
   353  		return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag)
   354  	}
   355  
   356  	// Lchown is not supported on Windows.
   357  	if Lchown && runtime.GOOS != "windows" {
   358  		if chownOpts == nil {
   359  			chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid}
   360  		}
   361  		if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil {
   362  			return err
   363  		}
   364  	}
   365  
   366  	for key, value := range hdr.Xattrs {
   367  		if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil {
   368  			return err
   369  		}
   370  	}
   371  
   372  	// There is no LChmod, so ignore mode for symlink. Also, this
   373  	// must happen after chown, as that can modify the file mode
   374  	if err := handleLChmod(hdr, path, hdrInfo); err != nil {
   375  		return err
   376  	}
   377  
   378  	ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
   379  	// syscall.UtimesNano doesn't support a NOFOLLOW flag atm
   380  	if hdr.Typeflag == tar.TypeLink {
   381  		if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) {
   382  			if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
   383  				return err
   384  			}
   385  		}
   386  	} else if hdr.Typeflag != tar.TypeSymlink {
   387  		if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
   388  			return err
   389  		}
   390  	} else {
   391  		if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
   392  			return err
   393  		}
   394  	}
   395  	return nil
   396  }
   397  
   398  // Tar creates an archive from the directory at `path`, and returns it as a
   399  // stream of bytes.
   400  func Tar(path string, compression Compression) (io.ReadCloser, error) {
   401  	return TarWithOptions(path, &TarOptions{Compression: compression})
   402  }
   403  
   404  // TarWithOptions creates an archive from the directory at `path`, only including files whose relative
   405  // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`.
   406  func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) {
   407  
   408  	// Fix the source path to work with long path names. This is a no-op
   409  	// on platforms other than Windows.
   410  	srcPath = fixVolumePathPrefix(srcPath)
   411  
   412  	patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns)
   413  
   414  	if err != nil {
   415  		return nil, err
   416  	}
   417  
   418  	pipeReader, pipeWriter := io.Pipe()
   419  
   420  	compressWriter, err := CompressStream(pipeWriter, options.Compression)
   421  	if err != nil {
   422  		return nil, err
   423  	}
   424  
   425  	go func() {
   426  		ta := &tarAppender{
   427  			TarWriter: tar.NewWriter(compressWriter),
   428  			Buffer:    pools.BufioWriter32KPool.Get(nil),
   429  			SeenFiles: make(map[uint64]string),
   430  		}
   431  
   432  		defer func() {
   433  			// Make sure to check the error on Close.
   434  			if err := ta.TarWriter.Close(); err != nil {
   435  				logrus.Debugf("Can't close tar writer: %s", err)
   436  			}
   437  			if err := compressWriter.Close(); err != nil {
   438  				logrus.Debugf("Can't close compress writer: %s", err)
   439  			}
   440  			if err := pipeWriter.Close(); err != nil {
   441  				logrus.Debugf("Can't close pipe writer: %s", err)
   442  			}
   443  		}()
   444  
   445  		// this buffer is needed for the duration of this piped stream
   446  		defer pools.BufioWriter32KPool.Put(ta.Buffer)
   447  
   448  		// In general we log errors here but ignore them because
   449  		// during e.g. a diff operation the container can continue
   450  		// mutating the filesystem and we can see transient errors
   451  		// from this
   452  
   453  		stat, err := os.Lstat(srcPath)
   454  		if err != nil {
   455  			return
   456  		}
   457  
   458  		if !stat.IsDir() {
   459  			// We can't later join a non-dir with any includes because the
   460  			// 'walk' will error if "file/." is stat-ed and "file" is not a
   461  			// directory. So, we must split the source path and use the
   462  			// basename as the include.
   463  			if len(options.IncludeFiles) > 0 {
   464  				logrus.Warn("Tar: Can't archive a file with includes")
   465  			}
   466  
   467  			dir, base := SplitPathDirEntry(srcPath)
   468  			srcPath = dir
   469  			options.IncludeFiles = []string{base}
   470  		}
   471  
   472  		if len(options.IncludeFiles) == 0 {
   473  			options.IncludeFiles = []string{"."}
   474  		}
   475  
   476  		seen := make(map[string]bool)
   477  
   478  		for _, include := range options.IncludeFiles {
   479  			rebaseName := options.RebaseNames[include]
   480  
   481  			walkRoot := getWalkRoot(srcPath, include)
   482  			filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error {
   483  				if err != nil {
   484  					logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err)
   485  					return nil
   486  				}
   487  
   488  				relFilePath, err := filepath.Rel(srcPath, filePath)
   489  				if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) {
   490  					// Error getting relative path OR we are looking
   491  					// at the source directory path. Skip in both situations.
   492  					return nil
   493  				}
   494  
   495  				if options.IncludeSourceDir && include == "." && relFilePath != "." {
   496  					relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator))
   497  				}
   498  
   499  				skip := false
   500  
   501  				// If "include" is an exact match for the current file
   502  				// then even if there's an "excludePatterns" pattern that
   503  				// matches it, don't skip it. IOW, assume an explicit 'include'
   504  				// is asking for that file no matter what - which is true
   505  				// for some files, like .dockerignore and Dockerfile (sometimes)
   506  				if include != relFilePath {
   507  					skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs)
   508  					if err != nil {
   509  						logrus.Debugf("Error matching %s: %v", relFilePath, err)
   510  						return err
   511  					}
   512  				}
   513  
   514  				if skip {
   515  					if !exceptions && f.IsDir() {
   516  						return filepath.SkipDir
   517  					}
   518  					return nil
   519  				}
   520  
   521  				if seen[relFilePath] {
   522  					return nil
   523  				}
   524  				seen[relFilePath] = true
   525  
   526  				// Rename the base resource.
   527  				if rebaseName != "" {
   528  					var replacement string
   529  					if rebaseName != string(filepath.Separator) {
   530  						// Special case the root directory to replace with an
   531  						// empty string instead so that we don't end up with
   532  						// double slashes in the paths.
   533  						replacement = rebaseName
   534  					}
   535  
   536  					relFilePath = strings.Replace(relFilePath, include, replacement, 1)
   537  				}
   538  
   539  				if err := ta.addTarFile(filePath, relFilePath); err != nil {
   540  					logrus.Debugf("Can't add file %s to tar: %s", filePath, err)
   541  				}
   542  				return nil
   543  			})
   544  		}
   545  	}()
   546  
   547  	return pipeReader, nil
   548  }
   549  
   550  // Unpack unpacks the decompressedArchive to dest with options.
   551  func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error {
   552  	tr := tar.NewReader(decompressedArchive)
   553  	trBuf := pools.BufioReader32KPool.Get(nil)
   554  	defer pools.BufioReader32KPool.Put(trBuf)
   555  
   556  	var dirs []*tar.Header
   557  
   558  	// Iterate through the files in the archive.
   559  loop:
   560  	for {
   561  		hdr, err := tr.Next()
   562  		if err == io.EOF {
   563  			// end of tar archive
   564  			break
   565  		}
   566  		if err != nil {
   567  			return err
   568  		}
   569  
   570  		// Normalize name, for safety and for a simple is-root check
   571  		// This keeps "../" as-is, but normalizes "/../" to "/". Or Windows:
   572  		// This keeps "..\" as-is, but normalizes "\..\" to "\".
   573  		hdr.Name = filepath.Clean(hdr.Name)
   574  
   575  		for _, exclude := range options.ExcludePatterns {
   576  			if strings.HasPrefix(hdr.Name, exclude) {
   577  				continue loop
   578  			}
   579  		}
   580  
   581  		// After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in
   582  		// the filepath format for the OS on which the daemon is running. Hence
   583  		// the check for a slash-suffix MUST be done in an OS-agnostic way.
   584  		if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
   585  			// Not the root directory, ensure that the parent directory exists
   586  			parent := filepath.Dir(hdr.Name)
   587  			parentPath := filepath.Join(dest, parent)
   588  			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
   589  				err = system.MkdirAll(parentPath, 0777)
   590  				if err != nil {
   591  					return err
   592  				}
   593  			}
   594  		}
   595  
   596  		path := filepath.Join(dest, hdr.Name)
   597  		rel, err := filepath.Rel(dest, path)
   598  		if err != nil {
   599  			return err
   600  		}
   601  		if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
   602  			return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
   603  		}
   604  
   605  		// If path exits we almost always just want to remove and replace it
   606  		// The only exception is when it is a directory *and* the file from
   607  		// the layer is also a directory. Then we want to merge them (i.e.
   608  		// just apply the metadata from the layer).
   609  		if fi, err := os.Lstat(path); err == nil {
   610  			if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir {
   611  				// If NoOverwriteDirNonDir is true then we cannot replace
   612  				// an existing directory with a non-directory from the archive.
   613  				return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest)
   614  			}
   615  
   616  			if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir {
   617  				// If NoOverwriteDirNonDir is true then we cannot replace
   618  				// an existing non-directory with a directory from the archive.
   619  				return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest)
   620  			}
   621  
   622  			if fi.IsDir() && hdr.Name == "." {
   623  				continue
   624  			}
   625  
   626  			if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
   627  				if err := os.RemoveAll(path); err != nil {
   628  					return err
   629  				}
   630  			}
   631  		}
   632  		trBuf.Reset(tr)
   633  
   634  		if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts); err != nil {
   635  			return err
   636  		}
   637  
   638  		// Directory mtimes must be handled at the end to avoid further
   639  		// file creation in them to modify the directory mtime
   640  		if hdr.Typeflag == tar.TypeDir {
   641  			dirs = append(dirs, hdr)
   642  		}
   643  	}
   644  
   645  	for _, hdr := range dirs {
   646  		path := filepath.Join(dest, hdr.Name)
   647  		ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
   648  		if err := syscall.UtimesNano(path, ts); err != nil {
   649  			return err
   650  		}
   651  	}
   652  	return nil
   653  }
   654  
   655  // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
   656  // and unpacks it into the directory at `dest`.
   657  // The archive may be compressed with one of the following algorithms:
   658  //  identity (uncompressed), gzip, bzip2, xz.
   659  // FIXME: specify behavior when target path exists vs. doesn't exist.
   660  func Untar(tarArchive io.Reader, dest string, options *TarOptions) error {
   661  	return untarHandler(tarArchive, dest, options, true)
   662  }
   663  
   664  // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive,
   665  // and unpacks it into the directory at `dest`.
   666  // The archive must be an uncompressed stream.
   667  func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error {
   668  	return untarHandler(tarArchive, dest, options, false)
   669  }
   670  
   671  // Handler for teasing out the automatic decompression
   672  func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error {
   673  	if tarArchive == nil {
   674  		return fmt.Errorf("Empty archive")
   675  	}
   676  	dest = filepath.Clean(dest)
   677  	if options == nil {
   678  		options = &TarOptions{}
   679  	}
   680  	if options.ExcludePatterns == nil {
   681  		options.ExcludePatterns = []string{}
   682  	}
   683  
   684  	r := tarArchive
   685  	if decompress {
   686  		decompressedArchive, err := DecompressStream(tarArchive)
   687  		if err != nil {
   688  			return err
   689  		}
   690  		defer decompressedArchive.Close()
   691  		r = decompressedArchive
   692  	}
   693  
   694  	return Unpack(r, dest, options)
   695  }
   696  
   697  // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
   698  // If either Tar or Untar fails, TarUntar aborts and returns the error.
   699  func (archiver *Archiver) TarUntar(src, dst string) error {
   700  	logrus.Debugf("TarUntar(%s %s)", src, dst)
   701  	archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
   702  	if err != nil {
   703  		return err
   704  	}
   705  	defer archive.Close()
   706  	return archiver.Untar(archive, dst, nil)
   707  }
   708  
   709  // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
   710  // If either Tar or Untar fails, TarUntar aborts and returns the error.
   711  func TarUntar(src, dst string) error {
   712  	return defaultArchiver.TarUntar(src, dst)
   713  }
   714  
   715  // UntarPath untar a file from path to a destination, src is the source tar file path.
   716  func (archiver *Archiver) UntarPath(src, dst string) error {
   717  	archive, err := os.Open(src)
   718  	if err != nil {
   719  		return err
   720  	}
   721  	defer archive.Close()
   722  	if err := archiver.Untar(archive, dst, nil); err != nil {
   723  		return err
   724  	}
   725  	return nil
   726  }
   727  
   728  // UntarPath is a convenience function which looks for an archive
   729  // at filesystem path `src`, and unpacks it at `dst`.
   730  func UntarPath(src, dst string) error {
   731  	return defaultArchiver.UntarPath(src, dst)
   732  }
   733  
   734  // CopyWithTar creates a tar archive of filesystem path `src`, and
   735  // unpacks it at filesystem path `dst`.
   736  // The archive is streamed directly with fixed buffering and no
   737  // intermediary disk IO.
   738  func (archiver *Archiver) CopyWithTar(src, dst string) error {
   739  	srcSt, err := os.Stat(src)
   740  	if err != nil {
   741  		return err
   742  	}
   743  	if !srcSt.IsDir() {
   744  		return archiver.CopyFileWithTar(src, dst)
   745  	}
   746  	// Create dst, copy src's content into it
   747  	logrus.Debugf("Creating dest directory: %s", dst)
   748  	if err := system.MkdirAll(dst, 0755); err != nil {
   749  		return err
   750  	}
   751  	logrus.Debugf("Calling TarUntar(%s, %s)", src, dst)
   752  	return archiver.TarUntar(src, dst)
   753  }
   754  
   755  // CopyWithTar creates a tar archive of filesystem path `src`, and
   756  // unpacks it at filesystem path `dst`.
   757  // The archive is streamed directly with fixed buffering and no
   758  // intermediary disk IO.
   759  func CopyWithTar(src, dst string) error {
   760  	return defaultArchiver.CopyWithTar(src, dst)
   761  }
   762  
   763  // CopyFileWithTar emulates the behavior of the 'cp' command-line
   764  // for a single file. It copies a regular file from path `src` to
   765  // path `dst`, and preserves all its metadata.
   766  func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
   767  	logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst)
   768  	srcSt, err := os.Stat(src)
   769  	if err != nil {
   770  		return err
   771  	}
   772  
   773  	if srcSt.IsDir() {
   774  		return fmt.Errorf("Can't copy a directory")
   775  	}
   776  
   777  	// Clean up the trailing slash. This must be done in an operating
   778  	// system specific manner.
   779  	if dst[len(dst)-1] == os.PathSeparator {
   780  		dst = filepath.Join(dst, filepath.Base(src))
   781  	}
   782  	// Create the holding directory if necessary
   783  	if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil {
   784  		return err
   785  	}
   786  
   787  	r, w := io.Pipe()
   788  	errC := promise.Go(func() error {
   789  		defer w.Close()
   790  
   791  		srcF, err := os.Open(src)
   792  		if err != nil {
   793  			return err
   794  		}
   795  		defer srcF.Close()
   796  
   797  		hdr, err := tar.FileInfoHeader(srcSt, "")
   798  		if err != nil {
   799  			return err
   800  		}
   801  		hdr.Name = filepath.Base(dst)
   802  		hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
   803  
   804  		tw := tar.NewWriter(w)
   805  		defer tw.Close()
   806  		if err := tw.WriteHeader(hdr); err != nil {
   807  			return err
   808  		}
   809  		if _, err := io.Copy(tw, srcF); err != nil {
   810  			return err
   811  		}
   812  		return nil
   813  	})
   814  	defer func() {
   815  		if er := <-errC; err != nil {
   816  			err = er
   817  		}
   818  	}()
   819  	return archiver.Untar(r, filepath.Dir(dst), nil)
   820  }
   821  
   822  // CopyFileWithTar emulates the behavior of the 'cp' command-line
   823  // for a single file. It copies a regular file from path `src` to
   824  // path `dst`, and preserves all its metadata.
   825  //
   826  // Destination handling is in an operating specific manner depending
   827  // where the daemon is running. If `dst` ends with a trailing slash
   828  // the final destination path will be `dst/base(src)`  (Linux) or
   829  // `dst\base(src)` (Windows).
   830  func CopyFileWithTar(src, dst string) (err error) {
   831  	return defaultArchiver.CopyFileWithTar(src, dst)
   832  }
   833  
   834  // CmdStream executes a command, and returns its stdout as a stream.
   835  // If the command fails to run or doesn't complete successfully, an error
   836  // will be returned, including anything written on stderr.
   837  func CmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
   838  	if input != nil {
   839  		stdin, err := cmd.StdinPipe()
   840  		if err != nil {
   841  			return nil, err
   842  		}
   843  		// Write stdin if any
   844  		go func() {
   845  			io.Copy(stdin, input)
   846  			stdin.Close()
   847  		}()
   848  	}
   849  	stdout, err := cmd.StdoutPipe()
   850  	if err != nil {
   851  		return nil, err
   852  	}
   853  	stderr, err := cmd.StderrPipe()
   854  	if err != nil {
   855  		return nil, err
   856  	}
   857  	pipeR, pipeW := io.Pipe()
   858  	errChan := make(chan []byte)
   859  	// Collect stderr, we will use it in case of an error
   860  	go func() {
   861  		errText, e := ioutil.ReadAll(stderr)
   862  		if e != nil {
   863  			errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
   864  		}
   865  		errChan <- errText
   866  	}()
   867  	// Copy stdout to the returned pipe
   868  	go func() {
   869  		_, err := io.Copy(pipeW, stdout)
   870  		if err != nil {
   871  			pipeW.CloseWithError(err)
   872  		}
   873  		errText := <-errChan
   874  		if err := cmd.Wait(); err != nil {
   875  			pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errText))
   876  		} else {
   877  			pipeW.Close()
   878  		}
   879  	}()
   880  	// Run the command and return the pipe
   881  	if err := cmd.Start(); err != nil {
   882  		return nil, err
   883  	}
   884  	return pipeR, nil
   885  }
   886  
   887  // NewTempArchive reads the content of src into a temporary file, and returns the contents
   888  // of that file as an archive. The archive can only be read once - as soon as reading completes,
   889  // the file will be deleted.
   890  func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
   891  	f, err := ioutil.TempFile(dir, "")
   892  	if err != nil {
   893  		return nil, err
   894  	}
   895  	if _, err := io.Copy(f, src); err != nil {
   896  		return nil, err
   897  	}
   898  	if _, err := f.Seek(0, 0); err != nil {
   899  		return nil, err
   900  	}
   901  	st, err := f.Stat()
   902  	if err != nil {
   903  		return nil, err
   904  	}
   905  	size := st.Size()
   906  	return &TempArchive{File: f, Size: size}, nil
   907  }
   908  
   909  // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes,
   910  // the file will be deleted.
   911  type TempArchive struct {
   912  	*os.File
   913  	Size   int64 // Pre-computed from Stat().Size() as a convenience
   914  	read   int64
   915  	closed bool
   916  }
   917  
   918  // Close closes the underlying file if it's still open, or does a no-op
   919  // to allow callers to try to close the TempArchive multiple times safely.
   920  func (archive *TempArchive) Close() error {
   921  	if archive.closed {
   922  		return nil
   923  	}
   924  
   925  	archive.closed = true
   926  
   927  	return archive.File.Close()
   928  }
   929  
   930  func (archive *TempArchive) Read(data []byte) (int, error) {
   931  	n, err := archive.File.Read(data)
   932  	archive.read += int64(n)
   933  	if err != nil || archive.read == archive.Size {
   934  		archive.Close()
   935  		os.Remove(archive.File.Name())
   936  	}
   937  	return n, err
   938  }