github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/registry/session.go (about)

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