archive_test.go 37 KB

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