diff.go 8.5 KB

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