8 // this is required for some certificates
21 "github.com/Sirupsen/logrus"
22 "github.com/docker/distribution/reference"
23 "github.com/docker/distribution/registry/api/errcode"
24 "github.com/docker/docker/api/types"
25 registrytypes "github.com/docker/docker/api/types/registry"
26 "github.com/docker/docker/pkg/ioutils"
27 "github.com/docker/docker/pkg/jsonmessage"
28 "github.com/docker/docker/pkg/stringid"
29 "github.com/docker/docker/pkg/tarsum"
30 "github.com/docker/docker/registry/resumable"
34 // ErrRepoNotFound is returned if the repository didn't exist on the
36 ErrRepoNotFound = errors.New("Repository not found")
39 // A Session is used to communicate with a V1 registry
41 indexEndpoint *V1Endpoint
43 // TODO(tiborvass): remove authConfig
44 authConfig *types.AuthConfig
48 type authTransport struct {
52 alwaysSetBasicAuth bool
55 mu sync.Mutex // guards modReq
56 modReq map[*http.Request]*http.Request // original -> modified
59 // AuthTransport handles the auth layer when communicating with a v1 registry (private or official)
61 // For private v1 registries, set alwaysSetBasicAuth to true.
63 // For the official v1 registry, if there isn't already an Authorization header in the request,
64 // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header.
65 // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing
66 // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent
69 // If the server sends a token without the client having requested it, it is ignored.
71 // This RoundTripper also has a CancelRequest method important for correct timeout handling.
72 func AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper {
74 base = http.DefaultTransport
76 return &authTransport{
78 AuthConfig: authConfig,
79 alwaysSetBasicAuth: alwaysSetBasicAuth,
80 modReq: make(map[*http.Request]*http.Request),
84 // cloneRequest returns a clone of the provided *http.Request.
85 // The clone is a shallow copy of the struct and its Header map.
86 func cloneRequest(r *http.Request) *http.Request {
87 // shallow copy of the struct
88 r2 := new(http.Request)
90 // deep copy of the Header
91 r2.Header = make(http.Header, len(r.Header))
92 for k, s := range r.Header {
93 r2.Header[k] = append([]string(nil), s...)
99 // RoundTrip changes an HTTP request's headers to add the necessary
100 // authentication-related headers
101 func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) {
102 // Authorization should not be set on 302 redirect for untrusted locations.
103 // This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
104 // As the authorization logic is currently implemented in RoundTrip,
105 // a 302 redirect is detected by looking at the Referrer header as go http package adds said header.
106 // This is safe as Docker doesn't set Referrer in other scenarios.
107 if orig.Header.Get("Referer") != "" && !trustedLocation(orig) {
108 return tr.RoundTripper.RoundTrip(orig)
111 req := cloneRequest(orig)
113 tr.modReq[orig] = req
116 if tr.alwaysSetBasicAuth {
117 if tr.AuthConfig == nil {
118 return nil, errors.New("unexpected error: empty auth config")
120 req.SetBasicAuth(tr.Username, tr.Password)
121 return tr.RoundTripper.RoundTrip(req)
125 if req.Header.Get("Authorization") == "" {
126 if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 {
127 req.SetBasicAuth(tr.Username, tr.Password)
128 } else if len(tr.token) > 0 {
129 req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ","))
132 resp, err := tr.RoundTripper.RoundTrip(req)
134 delete(tr.modReq, orig)
137 if len(resp.Header["X-Docker-Token"]) > 0 {
138 tr.token = resp.Header["X-Docker-Token"]
140 resp.Body = &ioutils.OnEOFReader{
144 delete(tr.modReq, orig)
151 // CancelRequest cancels an in-flight request by closing its connection.
152 func (tr *authTransport) CancelRequest(req *http.Request) {
153 type canceler interface {
154 CancelRequest(*http.Request)
156 if cr, ok := tr.RoundTripper.(canceler); ok {
158 modReq := tr.modReq[req]
159 delete(tr.modReq, req)
161 cr.CancelRequest(modReq)
165 func authorizeClient(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) error {
166 var alwaysSetBasicAuth bool
168 // If we're working with a standalone private registry over HTTPS, send Basic Auth headers
169 // alongside all our requests.
170 if endpoint.String() != IndexServer && endpoint.URL.Scheme == "https" {
171 info, err := endpoint.Ping()
175 if info.Standalone && authConfig != nil {
176 logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String())
177 alwaysSetBasicAuth = true
181 // Annotate the transport unconditionally so that v2 can
182 // properly fallback on v1 when an image is not found.
183 client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth)
185 jar, err := cookiejar.New(nil)
187 return errors.New("cookiejar.New is not supposed to return an error")
194 func newSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) *Session {
196 authConfig: authConfig,
198 indexEndpoint: endpoint,
199 id: stringid.GenerateRandomID(),
203 // NewSession creates a new session
204 // TODO(tiborvass): remove authConfig param once registry client v2 is vendored
205 func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) (*Session, error) {
206 if err := authorizeClient(client, authConfig, endpoint); err != nil {
210 return newSession(client, authConfig, endpoint), nil
213 // ID returns this registry session's ID.
214 func (r *Session) ID() string {
218 // GetRemoteHistory retrieves the history of a given image from the registry.
219 // It returns a list of the parent's JSON files (including the requested image).
220 func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) {
221 res, err := r.client.Get(registry + "images/" + imgID + "/ancestry")
225 defer res.Body.Close()
226 if res.StatusCode != 200 {
227 if res.StatusCode == 401 {
228 return nil, errcode.ErrorCodeUnauthorized.WithArgs()
230 return nil, newJSONError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res)
234 if err := json.NewDecoder(res.Body).Decode(&history); err != nil {
235 return nil, fmt.Errorf("Error while reading the http response: %v", err)
238 logrus.Debugf("Ancestry: %v", history)
242 // LookupRemoteImage checks if an image exists in the registry
243 func (r *Session) LookupRemoteImage(imgID, registry string) error {
244 res, err := r.client.Get(registry + "images/" + imgID + "/json")
249 if res.StatusCode != 200 {
250 return newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
255 // GetRemoteImageJSON retrieves an image's JSON metadata from the registry.
256 func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) {
257 res, err := r.client.Get(registry + "images/" + imgID + "/json")
259 return nil, -1, fmt.Errorf("Failed to download json: %s", err)
261 defer res.Body.Close()
262 if res.StatusCode != 200 {
263 return nil, -1, newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
265 // if the size header is not present, then set it to '-1'
266 imageSize := int64(-1)
267 if hdr := res.Header.Get("X-Docker-Size"); hdr != "" {
268 imageSize, err = strconv.ParseInt(hdr, 10, 64)
274 jsonString, err := ioutil.ReadAll(res.Body)
276 return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString)
278 return jsonString, imageSize, nil
281 // GetRemoteImageLayer retrieves an image layer from the registry
282 func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) {
287 imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID)
290 req, err := http.NewRequest("GET", imageURL, nil)
292 return nil, fmt.Errorf("Error while getting from the server: %v", err)
295 res, err = r.client.Do(req)
297 logrus.Debugf("Error contacting registry %s: %v", registry, err)
298 // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515
303 statusCode = res.StatusCode
305 return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
309 if res.StatusCode != 200 {
311 return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
312 res.StatusCode, imgID)
315 if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 {
316 logrus.Debug("server supports resume")
317 return resumable.NewRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil
319 logrus.Debug("server doesn't support resume")
323 // GetRemoteTag retrieves the tag named in the askedTag argument from the given
324 // repository. It queries each of the registries supplied in the registries
325 // argument, and returns data from the first one that answers the query
327 func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) {
328 repository := reference.Path(repositoryRef)
330 if strings.Count(repository, "/") == 0 {
331 // This will be removed once the registry supports auto-resolution on
332 // the "library" namespace
333 repository = "library/" + repository
335 for _, host := range registries {
336 endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag)
337 res, err := r.client.Get(endpoint)
342 logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
343 defer res.Body.Close()
345 if res.StatusCode == 404 {
346 return "", ErrRepoNotFound
348 if res.StatusCode != 200 {
353 if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil {
358 return "", fmt.Errorf("Could not reach any registry endpoint")
361 // GetRemoteTags retrieves all tags from the given repository. It queries each
362 // of the registries supplied in the registries argument, and returns data from
363 // the first one that answers the query successfully. It returns a map with
364 // tag names as the keys and image IDs as the values.
365 func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) {
366 repository := reference.Path(repositoryRef)
368 if strings.Count(repository, "/") == 0 {
369 // This will be removed once the registry supports auto-resolution on
370 // the "library" namespace
371 repository = "library/" + repository
373 for _, host := range registries {
374 endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository)
375 res, err := r.client.Get(endpoint)
380 logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
381 defer res.Body.Close()
383 if res.StatusCode == 404 {
384 return nil, ErrRepoNotFound
386 if res.StatusCode != 200 {
390 result := make(map[string]string)
391 if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
396 return nil, fmt.Errorf("Could not reach any registry endpoint")
399 func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
400 var endpoints []string
401 parsedURL, err := url.Parse(indexEp)
405 var urlScheme = parsedURL.Scheme
406 // The registry's URL scheme has to match the Index'
407 for _, ep := range headers {
408 epList := strings.Split(ep, ",")
409 for _, epListElement := range epList {
412 fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement)))
415 return endpoints, nil
418 // GetRepositoryData returns lists of images and endpoints for the repository
419 func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) {
420 repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), reference.Path(name))
422 logrus.Debugf("[registry] Calling GET %s", repositoryTarget)
424 req, err := http.NewRequest("GET", repositoryTarget, nil)
428 // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
429 req.Header.Set("X-Docker-Token", "true")
430 res, err := r.client.Do(req)
432 // check if the error is because of i/o timeout
433 // and return a non-obtuse error message for users
434 // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout"
435 // was a top search on the docker user forum
437 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)
439 return nil, fmt.Errorf("Error while pulling image: %v", err)
441 defer res.Body.Close()
442 if res.StatusCode == 401 {
443 return nil, errcode.ErrorCodeUnauthorized.WithArgs()
445 // TODO: Right now we're ignoring checksums in the response body.
446 // In the future, we need to use them to check image validity.
447 if res.StatusCode == 404 {
448 return nil, newJSONError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res)
449 } else if res.StatusCode != 200 {
450 errBody, err := ioutil.ReadAll(res.Body)
452 logrus.Debugf("Error reading response body: %s", err)
454 return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, reference.Path(name), errBody), res)
457 var endpoints []string
458 if res.Header.Get("X-Docker-Endpoints") != "" {
459 endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
464 // Assume the endpoint is on the same host
465 endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host))
468 remoteChecksums := []*ImgData{}
469 if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil {
473 // Forge a better object from the retrieved data
474 imgsData := make(map[string]*ImgData, len(remoteChecksums))
475 for _, elem := range remoteChecksums {
476 imgsData[elem.ID] = elem
479 return &RepositoryData{
481 Endpoints: endpoints,
485 // PushImageChecksumRegistry uploads checksums for an image
486 func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error {
487 u := registry + "images/" + imgData.ID + "/checksum"
489 logrus.Debugf("[registry] Calling PUT %s", u)
491 req, err := http.NewRequest("PUT", u, nil)
495 req.Header.Set("X-Docker-Checksum", imgData.Checksum)
496 req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload)
498 res, err := r.client.Do(req)
500 return fmt.Errorf("Failed to upload metadata: %v", err)
502 defer res.Body.Close()
503 if len(res.Cookies()) > 0 {
504 r.client.Jar.SetCookies(req.URL, res.Cookies())
506 if res.StatusCode != 200 {
507 errBody, err := ioutil.ReadAll(res.Body)
509 return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err)
511 var jsonBody map[string]string
512 if err := json.Unmarshal(errBody, &jsonBody); err != nil {
513 errBody = []byte(err.Error())
514 } else if jsonBody["error"] == "Image already exists" {
515 return ErrAlreadyExists
517 return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody)
522 // PushImageJSONRegistry pushes JSON metadata for a local image to the registry
523 func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error {
525 u := registry + "images/" + imgData.ID + "/json"
527 logrus.Debugf("[registry] Calling PUT %s", u)
529 req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw))
533 req.Header.Add("Content-type", "application/json")
535 res, err := r.client.Do(req)
537 return fmt.Errorf("Failed to upload metadata: %s", err)
539 defer res.Body.Close()
540 if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") {
541 return newJSONError("HTTP code 401, Docker will not send auth headers over HTTP.", res)
543 if res.StatusCode != 200 {
544 errBody, err := ioutil.ReadAll(res.Body)
546 return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
548 var jsonBody map[string]string
549 if err := json.Unmarshal(errBody, &jsonBody); err != nil {
550 errBody = []byte(err.Error())
551 } else if jsonBody["error"] == "Image already exists" {
552 return ErrAlreadyExists
554 return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res)
559 // PushImageLayerRegistry sends the checksum of an image layer to the registry
560 func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) {
561 u := registry + "images/" + imgID + "/layer"
563 logrus.Debugf("[registry] Calling PUT %s", u)
565 tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0)
571 h.Write([]byte{'\n'})
572 checksumLayer := io.TeeReader(tarsumLayer, h)
574 req, err := http.NewRequest("PUT", u, checksumLayer)
578 req.Header.Add("Content-Type", "application/octet-stream")
579 req.ContentLength = -1
580 req.TransferEncoding = []string{"chunked"}
581 res, err := r.client.Do(req)
583 return "", "", fmt.Errorf("Failed to upload layer: %v", err)
585 if rc, ok := layer.(io.Closer); ok {
586 if err := rc.Close(); err != nil {
590 defer res.Body.Close()
592 if res.StatusCode != 200 {
593 errBody, err := ioutil.ReadAll(res.Body)
595 return "", "", newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
597 return "", "", newJSONError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res)
600 checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil))
601 return tarsumLayer.Sum(jsonRaw), checksumPayload, nil
604 // PushRegistryTag pushes a tag on the registry.
605 // Remote has the format '<user>/<repo>
606 func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error {
607 // "jsonify" the string
608 revision = "\"" + revision + "\""
609 path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag)
611 req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision))
615 req.Header.Add("Content-type", "application/json")
616 req.ContentLength = int64(len(revision))
617 res, err := r.client.Do(req)
622 if res.StatusCode != 200 && res.StatusCode != 201 {
623 return newJSONError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res)
628 // PushImageJSONIndex uploads an image list to the repository
629 func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) {
630 cleanImgList := []*ImgData{}
632 for _, elem := range imgList {
633 if elem.Checksum != "" {
634 cleanImgList = append(cleanImgList, elem)
638 cleanImgList = imgList
641 imgListJSON, err := json.Marshal(cleanImgList)
649 u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), reference.Path(remote), suffix)
650 logrus.Debugf("[registry] PUT %s", u)
651 logrus.Debugf("Image list pushed to index:\n%s", imgListJSON)
652 headers := map[string][]string{
653 "Content-type": {"application/json"},
654 // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
655 "X-Docker-Token": {"true"},
658 headers["X-Docker-Endpoints"] = regs
661 // Redirect if necessary
662 var res *http.Response
664 if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil {
667 if !shouldRedirect(res) {
671 u = res.Header.Get("Location")
672 logrus.Debugf("Redirected to %s", u)
674 defer res.Body.Close()
676 if res.StatusCode == 401 {
677 return nil, errcode.ErrorCodeUnauthorized.WithArgs()
680 var tokens, endpoints []string
682 if res.StatusCode != 200 && res.StatusCode != 201 {
683 errBody, err := ioutil.ReadAll(res.Body)
685 logrus.Debugf("Error reading response body: %s", err)
687 return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
689 tokens = res.Header["X-Docker-Token"]
690 logrus.Debugf("Auth token: %v", tokens)
692 if res.Header.Get("X-Docker-Endpoints") == "" {
693 return nil, fmt.Errorf("Index response didn't contain any endpoints")
695 endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String())
700 if res.StatusCode != 204 {
701 errBody, err := ioutil.ReadAll(res.Body)
703 logrus.Debugf("Error reading response body: %s", err)
705 return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, reference.Path(remote), errBody), res)
709 return &RepositoryData{
710 Endpoints: endpoints,
714 func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) {
715 req, err := http.NewRequest("PUT", u, bytes.NewReader(body))
719 req.ContentLength = int64(len(body))
720 for k, v := range headers {
723 response, err := r.client.Do(req)
730 func shouldRedirect(response *http.Response) bool {
731 return response.StatusCode >= 300 && response.StatusCode < 400
734 // SearchRepositories performs a search against the remote repository
735 func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) {
736 if limit < 1 || limit > 100 {
737 return nil, fmt.Errorf("Limit %d is outside the range of [1, 100]", limit)
739 logrus.Debugf("Index server: %s", r.indexEndpoint)
740 u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit))
742 req, err := http.NewRequest("GET", u, nil)
744 return nil, fmt.Errorf("Error while getting from the server: %v", err)
746 // Have the AuthTransport send authentication, when logged in.
747 req.Header.Set("X-Docker-Token", "true")
748 res, err := r.client.Do(req)
752 defer res.Body.Close()
753 if res.StatusCode != 200 {
754 return nil, newJSONError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res)
756 result := new(registrytypes.SearchResults)
757 return result, json.NewDecoder(res.Body).Decode(result)
760 func isTimeout(err error) bool {
761 type timeout interface {
765 switch urlErr := err.(type) {
770 return ok && t.Timeout()
773 func newJSONError(msg string, res *http.Response) error {
774 return &jsonmessage.JSONError{
776 Code: res.StatusCode,