archive_unix_test.go 10 KB

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