diff.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package archive // import "github.com/docker/docker/pkg/archive"
  2. import (
  3. "archive/tar"
  4. "context"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "github.com/containerd/containerd/log"
  12. "github.com/docker/docker/pkg/pools"
  13. "github.com/docker/docker/pkg/system"
  14. )
  15. // UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be
  16. // compressed or uncompressed.
  17. // Returns the size in bytes of the contents of the layer.
  18. func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) {
  19. tr := tar.NewReader(layer)
  20. trBuf := pools.BufioReader32KPool.Get(tr)
  21. defer pools.BufioReader32KPool.Put(trBuf)
  22. var dirs []*tar.Header
  23. unpackedPaths := make(map[string]struct{})
  24. if options == nil {
  25. options = &TarOptions{}
  26. }
  27. if options.ExcludePatterns == nil {
  28. options.ExcludePatterns = []string{}
  29. }
  30. aufsTempdir := ""
  31. aufsHardlinks := make(map[string]*tar.Header)
  32. // Iterate through the files in the archive.
  33. for {
  34. hdr, err := tr.Next()
  35. if err == io.EOF {
  36. // end of tar archive
  37. break
  38. }
  39. if err != nil {
  40. return 0, err
  41. }
  42. size += hdr.Size
  43. // Normalize name, for safety and for a simple is-root check
  44. hdr.Name = filepath.Clean(hdr.Name)
  45. // Windows does not support filenames with colons in them. Ignore
  46. // these files. This is not a problem though (although it might
  47. // appear that it is). Let's suppose a client is running docker pull.
  48. // The daemon it points to is Windows. Would it make sense for the
  49. // client to be doing a docker pull Ubuntu for example (which has files
  50. // with colons in the name under /usr/share/man/man3)? No, absolutely
  51. // not as it would really only make sense that they were pulling a
  52. // Windows image. However, for development, it is necessary to be able
  53. // to pull Linux images which are in the repository.
  54. //
  55. // TODO Windows. Once the registry is aware of what images are Windows-
  56. // specific or Linux-specific, this warning should be changed to an error
  57. // to cater for the situation where someone does manage to upload a Linux
  58. // image but have it tagged as Windows inadvertently.
  59. if runtime.GOOS == "windows" {
  60. if strings.Contains(hdr.Name, ":") {
  61. log.G(context.TODO()).Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name)
  62. continue
  63. }
  64. }
  65. // Ensure that the parent directory exists.
  66. err = createImpliedDirectories(dest, hdr, options)
  67. if err != nil {
  68. return 0, err
  69. }
  70. // Skip AUFS metadata dirs
  71. if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) {
  72. // Regular files inside /.wh..wh.plnk can be used as hardlink targets
  73. // We don't want this directory, but we need the files in them so that
  74. // such hardlinks can be resolved.
  75. if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg {
  76. basename := filepath.Base(hdr.Name)
  77. aufsHardlinks[basename] = hdr
  78. if aufsTempdir == "" {
  79. if aufsTempdir, err = os.MkdirTemp(dest, "dockerplnk"); err != nil {
  80. return 0, err
  81. }
  82. defer os.RemoveAll(aufsTempdir)
  83. }
  84. if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, options); err != nil {
  85. return 0, err
  86. }
  87. }
  88. if hdr.Name != WhiteoutOpaqueDir {
  89. continue
  90. }
  91. }
  92. //#nosec G305 -- The joined path is guarded against path traversal.
  93. path := filepath.Join(dest, hdr.Name)
  94. rel, err := filepath.Rel(dest, path)
  95. if err != nil {
  96. return 0, err
  97. }
  98. // Note as these operations are platform specific, so must the slash be.
  99. if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
  100. return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
  101. }
  102. base := filepath.Base(path)
  103. if strings.HasPrefix(base, WhiteoutPrefix) {
  104. dir := filepath.Dir(path)
  105. if base == WhiteoutOpaqueDir {
  106. _, err := os.Lstat(dir)
  107. if err != nil {
  108. return 0, err
  109. }
  110. err = filepath.WalkDir(dir, func(path string, info os.DirEntry, err error) error {
  111. if err != nil {
  112. if os.IsNotExist(err) {
  113. err = nil // parent was deleted
  114. }
  115. return err
  116. }
  117. if path == dir {
  118. return nil
  119. }
  120. if _, exists := unpackedPaths[path]; !exists {
  121. return os.RemoveAll(path)
  122. }
  123. return nil
  124. })
  125. if err != nil {
  126. return 0, err
  127. }
  128. } else {
  129. originalBase := base[len(WhiteoutPrefix):]
  130. originalPath := filepath.Join(dir, originalBase)
  131. if err := os.RemoveAll(originalPath); err != nil {
  132. return 0, err
  133. }
  134. }
  135. } else {
  136. // If path exits we almost always just want to remove and replace it.
  137. // The only exception is when it is a directory *and* the file from
  138. // the layer is also a directory. Then we want to merge them (i.e.
  139. // just apply the metadata from the layer).
  140. if fi, err := os.Lstat(path); err == nil {
  141. if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
  142. if err := os.RemoveAll(path); err != nil {
  143. return 0, err
  144. }
  145. }
  146. }
  147. trBuf.Reset(tr)
  148. srcData := io.Reader(trBuf)
  149. srcHdr := hdr
  150. // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
  151. // we manually retarget these into the temporary files we extracted them into
  152. if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) {
  153. linkBasename := filepath.Base(hdr.Linkname)
  154. srcHdr = aufsHardlinks[linkBasename]
  155. if srcHdr == nil {
  156. return 0, fmt.Errorf("Invalid aufs hardlink")
  157. }
  158. tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename))
  159. if err != nil {
  160. return 0, err
  161. }
  162. defer tmpFile.Close()
  163. srcData = tmpFile
  164. }
  165. if err := remapIDs(options.IDMap, srcHdr); err != nil {
  166. return 0, err
  167. }
  168. if err := createTarFile(path, dest, srcHdr, srcData, options); err != nil {
  169. return 0, err
  170. }
  171. // Directory mtimes must be handled at the end to avoid further
  172. // file creation in them to modify the directory mtime
  173. if hdr.Typeflag == tar.TypeDir {
  174. dirs = append(dirs, hdr)
  175. }
  176. unpackedPaths[path] = struct{}{}
  177. }
  178. }
  179. for _, hdr := range dirs {
  180. //#nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice.
  181. path := filepath.Join(dest, hdr.Name)
  182. if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil {
  183. return 0, err
  184. }
  185. }
  186. return size, nil
  187. }
  188. // ApplyLayer parses a diff in the standard layer format from `layer`,
  189. // and applies it to the directory `dest`. The stream `layer` can be
  190. // compressed or uncompressed.
  191. // Returns the size in bytes of the contents of the layer.
  192. func ApplyLayer(dest string, layer io.Reader) (int64, error) {
  193. return applyLayerHandler(dest, layer, &TarOptions{}, true)
  194. }
  195. // ApplyUncompressedLayer parses a diff in the standard layer format from
  196. // `layer`, and applies it to the directory `dest`. The stream `layer`
  197. // can only be uncompressed.
  198. // Returns the size in bytes of the contents of the layer.
  199. func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) (int64, error) {
  200. return applyLayerHandler(dest, layer, options, false)
  201. }
  202. // IsEmpty checks if the tar archive is empty (doesn't contain any entries).
  203. func IsEmpty(rd io.Reader) (bool, error) {
  204. decompRd, err := DecompressStream(rd)
  205. if err != nil {
  206. return true, fmt.Errorf("failed to decompress archive: %v", err)
  207. }
  208. defer decompRd.Close()
  209. tarReader := tar.NewReader(decompRd)
  210. if _, err := tarReader.Next(); err != nil {
  211. if err == io.EOF {
  212. return true, nil
  213. }
  214. return false, fmt.Errorf("failed to read next archive header: %v", err)
  215. }
  216. return false, nil
  217. }
  218. // do the bulk load of ApplyLayer, but allow for not calling DecompressStream
  219. func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) {
  220. dest = filepath.Clean(dest)
  221. // We need to be able to set any perms
  222. restore := overrideUmask(0)
  223. defer restore()
  224. if decompress {
  225. decompLayer, err := DecompressStream(layer)
  226. if err != nil {
  227. return 0, err
  228. }
  229. defer decompLayer.Close()
  230. layer = decompLayer
  231. }
  232. return UnpackLayer(dest, layer, options)
  233. }