archive_test.go 37 KB

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