session.go 25 KB

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