archive.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package archive
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/bzip2"
  6. "compress/gzip"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "strings"
  16. "syscall"
  17. "github.com/dotcloud/docker/pkg/system"
  18. "github.com/dotcloud/docker/utils"
  19. "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  20. )
  21. type (
  22. Archive io.ReadCloser
  23. ArchiveReader io.Reader
  24. Compression int
  25. TarOptions struct {
  26. Includes []string
  27. Excludes []string
  28. Compression Compression
  29. NoLchown bool
  30. }
  31. )
  32. var (
  33. ErrNotImplemented = errors.New("Function not implemented")
  34. )
  35. const (
  36. Uncompressed Compression = iota
  37. Bzip2
  38. Gzip
  39. Xz
  40. )
  41. func IsArchive(header []byte) bool {
  42. compression := DetectCompression(header)
  43. if compression != Uncompressed {
  44. return true
  45. }
  46. r := tar.NewReader(bytes.NewBuffer(header))
  47. _, err := r.Next()
  48. return err == nil
  49. }
  50. func DetectCompression(source []byte) Compression {
  51. for compression, m := range map[Compression][]byte{
  52. Bzip2: {0x42, 0x5A, 0x68},
  53. Gzip: {0x1F, 0x8B, 0x08},
  54. Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
  55. } {
  56. if len(source) < len(m) {
  57. utils.Debugf("Len too short")
  58. continue
  59. }
  60. if bytes.Compare(m, source[:len(m)]) == 0 {
  61. return compression
  62. }
  63. }
  64. return Uncompressed
  65. }
  66. func xzDecompress(archive io.Reader) (io.ReadCloser, error) {
  67. args := []string{"xz", "-d", "-c", "-q"}
  68. return CmdStream(exec.Command(args[0], args[1:]...), archive)
  69. }
  70. func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
  71. buf := bufio.NewReader(archive)
  72. bs, err := buf.Peek(10)
  73. if err != nil {
  74. return nil, err
  75. }
  76. utils.Debugf("[tar autodetect] n: %v", bs)
  77. compression := DetectCompression(bs)
  78. switch compression {
  79. case Uncompressed:
  80. return ioutil.NopCloser(buf), nil
  81. case Gzip:
  82. return gzip.NewReader(buf)
  83. case Bzip2:
  84. return ioutil.NopCloser(bzip2.NewReader(buf)), nil
  85. case Xz:
  86. return xzDecompress(buf)
  87. default:
  88. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  89. }
  90. }
  91. func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) {
  92. switch compression {
  93. case Uncompressed:
  94. return utils.NopWriteCloser(dest), nil
  95. case Gzip:
  96. return gzip.NewWriter(dest), nil
  97. case Bzip2, Xz:
  98. // archive/bzip2 does not support writing, and there is no xz support at all
  99. // However, this is not a problem as docker only currently generates gzipped tars
  100. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  101. default:
  102. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  103. }
  104. }
  105. func (compression *Compression) Extension() string {
  106. switch *compression {
  107. case Uncompressed:
  108. return "tar"
  109. case Bzip2:
  110. return "tar.bz2"
  111. case Gzip:
  112. return "tar.gz"
  113. case Xz:
  114. return "tar.xz"
  115. }
  116. return ""
  117. }
  118. func addTarFile(path, name string, tw *tar.Writer, twBuf *bufio.Writer) error {
  119. fi, err := os.Lstat(path)
  120. if err != nil {
  121. return err
  122. }
  123. link := ""
  124. if fi.Mode()&os.ModeSymlink != 0 {
  125. if link, err = os.Readlink(path); err != nil {
  126. return err
  127. }
  128. }
  129. hdr, err := tar.FileInfoHeader(fi, link)
  130. if err != nil {
  131. return err
  132. }
  133. if fi.IsDir() && !strings.HasSuffix(name, "/") {
  134. name = name + "/"
  135. }
  136. hdr.Name = name
  137. stat, ok := fi.Sys().(*syscall.Stat_t)
  138. if ok {
  139. // Currently go does not fill in the major/minors
  140. if stat.Mode&syscall.S_IFBLK == syscall.S_IFBLK ||
  141. stat.Mode&syscall.S_IFCHR == syscall.S_IFCHR {
  142. hdr.Devmajor = int64(major(uint64(stat.Rdev)))
  143. hdr.Devminor = int64(minor(uint64(stat.Rdev)))
  144. }
  145. }
  146. capability, _ := system.Lgetxattr(path, "security.capability")
  147. if capability != nil {
  148. hdr.Xattrs = make(map[string]string)
  149. hdr.Xattrs["security.capability"] = string(capability)
  150. }
  151. if err := tw.WriteHeader(hdr); err != nil {
  152. return err
  153. }
  154. if hdr.Typeflag == tar.TypeReg {
  155. file, err := os.Open(path)
  156. if err != nil {
  157. return err
  158. }
  159. twBuf.Reset(tw)
  160. _, err = io.Copy(twBuf, file)
  161. file.Close()
  162. if err != nil {
  163. return err
  164. }
  165. err = twBuf.Flush()
  166. if err != nil {
  167. return err
  168. }
  169. twBuf.Reset(nil)
  170. }
  171. return nil
  172. }
  173. func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool) error {
  174. // hdr.Mode is in linux format, which we can use for sycalls,
  175. // but for os.Foo() calls we need the mode converted to os.FileMode,
  176. // so use hdrInfo.Mode() (they differ for e.g. setuid bits)
  177. hdrInfo := hdr.FileInfo()
  178. switch hdr.Typeflag {
  179. case tar.TypeDir:
  180. // Create directory unless it exists as a directory already.
  181. // In that case we just want to merge the two
  182. if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
  183. if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
  184. return err
  185. }
  186. }
  187. case tar.TypeReg, tar.TypeRegA:
  188. // Source is regular file
  189. file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
  190. if err != nil {
  191. return err
  192. }
  193. if _, err := io.Copy(file, reader); err != nil {
  194. file.Close()
  195. return err
  196. }
  197. file.Close()
  198. case tar.TypeBlock, tar.TypeChar, tar.TypeFifo:
  199. mode := uint32(hdr.Mode & 07777)
  200. switch hdr.Typeflag {
  201. case tar.TypeBlock:
  202. mode |= syscall.S_IFBLK
  203. case tar.TypeChar:
  204. mode |= syscall.S_IFCHR
  205. case tar.TypeFifo:
  206. mode |= syscall.S_IFIFO
  207. }
  208. if err := syscall.Mknod(path, mode, int(mkdev(hdr.Devmajor, hdr.Devminor))); err != nil {
  209. return err
  210. }
  211. case tar.TypeLink:
  212. if err := os.Link(filepath.Join(extractDir, hdr.Linkname), path); err != nil {
  213. return err
  214. }
  215. case tar.TypeSymlink:
  216. if err := os.Symlink(hdr.Linkname, path); err != nil {
  217. return err
  218. }
  219. case tar.TypeXGlobalHeader:
  220. utils.Debugf("PAX Global Extended Headers found and ignored")
  221. return nil
  222. default:
  223. return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag)
  224. }
  225. if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil && Lchown {
  226. return err
  227. }
  228. for key, value := range hdr.Xattrs {
  229. if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil {
  230. return err
  231. }
  232. }
  233. // There is no LChmod, so ignore mode for symlink. Also, this
  234. // must happen after chown, as that can modify the file mode
  235. if hdr.Typeflag != tar.TypeSymlink {
  236. if err := os.Chmod(path, hdrInfo.Mode()); err != nil {
  237. return err
  238. }
  239. }
  240. ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
  241. // syscall.UtimesNano doesn't support a NOFOLLOW flag atm, and
  242. if hdr.Typeflag != tar.TypeSymlink {
  243. if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
  244. return err
  245. }
  246. } else {
  247. if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
  248. return err
  249. }
  250. }
  251. return nil
  252. }
  253. // Tar creates an archive from the directory at `path`, and returns it as a
  254. // stream of bytes.
  255. func Tar(path string, compression Compression) (io.ReadCloser, error) {
  256. return TarWithOptions(path, &TarOptions{Compression: compression})
  257. }
  258. func escapeName(name string) string {
  259. escaped := make([]byte, 0)
  260. for i, c := range []byte(name) {
  261. if i == 0 && c == '/' {
  262. continue
  263. }
  264. // all printable chars except "-" which is 0x2d
  265. if (0x20 <= c && c <= 0x7E) && c != 0x2d {
  266. escaped = append(escaped, c)
  267. } else {
  268. escaped = append(escaped, fmt.Sprintf("\\%03o", c)...)
  269. }
  270. }
  271. return string(escaped)
  272. }
  273. // TarWithOptions creates an archive from the directory at `path`, only including files whose relative
  274. // paths are included in `options.Includes` (if non-nil) or not in `options.Excludes`.
  275. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) {
  276. pipeReader, pipeWriter := io.Pipe()
  277. compressWriter, err := CompressStream(pipeWriter, options.Compression)
  278. if err != nil {
  279. return nil, err
  280. }
  281. tw := tar.NewWriter(compressWriter)
  282. go func() {
  283. // In general we log errors here but ignore them because
  284. // during e.g. a diff operation the container can continue
  285. // mutating the filesystem and we can see transient errors
  286. // from this
  287. if options.Includes == nil {
  288. options.Includes = []string{"."}
  289. }
  290. twBuf := bufio.NewWriterSize(nil, twBufSize)
  291. for _, include := range options.Includes {
  292. filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error {
  293. if err != nil {
  294. utils.Debugf("Tar: Can't stat file %s to tar: %s\n", srcPath, err)
  295. return nil
  296. }
  297. relFilePath, err := filepath.Rel(srcPath, filePath)
  298. if err != nil {
  299. return nil
  300. }
  301. for _, exclude := range options.Excludes {
  302. matched, err := filepath.Match(exclude, relFilePath)
  303. if err != nil {
  304. utils.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude)
  305. return err
  306. }
  307. if matched {
  308. utils.Debugf("Skipping excluded path: %s", relFilePath)
  309. if f.IsDir() {
  310. return filepath.SkipDir
  311. }
  312. return nil
  313. }
  314. }
  315. if err := addTarFile(filePath, relFilePath, tw, twBuf); err != nil {
  316. utils.Debugf("Can't add file %s to tar: %s\n", srcPath, err)
  317. }
  318. return nil
  319. })
  320. }
  321. // Make sure to check the error on Close.
  322. if err := tw.Close(); err != nil {
  323. utils.Debugf("Can't close tar writer: %s\n", err)
  324. }
  325. if err := compressWriter.Close(); err != nil {
  326. utils.Debugf("Can't close compress writer: %s\n", err)
  327. }
  328. if err := pipeWriter.Close(); err != nil {
  329. utils.Debugf("Can't close pipe writer: %s\n", err)
  330. }
  331. }()
  332. return pipeReader, nil
  333. }
  334. // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
  335. // and unpacks it into the directory at `path`.
  336. // The archive may be compressed with one of the following algorithms:
  337. // identity (uncompressed), gzip, bzip2, xz.
  338. // FIXME: specify behavior when target path exists vs. doesn't exist.
  339. func Untar(archive io.Reader, dest string, options *TarOptions) error {
  340. if archive == nil {
  341. return fmt.Errorf("Empty archive")
  342. }
  343. decompressedArchive, err := DecompressStream(archive)
  344. if err != nil {
  345. return err
  346. }
  347. defer decompressedArchive.Close()
  348. tr := tar.NewReader(decompressedArchive)
  349. trBuf := bufio.NewReaderSize(nil, trBufSize)
  350. var dirs []*tar.Header
  351. // Iterate through the files in the archive.
  352. for {
  353. hdr, err := tr.Next()
  354. if err == io.EOF {
  355. // end of tar archive
  356. break
  357. }
  358. if err != nil {
  359. return err
  360. }
  361. // Normalize name, for safety and for a simple is-root check
  362. hdr.Name = filepath.Clean(hdr.Name)
  363. if !strings.HasSuffix(hdr.Name, "/") {
  364. // Not the root directory, ensure that the parent directory exists
  365. parent := filepath.Dir(hdr.Name)
  366. parentPath := filepath.Join(dest, parent)
  367. if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
  368. err = os.MkdirAll(parentPath, 0777)
  369. if err != nil {
  370. return err
  371. }
  372. }
  373. }
  374. path := filepath.Join(dest, hdr.Name)
  375. // If path exits we almost always just want to remove and replace it
  376. // The only exception is when it is a directory *and* the file from
  377. // the layer is also a directory. Then we want to merge them (i.e.
  378. // just apply the metadata from the layer).
  379. if fi, err := os.Lstat(path); err == nil {
  380. if fi.IsDir() && hdr.Name == "." {
  381. continue
  382. }
  383. if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
  384. if err := os.RemoveAll(path); err != nil {
  385. return err
  386. }
  387. }
  388. }
  389. trBuf.Reset(tr)
  390. if err := createTarFile(path, dest, hdr, trBuf, options == nil || !options.NoLchown); err != nil {
  391. return err
  392. }
  393. // Directory mtimes must be handled at the end to avoid further
  394. // file creation in them to modify the directory mtime
  395. if hdr.Typeflag == tar.TypeDir {
  396. dirs = append(dirs, hdr)
  397. }
  398. }
  399. for _, hdr := range dirs {
  400. path := filepath.Join(dest, hdr.Name)
  401. ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
  402. if err := syscall.UtimesNano(path, ts); err != nil {
  403. return err
  404. }
  405. }
  406. return nil
  407. }
  408. // TarUntar is a convenience function which calls Tar and Untar, with
  409. // the output of one piped into the other. If either Tar or Untar fails,
  410. // TarUntar aborts and returns the error.
  411. func TarUntar(src string, dst string) error {
  412. utils.Debugf("TarUntar(%s %s)", src, dst)
  413. archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
  414. if err != nil {
  415. return err
  416. }
  417. defer archive.Close()
  418. return Untar(archive, dst, nil)
  419. }
  420. // UntarPath is a convenience function which looks for an archive
  421. // at filesystem path `src`, and unpacks it at `dst`.
  422. func UntarPath(src, dst string) error {
  423. archive, err := os.Open(src)
  424. if err != nil {
  425. return err
  426. }
  427. defer archive.Close()
  428. if err := Untar(archive, dst, nil); err != nil {
  429. return err
  430. }
  431. return nil
  432. }
  433. // CopyWithTar creates a tar archive of filesystem path `src`, and
  434. // unpacks it at filesystem path `dst`.
  435. // The archive is streamed directly with fixed buffering and no
  436. // intermediary disk IO.
  437. //
  438. func CopyWithTar(src, dst string) error {
  439. srcSt, err := os.Stat(src)
  440. if err != nil {
  441. return err
  442. }
  443. if !srcSt.IsDir() {
  444. return CopyFileWithTar(src, dst)
  445. }
  446. // Create dst, copy src's content into it
  447. utils.Debugf("Creating dest directory: %s", dst)
  448. if err := os.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) {
  449. return err
  450. }
  451. utils.Debugf("Calling TarUntar(%s, %s)", src, dst)
  452. return TarUntar(src, dst)
  453. }
  454. // CopyFileWithTar emulates the behavior of the 'cp' command-line
  455. // for a single file. It copies a regular file from path `src` to
  456. // path `dst`, and preserves all its metadata.
  457. //
  458. // If `dst` ends with a trailing slash '/', the final destination path
  459. // will be `dst/base(src)`.
  460. func CopyFileWithTar(src, dst string) (err error) {
  461. utils.Debugf("CopyFileWithTar(%s, %s)", src, dst)
  462. srcSt, err := os.Stat(src)
  463. if err != nil {
  464. return err
  465. }
  466. if srcSt.IsDir() {
  467. return fmt.Errorf("Can't copy a directory")
  468. }
  469. // Clean up the trailing /
  470. if dst[len(dst)-1] == '/' {
  471. dst = path.Join(dst, filepath.Base(src))
  472. }
  473. // Create the holding directory if necessary
  474. if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  475. return err
  476. }
  477. r, w := io.Pipe()
  478. errC := utils.Go(func() error {
  479. defer w.Close()
  480. srcF, err := os.Open(src)
  481. if err != nil {
  482. return err
  483. }
  484. defer srcF.Close()
  485. hdr, err := tar.FileInfoHeader(srcSt, "")
  486. if err != nil {
  487. return err
  488. }
  489. hdr.Name = filepath.Base(dst)
  490. tw := tar.NewWriter(w)
  491. defer tw.Close()
  492. if err := tw.WriteHeader(hdr); err != nil {
  493. return err
  494. }
  495. if _, err := io.Copy(tw, srcF); err != nil {
  496. return err
  497. }
  498. return nil
  499. })
  500. defer func() {
  501. if er := <-errC; err != nil {
  502. err = er
  503. }
  504. }()
  505. return Untar(r, filepath.Dir(dst), nil)
  506. }
  507. // CmdStream executes a command, and returns its stdout as a stream.
  508. // If the command fails to run or doesn't complete successfully, an error
  509. // will be returned, including anything written on stderr.
  510. func CmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
  511. if input != nil {
  512. stdin, err := cmd.StdinPipe()
  513. if err != nil {
  514. return nil, err
  515. }
  516. // Write stdin if any
  517. go func() {
  518. io.Copy(stdin, input)
  519. stdin.Close()
  520. }()
  521. }
  522. stdout, err := cmd.StdoutPipe()
  523. if err != nil {
  524. return nil, err
  525. }
  526. stderr, err := cmd.StderrPipe()
  527. if err != nil {
  528. return nil, err
  529. }
  530. pipeR, pipeW := io.Pipe()
  531. errChan := make(chan []byte)
  532. // Collect stderr, we will use it in case of an error
  533. go func() {
  534. errText, e := ioutil.ReadAll(stderr)
  535. if e != nil {
  536. errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
  537. }
  538. errChan <- errText
  539. }()
  540. // Copy stdout to the returned pipe
  541. go func() {
  542. _, err := io.Copy(pipeW, stdout)
  543. if err != nil {
  544. pipeW.CloseWithError(err)
  545. }
  546. errText := <-errChan
  547. if err := cmd.Wait(); err != nil {
  548. pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errText))
  549. } else {
  550. pipeW.Close()
  551. }
  552. }()
  553. // Run the command and return the pipe
  554. if err := cmd.Start(); err != nil {
  555. return nil, err
  556. }
  557. return pipeR, nil
  558. }
  559. // NewTempArchive reads the content of src into a temporary file, and returns the contents
  560. // of that file as an archive. The archive can only be read once - as soon as reading completes,
  561. // the file will be deleted.
  562. func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
  563. f, err := ioutil.TempFile(dir, "")
  564. if err != nil {
  565. return nil, err
  566. }
  567. if _, err := io.Copy(f, src); err != nil {
  568. return nil, err
  569. }
  570. if err = f.Sync(); err != nil {
  571. return nil, err
  572. }
  573. if _, err := f.Seek(0, 0); err != nil {
  574. return nil, err
  575. }
  576. st, err := f.Stat()
  577. if err != nil {
  578. return nil, err
  579. }
  580. size := st.Size()
  581. return &TempArchive{f, size}, nil
  582. }
  583. type TempArchive struct {
  584. *os.File
  585. Size int64 // Pre-computed from Stat().Size() as a convenience
  586. }
  587. func (archive *TempArchive) Read(data []byte) (int, error) {
  588. n, err := archive.File.Read(data)
  589. if err != nil {
  590. os.Remove(archive.File.Name())
  591. }
  592. return n, err
  593. }