copy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. package dockerfile // import "github.com/docker/docker/builder/dockerfile"
  2. import (
  3. "archive/tar"
  4. "fmt"
  5. "io"
  6. "mime"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/docker/docker/builder"
  16. "github.com/docker/docker/builder/remotecontext"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/containerfs"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/ioutils"
  21. "github.com/docker/docker/pkg/progress"
  22. "github.com/docker/docker/pkg/streamformatter"
  23. "github.com/docker/docker/pkg/system"
  24. "github.com/docker/docker/pkg/urlutil"
  25. specs "github.com/opencontainers/image-spec/specs-go/v1"
  26. "github.com/pkg/errors"
  27. )
  28. const unnamedFilename = "__unnamed__"
  29. type pathCache interface {
  30. Load(key interface{}) (value interface{}, ok bool)
  31. Store(key, value interface{})
  32. }
  33. // copyInfo is a data object which stores the metadata about each source file in
  34. // a copyInstruction
  35. type copyInfo struct {
  36. root containerfs.ContainerFS
  37. path string
  38. hash string
  39. noDecompress bool
  40. }
  41. func (c copyInfo) fullPath() (string, error) {
  42. return c.root.ResolveScopedPath(c.path, true)
  43. }
  44. func newCopyInfoFromSource(source builder.Source, path string, hash string) copyInfo {
  45. return copyInfo{root: source.Root(), path: path, hash: hash}
  46. }
  47. func newCopyInfos(copyInfos ...copyInfo) []copyInfo {
  48. return copyInfos
  49. }
  50. // copyInstruction is a fully parsed COPY or ADD command that is passed to
  51. // Builder.performCopy to copy files into the image filesystem
  52. type copyInstruction struct {
  53. cmdName string
  54. infos []copyInfo
  55. dest string
  56. chownStr string
  57. allowLocalDecompression bool
  58. preserveOwnership bool
  59. }
  60. // copier reads a raw COPY or ADD command, fetches remote sources using a downloader,
  61. // and creates a copyInstruction
  62. type copier struct {
  63. imageSource *imageMount
  64. source builder.Source
  65. pathCache pathCache
  66. download sourceDownloader
  67. platform *specs.Platform
  68. // for cleanup. TODO: having copier.cleanup() is error prone and hard to
  69. // follow. Code calling performCopy should manage the lifecycle of its params.
  70. // Copier should take override source as input, not imageMount.
  71. activeLayer builder.RWLayer
  72. tmpPaths []string
  73. }
  74. func copierFromDispatchRequest(req dispatchRequest, download sourceDownloader, imageSource *imageMount) copier {
  75. platform := req.builder.platform
  76. if platform == nil {
  77. // May be nil if not explicitly set in API/dockerfile
  78. platform = &specs.Platform{}
  79. }
  80. if platform.OS == "" {
  81. // Default to the dispatch requests operating system if not explicit in API/dockerfile
  82. platform.OS = req.state.operatingSystem
  83. }
  84. if platform.OS == "" {
  85. // This is a failsafe just in case. Shouldn't be hit.
  86. platform.OS = runtime.GOOS
  87. }
  88. return copier{
  89. source: req.source,
  90. pathCache: req.builder.pathCache,
  91. download: download,
  92. imageSource: imageSource,
  93. platform: platform,
  94. }
  95. }
  96. func (o *copier) createCopyInstruction(args []string, cmdName string) (copyInstruction, error) {
  97. inst := copyInstruction{cmdName: cmdName}
  98. last := len(args) - 1
  99. // Work in platform-specific filepath semantics
  100. // TODO: This OS switch for paths is NOT correct and should not be supported.
  101. // Maintained for backwards compatibility
  102. pathOS := runtime.GOOS
  103. if o.platform != nil {
  104. pathOS = o.platform.OS
  105. }
  106. inst.dest = fromSlash(args[last], pathOS)
  107. separator := string(separator(pathOS))
  108. infos, err := o.getCopyInfosForSourcePaths(args[0:last], inst.dest)
  109. if err != nil {
  110. return inst, errors.Wrapf(err, "%s failed", cmdName)
  111. }
  112. if len(infos) > 1 && !strings.HasSuffix(inst.dest, separator) {
  113. return inst, errors.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
  114. }
  115. inst.infos = infos
  116. return inst, nil
  117. }
  118. // getCopyInfosForSourcePaths iterates over the source files and calculate the info
  119. // needed to copy (e.g. hash value if cached)
  120. // The dest is used in case source is URL (and ends with "/")
  121. func (o *copier) getCopyInfosForSourcePaths(sources []string, dest string) ([]copyInfo, error) {
  122. var infos []copyInfo
  123. for _, orig := range sources {
  124. subinfos, err := o.getCopyInfoForSourcePath(orig, dest)
  125. if err != nil {
  126. return nil, err
  127. }
  128. infos = append(infos, subinfos...)
  129. }
  130. if len(infos) == 0 {
  131. return nil, errors.New("no source files were specified")
  132. }
  133. return infos, nil
  134. }
  135. func (o *copier) getCopyInfoForSourcePath(orig, dest string) ([]copyInfo, error) {
  136. if !urlutil.IsURL(orig) {
  137. return o.calcCopyInfo(orig, true)
  138. }
  139. remote, path, err := o.download(orig)
  140. if err != nil {
  141. return nil, err
  142. }
  143. // If path == "" then we are unable to determine filename from src
  144. // We have to make sure dest is available
  145. if path == "" {
  146. if strings.HasSuffix(dest, "/") {
  147. return nil, errors.Errorf("cannot determine filename for source %s", orig)
  148. }
  149. path = unnamedFilename
  150. }
  151. o.tmpPaths = append(o.tmpPaths, remote.Root().Path())
  152. hash, err := remote.Hash(path)
  153. ci := newCopyInfoFromSource(remote, path, hash)
  154. ci.noDecompress = true // data from http shouldn't be extracted even on ADD
  155. return newCopyInfos(ci), err
  156. }
  157. // Cleanup removes any temporary directories created as part of downloading
  158. // remote files.
  159. func (o *copier) Cleanup() {
  160. for _, path := range o.tmpPaths {
  161. os.RemoveAll(path)
  162. }
  163. o.tmpPaths = []string{}
  164. if o.activeLayer != nil {
  165. o.activeLayer.Release()
  166. o.activeLayer = nil
  167. }
  168. }
  169. // TODO: allowWildcards can probably be removed by refactoring this function further.
  170. func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, error) {
  171. imageSource := o.imageSource
  172. // TODO: do this when creating copier. Requires validateCopySourcePath
  173. // (and other below) to be aware of the difference sources. Why is it only
  174. // done on image Source?
  175. if imageSource != nil && o.activeLayer == nil {
  176. // this needs to be protected against repeated calls as wildcard copy
  177. // will call it multiple times for a single COPY
  178. var err error
  179. rwLayer, err := imageSource.NewRWLayer()
  180. if err != nil {
  181. return nil, err
  182. }
  183. o.activeLayer = rwLayer
  184. o.source, err = remotecontext.NewLazySource(rwLayer.Root())
  185. if err != nil {
  186. return nil, errors.Wrapf(err, "failed to create context for copy from %s", rwLayer.Root().Path())
  187. }
  188. }
  189. if o.source == nil {
  190. return nil, errors.Errorf("missing build context")
  191. }
  192. root := o.source.Root()
  193. if err := validateCopySourcePath(imageSource, origPath, root.OS()); err != nil {
  194. return nil, err
  195. }
  196. // Work in source OS specific filepath semantics
  197. // For LCOW, this is NOT the daemon OS.
  198. origPath = root.FromSlash(origPath)
  199. origPath = strings.TrimPrefix(origPath, string(root.Separator()))
  200. origPath = strings.TrimPrefix(origPath, "."+string(root.Separator()))
  201. // Deal with wildcards
  202. if allowWildcards && containsWildcards(origPath, root.OS()) {
  203. return o.copyWithWildcards(origPath)
  204. }
  205. if imageSource != nil && imageSource.ImageID() != "" {
  206. // return a cached copy if one exists
  207. if h, ok := o.pathCache.Load(imageSource.ImageID() + origPath); ok {
  208. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, h.(string))), nil
  209. }
  210. }
  211. // Deal with the single file case
  212. copyInfo, err := copyInfoForFile(o.source, origPath)
  213. switch {
  214. case err != nil:
  215. return nil, err
  216. case copyInfo.hash != "":
  217. o.storeInPathCache(imageSource, origPath, copyInfo.hash)
  218. return newCopyInfos(copyInfo), err
  219. }
  220. // TODO: remove, handle dirs in Hash()
  221. subfiles, err := walkSource(o.source, origPath)
  222. if err != nil {
  223. return nil, err
  224. }
  225. hash := hashStringSlice("dir", subfiles)
  226. o.storeInPathCache(imageSource, origPath, hash)
  227. return newCopyInfos(newCopyInfoFromSource(o.source, origPath, hash)), nil
  228. }
  229. func containsWildcards(name, platform string) bool {
  230. isWindows := platform == "windows"
  231. for i := 0; i < len(name); i++ {
  232. ch := name[i]
  233. if ch == '\\' && !isWindows {
  234. i++
  235. } else if ch == '*' || ch == '?' || ch == '[' {
  236. return true
  237. }
  238. }
  239. return false
  240. }
  241. func (o *copier) storeInPathCache(im *imageMount, path string, hash string) {
  242. if im != nil {
  243. o.pathCache.Store(im.ImageID()+path, hash)
  244. }
  245. }
  246. func (o *copier) copyWithWildcards(origPath string) ([]copyInfo, error) {
  247. root := o.source.Root()
  248. var copyInfos []copyInfo
  249. if err := root.Walk(root.Path(), func(path string, info os.FileInfo, err error) error {
  250. if err != nil {
  251. return err
  252. }
  253. rel, err := remotecontext.Rel(root, path)
  254. if err != nil {
  255. return err
  256. }
  257. if rel == "." {
  258. return nil
  259. }
  260. if match, _ := root.Match(origPath, rel); !match {
  261. return nil
  262. }
  263. // Note we set allowWildcards to false in case the name has
  264. // a * in it
  265. subInfos, err := o.calcCopyInfo(rel, false)
  266. if err != nil {
  267. return err
  268. }
  269. copyInfos = append(copyInfos, subInfos...)
  270. return nil
  271. }); err != nil {
  272. return nil, err
  273. }
  274. return copyInfos, nil
  275. }
  276. func copyInfoForFile(source builder.Source, path string) (copyInfo, error) {
  277. fi, err := remotecontext.StatAt(source, path)
  278. if err != nil {
  279. return copyInfo{}, err
  280. }
  281. if fi.IsDir() {
  282. return copyInfo{}, nil
  283. }
  284. hash, err := source.Hash(path)
  285. if err != nil {
  286. return copyInfo{}, err
  287. }
  288. return newCopyInfoFromSource(source, path, "file:"+hash), nil
  289. }
  290. // TODO: dedupe with copyWithWildcards()
  291. func walkSource(source builder.Source, origPath string) ([]string, error) {
  292. fp, err := remotecontext.FullPath(source, origPath)
  293. if err != nil {
  294. return nil, err
  295. }
  296. // Must be a dir
  297. var subfiles []string
  298. err = source.Root().Walk(fp, func(path string, info os.FileInfo, err error) error {
  299. if err != nil {
  300. return err
  301. }
  302. rel, err := remotecontext.Rel(source.Root(), path)
  303. if err != nil {
  304. return err
  305. }
  306. if rel == "." {
  307. return nil
  308. }
  309. hash, err := source.Hash(rel)
  310. if err != nil {
  311. return nil
  312. }
  313. // we already checked handleHash above
  314. subfiles = append(subfiles, hash)
  315. return nil
  316. })
  317. if err != nil {
  318. return nil, err
  319. }
  320. sort.Strings(subfiles)
  321. return subfiles, nil
  322. }
  323. type sourceDownloader func(string) (builder.Source, string, error)
  324. func newRemoteSourceDownloader(output, stdout io.Writer) sourceDownloader {
  325. return func(url string) (builder.Source, string, error) {
  326. return downloadSource(output, stdout, url)
  327. }
  328. }
  329. func errOnSourceDownload(_ string) (builder.Source, string, error) {
  330. return nil, "", errors.New("source can't be a URL for COPY")
  331. }
  332. func getFilenameForDownload(path string, resp *http.Response) string {
  333. // Guess filename based on source
  334. if path != "" && !strings.HasSuffix(path, "/") {
  335. if filename := filepath.Base(filepath.FromSlash(path)); filename != "" {
  336. return filename
  337. }
  338. }
  339. // Guess filename based on Content-Disposition
  340. if contentDisposition := resp.Header.Get("Content-Disposition"); contentDisposition != "" {
  341. if _, params, err := mime.ParseMediaType(contentDisposition); err == nil {
  342. if params["filename"] != "" && !strings.HasSuffix(params["filename"], "/") {
  343. if filename := filepath.Base(filepath.FromSlash(params["filename"])); filename != "" {
  344. return filename
  345. }
  346. }
  347. }
  348. }
  349. return ""
  350. }
  351. func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote builder.Source, p string, err error) {
  352. u, err := url.Parse(srcURL)
  353. if err != nil {
  354. return
  355. }
  356. resp, err := remotecontext.GetWithStatusError(srcURL)
  357. if err != nil {
  358. return
  359. }
  360. filename := getFilenameForDownload(u.Path, resp)
  361. // Prepare file in a tmp dir
  362. tmpDir, err := ioutils.TempDir("", "docker-remote")
  363. if err != nil {
  364. return
  365. }
  366. defer func() {
  367. if err != nil {
  368. os.RemoveAll(tmpDir)
  369. }
  370. }()
  371. // If filename is empty, the returned filename will be "" but
  372. // the tmp filename will be created as "__unnamed__"
  373. tmpFileName := filename
  374. if filename == "" {
  375. tmpFileName = unnamedFilename
  376. }
  377. tmpFileName = filepath.Join(tmpDir, tmpFileName)
  378. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  379. if err != nil {
  380. return
  381. }
  382. progressOutput := streamformatter.NewJSONProgressOutput(output, true)
  383. progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading")
  384. // Download and dump result to tmp file
  385. // TODO: add filehash directly
  386. if _, err = io.Copy(tmpFile, progressReader); err != nil {
  387. tmpFile.Close()
  388. return
  389. }
  390. // TODO: how important is this random blank line to the output?
  391. fmt.Fprintln(stdout)
  392. // Set the mtime to the Last-Modified header value if present
  393. // Otherwise just remove atime and mtime
  394. mTime := time.Time{}
  395. lastMod := resp.Header.Get("Last-Modified")
  396. if lastMod != "" {
  397. // If we can't parse it then just let it default to 'zero'
  398. // otherwise use the parsed time value
  399. if parsedMTime, err := http.ParseTime(lastMod); err == nil {
  400. mTime = parsedMTime
  401. }
  402. }
  403. tmpFile.Close()
  404. if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
  405. return
  406. }
  407. lc, err := remotecontext.NewLazySource(containerfs.NewLocalContainerFS(tmpDir))
  408. return lc, filename, err
  409. }
  410. type copyFileOptions struct {
  411. decompress bool
  412. identity *idtools.Identity
  413. archiver Archiver
  414. }
  415. type copyEndpoint struct {
  416. driver containerfs.Driver
  417. path string
  418. }
  419. func performCopyForInfo(dest copyInfo, source copyInfo, options copyFileOptions) error {
  420. srcPath, err := source.fullPath()
  421. if err != nil {
  422. return err
  423. }
  424. destPath, err := dest.fullPath()
  425. if err != nil {
  426. return err
  427. }
  428. archiver := options.archiver
  429. srcEndpoint := &copyEndpoint{driver: source.root, path: srcPath}
  430. destEndpoint := &copyEndpoint{driver: dest.root, path: destPath}
  431. src, err := source.root.Stat(srcPath)
  432. if err != nil {
  433. return errors.Wrapf(err, "source path not found")
  434. }
  435. if src.IsDir() {
  436. return copyDirectory(archiver, srcEndpoint, destEndpoint, options.identity)
  437. }
  438. if options.decompress && isArchivePath(source.root, srcPath) && !source.noDecompress {
  439. return archiver.UntarPath(srcPath, destPath)
  440. }
  441. destExistsAsDir, err := isExistingDirectory(destEndpoint)
  442. if err != nil {
  443. return err
  444. }
  445. // dest.path must be used because destPath has already been cleaned of any
  446. // trailing slash
  447. if endsInSlash(dest.root, dest.path) || destExistsAsDir {
  448. // source.path must be used to get the correct filename when the source
  449. // is a symlink
  450. destPath = dest.root.Join(destPath, source.root.Base(source.path))
  451. destEndpoint = &copyEndpoint{driver: dest.root, path: destPath}
  452. }
  453. return copyFile(archiver, srcEndpoint, destEndpoint, options.identity)
  454. }
  455. func isArchivePath(driver containerfs.ContainerFS, path string) bool {
  456. file, err := driver.Open(path)
  457. if err != nil {
  458. return false
  459. }
  460. defer file.Close()
  461. rdr, err := archive.DecompressStream(file)
  462. if err != nil {
  463. return false
  464. }
  465. r := tar.NewReader(rdr)
  466. _, err = r.Next()
  467. return err == nil
  468. }
  469. func copyDirectory(archiver Archiver, source, dest *copyEndpoint, identity *idtools.Identity) error {
  470. destExists, err := isExistingDirectory(dest)
  471. if err != nil {
  472. return errors.Wrapf(err, "failed to query destination path")
  473. }
  474. if err := archiver.CopyWithTar(source.path, dest.path); err != nil {
  475. return errors.Wrapf(err, "failed to copy directory")
  476. }
  477. if identity != nil {
  478. // TODO: @gupta-ak. Investigate how LCOW permission mappings will work.
  479. return fixPermissions(source.path, dest.path, *identity, !destExists)
  480. }
  481. return nil
  482. }
  483. func copyFile(archiver Archiver, source, dest *copyEndpoint, identity *idtools.Identity) error {
  484. if runtime.GOOS == "windows" && dest.driver.OS() == "linux" {
  485. // LCOW
  486. if err := dest.driver.MkdirAll(dest.driver.Dir(dest.path), 0755); err != nil {
  487. return errors.Wrapf(err, "failed to create new directory")
  488. }
  489. } else {
  490. // Normal containers
  491. if identity == nil {
  492. // Use system.MkdirAll here, which is a custom version of os.MkdirAll
  493. // modified for use on Windows to handle volume GUID paths. These paths
  494. // are of the form \\?\Volume{<GUID>}\<path>. An example would be:
  495. // \\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\bin\busybox.exe
  496. if err := system.MkdirAll(filepath.Dir(dest.path), 0755); err != nil {
  497. return err
  498. }
  499. } else {
  500. if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest.path), 0755, *identity); err != nil {
  501. return errors.Wrapf(err, "failed to create new directory")
  502. }
  503. }
  504. }
  505. if err := archiver.CopyFileWithTar(source.path, dest.path); err != nil {
  506. return errors.Wrapf(err, "failed to copy file")
  507. }
  508. if identity != nil {
  509. // TODO: @gupta-ak. Investigate how LCOW permission mappings will work.
  510. return fixPermissions(source.path, dest.path, *identity, false)
  511. }
  512. return nil
  513. }
  514. func endsInSlash(driver containerfs.Driver, path string) bool {
  515. return strings.HasSuffix(path, string(driver.Separator()))
  516. }
  517. // isExistingDirectory returns true if the path exists and is a directory
  518. func isExistingDirectory(point *copyEndpoint) (bool, error) {
  519. destStat, err := point.driver.Stat(point.path)
  520. switch {
  521. case errors.Is(err, os.ErrNotExist):
  522. return false, nil
  523. case err != nil:
  524. return false, err
  525. }
  526. return destStat.IsDir(), nil
  527. }