archive_test.go 30 KB

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