session.go 24 KB

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