archive_test.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. "github.com/stretchr/testify/assert"
  16. "github.com/stretchr/testify/require"
  17. )
  18. var tmp string
  19. func init() {
  20. tmp = "/tmp/"
  21. if runtime.GOOS == "windows" {
  22. tmp = os.Getenv("TEMP") + `\`
  23. }
  24. }
  25. var defaultArchiver = NewDefaultArchiver()
  26. func defaultTarUntar(src, dst string) error {
  27. return defaultArchiver.TarUntar(src, dst)
  28. }
  29. func defaultUntarPath(src, dst string) error {
  30. return defaultArchiver.UntarPath(src, dst)
  31. }
  32. func defaultCopyFileWithTar(src, dst string) (err error) {
  33. return defaultArchiver.CopyFileWithTar(src, dst)
  34. }
  35. func defaultCopyWithTar(src, dst string) error {
  36. return defaultArchiver.CopyWithTar(src, dst)
  37. }
  38. func TestIsArchivePathDir(t *testing.T) {
  39. cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
  40. output, err := cmd.CombinedOutput()
  41. if err != nil {
  42. t.Fatalf("Fail to create an archive file for test : %s.", output)
  43. }
  44. if IsArchivePath(tmp + "archivedir") {
  45. t.Fatalf("Incorrectly recognised directory as an archive")
  46. }
  47. }
  48. func TestIsArchivePathInvalidFile(t *testing.T) {
  49. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1024 count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
  50. output, err := cmd.CombinedOutput()
  51. if err != nil {
  52. t.Fatalf("Fail to create an archive file for test : %s.", output)
  53. }
  54. if IsArchivePath(tmp + "archive") {
  55. t.Fatalf("Incorrectly recognised invalid tar path as archive")
  56. }
  57. if IsArchivePath(tmp + "archive.gz") {
  58. t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
  59. }
  60. }
  61. func TestIsArchivePathTar(t *testing.T) {
  62. var whichTar string
  63. if runtime.GOOS == "solaris" {
  64. whichTar = "gtar"
  65. } else {
  66. whichTar = "tar"
  67. }
  68. cmdStr := fmt.Sprintf("touch /tmp/archivedata && %s -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz", whichTar)
  69. cmd := exec.Command("sh", "-c", cmdStr)
  70. output, err := cmd.CombinedOutput()
  71. if err != nil {
  72. t.Fatalf("Fail to create an archive file for test : %s.", output)
  73. }
  74. if !IsArchivePath(tmp + "/archive") {
  75. t.Fatalf("Did not recognise valid tar path as archive")
  76. }
  77. if !IsArchivePath(tmp + "archive.gz") {
  78. t.Fatalf("Did not recognise valid compressed tar path as archive")
  79. }
  80. }
  81. func testDecompressStream(t *testing.T, ext, compressCommand string) {
  82. cmd := exec.Command("sh", "-c",
  83. fmt.Sprintf("touch /tmp/archive && %s /tmp/archive", compressCommand))
  84. output, err := cmd.CombinedOutput()
  85. if err != nil {
  86. t.Fatalf("Failed to create an archive file for test : %s.", output)
  87. }
  88. filename := "archive." + ext
  89. archive, err := os.Open(tmp + filename)
  90. if err != nil {
  91. t.Fatalf("Failed to open file %s: %v", filename, err)
  92. }
  93. defer archive.Close()
  94. r, err := DecompressStream(archive)
  95. if err != nil {
  96. t.Fatalf("Failed to decompress %s: %v", filename, err)
  97. }
  98. if _, err = ioutil.ReadAll(r); err != nil {
  99. t.Fatalf("Failed to read the decompressed stream: %v ", err)
  100. }
  101. if err = r.Close(); err != nil {
  102. t.Fatalf("Failed to close the decompressed stream: %v ", err)
  103. }
  104. }
  105. func TestDecompressStreamGzip(t *testing.T) {
  106. testDecompressStream(t, "gz", "gzip -f")
  107. }
  108. func TestDecompressStreamBzip2(t *testing.T) {
  109. testDecompressStream(t, "bz2", "bzip2 -f")
  110. }
  111. func TestDecompressStreamXz(t *testing.T) {
  112. if runtime.GOOS == "windows" {
  113. t.Skip("Xz not present in msys2")
  114. }
  115. testDecompressStream(t, "xz", "xz -f")
  116. }
  117. func TestCompressStreamXzUnsupported(t *testing.T) {
  118. dest, err := os.Create(tmp + "dest")
  119. if err != nil {
  120. t.Fatalf("Fail to create the destination file")
  121. }
  122. defer dest.Close()
  123. _, err = CompressStream(dest, Xz)
  124. if err == nil {
  125. t.Fatalf("Should fail as xz is unsupported for compression format.")
  126. }
  127. }
  128. func TestCompressStreamBzip2Unsupported(t *testing.T) {
  129. dest, err := os.Create(tmp + "dest")
  130. if err != nil {
  131. t.Fatalf("Fail to create the destination file")
  132. }
  133. defer dest.Close()
  134. _, err = CompressStream(dest, Xz)
  135. if err == nil {
  136. t.Fatalf("Should fail as xz is unsupported for compression format.")
  137. }
  138. }
  139. func TestCompressStreamInvalid(t *testing.T) {
  140. dest, err := os.Create(tmp + "dest")
  141. if err != nil {
  142. t.Fatalf("Fail to create the destination file")
  143. }
  144. defer dest.Close()
  145. _, err = CompressStream(dest, -1)
  146. if err == nil {
  147. t.Fatalf("Should fail as xz is unsupported for compression format.")
  148. }
  149. }
  150. func TestExtensionInvalid(t *testing.T) {
  151. compression := Compression(-1)
  152. output := compression.Extension()
  153. if output != "" {
  154. t.Fatalf("The extension of an invalid compression should be an empty string.")
  155. }
  156. }
  157. func TestExtensionUncompressed(t *testing.T) {
  158. compression := Uncompressed
  159. output := compression.Extension()
  160. if output != "tar" {
  161. t.Fatalf("The extension of an uncompressed archive should be 'tar'.")
  162. }
  163. }
  164. func TestExtensionBzip2(t *testing.T) {
  165. compression := Bzip2
  166. output := compression.Extension()
  167. if output != "tar.bz2" {
  168. t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
  169. }
  170. }
  171. func TestExtensionGzip(t *testing.T) {
  172. compression := Gzip
  173. output := compression.Extension()
  174. if output != "tar.gz" {
  175. t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
  176. }
  177. }
  178. func TestExtensionXz(t *testing.T) {
  179. compression := Xz
  180. output := compression.Extension()
  181. if output != "tar.xz" {
  182. t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
  183. }
  184. }
  185. func TestCmdStreamLargeStderr(t *testing.T) {
  186. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
  187. out, _, err := cmdStream(cmd, nil)
  188. if err != nil {
  189. t.Fatalf("Failed to start command: %s", err)
  190. }
  191. errCh := make(chan error)
  192. go func() {
  193. _, err := io.Copy(ioutil.Discard, out)
  194. errCh <- err
  195. }()
  196. select {
  197. case err := <-errCh:
  198. if err != nil {
  199. t.Fatalf("Command should not have failed (err=%.100s...)", err)
  200. }
  201. case <-time.After(5 * time.Second):
  202. t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
  203. }
  204. }
  205. func TestCmdStreamBad(t *testing.T) {
  206. // TODO Windows: Figure out why this is failing in CI but not locally
  207. if runtime.GOOS == "windows" {
  208. t.Skip("Failing on Windows CI machines")
  209. }
  210. badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
  211. out, _, err := cmdStream(badCmd, nil)
  212. if err != nil {
  213. t.Fatalf("Failed to start command: %s", err)
  214. }
  215. if output, err := ioutil.ReadAll(out); err == nil {
  216. t.Fatalf("Command should have failed")
  217. } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
  218. t.Fatalf("Wrong error value (%s)", err)
  219. } else if s := string(output); s != "hello\n" {
  220. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  221. }
  222. }
  223. func TestCmdStreamGood(t *testing.T) {
  224. cmd := exec.Command("sh", "-c", "echo hello; exit 0")
  225. out, _, err := cmdStream(cmd, nil)
  226. if err != nil {
  227. t.Fatal(err)
  228. }
  229. if output, err := ioutil.ReadAll(out); err != nil {
  230. t.Fatalf("Command should not have failed (err=%s)", err)
  231. } else if s := string(output); s != "hello\n" {
  232. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  233. }
  234. }
  235. func TestUntarPathWithInvalidDest(t *testing.T) {
  236. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  237. if err != nil {
  238. t.Fatal(err)
  239. }
  240. defer os.RemoveAll(tempFolder)
  241. invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
  242. // Create a src file
  243. srcFile := filepath.Join(tempFolder, "src")
  244. tarFile := filepath.Join(tempFolder, "src.tar")
  245. os.Create(srcFile)
  246. os.Create(invalidDestFolder) // being a file (not dir) should cause an error
  247. // Translate back to Unix semantics as next exec.Command is run under sh
  248. srcFileU := srcFile
  249. tarFileU := tarFile
  250. if runtime.GOOS == "windows" {
  251. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  252. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  253. }
  254. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  255. _, err = cmd.CombinedOutput()
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. err = defaultUntarPath(tarFile, invalidDestFolder)
  260. if err == nil {
  261. t.Fatalf("UntarPath with invalid destination path should throw an error.")
  262. }
  263. }
  264. func TestUntarPathWithInvalidSrc(t *testing.T) {
  265. dest, err := ioutil.TempDir("", "docker-archive-test")
  266. if err != nil {
  267. t.Fatalf("Fail to create the destination file")
  268. }
  269. defer os.RemoveAll(dest)
  270. err = defaultUntarPath("/invalid/path", dest)
  271. if err == nil {
  272. t.Fatalf("UntarPath with invalid src path should throw an error.")
  273. }
  274. }
  275. func TestUntarPath(t *testing.T) {
  276. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  277. if err != nil {
  278. t.Fatal(err)
  279. }
  280. defer os.RemoveAll(tmpFolder)
  281. srcFile := filepath.Join(tmpFolder, "src")
  282. tarFile := filepath.Join(tmpFolder, "src.tar")
  283. os.Create(filepath.Join(tmpFolder, "src"))
  284. destFolder := filepath.Join(tmpFolder, "dest")
  285. err = os.MkdirAll(destFolder, 0740)
  286. if err != nil {
  287. t.Fatalf("Fail to create the destination file")
  288. }
  289. // Translate back to Unix semantics as next exec.Command is run under sh
  290. srcFileU := srcFile
  291. tarFileU := tarFile
  292. if runtime.GOOS == "windows" {
  293. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  294. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  295. }
  296. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  297. _, err = cmd.CombinedOutput()
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. err = defaultUntarPath(tarFile, destFolder)
  302. if err != nil {
  303. t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
  304. }
  305. expectedFile := filepath.Join(destFolder, srcFileU)
  306. _, err = os.Stat(expectedFile)
  307. if err != nil {
  308. t.Fatalf("Destination folder should contain the source file but did not.")
  309. }
  310. }
  311. // Do the same test as above but with the destination as file, it should fail
  312. func TestUntarPathWithDestinationFile(t *testing.T) {
  313. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  314. if err != nil {
  315. t.Fatal(err)
  316. }
  317. defer os.RemoveAll(tmpFolder)
  318. srcFile := filepath.Join(tmpFolder, "src")
  319. tarFile := filepath.Join(tmpFolder, "src.tar")
  320. os.Create(filepath.Join(tmpFolder, "src"))
  321. // Translate back to Unix semantics as next exec.Command is run under sh
  322. srcFileU := srcFile
  323. tarFileU := tarFile
  324. if runtime.GOOS == "windows" {
  325. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  326. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  327. }
  328. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  329. _, err = cmd.CombinedOutput()
  330. if err != nil {
  331. t.Fatal(err)
  332. }
  333. destFile := filepath.Join(tmpFolder, "dest")
  334. _, err = os.Create(destFile)
  335. if err != nil {
  336. t.Fatalf("Fail to create the destination file")
  337. }
  338. err = defaultUntarPath(tarFile, destFile)
  339. if err == nil {
  340. t.Fatalf("UntarPath should throw an error if the destination if a file")
  341. }
  342. }
  343. // Do the same test as above but with the destination folder already exists
  344. // and the destination file is a directory
  345. // It's working, see https://github.com/docker/docker/issues/10040
  346. func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
  347. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  348. if err != nil {
  349. t.Fatal(err)
  350. }
  351. defer os.RemoveAll(tmpFolder)
  352. srcFile := filepath.Join(tmpFolder, "src")
  353. tarFile := filepath.Join(tmpFolder, "src.tar")
  354. os.Create(srcFile)
  355. // Translate back to Unix semantics as next exec.Command is run under sh
  356. srcFileU := srcFile
  357. tarFileU := tarFile
  358. if runtime.GOOS == "windows" {
  359. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  360. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  361. }
  362. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  363. _, err = cmd.CombinedOutput()
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. destFolder := filepath.Join(tmpFolder, "dest")
  368. err = os.MkdirAll(destFolder, 0740)
  369. if err != nil {
  370. t.Fatalf("Fail to create the destination folder")
  371. }
  372. // Let's create a folder that will has the same path as the extracted file (from tar)
  373. destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
  374. err = os.MkdirAll(destSrcFileAsFolder, 0740)
  375. if err != nil {
  376. t.Fatal(err)
  377. }
  378. err = defaultUntarPath(tarFile, destFolder)
  379. if err != nil {
  380. t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
  381. }
  382. }
  383. func TestCopyWithTarInvalidSrc(t *testing.T) {
  384. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  385. if err != nil {
  386. t.Fatal(nil)
  387. }
  388. destFolder := filepath.Join(tempFolder, "dest")
  389. invalidSrc := filepath.Join(tempFolder, "doesnotexists")
  390. err = os.MkdirAll(destFolder, 0740)
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. err = defaultCopyWithTar(invalidSrc, destFolder)
  395. if err == nil {
  396. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  397. }
  398. }
  399. func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
  400. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  401. if err != nil {
  402. t.Fatal(nil)
  403. }
  404. srcFolder := filepath.Join(tempFolder, "src")
  405. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  406. err = os.MkdirAll(srcFolder, 0740)
  407. if err != nil {
  408. t.Fatal(err)
  409. }
  410. err = defaultCopyWithTar(srcFolder, inexistentDestFolder)
  411. if err != nil {
  412. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  413. }
  414. _, err = os.Stat(inexistentDestFolder)
  415. if err != nil {
  416. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  417. }
  418. }
  419. // Test CopyWithTar with a file as src
  420. func TestCopyWithTarSrcFile(t *testing.T) {
  421. folder, err := ioutil.TempDir("", "docker-archive-test")
  422. if err != nil {
  423. t.Fatal(err)
  424. }
  425. defer os.RemoveAll(folder)
  426. dest := filepath.Join(folder, "dest")
  427. srcFolder := filepath.Join(folder, "src")
  428. src := filepath.Join(folder, filepath.Join("src", "src"))
  429. err = os.MkdirAll(srcFolder, 0740)
  430. if err != nil {
  431. t.Fatal(err)
  432. }
  433. err = os.MkdirAll(dest, 0740)
  434. if err != nil {
  435. t.Fatal(err)
  436. }
  437. ioutil.WriteFile(src, []byte("content"), 0777)
  438. err = defaultCopyWithTar(src, dest)
  439. if err != nil {
  440. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  441. }
  442. _, err = os.Stat(dest)
  443. // FIXME Check the content
  444. if err != nil {
  445. t.Fatalf("Destination file should be the same as the source.")
  446. }
  447. }
  448. // Test CopyWithTar with a folder as src
  449. func TestCopyWithTarSrcFolder(t *testing.T) {
  450. folder, err := ioutil.TempDir("", "docker-archive-test")
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. defer os.RemoveAll(folder)
  455. dest := filepath.Join(folder, "dest")
  456. src := filepath.Join(folder, filepath.Join("src", "folder"))
  457. err = os.MkdirAll(src, 0740)
  458. if err != nil {
  459. t.Fatal(err)
  460. }
  461. err = os.MkdirAll(dest, 0740)
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
  466. err = defaultCopyWithTar(src, dest)
  467. if err != nil {
  468. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  469. }
  470. _, err = os.Stat(dest)
  471. // FIXME Check the content (the file inside)
  472. if err != nil {
  473. t.Fatalf("Destination folder should contain the source file but did not.")
  474. }
  475. }
  476. func TestCopyFileWithTarInvalidSrc(t *testing.T) {
  477. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  478. if err != nil {
  479. t.Fatal(err)
  480. }
  481. defer os.RemoveAll(tempFolder)
  482. destFolder := filepath.Join(tempFolder, "dest")
  483. err = os.MkdirAll(destFolder, 0740)
  484. if err != nil {
  485. t.Fatal(err)
  486. }
  487. invalidFile := filepath.Join(tempFolder, "doesnotexists")
  488. err = defaultCopyFileWithTar(invalidFile, destFolder)
  489. if err == nil {
  490. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  491. }
  492. }
  493. func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
  494. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  495. if err != nil {
  496. t.Fatal(nil)
  497. }
  498. defer os.RemoveAll(tempFolder)
  499. srcFile := filepath.Join(tempFolder, "src")
  500. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  501. _, err = os.Create(srcFile)
  502. if err != nil {
  503. t.Fatal(err)
  504. }
  505. err = defaultCopyFileWithTar(srcFile, inexistentDestFolder)
  506. if err != nil {
  507. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  508. }
  509. _, err = os.Stat(inexistentDestFolder)
  510. if err != nil {
  511. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  512. }
  513. // FIXME Test the src file and content
  514. }
  515. func TestCopyFileWithTarSrcFolder(t *testing.T) {
  516. folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. defer os.RemoveAll(folder)
  521. dest := filepath.Join(folder, "dest")
  522. src := filepath.Join(folder, "srcfolder")
  523. err = os.MkdirAll(src, 0740)
  524. if err != nil {
  525. t.Fatal(err)
  526. }
  527. err = os.MkdirAll(dest, 0740)
  528. if err != nil {
  529. t.Fatal(err)
  530. }
  531. err = defaultCopyFileWithTar(src, dest)
  532. if err == nil {
  533. t.Fatalf("CopyFileWithTar should throw an error with a folder.")
  534. }
  535. }
  536. func TestCopyFileWithTarSrcFile(t *testing.T) {
  537. folder, err := ioutil.TempDir("", "docker-archive-test")
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. defer os.RemoveAll(folder)
  542. dest := filepath.Join(folder, "dest")
  543. srcFolder := filepath.Join(folder, "src")
  544. src := filepath.Join(folder, filepath.Join("src", "src"))
  545. err = os.MkdirAll(srcFolder, 0740)
  546. if err != nil {
  547. t.Fatal(err)
  548. }
  549. err = os.MkdirAll(dest, 0740)
  550. if err != nil {
  551. t.Fatal(err)
  552. }
  553. ioutil.WriteFile(src, []byte("content"), 0777)
  554. err = defaultCopyWithTar(src, dest+"/")
  555. if err != nil {
  556. t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
  557. }
  558. _, err = os.Stat(dest)
  559. if err != nil {
  560. t.Fatalf("Destination folder should contain the source file but did not.")
  561. }
  562. }
  563. func TestTarFiles(t *testing.T) {
  564. // TODO Windows: Figure out how to port this test.
  565. if runtime.GOOS == "windows" {
  566. t.Skip("Failing on Windows")
  567. }
  568. // try without hardlinks
  569. if err := checkNoChanges(1000, false); err != nil {
  570. t.Fatal(err)
  571. }
  572. // try with hardlinks
  573. if err := checkNoChanges(1000, true); err != nil {
  574. t.Fatal(err)
  575. }
  576. }
  577. func checkNoChanges(fileNum int, hardlinks bool) error {
  578. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  579. if err != nil {
  580. return err
  581. }
  582. defer os.RemoveAll(srcDir)
  583. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  584. if err != nil {
  585. return err
  586. }
  587. defer os.RemoveAll(destDir)
  588. _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
  589. if err != nil {
  590. return err
  591. }
  592. err = defaultTarUntar(srcDir, destDir)
  593. if err != nil {
  594. return err
  595. }
  596. changes, err := ChangesDirs(destDir, srcDir)
  597. if err != nil {
  598. return err
  599. }
  600. if len(changes) > 0 {
  601. return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
  602. }
  603. return nil
  604. }
  605. func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
  606. archive, err := TarWithOptions(origin, options)
  607. if err != nil {
  608. t.Fatal(err)
  609. }
  610. defer archive.Close()
  611. buf := make([]byte, 10)
  612. if _, err := archive.Read(buf); err != nil {
  613. return nil, err
  614. }
  615. wrap := io.MultiReader(bytes.NewReader(buf), archive)
  616. detectedCompression := DetectCompression(buf)
  617. compression := options.Compression
  618. if detectedCompression.Extension() != compression.Extension() {
  619. return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
  620. }
  621. tmp, err := ioutil.TempDir("", "docker-test-untar")
  622. if err != nil {
  623. return nil, err
  624. }
  625. defer os.RemoveAll(tmp)
  626. if err := Untar(wrap, tmp, nil); err != nil {
  627. return nil, err
  628. }
  629. if _, err := os.Stat(tmp); err != nil {
  630. return nil, err
  631. }
  632. return ChangesDirs(origin, tmp)
  633. }
  634. func TestTarUntar(t *testing.T) {
  635. // TODO Windows: Figure out how to fix this test.
  636. if runtime.GOOS == "windows" {
  637. t.Skip("Failing on Windows")
  638. }
  639. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  640. if err != nil {
  641. t.Fatal(err)
  642. }
  643. defer os.RemoveAll(origin)
  644. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  645. t.Fatal(err)
  646. }
  647. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  648. t.Fatal(err)
  649. }
  650. if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
  651. t.Fatal(err)
  652. }
  653. for _, c := range []Compression{
  654. Uncompressed,
  655. Gzip,
  656. } {
  657. changes, err := tarUntar(t, origin, &TarOptions{
  658. Compression: c,
  659. ExcludePatterns: []string{"3"},
  660. })
  661. if err != nil {
  662. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  663. }
  664. if len(changes) != 1 || changes[0].Path != "/3" {
  665. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  666. }
  667. }
  668. }
  669. func TestTarWithOptions(t *testing.T) {
  670. // TODO Windows: Figure out how to fix this test.
  671. if runtime.GOOS == "windows" {
  672. t.Skip("Failing on Windows")
  673. }
  674. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  675. if err != nil {
  676. t.Fatal(err)
  677. }
  678. if _, err := ioutil.TempDir(origin, "folder"); err != nil {
  679. t.Fatal(err)
  680. }
  681. defer os.RemoveAll(origin)
  682. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  683. t.Fatal(err)
  684. }
  685. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  686. t.Fatal(err)
  687. }
  688. cases := []struct {
  689. opts *TarOptions
  690. numChanges int
  691. }{
  692. {&TarOptions{IncludeFiles: []string{"1"}}, 2},
  693. {&TarOptions{ExcludePatterns: []string{"2"}}, 1},
  694. {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
  695. {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
  696. {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
  697. }
  698. for _, testCase := range cases {
  699. changes, err := tarUntar(t, origin, testCase.opts)
  700. if err != nil {
  701. t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
  702. }
  703. if len(changes) != testCase.numChanges {
  704. t.Errorf("Expected %d changes, got %d for %+v:",
  705. testCase.numChanges, len(changes), testCase.opts)
  706. }
  707. }
  708. }
  709. // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
  710. // use PAX Global Extended Headers.
  711. // Failing prevents the archives from being uncompressed during ADD
  712. func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
  713. hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
  714. tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
  715. if err != nil {
  716. t.Fatal(err)
  717. }
  718. defer os.RemoveAll(tmpDir)
  719. err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil, false)
  720. if err != nil {
  721. t.Fatal(err)
  722. }
  723. }
  724. // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
  725. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
  726. func TestUntarUstarGnuConflict(t *testing.T) {
  727. f, err := os.Open("testdata/broken.tar")
  728. if err != nil {
  729. t.Fatal(err)
  730. }
  731. defer f.Close()
  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 := defaultTarUntar(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 := defaultTarUntar(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. }
  1073. func TestReplaceFileTarWrapper(t *testing.T) {
  1074. filesInArchive := 20
  1075. testcases := []struct {
  1076. doc string
  1077. filename string
  1078. modifier TarModifierFunc
  1079. expected string
  1080. fileCount int
  1081. }{
  1082. {
  1083. doc: "Modifier creates a new file",
  1084. filename: "newfile",
  1085. modifier: createModifier(t),
  1086. expected: "the new content",
  1087. fileCount: filesInArchive + 1,
  1088. },
  1089. {
  1090. doc: "Modifier replaces a file",
  1091. filename: "file-2",
  1092. modifier: createOrReplaceModifier,
  1093. expected: "the new content",
  1094. fileCount: filesInArchive,
  1095. },
  1096. {
  1097. doc: "Modifier replaces the last file",
  1098. filename: fmt.Sprintf("file-%d", filesInArchive-1),
  1099. modifier: createOrReplaceModifier,
  1100. expected: "the new content",
  1101. fileCount: filesInArchive,
  1102. },
  1103. {
  1104. doc: "Modifier appends to a file",
  1105. filename: "file-3",
  1106. modifier: appendModifier,
  1107. expected: "fooo\nnext line",
  1108. fileCount: filesInArchive,
  1109. },
  1110. }
  1111. for _, testcase := range testcases {
  1112. sourceArchive, cleanup := buildSourceArchive(t, filesInArchive)
  1113. defer cleanup()
  1114. resultArchive := ReplaceFileTarWrapper(
  1115. sourceArchive,
  1116. map[string]TarModifierFunc{testcase.filename: testcase.modifier})
  1117. actual := readFileFromArchive(t, resultArchive, testcase.filename, testcase.fileCount, testcase.doc)
  1118. assert.Equal(t, testcase.expected, actual, testcase.doc)
  1119. }
  1120. }
  1121. // TestPrefixHeaderReadable tests that files that could be created with the
  1122. // version of this package that was built with <=go17 are still readable.
  1123. func TestPrefixHeaderReadable(t *testing.T) {
  1124. // https://gist.github.com/stevvooe/e2a790ad4e97425896206c0816e1a882#file-out-go
  1125. var testFile = []byte("\x1f\x8b\x08\x08\x44\x21\x68\x59\x00\x03\x74\x2e\x74\x61\x72\x00\x4b\xcb\xcf\x67\xa0\x35\x30\x80\x00\x86\x06\x10\x47\x01\xc1\x37\x40\x00\x54\xb6\xb1\xa1\xa9\x99\x09\x48\x25\x1d\x40\x69\x71\x49\x62\x91\x02\xe5\x76\xa1\x79\x84\x21\x91\xd6\x80\x72\xaf\x8f\x82\x51\x30\x0a\x46\x36\x00\x00\xf0\x1c\x1e\x95\x00\x06\x00\x00")
  1126. tmpDir, err := ioutil.TempDir("", "prefix-test")
  1127. require.NoError(t, err)
  1128. defer os.RemoveAll(tmpDir)
  1129. err = Untar(bytes.NewReader(testFile), tmpDir, nil)
  1130. require.NoError(t, err)
  1131. baseName := "foo"
  1132. pth := strings.Repeat("a", 100-len(baseName)) + "/" + baseName
  1133. _, err = os.Lstat(filepath.Join(tmpDir, pth))
  1134. require.NoError(t, err)
  1135. }
  1136. func buildSourceArchive(t *testing.T, numberOfFiles int) (io.ReadCloser, func()) {
  1137. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  1138. require.NoError(t, err)
  1139. _, err = prepareUntarSourceDirectory(numberOfFiles, srcDir, false)
  1140. require.NoError(t, err)
  1141. sourceArchive, err := TarWithOptions(srcDir, &TarOptions{})
  1142. require.NoError(t, err)
  1143. return sourceArchive, func() {
  1144. os.RemoveAll(srcDir)
  1145. sourceArchive.Close()
  1146. }
  1147. }
  1148. func createOrReplaceModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1149. return &tar.Header{
  1150. Mode: 0600,
  1151. Typeflag: tar.TypeReg,
  1152. }, []byte("the new content"), nil
  1153. }
  1154. func createModifier(t *testing.T) TarModifierFunc {
  1155. return func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1156. assert.Nil(t, content)
  1157. return createOrReplaceModifier(path, header, content)
  1158. }
  1159. }
  1160. func appendModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1161. buffer := bytes.Buffer{}
  1162. if content != nil {
  1163. if _, err := buffer.ReadFrom(content); err != nil {
  1164. return nil, nil, err
  1165. }
  1166. }
  1167. buffer.WriteString("\nnext line")
  1168. return &tar.Header{Mode: 0600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil
  1169. }
  1170. func readFileFromArchive(t *testing.T, archive io.ReadCloser, name string, expectedCount int, doc string) string {
  1171. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  1172. require.NoError(t, err)
  1173. defer os.RemoveAll(destDir)
  1174. err = Untar(archive, destDir, nil)
  1175. require.NoError(t, err)
  1176. files, _ := ioutil.ReadDir(destDir)
  1177. assert.Len(t, files, expectedCount, doc)
  1178. content, err := ioutil.ReadFile(filepath.Join(destDir, name))
  1179. assert.NoError(t, err)
  1180. return string(content)
  1181. }