archive_unix_test.go 11 KB

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