copy.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. //go:build linux
  2. // +build linux
  3. package copy // import "github.com/docker/docker/daemon/graphdriver/copy"
  4. import (
  5. "container/list"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "syscall"
  12. "time"
  13. "github.com/containerd/containerd/pkg/userns"
  14. "github.com/docker/docker/pkg/pools"
  15. "github.com/docker/docker/pkg/system"
  16. "golang.org/x/sys/unix"
  17. )
  18. // Mode indicates whether to use hardlink or copy content
  19. type Mode int
  20. const (
  21. // Content creates a new file, and copies the content of the file
  22. Content Mode = iota
  23. // Hardlink creates a new hardlink to the existing file
  24. Hardlink
  25. )
  26. func copyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error {
  27. srcFile, err := os.Open(srcPath)
  28. if err != nil {
  29. return err
  30. }
  31. defer srcFile.Close()
  32. // If the destination file already exists, we shouldn't blow it away
  33. dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileinfo.Mode())
  34. if err != nil {
  35. return err
  36. }
  37. defer dstFile.Close()
  38. if *copyWithFileClone {
  39. err = unix.IoctlFileClone(int(dstFile.Fd()), int(srcFile.Fd()))
  40. if err == nil {
  41. return nil
  42. }
  43. *copyWithFileClone = false
  44. if err == unix.EXDEV {
  45. *copyWithFileRange = false
  46. }
  47. }
  48. if *copyWithFileRange {
  49. err = doCopyWithFileRange(srcFile, dstFile, fileinfo)
  50. // Trying the file_clone may not have caught the exdev case
  51. // as the ioctl may not have been available (therefore EINVAL)
  52. if err == unix.EXDEV || err == unix.ENOSYS {
  53. *copyWithFileRange = false
  54. } else {
  55. return err
  56. }
  57. }
  58. return legacyCopy(srcFile, dstFile)
  59. }
  60. func doCopyWithFileRange(srcFile, dstFile *os.File, fileinfo os.FileInfo) error {
  61. amountLeftToCopy := fileinfo.Size()
  62. for amountLeftToCopy > 0 {
  63. n, err := unix.CopyFileRange(int(srcFile.Fd()), nil, int(dstFile.Fd()), nil, int(amountLeftToCopy), 0)
  64. if err != nil {
  65. return err
  66. }
  67. amountLeftToCopy = amountLeftToCopy - int64(n)
  68. }
  69. return nil
  70. }
  71. func legacyCopy(srcFile io.Reader, dstFile io.Writer) error {
  72. _, err := pools.Copy(dstFile, srcFile)
  73. return err
  74. }
  75. func copyXattr(srcPath, dstPath, attr string) error {
  76. data, err := system.Lgetxattr(srcPath, attr)
  77. if err != nil {
  78. if errors.Is(err, syscall.EOPNOTSUPP) {
  79. // Task failed successfully: there is no xattr to copy
  80. // if the source filesystem doesn't support xattrs.
  81. return nil
  82. }
  83. return err
  84. }
  85. if data != nil {
  86. if err := system.Lsetxattr(dstPath, attr, data, 0); err != nil {
  87. return err
  88. }
  89. }
  90. return nil
  91. }
  92. type fileID struct {
  93. dev uint64
  94. ino uint64
  95. }
  96. type dirMtimeInfo struct {
  97. dstPath *string
  98. stat *syscall.Stat_t
  99. }
  100. // DirCopy copies or hardlinks the contents of one directory to another, properly
  101. // handling soft links, "security.capability" and (optionally) "trusted.overlay.opaque"
  102. // xattrs.
  103. //
  104. // The copyOpaqueXattrs controls if "trusted.overlay.opaque" xattrs are copied.
  105. // Passing false disables copying "trusted.overlay.opaque" xattrs.
  106. func DirCopy(srcDir, dstDir string, copyMode Mode, copyOpaqueXattrs bool) error {
  107. copyWithFileRange := true
  108. copyWithFileClone := true
  109. // This is a map of source file inodes to dst file paths
  110. copiedFiles := make(map[fileID]string)
  111. dirsToSetMtimes := list.New()
  112. err := filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error {
  113. if err != nil {
  114. return err
  115. }
  116. // Rebase path
  117. relPath, err := filepath.Rel(srcDir, srcPath)
  118. if err != nil {
  119. return err
  120. }
  121. dstPath := filepath.Join(dstDir, relPath)
  122. stat, ok := f.Sys().(*syscall.Stat_t)
  123. if !ok {
  124. return fmt.Errorf("Unable to get raw syscall.Stat_t data for %s", srcPath)
  125. }
  126. isHardlink := false
  127. switch mode := f.Mode(); {
  128. case mode.IsRegular():
  129. // the type is 32bit on mips
  130. id := fileID{dev: uint64(stat.Dev), ino: stat.Ino} //nolint: unconvert
  131. if copyMode == Hardlink {
  132. isHardlink = true
  133. if err2 := os.Link(srcPath, dstPath); err2 != nil {
  134. return err2
  135. }
  136. } else if hardLinkDstPath, ok := copiedFiles[id]; ok {
  137. if err2 := os.Link(hardLinkDstPath, dstPath); err2 != nil {
  138. return err2
  139. }
  140. } else {
  141. if err2 := copyRegular(srcPath, dstPath, f, &copyWithFileRange, &copyWithFileClone); err2 != nil {
  142. return err2
  143. }
  144. copiedFiles[id] = dstPath
  145. }
  146. case mode.IsDir():
  147. if err := os.Mkdir(dstPath, f.Mode()); err != nil && !os.IsExist(err) {
  148. return err
  149. }
  150. case mode&os.ModeSymlink != 0:
  151. link, err := os.Readlink(srcPath)
  152. if err != nil {
  153. return err
  154. }
  155. if err := os.Symlink(link, dstPath); err != nil {
  156. return err
  157. }
  158. case mode&os.ModeNamedPipe != 0:
  159. fallthrough
  160. case mode&os.ModeSocket != 0:
  161. if err := unix.Mkfifo(dstPath, stat.Mode); err != nil {
  162. return err
  163. }
  164. case mode&os.ModeDevice != 0:
  165. if userns.RunningInUserNS() {
  166. // cannot create a device if running in user namespace
  167. return nil
  168. }
  169. if err := unix.Mknod(dstPath, stat.Mode, int(stat.Rdev)); err != nil {
  170. return err
  171. }
  172. default:
  173. return fmt.Errorf("unknown file type (%d / %s) for %s", f.Mode(), f.Mode().String(), srcPath)
  174. }
  175. // Everything below is copying metadata from src to dst. All this metadata
  176. // already shares an inode for hardlinks.
  177. if isHardlink {
  178. return nil
  179. }
  180. if err := os.Lchown(dstPath, int(stat.Uid), int(stat.Gid)); err != nil {
  181. return err
  182. }
  183. if err := copyXattr(srcPath, dstPath, "security.capability"); err != nil {
  184. return err
  185. }
  186. if copyOpaqueXattrs {
  187. if err := doCopyXattrs(srcPath, dstPath); err != nil {
  188. return err
  189. }
  190. }
  191. isSymlink := f.Mode()&os.ModeSymlink != 0
  192. // There is no LChmod, so ignore mode for symlink. Also, this
  193. // must happen after chown, as that can modify the file mode
  194. if !isSymlink {
  195. if err := os.Chmod(dstPath, f.Mode()); err != nil {
  196. return err
  197. }
  198. }
  199. // system.Chtimes doesn't support a NOFOLLOW flag atm
  200. //nolint: unconvert
  201. if f.IsDir() {
  202. dirsToSetMtimes.PushFront(&dirMtimeInfo{dstPath: &dstPath, stat: stat})
  203. } else if !isSymlink {
  204. aTime := time.Unix(stat.Atim.Unix())
  205. mTime := time.Unix(stat.Mtim.Unix())
  206. if err := system.Chtimes(dstPath, aTime, mTime); err != nil {
  207. return err
  208. }
  209. } else {
  210. ts := []syscall.Timespec{stat.Atim, stat.Mtim}
  211. if err := system.LUtimesNano(dstPath, ts); err != nil {
  212. return err
  213. }
  214. }
  215. return nil
  216. })
  217. if err != nil {
  218. return err
  219. }
  220. for e := dirsToSetMtimes.Front(); e != nil; e = e.Next() {
  221. mtimeInfo := e.Value.(*dirMtimeInfo)
  222. ts := []syscall.Timespec{mtimeInfo.stat.Atim, mtimeInfo.stat.Mtim}
  223. if err := system.LUtimesNano(*mtimeInfo.dstPath, ts); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. func doCopyXattrs(srcPath, dstPath string) error {
  230. // We need to copy this attribute if it appears in an overlay upper layer, as
  231. // this function is used to copy those. It is set by overlay if a directory
  232. // is removed and then re-created and should not inherit anything from the
  233. // same dir in the lower dir.
  234. return copyXattr(srcPath, dstPath, "trusted.overlay.opaque")
  235. }