github.com/pritambaral/docker@v1.4.2-0.20150120174542-b2fe1b3dd952/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  	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.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`.
   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.IncludeFiles == nil {
   405  			options.IncludeFiles = []string{"."}
   406  		}
   407  
   408  		seen := make(map[string]bool)
   409  
   410  		var renamedRelFilePath string // For when tar.Options.Name is set
   411  		for _, include := range options.IncludeFiles {
   412  			filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error {
   413  				if err != nil {
   414  					log.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err)
   415  					return nil
   416  				}
   417  
   418  				relFilePath, err := filepath.Rel(srcPath, filePath)
   419  				if err != nil || (relFilePath == "." && f.IsDir()) {
   420  					// Error getting relative path OR we are looking
   421  					// at the root path. Skip in both situations.
   422  					return nil
   423  				}
   424  
   425  				skip := false
   426  
   427  				// If "include" is an exact match for the current file
   428  				// then even if there's an "excludePatterns" pattern that
   429  				// matches it, don't skip it. IOW, assume an explicit 'include'
   430  				// is asking for that file no matter what - which is true
   431  				// for some files, like .dockerignore and Dockerfile (sometimes)
   432  				if include != relFilePath {
   433  					skip, err = fileutils.Matches(relFilePath, options.ExcludePatterns)
   434  					if err != nil {
   435  						log.Debugf("Error matching %s", relFilePath, err)
   436  						return err
   437  					}
   438  				}
   439  
   440  				if skip {
   441  					if f.IsDir() {
   442  						return filepath.SkipDir
   443  					}
   444  					return nil
   445  				}
   446  
   447  				if seen[relFilePath] {
   448  					return nil
   449  				}
   450  				seen[relFilePath] = true
   451  
   452  				// Rename the base resource
   453  				if options.Name != "" && filePath == srcPath+"/"+filepath.Base(relFilePath) {
   454  					renamedRelFilePath = relFilePath
   455  				}
   456  				// Set this to make sure the items underneath also get renamed
   457  				if options.Name != "" {
   458  					relFilePath = strings.Replace(relFilePath, renamedRelFilePath, options.Name, 1)
   459  				}
   460  
   461  				if err := ta.addTarFile(filePath, relFilePath); err != nil {
   462  					log.Debugf("Can't add file %s to tar: %s", srcPath, err)
   463  				}
   464  				return nil
   465  			})
   466  		}
   467  
   468  		// Make sure to check the error on Close.
   469  		if err := ta.TarWriter.Close(); err != nil {
   470  			log.Debugf("Can't close tar writer: %s", err)
   471  		}
   472  		if err := compressWriter.Close(); err != nil {
   473  			log.Debugf("Can't close compress writer: %s", err)
   474  		}
   475  		if err := pipeWriter.Close(); err != nil {
   476  			log.Debugf("Can't close pipe writer: %s", err)
   477  		}
   478  	}()
   479  
   480  	return pipeReader, nil
   481  }
   482  
   483  func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error {
   484  	tr := tar.NewReader(decompressedArchive)
   485  	trBuf := pools.BufioReader32KPool.Get(nil)
   486  	defer pools.BufioReader32KPool.Put(trBuf)
   487  
   488  	var dirs []*tar.Header
   489  
   490  	// Iterate through the files in the archive.
   491  loop:
   492  	for {
   493  		hdr, err := tr.Next()
   494  		if err == io.EOF {
   495  			// end of tar archive
   496  			break
   497  		}
   498  		if err != nil {
   499  			return err
   500  		}
   501  
   502  		// Normalize name, for safety and for a simple is-root check
   503  		// This keeps "../" as-is, but normalizes "/../" to "/"
   504  		hdr.Name = filepath.Clean(hdr.Name)
   505  
   506  		for _, exclude := range options.ExcludePatterns {
   507  			if strings.HasPrefix(hdr.Name, exclude) {
   508  				continue loop
   509  			}
   510  		}
   511  
   512  		if !strings.HasSuffix(hdr.Name, "/") {
   513  			// Not the root directory, ensure that the parent directory exists
   514  			parent := filepath.Dir(hdr.Name)
   515  			parentPath := filepath.Join(dest, parent)
   516  			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
   517  				err = os.MkdirAll(parentPath, 0777)
   518  				if err != nil {
   519  					return err
   520  				}
   521  			}
   522  		}
   523  
   524  		path := filepath.Join(dest, hdr.Name)
   525  		rel, err := filepath.Rel(dest, path)
   526  		if err != nil {
   527  			return err
   528  		}
   529  		if strings.HasPrefix(rel, "..") {
   530  			return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
   531  		}
   532  
   533  		// If path exits we almost always just want to remove and replace it
   534  		// The only exception is when it is a directory *and* the file from
   535  		// the layer is also a directory. Then we want to merge them (i.e.
   536  		// just apply the metadata from the layer).
   537  		if fi, err := os.Lstat(path); err == nil {
   538  			if fi.IsDir() && hdr.Name == "." {
   539  				continue
   540  			}
   541  			if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
   542  				if err := os.RemoveAll(path); err != nil {
   543  					return err
   544  				}
   545  			}
   546  		}
   547  		trBuf.Reset(tr)
   548  		if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown); err != nil {
   549  			return err
   550  		}
   551  
   552  		// Directory mtimes must be handled at the end to avoid further
   553  		// file creation in them to modify the directory mtime
   554  		if hdr.Typeflag == tar.TypeDir {
   555  			dirs = append(dirs, hdr)
   556  		}
   557  	}
   558  
   559  	for _, hdr := range dirs {
   560  		path := filepath.Join(dest, hdr.Name)
   561  		ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
   562  		if err := syscall.UtimesNano(path, ts); err != nil {
   563  			return err
   564  		}
   565  	}
   566  	return nil
   567  }
   568  
   569  // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
   570  // and unpacks it into the directory at `dest`.
   571  // The archive may be compressed with one of the following algorithms:
   572  //  identity (uncompressed), gzip, bzip2, xz.
   573  // FIXME: specify behavior when target path exists vs. doesn't exist.
   574  func Untar(archive io.Reader, dest string, options *TarOptions) error {
   575  	if archive == nil {
   576  		return fmt.Errorf("Empty archive")
   577  	}
   578  	dest = filepath.Clean(dest)
   579  	if options == nil {
   580  		options = &TarOptions{}
   581  	}
   582  	if options.ExcludePatterns == nil {
   583  		options.ExcludePatterns = []string{}
   584  	}
   585  	decompressedArchive, err := DecompressStream(archive)
   586  	if err != nil {
   587  		return err
   588  	}
   589  	defer decompressedArchive.Close()
   590  	return Unpack(decompressedArchive, dest, options)
   591  }
   592  
   593  func (archiver *Archiver) TarUntar(src, dst string) error {
   594  	log.Debugf("TarUntar(%s %s)", src, dst)
   595  	archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
   596  	if err != nil {
   597  		return err
   598  	}
   599  	defer archive.Close()
   600  	return archiver.Untar(archive, dst, nil)
   601  }
   602  
   603  // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
   604  // If either Tar or Untar fails, TarUntar aborts and returns the error.
   605  func TarUntar(src, dst string) error {
   606  	return defaultArchiver.TarUntar(src, dst)
   607  }
   608  
   609  func (archiver *Archiver) UntarPath(src, dst string) error {
   610  	archive, err := os.Open(src)
   611  	if err != nil {
   612  		return err
   613  	}
   614  	defer archive.Close()
   615  	if err := archiver.Untar(archive, dst, nil); err != nil {
   616  		return err
   617  	}
   618  	return nil
   619  }
   620  
   621  // UntarPath is a convenience function which looks for an archive
   622  // at filesystem path `src`, and unpacks it at `dst`.
   623  func UntarPath(src, dst string) error {
   624  	return defaultArchiver.UntarPath(src, dst)
   625  }
   626  
   627  func (archiver *Archiver) CopyWithTar(src, dst string) error {
   628  	srcSt, err := os.Stat(src)
   629  	if err != nil {
   630  		return err
   631  	}
   632  	if !srcSt.IsDir() {
   633  		return archiver.CopyFileWithTar(src, dst)
   634  	}
   635  	// Create dst, copy src's content into it
   636  	log.Debugf("Creating dest directory: %s", dst)
   637  	if err := os.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) {
   638  		return err
   639  	}
   640  	log.Debugf("Calling TarUntar(%s, %s)", src, dst)
   641  	return archiver.TarUntar(src, dst)
   642  }
   643  
   644  // CopyWithTar creates a tar archive of filesystem path `src`, and
   645  // unpacks it at filesystem path `dst`.
   646  // The archive is streamed directly with fixed buffering and no
   647  // intermediary disk IO.
   648  func CopyWithTar(src, dst string) error {
   649  	return defaultArchiver.CopyWithTar(src, dst)
   650  }
   651  
   652  func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
   653  	log.Debugf("CopyFileWithTar(%s, %s)", src, dst)
   654  	srcSt, err := os.Stat(src)
   655  	if err != nil {
   656  		return err
   657  	}
   658  	if srcSt.IsDir() {
   659  		return fmt.Errorf("Can't copy a directory")
   660  	}
   661  	// Clean up the trailing /
   662  	if dst[len(dst)-1] == '/' {
   663  		dst = path.Join(dst, filepath.Base(src))
   664  	}
   665  	// Create the holding directory if necessary
   666  	if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil && !os.IsExist(err) {
   667  		return err
   668  	}
   669  
   670  	r, w := io.Pipe()
   671  	errC := promise.Go(func() error {
   672  		defer w.Close()
   673  
   674  		srcF, err := os.Open(src)
   675  		if err != nil {
   676  			return err
   677  		}
   678  		defer srcF.Close()
   679  
   680  		hdr, err := tar.FileInfoHeader(srcSt, "")
   681  		if err != nil {
   682  			return err
   683  		}
   684  		hdr.Name = filepath.Base(dst)
   685  		tw := tar.NewWriter(w)
   686  		defer tw.Close()
   687  		if err := tw.WriteHeader(hdr); err != nil {
   688  			return err
   689  		}
   690  		if _, err := io.Copy(tw, srcF); err != nil {
   691  			return err
   692  		}
   693  		return nil
   694  	})
   695  	defer func() {
   696  		if er := <-errC; err != nil {
   697  			err = er
   698  		}
   699  	}()
   700  	return archiver.Untar(r, filepath.Dir(dst), nil)
   701  }
   702  
   703  // CopyFileWithTar emulates the behavior of the 'cp' command-line
   704  // for a single file. It copies a regular file from path `src` to
   705  // path `dst`, and preserves all its metadata.
   706  //
   707  // If `dst` ends with a trailing slash '/', the final destination path
   708  // will be `dst/base(src)`.
   709  func CopyFileWithTar(src, dst string) (err error) {
   710  	return defaultArchiver.CopyFileWithTar(src, dst)
   711  }
   712  
   713  // CmdStream executes a command, and returns its stdout as a stream.
   714  // If the command fails to run or doesn't complete successfully, an error
   715  // will be returned, including anything written on stderr.
   716  func CmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
   717  	if input != nil {
   718  		stdin, err := cmd.StdinPipe()
   719  		if err != nil {
   720  			return nil, err
   721  		}
   722  		// Write stdin if any
   723  		go func() {
   724  			io.Copy(stdin, input)
   725  			stdin.Close()
   726  		}()
   727  	}
   728  	stdout, err := cmd.StdoutPipe()
   729  	if err != nil {
   730  		return nil, err
   731  	}
   732  	stderr, err := cmd.StderrPipe()
   733  	if err != nil {
   734  		return nil, err
   735  	}
   736  	pipeR, pipeW := io.Pipe()
   737  	errChan := make(chan []byte)
   738  	// Collect stderr, we will use it in case of an error
   739  	go func() {
   740  		errText, e := ioutil.ReadAll(stderr)
   741  		if e != nil {
   742  			errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
   743  		}
   744  		errChan <- errText
   745  	}()
   746  	// Copy stdout to the returned pipe
   747  	go func() {
   748  		_, err := io.Copy(pipeW, stdout)
   749  		if err != nil {
   750  			pipeW.CloseWithError(err)
   751  		}
   752  		errText := <-errChan
   753  		if err := cmd.Wait(); err != nil {
   754  			pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errText))
   755  		} else {
   756  			pipeW.Close()
   757  		}
   758  	}()
   759  	// Run the command and return the pipe
   760  	if err := cmd.Start(); err != nil {
   761  		return nil, err
   762  	}
   763  	return pipeR, nil
   764  }
   765  
   766  // NewTempArchive reads the content of src into a temporary file, and returns the contents
   767  // of that file as an archive. The archive can only be read once - as soon as reading completes,
   768  // the file will be deleted.
   769  func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
   770  	f, err := ioutil.TempFile(dir, "")
   771  	if err != nil {
   772  		return nil, err
   773  	}
   774  	if _, err := io.Copy(f, src); err != nil {
   775  		return nil, err
   776  	}
   777  	if err = f.Sync(); err != nil {
   778  		return nil, err
   779  	}
   780  	if _, err := f.Seek(0, 0); err != nil {
   781  		return nil, err
   782  	}
   783  	st, err := f.Stat()
   784  	if err != nil {
   785  		return nil, err
   786  	}
   787  	size := st.Size()
   788  	return &TempArchive{File: f, Size: size}, nil
   789  }
   790  
   791  type TempArchive struct {
   792  	*os.File
   793  	Size   int64 // Pre-computed from Stat().Size() as a convenience
   794  	read   int64
   795  	closed bool
   796  }
   797  
   798  // Close closes the underlying file if it's still open, or does a no-op
   799  // to allow callers to try to close the TempArchive multiple times safely.
   800  func (archive *TempArchive) Close() error {
   801  	if archive.closed {
   802  		return nil
   803  	}
   804  
   805  	archive.closed = true
   806  
   807  	return archive.File.Close()
   808  }
   809  
   810  func (archive *TempArchive) Read(data []byte) (int, error) {
   811  	n, err := archive.File.Read(data)
   812  	archive.read += int64(n)
   813  	if err != nil || archive.read == archive.Size {
   814  		archive.Close()
   815  		os.Remove(archive.File.Name())
   816  	}
   817  	return n, err
   818  }