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