github.com/nullne/docker@v1.13.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/idtools"
    23  	"github.com/docker/docker/pkg/ioutils"
    24  	"github.com/docker/docker/pkg/pools"
    25  	"github.com/docker/docker/pkg/promise"
    26  	"github.com/docker/docker/pkg/system"
    27  )
    28  
    29  type (
    30  	// Compression is the state represents if compressed or not.
    31  	Compression int
    32  	// WhiteoutFormat is the format of whiteouts unpacked
    33  	WhiteoutFormat int
    34  	// TarChownOptions wraps the chown options UID and GID.
    35  	TarChownOptions struct {
    36  		UID, GID int
    37  	}
    38  
    39  	// TarOptions wraps the tar options.
    40  	TarOptions struct {
    41  		IncludeFiles     []string
    42  		ExcludePatterns  []string
    43  		Compression      Compression
    44  		NoLchown         bool
    45  		UIDMaps          []idtools.IDMap
    46  		GIDMaps          []idtools.IDMap
    47  		ChownOpts        *TarChownOptions
    48  		IncludeSourceDir bool
    49  		// WhiteoutFormat is the expected on disk format for whiteout files.
    50  		// This format will be converted to the standard format on pack
    51  		// and from the standard format on unpack.
    52  		WhiteoutFormat WhiteoutFormat
    53  		// When unpacking, specifies whether overwriting a directory with a
    54  		// non-directory is allowed and vice versa.
    55  		NoOverwriteDirNonDir bool
    56  		// For each include when creating an archive, the included name will be
    57  		// replaced with the matching name from this map.
    58  		RebaseNames map[string]string
    59  		InUserNS    bool
    60  	}
    61  
    62  	// Archiver allows the reuse of most utility functions of this package
    63  	// with a pluggable Untar function. Also, to facilitate the passing of
    64  	// specific id mappings for untar, an archiver can be created with maps
    65  	// which will then be passed to Untar operations
    66  	Archiver struct {
    67  		Untar   func(io.Reader, string, *TarOptions) error
    68  		UIDMaps []idtools.IDMap
    69  		GIDMaps []idtools.IDMap
    70  	}
    71  
    72  	// breakoutError is used to differentiate errors related to breaking out
    73  	// When testing archive breakout in the unit tests, this error is expected
    74  	// in order for the test to pass.
    75  	breakoutError error
    76  )
    77  
    78  var (
    79  	// ErrNotImplemented is the error message of function not implemented.
    80  	ErrNotImplemented = errors.New("Function not implemented")
    81  	defaultArchiver   = &Archiver{Untar: Untar, UIDMaps: nil, GIDMaps: nil}
    82  )
    83  
    84  const (
    85  	// HeaderSize is the size in bytes of a tar header
    86  	HeaderSize = 512
    87  )
    88  
    89  const (
    90  	// Uncompressed represents the uncompressed.
    91  	Uncompressed Compression = iota
    92  	// Bzip2 is bzip2 compression algorithm.
    93  	Bzip2
    94  	// Gzip is gzip compression algorithm.
    95  	Gzip
    96  	// Xz is xz compression algorithm.
    97  	Xz
    98  )
    99  
   100  const (
   101  	// AUFSWhiteoutFormat is the default format for whiteouts
   102  	AUFSWhiteoutFormat WhiteoutFormat = iota
   103  	// OverlayWhiteoutFormat formats whiteout according to the overlay
   104  	// standard.
   105  	OverlayWhiteoutFormat
   106  )
   107  
   108  // IsArchive checks for the magic bytes of a tar or any supported compression
   109  // algorithm.
   110  func IsArchive(header []byte) bool {
   111  	compression := DetectCompression(header)
   112  	if compression != Uncompressed {
   113  		return true
   114  	}
   115  	r := tar.NewReader(bytes.NewBuffer(header))
   116  	_, err := r.Next()
   117  	return err == nil
   118  }
   119  
   120  // IsArchivePath checks if the (possibly compressed) file at the given path
   121  // starts with a tar file header.
   122  func IsArchivePath(path string) bool {
   123  	file, err := os.Open(path)
   124  	if err != nil {
   125  		return false
   126  	}
   127  	defer file.Close()
   128  	rdr, err := DecompressStream(file)
   129  	if err != nil {
   130  		return false
   131  	}
   132  	r := tar.NewReader(rdr)
   133  	_, err = r.Next()
   134  	return err == nil
   135  }
   136  
   137  // DetectCompression detects the compression algorithm of the source.
   138  func DetectCompression(source []byte) Compression {
   139  	for compression, m := range map[Compression][]byte{
   140  		Bzip2: {0x42, 0x5A, 0x68},
   141  		Gzip:  {0x1F, 0x8B, 0x08},
   142  		Xz:    {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
   143  	} {
   144  		if len(source) < len(m) {
   145  			logrus.Debug("Len too short")
   146  			continue
   147  		}
   148  		if bytes.Compare(m, source[:len(m)]) == 0 {
   149  			return compression
   150  		}
   151  	}
   152  	return Uncompressed
   153  }
   154  
   155  func xzDecompress(archive io.Reader) (io.ReadCloser, <-chan struct{}, error) {
   156  	args := []string{"xz", "-d", "-c", "-q"}
   157  
   158  	return cmdStream(exec.Command(args[0], args[1:]...), archive)
   159  }
   160  
   161  // DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive.
   162  func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
   163  	p := pools.BufioReader32KPool
   164  	buf := p.Get(archive)
   165  	bs, err := buf.Peek(10)
   166  	if err != nil && err != io.EOF {
   167  		// Note: we'll ignore any io.EOF error because there are some odd
   168  		// cases where the layer.tar file will be empty (zero bytes) and
   169  		// that results in an io.EOF from the Peek() call. So, in those
   170  		// cases we'll just treat it as a non-compressed stream and
   171  		// that means just create an empty layer.
   172  		// See Issue 18170
   173  		return nil, err
   174  	}
   175  
   176  	compression := DetectCompression(bs)
   177  	switch compression {
   178  	case Uncompressed:
   179  		readBufWrapper := p.NewReadCloserWrapper(buf, buf)
   180  		return readBufWrapper, nil
   181  	case Gzip:
   182  		gzReader, err := gzip.NewReader(buf)
   183  		if err != nil {
   184  			return nil, err
   185  		}
   186  		readBufWrapper := p.NewReadCloserWrapper(buf, gzReader)
   187  		return readBufWrapper, nil
   188  	case Bzip2:
   189  		bz2Reader := bzip2.NewReader(buf)
   190  		readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader)
   191  		return readBufWrapper, nil
   192  	case Xz:
   193  		xzReader, chdone, err := xzDecompress(buf)
   194  		if err != nil {
   195  			return nil, err
   196  		}
   197  		readBufWrapper := p.NewReadCloserWrapper(buf, xzReader)
   198  		return ioutils.NewReadCloserWrapper(readBufWrapper, func() error {
   199  			<-chdone
   200  			return readBufWrapper.Close()
   201  		}), nil
   202  	default:
   203  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   204  	}
   205  }
   206  
   207  // CompressStream compresseses the dest with specified compression algorithm.
   208  func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) {
   209  	p := pools.BufioWriter32KPool
   210  	buf := p.Get(dest)
   211  	switch compression {
   212  	case Uncompressed:
   213  		writeBufWrapper := p.NewWriteCloserWrapper(buf, buf)
   214  		return writeBufWrapper, nil
   215  	case Gzip:
   216  		gzWriter := gzip.NewWriter(dest)
   217  		writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter)
   218  		return writeBufWrapper, nil
   219  	case Bzip2, Xz:
   220  		// archive/bzip2 does not support writing, and there is no xz support at all
   221  		// However, this is not a problem as docker only currently generates gzipped tars
   222  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   223  	default:
   224  		return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
   225  	}
   226  }
   227  
   228  // Extension returns the extension of a file that uses the specified compression algorithm.
   229  func (compression *Compression) Extension() string {
   230  	switch *compression {
   231  	case Uncompressed:
   232  		return "tar"
   233  	case Bzip2:
   234  		return "tar.bz2"
   235  	case Gzip:
   236  		return "tar.gz"
   237  	case Xz:
   238  		return "tar.xz"
   239  	}
   240  	return ""
   241  }
   242  
   243  type tarWhiteoutConverter interface {
   244  	ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error)
   245  	ConvertRead(*tar.Header, string) (bool, error)
   246  }
   247  
   248  type tarAppender struct {
   249  	TarWriter *tar.Writer
   250  	Buffer    *bufio.Writer
   251  
   252  	// for hardlink mapping
   253  	SeenFiles map[uint64]string
   254  	UIDMaps   []idtools.IDMap
   255  	GIDMaps   []idtools.IDMap
   256  
   257  	// For packing and unpacking whiteout files in the
   258  	// non standard format. The whiteout files defined
   259  	// by the AUFS standard are used as the tar whiteout
   260  	// standard.
   261  	WhiteoutConverter tarWhiteoutConverter
   262  }
   263  
   264  // canonicalTarName provides a platform-independent and consistent posix-style
   265  //path for files and directories to be archived regardless of the platform.
   266  func canonicalTarName(name string, isDir bool) (string, error) {
   267  	name, err := CanonicalTarNameForPath(name)
   268  	if err != nil {
   269  		return "", err
   270  	}
   271  
   272  	// suffix with '/' for directories
   273  	if isDir && !strings.HasSuffix(name, "/") {
   274  		name += "/"
   275  	}
   276  	return name, nil
   277  }
   278  
   279  // addTarFile adds to the tar archive a file from `path` as `name`
   280  func (ta *tarAppender) addTarFile(path, name string) error {
   281  	fi, err := os.Lstat(path)
   282  	if err != nil {
   283  		return err
   284  	}
   285  
   286  	link := ""
   287  	if fi.Mode()&os.ModeSymlink != 0 {
   288  		if link, err = os.Readlink(path); err != nil {
   289  			return err
   290  		}
   291  	}
   292  
   293  	hdr, err := tar.FileInfoHeader(fi, link)
   294  	if err != nil {
   295  		return err
   296  	}
   297  	hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
   298  
   299  	name, err = canonicalTarName(name, fi.IsDir())
   300  	if err != nil {
   301  		return fmt.Errorf("tar: cannot canonicalize path: %v", err)
   302  	}
   303  	hdr.Name = name
   304  
   305  	inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys())
   306  	if err != nil {
   307  		return err
   308  	}
   309  
   310  	// if it's not a directory and has more than 1 link,
   311  	// it's hard linked, so set the type flag accordingly
   312  	if !fi.IsDir() && hasHardlinks(fi) {
   313  		// a link should have a name that it links too
   314  		// and that linked name should be first in the tar archive
   315  		if oldpath, ok := ta.SeenFiles[inode]; ok {
   316  			hdr.Typeflag = tar.TypeLink
   317  			hdr.Linkname = oldpath
   318  			hdr.Size = 0 // This Must be here for the writer math to add up!
   319  		} else {
   320  			ta.SeenFiles[inode] = name
   321  		}
   322  	}
   323  
   324  	capability, _ := system.Lgetxattr(path, "security.capability")
   325  	if capability != nil {
   326  		hdr.Xattrs = make(map[string]string)
   327  		hdr.Xattrs["security.capability"] = string(capability)
   328  	}
   329  
   330  	//handle re-mapping container ID mappings back to host ID mappings before
   331  	//writing tar headers/files. We skip whiteout files because they were written
   332  	//by the kernel and already have proper ownership relative to the host
   333  	if !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && (ta.UIDMaps != nil || ta.GIDMaps != nil) {
   334  		uid, gid, err := getFileUIDGID(fi.Sys())
   335  		if err != nil {
   336  			return err
   337  		}
   338  		xUID, err := idtools.ToContainer(uid, ta.UIDMaps)
   339  		if err != nil {
   340  			return err
   341  		}
   342  		xGID, err := idtools.ToContainer(gid, ta.GIDMaps)
   343  		if err != nil {
   344  			return err
   345  		}
   346  		hdr.Uid = xUID
   347  		hdr.Gid = xGID
   348  	}
   349  
   350  	if ta.WhiteoutConverter != nil {
   351  		wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi)
   352  		if err != nil {
   353  			return err
   354  		}
   355  
   356  		// If a new whiteout file exists, write original hdr, then
   357  		// replace hdr with wo to be written after. Whiteouts should
   358  		// always be written after the original. Note the original
   359  		// hdr may have been updated to be a whiteout with returning
   360  		// a whiteout header
   361  		if wo != nil {
   362  			if err := ta.TarWriter.WriteHeader(hdr); err != nil {
   363  				return err
   364  			}
   365  			if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
   366  				return fmt.Errorf("tar: cannot use whiteout for non-empty file")
   367  			}
   368  			hdr = wo
   369  		}
   370  	}
   371  
   372  	if err := ta.TarWriter.WriteHeader(hdr); err != nil {
   373  		return err
   374  	}
   375  
   376  	if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
   377  		file, err := os.Open(path)
   378  		if err != nil {
   379  			return err
   380  		}
   381  
   382  		ta.Buffer.Reset(ta.TarWriter)
   383  		defer ta.Buffer.Reset(nil)
   384  		_, err = io.Copy(ta.Buffer, file)
   385  		file.Close()
   386  		if err != nil {
   387  			return err
   388  		}
   389  		err = ta.Buffer.Flush()
   390  		if err != nil {
   391  			return err
   392  		}
   393  	}
   394  
   395  	return nil
   396  }
   397  
   398  func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions, inUserns bool) error {
   399  	// hdr.Mode is in linux format, which we can use for sycalls,
   400  	// but for os.Foo() calls we need the mode converted to os.FileMode,
   401  	// so use hdrInfo.Mode() (they differ for e.g. setuid bits)
   402  	hdrInfo := hdr.FileInfo()
   403  
   404  	switch hdr.Typeflag {
   405  	case tar.TypeDir:
   406  		// Create directory unless it exists as a directory already.
   407  		// In that case we just want to merge the two
   408  		if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
   409  			if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
   410  				return err
   411  			}
   412  		}
   413  
   414  	case tar.TypeReg, tar.TypeRegA:
   415  		// Source is regular file
   416  		file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
   417  		if err != nil {
   418  			return err
   419  		}
   420  		if _, err := io.Copy(file, reader); err != nil {
   421  			file.Close()
   422  			return err
   423  		}
   424  		file.Close()
   425  
   426  	case tar.TypeBlock, tar.TypeChar:
   427  		if inUserns { // cannot create devices in a userns
   428  			return nil
   429  		}
   430  		// Handle this is an OS-specific way
   431  		if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
   432  			return err
   433  		}
   434  
   435  	case tar.TypeFifo:
   436  		// Handle this is an OS-specific way
   437  		if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
   438  			return err
   439  		}
   440  
   441  	case tar.TypeLink:
   442  		targetPath := filepath.Join(extractDir, hdr.Linkname)
   443  		// check for hardlink breakout
   444  		if !strings.HasPrefix(targetPath, extractDir) {
   445  			return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname))
   446  		}
   447  		if err := os.Link(targetPath, path); err != nil {
   448  			return err
   449  		}
   450  
   451  	case tar.TypeSymlink:
   452  		// 	path 				-> hdr.Linkname = targetPath
   453  		// e.g. /extractDir/path/to/symlink 	-> ../2/file	= /extractDir/path/2/file
   454  		targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname)
   455  
   456  		// the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because
   457  		// that symlink would first have to be created, which would be caught earlier, at this very check:
   458  		if !strings.HasPrefix(targetPath, extractDir) {
   459  			return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname))
   460  		}
   461  		if err := os.Symlink(hdr.Linkname, path); err != nil {
   462  			return err
   463  		}
   464  
   465  	case tar.TypeXGlobalHeader:
   466  		logrus.Debug("PAX Global Extended Headers found and ignored")
   467  		return nil
   468  
   469  	default:
   470  		return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag)
   471  	}
   472  
   473  	// Lchown is not supported on Windows.
   474  	if Lchown && runtime.GOOS != "windows" {
   475  		if chownOpts == nil {
   476  			chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid}
   477  		}
   478  		if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil {
   479  			return err
   480  		}
   481  	}
   482  
   483  	var errors []string
   484  	for key, value := range hdr.Xattrs {
   485  		if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil {
   486  			if err == syscall.ENOTSUP {
   487  				// We ignore errors here because not all graphdrivers support
   488  				// xattrs *cough* old versions of AUFS *cough*. However only
   489  				// ENOTSUP should be emitted in that case, otherwise we still
   490  				// bail.
   491  				errors = append(errors, err.Error())
   492  				continue
   493  			}
   494  			return err
   495  		}
   496  
   497  	}
   498  
   499  	if len(errors) > 0 {
   500  		logrus.WithFields(logrus.Fields{
   501  			"errors": errors,
   502  		}).Warn("ignored xattrs in archive: underlying filesystem doesn't support them")
   503  	}
   504  
   505  	// There is no LChmod, so ignore mode for symlink. Also, this
   506  	// must happen after chown, as that can modify the file mode
   507  	if err := handleLChmod(hdr, path, hdrInfo); err != nil {
   508  		return err
   509  	}
   510  
   511  	aTime := hdr.AccessTime
   512  	if aTime.Before(hdr.ModTime) {
   513  		// Last access time should never be before last modified time.
   514  		aTime = hdr.ModTime
   515  	}
   516  
   517  	// system.Chtimes doesn't support a NOFOLLOW flag atm
   518  	if hdr.Typeflag == tar.TypeLink {
   519  		if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) {
   520  			if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil {
   521  				return err
   522  			}
   523  		}
   524  	} else if hdr.Typeflag != tar.TypeSymlink {
   525  		if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil {
   526  			return err
   527  		}
   528  	} else {
   529  		ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)}
   530  		if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
   531  			return err
   532  		}
   533  	}
   534  	return nil
   535  }
   536  
   537  // Tar creates an archive from the directory at `path`, and returns it as a
   538  // stream of bytes.
   539  func Tar(path string, compression Compression) (io.ReadCloser, error) {
   540  	return TarWithOptions(path, &TarOptions{Compression: compression})
   541  }
   542  
   543  // TarWithOptions creates an archive from the directory at `path`, only including files whose relative
   544  // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`.
   545  func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) {
   546  
   547  	// Fix the source path to work with long path names. This is a no-op
   548  	// on platforms other than Windows.
   549  	srcPath = fixVolumePathPrefix(srcPath)
   550  
   551  	patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns)
   552  
   553  	if err != nil {
   554  		return nil, err
   555  	}
   556  
   557  	pipeReader, pipeWriter := io.Pipe()
   558  
   559  	compressWriter, err := CompressStream(pipeWriter, options.Compression)
   560  	if err != nil {
   561  		return nil, err
   562  	}
   563  
   564  	go func() {
   565  		ta := &tarAppender{
   566  			TarWriter:         tar.NewWriter(compressWriter),
   567  			Buffer:            pools.BufioWriter32KPool.Get(nil),
   568  			SeenFiles:         make(map[uint64]string),
   569  			UIDMaps:           options.UIDMaps,
   570  			GIDMaps:           options.GIDMaps,
   571  			WhiteoutConverter: getWhiteoutConverter(options.WhiteoutFormat),
   572  		}
   573  
   574  		defer func() {
   575  			// Make sure to check the error on Close.
   576  			if err := ta.TarWriter.Close(); err != nil {
   577  				logrus.Errorf("Can't close tar writer: %s", err)
   578  			}
   579  			if err := compressWriter.Close(); err != nil {
   580  				logrus.Errorf("Can't close compress writer: %s", err)
   581  			}
   582  			if err := pipeWriter.Close(); err != nil {
   583  				logrus.Errorf("Can't close pipe writer: %s", err)
   584  			}
   585  		}()
   586  
   587  		// this buffer is needed for the duration of this piped stream
   588  		defer pools.BufioWriter32KPool.Put(ta.Buffer)
   589  
   590  		// In general we log errors here but ignore them because
   591  		// during e.g. a diff operation the container can continue
   592  		// mutating the filesystem and we can see transient errors
   593  		// from this
   594  
   595  		stat, err := os.Lstat(srcPath)
   596  		if err != nil {
   597  			return
   598  		}
   599  
   600  		if !stat.IsDir() {
   601  			// We can't later join a non-dir with any includes because the
   602  			// 'walk' will error if "file/." is stat-ed and "file" is not a
   603  			// directory. So, we must split the source path and use the
   604  			// basename as the include.
   605  			if len(options.IncludeFiles) > 0 {
   606  				logrus.Warn("Tar: Can't archive a file with includes")
   607  			}
   608  
   609  			dir, base := SplitPathDirEntry(srcPath)
   610  			srcPath = dir
   611  			options.IncludeFiles = []string{base}
   612  		}
   613  
   614  		if len(options.IncludeFiles) == 0 {
   615  			options.IncludeFiles = []string{"."}
   616  		}
   617  
   618  		seen := make(map[string]bool)
   619  
   620  		for _, include := range options.IncludeFiles {
   621  			rebaseName := options.RebaseNames[include]
   622  
   623  			walkRoot := getWalkRoot(srcPath, include)
   624  			filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error {
   625  				if err != nil {
   626  					logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err)
   627  					return nil
   628  				}
   629  
   630  				relFilePath, err := filepath.Rel(srcPath, filePath)
   631  				if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) {
   632  					// Error getting relative path OR we are looking
   633  					// at the source directory path. Skip in both situations.
   634  					return nil
   635  				}
   636  
   637  				if options.IncludeSourceDir && include == "." && relFilePath != "." {
   638  					relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator))
   639  				}
   640  
   641  				skip := false
   642  
   643  				// If "include" is an exact match for the current file
   644  				// then even if there's an "excludePatterns" pattern that
   645  				// matches it, don't skip it. IOW, assume an explicit 'include'
   646  				// is asking for that file no matter what - which is true
   647  				// for some files, like .dockerignore and Dockerfile (sometimes)
   648  				if include != relFilePath {
   649  					skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs)
   650  					if err != nil {
   651  						logrus.Errorf("Error matching %s: %v", relFilePath, err)
   652  						return err
   653  					}
   654  				}
   655  
   656  				if skip {
   657  					// If we want to skip this file and its a directory
   658  					// then we should first check to see if there's an
   659  					// excludes pattern (eg !dir/file) that starts with this
   660  					// dir. If so then we can't skip this dir.
   661  
   662  					// Its not a dir then so we can just return/skip.
   663  					if !f.IsDir() {
   664  						return nil
   665  					}
   666  
   667  					// No exceptions (!...) in patterns so just skip dir
   668  					if !exceptions {
   669  						return filepath.SkipDir
   670  					}
   671  
   672  					dirSlash := relFilePath + string(filepath.Separator)
   673  
   674  					for _, pat := range patterns {
   675  						if pat[0] != '!' {
   676  							continue
   677  						}
   678  						pat = pat[1:] + string(filepath.Separator)
   679  						if strings.HasPrefix(pat, dirSlash) {
   680  							// found a match - so can't skip this dir
   681  							return nil
   682  						}
   683  					}
   684  
   685  					// No matching exclusion dir so just skip dir
   686  					return filepath.SkipDir
   687  				}
   688  
   689  				if seen[relFilePath] {
   690  					return nil
   691  				}
   692  				seen[relFilePath] = true
   693  
   694  				// Rename the base resource.
   695  				if rebaseName != "" {
   696  					var replacement string
   697  					if rebaseName != string(filepath.Separator) {
   698  						// Special case the root directory to replace with an
   699  						// empty string instead so that we don't end up with
   700  						// double slashes in the paths.
   701  						replacement = rebaseName
   702  					}
   703  
   704  					relFilePath = strings.Replace(relFilePath, include, replacement, 1)
   705  				}
   706  
   707  				if err := ta.addTarFile(filePath, relFilePath); err != nil {
   708  					logrus.Errorf("Can't add file %s to tar: %s", filePath, err)
   709  					// if pipe is broken, stop writing tar stream to it
   710  					if err == io.ErrClosedPipe {
   711  						return err
   712  					}
   713  				}
   714  				return nil
   715  			})
   716  		}
   717  	}()
   718  
   719  	return pipeReader, nil
   720  }
   721  
   722  // Unpack unpacks the decompressedArchive to dest with options.
   723  func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error {
   724  	tr := tar.NewReader(decompressedArchive)
   725  	trBuf := pools.BufioReader32KPool.Get(nil)
   726  	defer pools.BufioReader32KPool.Put(trBuf)
   727  
   728  	var dirs []*tar.Header
   729  	remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps)
   730  	if err != nil {
   731  		return err
   732  	}
   733  	whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat)
   734  
   735  	// Iterate through the files in the archive.
   736  loop:
   737  	for {
   738  		hdr, err := tr.Next()
   739  		if err == io.EOF {
   740  			// end of tar archive
   741  			break
   742  		}
   743  		if err != nil {
   744  			return err
   745  		}
   746  
   747  		// Normalize name, for safety and for a simple is-root check
   748  		// This keeps "../" as-is, but normalizes "/../" to "/". Or Windows:
   749  		// This keeps "..\" as-is, but normalizes "\..\" to "\".
   750  		hdr.Name = filepath.Clean(hdr.Name)
   751  
   752  		for _, exclude := range options.ExcludePatterns {
   753  			if strings.HasPrefix(hdr.Name, exclude) {
   754  				continue loop
   755  			}
   756  		}
   757  
   758  		// After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in
   759  		// the filepath format for the OS on which the daemon is running. Hence
   760  		// the check for a slash-suffix MUST be done in an OS-agnostic way.
   761  		if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
   762  			// Not the root directory, ensure that the parent directory exists
   763  			parent := filepath.Dir(hdr.Name)
   764  			parentPath := filepath.Join(dest, parent)
   765  			if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
   766  				err = idtools.MkdirAllNewAs(parentPath, 0777, remappedRootUID, remappedRootGID)
   767  				if err != nil {
   768  					return err
   769  				}
   770  			}
   771  		}
   772  
   773  		path := filepath.Join(dest, hdr.Name)
   774  		rel, err := filepath.Rel(dest, path)
   775  		if err != nil {
   776  			return err
   777  		}
   778  		if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
   779  			return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
   780  		}
   781  
   782  		// If path exits we almost always just want to remove and replace it
   783  		// The only exception is when it is a directory *and* the file from
   784  		// the layer is also a directory. Then we want to merge them (i.e.
   785  		// just apply the metadata from the layer).
   786  		if fi, err := os.Lstat(path); err == nil {
   787  			if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir {
   788  				// If NoOverwriteDirNonDir is true then we cannot replace
   789  				// an existing directory with a non-directory from the archive.
   790  				return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest)
   791  			}
   792  
   793  			if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir {
   794  				// If NoOverwriteDirNonDir is true then we cannot replace
   795  				// an existing non-directory with a directory from the archive.
   796  				return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest)
   797  			}
   798  
   799  			if fi.IsDir() && hdr.Name == "." {
   800  				continue
   801  			}
   802  
   803  			if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
   804  				if err := os.RemoveAll(path); err != nil {
   805  					return err
   806  				}
   807  			}
   808  		}
   809  		trBuf.Reset(tr)
   810  
   811  		// if the options contain a uid & gid maps, convert header uid/gid
   812  		// entries using the maps such that lchown sets the proper mapped
   813  		// uid/gid after writing the file. We only perform this mapping if
   814  		// the file isn't already owned by the remapped root UID or GID, as
   815  		// that specific uid/gid has no mapping from container -> host, and
   816  		// those files already have the proper ownership for inside the
   817  		// container.
   818  		if hdr.Uid != remappedRootUID {
   819  			xUID, err := idtools.ToHost(hdr.Uid, options.UIDMaps)
   820  			if err != nil {
   821  				return err
   822  			}
   823  			hdr.Uid = xUID
   824  		}
   825  		if hdr.Gid != remappedRootGID {
   826  			xGID, err := idtools.ToHost(hdr.Gid, options.GIDMaps)
   827  			if err != nil {
   828  				return err
   829  			}
   830  			hdr.Gid = xGID
   831  		}
   832  
   833  		if whiteoutConverter != nil {
   834  			writeFile, err := whiteoutConverter.ConvertRead(hdr, path)
   835  			if err != nil {
   836  				return err
   837  			}
   838  			if !writeFile {
   839  				continue
   840  			}
   841  		}
   842  
   843  		if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts, options.InUserNS); err != nil {
   844  			return err
   845  		}
   846  
   847  		// Directory mtimes must be handled at the end to avoid further
   848  		// file creation in them to modify the directory mtime
   849  		if hdr.Typeflag == tar.TypeDir {
   850  			dirs = append(dirs, hdr)
   851  		}
   852  	}
   853  
   854  	for _, hdr := range dirs {
   855  		path := filepath.Join(dest, hdr.Name)
   856  
   857  		if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil {
   858  			return err
   859  		}
   860  	}
   861  	return nil
   862  }
   863  
   864  // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
   865  // and unpacks it into the directory at `dest`.
   866  // The archive may be compressed with one of the following algorithms:
   867  //  identity (uncompressed), gzip, bzip2, xz.
   868  // FIXME: specify behavior when target path exists vs. doesn't exist.
   869  func Untar(tarArchive io.Reader, dest string, options *TarOptions) error {
   870  	return untarHandler(tarArchive, dest, options, true)
   871  }
   872  
   873  // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive,
   874  // and unpacks it into the directory at `dest`.
   875  // The archive must be an uncompressed stream.
   876  func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error {
   877  	return untarHandler(tarArchive, dest, options, false)
   878  }
   879  
   880  // Handler for teasing out the automatic decompression
   881  func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error {
   882  	if tarArchive == nil {
   883  		return fmt.Errorf("Empty archive")
   884  	}
   885  	dest = filepath.Clean(dest)
   886  	if options == nil {
   887  		options = &TarOptions{}
   888  	}
   889  	if options.ExcludePatterns == nil {
   890  		options.ExcludePatterns = []string{}
   891  	}
   892  
   893  	r := tarArchive
   894  	if decompress {
   895  		decompressedArchive, err := DecompressStream(tarArchive)
   896  		if err != nil {
   897  			return err
   898  		}
   899  		defer decompressedArchive.Close()
   900  		r = decompressedArchive
   901  	}
   902  
   903  	return Unpack(r, dest, options)
   904  }
   905  
   906  // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
   907  // If either Tar or Untar fails, TarUntar aborts and returns the error.
   908  func (archiver *Archiver) TarUntar(src, dst string) error {
   909  	logrus.Debugf("TarUntar(%s %s)", src, dst)
   910  	archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
   911  	if err != nil {
   912  		return err
   913  	}
   914  	defer archive.Close()
   915  
   916  	var options *TarOptions
   917  	if archiver.UIDMaps != nil || archiver.GIDMaps != nil {
   918  		options = &TarOptions{
   919  			UIDMaps: archiver.UIDMaps,
   920  			GIDMaps: archiver.GIDMaps,
   921  		}
   922  	}
   923  	return archiver.Untar(archive, dst, options)
   924  }
   925  
   926  // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
   927  // If either Tar or Untar fails, TarUntar aborts and returns the error.
   928  func TarUntar(src, dst string) error {
   929  	return defaultArchiver.TarUntar(src, dst)
   930  }
   931  
   932  // UntarPath untar a file from path to a destination, src is the source tar file path.
   933  func (archiver *Archiver) UntarPath(src, dst string) error {
   934  	archive, err := os.Open(src)
   935  	if err != nil {
   936  		return err
   937  	}
   938  	defer archive.Close()
   939  	var options *TarOptions
   940  	if archiver.UIDMaps != nil || archiver.GIDMaps != nil {
   941  		options = &TarOptions{
   942  			UIDMaps: archiver.UIDMaps,
   943  			GIDMaps: archiver.GIDMaps,
   944  		}
   945  	}
   946  	return archiver.Untar(archive, dst, options)
   947  }
   948  
   949  // UntarPath is a convenience function which looks for an archive
   950  // at filesystem path `src`, and unpacks it at `dst`.
   951  func UntarPath(src, dst string) error {
   952  	return defaultArchiver.UntarPath(src, dst)
   953  }
   954  
   955  // CopyWithTar creates a tar archive of filesystem path `src`, and
   956  // unpacks it at filesystem path `dst`.
   957  // The archive is streamed directly with fixed buffering and no
   958  // intermediary disk IO.
   959  func (archiver *Archiver) CopyWithTar(src, dst string) error {
   960  	srcSt, err := os.Stat(src)
   961  	if err != nil {
   962  		return err
   963  	}
   964  	if !srcSt.IsDir() {
   965  		return archiver.CopyFileWithTar(src, dst)
   966  	}
   967  
   968  	// if this archiver is set up with ID mapping we need to create
   969  	// the new destination directory with the remapped root UID/GID pair
   970  	// as owner
   971  	rootUID, rootGID, err := idtools.GetRootUIDGID(archiver.UIDMaps, archiver.GIDMaps)
   972  	if err != nil {
   973  		return err
   974  	}
   975  	// Create dst, copy src's content into it
   976  	logrus.Debugf("Creating dest directory: %s", dst)
   977  	if err := idtools.MkdirAllNewAs(dst, 0755, rootUID, rootGID); err != nil {
   978  		return err
   979  	}
   980  	logrus.Debugf("Calling TarUntar(%s, %s)", src, dst)
   981  	return archiver.TarUntar(src, dst)
   982  }
   983  
   984  // CopyWithTar creates a tar archive of filesystem path `src`, and
   985  // unpacks it at filesystem path `dst`.
   986  // The archive is streamed directly with fixed buffering and no
   987  // intermediary disk IO.
   988  func CopyWithTar(src, dst string) error {
   989  	return defaultArchiver.CopyWithTar(src, dst)
   990  }
   991  
   992  // CopyFileWithTar emulates the behavior of the 'cp' command-line
   993  // for a single file. It copies a regular file from path `src` to
   994  // path `dst`, and preserves all its metadata.
   995  func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
   996  	logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst)
   997  	srcSt, err := os.Stat(src)
   998  	if err != nil {
   999  		return err
  1000  	}
  1001  
  1002  	if srcSt.IsDir() {
  1003  		return fmt.Errorf("Can't copy a directory")
  1004  	}
  1005  
  1006  	// Clean up the trailing slash. This must be done in an operating
  1007  	// system specific manner.
  1008  	if dst[len(dst)-1] == os.PathSeparator {
  1009  		dst = filepath.Join(dst, filepath.Base(src))
  1010  	}
  1011  	// Create the holding directory if necessary
  1012  	if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil {
  1013  		return err
  1014  	}
  1015  
  1016  	r, w := io.Pipe()
  1017  	errC := promise.Go(func() error {
  1018  		defer w.Close()
  1019  
  1020  		srcF, err := os.Open(src)
  1021  		if err != nil {
  1022  			return err
  1023  		}
  1024  		defer srcF.Close()
  1025  
  1026  		hdr, err := tar.FileInfoHeader(srcSt, "")
  1027  		if err != nil {
  1028  			return err
  1029  		}
  1030  		hdr.Name = filepath.Base(dst)
  1031  		hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
  1032  
  1033  		remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(archiver.UIDMaps, archiver.GIDMaps)
  1034  		if err != nil {
  1035  			return err
  1036  		}
  1037  
  1038  		// only perform mapping if the file being copied isn't already owned by the
  1039  		// uid or gid of the remapped root in the container
  1040  		if remappedRootUID != hdr.Uid {
  1041  			xUID, err := idtools.ToHost(hdr.Uid, archiver.UIDMaps)
  1042  			if err != nil {
  1043  				return err
  1044  			}
  1045  			hdr.Uid = xUID
  1046  		}
  1047  		if remappedRootGID != hdr.Gid {
  1048  			xGID, err := idtools.ToHost(hdr.Gid, archiver.GIDMaps)
  1049  			if err != nil {
  1050  				return err
  1051  			}
  1052  			hdr.Gid = xGID
  1053  		}
  1054  
  1055  		tw := tar.NewWriter(w)
  1056  		defer tw.Close()
  1057  		if err := tw.WriteHeader(hdr); err != nil {
  1058  			return err
  1059  		}
  1060  		if _, err := io.Copy(tw, srcF); err != nil {
  1061  			return err
  1062  		}
  1063  		return nil
  1064  	})
  1065  	defer func() {
  1066  		if er := <-errC; err == nil && er != nil {
  1067  			err = er
  1068  		}
  1069  	}()
  1070  
  1071  	err = archiver.Untar(r, filepath.Dir(dst), nil)
  1072  	if err != nil {
  1073  		r.CloseWithError(err)
  1074  	}
  1075  	return err
  1076  }
  1077  
  1078  // CopyFileWithTar emulates the behavior of the 'cp' command-line
  1079  // for a single file. It copies a regular file from path `src` to
  1080  // path `dst`, and preserves all its metadata.
  1081  //
  1082  // Destination handling is in an operating specific manner depending
  1083  // where the daemon is running. If `dst` ends with a trailing slash
  1084  // the final destination path will be `dst/base(src)`  (Linux) or
  1085  // `dst\base(src)` (Windows).
  1086  func CopyFileWithTar(src, dst string) (err error) {
  1087  	return defaultArchiver.CopyFileWithTar(src, dst)
  1088  }
  1089  
  1090  // cmdStream executes a command, and returns its stdout as a stream.
  1091  // If the command fails to run or doesn't complete successfully, an error
  1092  // will be returned, including anything written on stderr.
  1093  func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, <-chan struct{}, error) {
  1094  	chdone := make(chan struct{})
  1095  	cmd.Stdin = input
  1096  	pipeR, pipeW := io.Pipe()
  1097  	cmd.Stdout = pipeW
  1098  	var errBuf bytes.Buffer
  1099  	cmd.Stderr = &errBuf
  1100  
  1101  	// Run the command and return the pipe
  1102  	if err := cmd.Start(); err != nil {
  1103  		return nil, nil, err
  1104  	}
  1105  
  1106  	// Copy stdout to the returned pipe
  1107  	go func() {
  1108  		if err := cmd.Wait(); err != nil {
  1109  			pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String()))
  1110  		} else {
  1111  			pipeW.Close()
  1112  		}
  1113  		close(chdone)
  1114  	}()
  1115  
  1116  	return pipeR, chdone, nil
  1117  }
  1118  
  1119  // NewTempArchive reads the content of src into a temporary file, and returns the contents
  1120  // of that file as an archive. The archive can only be read once - as soon as reading completes,
  1121  // the file will be deleted.
  1122  func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) {
  1123  	f, err := ioutil.TempFile(dir, "")
  1124  	if err != nil {
  1125  		return nil, err
  1126  	}
  1127  	if _, err := io.Copy(f, src); err != nil {
  1128  		return nil, err
  1129  	}
  1130  	if _, err := f.Seek(0, 0); err != nil {
  1131  		return nil, err
  1132  	}
  1133  	st, err := f.Stat()
  1134  	if err != nil {
  1135  		return nil, err
  1136  	}
  1137  	size := st.Size()
  1138  	return &TempArchive{File: f, Size: size}, nil
  1139  }
  1140  
  1141  // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes,
  1142  // the file will be deleted.
  1143  type TempArchive struct {
  1144  	*os.File
  1145  	Size   int64 // Pre-computed from Stat().Size() as a convenience
  1146  	read   int64
  1147  	closed bool
  1148  }
  1149  
  1150  // Close closes the underlying file if it's still open, or does a no-op
  1151  // to allow callers to try to close the TempArchive multiple times safely.
  1152  func (archive *TempArchive) Close() error {
  1153  	if archive.closed {
  1154  		return nil
  1155  	}
  1156  
  1157  	archive.closed = true
  1158  
  1159  	return archive.File.Close()
  1160  }
  1161  
  1162  func (archive *TempArchive) Read(data []byte) (int, error) {
  1163  	n, err := archive.File.Read(data)
  1164  	archive.read += int64(n)
  1165  	if err != nil || archive.read == archive.Size {
  1166  		archive.Close()
  1167  		os.Remove(archive.File.Name())
  1168  	}
  1169  	return n, err
  1170  }