archive.go 21 KB

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