archive.go 14 KB

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