session.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. package registry // import "github.com/docker/docker/registry"
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. // this is required for some certificates
  6. _ "crypto/sha512"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "net/http/cookiejar"
  14. "net/url"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "github.com/docker/distribution/reference"
  19. "github.com/docker/distribution/registry/api/errcode"
  20. "github.com/docker/docker/api/types"
  21. registrytypes "github.com/docker/docker/api/types/registry"
  22. "github.com/docker/docker/errdefs"
  23. "github.com/docker/docker/pkg/ioutils"
  24. "github.com/docker/docker/pkg/jsonmessage"
  25. "github.com/docker/docker/pkg/stringid"
  26. "github.com/docker/docker/pkg/tarsum"
  27. "github.com/docker/docker/registry/resumable"
  28. "github.com/pkg/errors"
  29. "github.com/sirupsen/logrus"
  30. )
  31. var (
  32. // ErrRepoNotFound is returned if the repository didn't exist on the
  33. // remote side
  34. ErrRepoNotFound notFoundError = "Repository not found"
  35. )
  36. // A Session is used to communicate with a V1 registry
  37. type Session struct {
  38. indexEndpoint *V1Endpoint
  39. client *http.Client
  40. // TODO(tiborvass): remove authConfig
  41. authConfig *types.AuthConfig
  42. id string
  43. }
  44. type authTransport struct {
  45. http.RoundTripper
  46. *types.AuthConfig
  47. alwaysSetBasicAuth bool
  48. token []string
  49. mu sync.Mutex // guards modReq
  50. modReq map[*http.Request]*http.Request // original -> modified
  51. }
  52. // AuthTransport handles the auth layer when communicating with a v1 registry (private or official)
  53. //
  54. // For private v1 registries, set alwaysSetBasicAuth to true.
  55. //
  56. // For the official v1 registry, if there isn't already an Authorization header in the request,
  57. // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header.
  58. // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing
  59. // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent
  60. // requests.
  61. //
  62. // If the server sends a token without the client having requested it, it is ignored.
  63. //
  64. // This RoundTripper also has a CancelRequest method important for correct timeout handling.
  65. func AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper {
  66. if base == nil {
  67. base = http.DefaultTransport
  68. }
  69. return &authTransport{
  70. RoundTripper: base,
  71. AuthConfig: authConfig,
  72. alwaysSetBasicAuth: alwaysSetBasicAuth,
  73. modReq: make(map[*http.Request]*http.Request),
  74. }
  75. }
  76. // cloneRequest returns a clone of the provided *http.Request.
  77. // The clone is a shallow copy of the struct and its Header map.
  78. func cloneRequest(r *http.Request) *http.Request {
  79. // shallow copy of the struct
  80. r2 := new(http.Request)
  81. *r2 = *r
  82. // deep copy of the Header
  83. r2.Header = make(http.Header, len(r.Header))
  84. for k, s := range r.Header {
  85. r2.Header[k] = append([]string(nil), s...)
  86. }
  87. return r2
  88. }
  89. // RoundTrip changes an HTTP request's headers to add the necessary
  90. // authentication-related headers
  91. func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) {
  92. // Authorization should not be set on 302 redirect for untrusted locations.
  93. // This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
  94. // As the authorization logic is currently implemented in RoundTrip,
  95. // a 302 redirect is detected by looking at the Referrer header as go http package adds said header.
  96. // This is safe as Docker doesn't set Referrer in other scenarios.
  97. if orig.Header.Get("Referer") != "" && !trustedLocation(orig) {
  98. return tr.RoundTripper.RoundTrip(orig)
  99. }
  100. req := cloneRequest(orig)
  101. tr.mu.Lock()
  102. tr.modReq[orig] = req
  103. tr.mu.Unlock()
  104. if tr.alwaysSetBasicAuth {
  105. if tr.AuthConfig == nil {
  106. return nil, errors.New("unexpected error: empty auth config")
  107. }
  108. req.SetBasicAuth(tr.Username, tr.Password)
  109. return tr.RoundTripper.RoundTrip(req)
  110. }
  111. // Don't override
  112. if req.Header.Get("Authorization") == "" {
  113. if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 {
  114. req.SetBasicAuth(tr.Username, tr.Password)
  115. } else if len(tr.token) > 0 {
  116. req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ","))
  117. }
  118. }
  119. resp, err := tr.RoundTripper.RoundTrip(req)
  120. if err != nil {
  121. tr.mu.Lock()
  122. delete(tr.modReq, orig)
  123. tr.mu.Unlock()
  124. return nil, err
  125. }
  126. if len(resp.Header["X-Docker-Token"]) > 0 {
  127. tr.token = resp.Header["X-Docker-Token"]
  128. }
  129. resp.Body = &ioutils.OnEOFReader{
  130. Rc: resp.Body,
  131. Fn: func() {
  132. tr.mu.Lock()
  133. delete(tr.modReq, orig)
  134. tr.mu.Unlock()
  135. },
  136. }
  137. return resp, nil
  138. }
  139. // CancelRequest cancels an in-flight request by closing its connection.
  140. func (tr *authTransport) CancelRequest(req *http.Request) {
  141. type canceler interface {
  142. CancelRequest(*http.Request)
  143. }
  144. if cr, ok := tr.RoundTripper.(canceler); ok {
  145. tr.mu.Lock()
  146. modReq := tr.modReq[req]
  147. delete(tr.modReq, req)
  148. tr.mu.Unlock()
  149. cr.CancelRequest(modReq)
  150. }
  151. }
  152. func authorizeClient(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) error {
  153. var alwaysSetBasicAuth bool
  154. // If we're working with a standalone private registry over HTTPS, send Basic Auth headers
  155. // alongside all our requests.
  156. if endpoint.String() != IndexServer && endpoint.URL.Scheme == "https" {
  157. info, err := endpoint.Ping()
  158. if err != nil {
  159. return err
  160. }
  161. if info.Standalone && authConfig != nil {
  162. logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String())
  163. alwaysSetBasicAuth = true
  164. }
  165. }
  166. // Annotate the transport unconditionally so that v2 can
  167. // properly fallback on v1 when an image is not found.
  168. client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth)
  169. jar, err := cookiejar.New(nil)
  170. if err != nil {
  171. return errors.New("cookiejar.New is not supposed to return an error")
  172. }
  173. client.Jar = jar
  174. return nil
  175. }
  176. func newSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) *Session {
  177. return &Session{
  178. authConfig: authConfig,
  179. client: client,
  180. indexEndpoint: endpoint,
  181. id: stringid.GenerateRandomID(),
  182. }
  183. }
  184. // NewSession creates a new session
  185. // TODO(tiborvass): remove authConfig param once registry client v2 is vendored
  186. func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) (*Session, error) {
  187. if err := authorizeClient(client, authConfig, endpoint); err != nil {
  188. return nil, err
  189. }
  190. return newSession(client, authConfig, endpoint), nil
  191. }
  192. // ID returns this registry session's ID.
  193. func (r *Session) ID() string {
  194. return r.id
  195. }
  196. // GetRemoteHistory retrieves the history of a given image from the registry.
  197. // It returns a list of the parent's JSON files (including the requested image).
  198. func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) {
  199. res, err := r.client.Get(registry + "images/" + imgID + "/ancestry")
  200. if err != nil {
  201. return nil, err
  202. }
  203. defer res.Body.Close()
  204. if res.StatusCode != http.StatusOK {
  205. if res.StatusCode == http.StatusUnauthorized {
  206. return nil, errcode.ErrorCodeUnauthorized.WithArgs()
  207. }
  208. return nil, newJSONError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res)
  209. }
  210. var history []string
  211. if err := json.NewDecoder(res.Body).Decode(&history); err != nil {
  212. return nil, fmt.Errorf("Error while reading the http response: %v", err)
  213. }
  214. logrus.Debugf("Ancestry: %v", history)
  215. return history, nil
  216. }
  217. // LookupRemoteImage checks if an image exists in the registry
  218. func (r *Session) LookupRemoteImage(imgID, registry string) error {
  219. res, err := r.client.Get(registry + "images/" + imgID + "/json")
  220. if err != nil {
  221. return err
  222. }
  223. res.Body.Close()
  224. if res.StatusCode != http.StatusOK {
  225. return newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
  226. }
  227. return nil
  228. }
  229. // GetRemoteImageJSON retrieves an image's JSON metadata from the registry.
  230. func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) {
  231. res, err := r.client.Get(registry + "images/" + imgID + "/json")
  232. if err != nil {
  233. return nil, -1, fmt.Errorf("Failed to download json: %s", err)
  234. }
  235. defer res.Body.Close()
  236. if res.StatusCode != http.StatusOK {
  237. return nil, -1, newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
  238. }
  239. // if the size header is not present, then set it to '-1'
  240. imageSize := int64(-1)
  241. if hdr := res.Header.Get("X-Docker-Size"); hdr != "" {
  242. imageSize, err = strconv.ParseInt(hdr, 10, 64)
  243. if err != nil {
  244. return nil, -1, err
  245. }
  246. }
  247. jsonString, err := ioutil.ReadAll(res.Body)
  248. if err != nil {
  249. return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString)
  250. }
  251. return jsonString, imageSize, nil
  252. }
  253. // GetRemoteImageLayer retrieves an image layer from the registry
  254. func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) {
  255. var (
  256. statusCode = 0
  257. res *http.Response
  258. err error
  259. imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID)
  260. )
  261. req, err := http.NewRequest(http.MethodGet, imageURL, nil)
  262. if err != nil {
  263. return nil, fmt.Errorf("Error while getting from the server: %v", err)
  264. }
  265. res, err = r.client.Do(req)
  266. if err != nil {
  267. logrus.Debugf("Error contacting registry %s: %v", registry, err)
  268. // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515
  269. if res != nil {
  270. if res.Body != nil {
  271. res.Body.Close()
  272. }
  273. statusCode = res.StatusCode
  274. }
  275. return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
  276. statusCode, imgID)
  277. }
  278. if res.StatusCode != http.StatusOK {
  279. res.Body.Close()
  280. return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
  281. res.StatusCode, imgID)
  282. }
  283. if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 {
  284. logrus.Debug("server supports resume")
  285. return resumable.NewRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil
  286. }
  287. logrus.Debug("server doesn't support resume")
  288. return res.Body, nil
  289. }
  290. // GetRemoteTag retrieves the tag named in the askedTag argument from the given
  291. // repository. It queries each of the registries supplied in the registries
  292. // argument, and returns data from the first one that answers the query
  293. // successfully.
  294. func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) {
  295. repository := reference.Path(repositoryRef)
  296. if strings.Count(repository, "/") == 0 {
  297. // This will be removed once the registry supports auto-resolution on
  298. // the "library" namespace
  299. repository = "library/" + repository
  300. }
  301. for _, host := range registries {
  302. endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag)
  303. res, err := r.client.Get(endpoint)
  304. if err != nil {
  305. return "", err
  306. }
  307. logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
  308. defer res.Body.Close()
  309. if res.StatusCode == 404 {
  310. return "", ErrRepoNotFound
  311. }
  312. if res.StatusCode != http.StatusOK {
  313. continue
  314. }
  315. var tagID string
  316. if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil {
  317. return "", err
  318. }
  319. return tagID, nil
  320. }
  321. return "", fmt.Errorf("Could not reach any registry endpoint")
  322. }
  323. // GetRemoteTags retrieves all tags from the given repository. It queries each
  324. // of the registries supplied in the registries argument, and returns data from
  325. // the first one that answers the query successfully. It returns a map with
  326. // tag names as the keys and image IDs as the values.
  327. func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) {
  328. repository := reference.Path(repositoryRef)
  329. if strings.Count(repository, "/") == 0 {
  330. // This will be removed once the registry supports auto-resolution on
  331. // the "library" namespace
  332. repository = "library/" + repository
  333. }
  334. for _, host := range registries {
  335. endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository)
  336. res, err := r.client.Get(endpoint)
  337. if err != nil {
  338. return nil, err
  339. }
  340. logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
  341. defer res.Body.Close()
  342. if res.StatusCode == 404 {
  343. return nil, ErrRepoNotFound
  344. }
  345. if res.StatusCode != http.StatusOK {
  346. continue
  347. }
  348. result := make(map[string]string)
  349. if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
  350. return nil, err
  351. }
  352. return result, nil
  353. }
  354. return nil, fmt.Errorf("Could not reach any registry endpoint")
  355. }
  356. func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
  357. var endpoints []string
  358. parsedURL, err := url.Parse(indexEp)
  359. if err != nil {
  360. return nil, err
  361. }
  362. var urlScheme = parsedURL.Scheme
  363. // The registry's URL scheme has to match the Index'
  364. for _, ep := range headers {
  365. epList := strings.Split(ep, ",")
  366. for _, epListElement := range epList {
  367. endpoints = append(
  368. endpoints,
  369. fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement)))
  370. }
  371. }
  372. return endpoints, nil
  373. }
  374. // GetRepositoryData returns lists of images and endpoints for the repository
  375. func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) {
  376. repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), reference.Path(name))
  377. logrus.Debugf("[registry] Calling GET %s", repositoryTarget)
  378. req, err := http.NewRequest(http.MethodGet, repositoryTarget, nil)
  379. if err != nil {
  380. return nil, err
  381. }
  382. // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
  383. req.Header.Set("X-Docker-Token", "true")
  384. res, err := r.client.Do(req)
  385. if err != nil {
  386. // check if the error is because of i/o timeout
  387. // and return a non-obtuse error message for users
  388. // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout"
  389. // was a top search on the docker user forum
  390. if isTimeout(err) {
  391. return nil, fmt.Errorf("network timed out while trying to connect to %s. You may want to check your internet connection or if you are behind a proxy", repositoryTarget)
  392. }
  393. return nil, fmt.Errorf("Error while pulling image: %v", err)
  394. }
  395. defer res.Body.Close()
  396. if res.StatusCode == http.StatusUnauthorized {
  397. return nil, errcode.ErrorCodeUnauthorized.WithArgs()
  398. }
  399. // TODO: Right now we're ignoring checksums in the response body.
  400. // In the future, we need to use them to check image validity.
  401. if res.StatusCode == 404 {
  402. return nil, newJSONError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res)
  403. } else if res.StatusCode != http.StatusOK {
  404. errBody, err := ioutil.ReadAll(res.Body)
  405. if err != nil {
  406. logrus.Debugf("Error reading response body: %s", err)
  407. }
  408. return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, reference.Path(name), errBody), res)
  409. }
  410. var endpoints []string
  411. if res.Header.Get("X-Docker-Endpoints") != "" {
  412. endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
  413. if err != nil {
  414. return nil, err
  415. }
  416. } else {
  417. // Assume the endpoint is on the same host
  418. endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host))
  419. }
  420. remoteChecksums := []*ImgData{}
  421. if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil {
  422. return nil, err
  423. }
  424. // Forge a better object from the retrieved data
  425. imgsData := make(map[string]*ImgData, len(remoteChecksums))
  426. for _, elem := range remoteChecksums {
  427. imgsData[elem.ID] = elem
  428. }
  429. return &RepositoryData{
  430. ImgList: imgsData,
  431. Endpoints: endpoints,
  432. }, nil
  433. }
  434. // PushImageChecksumRegistry uploads checksums for an image
  435. func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error {
  436. u := registry + "images/" + imgData.ID + "/checksum"
  437. logrus.Debugf("[registry] Calling PUT %s", u)
  438. req, err := http.NewRequest(http.MethodPut, u, nil)
  439. if err != nil {
  440. return err
  441. }
  442. req.Header.Set("X-Docker-Checksum", imgData.Checksum)
  443. req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload)
  444. res, err := r.client.Do(req)
  445. if err != nil {
  446. return fmt.Errorf("Failed to upload metadata: %v", err)
  447. }
  448. defer res.Body.Close()
  449. if len(res.Cookies()) > 0 {
  450. r.client.Jar.SetCookies(req.URL, res.Cookies())
  451. }
  452. if res.StatusCode != http.StatusOK {
  453. errBody, err := ioutil.ReadAll(res.Body)
  454. if err != nil {
  455. return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err)
  456. }
  457. var jsonBody map[string]string
  458. if err := json.Unmarshal(errBody, &jsonBody); err != nil {
  459. errBody = []byte(err.Error())
  460. } else if jsonBody["error"] == "Image already exists" {
  461. return ErrAlreadyExists
  462. }
  463. return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody)
  464. }
  465. return nil
  466. }
  467. // PushImageJSONRegistry pushes JSON metadata for a local image to the registry
  468. func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error {
  469. u := registry + "images/" + imgData.ID + "/json"
  470. logrus.Debugf("[registry] Calling PUT %s", u)
  471. req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(jsonRaw))
  472. if err != nil {
  473. return err
  474. }
  475. req.Header.Add("Content-type", "application/json")
  476. res, err := r.client.Do(req)
  477. if err != nil {
  478. return fmt.Errorf("Failed to upload metadata: %s", err)
  479. }
  480. defer res.Body.Close()
  481. if res.StatusCode == http.StatusUnauthorized && strings.HasPrefix(registry, "http://") {
  482. return newJSONError("HTTP code 401, Docker will not send auth headers over HTTP.", res)
  483. }
  484. if res.StatusCode != http.StatusOK {
  485. errBody, err := ioutil.ReadAll(res.Body)
  486. if err != nil {
  487. return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
  488. }
  489. var jsonBody map[string]string
  490. if err := json.Unmarshal(errBody, &jsonBody); err != nil {
  491. errBody = []byte(err.Error())
  492. } else if jsonBody["error"] == "Image already exists" {
  493. return ErrAlreadyExists
  494. }
  495. return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res)
  496. }
  497. return nil
  498. }
  499. // PushImageLayerRegistry sends the checksum of an image layer to the registry
  500. func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) {
  501. u := registry + "images/" + imgID + "/layer"
  502. logrus.Debugf("[registry] Calling PUT %s", u)
  503. tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0)
  504. if err != nil {
  505. return "", "", err
  506. }
  507. h := sha256.New()
  508. h.Write(jsonRaw)
  509. h.Write([]byte{'\n'})
  510. checksumLayer := io.TeeReader(tarsumLayer, h)
  511. req, err := http.NewRequest(http.MethodPut, u, checksumLayer)
  512. if err != nil {
  513. return "", "", err
  514. }
  515. req.Header.Add("Content-Type", "application/octet-stream")
  516. req.ContentLength = -1
  517. req.TransferEncoding = []string{"chunked"}
  518. res, err := r.client.Do(req)
  519. if err != nil {
  520. return "", "", fmt.Errorf("Failed to upload layer: %v", err)
  521. }
  522. if rc, ok := layer.(io.Closer); ok {
  523. if err := rc.Close(); err != nil {
  524. return "", "", err
  525. }
  526. }
  527. defer res.Body.Close()
  528. if res.StatusCode != http.StatusOK {
  529. errBody, err := ioutil.ReadAll(res.Body)
  530. if err != nil {
  531. return "", "", newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
  532. }
  533. return "", "", newJSONError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res)
  534. }
  535. checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil))
  536. return tarsumLayer.Sum(jsonRaw), checksumPayload, nil
  537. }
  538. // PushRegistryTag pushes a tag on the registry.
  539. // Remote has the format '<user>/<repo>
  540. func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error {
  541. // "jsonify" the string
  542. revision = "\"" + revision + "\""
  543. path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag)
  544. req, err := http.NewRequest(http.MethodPut, registry+path, strings.NewReader(revision))
  545. if err != nil {
  546. return err
  547. }
  548. req.Header.Add("Content-type", "application/json")
  549. req.ContentLength = int64(len(revision))
  550. res, err := r.client.Do(req)
  551. if err != nil {
  552. return err
  553. }
  554. res.Body.Close()
  555. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
  556. return newJSONError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res)
  557. }
  558. return nil
  559. }
  560. // PushImageJSONIndex uploads an image list to the repository
  561. func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) {
  562. cleanImgList := []*ImgData{}
  563. if validate {
  564. for _, elem := range imgList {
  565. if elem.Checksum != "" {
  566. cleanImgList = append(cleanImgList, elem)
  567. }
  568. }
  569. } else {
  570. cleanImgList = imgList
  571. }
  572. imgListJSON, err := json.Marshal(cleanImgList)
  573. if err != nil {
  574. return nil, err
  575. }
  576. var suffix string
  577. if validate {
  578. suffix = "images"
  579. }
  580. u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), reference.Path(remote), suffix)
  581. logrus.Debugf("[registry] PUT %s", u)
  582. logrus.Debugf("Image list pushed to index:\n%s", imgListJSON)
  583. headers := map[string][]string{
  584. "Content-type": {"application/json"},
  585. // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
  586. "X-Docker-Token": {"true"},
  587. }
  588. if validate {
  589. headers["X-Docker-Endpoints"] = regs
  590. }
  591. // Redirect if necessary
  592. var res *http.Response
  593. for {
  594. if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil {
  595. return nil, err
  596. }
  597. if !shouldRedirect(res) {
  598. break
  599. }
  600. res.Body.Close()
  601. u = res.Header.Get("Location")
  602. logrus.Debugf("Redirected to %s", u)
  603. }
  604. defer res.Body.Close()
  605. if res.StatusCode == http.StatusUnauthorized {
  606. return nil, errcode.ErrorCodeUnauthorized.WithArgs()
  607. }
  608. var tokens, endpoints []string
  609. if !validate {
  610. if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
  611. errBody, err := ioutil.ReadAll(res.Body)
  612. if err != nil {
  613. logrus.Debugf("Error reading response body: %s", err)
  614. }
  615. return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
  616. }
  617. tokens = res.Header["X-Docker-Token"]
  618. logrus.Debugf("Auth token: %v", tokens)
  619. if res.Header.Get("X-Docker-Endpoints") == "" {
  620. return nil, fmt.Errorf("Index response didn't contain any endpoints")
  621. }
  622. endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
  623. if err != nil {
  624. return nil, err
  625. }
  626. } else {
  627. if res.StatusCode != http.StatusNoContent {
  628. errBody, err := ioutil.ReadAll(res.Body)
  629. if err != nil {
  630. logrus.Debugf("Error reading response body: %s", err)
  631. }
  632. return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
  633. }
  634. }
  635. return &RepositoryData{
  636. Endpoints: endpoints,
  637. }, nil
  638. }
  639. func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) {
  640. req, err := http.NewRequest(http.MethodPut, u, bytes.NewReader(body))
  641. if err != nil {
  642. return nil, err
  643. }
  644. req.ContentLength = int64(len(body))
  645. for k, v := range headers {
  646. req.Header[k] = v
  647. }
  648. response, err := r.client.Do(req)
  649. if err != nil {
  650. return nil, err
  651. }
  652. return response, nil
  653. }
  654. func shouldRedirect(response *http.Response) bool {
  655. return response.StatusCode >= 300 && response.StatusCode < 400
  656. }
  657. // SearchRepositories performs a search against the remote repository
  658. func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) {
  659. if limit < 1 || limit > 100 {
  660. return nil, errdefs.InvalidParameter(errors.Errorf("Limit %d is outside the range of [1, 100]", limit))
  661. }
  662. logrus.Debugf("Index server: %s", r.indexEndpoint)
  663. u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit))
  664. req, err := http.NewRequest(http.MethodGet, u, nil)
  665. if err != nil {
  666. return nil, errors.Wrap(errdefs.InvalidParameter(err), "Error building request")
  667. }
  668. // Have the AuthTransport send authentication, when logged in.
  669. req.Header.Set("X-Docker-Token", "true")
  670. res, err := r.client.Do(req)
  671. if err != nil {
  672. return nil, errdefs.System(err)
  673. }
  674. defer res.Body.Close()
  675. if res.StatusCode != http.StatusOK {
  676. return nil, newJSONError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res)
  677. }
  678. result := new(registrytypes.SearchResults)
  679. return result, errors.Wrap(json.NewDecoder(res.Body).Decode(result), "error decoding registry search results")
  680. }
  681. func isTimeout(err error) bool {
  682. type timeout interface {
  683. Timeout() bool
  684. }
  685. e := err
  686. switch urlErr := err.(type) {
  687. case *url.Error:
  688. e = urlErr.Err
  689. }
  690. t, ok := e.(timeout)
  691. return ok && t.Timeout()
  692. }
  693. func newJSONError(msg string, res *http.Response) error {
  694. return &jsonmessage.JSONError{
  695. Message: msg,
  696. Code: res.StatusCode,
  697. }
  698. }