registry/session.go
752dd707
 package registry
 
 import (
 	"bytes"
 	"crypto/sha256"
a01cc3ca
 	"errors"
73823e5e
 	"sync"
ae3b59c1
 	// this is required for some certificates
752dd707
 	_ "crypto/sha512"
 	"encoding/hex"
 	"encoding/json"
 	"fmt"
 	"io"
 	"io/ioutil"
 	"net/http"
 	"net/http/cookiejar"
 	"net/url"
 	"strconv"
 	"strings"
 
6f4d8470
 	"github.com/Sirupsen/logrus"
dc2f5d0f
 	"github.com/docker/distribution/registry/api/errcode"
ee7dd44c
 	"github.com/docker/docker/pkg/httputils"
276c640b
 	"github.com/docker/docker/pkg/ioutils"
1b67c38f
 	"github.com/docker/docker/pkg/stringid"
752dd707
 	"github.com/docker/docker/pkg/tarsum"
2655954c
 	"github.com/docker/docker/reference"
907407d0
 	"github.com/docker/engine-api/types"
 	registrytypes "github.com/docker/engine-api/types/registry"
752dd707
 )
 
b349a74c
 var (
4fcb9ac4
 	// ErrRepoNotFound is returned if the repository didn't exist on the
 	// remote side
b349a74c
 	ErrRepoNotFound = errors.New("Repository not found")
 )
 
4fcb9ac4
 // A Session is used to communicate with a V1 registry
752dd707
 type Session struct {
61c6f206
 	indexEndpoint *Endpoint
a01cc3ca
 	client        *http.Client
 	// TODO(tiborvass): remove authConfig
5b321e32
 	authConfig *types.AuthConfig
1b67c38f
 	id         string
752dd707
 }
 
73823e5e
 type authTransport struct {
 	http.RoundTripper
5b321e32
 	*types.AuthConfig
73823e5e
 
 	alwaysSetBasicAuth bool
 	token              []string
 
 	mu     sync.Mutex                      // guards modReq
 	modReq map[*http.Request]*http.Request // original -> modified
 }
 
 // AuthTransport handles the auth layer when communicating with a v1 registry (private or official)
a01cc3ca
 //
 // For private v1 registries, set alwaysSetBasicAuth to true.
 //
 // For the official v1 registry, if there isn't already an Authorization header in the request,
 // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header.
 // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing
 // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent
 // requests.
 //
 // If the server sends a token without the client having requested it, it is ignored.
 //
 // This RoundTripper also has a CancelRequest method important for correct timeout handling.
5b321e32
 func AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper {
73823e5e
 	if base == nil {
 		base = http.DefaultTransport
 	}
 	return &authTransport{
 		RoundTripper:       base,
 		AuthConfig:         authConfig,
 		alwaysSetBasicAuth: alwaysSetBasicAuth,
 		modReq:             make(map[*http.Request]*http.Request),
 	}
a01cc3ca
 }
752dd707
 
276c640b
 // cloneRequest returns a clone of the provided *http.Request.
 // The clone is a shallow copy of the struct and its Header map.
 func cloneRequest(r *http.Request) *http.Request {
 	// shallow copy of the struct
 	r2 := new(http.Request)
 	*r2 = *r
 	// deep copy of the Header
 	r2.Header = make(http.Header, len(r.Header))
 	for k, s := range r.Header {
 		r2.Header[k] = append([]string(nil), s...)
 	}
 
 	return r2
 }
 
4fcb9ac4
 // RoundTrip changes a HTTP request's headers to add the necessary
 // authentication-related headers
73823e5e
 func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) {
123a0582
 	// Authorization should not be set on 302 redirect for untrusted locations.
4fcb9ac4
 	// This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
123a0582
 	// As the authorization logic is currently implemented in RoundTrip,
927b334e
 	// a 302 redirect is detected by looking at the Referrer header as go http package adds said header.
 	// This is safe as Docker doesn't set Referrer in other scenarios.
123a0582
 	if orig.Header.Get("Referer") != "" && !trustedLocation(orig) {
 		return tr.RoundTripper.RoundTrip(orig)
 	}
 
19515a7a
 	req := cloneRequest(orig)
73823e5e
 	tr.mu.Lock()
 	tr.modReq[orig] = req
 	tr.mu.Unlock()
a01cc3ca
 
 	if tr.alwaysSetBasicAuth {
b32c4cb4
 		if tr.AuthConfig == nil {
 			return nil, errors.New("unexpected error: empty auth config")
 		}
a01cc3ca
 		req.SetBasicAuth(tr.Username, tr.Password)
 		return tr.RoundTripper.RoundTrip(req)
752dd707
 	}
 
a01cc3ca
 	// Don't override
 	if req.Header.Get("Authorization") == "" {
b32c4cb4
 		if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 {
a01cc3ca
 			req.SetBasicAuth(tr.Username, tr.Password)
123a0582
 		} else if len(tr.token) > 0 {
a01cc3ca
 			req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ","))
 		}
 	}
 	resp, err := tr.RoundTripper.RoundTrip(req)
752dd707
 	if err != nil {
73823e5e
 		delete(tr.modReq, orig)
752dd707
 		return nil, err
 	}
fc29f7f7
 	if len(resp.Header["X-Docker-Token"]) > 0 {
a01cc3ca
 		tr.token = resp.Header["X-Docker-Token"]
 	}
276c640b
 	resp.Body = &ioutils.OnEOFReader{
73823e5e
 		Rc: resp.Body,
9d98c288
 		Fn: func() {
 			tr.mu.Lock()
 			delete(tr.modReq, orig)
 			tr.mu.Unlock()
 		},
73823e5e
 	}
a01cc3ca
 	return resp, nil
 }
 
73823e5e
 // CancelRequest cancels an in-flight request by closing its connection.
 func (tr *authTransport) CancelRequest(req *http.Request) {
 	type canceler interface {
 		CancelRequest(*http.Request)
 	}
 	if cr, ok := tr.RoundTripper.(canceler); ok {
 		tr.mu.Lock()
 		modReq := tr.modReq[req]
 		delete(tr.modReq, req)
 		tr.mu.Unlock()
 		cr.CancelRequest(modReq)
 	}
 }
 
4fcb9ac4
 // NewSession creates a new session
a01cc3ca
 // TODO(tiborvass): remove authConfig param once registry client v2 is vendored
5b321e32
 func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *Endpoint) (r *Session, err error) {
a01cc3ca
 	r = &Session{
 		authConfig:    authConfig,
 		client:        client,
 		indexEndpoint: endpoint,
1b67c38f
 		id:            stringid.GenerateRandomID(),
a01cc3ca
 	}
 
 	var alwaysSetBasicAuth bool
752dd707
 
 	// If we're working with a standalone private registry over HTTPS, send Basic Auth headers
a01cc3ca
 	// alongside all our requests.
4fcb9ac4
 	if endpoint.VersionString(1) != IndexServer && endpoint.URL.Scheme == "https" {
a01cc3ca
 		info, err := endpoint.Ping()
752dd707
 		if err != nil {
 			return nil, err
 		}
a01cc3ca
 		if info.Standalone && authConfig != nil {
 			logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String())
 			alwaysSetBasicAuth = true
752dd707
 		}
 	}
 
c2315102
 	// Annotate the transport unconditionally so that v2 can
 	// properly fallback on v1 when an image is not found.
 	client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth)
752dd707
 
a01cc3ca
 	jar, err := cookiejar.New(nil)
 	if err != nil {
 		return nil, errors.New("cookiejar.New is not supposed to return an error")
 	}
 	client.Jar = jar
 
 	return r, nil
752dd707
 }
 
1b67c38f
 // ID returns this registry session's ID.
 func (r *Session) ID() string {
 	return r.id
 }
 
4fcb9ac4
 // GetRemoteHistory retrieves the history of a given image from the registry.
 // It returns a list of the parent's JSON files (including the requested image).
a01cc3ca
 func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) {
 	res, err := r.client.Get(registry + "images/" + imgID + "/ancestry")
752dd707
 	if err != nil {
 		return nil, err
 	}
 	defer res.Body.Close()
 	if res.StatusCode != 200 {
 		if res.StatusCode == 401 {
dc2f5d0f
 			return nil, errcode.ErrorCodeUnauthorized.WithArgs()
752dd707
 		}
c30a55f1
 		return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res)
752dd707
 	}
 
a01cc3ca
 	var history []string
 	if err := json.NewDecoder(res.Body).Decode(&history); err != nil {
 		return nil, fmt.Errorf("Error while reading the http response: %v", err)
752dd707
 	}
 
a01cc3ca
 	logrus.Debugf("Ancestry: %v", history)
 	return history, nil
752dd707
 }
 
4fcb9ac4
 // LookupRemoteImage checks if an image exists in the registry
a01cc3ca
 func (r *Session) LookupRemoteImage(imgID, registry string) error {
 	res, err := r.client.Get(registry + "images/" + imgID + "/json")
752dd707
 	if err != nil {
8123c1e9
 		return err
752dd707
 	}
 	res.Body.Close()
8123c1e9
 	if res.StatusCode != 200 {
c30a55f1
 		return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
8123c1e9
 	}
 	return nil
752dd707
 }
 
4fcb9ac4
 // GetRemoteImageJSON retrieves an image's JSON metadata from the registry.
1f61084d
 func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) {
a01cc3ca
 	res, err := r.client.Get(registry + "images/" + imgID + "/json")
752dd707
 	if err != nil {
 		return nil, -1, fmt.Errorf("Failed to download json: %s", err)
 	}
 	defer res.Body.Close()
 	if res.StatusCode != 200 {
c30a55f1
 		return nil, -1, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res)
752dd707
 	}
 	// if the size header is not present, then set it to '-1'
1f61084d
 	imageSize := int64(-1)
752dd707
 	if hdr := res.Header.Get("X-Docker-Size"); hdr != "" {
1f61084d
 		imageSize, err = strconv.ParseInt(hdr, 10, 64)
752dd707
 		if err != nil {
 			return nil, -1, err
 		}
 	}
 
 	jsonString, err := ioutil.ReadAll(res.Body)
 	if err != nil {
a01cc3ca
 		return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString)
752dd707
 	}
 	return jsonString, imageSize, nil
 }
 
4fcb9ac4
 // GetRemoteImageLayer retrieves an image layer from the registry
a01cc3ca
 func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) {
752dd707
 	var (
3e6c69e5
 		statusCode = 0
 		res        *http.Response
a01cc3ca
 		err        error
3e6c69e5
 		imageURL   = fmt.Sprintf("%simages/%s/layer", registry, imgID)
752dd707
 	)
 
a01cc3ca
 	req, err := http.NewRequest("GET", imageURL, nil)
752dd707
 	if err != nil {
a01cc3ca
 		return nil, fmt.Errorf("Error while getting from the server: %v", err)
752dd707
 	}
572ce802
 	statusCode = 0
 	res, err = r.client.Do(req)
 	if err != nil {
a01cc3ca
 		logrus.Debugf("Error contacting registry %s: %v", registry, err)
 		if res != nil {
 			if res.Body != nil {
 				res.Body.Close()
752dd707
 			}
a01cc3ca
 			statusCode = res.StatusCode
 		}
572ce802
 		return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
 			statusCode, imgID)
752dd707
 	}
 
 	if res.StatusCode != 200 {
 		res.Body.Close()
 		return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
 			res.StatusCode, imgID)
 	}
 
 	if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 {
6f4d8470
 		logrus.Debugf("server supports resume")
a01cc3ca
 		return httputils.ResumableRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil
752dd707
 	}
6f4d8470
 	logrus.Debugf("server doesn't support resume")
752dd707
 	return res.Body, nil
 }
 
4fcb9ac4
 // GetRemoteTag retrieves the tag named in the askedTag argument from the given
 // repository. It queries each of the registries supplied in the registries
 // argument, and returns data from the first one that answers the query
 // successfully.
4352da78
 func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) {
ffded61d
 	repository := repositoryRef.RemoteName()
4352da78
 
b349a74c
 	if strings.Count(repository, "/") == 0 {
4fcb9ac4
 		// This will be removed once the registry supports auto-resolution on
b349a74c
 		// the "library" namespace
 		repository = "library/" + repository
 	}
 	for _, host := range registries {
 		endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag)
 		res, err := r.client.Get(endpoint)
 		if err != nil {
 			return "", err
 		}
 
 		logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
 		defer res.Body.Close()
 
 		if res.StatusCode == 404 {
 			return "", ErrRepoNotFound
 		}
 		if res.StatusCode != 200 {
 			continue
 		}
 
4fcb9ac4
 		var tagID string
 		if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil {
b349a74c
 			return "", err
 		}
4fcb9ac4
 		return tagID, nil
b349a74c
 	}
 	return "", fmt.Errorf("Could not reach any registry endpoint")
 }
 
4fcb9ac4
 // GetRemoteTags retrieves all tags from the given repository. It queries each
 // of the registries supplied in the registries argument, and returns data from
 // the first one that answers the query successfully. It returns a map with
 // tag names as the keys and image IDs as the values.
4352da78
 func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) {
ffded61d
 	repository := repositoryRef.RemoteName()
4352da78
 
752dd707
 	if strings.Count(repository, "/") == 0 {
4fcb9ac4
 		// This will be removed once the registry supports auto-resolution on
752dd707
 		// the "library" namespace
 		repository = "library/" + repository
 	}
 	for _, host := range registries {
 		endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository)
a01cc3ca
 		res, err := r.client.Get(endpoint)
752dd707
 		if err != nil {
 			return nil, err
 		}
 
6f4d8470
 		logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint)
752dd707
 		defer res.Body.Close()
 
8655214b
 		if res.StatusCode == 404 {
b349a74c
 			return nil, ErrRepoNotFound
5f2b051e
 		}
 		if res.StatusCode != 200 {
8655214b
 			continue
752dd707
 		}
 
 		result := make(map[string]string)
b65eb8d2
 		if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
752dd707
 			return nil, err
 		}
 		return result, nil
 	}
 	return nil, fmt.Errorf("Could not reach any registry endpoint")
 }
 
 func buildEndpointsList(headers []string, indexEp string) ([]string, error) {
 	var endpoints []string
ae3b59c1
 	parsedURL, err := url.Parse(indexEp)
752dd707
 	if err != nil {
 		return nil, err
 	}
ae3b59c1
 	var urlScheme = parsedURL.Scheme
4fcb9ac4
 	// The registry's URL scheme has to match the Index'
752dd707
 	for _, ep := range headers {
 		epList := strings.Split(ep, ",")
 		for _, epListElement := range epList {
 			endpoints = append(
 				endpoints,
 				fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement)))
 		}
 	}
 	return endpoints, nil
 }
 
4fcb9ac4
 // GetRepositoryData returns lists of images and endpoints for the repository
ffded61d
 func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) {
 	repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.VersionString(1), name.RemoteName())
752dd707
 
6f4d8470
 	logrus.Debugf("[registry] Calling GET %s", repositoryTarget)
752dd707
 
a01cc3ca
 	req, err := http.NewRequest("GET", repositoryTarget, nil)
752dd707
 	if err != nil {
 		return nil, err
 	}
a01cc3ca
 	// this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
752dd707
 	req.Header.Set("X-Docker-Token", "true")
a01cc3ca
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
ca3dae52
 		// check if the error is because of i/o timeout
 		// and return a non-obtuse error message for users
 		// "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout"
 		// was a top search on the docker user forum
9dc7d07f
 		if isTimeout(err) {
ca3dae52
 			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)
 		}
 		return nil, fmt.Errorf("Error while pulling image: %v", err)
752dd707
 	}
 	defer res.Body.Close()
 	if res.StatusCode == 401 {
dc2f5d0f
 		return nil, errcode.ErrorCodeUnauthorized.WithArgs()
752dd707
 	}
 	// TODO: Right now we're ignoring checksums in the response body.
 	// In the future, we need to use them to check image validity.
c8d2ec93
 	if res.StatusCode == 404 {
c30a55f1
 		return nil, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res)
c8d2ec93
 	} else if res.StatusCode != 200 {
efa65d16
 		errBody, err := ioutil.ReadAll(res.Body)
 		if err != nil {
6f4d8470
 			logrus.Debugf("Error reading response body: %s", err)
efa65d16
 		}
ffded61d
 		return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, name.RemoteName(), errBody), res)
752dd707
 	}
 
 	var endpoints []string
 	if res.Header.Get("X-Docker-Endpoints") != "" {
7c88e8f1
 		endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1))
752dd707
 		if err != nil {
 			return nil, err
 		}
 	} else {
 		// Assume the endpoint is on the same host
61c6f206
 		endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host))
752dd707
 	}
 
 	remoteChecksums := []*ImgData{}
b65eb8d2
 	if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil {
752dd707
 		return nil, err
 	}
 
 	// Forge a better object from the retrieved data
19515a7a
 	imgsData := make(map[string]*ImgData, len(remoteChecksums))
752dd707
 	for _, elem := range remoteChecksums {
 		imgsData[elem.ID] = elem
 	}
 
 	return &RepositoryData{
 		ImgList:   imgsData,
 		Endpoints: endpoints,
 	}, nil
 }
 
4fcb9ac4
 // PushImageChecksumRegistry uploads checksums for an image
a01cc3ca
 func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error {
 	u := registry + "images/" + imgData.ID + "/checksum"
752dd707
 
a01cc3ca
 	logrus.Debugf("[registry] Calling PUT %s", u)
752dd707
 
a01cc3ca
 	req, err := http.NewRequest("PUT", u, nil)
752dd707
 	if err != nil {
 		return err
 	}
 	req.Header.Set("X-Docker-Checksum", imgData.Checksum)
 	req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload)
 
a01cc3ca
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
a01cc3ca
 		return fmt.Errorf("Failed to upload metadata: %v", err)
752dd707
 	}
 	defer res.Body.Close()
 	if len(res.Cookies()) > 0 {
a01cc3ca
 		r.client.Jar.SetCookies(req.URL, res.Cookies())
752dd707
 	}
 	if res.StatusCode != 200 {
 		errBody, err := ioutil.ReadAll(res.Body)
 		if err != nil {
 			return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err)
 		}
 		var jsonBody map[string]string
 		if err := json.Unmarshal(errBody, &jsonBody); err != nil {
 			errBody = []byte(err.Error())
 		} else if jsonBody["error"] == "Image already exists" {
 			return ErrAlreadyExists
 		}
33c94eb2
 		return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody)
752dd707
 	}
 	return nil
 }
 
4fcb9ac4
 // PushImageJSONRegistry pushes JSON metadata for a local image to the registry
a01cc3ca
 func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error {
752dd707
 
a01cc3ca
 	u := registry + "images/" + imgData.ID + "/json"
752dd707
 
a01cc3ca
 	logrus.Debugf("[registry] Calling PUT %s", u)
 
 	req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw))
752dd707
 	if err != nil {
 		return err
 	}
 	req.Header.Add("Content-type", "application/json")
 
a01cc3ca
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
 		return fmt.Errorf("Failed to upload metadata: %s", err)
 	}
 	defer res.Body.Close()
 	if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") {
c30a55f1
 		return httputils.NewHTTPRequestError("HTTP code 401, Docker will not send auth headers over HTTP.", res)
752dd707
 	}
 	if res.StatusCode != 200 {
 		errBody, err := ioutil.ReadAll(res.Body)
 		if err != nil {
c30a55f1
 			return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
752dd707
 		}
 		var jsonBody map[string]string
 		if err := json.Unmarshal(errBody, &jsonBody); err != nil {
 			errBody = []byte(err.Error())
 		} else if jsonBody["error"] == "Image already exists" {
 			return ErrAlreadyExists
 		}
c30a55f1
 		return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res)
752dd707
 	}
 	return nil
 }
 
4fcb9ac4
 // PushImageLayerRegistry sends the checksum of an image layer to the registry
a01cc3ca
 func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) {
 	u := registry + "images/" + imgID + "/layer"
752dd707
 
a01cc3ca
 	logrus.Debugf("[registry] Calling PUT %s", u)
752dd707
 
747f89cd
 	tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0)
 	if err != nil {
 		return "", "", err
 	}
752dd707
 	h := sha256.New()
 	h.Write(jsonRaw)
 	h.Write([]byte{'\n'})
 	checksumLayer := io.TeeReader(tarsumLayer, h)
 
a01cc3ca
 	req, err := http.NewRequest("PUT", u, checksumLayer)
752dd707
 	if err != nil {
 		return "", "", err
 	}
 	req.Header.Add("Content-Type", "application/octet-stream")
 	req.ContentLength = -1
 	req.TransferEncoding = []string{"chunked"}
a01cc3ca
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
a01cc3ca
 		return "", "", fmt.Errorf("Failed to upload layer: %v", err)
752dd707
 	}
 	if rc, ok := layer.(io.Closer); ok {
 		if err := rc.Close(); err != nil {
 			return "", "", err
 		}
 	}
 	defer res.Body.Close()
 
 	if res.StatusCode != 200 {
 		errBody, err := ioutil.ReadAll(res.Body)
 		if err != nil {
c30a55f1
 			return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res)
752dd707
 		}
c30a55f1
 		return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res)
752dd707
 	}
 
 	checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil))
 	return tarsumLayer.Sum(jsonRaw), checksumPayload, nil
 }
 
4fcb9ac4
 // PushRegistryTag pushes a tag on the registry.
752dd707
 // Remote has the format '<user>/<repo>
4352da78
 func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error {
752dd707
 	// "jsonify" the string
 	revision = "\"" + revision + "\""
ffded61d
 	path := fmt.Sprintf("repositories/%s/tags/%s", remote.RemoteName(), tag)
752dd707
 
a01cc3ca
 	req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision))
752dd707
 	if err != nil {
 		return err
 	}
 	req.Header.Add("Content-type", "application/json")
 	req.ContentLength = int64(len(revision))
a01cc3ca
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
 		return err
 	}
 	res.Body.Close()
 	if res.StatusCode != 200 && res.StatusCode != 201 {
ffded61d
 		return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, remote.RemoteName()), res)
752dd707
 	}
 	return nil
 }
 
4fcb9ac4
 // PushImageJSONIndex uploads an image list to the repository
4352da78
 func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) {
752dd707
 	cleanImgList := []*ImgData{}
 	if validate {
 		for _, elem := range imgList {
 			if elem.Checksum != "" {
 				cleanImgList = append(cleanImgList, elem)
 			}
 		}
 	} else {
 		cleanImgList = imgList
 	}
 
 	imgListJSON, err := json.Marshal(cleanImgList)
 	if err != nil {
 		return nil, err
 	}
 	var suffix string
 	if validate {
 		suffix = "images"
 	}
ffded61d
 	u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.VersionString(1), remote.RemoteName(), suffix)
6f4d8470
 	logrus.Debugf("[registry] PUT %s", u)
 	logrus.Debugf("Image list pushed to index:\n%s", imgListJSON)
9a7a1e5b
 	headers := map[string][]string{
a01cc3ca
 		"Content-type": {"application/json"},
 		// this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests
9a7a1e5b
 		"X-Docker-Token": {"true"},
752dd707
 	}
 	if validate {
9a7a1e5b
 		headers["X-Docker-Endpoints"] = regs
752dd707
 	}
 
 	// Redirect if necessary
9a7a1e5b
 	var res *http.Response
 	for {
 		if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil {
752dd707
 			return nil, err
 		}
9a7a1e5b
 		if !shouldRedirect(res) {
 			break
752dd707
 		}
9a7a1e5b
 		res.Body.Close()
 		u = res.Header.Get("Location")
6f4d8470
 		logrus.Debugf("Redirected to %s", u)
752dd707
 	}
9a7a1e5b
 	defer res.Body.Close()
752dd707
 
6b2eeaf8
 	if res.StatusCode == 401 {
dc2f5d0f
 		return nil, errcode.ErrorCodeUnauthorized.WithArgs()
6b2eeaf8
 	}
 
752dd707
 	var tokens, endpoints []string
 	if !validate {
 		if res.StatusCode != 200 && res.StatusCode != 201 {
 			errBody, err := ioutil.ReadAll(res.Body)
 			if err != nil {
6f4d8470
 				logrus.Debugf("Error reading response body: %s", err)
752dd707
 			}
ffded61d
 			return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
752dd707
 		}
8655214b
 		tokens = res.Header["X-Docker-Token"]
 		logrus.Debugf("Auth token: %v", tokens)
752dd707
 
8655214b
 		if res.Header.Get("X-Docker-Endpoints") == "" {
752dd707
 			return nil, fmt.Errorf("Index response didn't contain any endpoints")
 		}
8655214b
 		endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1))
 		if err != nil {
 			return nil, err
 		}
a01cc3ca
 	} else {
752dd707
 		if res.StatusCode != 204 {
 			errBody, err := ioutil.ReadAll(res.Body)
 			if err != nil {
6f4d8470
 				logrus.Debugf("Error reading response body: %s", err)
752dd707
 			}
ffded61d
 			return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote.RemoteName(), errBody), res)
752dd707
 		}
 	}
 
 	return &RepositoryData{
 		Endpoints: endpoints,
 	}, nil
 }
 
9a7a1e5b
 func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) {
a01cc3ca
 	req, err := http.NewRequest("PUT", u, bytes.NewReader(body))
9a7a1e5b
 	if err != nil {
 		return nil, err
 	}
 	req.ContentLength = int64(len(body))
 	for k, v := range headers {
 		req.Header[k] = v
 	}
a01cc3ca
 	response, err := r.client.Do(req)
9a7a1e5b
 	if err != nil {
 		return nil, err
 	}
 	return response, nil
 }
 
 func shouldRedirect(response *http.Response) bool {
 	return response.StatusCode >= 300 && response.StatusCode < 400
 }
 
4fcb9ac4
 // SearchRepositories performs a search against the remote repository
c4472b38
 func (r *Session) SearchRepositories(term string) (*registrytypes.SearchResults, error) {
6f4d8470
 	logrus.Debugf("Index server: %s", r.indexEndpoint)
7c88e8f1
 	u := r.indexEndpoint.VersionString(1) + "search?q=" + url.QueryEscape(term)
5a170484
 
 	req, err := http.NewRequest("GET", u, nil)
 	if err != nil {
 		return nil, fmt.Errorf("Error while getting from the server: %v", err)
 	}
 	// Have the AuthTransport send authentication, when logged in.
 	req.Header.Set("X-Docker-Token", "true")
 	res, err := r.client.Do(req)
752dd707
 	if err != nil {
 		return nil, err
 	}
 	defer res.Body.Close()
 	if res.StatusCode != 200 {
c30a55f1
 		return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res)
752dd707
 	}
c4472b38
 	result := new(registrytypes.SearchResults)
84453814
 	return result, json.NewDecoder(res.Body).Decode(result)
752dd707
 }
 
4fcb9ac4
 // GetAuthConfig returns the authentication settings for a session
a01cc3ca
 // TODO(tiborvass): remove this once registry client v2 is vendored
5b321e32
 func (r *Session) GetAuthConfig(withPasswd bool) *types.AuthConfig {
752dd707
 	password := ""
 	if withPasswd {
 		password = r.authConfig.Password
 	}
5b321e32
 	return &types.AuthConfig{
752dd707
 		Username: r.authConfig.Username,
 		Password: password,
 		Email:    r.authConfig.Email,
 	}
 }
9dc7d07f
 
 func isTimeout(err error) bool {
 	type timeout interface {
 		Timeout() bool
 	}
 	e := err
 	switch urlErr := err.(type) {
 	case *url.Error:
 		e = urlErr.Err
 	}
 	t, ok := e.(timeout)
 	return ok && t.Timeout()
 }