github.com/fntlnz/docker@v1.9.0-rc3/registry/session.go (about)

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