archive_unix_test.go 11 KB

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