archive_unix_test.go 11 KB

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