diff.go 8.2 KB

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