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