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/registry/api/errcode"
  21. "github.com/docker/docker/pkg/httputils"
  22. "github.com/docker/docker/pkg/ioutils"
  23. "github.com/docker/docker/pkg/stringid"
  24. "github.com/docker/docker/pkg/tarsum"
  25. "github.com/docker/docker/reference"
  26. "github.com/docker/engine-api/types"
  27. registrytypes "github.com/docker/engine-api/types/registry"
  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. statusCode = 0
  262. res, err = r.client.Do(req)
  263. if err != nil {
  264. logrus.Debugf("Error contacting registry %s: %v", registry, err)
  265. // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515
  266. if res != nil {
  267. if res.Body != nil {
  268. res.Body.Close()
  269. }
  270. statusCode = res.StatusCode
  271. }
  272. return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
  273. statusCode, imgID)
  274. }
  275. if res.StatusCode != 200 {
  276. res.Body.Close()
  277. return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
  278. res.StatusCode, imgID)
  279. }
  280. if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 {
  281. logrus.Debug("server supports resume")
  282. return httputils.ResumableRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil
  283. }
  284. logrus.Debug("server doesn't support resume")
  285. return res.Body, nil
  286. }
  287. // GetRemoteTag retrieves the tag named in the askedTag argument from the given
  288. // repository. It queries each of the registries supplied in the registries
  289. // argument, and returns data from the first one that answers the query
  290. // successfully.
  291. func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) {
  292. repository := repositoryRef.RemoteName()
  293. if strings.Count(repository, "/") == 0 {
  294. // This will be removed once the registry supports auto-resolution on
  295. // the "library" namespace
  296. repository = "library/" + repository
  297. }
  298. for _, host := range registries {
  299. endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag)
  300. res, err := r.client.Get(endpoint)
  301. if err != nil {
  302. return "", err
  303. }
  304. logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
  305. defer res.Body.Close()
  306. if res.StatusCode == 404 {
  307. return "", ErrRepoNotFound
  308. }
  309. if res.StatusCode != 200 {
  310. continue
  311. }
  312. var tagID string
  313. if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil {
  314. return "", err
  315. }
  316. return tagID, nil
  317. }
  318. return "", fmt.Errorf("Could not reach any registry endpoint")
  319. }
  320. // GetRemoteTags retrieves all tags from the given repository. It queries each
  321. // of the registries supplied in the registries argument, and returns data from
  322. // the first one that answers the query successfully. It returns a map with
  323. // tag names as the keys and image IDs as the values.
  324. func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) {
  325. repository := repositoryRef.RemoteName()
  326. if strings.Count(repository, "/") == 0 {
  327. // This will be removed once the registry supports auto-resolution on
  328. // the "library" namespace
  329. repository = "library/" + repository
  330. }
  331. for _, host := range registries {
  332. endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository)
  333. res, err := r.client.Get(endpoint)
  334. if err != nil {
  335. return nil, err
  336. }
  337. logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
  338. defer res.Body.Close()
  339. if res.StatusCode == 404 {
  340. return nil, ErrRepoNotFound
  341. }
  342. if res.StatusCode != 200 {
  343. continue
  344. }
  345. result := make(map[string]string)
  346. if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
  347. return nil, err
  348. }
  349. return result, nil
  350. }
  351. return nil, fmt.Errorf("Could not reach any registry endpoint")
  352. }
  353. func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
  354. var endpoints []string
  355. parsedURL, err := url.Parse(indexEp)
  356. if err != nil {
  357. return nil, err
  358. }
  359. var urlScheme = parsedURL.Scheme
  360. // The registry's URL scheme has to match the Index'
  361. for _, ep := range headers {
  362. epList := strings.Split(ep, ",")
  363. for _, epListElement := range epList {
  364. endpoints = append(
  365. endpoints,
  366. fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement)))
  367. }
  368. }
  369. return endpoints, nil
  370. }
  371. // GetRepositoryData returns lists of images and endpoints for the repository
  372. func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) {
  373. repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), name.RemoteName())
  374. logrus.Debugf("[registry] Calling GET %s", repositoryTarget)
  375. req, err := http.NewRequest("GET", repositoryTarget, nil)
  376. if err != nil {
  377. return nil, err
  378. }
  379. // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
  380. req.Header.Set("X-Docker-Token", "true")
  381. res, err := r.client.Do(req)
  382. if err != nil {
  383. // check if the error is because of i/o timeout
  384. // and return a non-obtuse error message for users
  385. // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout"
  386. // was a top search on the docker user forum
  387. if isTimeout(err) {
  388. 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)
  389. }
  390. return nil, fmt.Errorf("Error while pulling image: %v", err)
  391. }
  392. defer res.Body.Close()
  393. if res.StatusCode == 401 {
  394. return nil, errcode.ErrorCodeUnauthorized.WithArgs()
  395. }
  396. // TODO: Right now we're ignoring checksums in the response body.
  397. // In the future, we need to use them to check image validity.
  398. if res.StatusCode == 404 {
  399. return nil, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res)
  400. } else if res.StatusCode != 200 {
  401. errBody, err := ioutil.ReadAll(res.Body)
  402. if err != nil {
  403. logrus.Debugf("Error reading response body: %s", err)
  404. }
  405. return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, name.RemoteName(), errBody), res)
  406. }
  407. var endpoints []string
  408. if res.Header.Get("X-Docker-Endpoints") != "" {
  409. endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
  410. if err != nil {
  411. return nil, err
  412. }
  413. } else {
  414. // Assume the endpoint is on the same host
  415. endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host))
  416. }
  417. remoteChecksums := []*ImgData{}
  418. if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil {
  419. return nil, err
  420. }
  421. // Forge a better object from the retrieved data
  422. imgsData := make(map[string]*ImgData, len(remoteChecksums))
  423. for _, elem := range remoteChecksums {
  424. imgsData[elem.ID] = elem
  425. }
  426. return &RepositoryData{
  427. ImgList: imgsData,
  428. Endpoints: endpoints,
  429. }, nil
  430. }
  431. // PushImageChecksumRegistry uploads checksums for an image
  432. func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error {
  433. u := registry + "images/" + imgData.ID + "/checksum"
  434. logrus.Debugf("[registry] Calling PUT %s", u)
  435. req, err := http.NewRequest("PUT", u, nil)
  436. if err != nil {
  437. return err
  438. }
  439. req.Header.Set("X-Docker-Checksum", imgData.Checksum)
  440. req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload)
  441. res, err := r.client.Do(req)
  442. if err != nil {
  443. return fmt.Errorf("Failed to upload metadata: %v", err)
  444. }
  445. defer res.Body.Close()
  446. if len(res.Cookies()) > 0 {
  447. r.client.Jar.SetCookies(req.URL, res.Cookies())
  448. }
  449. if res.StatusCode != 200 {
  450. errBody, err := ioutil.ReadAll(res.Body)
  451. if err != nil {
  452. return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err)
  453. }
  454. var jsonBody map[string]string
  455. if err := json.Unmarshal(errBody, &jsonBody); err != nil {
  456. errBody = []byte(err.Error())
  457. } else if jsonBody["error"] == "Image already exists" {
  458. return ErrAlreadyExists
  459. }
  460. return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody)
  461. }
  462. return nil
  463. }
  464. // PushImageJSONRegistry pushes JSON metadata for a local image to the registry
  465. func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error {
  466. u := registry + "images/" + imgData.ID + "/json"
  467. logrus.Debugf("[registry] Calling PUT %s", u)
  468. req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw))
  469. if err != nil {
  470. return err
  471. }
  472. req.Header.Add("Content-type", "application/json")
  473. res, err := r.client.Do(req)
  474. if err != nil {
  475. return fmt.Errorf("Failed to upload metadata: %s", err)
  476. }
  477. defer res.Body.Close()
  478. if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") {
  479. return httputils.NewHTTPRequestError("HTTP code 401, Docker will not send auth headers over HTTP.", res)
  480. }
  481. if res.StatusCode != 200 {
  482. errBody, err := ioutil.ReadAll(res.Body)
  483. if err != nil {
  484. return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
  485. }
  486. var jsonBody map[string]string
  487. if err := json.Unmarshal(errBody, &jsonBody); err != nil {
  488. errBody = []byte(err.Error())
  489. } else if jsonBody["error"] == "Image already exists" {
  490. return ErrAlreadyExists
  491. }
  492. return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res)
  493. }
  494. return nil
  495. }
  496. // PushImageLayerRegistry sends the checksum of an image layer to the registry
  497. func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) {
  498. u := registry + "images/" + imgID + "/layer"
  499. logrus.Debugf("[registry] Calling PUT %s", u)
  500. tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0)
  501. if err != nil {
  502. return "", "", err
  503. }
  504. h := sha256.New()
  505. h.Write(jsonRaw)
  506. h.Write([]byte{'\n'})
  507. checksumLayer := io.TeeReader(tarsumLayer, h)
  508. req, err := http.NewRequest("PUT", u, checksumLayer)
  509. if err != nil {
  510. return "", "", err
  511. }
  512. req.Header.Add("Content-Type", "application/octet-stream")
  513. req.ContentLength = -1
  514. req.TransferEncoding = []string{"chunked"}
  515. res, err := r.client.Do(req)
  516. if err != nil {
  517. return "", "", fmt.Errorf("Failed to upload layer: %v", err)
  518. }
  519. if rc, ok := layer.(io.Closer); ok {
  520. if err := rc.Close(); err != nil {
  521. return "", "", err
  522. }
  523. }
  524. defer res.Body.Close()
  525. if res.StatusCode != 200 {
  526. errBody, err := ioutil.ReadAll(res.Body)
  527. if err != nil {
  528. return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
  529. }
  530. return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res)
  531. }
  532. checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil))
  533. return tarsumLayer.Sum(jsonRaw), checksumPayload, nil
  534. }
  535. // PushRegistryTag pushes a tag on the registry.
  536. // Remote has the format '<user>/<repo>
  537. func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error {
  538. // "jsonify" the string
  539. revision = "\"" + revision + "\""
  540. path := fmt.Sprintf("repositories/%s/tags/%s", remote.RemoteName(), tag)
  541. req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision))
  542. if err != nil {
  543. return err
  544. }
  545. req.Header.Add("Content-type", "application/json")
  546. req.ContentLength = int64(len(revision))
  547. res, err := r.client.Do(req)
  548. if err != nil {
  549. return err
  550. }
  551. res.Body.Close()
  552. if res.StatusCode != 200 && res.StatusCode != 201 {
  553. return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, remote.RemoteName()), res)
  554. }
  555. return nil
  556. }
  557. // PushImageJSONIndex uploads an image list to the repository
  558. func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) {
  559. cleanImgList := []*ImgData{}
  560. if validate {
  561. for _, elem := range imgList {
  562. if elem.Checksum != "" {
  563. cleanImgList = append(cleanImgList, elem)
  564. }
  565. }
  566. } else {
  567. cleanImgList = imgList
  568. }
  569. imgListJSON, err := json.Marshal(cleanImgList)
  570. if err != nil {
  571. return nil, err
  572. }
  573. var suffix string
  574. if validate {
  575. suffix = "images"
  576. }
  577. u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), remote.RemoteName(), suffix)
  578. logrus.Debugf("[registry] PUT %s", u)
  579. logrus.Debugf("Image list pushed to index:\n%s", imgListJSON)
  580. headers := map[string][]string{
  581. "Content-type": {"application/json"},
  582. // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
  583. "X-Docker-Token": {"true"},
  584. }
  585. if validate {
  586. headers["X-Docker-Endpoints"] = regs
  587. }
  588. // Redirect if necessary
  589. var res *http.Response
  590. for {
  591. if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil {
  592. return nil, err
  593. }
  594. if !shouldRedirect(res) {
  595. break
  596. }
  597. res.Body.Close()
  598. u = res.Header.Get("Location")
  599. logrus.Debugf("Redirected to %s", u)
  600. }
  601. defer res.Body.Close()
  602. if res.StatusCode == 401 {
  603. return nil, errcode.ErrorCodeUnauthorized.WithArgs()
  604. }
  605. var tokens, endpoints []string
  606. if !validate {
  607. if res.StatusCode != 200 && res.StatusCode != 201 {
  608. errBody, err := ioutil.ReadAll(res.Body)
  609. if err != nil {
  610. logrus.Debugf("Error reading response body: %s", err)
  611. }
  612. return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
  613. }
  614. tokens = res.Header["X-Docker-Token"]
  615. logrus.Debugf("Auth token: %v", tokens)
  616. if res.Header.Get("X-Docker-Endpoints") == "" {
  617. return nil, fmt.Errorf("Index response didn't contain any endpoints")
  618. }
  619. endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
  620. if err != nil {
  621. return nil, err
  622. }
  623. } else {
  624. if res.StatusCode != 204 {
  625. errBody, err := ioutil.ReadAll(res.Body)
  626. if err != nil {
  627. logrus.Debugf("Error reading response body: %s", err)
  628. }
  629. return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
  630. }
  631. }
  632. return &RepositoryData{
  633. Endpoints: endpoints,
  634. }, nil
  635. }
  636. func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) {
  637. req, err := http.NewRequest("PUT", u, bytes.NewReader(body))
  638. if err != nil {
  639. return nil, err
  640. }
  641. req.ContentLength = int64(len(body))
  642. for k, v := range headers {
  643. req.Header[k] = v
  644. }
  645. response, err := r.client.Do(req)
  646. if err != nil {
  647. return nil, err
  648. }
  649. return response, nil
  650. }
  651. func shouldRedirect(response *http.Response) bool {
  652. return response.StatusCode >= 300 && response.StatusCode < 400
  653. }
  654. // SearchRepositories performs a search against the remote repository
  655. func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) {
  656. if limit < 1 || limit > 100 {
  657. return nil, fmt.Errorf("Limit %d is outside the range of [1, 100]", limit)
  658. }
  659. logrus.Debugf("Index server: %s", r.indexEndpoint)
  660. u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit))
  661. req, err := http.NewRequest("GET", u, nil)
  662. if err != nil {
  663. return nil, fmt.Errorf("Error while getting from the server: %v", err)
  664. }
  665. // Have the AuthTransport send authentication, when logged in.
  666. req.Header.Set("X-Docker-Token", "true")
  667. res, err := r.client.Do(req)
  668. if err != nil {
  669. return nil, err
  670. }
  671. defer res.Body.Close()
  672. if res.StatusCode != 200 {
  673. return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res)
  674. }
  675. result := new(registrytypes.SearchResults)
  676. return result, json.NewDecoder(res.Body).Decode(result)
  677. }
  678. // GetAuthConfig returns the authentication settings for a session
  679. // TODO(tiborvass): remove this once registry client v2 is vendored
  680. func (r *Session) GetAuthConfig(withPasswd bool) *types.AuthConfig {
  681. password := ""
  682. if withPasswd {
  683. password = r.authConfig.Password
  684. }
  685. return &types.AuthConfig{
  686. Username: r.authConfig.Username,
  687. Password: password,
  688. }
  689. }
  690. func isTimeout(err error) bool {
  691. type timeout interface {
  692. Timeout() bool
  693. }
  694. e := err
  695. switch urlErr := err.(type) {
  696. case *url.Error:
  697. e = urlErr.Err
  698. }
  699. t, ok := e.(timeout)
  700. return ok && t.Timeout()
  701. }