archive_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. package archive
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "syscall"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  16. )
  17. func TestCmdStreamLargeStderr(t *testing.T) {
  18. cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
  19. out, err := CmdStream(cmd, nil)
  20. if err != nil {
  21. t.Fatalf("Failed to start command: %s", err)
  22. }
  23. errCh := make(chan error)
  24. go func() {
  25. _, err := io.Copy(ioutil.Discard, out)
  26. errCh <- err
  27. }()
  28. select {
  29. case err := <-errCh:
  30. if err != nil {
  31. t.Fatalf("Command should not have failed (err=%.100s...)", err)
  32. }
  33. case <-time.After(5 * time.Second):
  34. t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
  35. }
  36. }
  37. func TestCmdStreamBad(t *testing.T) {
  38. badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
  39. out, err := CmdStream(badCmd, nil)
  40. if err != nil {
  41. t.Fatalf("Failed to start command: %s", err)
  42. }
  43. if output, err := ioutil.ReadAll(out); err == nil {
  44. t.Fatalf("Command should have failed")
  45. } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
  46. t.Fatalf("Wrong error value (%s)", err)
  47. } else if s := string(output); s != "hello\n" {
  48. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  49. }
  50. }
  51. func TestCmdStreamGood(t *testing.T) {
  52. cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0")
  53. out, err := CmdStream(cmd, nil)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. if output, err := ioutil.ReadAll(out); err != nil {
  58. t.Fatalf("Command should not have failed (err=%s)", err)
  59. } else if s := string(output); s != "hello\n" {
  60. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  61. }
  62. }
  63. func TestTarFiles(t *testing.T) {
  64. // try without hardlinks
  65. if err := checkNoChanges(1000, false); err != nil {
  66. t.Fatal(err)
  67. }
  68. // try with hardlinks
  69. if err := checkNoChanges(1000, true); err != nil {
  70. t.Fatal(err)
  71. }
  72. }
  73. func checkNoChanges(fileNum int, hardlinks bool) error {
  74. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  75. if err != nil {
  76. return err
  77. }
  78. defer os.RemoveAll(srcDir)
  79. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  80. if err != nil {
  81. return err
  82. }
  83. defer os.RemoveAll(destDir)
  84. _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
  85. if err != nil {
  86. return err
  87. }
  88. err = TarUntar(srcDir, destDir)
  89. if err != nil {
  90. return err
  91. }
  92. changes, err := ChangesDirs(destDir, srcDir)
  93. if err != nil {
  94. return err
  95. }
  96. if len(changes) > 0 {
  97. return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
  98. }
  99. return nil
  100. }
  101. func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
  102. archive, err := TarWithOptions(origin, options)
  103. if err != nil {
  104. t.Fatal(err)
  105. }
  106. defer archive.Close()
  107. buf := make([]byte, 10)
  108. if _, err := archive.Read(buf); err != nil {
  109. return nil, err
  110. }
  111. wrap := io.MultiReader(bytes.NewReader(buf), archive)
  112. detectedCompression := DetectCompression(buf)
  113. compression := options.Compression
  114. if detectedCompression.Extension() != compression.Extension() {
  115. return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
  116. }
  117. tmp, err := ioutil.TempDir("", "docker-test-untar")
  118. if err != nil {
  119. return nil, err
  120. }
  121. defer os.RemoveAll(tmp)
  122. if err := Untar(wrap, tmp, nil); err != nil {
  123. return nil, err
  124. }
  125. if _, err := os.Stat(tmp); err != nil {
  126. return nil, err
  127. }
  128. return ChangesDirs(origin, tmp)
  129. }
  130. func TestTarUntar(t *testing.T) {
  131. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  132. if err != nil {
  133. t.Fatal(err)
  134. }
  135. defer os.RemoveAll(origin)
  136. if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  137. t.Fatal(err)
  138. }
  139. if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  140. t.Fatal(err)
  141. }
  142. if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
  143. t.Fatal(err)
  144. }
  145. for _, c := range []Compression{
  146. Uncompressed,
  147. Gzip,
  148. } {
  149. changes, err := tarUntar(t, origin, &TarOptions{
  150. Compression: c,
  151. Excludes: []string{"3"},
  152. })
  153. if err != nil {
  154. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  155. }
  156. if len(changes) != 1 || changes[0].Path != "/3" {
  157. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  158. }
  159. }
  160. }
  161. func TestTarWithOptions(t *testing.T) {
  162. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  163. if err != nil {
  164. t.Fatal(err)
  165. }
  166. defer os.RemoveAll(origin)
  167. if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  168. t.Fatal(err)
  169. }
  170. if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  171. t.Fatal(err)
  172. }
  173. cases := []struct {
  174. opts *TarOptions
  175. numChanges int
  176. }{
  177. {&TarOptions{Includes: []string{"1"}}, 1},
  178. {&TarOptions{Excludes: []string{"2"}}, 1},
  179. }
  180. for _, testCase := range cases {
  181. changes, err := tarUntar(t, origin, testCase.opts)
  182. if err != nil {
  183. t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
  184. }
  185. if len(changes) != testCase.numChanges {
  186. t.Errorf("Expected %d changes, got %d for %+v:",
  187. testCase.numChanges, len(changes), testCase.opts)
  188. }
  189. }
  190. }
  191. // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
  192. // use PAX Global Extended Headers.
  193. // Failing prevents the archives from being uncompressed during ADD
  194. func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
  195. hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
  196. tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. defer os.RemoveAll(tmpDir)
  201. err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true)
  202. if err != nil {
  203. t.Fatal(err)
  204. }
  205. }
  206. // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
  207. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
  208. func TestUntarUstarGnuConflict(t *testing.T) {
  209. f, err := os.Open("testdata/broken.tar")
  210. if err != nil {
  211. t.Fatal(err)
  212. }
  213. found := false
  214. tr := tar.NewReader(f)
  215. // Iterate through the files in the archive.
  216. for {
  217. hdr, err := tr.Next()
  218. if err == io.EOF {
  219. // end of tar archive
  220. break
  221. }
  222. if err != nil {
  223. t.Fatal(err)
  224. }
  225. if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
  226. found = true
  227. break
  228. }
  229. }
  230. if !found {
  231. t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
  232. }
  233. }
  234. func TestTarWithHardLink(t *testing.T) {
  235. origin, err := ioutil.TempDir("", "docker-test-tar-hardlink")
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. defer os.RemoveAll(origin)
  240. if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  241. t.Fatal(err)
  242. }
  243. if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil {
  244. t.Fatal(err)
  245. }
  246. var i1, i2 uint64
  247. if i1, err = getNlink(path.Join(origin, "1")); err != nil {
  248. t.Fatal(err)
  249. }
  250. // sanity check that we can hardlink
  251. if i1 != 2 {
  252. t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1)
  253. }
  254. dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest")
  255. if err != nil {
  256. t.Fatal(err)
  257. }
  258. defer os.RemoveAll(dest)
  259. // we'll do this in two steps to separate failure
  260. fh, err := Tar(origin, Uncompressed)
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. // ensure we can read the whole thing with no error, before writing back out
  265. buf, err := ioutil.ReadAll(fh)
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. bRdr := bytes.NewReader(buf)
  270. err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed})
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. if i1, err = getInode(path.Join(dest, "1")); err != nil {
  275. t.Fatal(err)
  276. }
  277. if i2, err = getInode(path.Join(dest, "2")); err != nil {
  278. t.Fatal(err)
  279. }
  280. if i1 != i2 {
  281. t.Errorf("expected matching inodes, but got %d and %d", i1, i2)
  282. }
  283. }
  284. func getNlink(path string) (uint64, error) {
  285. stat, err := os.Stat(path)
  286. if err != nil {
  287. return 0, err
  288. }
  289. statT, ok := stat.Sys().(*syscall.Stat_t)
  290. if !ok {
  291. return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys())
  292. }
  293. return statT.Nlink, nil
  294. }
  295. func getInode(path string) (uint64, error) {
  296. stat, err := os.Stat(path)
  297. if err != nil {
  298. return 0, err
  299. }
  300. statT, ok := stat.Sys().(*syscall.Stat_t)
  301. if !ok {
  302. return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys())
  303. }
  304. return statT.Ino, nil
  305. }
  306. func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
  307. fileData := []byte("fooo")
  308. for n := 0; n < numberOfFiles; n++ {
  309. fileName := fmt.Sprintf("file-%d", n)
  310. if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil {
  311. return 0, err
  312. }
  313. if makeLinks {
  314. if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil {
  315. return 0, err
  316. }
  317. }
  318. }
  319. totalSize := numberOfFiles * len(fileData)
  320. return totalSize, nil
  321. }
  322. func BenchmarkTarUntar(b *testing.B) {
  323. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  324. if err != nil {
  325. b.Fatal(err)
  326. }
  327. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  328. if err != nil {
  329. b.Fatal(err)
  330. }
  331. target := path.Join(tempDir, "dest")
  332. n, err := prepareUntarSourceDirectory(100, origin, false)
  333. if err != nil {
  334. b.Fatal(err)
  335. }
  336. defer os.RemoveAll(origin)
  337. defer os.RemoveAll(tempDir)
  338. b.ResetTimer()
  339. b.SetBytes(int64(n))
  340. for n := 0; n < b.N; n++ {
  341. err := TarUntar(origin, target)
  342. if err != nil {
  343. b.Fatal(err)
  344. }
  345. os.RemoveAll(target)
  346. }
  347. }
  348. func BenchmarkTarUntarWithLinks(b *testing.B) {
  349. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  350. if err != nil {
  351. b.Fatal(err)
  352. }
  353. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  354. if err != nil {
  355. b.Fatal(err)
  356. }
  357. target := path.Join(tempDir, "dest")
  358. n, err := prepareUntarSourceDirectory(100, origin, true)
  359. if err != nil {
  360. b.Fatal(err)
  361. }
  362. defer os.RemoveAll(origin)
  363. defer os.RemoveAll(tempDir)
  364. b.ResetTimer()
  365. b.SetBytes(int64(n))
  366. for n := 0; n < b.N; n++ {
  367. err := TarUntar(origin, target)
  368. if err != nil {
  369. b.Fatal(err)
  370. }
  371. os.RemoveAll(target)
  372. }
  373. }
  374. func TestUntarInvalidFilenames(t *testing.T) {
  375. for i, headers := range [][]*tar.Header{
  376. {
  377. {
  378. Name: "../victim/dotdot",
  379. Typeflag: tar.TypeReg,
  380. Mode: 0644,
  381. },
  382. },
  383. {
  384. {
  385. // Note the leading slash
  386. Name: "/../victim/slash-dotdot",
  387. Typeflag: tar.TypeReg,
  388. Mode: 0644,
  389. },
  390. },
  391. } {
  392. if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
  393. t.Fatalf("i=%d. %v", i, err)
  394. }
  395. }
  396. }
  397. func TestUntarInvalidHardlink(t *testing.T) {
  398. for i, headers := range [][]*tar.Header{
  399. { // try reading victim/hello (../)
  400. {
  401. Name: "dotdot",
  402. Typeflag: tar.TypeLink,
  403. Linkname: "../victim/hello",
  404. Mode: 0644,
  405. },
  406. },
  407. { // try reading victim/hello (/../)
  408. {
  409. Name: "slash-dotdot",
  410. Typeflag: tar.TypeLink,
  411. // Note the leading slash
  412. Linkname: "/../victim/hello",
  413. Mode: 0644,
  414. },
  415. },
  416. { // try writing victim/file
  417. {
  418. Name: "loophole-victim",
  419. Typeflag: tar.TypeLink,
  420. Linkname: "../victim",
  421. Mode: 0755,
  422. },
  423. {
  424. Name: "loophole-victim/file",
  425. Typeflag: tar.TypeReg,
  426. Mode: 0644,
  427. },
  428. },
  429. { // try reading victim/hello (hardlink, symlink)
  430. {
  431. Name: "loophole-victim",
  432. Typeflag: tar.TypeLink,
  433. Linkname: "../victim",
  434. Mode: 0755,
  435. },
  436. {
  437. Name: "symlink",
  438. Typeflag: tar.TypeSymlink,
  439. Linkname: "loophole-victim/hello",
  440. Mode: 0644,
  441. },
  442. },
  443. { // Try reading victim/hello (hardlink, hardlink)
  444. {
  445. Name: "loophole-victim",
  446. Typeflag: tar.TypeLink,
  447. Linkname: "../victim",
  448. Mode: 0755,
  449. },
  450. {
  451. Name: "hardlink",
  452. Typeflag: tar.TypeLink,
  453. Linkname: "loophole-victim/hello",
  454. Mode: 0644,
  455. },
  456. },
  457. { // Try removing victim directory (hardlink)
  458. {
  459. Name: "loophole-victim",
  460. Typeflag: tar.TypeLink,
  461. Linkname: "../victim",
  462. Mode: 0755,
  463. },
  464. {
  465. Name: "loophole-victim",
  466. Typeflag: tar.TypeReg,
  467. Mode: 0644,
  468. },
  469. },
  470. } {
  471. if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
  472. t.Fatalf("i=%d. %v", i, err)
  473. }
  474. }
  475. }
  476. func TestUntarInvalidSymlink(t *testing.T) {
  477. for i, headers := range [][]*tar.Header{
  478. { // try reading victim/hello (../)
  479. {
  480. Name: "dotdot",
  481. Typeflag: tar.TypeSymlink,
  482. Linkname: "../victim/hello",
  483. Mode: 0644,
  484. },
  485. },
  486. { // try reading victim/hello (/../)
  487. {
  488. Name: "slash-dotdot",
  489. Typeflag: tar.TypeSymlink,
  490. // Note the leading slash
  491. Linkname: "/../victim/hello",
  492. Mode: 0644,
  493. },
  494. },
  495. { // try writing victim/file
  496. {
  497. Name: "loophole-victim",
  498. Typeflag: tar.TypeSymlink,
  499. Linkname: "../victim",
  500. Mode: 0755,
  501. },
  502. {
  503. Name: "loophole-victim/file",
  504. Typeflag: tar.TypeReg,
  505. Mode: 0644,
  506. },
  507. },
  508. { // try reading victim/hello (symlink, symlink)
  509. {
  510. Name: "loophole-victim",
  511. Typeflag: tar.TypeSymlink,
  512. Linkname: "../victim",
  513. Mode: 0755,
  514. },
  515. {
  516. Name: "symlink",
  517. Typeflag: tar.TypeSymlink,
  518. Linkname: "loophole-victim/hello",
  519. Mode: 0644,
  520. },
  521. },
  522. { // try reading victim/hello (symlink, hardlink)
  523. {
  524. Name: "loophole-victim",
  525. Typeflag: tar.TypeSymlink,
  526. Linkname: "../victim",
  527. Mode: 0755,
  528. },
  529. {
  530. Name: "hardlink",
  531. Typeflag: tar.TypeLink,
  532. Linkname: "loophole-victim/hello",
  533. Mode: 0644,
  534. },
  535. },
  536. { // try removing victim directory (symlink)
  537. {
  538. Name: "loophole-victim",
  539. Typeflag: tar.TypeSymlink,
  540. Linkname: "../victim",
  541. Mode: 0755,
  542. },
  543. {
  544. Name: "loophole-victim",
  545. Typeflag: tar.TypeReg,
  546. Mode: 0644,
  547. },
  548. },
  549. { // try writing to victim/newdir/newfile with a symlink in the path
  550. {
  551. // this header needs to be before the next one, or else there is an error
  552. Name: "dir/loophole",
  553. Typeflag: tar.TypeSymlink,
  554. Linkname: "../../victim",
  555. Mode: 0755,
  556. },
  557. {
  558. Name: "dir/loophole/newdir/newfile",
  559. Typeflag: tar.TypeReg,
  560. Mode: 0644,
  561. },
  562. },
  563. } {
  564. if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
  565. t.Fatalf("i=%d. %v", i, err)
  566. }
  567. }
  568. }
  569. func TestTempArchiveCloseMultipleTimes(t *testing.T) {
  570. reader := ioutil.NopCloser(strings.NewReader("hello"))
  571. tempArchive, err := NewTempArchive(reader, "")
  572. buf := make([]byte, 10)
  573. n, err := tempArchive.Read(buf)
  574. if n != 5 {
  575. t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
  576. }
  577. for i := 0; i < 3; i++ {
  578. if err = tempArchive.Close(); err != nil {
  579. t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
  580. }
  581. }
  582. }