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