archive_test.go 37 KB

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