pull_v2.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. package distribution
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/url"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "github.com/docker/distribution"
  12. "github.com/docker/distribution/manifest/manifestlist"
  13. "github.com/docker/distribution/manifest/schema1"
  14. "github.com/docker/distribution/manifest/schema2"
  15. "github.com/docker/distribution/reference"
  16. "github.com/docker/distribution/registry/api/errcode"
  17. "github.com/docker/distribution/registry/client/auth"
  18. "github.com/docker/distribution/registry/client/transport"
  19. "github.com/docker/docker/distribution/metadata"
  20. "github.com/docker/docker/distribution/xfer"
  21. "github.com/docker/docker/image"
  22. "github.com/docker/docker/image/v1"
  23. "github.com/docker/docker/layer"
  24. "github.com/docker/docker/pkg/ioutils"
  25. "github.com/docker/docker/pkg/progress"
  26. "github.com/docker/docker/pkg/stringid"
  27. "github.com/docker/docker/pkg/system"
  28. refstore "github.com/docker/docker/reference"
  29. "github.com/docker/docker/registry"
  30. digest "github.com/opencontainers/go-digest"
  31. "github.com/pkg/errors"
  32. "github.com/sirupsen/logrus"
  33. "golang.org/x/net/context"
  34. )
  35. var (
  36. errRootFSMismatch = errors.New("layers from manifest don't match image configuration")
  37. errRootFSInvalid = errors.New("invalid rootfs in image configuration")
  38. )
  39. // ImageConfigPullError is an error pulling the image config blob
  40. // (only applies to schema2).
  41. type ImageConfigPullError struct {
  42. Err error
  43. }
  44. // Error returns the error string for ImageConfigPullError.
  45. func (e ImageConfigPullError) Error() string {
  46. return "error pulling image configuration: " + e.Err.Error()
  47. }
  48. type v2Puller struct {
  49. V2MetadataService metadata.V2MetadataService
  50. endpoint registry.APIEndpoint
  51. config *ImagePullConfig
  52. repoInfo *registry.RepositoryInfo
  53. repo distribution.Repository
  54. // confirmedV2 is set to true if we confirm we're talking to a v2
  55. // registry. This is used to limit fallbacks to the v1 protocol.
  56. confirmedV2 bool
  57. }
  58. func (p *v2Puller) Pull(ctx context.Context, ref reference.Named, platform string) (err error) {
  59. // TODO(tiborvass): was ReceiveTimeout
  60. p.repo, p.confirmedV2, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
  61. if err != nil {
  62. logrus.Warnf("Error getting v2 registry: %v", err)
  63. return err
  64. }
  65. if err = p.pullV2Repository(ctx, ref, platform); err != nil {
  66. if _, ok := err.(fallbackError); ok {
  67. return err
  68. }
  69. if continueOnError(err, p.endpoint.Mirror) {
  70. return fallbackError{
  71. err: err,
  72. confirmedV2: p.confirmedV2,
  73. transportOK: true,
  74. }
  75. }
  76. }
  77. return err
  78. }
  79. func (p *v2Puller) pullV2Repository(ctx context.Context, ref reference.Named, platform string) (err error) {
  80. var layersDownloaded bool
  81. if !reference.IsNameOnly(ref) {
  82. layersDownloaded, err = p.pullV2Tag(ctx, ref, platform)
  83. if err != nil {
  84. return err
  85. }
  86. } else {
  87. tags, err := p.repo.Tags(ctx).All(ctx)
  88. if err != nil {
  89. // If this repository doesn't exist on V2, we should
  90. // permit a fallback to V1.
  91. return allowV1Fallback(err)
  92. }
  93. // The v2 registry knows about this repository, so we will not
  94. // allow fallback to the v1 protocol even if we encounter an
  95. // error later on.
  96. p.confirmedV2 = true
  97. for _, tag := range tags {
  98. tagRef, err := reference.WithTag(ref, tag)
  99. if err != nil {
  100. return err
  101. }
  102. pulledNew, err := p.pullV2Tag(ctx, tagRef, platform)
  103. if err != nil {
  104. // Since this is the pull-all-tags case, don't
  105. // allow an error pulling a particular tag to
  106. // make the whole pull fall back to v1.
  107. if fallbackErr, ok := err.(fallbackError); ok {
  108. return fallbackErr.err
  109. }
  110. return err
  111. }
  112. // pulledNew is true if either new layers were downloaded OR if existing images were newly tagged
  113. // TODO(tiborvass): should we change the name of `layersDownload`? What about message in WriteStatus?
  114. layersDownloaded = layersDownloaded || pulledNew
  115. }
  116. }
  117. writeStatus(reference.FamiliarString(ref), p.config.ProgressOutput, layersDownloaded)
  118. return nil
  119. }
  120. type v2LayerDescriptor struct {
  121. digest digest.Digest
  122. diffID layer.DiffID
  123. repoInfo *registry.RepositoryInfo
  124. repo distribution.Repository
  125. V2MetadataService metadata.V2MetadataService
  126. tmpFile *os.File
  127. verifier digest.Verifier
  128. src distribution.Descriptor
  129. }
  130. func (ld *v2LayerDescriptor) Key() string {
  131. return "v2:" + ld.digest.String()
  132. }
  133. func (ld *v2LayerDescriptor) ID() string {
  134. return stringid.TruncateID(ld.digest.String())
  135. }
  136. func (ld *v2LayerDescriptor) DiffID() (layer.DiffID, error) {
  137. if ld.diffID != "" {
  138. return ld.diffID, nil
  139. }
  140. return ld.V2MetadataService.GetDiffID(ld.digest)
  141. }
  142. func (ld *v2LayerDescriptor) Download(ctx context.Context, progressOutput progress.Output) (io.ReadCloser, int64, error) {
  143. logrus.Debugf("pulling blob %q", ld.digest)
  144. var (
  145. err error
  146. offset int64
  147. )
  148. if ld.tmpFile == nil {
  149. ld.tmpFile, err = createDownloadFile()
  150. if err != nil {
  151. return nil, 0, xfer.DoNotRetry{Err: err}
  152. }
  153. } else {
  154. offset, err = ld.tmpFile.Seek(0, os.SEEK_END)
  155. if err != nil {
  156. logrus.Debugf("error seeking to end of download file: %v", err)
  157. offset = 0
  158. ld.tmpFile.Close()
  159. if err := os.Remove(ld.tmpFile.Name()); err != nil {
  160. logrus.Errorf("Failed to remove temp file: %s", ld.tmpFile.Name())
  161. }
  162. ld.tmpFile, err = createDownloadFile()
  163. if err != nil {
  164. return nil, 0, xfer.DoNotRetry{Err: err}
  165. }
  166. } else if offset != 0 {
  167. logrus.Debugf("attempting to resume download of %q from %d bytes", ld.digest, offset)
  168. }
  169. }
  170. tmpFile := ld.tmpFile
  171. layerDownload, err := ld.open(ctx)
  172. if err != nil {
  173. logrus.Errorf("Error initiating layer download: %v", err)
  174. return nil, 0, retryOnError(err)
  175. }
  176. if offset != 0 {
  177. _, err := layerDownload.Seek(offset, os.SEEK_SET)
  178. if err != nil {
  179. if err := ld.truncateDownloadFile(); err != nil {
  180. return nil, 0, xfer.DoNotRetry{Err: err}
  181. }
  182. return nil, 0, err
  183. }
  184. }
  185. size, err := layerDownload.Seek(0, os.SEEK_END)
  186. if err != nil {
  187. // Seek failed, perhaps because there was no Content-Length
  188. // header. This shouldn't fail the download, because we can
  189. // still continue without a progress bar.
  190. size = 0
  191. } else {
  192. if size != 0 && offset > size {
  193. logrus.Debug("Partial download is larger than full blob. Starting over")
  194. offset = 0
  195. if err := ld.truncateDownloadFile(); err != nil {
  196. return nil, 0, xfer.DoNotRetry{Err: err}
  197. }
  198. }
  199. // Restore the seek offset either at the beginning of the
  200. // stream, or just after the last byte we have from previous
  201. // attempts.
  202. _, err = layerDownload.Seek(offset, os.SEEK_SET)
  203. if err != nil {
  204. return nil, 0, err
  205. }
  206. }
  207. reader := progress.NewProgressReader(ioutils.NewCancelReadCloser(ctx, layerDownload), progressOutput, size-offset, ld.ID(), "Downloading")
  208. defer reader.Close()
  209. if ld.verifier == nil {
  210. ld.verifier = ld.digest.Verifier()
  211. }
  212. _, err = io.Copy(tmpFile, io.TeeReader(reader, ld.verifier))
  213. if err != nil {
  214. if err == transport.ErrWrongCodeForByteRange {
  215. if err := ld.truncateDownloadFile(); err != nil {
  216. return nil, 0, xfer.DoNotRetry{Err: err}
  217. }
  218. return nil, 0, err
  219. }
  220. return nil, 0, retryOnError(err)
  221. }
  222. progress.Update(progressOutput, ld.ID(), "Verifying Checksum")
  223. if !ld.verifier.Verified() {
  224. err = fmt.Errorf("filesystem layer verification failed for digest %s", ld.digest)
  225. logrus.Error(err)
  226. // Allow a retry if this digest verification error happened
  227. // after a resumed download.
  228. if offset != 0 {
  229. if err := ld.truncateDownloadFile(); err != nil {
  230. return nil, 0, xfer.DoNotRetry{Err: err}
  231. }
  232. return nil, 0, err
  233. }
  234. return nil, 0, xfer.DoNotRetry{Err: err}
  235. }
  236. progress.Update(progressOutput, ld.ID(), "Download complete")
  237. logrus.Debugf("Downloaded %s to tempfile %s", ld.ID(), tmpFile.Name())
  238. _, err = tmpFile.Seek(0, os.SEEK_SET)
  239. if err != nil {
  240. tmpFile.Close()
  241. if err := os.Remove(tmpFile.Name()); err != nil {
  242. logrus.Errorf("Failed to remove temp file: %s", tmpFile.Name())
  243. }
  244. ld.tmpFile = nil
  245. ld.verifier = nil
  246. return nil, 0, xfer.DoNotRetry{Err: err}
  247. }
  248. // hand off the temporary file to the download manager, so it will only
  249. // be closed once
  250. ld.tmpFile = nil
  251. return ioutils.NewReadCloserWrapper(tmpFile, func() error {
  252. tmpFile.Close()
  253. err := os.RemoveAll(tmpFile.Name())
  254. if err != nil {
  255. logrus.Errorf("Failed to remove temp file: %s", tmpFile.Name())
  256. }
  257. return err
  258. }), size, nil
  259. }
  260. func (ld *v2LayerDescriptor) Close() {
  261. if ld.tmpFile != nil {
  262. ld.tmpFile.Close()
  263. if err := os.RemoveAll(ld.tmpFile.Name()); err != nil {
  264. logrus.Errorf("Failed to remove temp file: %s", ld.tmpFile.Name())
  265. }
  266. }
  267. }
  268. func (ld *v2LayerDescriptor) truncateDownloadFile() error {
  269. // Need a new hash context since we will be redoing the download
  270. ld.verifier = nil
  271. if _, err := ld.tmpFile.Seek(0, os.SEEK_SET); err != nil {
  272. logrus.Errorf("error seeking to beginning of download file: %v", err)
  273. return err
  274. }
  275. if err := ld.tmpFile.Truncate(0); err != nil {
  276. logrus.Errorf("error truncating download file: %v", err)
  277. return err
  278. }
  279. return nil
  280. }
  281. func (ld *v2LayerDescriptor) Registered(diffID layer.DiffID) {
  282. // Cache mapping from this layer's DiffID to the blobsum
  283. ld.V2MetadataService.Add(diffID, metadata.V2Metadata{Digest: ld.digest, SourceRepository: ld.repoInfo.Name.Name()})
  284. }
  285. func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named, os string) (tagUpdated bool, err error) {
  286. manSvc, err := p.repo.Manifests(ctx)
  287. if err != nil {
  288. return false, err
  289. }
  290. var (
  291. manifest distribution.Manifest
  292. tagOrDigest string // Used for logging/progress only
  293. )
  294. if digested, isDigested := ref.(reference.Canonical); isDigested {
  295. manifest, err = manSvc.Get(ctx, digested.Digest())
  296. if err != nil {
  297. return false, err
  298. }
  299. tagOrDigest = digested.Digest().String()
  300. } else if tagged, isTagged := ref.(reference.NamedTagged); isTagged {
  301. manifest, err = manSvc.Get(ctx, "", distribution.WithTag(tagged.Tag()))
  302. if err != nil {
  303. return false, allowV1Fallback(err)
  304. }
  305. tagOrDigest = tagged.Tag()
  306. } else {
  307. return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", reference.FamiliarString(ref))
  308. }
  309. if manifest == nil {
  310. return false, fmt.Errorf("image manifest does not exist for tag or digest %q", tagOrDigest)
  311. }
  312. if m, ok := manifest.(*schema2.DeserializedManifest); ok {
  313. var allowedMediatype bool
  314. for _, t := range p.config.Schema2Types {
  315. if m.Manifest.Config.MediaType == t {
  316. allowedMediatype = true
  317. break
  318. }
  319. }
  320. if !allowedMediatype {
  321. configClass := mediaTypeClasses[m.Manifest.Config.MediaType]
  322. if configClass == "" {
  323. configClass = "unknown"
  324. }
  325. return false, invalidManifestClassError{m.Manifest.Config.MediaType, configClass}
  326. }
  327. }
  328. // If manSvc.Get succeeded, we can be confident that the registry on
  329. // the other side speaks the v2 protocol.
  330. p.confirmedV2 = true
  331. logrus.Debugf("Pulling ref from V2 registry: %s", reference.FamiliarString(ref))
  332. progress.Message(p.config.ProgressOutput, tagOrDigest, "Pulling from "+reference.FamiliarName(p.repo.Named()))
  333. var (
  334. id digest.Digest
  335. manifestDigest digest.Digest
  336. )
  337. switch v := manifest.(type) {
  338. case *schema1.SignedManifest:
  339. if p.config.RequireSchema2 {
  340. return false, fmt.Errorf("invalid manifest: not schema2")
  341. }
  342. id, manifestDigest, err = p.pullSchema1(ctx, ref, v, os)
  343. if err != nil {
  344. return false, err
  345. }
  346. case *schema2.DeserializedManifest:
  347. id, manifestDigest, err = p.pullSchema2(ctx, ref, v, os)
  348. if err != nil {
  349. return false, err
  350. }
  351. case *manifestlist.DeserializedManifestList:
  352. id, manifestDigest, err = p.pullManifestList(ctx, ref, v, os)
  353. if err != nil {
  354. return false, err
  355. }
  356. default:
  357. return false, invalidManifestFormatError{}
  358. }
  359. progress.Message(p.config.ProgressOutput, "", "Digest: "+manifestDigest.String())
  360. if p.config.ReferenceStore != nil {
  361. oldTagID, err := p.config.ReferenceStore.Get(ref)
  362. if err == nil {
  363. if oldTagID == id {
  364. return false, addDigestReference(p.config.ReferenceStore, ref, manifestDigest, id)
  365. }
  366. } else if err != refstore.ErrDoesNotExist {
  367. return false, err
  368. }
  369. if canonical, ok := ref.(reference.Canonical); ok {
  370. if err = p.config.ReferenceStore.AddDigest(canonical, id, true); err != nil {
  371. return false, err
  372. }
  373. } else {
  374. if err = addDigestReference(p.config.ReferenceStore, ref, manifestDigest, id); err != nil {
  375. return false, err
  376. }
  377. if err = p.config.ReferenceStore.AddTag(ref, id, true); err != nil {
  378. return false, err
  379. }
  380. }
  381. }
  382. return true, nil
  383. }
  384. func (p *v2Puller) pullSchema1(ctx context.Context, ref reference.Reference, unverifiedManifest *schema1.SignedManifest, requestedOS string) (id digest.Digest, manifestDigest digest.Digest, err error) {
  385. var verifiedManifest *schema1.Manifest
  386. verifiedManifest, err = verifySchema1Manifest(unverifiedManifest, ref)
  387. if err != nil {
  388. return "", "", err
  389. }
  390. rootFS := image.NewRootFS()
  391. // remove duplicate layers and check parent chain validity
  392. err = fixManifestLayers(verifiedManifest)
  393. if err != nil {
  394. return "", "", err
  395. }
  396. var descriptors []xfer.DownloadDescriptor
  397. // Image history converted to the new format
  398. var history []image.History
  399. // Note that the order of this loop is in the direction of bottom-most
  400. // to top-most, so that the downloads slice gets ordered correctly.
  401. for i := len(verifiedManifest.FSLayers) - 1; i >= 0; i-- {
  402. blobSum := verifiedManifest.FSLayers[i].BlobSum
  403. var throwAway struct {
  404. ThrowAway bool `json:"throwaway,omitempty"`
  405. }
  406. if err := json.Unmarshal([]byte(verifiedManifest.History[i].V1Compatibility), &throwAway); err != nil {
  407. return "", "", err
  408. }
  409. h, err := v1.HistoryFromConfig([]byte(verifiedManifest.History[i].V1Compatibility), throwAway.ThrowAway)
  410. if err != nil {
  411. return "", "", err
  412. }
  413. history = append(history, h)
  414. if throwAway.ThrowAway {
  415. continue
  416. }
  417. layerDescriptor := &v2LayerDescriptor{
  418. digest: blobSum,
  419. repoInfo: p.repoInfo,
  420. repo: p.repo,
  421. V2MetadataService: p.V2MetadataService,
  422. }
  423. descriptors = append(descriptors, layerDescriptor)
  424. }
  425. // The v1 manifest itself doesn't directly contain a platform. However,
  426. // the history does, but unfortunately that's a string, so search through
  427. // all the history until hopefully we find one which indicates the os.
  428. // supertest2014/nyan is an example of a registry image with schemav1.
  429. configOS := runtime.GOOS
  430. if system.LCOWSupported() {
  431. type config struct {
  432. Os string `json:"os,omitempty"`
  433. }
  434. for _, v := range verifiedManifest.History {
  435. var c config
  436. if err := json.Unmarshal([]byte(v.V1Compatibility), &c); err == nil {
  437. if c.Os != "" {
  438. configOS = c.Os
  439. break
  440. }
  441. }
  442. }
  443. }
  444. // Early bath if the requested OS doesn't match that of the configuration.
  445. // This avoids doing the download, only to potentially fail later.
  446. if !strings.EqualFold(configOS, requestedOS) {
  447. return "", "", fmt.Errorf("cannot download image with operating system %q when requesting %q", configOS, requestedOS)
  448. }
  449. resultRootFS, release, err := p.config.DownloadManager.Download(ctx, *rootFS, layer.OS(configOS), descriptors, p.config.ProgressOutput)
  450. if err != nil {
  451. return "", "", err
  452. }
  453. defer release()
  454. config, err := v1.MakeConfigFromV1Config([]byte(verifiedManifest.History[0].V1Compatibility), &resultRootFS, history)
  455. if err != nil {
  456. return "", "", err
  457. }
  458. imageID, err := p.config.ImageStore.Put(config)
  459. if err != nil {
  460. return "", "", err
  461. }
  462. manifestDigest = digest.FromBytes(unverifiedManifest.Canonical)
  463. return imageID, manifestDigest, nil
  464. }
  465. func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *schema2.DeserializedManifest, requestedOS string) (id digest.Digest, manifestDigest digest.Digest, err error) {
  466. manifestDigest, err = schema2ManifestDigest(ref, mfst)
  467. if err != nil {
  468. return "", "", err
  469. }
  470. target := mfst.Target()
  471. if _, err := p.config.ImageStore.Get(target.Digest); err == nil {
  472. // If the image already exists locally, no need to pull
  473. // anything.
  474. return target.Digest, manifestDigest, nil
  475. }
  476. var descriptors []xfer.DownloadDescriptor
  477. // Note that the order of this loop is in the direction of bottom-most
  478. // to top-most, so that the downloads slice gets ordered correctly.
  479. for _, d := range mfst.Layers {
  480. layerDescriptor := &v2LayerDescriptor{
  481. digest: d.Digest,
  482. repo: p.repo,
  483. repoInfo: p.repoInfo,
  484. V2MetadataService: p.V2MetadataService,
  485. src: d,
  486. }
  487. descriptors = append(descriptors, layerDescriptor)
  488. }
  489. configChan := make(chan []byte, 1)
  490. configErrChan := make(chan error, 1)
  491. layerErrChan := make(chan error, 1)
  492. downloadsDone := make(chan struct{})
  493. var cancel func()
  494. ctx, cancel = context.WithCancel(ctx)
  495. defer cancel()
  496. // Pull the image config
  497. go func() {
  498. configJSON, err := p.pullSchema2Config(ctx, target.Digest)
  499. if err != nil {
  500. configErrChan <- ImageConfigPullError{Err: err}
  501. cancel()
  502. return
  503. }
  504. configChan <- configJSON
  505. }()
  506. var (
  507. configJSON []byte // raw serialized image config
  508. downloadedRootFS *image.RootFS // rootFS from registered layers
  509. configRootFS *image.RootFS // rootFS from configuration
  510. release func() // release resources from rootFS download
  511. configOS layer.OS // for LCOW when registering downloaded layers
  512. )
  513. // https://github.com/docker/docker/issues/24766 - Err on the side of caution,
  514. // explicitly blocking images intended for linux from the Windows daemon. On
  515. // Windows, we do this before the attempt to download, effectively serialising
  516. // the download slightly slowing it down. We have to do it this way, as
  517. // chances are the download of layers itself would fail due to file names
  518. // which aren't suitable for NTFS. At some point in the future, if a similar
  519. // check to block Windows images being pulled on Linux is implemented, it
  520. // may be necessary to perform the same type of serialisation.
  521. if runtime.GOOS == "windows" {
  522. configJSON, configRootFS, configOS, err = receiveConfig(p.config.ImageStore, configChan, configErrChan)
  523. if err != nil {
  524. return "", "", err
  525. }
  526. if configRootFS == nil {
  527. return "", "", errRootFSInvalid
  528. }
  529. if len(descriptors) != len(configRootFS.DiffIDs) {
  530. return "", "", errRootFSMismatch
  531. }
  532. // Early bath if the requested OS doesn't match that of the configuration.
  533. // This avoids doing the download, only to potentially fail later.
  534. if !strings.EqualFold(string(configOS), requestedOS) {
  535. return "", "", fmt.Errorf("cannot download image with operating system %q when requesting %q", configOS, requestedOS)
  536. }
  537. // Populate diff ids in descriptors to avoid downloading foreign layers
  538. // which have been side loaded
  539. for i := range descriptors {
  540. descriptors[i].(*v2LayerDescriptor).diffID = configRootFS.DiffIDs[i]
  541. }
  542. }
  543. if p.config.DownloadManager != nil {
  544. go func() {
  545. var (
  546. err error
  547. rootFS image.RootFS
  548. )
  549. downloadRootFS := *image.NewRootFS()
  550. rootFS, release, err = p.config.DownloadManager.Download(ctx, downloadRootFS, layer.OS(requestedOS), descriptors, p.config.ProgressOutput)
  551. if err != nil {
  552. // Intentionally do not cancel the config download here
  553. // as the error from config download (if there is one)
  554. // is more interesting than the layer download error
  555. layerErrChan <- err
  556. return
  557. }
  558. downloadedRootFS = &rootFS
  559. close(downloadsDone)
  560. }()
  561. } else {
  562. // We have nothing to download
  563. close(downloadsDone)
  564. }
  565. if configJSON == nil {
  566. configJSON, configRootFS, _, err = receiveConfig(p.config.ImageStore, configChan, configErrChan)
  567. if err == nil && configRootFS == nil {
  568. err = errRootFSInvalid
  569. }
  570. if err != nil {
  571. cancel()
  572. select {
  573. case <-downloadsDone:
  574. case <-layerErrChan:
  575. }
  576. return "", "", err
  577. }
  578. }
  579. select {
  580. case <-downloadsDone:
  581. case err = <-layerErrChan:
  582. return "", "", err
  583. }
  584. if release != nil {
  585. defer release()
  586. }
  587. if downloadedRootFS != nil {
  588. // The DiffIDs returned in rootFS MUST match those in the config.
  589. // Otherwise the image config could be referencing layers that aren't
  590. // included in the manifest.
  591. if len(downloadedRootFS.DiffIDs) != len(configRootFS.DiffIDs) {
  592. return "", "", errRootFSMismatch
  593. }
  594. for i := range downloadedRootFS.DiffIDs {
  595. if downloadedRootFS.DiffIDs[i] != configRootFS.DiffIDs[i] {
  596. return "", "", errRootFSMismatch
  597. }
  598. }
  599. }
  600. imageID, err := p.config.ImageStore.Put(configJSON)
  601. if err != nil {
  602. return "", "", err
  603. }
  604. return imageID, manifestDigest, nil
  605. }
  606. func receiveConfig(s ImageConfigStore, configChan <-chan []byte, errChan <-chan error) ([]byte, *image.RootFS, layer.OS, error) {
  607. select {
  608. case configJSON := <-configChan:
  609. rootfs, os, err := s.RootFSAndOSFromConfig(configJSON)
  610. if err != nil {
  611. return nil, nil, "", err
  612. }
  613. return configJSON, rootfs, os, nil
  614. case err := <-errChan:
  615. return nil, nil, "", err
  616. // Don't need a case for ctx.Done in the select because cancellation
  617. // will trigger an error in p.pullSchema2ImageConfig.
  618. }
  619. }
  620. // pullManifestList handles "manifest lists" which point to various
  621. // platform-specific manifests.
  622. func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mfstList *manifestlist.DeserializedManifestList, os string) (id digest.Digest, manifestListDigest digest.Digest, err error) {
  623. manifestListDigest, err = schema2ManifestDigest(ref, mfstList)
  624. if err != nil {
  625. return "", "", err
  626. }
  627. logrus.Debugf("%s resolved to a manifestList object with %d entries; looking for a %s/%s match", ref, len(mfstList.Manifests), os, runtime.GOARCH)
  628. manifestMatches := filterManifests(mfstList.Manifests, os)
  629. if len(manifestMatches) == 0 {
  630. errMsg := fmt.Sprintf("no matching manifest for %s/%s in the manifest list entries", os, runtime.GOARCH)
  631. logrus.Debugf(errMsg)
  632. return "", "", errors.New(errMsg)
  633. }
  634. if len(manifestMatches) > 1 {
  635. logrus.Debugf("found multiple matches in manifest list, choosing best match %s", manifestMatches[0].Digest.String())
  636. }
  637. manifestDigest := manifestMatches[0].Digest
  638. manSvc, err := p.repo.Manifests(ctx)
  639. if err != nil {
  640. return "", "", err
  641. }
  642. manifest, err := manSvc.Get(ctx, manifestDigest)
  643. if err != nil {
  644. return "", "", err
  645. }
  646. manifestRef, err := reference.WithDigest(reference.TrimNamed(ref), manifestDigest)
  647. if err != nil {
  648. return "", "", err
  649. }
  650. switch v := manifest.(type) {
  651. case *schema1.SignedManifest:
  652. id, _, err = p.pullSchema1(ctx, manifestRef, v, os)
  653. if err != nil {
  654. return "", "", err
  655. }
  656. case *schema2.DeserializedManifest:
  657. id, _, err = p.pullSchema2(ctx, manifestRef, v, os)
  658. if err != nil {
  659. return "", "", err
  660. }
  661. default:
  662. return "", "", errors.New("unsupported manifest format")
  663. }
  664. return id, manifestListDigest, err
  665. }
  666. func (p *v2Puller) pullSchema2Config(ctx context.Context, dgst digest.Digest) (configJSON []byte, err error) {
  667. blobs := p.repo.Blobs(ctx)
  668. configJSON, err = blobs.Get(ctx, dgst)
  669. if err != nil {
  670. return nil, err
  671. }
  672. // Verify image config digest
  673. verifier := dgst.Verifier()
  674. if _, err := verifier.Write(configJSON); err != nil {
  675. return nil, err
  676. }
  677. if !verifier.Verified() {
  678. err := fmt.Errorf("image config verification failed for digest %s", dgst)
  679. logrus.Error(err)
  680. return nil, err
  681. }
  682. return configJSON, nil
  683. }
  684. // schema2ManifestDigest computes the manifest digest, and, if pulling by
  685. // digest, ensures that it matches the requested digest.
  686. func schema2ManifestDigest(ref reference.Named, mfst distribution.Manifest) (digest.Digest, error) {
  687. _, canonical, err := mfst.Payload()
  688. if err != nil {
  689. return "", err
  690. }
  691. // If pull by digest, then verify the manifest digest.
  692. if digested, isDigested := ref.(reference.Canonical); isDigested {
  693. verifier := digested.Digest().Verifier()
  694. if _, err := verifier.Write(canonical); err != nil {
  695. return "", err
  696. }
  697. if !verifier.Verified() {
  698. err := fmt.Errorf("manifest verification failed for digest %s", digested.Digest())
  699. logrus.Error(err)
  700. return "", err
  701. }
  702. return digested.Digest(), nil
  703. }
  704. return digest.FromBytes(canonical), nil
  705. }
  706. // allowV1Fallback checks if the error is a possible reason to fallback to v1
  707. // (even if confirmedV2 has been set already), and if so, wraps the error in
  708. // a fallbackError with confirmedV2 set to false. Otherwise, it returns the
  709. // error unmodified.
  710. func allowV1Fallback(err error) error {
  711. switch v := err.(type) {
  712. case errcode.Errors:
  713. if len(v) != 0 {
  714. if v0, ok := v[0].(errcode.Error); ok && shouldV2Fallback(v0) {
  715. return fallbackError{
  716. err: err,
  717. confirmedV2: false,
  718. transportOK: true,
  719. }
  720. }
  721. }
  722. case errcode.Error:
  723. if shouldV2Fallback(v) {
  724. return fallbackError{
  725. err: err,
  726. confirmedV2: false,
  727. transportOK: true,
  728. }
  729. }
  730. case *url.Error:
  731. if v.Err == auth.ErrNoBasicAuthCredentials {
  732. return fallbackError{err: err, confirmedV2: false}
  733. }
  734. }
  735. return err
  736. }
  737. func verifySchema1Manifest(signedManifest *schema1.SignedManifest, ref reference.Reference) (m *schema1.Manifest, err error) {
  738. // If pull by digest, then verify the manifest digest. NOTE: It is
  739. // important to do this first, before any other content validation. If the
  740. // digest cannot be verified, don't even bother with those other things.
  741. if digested, isCanonical := ref.(reference.Canonical); isCanonical {
  742. verifier := digested.Digest().Verifier()
  743. if _, err := verifier.Write(signedManifest.Canonical); err != nil {
  744. return nil, err
  745. }
  746. if !verifier.Verified() {
  747. err := fmt.Errorf("image verification failed for digest %s", digested.Digest())
  748. logrus.Error(err)
  749. return nil, err
  750. }
  751. }
  752. m = &signedManifest.Manifest
  753. if m.SchemaVersion != 1 {
  754. return nil, fmt.Errorf("unsupported schema version %d for %q", m.SchemaVersion, reference.FamiliarString(ref))
  755. }
  756. if len(m.FSLayers) != len(m.History) {
  757. return nil, fmt.Errorf("length of history not equal to number of layers for %q", reference.FamiliarString(ref))
  758. }
  759. if len(m.FSLayers) == 0 {
  760. return nil, fmt.Errorf("no FSLayers in manifest for %q", reference.FamiliarString(ref))
  761. }
  762. return m, nil
  763. }
  764. // fixManifestLayers removes repeated layers from the manifest and checks the
  765. // correctness of the parent chain.
  766. func fixManifestLayers(m *schema1.Manifest) error {
  767. imgs := make([]*image.V1Image, len(m.FSLayers))
  768. for i := range m.FSLayers {
  769. img := &image.V1Image{}
  770. if err := json.Unmarshal([]byte(m.History[i].V1Compatibility), img); err != nil {
  771. return err
  772. }
  773. imgs[i] = img
  774. if err := v1.ValidateID(img.ID); err != nil {
  775. return err
  776. }
  777. }
  778. if imgs[len(imgs)-1].Parent != "" && runtime.GOOS != "windows" {
  779. // Windows base layer can point to a base layer parent that is not in manifest.
  780. return errors.New("invalid parent ID in the base layer of the image")
  781. }
  782. // check general duplicates to error instead of a deadlock
  783. idmap := make(map[string]struct{})
  784. var lastID string
  785. for _, img := range imgs {
  786. // skip IDs that appear after each other, we handle those later
  787. if _, exists := idmap[img.ID]; img.ID != lastID && exists {
  788. return fmt.Errorf("ID %+v appears multiple times in manifest", img.ID)
  789. }
  790. lastID = img.ID
  791. idmap[lastID] = struct{}{}
  792. }
  793. // backwards loop so that we keep the remaining indexes after removing items
  794. for i := len(imgs) - 2; i >= 0; i-- {
  795. if imgs[i].ID == imgs[i+1].ID { // repeated ID. remove and continue
  796. m.FSLayers = append(m.FSLayers[:i], m.FSLayers[i+1:]...)
  797. m.History = append(m.History[:i], m.History[i+1:]...)
  798. } else if imgs[i].Parent != imgs[i+1].ID {
  799. return fmt.Errorf("invalid parent ID. Expected %v, got %v", imgs[i+1].ID, imgs[i].Parent)
  800. }
  801. }
  802. return nil
  803. }
  804. func createDownloadFile() (*os.File, error) {
  805. return ioutil.TempFile("", "GetImageBlob")
  806. }