archive_unix_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // +build !windows
  2. package archive // import "github.com/docker/docker/pkg/archive"
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "syscall"
  11. "testing"
  12. "github.com/docker/docker/pkg/system"
  13. "golang.org/x/sys/unix"
  14. "gotest.tools/assert"
  15. is "gotest.tools/assert/cmp"
  16. "gotest.tools/skip"
  17. )
  18. func TestCanonicalTarNameForPath(t *testing.T) {
  19. cases := []struct{ in, expected string }{
  20. {"foo", "foo"},
  21. {"foo/bar", "foo/bar"},
  22. {"foo/dir/", "foo/dir/"},
  23. }
  24. for _, v := range cases {
  25. if CanonicalTarNameForPath(v.in) != v.expected {
  26. t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, CanonicalTarNameForPath(v.in))
  27. }
  28. }
  29. }
  30. func TestCanonicalTarName(t *testing.T) {
  31. cases := []struct {
  32. in string
  33. isDir bool
  34. expected string
  35. }{
  36. {"foo", false, "foo"},
  37. {"foo", true, "foo/"},
  38. {"foo/bar", false, "foo/bar"},
  39. {"foo/bar", true, "foo/bar/"},
  40. }
  41. for _, v := range cases {
  42. if canonicalTarName(v.in, v.isDir) != v.expected {
  43. t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, canonicalTarName(v.in, v.isDir))
  44. }
  45. }
  46. }
  47. func TestChmodTarEntry(t *testing.T) {
  48. cases := []struct {
  49. in, expected os.FileMode
  50. }{
  51. {0000, 0000},
  52. {0777, 0777},
  53. {0644, 0644},
  54. {0755, 0755},
  55. {0444, 0444},
  56. }
  57. for _, v := range cases {
  58. if out := chmodTarEntry(v.in); out != v.expected {
  59. t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out)
  60. }
  61. }
  62. }
  63. func TestTarWithHardLink(t *testing.T) {
  64. origin, err := ioutil.TempDir("", "docker-test-tar-hardlink")
  65. assert.NilError(t, err)
  66. defer os.RemoveAll(origin)
  67. err = ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700)
  68. assert.NilError(t, err)
  69. err = os.Link(filepath.Join(origin, "1"), filepath.Join(origin, "2"))
  70. assert.NilError(t, err)
  71. var i1, i2 uint64
  72. i1, err = getNlink(filepath.Join(origin, "1"))
  73. assert.NilError(t, err)
  74. // sanity check that we can hardlink
  75. if i1 != 2 {
  76. t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1)
  77. }
  78. dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest")
  79. assert.NilError(t, err)
  80. defer os.RemoveAll(dest)
  81. // we'll do this in two steps to separate failure
  82. fh, err := Tar(origin, Uncompressed)
  83. assert.NilError(t, err)
  84. // ensure we can read the whole thing with no error, before writing back out
  85. buf, err := ioutil.ReadAll(fh)
  86. assert.NilError(t, err)
  87. bRdr := bytes.NewReader(buf)
  88. err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed})
  89. assert.NilError(t, err)
  90. i1, err = getInode(filepath.Join(dest, "1"))
  91. assert.NilError(t, err)
  92. i2, err = getInode(filepath.Join(dest, "2"))
  93. assert.NilError(t, err)
  94. assert.Check(t, is.Equal(i1, i2))
  95. }
  96. func TestTarWithHardLinkAndRebase(t *testing.T) {
  97. tmpDir, err := ioutil.TempDir("", "docker-test-tar-hardlink-rebase")
  98. assert.NilError(t, err)
  99. defer os.RemoveAll(tmpDir)
  100. origin := filepath.Join(tmpDir, "origin")
  101. err = os.Mkdir(origin, 0700)
  102. assert.NilError(t, err)
  103. err = ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700)
  104. assert.NilError(t, err)
  105. err = os.Link(filepath.Join(origin, "1"), filepath.Join(origin, "2"))
  106. assert.NilError(t, err)
  107. var i1, i2 uint64
  108. i1, err = getNlink(filepath.Join(origin, "1"))
  109. assert.NilError(t, err)
  110. // sanity check that we can hardlink
  111. if i1 != 2 {
  112. t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1)
  113. }
  114. dest := filepath.Join(tmpDir, "dest")
  115. bRdr, err := TarResourceRebase(origin, "origin")
  116. assert.NilError(t, err)
  117. dstDir, srcBase := SplitPathDirEntry(origin)
  118. _, dstBase := SplitPathDirEntry(dest)
  119. content := RebaseArchiveEntries(bRdr, srcBase, dstBase)
  120. err = Untar(content, dstDir, &TarOptions{Compression: Uncompressed, NoLchown: true, NoOverwriteDirNonDir: true})
  121. assert.NilError(t, err)
  122. i1, err = getInode(filepath.Join(dest, "1"))
  123. assert.NilError(t, err)
  124. i2, err = getInode(filepath.Join(dest, "2"))
  125. assert.NilError(t, err)
  126. assert.Check(t, is.Equal(i1, i2))
  127. }
  128. func getNlink(path string) (uint64, error) {
  129. stat, err := os.Stat(path)
  130. if err != nil {
  131. return 0, err
  132. }
  133. statT, ok := stat.Sys().(*syscall.Stat_t)
  134. if !ok {
  135. return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys())
  136. }
  137. // We need this conversion on ARM64
  138. return uint64(statT.Nlink), nil
  139. }
  140. func getInode(path string) (uint64, error) {
  141. stat, err := os.Stat(path)
  142. if err != nil {
  143. return 0, err
  144. }
  145. statT, ok := stat.Sys().(*syscall.Stat_t)
  146. if !ok {
  147. return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys())
  148. }
  149. return statT.Ino, nil
  150. }
  151. func TestTarWithBlockCharFifo(t *testing.T) {
  152. skip.If(t, os.Getuid() != 0, "skipping test that requires root")
  153. origin, err := ioutil.TempDir("", "docker-test-tar-hardlink")
  154. assert.NilError(t, err)
  155. defer os.RemoveAll(origin)
  156. err = ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700)
  157. assert.NilError(t, err)
  158. err = system.Mknod(filepath.Join(origin, "2"), unix.S_IFBLK, int(system.Mkdev(int64(12), int64(5))))
  159. assert.NilError(t, err)
  160. err = system.Mknod(filepath.Join(origin, "3"), unix.S_IFCHR, int(system.Mkdev(int64(12), int64(5))))
  161. assert.NilError(t, err)
  162. err = system.Mknod(filepath.Join(origin, "4"), unix.S_IFIFO, int(system.Mkdev(int64(12), int64(5))))
  163. assert.NilError(t, err)
  164. dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest")
  165. assert.NilError(t, err)
  166. defer os.RemoveAll(dest)
  167. // we'll do this in two steps to separate failure
  168. fh, err := Tar(origin, Uncompressed)
  169. assert.NilError(t, err)
  170. // ensure we can read the whole thing with no error, before writing back out
  171. buf, err := ioutil.ReadAll(fh)
  172. assert.NilError(t, err)
  173. bRdr := bytes.NewReader(buf)
  174. err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed})
  175. assert.NilError(t, err)
  176. changes, err := ChangesDirs(origin, dest)
  177. assert.NilError(t, err)
  178. if len(changes) > 0 {
  179. t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %v", changes)
  180. }
  181. }
  182. // TestTarUntarWithXattr is Unix as Lsetxattr is not supported on Windows
  183. func TestTarUntarWithXattr(t *testing.T) {
  184. skip.If(t, os.Getuid() != 0, "skipping test that requires root")
  185. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  186. assert.NilError(t, err)
  187. defer os.RemoveAll(origin)
  188. err = ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700)
  189. assert.NilError(t, err)
  190. err = ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700)
  191. assert.NilError(t, err)
  192. err = ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700)
  193. assert.NilError(t, err)
  194. err = system.Lsetxattr(filepath.Join(origin, "2"), "security.capability", []byte{0x00}, 0)
  195. assert.NilError(t, err)
  196. for _, c := range []Compression{
  197. Uncompressed,
  198. Gzip,
  199. } {
  200. changes, err := tarUntar(t, origin, &TarOptions{
  201. Compression: c,
  202. ExcludePatterns: []string{"3"},
  203. })
  204. if err != nil {
  205. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  206. }
  207. if len(changes) != 1 || changes[0].Path != "/3" {
  208. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  209. }
  210. capability, _ := system.Lgetxattr(filepath.Join(origin, "2"), "security.capability")
  211. if capability == nil && capability[0] != 0x00 {
  212. t.Fatalf("Untar should have kept the 'security.capability' xattr.")
  213. }
  214. }
  215. }
  216. func TestCopyInfoDestinationPathSymlink(t *testing.T) {
  217. tmpDir, _ := getTestTempDirs(t)
  218. defer removeAllPaths(tmpDir)
  219. root := strings.TrimRight(tmpDir, "/") + "/"
  220. type FileTestData struct {
  221. resource FileData
  222. file string
  223. expected CopyInfo
  224. }
  225. testData := []FileTestData{
  226. //Create a directory: /tmp/archive-copy-test*/dir1
  227. //Test will "copy" file1 to dir1
  228. {resource: FileData{filetype: Dir, path: "dir1", permissions: 0740}, file: "file1", expected: CopyInfo{Path: root + "dir1/file1", Exists: false, IsDir: false}},
  229. //Create a symlink directory to dir1: /tmp/archive-copy-test*/dirSymlink -> dir1
  230. //Test will "copy" file2 to dirSymlink
  231. {resource: FileData{filetype: Symlink, path: "dirSymlink", contents: root + "dir1", permissions: 0600}, file: "file2", expected: CopyInfo{Path: root + "dirSymlink/file2", Exists: false, IsDir: false}},
  232. //Create a file in tmp directory: /tmp/archive-copy-test*/file1
  233. //Test to cover when the full file path already exists.
  234. {resource: FileData{filetype: Regular, path: "file1", permissions: 0600}, file: "", expected: CopyInfo{Path: root + "file1", Exists: true}},
  235. //Create a directory: /tmp/archive-copy*/dir2
  236. //Test to cover when the full directory path already exists
  237. {resource: FileData{filetype: Dir, path: "dir2", permissions: 0740}, file: "", expected: CopyInfo{Path: root + "dir2", Exists: true, IsDir: true}},
  238. //Create a symlink to a non-existent target: /tmp/archive-copy*/symlink1 -> noSuchTarget
  239. //Negative test to cover symlinking to a target that does not exit
  240. {resource: FileData{filetype: Symlink, path: "symlink1", contents: "noSuchTarget", permissions: 0600}, file: "", expected: CopyInfo{Path: root + "noSuchTarget", Exists: false}},
  241. //Create a file in tmp directory for next test: /tmp/existingfile
  242. {resource: FileData{filetype: Regular, path: "existingfile", permissions: 0600}, file: "", expected: CopyInfo{Path: root + "existingfile", Exists: true}},
  243. //Create a symlink to an existing file: /tmp/archive-copy*/symlink2 -> /tmp/existingfile
  244. //Test to cover when the parent directory of a new file is a symlink
  245. {resource: FileData{filetype: Symlink, path: "symlink2", contents: "existingfile", permissions: 0600}, file: "", expected: CopyInfo{Path: root + "existingfile", Exists: true}},
  246. }
  247. var dirs []FileData
  248. for _, data := range testData {
  249. dirs = append(dirs, data.resource)
  250. }
  251. provisionSampleDir(t, tmpDir, dirs)
  252. for _, info := range testData {
  253. p := filepath.Join(tmpDir, info.resource.path, info.file)
  254. ci, err := CopyInfoDestinationPath(p)
  255. assert.Check(t, err)
  256. assert.Check(t, is.DeepEqual(info.expected, ci))
  257. }
  258. }