archive.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package daemon
  2. import (
  3. "errors"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/docker/docker/builder"
  9. "github.com/docker/docker/container"
  10. "github.com/docker/docker/pkg/archive"
  11. "github.com/docker/docker/pkg/chrootarchive"
  12. "github.com/docker/docker/pkg/idtools"
  13. "github.com/docker/docker/pkg/ioutils"
  14. "github.com/docker/docker/pkg/system"
  15. "github.com/docker/engine-api/types"
  16. )
  17. // ErrExtractPointNotDirectory is used to convey that the operation to extract
  18. // a tar archive to a directory in a container has failed because the specified
  19. // path does not refer to a directory.
  20. var ErrExtractPointNotDirectory = errors.New("extraction point is not a directory")
  21. // ContainerCopy performs a deprecated operation of archiving the resource at
  22. // the specified path in the container identified by the given name.
  23. func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) {
  24. container, err := daemon.GetContainer(name)
  25. if err != nil {
  26. return nil, err
  27. }
  28. if res[0] == '/' || res[0] == '\\' {
  29. res = res[1:]
  30. }
  31. return daemon.containerCopy(container, res)
  32. }
  33. // ContainerStatPath stats the filesystem resource at the specified path in the
  34. // container identified by the given name.
  35. func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) {
  36. container, err := daemon.GetContainer(name)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return daemon.containerStatPath(container, path)
  41. }
  42. // ContainerArchivePath creates an archive of the filesystem resource at the
  43. // specified path in the container identified by the given name. Returns a
  44. // tar archive of the resource and whether it was a directory or a single file.
  45. func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
  46. container, err := daemon.GetContainer(name)
  47. if err != nil {
  48. return nil, nil, err
  49. }
  50. return daemon.containerArchivePath(container, path)
  51. }
  52. // ContainerExtractToDir extracts the given archive to the specified location
  53. // in the filesystem of the container identified by the given name. The given
  54. // path must be of a directory in the container. If it is not, the error will
  55. // be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will
  56. // be an error if unpacking the given content would cause an existing directory
  57. // to be replaced with a non-directory and vice versa.
  58. func (daemon *Daemon) ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error {
  59. container, err := daemon.GetContainer(name)
  60. if err != nil {
  61. return err
  62. }
  63. return daemon.containerExtractToDir(container, path, noOverwriteDirNonDir, content)
  64. }
  65. // containerStatPath stats the filesystem resource at the specified path in this
  66. // container. Returns stat info about the resource.
  67. func (daemon *Daemon) containerStatPath(container *container.Container, path string) (stat *types.ContainerPathStat, err error) {
  68. container.Lock()
  69. defer container.Unlock()
  70. if err = daemon.Mount(container); err != nil {
  71. return nil, err
  72. }
  73. defer daemon.Unmount(container)
  74. err = daemon.mountVolumes(container)
  75. defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
  76. if err != nil {
  77. return nil, err
  78. }
  79. resolvedPath, absPath, err := container.ResolvePath(path)
  80. if err != nil {
  81. return nil, err
  82. }
  83. return container.StatPath(resolvedPath, absPath)
  84. }
  85. // containerArchivePath creates an archive of the filesystem resource at the specified
  86. // path in this container. Returns a tar archive of the resource and stat info
  87. // about the resource.
  88. func (daemon *Daemon) containerArchivePath(container *container.Container, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
  89. container.Lock()
  90. defer func() {
  91. if err != nil {
  92. // Wait to unlock the container until the archive is fully read
  93. // (see the ReadCloseWrapper func below) or if there is an error
  94. // before that occurs.
  95. container.Unlock()
  96. }
  97. }()
  98. if err = daemon.Mount(container); err != nil {
  99. return nil, nil, err
  100. }
  101. defer func() {
  102. if err != nil {
  103. // unmount any volumes
  104. container.UnmountVolumes(true, daemon.LogVolumeEvent)
  105. // unmount the container's rootfs
  106. daemon.Unmount(container)
  107. }
  108. }()
  109. if err = daemon.mountVolumes(container); err != nil {
  110. return nil, nil, err
  111. }
  112. resolvedPath, absPath, err := container.ResolvePath(path)
  113. if err != nil {
  114. return nil, nil, err
  115. }
  116. stat, err = container.StatPath(resolvedPath, absPath)
  117. if err != nil {
  118. return nil, nil, err
  119. }
  120. // We need to rebase the archive entries if the last element of the
  121. // resolved path was a symlink that was evaluated and is now different
  122. // than the requested path. For example, if the given path was "/foo/bar/",
  123. // but it resolved to "/var/lib/docker/containers/{id}/foo/baz/", we want
  124. // to ensure that the archive entries start with "bar" and not "baz". This
  125. // also catches the case when the root directory of the container is
  126. // requested: we want the archive entries to start with "/" and not the
  127. // container ID.
  128. data, err := archive.TarResourceRebase(resolvedPath, filepath.Base(absPath))
  129. if err != nil {
  130. return nil, nil, err
  131. }
  132. content = ioutils.NewReadCloserWrapper(data, func() error {
  133. err := data.Close()
  134. container.UnmountVolumes(true, daemon.LogVolumeEvent)
  135. daemon.Unmount(container)
  136. container.Unlock()
  137. return err
  138. })
  139. daemon.LogContainerEvent(container, "archive-path")
  140. return content, stat, nil
  141. }
  142. // containerExtractToDir extracts the given tar archive to the specified location in the
  143. // filesystem of this container. The given path must be of a directory in the
  144. // container. If it is not, the error will be ErrExtractPointNotDirectory. If
  145. // noOverwriteDirNonDir is true then it will be an error if unpacking the
  146. // given content would cause an existing directory to be replaced with a non-
  147. // directory and vice versa.
  148. func (daemon *Daemon) containerExtractToDir(container *container.Container, path string, noOverwriteDirNonDir bool, content io.Reader) (err error) {
  149. container.Lock()
  150. defer container.Unlock()
  151. if err = daemon.Mount(container); err != nil {
  152. return err
  153. }
  154. defer daemon.Unmount(container)
  155. err = daemon.mountVolumes(container)
  156. defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
  157. if err != nil {
  158. return err
  159. }
  160. // Check if a drive letter supplied, it must be the system drive. No-op except on Windows
  161. path, err = system.CheckSystemDriveAndRemoveDriveLetter(path)
  162. if err != nil {
  163. return err
  164. }
  165. // The destination path needs to be resolved to a host path, with all
  166. // symbolic links followed in the scope of the container's rootfs. Note
  167. // that we do not use `container.ResolvePath(path)` here because we need
  168. // to also evaluate the last path element if it is a symlink. This is so
  169. // that you can extract an archive to a symlink that points to a directory.
  170. // Consider the given path as an absolute path in the container.
  171. absPath := archive.PreserveTrailingDotOrSeparator(filepath.Join(string(filepath.Separator), path), path)
  172. // This will evaluate the last path element if it is a symlink.
  173. resolvedPath, err := container.GetResourcePath(absPath)
  174. if err != nil {
  175. return err
  176. }
  177. stat, err := os.Lstat(resolvedPath)
  178. if err != nil {
  179. return err
  180. }
  181. if !stat.IsDir() {
  182. return ErrExtractPointNotDirectory
  183. }
  184. // Need to check if the path is in a volume. If it is, it cannot be in a
  185. // read-only volume. If it is not in a volume, the container cannot be
  186. // configured with a read-only rootfs.
  187. // Use the resolved path relative to the container rootfs as the new
  188. // absPath. This way we fully follow any symlinks in a volume that may
  189. // lead back outside the volume.
  190. //
  191. // The Windows implementation of filepath.Rel in golang 1.4 does not
  192. // support volume style file path semantics. On Windows when using the
  193. // filter driver, we are guaranteed that the path will always be
  194. // a volume file path.
  195. var baseRel string
  196. if strings.HasPrefix(resolvedPath, `\\?\Volume{`) {
  197. if strings.HasPrefix(resolvedPath, container.BaseFS) {
  198. baseRel = resolvedPath[len(container.BaseFS):]
  199. if baseRel[:1] == `\` {
  200. baseRel = baseRel[1:]
  201. }
  202. }
  203. } else {
  204. baseRel, err = filepath.Rel(container.BaseFS, resolvedPath)
  205. }
  206. if err != nil {
  207. return err
  208. }
  209. // Make it an absolute path.
  210. absPath = filepath.Join(string(filepath.Separator), baseRel)
  211. toVolume, err := checkIfPathIsInAVolume(container, absPath)
  212. if err != nil {
  213. return err
  214. }
  215. if !toVolume && container.HostConfig.ReadonlyRootfs {
  216. return ErrRootFSReadOnly
  217. }
  218. uid, gid := daemon.GetRemappedUIDGID()
  219. options := &archive.TarOptions{
  220. NoOverwriteDirNonDir: noOverwriteDirNonDir,
  221. ChownOpts: &archive.TarChownOptions{
  222. UID: uid, GID: gid, // TODO: should all ownership be set to root (either real or remapped)?
  223. },
  224. }
  225. if err := chrootarchive.Untar(content, resolvedPath, options); err != nil {
  226. return err
  227. }
  228. daemon.LogContainerEvent(container, "extract-to-dir")
  229. return nil
  230. }
  231. func (daemon *Daemon) containerCopy(container *container.Container, resource string) (rc io.ReadCloser, err error) {
  232. container.Lock()
  233. defer func() {
  234. if err != nil {
  235. // Wait to unlock the container until the archive is fully read
  236. // (see the ReadCloseWrapper func below) or if there is an error
  237. // before that occurs.
  238. container.Unlock()
  239. }
  240. }()
  241. if err := daemon.Mount(container); err != nil {
  242. return nil, err
  243. }
  244. defer func() {
  245. if err != nil {
  246. // unmount any volumes
  247. container.UnmountVolumes(true, daemon.LogVolumeEvent)
  248. // unmount the container's rootfs
  249. daemon.Unmount(container)
  250. }
  251. }()
  252. if err := daemon.mountVolumes(container); err != nil {
  253. return nil, err
  254. }
  255. basePath, err := container.GetResourcePath(resource)
  256. if err != nil {
  257. return nil, err
  258. }
  259. stat, err := os.Stat(basePath)
  260. if err != nil {
  261. return nil, err
  262. }
  263. var filter []string
  264. if !stat.IsDir() {
  265. d, f := filepath.Split(basePath)
  266. basePath = d
  267. filter = []string{f}
  268. } else {
  269. filter = []string{filepath.Base(basePath)}
  270. basePath = filepath.Dir(basePath)
  271. }
  272. archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
  273. Compression: archive.Uncompressed,
  274. IncludeFiles: filter,
  275. })
  276. if err != nil {
  277. return nil, err
  278. }
  279. reader := ioutils.NewReadCloserWrapper(archive, func() error {
  280. err := archive.Close()
  281. container.UnmountVolumes(true, daemon.LogVolumeEvent)
  282. daemon.Unmount(container)
  283. container.Unlock()
  284. return err
  285. })
  286. daemon.LogContainerEvent(container, "copy")
  287. return reader, nil
  288. }
  289. // CopyOnBuild copies/extracts a source FileInfo to a destination path inside a container
  290. // specified by a container object.
  291. // TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
  292. // CopyOnBuild should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths.
  293. func (daemon *Daemon) CopyOnBuild(cID string, destPath string, src builder.FileInfo, decompress bool) error {
  294. srcPath := src.Path()
  295. destExists := true
  296. destDir := false
  297. rootUID, rootGID := daemon.GetRemappedUIDGID()
  298. // Work in daemon-local OS specific file paths
  299. destPath = filepath.FromSlash(destPath)
  300. c, err := daemon.GetContainer(cID)
  301. if err != nil {
  302. return err
  303. }
  304. err = daemon.Mount(c)
  305. if err != nil {
  306. return err
  307. }
  308. defer daemon.Unmount(c)
  309. dest, err := c.GetResourcePath(destPath)
  310. if err != nil {
  311. return err
  312. }
  313. // Preserve the trailing slash
  314. // TODO: why are we appending another path separator if there was already one?
  315. if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." {
  316. destDir = true
  317. dest += string(os.PathSeparator)
  318. }
  319. destPath = dest
  320. destStat, err := os.Stat(destPath)
  321. if err != nil {
  322. if !os.IsNotExist(err) {
  323. //logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err)
  324. return err
  325. }
  326. destExists = false
  327. }
  328. uidMaps, gidMaps := daemon.GetUIDGIDMaps()
  329. archiver := &archive.Archiver{
  330. Untar: chrootarchive.Untar,
  331. UIDMaps: uidMaps,
  332. GIDMaps: gidMaps,
  333. }
  334. if src.IsDir() {
  335. // copy as directory
  336. if err := archiver.CopyWithTar(srcPath, destPath); err != nil {
  337. return err
  338. }
  339. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  340. }
  341. if decompress && archive.IsArchivePath(srcPath) {
  342. // Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file)
  343. // First try to unpack the source as an archive
  344. // to support the untar feature we need to clean up the path a little bit
  345. // because tar is very forgiving. First we need to strip off the archive's
  346. // filename from the path but this is only added if it does not end in slash
  347. tarDest := destPath
  348. if strings.HasSuffix(tarDest, string(os.PathSeparator)) {
  349. tarDest = filepath.Dir(destPath)
  350. }
  351. // try to successfully untar the orig
  352. err := archiver.UntarPath(srcPath, tarDest)
  353. /*
  354. if err != nil {
  355. logrus.Errorf("Couldn't untar to %s: %v", tarDest, err)
  356. }
  357. */
  358. return err
  359. }
  360. // only needed for fixPermissions, but might as well put it before CopyFileWithTar
  361. if destDir || (destExists && destStat.IsDir()) {
  362. destPath = filepath.Join(destPath, src.Name())
  363. }
  364. if err := idtools.MkdirAllNewAs(filepath.Dir(destPath), 0755, rootUID, rootGID); err != nil {
  365. return err
  366. }
  367. if err := archiver.CopyFileWithTar(srcPath, destPath); err != nil {
  368. return err
  369. }
  370. return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
  371. }