github.com/titanous/docker@v1.4.1/pkg/archive/archive.go (about)

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