diff.go 8.5 KB

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