archive_test.go 36 KB

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