archive_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. package archive
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "testing"
  14. "time"
  15. )
  16. var tmp string
  17. func init() {
  18. tmp = "/tmp/"
  19. if runtime.GOOS == "windows" {
  20. tmp = os.Getenv("TEMP") + `\`
  21. }
  22. }
  23. func TestIsArchiveNilHeader(t *testing.T) {
  24. out := IsArchive(nil)
  25. if out {
  26. t.Fatalf("isArchive should return false as nil is not a valid archive header")
  27. }
  28. }
  29. func TestIsArchiveInvalidHeader(t *testing.T) {
  30. header := []byte{0x00, 0x01, 0x02}
  31. out := IsArchive(header)
  32. if out {
  33. t.Fatalf("isArchive should return false as %s is not a valid archive header", header)
  34. }
  35. }
  36. func TestIsArchiveBzip2(t *testing.T) {
  37. header := []byte{0x42, 0x5A, 0x68}
  38. out := IsArchive(header)
  39. if !out {
  40. t.Fatalf("isArchive should return true as %s is a bz2 header", header)
  41. }
  42. }
  43. func TestIsArchive7zip(t *testing.T) {
  44. header := []byte{0x50, 0x4b, 0x03, 0x04}
  45. out := IsArchive(header)
  46. if out {
  47. t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header)
  48. }
  49. }
  50. func TestIsArchivePathDir(t *testing.T) {
  51. cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
  52. output, err := cmd.CombinedOutput()
  53. if err != nil {
  54. t.Fatalf("Fail to create an archive file for test : %s.", output)
  55. }
  56. if IsArchivePath(tmp + "archivedir") {
  57. t.Fatalf("Incorrectly recognised directory as an archive")
  58. }
  59. }
  60. func TestIsArchivePathInvalidFile(t *testing.T) {
  61. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1K count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
  62. output, err := cmd.CombinedOutput()
  63. if err != nil {
  64. t.Fatalf("Fail to create an archive file for test : %s.", output)
  65. }
  66. if IsArchivePath(tmp + "archive") {
  67. t.Fatalf("Incorrectly recognised invalid tar path as archive")
  68. }
  69. if IsArchivePath(tmp + "archive.gz") {
  70. t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
  71. }
  72. }
  73. func TestIsArchivePathTar(t *testing.T) {
  74. cmd := exec.Command("sh", "-c", "touch /tmp/archivedata && tar -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz")
  75. output, err := cmd.CombinedOutput()
  76. if err != nil {
  77. t.Fatalf("Fail to create an archive file for test : %s.", output)
  78. }
  79. if !IsArchivePath(tmp + "/archive") {
  80. t.Fatalf("Did not recognise valid tar path as archive")
  81. }
  82. if !IsArchivePath(tmp + "archive.gz") {
  83. t.Fatalf("Did not recognise valid compressed tar path as archive")
  84. }
  85. }
  86. func TestDecompressStreamGzip(t *testing.T) {
  87. cmd := exec.Command("sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive")
  88. output, err := cmd.CombinedOutput()
  89. if err != nil {
  90. t.Fatalf("Fail to create an archive file for test : %s.", output)
  91. }
  92. archive, err := os.Open(tmp + "archive.gz")
  93. _, err = DecompressStream(archive)
  94. if err != nil {
  95. t.Fatalf("Failed to decompress a gzip file.")
  96. }
  97. }
  98. func TestDecompressStreamBzip2(t *testing.T) {
  99. cmd := exec.Command("sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive")
  100. output, err := cmd.CombinedOutput()
  101. if err != nil {
  102. t.Fatalf("Fail to create an archive file for test : %s.", output)
  103. }
  104. archive, err := os.Open(tmp + "archive.bz2")
  105. _, err = DecompressStream(archive)
  106. if err != nil {
  107. t.Fatalf("Failed to decompress a bzip2 file.")
  108. }
  109. }
  110. func TestDecompressStreamXz(t *testing.T) {
  111. if runtime.GOOS == "windows" {
  112. t.Skip("Xz not present in msys2")
  113. }
  114. cmd := exec.Command("sh", "-c", "touch /tmp/archive && xz -f /tmp/archive")
  115. output, err := cmd.CombinedOutput()
  116. if err != nil {
  117. t.Fatalf("Fail to create an archive file for test : %s.", output)
  118. }
  119. archive, err := os.Open(tmp + "archive.xz")
  120. _, err = DecompressStream(archive)
  121. if err != nil {
  122. t.Fatalf("Failed to decompress a xz file.")
  123. }
  124. }
  125. func TestCompressStreamXzUnsuported(t *testing.T) {
  126. dest, err := os.Create(tmp + "dest")
  127. if err != nil {
  128. t.Fatalf("Fail to create the destination file")
  129. }
  130. _, err = CompressStream(dest, Xz)
  131. if err == nil {
  132. t.Fatalf("Should fail as xz is unsupported for compression format.")
  133. }
  134. }
  135. func TestCompressStreamBzip2Unsupported(t *testing.T) {
  136. dest, err := os.Create(tmp + "dest")
  137. if err != nil {
  138. t.Fatalf("Fail to create the destination file")
  139. }
  140. _, err = CompressStream(dest, Xz)
  141. if err == nil {
  142. t.Fatalf("Should fail as xz is unsupported for compression format.")
  143. }
  144. }
  145. func TestCompressStreamInvalid(t *testing.T) {
  146. dest, err := os.Create(tmp + "dest")
  147. if err != nil {
  148. t.Fatalf("Fail to create the destination file")
  149. }
  150. _, err = CompressStream(dest, -1)
  151. if err == nil {
  152. t.Fatalf("Should fail as xz is unsupported for compression format.")
  153. }
  154. }
  155. func TestExtensionInvalid(t *testing.T) {
  156. compression := Compression(-1)
  157. output := compression.Extension()
  158. if output != "" {
  159. t.Fatalf("The extension of an invalid compression should be an empty string.")
  160. }
  161. }
  162. func TestExtensionUncompressed(t *testing.T) {
  163. compression := Uncompressed
  164. output := compression.Extension()
  165. if output != "tar" {
  166. t.Fatalf("The extension of a uncompressed archive should be 'tar'.")
  167. }
  168. }
  169. func TestExtensionBzip2(t *testing.T) {
  170. compression := Bzip2
  171. output := compression.Extension()
  172. if output != "tar.bz2" {
  173. t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
  174. }
  175. }
  176. func TestExtensionGzip(t *testing.T) {
  177. compression := Gzip
  178. output := compression.Extension()
  179. if output != "tar.gz" {
  180. t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
  181. }
  182. }
  183. func TestExtensionXz(t *testing.T) {
  184. compression := Xz
  185. output := compression.Extension()
  186. if output != "tar.xz" {
  187. t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
  188. }
  189. }
  190. func TestCmdStreamLargeStderr(t *testing.T) {
  191. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
  192. out, _, err := cmdStream(cmd, nil)
  193. if err != nil {
  194. t.Fatalf("Failed to start command: %s", err)
  195. }
  196. errCh := make(chan error)
  197. go func() {
  198. _, err := io.Copy(ioutil.Discard, out)
  199. errCh <- err
  200. }()
  201. select {
  202. case err := <-errCh:
  203. if err != nil {
  204. t.Fatalf("Command should not have failed (err=%.100s...)", err)
  205. }
  206. case <-time.After(5 * time.Second):
  207. t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
  208. }
  209. }
  210. func TestCmdStreamBad(t *testing.T) {
  211. badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
  212. out, _, err := cmdStream(badCmd, nil)
  213. if err != nil {
  214. t.Fatalf("Failed to start command: %s", err)
  215. }
  216. if output, err := ioutil.ReadAll(out); err == nil {
  217. t.Fatalf("Command should have failed")
  218. } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
  219. t.Fatalf("Wrong error value (%s)", err)
  220. } else if s := string(output); s != "hello\n" {
  221. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  222. }
  223. }
  224. func TestCmdStreamGood(t *testing.T) {
  225. cmd := exec.Command("sh", "-c", "echo hello; exit 0")
  226. out, _, err := cmdStream(cmd, nil)
  227. if err != nil {
  228. t.Fatal(err)
  229. }
  230. if output, err := ioutil.ReadAll(out); err != nil {
  231. t.Fatalf("Command should not have failed (err=%s)", err)
  232. } else if s := string(output); s != "hello\n" {
  233. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  234. }
  235. }
  236. func TestUntarPathWithInvalidDest(t *testing.T) {
  237. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  238. if err != nil {
  239. t.Fatal(err)
  240. }
  241. defer os.RemoveAll(tempFolder)
  242. invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
  243. // Create a src file
  244. srcFile := filepath.Join(tempFolder, "src")
  245. tarFile := filepath.Join(tempFolder, "src.tar")
  246. os.Create(srcFile)
  247. os.Create(invalidDestFolder) // being a file (not dir) should cause an error
  248. // Translate back to Unix semantics as next exec.Command is run under sh
  249. srcFileU := srcFile
  250. tarFileU := tarFile
  251. if runtime.GOOS == "windows" {
  252. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  253. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  254. }
  255. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  256. _, err = cmd.CombinedOutput()
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. err = UntarPath(tarFile, invalidDestFolder)
  261. if err == nil {
  262. t.Fatalf("UntarPath with invalid destination path should throw an error.")
  263. }
  264. }
  265. func TestUntarPathWithInvalidSrc(t *testing.T) {
  266. dest, err := ioutil.TempDir("", "docker-archive-test")
  267. if err != nil {
  268. t.Fatalf("Fail to create the destination file")
  269. }
  270. defer os.RemoveAll(dest)
  271. err = UntarPath("/invalid/path", dest)
  272. if err == nil {
  273. t.Fatalf("UntarPath with invalid src path should throw an error.")
  274. }
  275. }
  276. func TestUntarPath(t *testing.T) {
  277. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. defer os.RemoveAll(tmpFolder)
  282. srcFile := filepath.Join(tmpFolder, "src")
  283. tarFile := filepath.Join(tmpFolder, "src.tar")
  284. os.Create(filepath.Join(tmpFolder, "src"))
  285. destFolder := filepath.Join(tmpFolder, "dest")
  286. err = os.MkdirAll(destFolder, 0740)
  287. if err != nil {
  288. t.Fatalf("Fail to create the destination file")
  289. }
  290. // Translate back to Unix semantics as next exec.Command is run under sh
  291. srcFileU := srcFile
  292. tarFileU := tarFile
  293. if runtime.GOOS == "windows" {
  294. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  295. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  296. }
  297. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  298. _, err = cmd.CombinedOutput()
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. err = UntarPath(tarFile, destFolder)
  303. if err != nil {
  304. t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
  305. }
  306. expectedFile := filepath.Join(destFolder, srcFileU)
  307. _, err = os.Stat(expectedFile)
  308. if err != nil {
  309. t.Fatalf("Destination folder should contain the source file but did not.")
  310. }
  311. }
  312. // Do the same test as above but with the destination as file, it should fail
  313. func TestUntarPathWithDestinationFile(t *testing.T) {
  314. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. defer os.RemoveAll(tmpFolder)
  319. srcFile := filepath.Join(tmpFolder, "src")
  320. tarFile := filepath.Join(tmpFolder, "src.tar")
  321. os.Create(filepath.Join(tmpFolder, "src"))
  322. // Translate back to Unix semantics as next exec.Command is run under sh
  323. srcFileU := srcFile
  324. tarFileU := tarFile
  325. if runtime.GOOS == "windows" {
  326. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  327. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  328. }
  329. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  330. _, err = cmd.CombinedOutput()
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. destFile := filepath.Join(tmpFolder, "dest")
  335. _, err = os.Create(destFile)
  336. if err != nil {
  337. t.Fatalf("Fail to create the destination file")
  338. }
  339. err = UntarPath(tarFile, destFile)
  340. if err == nil {
  341. t.Fatalf("UntarPath should throw an error if the destination if a file")
  342. }
  343. }
  344. // Do the same test as above but with the destination folder already exists
  345. // and the destination file is a directory
  346. // It's working, see https://github.com/docker/docker/issues/10040
  347. func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
  348. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  349. if err != nil {
  350. t.Fatal(err)
  351. }
  352. defer os.RemoveAll(tmpFolder)
  353. srcFile := filepath.Join(tmpFolder, "src")
  354. tarFile := filepath.Join(tmpFolder, "src.tar")
  355. os.Create(srcFile)
  356. // Translate back to Unix semantics as next exec.Command is run under sh
  357. srcFileU := srcFile
  358. tarFileU := tarFile
  359. if runtime.GOOS == "windows" {
  360. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  361. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  362. }
  363. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  364. _, err = cmd.CombinedOutput()
  365. if err != nil {
  366. t.Fatal(err)
  367. }
  368. destFolder := filepath.Join(tmpFolder, "dest")
  369. err = os.MkdirAll(destFolder, 0740)
  370. if err != nil {
  371. t.Fatalf("Fail to create the destination folder")
  372. }
  373. // Let's create a folder that will has the same path as the extracted file (from tar)
  374. destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
  375. err = os.MkdirAll(destSrcFileAsFolder, 0740)
  376. if err != nil {
  377. t.Fatal(err)
  378. }
  379. err = UntarPath(tarFile, destFolder)
  380. if err != nil {
  381. t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
  382. }
  383. }
  384. func TestCopyWithTarInvalidSrc(t *testing.T) {
  385. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  386. if err != nil {
  387. t.Fatal(nil)
  388. }
  389. destFolder := filepath.Join(tempFolder, "dest")
  390. invalidSrc := filepath.Join(tempFolder, "doesnotexists")
  391. err = os.MkdirAll(destFolder, 0740)
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. err = CopyWithTar(invalidSrc, destFolder)
  396. if err == nil {
  397. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  398. }
  399. }
  400. func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
  401. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  402. if err != nil {
  403. t.Fatal(nil)
  404. }
  405. srcFolder := filepath.Join(tempFolder, "src")
  406. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  407. err = os.MkdirAll(srcFolder, 0740)
  408. if err != nil {
  409. t.Fatal(err)
  410. }
  411. err = CopyWithTar(srcFolder, inexistentDestFolder)
  412. if err != nil {
  413. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  414. }
  415. _, err = os.Stat(inexistentDestFolder)
  416. if err != nil {
  417. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  418. }
  419. }
  420. // Test CopyWithTar with a file as src
  421. func TestCopyWithTarSrcFile(t *testing.T) {
  422. folder, err := ioutil.TempDir("", "docker-archive-test")
  423. if err != nil {
  424. t.Fatal(err)
  425. }
  426. defer os.RemoveAll(folder)
  427. dest := filepath.Join(folder, "dest")
  428. srcFolder := filepath.Join(folder, "src")
  429. src := filepath.Join(folder, filepath.Join("src", "src"))
  430. err = os.MkdirAll(srcFolder, 0740)
  431. if err != nil {
  432. t.Fatal(err)
  433. }
  434. err = os.MkdirAll(dest, 0740)
  435. if err != nil {
  436. t.Fatal(err)
  437. }
  438. ioutil.WriteFile(src, []byte("content"), 0777)
  439. err = CopyWithTar(src, dest)
  440. if err != nil {
  441. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  442. }
  443. _, err = os.Stat(dest)
  444. // FIXME Check the content
  445. if err != nil {
  446. t.Fatalf("Destination file should be the same as the source.")
  447. }
  448. }
  449. // Test CopyWithTar with a folder as src
  450. func TestCopyWithTarSrcFolder(t *testing.T) {
  451. folder, err := ioutil.TempDir("", "docker-archive-test")
  452. if err != nil {
  453. t.Fatal(err)
  454. }
  455. defer os.RemoveAll(folder)
  456. dest := filepath.Join(folder, "dest")
  457. src := filepath.Join(folder, filepath.Join("src", "folder"))
  458. err = os.MkdirAll(src, 0740)
  459. if err != nil {
  460. t.Fatal(err)
  461. }
  462. err = os.MkdirAll(dest, 0740)
  463. if err != nil {
  464. t.Fatal(err)
  465. }
  466. ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
  467. err = CopyWithTar(src, dest)
  468. if err != nil {
  469. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  470. }
  471. _, err = os.Stat(dest)
  472. // FIXME Check the content (the file inside)
  473. if err != nil {
  474. t.Fatalf("Destination folder should contain the source file but did not.")
  475. }
  476. }
  477. func TestCopyFileWithTarInvalidSrc(t *testing.T) {
  478. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  479. if err != nil {
  480. t.Fatal(err)
  481. }
  482. defer os.RemoveAll(tempFolder)
  483. destFolder := filepath.Join(tempFolder, "dest")
  484. err = os.MkdirAll(destFolder, 0740)
  485. if err != nil {
  486. t.Fatal(err)
  487. }
  488. invalidFile := filepath.Join(tempFolder, "doesnotexists")
  489. err = CopyFileWithTar(invalidFile, destFolder)
  490. if err == nil {
  491. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  492. }
  493. }
  494. func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
  495. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  496. if err != nil {
  497. t.Fatal(nil)
  498. }
  499. defer os.RemoveAll(tempFolder)
  500. srcFile := filepath.Join(tempFolder, "src")
  501. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  502. _, err = os.Create(srcFile)
  503. if err != nil {
  504. t.Fatal(err)
  505. }
  506. err = CopyFileWithTar(srcFile, inexistentDestFolder)
  507. if err != nil {
  508. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  509. }
  510. _, err = os.Stat(inexistentDestFolder)
  511. if err != nil {
  512. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  513. }
  514. // FIXME Test the src file and content
  515. }
  516. func TestCopyFileWithTarSrcFolder(t *testing.T) {
  517. folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
  518. if err != nil {
  519. t.Fatal(err)
  520. }
  521. defer os.RemoveAll(folder)
  522. dest := filepath.Join(folder, "dest")
  523. src := filepath.Join(folder, "srcfolder")
  524. err = os.MkdirAll(src, 0740)
  525. if err != nil {
  526. t.Fatal(err)
  527. }
  528. err = os.MkdirAll(dest, 0740)
  529. if err != nil {
  530. t.Fatal(err)
  531. }
  532. err = CopyFileWithTar(src, dest)
  533. if err == nil {
  534. t.Fatalf("CopyFileWithTar should throw an error with a folder.")
  535. }
  536. }
  537. func TestCopyFileWithTarSrcFile(t *testing.T) {
  538. folder, err := ioutil.TempDir("", "docker-archive-test")
  539. if err != nil {
  540. t.Fatal(err)
  541. }
  542. defer os.RemoveAll(folder)
  543. dest := filepath.Join(folder, "dest")
  544. srcFolder := filepath.Join(folder, "src")
  545. src := filepath.Join(folder, filepath.Join("src", "src"))
  546. err = os.MkdirAll(srcFolder, 0740)
  547. if err != nil {
  548. t.Fatal(err)
  549. }
  550. err = os.MkdirAll(dest, 0740)
  551. if err != nil {
  552. t.Fatal(err)
  553. }
  554. ioutil.WriteFile(src, []byte("content"), 0777)
  555. err = CopyWithTar(src, dest+"/")
  556. if err != nil {
  557. t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
  558. }
  559. _, err = os.Stat(dest)
  560. if err != nil {
  561. t.Fatalf("Destination folder should contain the source file but did not.")
  562. }
  563. }
  564. func TestTarFiles(t *testing.T) {
  565. // TODO Windows: Figure out how to port this test.
  566. if runtime.GOOS == "windows" {
  567. t.Skip("Failing on Windows")
  568. }
  569. // try without hardlinks
  570. if err := checkNoChanges(1000, false); err != nil {
  571. t.Fatal(err)
  572. }
  573. // try with hardlinks
  574. if err := checkNoChanges(1000, true); err != nil {
  575. t.Fatal(err)
  576. }
  577. }
  578. func checkNoChanges(fileNum int, hardlinks bool) error {
  579. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  580. if err != nil {
  581. return err
  582. }
  583. defer os.RemoveAll(srcDir)
  584. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  585. if err != nil {
  586. return err
  587. }
  588. defer os.RemoveAll(destDir)
  589. _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
  590. if err != nil {
  591. return err
  592. }
  593. err = TarUntar(srcDir, destDir)
  594. if err != nil {
  595. return err
  596. }
  597. changes, err := ChangesDirs(destDir, srcDir)
  598. if err != nil {
  599. return err
  600. }
  601. if len(changes) > 0 {
  602. return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
  603. }
  604. return nil
  605. }
  606. func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
  607. archive, err := TarWithOptions(origin, options)
  608. if err != nil {
  609. t.Fatal(err)
  610. }
  611. defer archive.Close()
  612. buf := make([]byte, 10)
  613. if _, err := archive.Read(buf); err != nil {
  614. return nil, err
  615. }
  616. wrap := io.MultiReader(bytes.NewReader(buf), archive)
  617. detectedCompression := DetectCompression(buf)
  618. compression := options.Compression
  619. if detectedCompression.Extension() != compression.Extension() {
  620. return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
  621. }
  622. tmp, err := ioutil.TempDir("", "docker-test-untar")
  623. if err != nil {
  624. return nil, err
  625. }
  626. defer os.RemoveAll(tmp)
  627. if err := Untar(wrap, tmp, nil); err != nil {
  628. return nil, err
  629. }
  630. if _, err := os.Stat(tmp); err != nil {
  631. return nil, err
  632. }
  633. return ChangesDirs(origin, tmp)
  634. }
  635. func TestTarUntar(t *testing.T) {
  636. // TODO Windows: Figure out how to fix this test.
  637. if runtime.GOOS == "windows" {
  638. t.Skip("Failing on Windows")
  639. }
  640. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  641. if err != nil {
  642. t.Fatal(err)
  643. }
  644. defer os.RemoveAll(origin)
  645. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  646. t.Fatal(err)
  647. }
  648. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  649. t.Fatal(err)
  650. }
  651. if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
  652. t.Fatal(err)
  653. }
  654. for _, c := range []Compression{
  655. Uncompressed,
  656. Gzip,
  657. } {
  658. changes, err := tarUntar(t, origin, &TarOptions{
  659. Compression: c,
  660. ExcludePatterns: []string{"3"},
  661. })
  662. if err != nil {
  663. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  664. }
  665. if len(changes) != 1 || changes[0].Path != "/3" {
  666. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  667. }
  668. }
  669. }
  670. func TestTarWithOptions(t *testing.T) {
  671. // TODO Windows: Figure out how to fix this test.
  672. if runtime.GOOS == "windows" {
  673. t.Skip("Failing on Windows")
  674. }
  675. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  676. if err != nil {
  677. t.Fatal(err)
  678. }
  679. if _, err := ioutil.TempDir(origin, "folder"); err != nil {
  680. t.Fatal(err)
  681. }
  682. defer os.RemoveAll(origin)
  683. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  684. t.Fatal(err)
  685. }
  686. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  687. t.Fatal(err)
  688. }
  689. cases := []struct {
  690. opts *TarOptions
  691. numChanges int
  692. }{
  693. {&TarOptions{IncludeFiles: []string{"1"}}, 2},
  694. {&TarOptions{ExcludePatterns: []string{"2"}}, 1},
  695. {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
  696. {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
  697. {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
  698. }
  699. for _, testCase := range cases {
  700. changes, err := tarUntar(t, origin, testCase.opts)
  701. if err != nil {
  702. t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
  703. }
  704. if len(changes) != testCase.numChanges {
  705. t.Errorf("Expected %d changes, got %d for %+v:",
  706. testCase.numChanges, len(changes), testCase.opts)
  707. }
  708. }
  709. }
  710. // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
  711. // use PAX Global Extended Headers.
  712. // Failing prevents the archives from being uncompressed during ADD
  713. func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
  714. hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
  715. tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
  716. if err != nil {
  717. t.Fatal(err)
  718. }
  719. defer os.RemoveAll(tmpDir)
  720. err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil)
  721. if err != nil {
  722. t.Fatal(err)
  723. }
  724. }
  725. // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
  726. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
  727. func TestUntarUstarGnuConflict(t *testing.T) {
  728. f, err := os.Open("testdata/broken.tar")
  729. if err != nil {
  730. t.Fatal(err)
  731. }
  732. found := false
  733. tr := tar.NewReader(f)
  734. // Iterate through the files in the archive.
  735. for {
  736. hdr, err := tr.Next()
  737. if err == io.EOF {
  738. // end of tar archive
  739. break
  740. }
  741. if err != nil {
  742. t.Fatal(err)
  743. }
  744. if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
  745. found = true
  746. break
  747. }
  748. }
  749. if !found {
  750. t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
  751. }
  752. }
  753. func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
  754. fileData := []byte("fooo")
  755. for n := 0; n < numberOfFiles; n++ {
  756. fileName := fmt.Sprintf("file-%d", n)
  757. if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil {
  758. return 0, err
  759. }
  760. if makeLinks {
  761. if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
  762. return 0, err
  763. }
  764. }
  765. }
  766. totalSize := numberOfFiles * len(fileData)
  767. return totalSize, nil
  768. }
  769. func BenchmarkTarUntar(b *testing.B) {
  770. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  771. if err != nil {
  772. b.Fatal(err)
  773. }
  774. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  775. if err != nil {
  776. b.Fatal(err)
  777. }
  778. target := filepath.Join(tempDir, "dest")
  779. n, err := prepareUntarSourceDirectory(100, origin, false)
  780. if err != nil {
  781. b.Fatal(err)
  782. }
  783. defer os.RemoveAll(origin)
  784. defer os.RemoveAll(tempDir)
  785. b.ResetTimer()
  786. b.SetBytes(int64(n))
  787. for n := 0; n < b.N; n++ {
  788. err := TarUntar(origin, target)
  789. if err != nil {
  790. b.Fatal(err)
  791. }
  792. os.RemoveAll(target)
  793. }
  794. }
  795. func BenchmarkTarUntarWithLinks(b *testing.B) {
  796. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  797. if err != nil {
  798. b.Fatal(err)
  799. }
  800. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  801. if err != nil {
  802. b.Fatal(err)
  803. }
  804. target := filepath.Join(tempDir, "dest")
  805. n, err := prepareUntarSourceDirectory(100, origin, true)
  806. if err != nil {
  807. b.Fatal(err)
  808. }
  809. defer os.RemoveAll(origin)
  810. defer os.RemoveAll(tempDir)
  811. b.ResetTimer()
  812. b.SetBytes(int64(n))
  813. for n := 0; n < b.N; n++ {
  814. err := TarUntar(origin, target)
  815. if err != nil {
  816. b.Fatal(err)
  817. }
  818. os.RemoveAll(target)
  819. }
  820. }
  821. func TestUntarInvalidFilenames(t *testing.T) {
  822. // TODO Windows: Figure out how to fix this test.
  823. if runtime.GOOS == "windows" {
  824. t.Skip("Passes but hits breakoutError: platform and architecture is not supported")
  825. }
  826. for i, headers := range [][]*tar.Header{
  827. {
  828. {
  829. Name: "../victim/dotdot",
  830. Typeflag: tar.TypeReg,
  831. Mode: 0644,
  832. },
  833. },
  834. {
  835. {
  836. // Note the leading slash
  837. Name: "/../victim/slash-dotdot",
  838. Typeflag: tar.TypeReg,
  839. Mode: 0644,
  840. },
  841. },
  842. } {
  843. if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
  844. t.Fatalf("i=%d. %v", i, err)
  845. }
  846. }
  847. }
  848. func TestUntarHardlinkToSymlink(t *testing.T) {
  849. // TODO Windows. There may be a way of running this, but turning off for now
  850. if runtime.GOOS == "windows" {
  851. t.Skip("hardlinks on Windows")
  852. }
  853. for i, headers := range [][]*tar.Header{
  854. {
  855. {
  856. Name: "symlink1",
  857. Typeflag: tar.TypeSymlink,
  858. Linkname: "regfile",
  859. Mode: 0644,
  860. },
  861. {
  862. Name: "symlink2",
  863. Typeflag: tar.TypeLink,
  864. Linkname: "symlink1",
  865. Mode: 0644,
  866. },
  867. {
  868. Name: "regfile",
  869. Typeflag: tar.TypeReg,
  870. Mode: 0644,
  871. },
  872. },
  873. } {
  874. if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
  875. t.Fatalf("i=%d. %v", i, err)
  876. }
  877. }
  878. }
  879. func TestUntarInvalidHardlink(t *testing.T) {
  880. // TODO Windows. There may be a way of running this, but turning off for now
  881. if runtime.GOOS == "windows" {
  882. t.Skip("hardlinks on Windows")
  883. }
  884. for i, headers := range [][]*tar.Header{
  885. { // try reading victim/hello (../)
  886. {
  887. Name: "dotdot",
  888. Typeflag: tar.TypeLink,
  889. Linkname: "../victim/hello",
  890. Mode: 0644,
  891. },
  892. },
  893. { // try reading victim/hello (/../)
  894. {
  895. Name: "slash-dotdot",
  896. Typeflag: tar.TypeLink,
  897. // Note the leading slash
  898. Linkname: "/../victim/hello",
  899. Mode: 0644,
  900. },
  901. },
  902. { // try writing victim/file
  903. {
  904. Name: "loophole-victim",
  905. Typeflag: tar.TypeLink,
  906. Linkname: "../victim",
  907. Mode: 0755,
  908. },
  909. {
  910. Name: "loophole-victim/file",
  911. Typeflag: tar.TypeReg,
  912. Mode: 0644,
  913. },
  914. },
  915. { // try reading victim/hello (hardlink, symlink)
  916. {
  917. Name: "loophole-victim",
  918. Typeflag: tar.TypeLink,
  919. Linkname: "../victim",
  920. Mode: 0755,
  921. },
  922. {
  923. Name: "symlink",
  924. Typeflag: tar.TypeSymlink,
  925. Linkname: "loophole-victim/hello",
  926. Mode: 0644,
  927. },
  928. },
  929. { // Try reading victim/hello (hardlink, hardlink)
  930. {
  931. Name: "loophole-victim",
  932. Typeflag: tar.TypeLink,
  933. Linkname: "../victim",
  934. Mode: 0755,
  935. },
  936. {
  937. Name: "hardlink",
  938. Typeflag: tar.TypeLink,
  939. Linkname: "loophole-victim/hello",
  940. Mode: 0644,
  941. },
  942. },
  943. { // Try removing victim directory (hardlink)
  944. {
  945. Name: "loophole-victim",
  946. Typeflag: tar.TypeLink,
  947. Linkname: "../victim",
  948. Mode: 0755,
  949. },
  950. {
  951. Name: "loophole-victim",
  952. Typeflag: tar.TypeReg,
  953. Mode: 0644,
  954. },
  955. },
  956. } {
  957. if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
  958. t.Fatalf("i=%d. %v", i, err)
  959. }
  960. }
  961. }
  962. func TestUntarInvalidSymlink(t *testing.T) {
  963. // TODO Windows. There may be a way of running this, but turning off for now
  964. if runtime.GOOS == "windows" {
  965. t.Skip("hardlinks on Windows")
  966. }
  967. for i, headers := range [][]*tar.Header{
  968. { // try reading victim/hello (../)
  969. {
  970. Name: "dotdot",
  971. Typeflag: tar.TypeSymlink,
  972. Linkname: "../victim/hello",
  973. Mode: 0644,
  974. },
  975. },
  976. { // try reading victim/hello (/../)
  977. {
  978. Name: "slash-dotdot",
  979. Typeflag: tar.TypeSymlink,
  980. // Note the leading slash
  981. Linkname: "/../victim/hello",
  982. Mode: 0644,
  983. },
  984. },
  985. { // try writing victim/file
  986. {
  987. Name: "loophole-victim",
  988. Typeflag: tar.TypeSymlink,
  989. Linkname: "../victim",
  990. Mode: 0755,
  991. },
  992. {
  993. Name: "loophole-victim/file",
  994. Typeflag: tar.TypeReg,
  995. Mode: 0644,
  996. },
  997. },
  998. { // try reading victim/hello (symlink, symlink)
  999. {
  1000. Name: "loophole-victim",
  1001. Typeflag: tar.TypeSymlink,
  1002. Linkname: "../victim",
  1003. Mode: 0755,
  1004. },
  1005. {
  1006. Name: "symlink",
  1007. Typeflag: tar.TypeSymlink,
  1008. Linkname: "loophole-victim/hello",
  1009. Mode: 0644,
  1010. },
  1011. },
  1012. { // try reading victim/hello (symlink, hardlink)
  1013. {
  1014. Name: "loophole-victim",
  1015. Typeflag: tar.TypeSymlink,
  1016. Linkname: "../victim",
  1017. Mode: 0755,
  1018. },
  1019. {
  1020. Name: "hardlink",
  1021. Typeflag: tar.TypeLink,
  1022. Linkname: "loophole-victim/hello",
  1023. Mode: 0644,
  1024. },
  1025. },
  1026. { // try removing victim directory (symlink)
  1027. {
  1028. Name: "loophole-victim",
  1029. Typeflag: tar.TypeSymlink,
  1030. Linkname: "../victim",
  1031. Mode: 0755,
  1032. },
  1033. {
  1034. Name: "loophole-victim",
  1035. Typeflag: tar.TypeReg,
  1036. Mode: 0644,
  1037. },
  1038. },
  1039. { // try writing to victim/newdir/newfile with a symlink in the path
  1040. {
  1041. // this header needs to be before the next one, or else there is an error
  1042. Name: "dir/loophole",
  1043. Typeflag: tar.TypeSymlink,
  1044. Linkname: "../../victim",
  1045. Mode: 0755,
  1046. },
  1047. {
  1048. Name: "dir/loophole/newdir/newfile",
  1049. Typeflag: tar.TypeReg,
  1050. Mode: 0644,
  1051. },
  1052. },
  1053. } {
  1054. if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
  1055. t.Fatalf("i=%d. %v", i, err)
  1056. }
  1057. }
  1058. }
  1059. func TestTempArchiveCloseMultipleTimes(t *testing.T) {
  1060. reader := ioutil.NopCloser(strings.NewReader("hello"))
  1061. tempArchive, err := NewTempArchive(reader, "")
  1062. buf := make([]byte, 10)
  1063. n, err := tempArchive.Read(buf)
  1064. if n != 5 {
  1065. t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
  1066. }
  1067. for i := 0; i < 3; i++ {
  1068. if err = tempArchive.Close(); err != nil {
  1069. t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
  1070. }
  1071. }
  1072. }