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