archive_unix_test.go 10 KB

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