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