diff.go 7.4 KB

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