archive.go 18 KB

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