github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/net/http/transport.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // HTTP client implementation. See RFC 7230 through 7235. 6 // 7 // This is the low-level Transport implementation of RoundTripper. 8 // The high-level interface is in client.go. 9 10 package http 11 12 import ( 13 "bufio" 14 "compress/gzip" 15 "container/list" 16 "context" 17 "crypto/tls" 18 "errors" 19 "fmt" 20 "io" 21 "log" 22 "net" 23 "net/http/httptrace" 24 "net/textproto" 25 "net/url" 26 "os" 27 "reflect" 28 "strings" 29 "sync" 30 "sync/atomic" 31 "time" 32 33 "golang.org/x/net/http/httpguts" 34 "golang.org/x/net/http/httpproxy" 35 ) 36 37 // DefaultTransport is the default implementation of Transport and is 38 // used by DefaultClient. It establishes network connections as needed 39 // and caches them for reuse by subsequent calls. It uses HTTP proxies 40 // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and 41 // $no_proxy) environment variables. 42 var DefaultTransport RoundTripper = &Transport{ 43 Proxy: ProxyFromEnvironment, 44 DialContext: (&net.Dialer{ 45 Timeout: 30 * time.Second, 46 KeepAlive: 30 * time.Second, 47 DualStack: true, 48 }).DialContext, 49 ForceAttemptHTTP2: true, 50 MaxIdleConns: 100, 51 IdleConnTimeout: 90 * time.Second, 52 TLSHandshakeTimeout: 10 * time.Second, 53 ExpectContinueTimeout: 1 * time.Second, 54 } 55 56 // DefaultMaxIdleConnsPerHost is the default value of Transport's 57 // MaxIdleConnsPerHost. 58 const DefaultMaxIdleConnsPerHost = 2 59 60 // Transport is an implementation of RoundTripper that supports HTTP, 61 // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT). 62 // 63 // By default, Transport caches connections for future re-use. 64 // This may leave many open connections when accessing many hosts. 65 // This behavior can be managed using Transport's CloseIdleConnections method 66 // and the MaxIdleConnsPerHost and DisableKeepAlives fields. 67 // 68 // Transports should be reused instead of created as needed. 69 // Transports are safe for concurrent use by multiple goroutines. 70 // 71 // A Transport is a low-level primitive for making HTTP and HTTPS requests. 72 // For high-level functionality, such as cookies and redirects, see Client. 73 // 74 // Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 75 // for HTTPS URLs, depending on whether the server supports HTTP/2, 76 // and how the Transport is configured. The DefaultTransport supports HTTP/2. 77 // To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 78 // and call ConfigureTransport. See the package docs for more about HTTP/2. 79 // 80 // Responses with status codes in the 1xx range are either handled 81 // automatically (100 expect-continue) or ignored. The one 82 // exception is HTTP status code 101 (Switching Protocols), which is 83 // considered a terminal status and returned by RoundTrip. To see the 84 // ignored 1xx responses, use the httptrace trace package's 85 // ClientTrace.Got1xxResponse. 86 // 87 // Transport only retries a request upon encountering a network error 88 // if the request is idempotent and either has no body or has its 89 // Request.GetBody defined. HTTP requests are considered idempotent if 90 // they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their 91 // Header map contains an "Idempotency-Key" or "X-Idempotency-Key" 92 // entry. If the idempotency key value is a zero-length slice, the 93 // request is treated as idempotent but the header is not sent on the 94 // wire. 95 type Transport struct { 96 idleMu sync.Mutex 97 closeIdle bool // user has requested to close all idle conns 98 idleConn map[connectMethodKey][]*persistConn // most recently used at end 99 idleConnWait map[connectMethodKey]wantConnQueue // waiting getConns 100 idleLRU connLRU 101 102 reqMu sync.Mutex 103 reqCanceler map[*Request]func(error) 104 105 altMu sync.Mutex // guards changing altProto only 106 altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme 107 108 connsPerHostMu sync.Mutex 109 connsPerHost map[connectMethodKey]int 110 connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns 111 112 // Proxy specifies a function to return a proxy for a given 113 // Request. If the function returns a non-nil error, the 114 // request is aborted with the provided error. 115 // 116 // The proxy type is determined by the URL scheme. "http", 117 // "https", and "socks5" are supported. If the scheme is empty, 118 // "http" is assumed. 119 // 120 // If Proxy is nil or returns a nil *URL, no proxy is used. 121 Proxy func(*Request) (*url.URL, error) 122 123 // DialContext specifies the dial function for creating unencrypted TCP connections. 124 // If DialContext is nil (and the deprecated Dial below is also nil), 125 // then the transport dials using package net. 126 // 127 // DialContext runs concurrently with calls to RoundTrip. 128 // A RoundTrip call that initiates a dial may end up using 129 // a connection dialed previously when the earlier connection 130 // becomes idle before the later DialContext completes. 131 DialContext func(ctx context.Context, network, addr string) (net.Conn, error) 132 133 // Dial specifies the dial function for creating unencrypted TCP connections. 134 // 135 // Dial runs concurrently with calls to RoundTrip. 136 // A RoundTrip call that initiates a dial may end up using 137 // a connection dialed previously when the earlier connection 138 // becomes idle before the later Dial completes. 139 // 140 // Deprecated: Use DialContext instead, which allows the transport 141 // to cancel dials as soon as they are no longer needed. 142 // If both are set, DialContext takes priority. 143 Dial func(network, addr string) (net.Conn, error) 144 145 // DialTLSContext specifies an optional dial function for creating 146 // TLS connections for non-proxied HTTPS requests. 147 // 148 // If DialTLSContext is nil (and the deprecated DialTLS below is also nil), 149 // DialContext and TLSClientConfig are used. 150 // 151 // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS 152 // requests and the TLSClientConfig and TLSHandshakeTimeout 153 // are ignored. The returned net.Conn is assumed to already be 154 // past the TLS handshake. 155 DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) 156 157 // DialTLS specifies an optional dial function for creating 158 // TLS connections for non-proxied HTTPS requests. 159 // 160 // Deprecated: Use DialTLSContext instead, which allows the transport 161 // to cancel dials as soon as they are no longer needed. 162 // If both are set, DialTLSContext takes priority. 163 DialTLS func(network, addr string) (net.Conn, error) 164 165 // TLSClientConfig specifies the TLS configuration to use with 166 // tls.Client. 167 // If nil, the default configuration is used. 168 // If non-nil, HTTP/2 support may not be enabled by default. 169 TLSClientConfig *tls.Config 170 171 // TLSHandshakeTimeout specifies the maximum amount of time waiting to 172 // wait for a TLS handshake. Zero means no timeout. 173 TLSHandshakeTimeout time.Duration 174 175 // DisableKeepAlives, if true, disables HTTP keep-alives and 176 // will only use the connection to the server for a single 177 // HTTP request. 178 // 179 // This is unrelated to the similarly named TCP keep-alives. 180 DisableKeepAlives bool 181 182 // DisableCompression, if true, prevents the Transport from 183 // requesting compression with an "Accept-Encoding: gzip" 184 // request header when the Request contains no existing 185 // Accept-Encoding value. If the Transport requests gzip on 186 // its own and gets a gzipped response, it's transparently 187 // decoded in the Response.Body. However, if the user 188 // explicitly requested gzip it is not automatically 189 // uncompressed. 190 DisableCompression bool 191 192 // MaxIdleConns controls the maximum number of idle (keep-alive) 193 // connections across all hosts. Zero means no limit. 194 MaxIdleConns int 195 196 // MaxIdleConnsPerHost, if non-zero, controls the maximum idle 197 // (keep-alive) connections to keep per-host. If zero, 198 // DefaultMaxIdleConnsPerHost is used. 199 MaxIdleConnsPerHost int 200 201 // MaxConnsPerHost optionally limits the total number of 202 // connections per host, including connections in the dialing, 203 // active, and idle states. On limit violation, dials will block. 204 // 205 // Zero means no limit. 206 MaxConnsPerHost int 207 208 // IdleConnTimeout is the maximum amount of time an idle 209 // (keep-alive) connection will remain idle before closing 210 // itself. 211 // Zero means no limit. 212 IdleConnTimeout time.Duration 213 214 // ResponseHeaderTimeout, if non-zero, specifies the amount of 215 // time to wait for a server's response headers after fully 216 // writing the request (including its body, if any). This 217 // time does not include the time to read the response body. 218 ResponseHeaderTimeout time.Duration 219 220 // ExpectContinueTimeout, if non-zero, specifies the amount of 221 // time to wait for a server's first response headers after fully 222 // writing the request headers if the request has an 223 // "Expect: 100-continue" header. Zero means no timeout and 224 // causes the body to be sent immediately, without 225 // waiting for the server to approve. 226 // This time does not include the time to send the request header. 227 ExpectContinueTimeout time.Duration 228 229 // TLSNextProto specifies how the Transport switches to an 230 // alternate protocol (such as HTTP/2) after a TLS ALPN 231 // protocol negotiation. If Transport dials an TLS connection 232 // with a non-empty protocol name and TLSNextProto contains a 233 // map entry for that key (such as "h2"), then the func is 234 // called with the request's authority (such as "example.com" 235 // or "example.com:1234") and the TLS connection. The function 236 // must return a RoundTripper that then handles the request. 237 // If TLSNextProto is not nil, HTTP/2 support is not enabled 238 // automatically. 239 TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper 240 241 // ProxyConnectHeader optionally specifies headers to send to 242 // proxies during CONNECT requests. 243 ProxyConnectHeader Header 244 245 // MaxResponseHeaderBytes specifies a limit on how many 246 // response bytes are allowed in the server's response 247 // header. 248 // 249 // Zero means to use a default limit. 250 MaxResponseHeaderBytes int64 251 252 // WriteBufferSize specifies the size of the write buffer used 253 // when writing to the transport. 254 // If zero, a default (currently 4KB) is used. 255 WriteBufferSize int 256 257 // ReadBufferSize specifies the size of the read buffer used 258 // when reading from the transport. 259 // If zero, a default (currently 4KB) is used. 260 ReadBufferSize int 261 262 // nextProtoOnce guards initialization of TLSNextProto and 263 // h2transport (via onceSetNextProtoDefaults) 264 nextProtoOnce sync.Once 265 h2transport h2Transport // non-nil if http2 wired up 266 tlsNextProtoWasNil bool // whether TLSNextProto was nil when the Once fired 267 268 // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero 269 // Dial, DialTLS, or DialContext func or TLSClientConfig is provided. 270 // By default, use of any those fields conservatively disables HTTP/2. 271 // To use a custom dialer or TLS config and still attempt HTTP/2 272 // upgrades, set this to true. 273 ForceAttemptHTTP2 bool 274 } 275 276 func (t *Transport) writeBufferSize() int { 277 if t.WriteBufferSize > 0 { 278 return t.WriteBufferSize 279 } 280 return 4 << 10 281 } 282 283 func (t *Transport) readBufferSize() int { 284 if t.ReadBufferSize > 0 { 285 return t.ReadBufferSize 286 } 287 return 4 << 10 288 } 289 290 // Clone returns a deep copy of t's exported fields. 291 func (t *Transport) Clone() *Transport { 292 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults) 293 t2 := &Transport{ 294 Proxy: t.Proxy, 295 DialContext: t.DialContext, 296 Dial: t.Dial, 297 DialTLS: t.DialTLS, 298 DialTLSContext: t.DialTLSContext, 299 TLSHandshakeTimeout: t.TLSHandshakeTimeout, 300 DisableKeepAlives: t.DisableKeepAlives, 301 DisableCompression: t.DisableCompression, 302 MaxIdleConns: t.MaxIdleConns, 303 MaxIdleConnsPerHost: t.MaxIdleConnsPerHost, 304 MaxConnsPerHost: t.MaxConnsPerHost, 305 IdleConnTimeout: t.IdleConnTimeout, 306 ResponseHeaderTimeout: t.ResponseHeaderTimeout, 307 ExpectContinueTimeout: t.ExpectContinueTimeout, 308 ProxyConnectHeader: t.ProxyConnectHeader.Clone(), 309 MaxResponseHeaderBytes: t.MaxResponseHeaderBytes, 310 ForceAttemptHTTP2: t.ForceAttemptHTTP2, 311 WriteBufferSize: t.WriteBufferSize, 312 ReadBufferSize: t.ReadBufferSize, 313 } 314 if t.TLSClientConfig != nil { 315 t2.TLSClientConfig = t.TLSClientConfig.Clone() 316 } 317 if !t.tlsNextProtoWasNil { 318 npm := map[string]func(authority string, c *tls.Conn) RoundTripper{} 319 for k, v := range t.TLSNextProto { 320 npm[k] = v 321 } 322 t2.TLSNextProto = npm 323 } 324 return t2 325 } 326 327 // h2Transport is the interface we expect to be able to call from 328 // net/http against an *http2.Transport that's either bundled into 329 // h2_bundle.go or supplied by the user via x/net/http2. 330 // 331 // We name it with the "h2" prefix to stay out of the "http2" prefix 332 // namespace used by x/tools/cmd/bundle for h2_bundle.go. 333 type h2Transport interface { 334 CloseIdleConnections() 335 } 336 337 func (t *Transport) hasCustomTLSDialer() bool { 338 return t.DialTLS != nil || t.DialTLSContext != nil 339 } 340 341 // onceSetNextProtoDefaults initializes TLSNextProto. 342 // It must be called via t.nextProtoOnce.Do. 343 func (t *Transport) onceSetNextProtoDefaults() { 344 t.tlsNextProtoWasNil = (t.TLSNextProto == nil) 345 if strings.Contains(os.Getenv("GODEBUG"), "http2client=0") { 346 return 347 } 348 349 // If they've already configured http2 with 350 // golang.org/x/net/http2 instead of the bundled copy, try to 351 // get at its http2.Transport value (via the "https" 352 // altproto map) so we can call CloseIdleConnections on it if 353 // requested. (Issue 22891) 354 altProto, _ := t.altProto.Load().(map[string]RoundTripper) 355 if rv := reflect.ValueOf(altProto["https"]); rv.IsValid() && rv.Type().Kind() == reflect.Struct && rv.Type().NumField() == 1 { 356 if v := rv.Field(0); v.CanInterface() { 357 if h2i, ok := v.Interface().(h2Transport); ok { 358 t.h2transport = h2i 359 return 360 } 361 } 362 } 363 364 if t.TLSNextProto != nil { 365 // This is the documented way to disable http2 on a 366 // Transport. 367 return 368 } 369 if !t.ForceAttemptHTTP2 && (t.TLSClientConfig != nil || t.Dial != nil || t.DialContext != nil || t.hasCustomTLSDialer()) { 370 // Be conservative and don't automatically enable 371 // http2 if they've specified a custom TLS config or 372 // custom dialers. Let them opt-in themselves via 373 // http2.ConfigureTransport so we don't surprise them 374 // by modifying their tls.Config. Issue 14275. 375 // However, if ForceAttemptHTTP2 is true, it overrides the above checks. 376 return 377 } 378 if omitBundledHTTP2 { 379 return 380 } 381 t2, err := http2configureTransport(t) 382 if err != nil { 383 log.Printf("Error enabling Transport HTTP/2 support: %v", err) 384 return 385 } 386 t.h2transport = t2 387 388 // Auto-configure the http2.Transport's MaxHeaderListSize from 389 // the http.Transport's MaxResponseHeaderBytes. They don't 390 // exactly mean the same thing, but they're close. 391 // 392 // TODO: also add this to x/net/http2.Configure Transport, behind 393 // a +build go1.7 build tag: 394 if limit1 := t.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 { 395 const h2max = 1<<32 - 1 396 if limit1 >= h2max { 397 t2.MaxHeaderListSize = h2max 398 } else { 399 t2.MaxHeaderListSize = uint32(limit1) 400 } 401 } 402 } 403 404 // ProxyFromEnvironment returns the URL of the proxy to use for a 405 // given request, as indicated by the environment variables 406 // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions 407 // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https 408 // requests. 409 // 410 // The environment values may be either a complete URL or a 411 // "host[:port]", in which case the "http" scheme is assumed. 412 // An error is returned if the value is a different form. 413 // 414 // A nil URL and nil error are returned if no proxy is defined in the 415 // environment, or a proxy should not be used for the given request, 416 // as defined by NO_PROXY. 417 // 418 // As a special case, if req.URL.Host is "localhost" (with or without 419 // a port number), then a nil URL and nil error will be returned. 420 func ProxyFromEnvironment(req *Request) (*url.URL, error) { 421 return envProxyFunc()(req.URL) 422 } 423 424 // ProxyURL returns a proxy function (for use in a Transport) 425 // that always returns the same URL. 426 func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { 427 return func(*Request) (*url.URL, error) { 428 return fixedURL, nil 429 } 430 } 431 432 // transportRequest is a wrapper around a *Request that adds 433 // optional extra headers to write and stores any error to return 434 // from roundTrip. 435 type transportRequest struct { 436 *Request // original request, not to be mutated 437 extra Header // extra headers to write, or nil 438 trace *httptrace.ClientTrace // optional 439 440 mu sync.Mutex // guards err 441 err error // first setError value for mapRoundTripError to consider 442 } 443 444 func (tr *transportRequest) extraHeaders() Header { 445 if tr.extra == nil { 446 tr.extra = make(Header) 447 } 448 return tr.extra 449 } 450 451 func (tr *transportRequest) setError(err error) { 452 tr.mu.Lock() 453 if tr.err == nil { 454 tr.err = err 455 } 456 tr.mu.Unlock() 457 } 458 459 // useRegisteredProtocol reports whether an alternate protocol (as registered 460 // with Transport.RegisterProtocol) should be respected for this request. 461 func (t *Transport) useRegisteredProtocol(req *Request) bool { 462 if req.URL.Scheme == "https" && req.requiresHTTP1() { 463 // If this request requires HTTP/1, don't use the 464 // "https" alternate protocol, which is used by the 465 // HTTP/2 code to take over requests if there's an 466 // existing cached HTTP/2 connection. 467 return false 468 } 469 return true 470 } 471 472 // roundTrip implements a RoundTripper over HTTP. 473 func (t *Transport) roundTrip(req *Request) (*Response, error) { 474 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults) 475 ctx := req.Context() 476 trace := httptrace.ContextClientTrace(ctx) 477 478 if req.URL == nil { 479 req.closeBody() 480 return nil, errors.New("http: nil Request.URL") 481 } 482 if req.Header == nil { 483 req.closeBody() 484 return nil, errors.New("http: nil Request.Header") 485 } 486 scheme := req.URL.Scheme 487 isHTTP := scheme == "http" || scheme == "https" 488 if isHTTP { 489 for k, vv := range req.Header { 490 if !httpguts.ValidHeaderFieldName(k) { 491 req.closeBody() 492 return nil, fmt.Errorf("net/http: invalid header field name %q", k) 493 } 494 for _, v := range vv { 495 if !httpguts.ValidHeaderFieldValue(v) { 496 req.closeBody() 497 return nil, fmt.Errorf("net/http: invalid header field value %q for key %v", v, k) 498 } 499 } 500 } 501 } 502 503 if t.useRegisteredProtocol(req) { 504 altProto, _ := t.altProto.Load().(map[string]RoundTripper) 505 if altRT := altProto[scheme]; altRT != nil { 506 if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol { 507 return resp, err 508 } 509 } 510 } 511 if !isHTTP { 512 req.closeBody() 513 return nil, &badStringError{"unsupported protocol scheme", scheme} 514 } 515 if req.Method != "" && !validMethod(req.Method) { 516 req.closeBody() 517 return nil, fmt.Errorf("net/http: invalid method %q", req.Method) 518 } 519 if req.URL.Host == "" { 520 req.closeBody() 521 return nil, errors.New("http: no Host in request URL") 522 } 523 524 for { 525 select { 526 case <-ctx.Done(): 527 req.closeBody() 528 return nil, ctx.Err() 529 default: 530 } 531 532 // treq gets modified by roundTrip, so we need to recreate for each retry. 533 treq := &transportRequest{Request: req, trace: trace} 534 cm, err := t.connectMethodForRequest(treq) 535 if err != nil { 536 req.closeBody() 537 return nil, err 538 } 539 540 // Get the cached or newly-created connection to either the 541 // host (for http or https), the http proxy, or the http proxy 542 // pre-CONNECTed to https server. In any case, we'll be ready 543 // to send it requests. 544 pconn, err := t.getConn(treq, cm) 545 if err != nil { 546 t.setReqCanceler(req, nil) 547 req.closeBody() 548 return nil, err 549 } 550 551 var resp *Response 552 if pconn.alt != nil { 553 // HTTP/2 path. 554 t.setReqCanceler(req, nil) // not cancelable with CancelRequest 555 resp, err = pconn.alt.RoundTrip(req) 556 } else { 557 resp, err = pconn.roundTrip(treq) 558 } 559 if err == nil { 560 return resp, nil 561 } 562 563 // Failed. Clean up and determine whether to retry. 564 565 _, isH2DialError := pconn.alt.(http2erringRoundTripper) 566 if http2isNoCachedConnError(err) || isH2DialError { 567 if t.removeIdleConn(pconn) { 568 t.decConnsPerHost(pconn.cacheKey) 569 } 570 } 571 if !pconn.shouldRetryRequest(req, err) { 572 // Issue 16465: return underlying net.Conn.Read error from peek, 573 // as we've historically done. 574 if e, ok := err.(transportReadFromServerError); ok { 575 err = e.err 576 } 577 return nil, err 578 } 579 testHookRoundTripRetried() 580 581 // Rewind the body if we're able to. 582 if req.GetBody != nil { 583 newReq := *req 584 var err error 585 newReq.Body, err = req.GetBody() 586 if err != nil { 587 return nil, err 588 } 589 req = &newReq 590 } 591 } 592 } 593 594 // shouldRetryRequest reports whether we should retry sending a failed 595 // HTTP request on a new connection. The non-nil input error is the 596 // error from roundTrip. 597 func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool { 598 if http2isNoCachedConnError(err) { 599 // Issue 16582: if the user started a bunch of 600 // requests at once, they can all pick the same conn 601 // and violate the server's max concurrent streams. 602 // Instead, match the HTTP/1 behavior for now and dial 603 // again to get a new TCP connection, rather than failing 604 // this request. 605 return true 606 } 607 if err == errMissingHost { 608 // User error. 609 return false 610 } 611 if !pc.isReused() { 612 // This was a fresh connection. There's no reason the server 613 // should've hung up on us. 614 // 615 // Also, if we retried now, we could loop forever 616 // creating new connections and retrying if the server 617 // is just hanging up on us because it doesn't like 618 // our request (as opposed to sending an error). 619 return false 620 } 621 if _, ok := err.(nothingWrittenError); ok { 622 // We never wrote anything, so it's safe to retry, if there's no body or we 623 // can "rewind" the body with GetBody. 624 return req.outgoingLength() == 0 || req.GetBody != nil 625 } 626 if !req.isReplayable() { 627 // Don't retry non-idempotent requests. 628 return false 629 } 630 if _, ok := err.(transportReadFromServerError); ok { 631 // We got some non-EOF net.Conn.Read failure reading 632 // the 1st response byte from the server. 633 return true 634 } 635 if err == errServerClosedIdle { 636 // The server replied with io.EOF while we were trying to 637 // read the response. Probably an unfortunately keep-alive 638 // timeout, just as the client was writing a request. 639 return true 640 } 641 return false // conservatively 642 } 643 644 // ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol. 645 var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol") 646 647 // RegisterProtocol registers a new protocol with scheme. 648 // The Transport will pass requests using the given scheme to rt. 649 // It is rt's responsibility to simulate HTTP request semantics. 650 // 651 // RegisterProtocol can be used by other packages to provide 652 // implementations of protocol schemes like "ftp" or "file". 653 // 654 // If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will 655 // handle the RoundTrip itself for that one request, as if the 656 // protocol were not registered. 657 func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { 658 t.altMu.Lock() 659 defer t.altMu.Unlock() 660 oldMap, _ := t.altProto.Load().(map[string]RoundTripper) 661 if _, exists := oldMap[scheme]; exists { 662 panic("protocol " + scheme + " already registered") 663 } 664 newMap := make(map[string]RoundTripper) 665 for k, v := range oldMap { 666 newMap[k] = v 667 } 668 newMap[scheme] = rt 669 t.altProto.Store(newMap) 670 } 671 672 // CloseIdleConnections closes any connections which were previously 673 // connected from previous requests but are now sitting idle in 674 // a "keep-alive" state. It does not interrupt any connections currently 675 // in use. 676 func (t *Transport) CloseIdleConnections() { 677 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults) 678 t.idleMu.Lock() 679 m := t.idleConn 680 t.idleConn = nil 681 t.closeIdle = true // close newly idle connections 682 t.idleLRU = connLRU{} 683 t.idleMu.Unlock() 684 for _, conns := range m { 685 for _, pconn := range conns { 686 pconn.close(errCloseIdleConns) 687 } 688 } 689 if t2 := t.h2transport; t2 != nil { 690 t2.CloseIdleConnections() 691 } 692 } 693 694 // CancelRequest cancels an in-flight request by closing its connection. 695 // CancelRequest should only be called after RoundTrip has returned. 696 // 697 // Deprecated: Use Request.WithContext to create a request with a 698 // cancelable context instead. CancelRequest cannot cancel HTTP/2 699 // requests. 700 func (t *Transport) CancelRequest(req *Request) { 701 t.cancelRequest(req, errRequestCanceled) 702 } 703 704 // Cancel an in-flight request, recording the error value. 705 func (t *Transport) cancelRequest(req *Request, err error) { 706 t.reqMu.Lock() 707 cancel := t.reqCanceler[req] 708 delete(t.reqCanceler, req) 709 t.reqMu.Unlock() 710 if cancel != nil { 711 cancel(err) 712 } 713 } 714 715 // 716 // Private implementation past this point. 717 // 718 719 var ( 720 // proxyConfigOnce guards proxyConfig 721 envProxyOnce sync.Once 722 envProxyFuncValue func(*url.URL) (*url.URL, error) 723 ) 724 725 // defaultProxyConfig returns a ProxyConfig value looked up 726 // from the environment. This mitigates expensive lookups 727 // on some platforms (e.g. Windows). 728 func envProxyFunc() func(*url.URL) (*url.URL, error) { 729 envProxyOnce.Do(func() { 730 envProxyFuncValue = httpproxy.FromEnvironment().ProxyFunc() 731 }) 732 return envProxyFuncValue 733 } 734 735 // resetProxyConfig is used by tests. 736 func resetProxyConfig() { 737 envProxyOnce = sync.Once{} 738 envProxyFuncValue = nil 739 } 740 741 func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) { 742 cm.targetScheme = treq.URL.Scheme 743 cm.targetAddr = canonicalAddr(treq.URL) 744 if t.Proxy != nil { 745 cm.proxyURL, err = t.Proxy(treq.Request) 746 } 747 cm.onlyH1 = treq.requiresHTTP1() 748 return cm, err 749 } 750 751 // proxyAuth returns the Proxy-Authorization header to set 752 // on requests, if applicable. 753 func (cm *connectMethod) proxyAuth() string { 754 if cm.proxyURL == nil { 755 return "" 756 } 757 if u := cm.proxyURL.User; u != nil { 758 username := u.Username() 759 password, _ := u.Password() 760 return "Basic " + basicAuth(username, password) 761 } 762 return "" 763 } 764 765 // error values for debugging and testing, not seen by users. 766 var ( 767 errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled") 768 errConnBroken = errors.New("http: putIdleConn: connection is in bad state") 769 errCloseIdle = errors.New("http: putIdleConn: CloseIdleConnections was called") 770 errTooManyIdle = errors.New("http: putIdleConn: too many idle connections") 771 errTooManyIdleHost = errors.New("http: putIdleConn: too many idle connections for host") 772 errCloseIdleConns = errors.New("http: CloseIdleConnections called") 773 errReadLoopExiting = errors.New("http: persistConn.readLoop exiting") 774 errIdleConnTimeout = errors.New("http: idle connection timeout") 775 776 // errServerClosedIdle is not seen by users for idempotent requests, but may be 777 // seen by a user if the server shuts down an idle connection and sends its FIN 778 // in flight with already-written POST body bytes from the client. 779 // See https://github.com/golang/go/issues/19943#issuecomment-355607646 780 errServerClosedIdle = errors.New("http: server closed idle connection") 781 ) 782 783 // transportReadFromServerError is used by Transport.readLoop when the 784 // 1 byte peek read fails and we're actually anticipating a response. 785 // Usually this is just due to the inherent keep-alive shut down race, 786 // where the server closed the connection at the same time the client 787 // wrote. The underlying err field is usually io.EOF or some 788 // ECONNRESET sort of thing which varies by platform. But it might be 789 // the user's custom net.Conn.Read error too, so we carry it along for 790 // them to return from Transport.RoundTrip. 791 type transportReadFromServerError struct { 792 err error 793 } 794 795 func (e transportReadFromServerError) Unwrap() error { return e.err } 796 797 func (e transportReadFromServerError) Error() string { 798 return fmt.Sprintf("net/http: Transport failed to read from server: %v", e.err) 799 } 800 801 func (t *Transport) putOrCloseIdleConn(pconn *persistConn) { 802 if err := t.tryPutIdleConn(pconn); err != nil { 803 pconn.close(err) 804 } 805 } 806 807 func (t *Transport) maxIdleConnsPerHost() int { 808 if v := t.MaxIdleConnsPerHost; v != 0 { 809 return v 810 } 811 return DefaultMaxIdleConnsPerHost 812 } 813 814 // tryPutIdleConn adds pconn to the list of idle persistent connections awaiting 815 // a new request. 816 // If pconn is no longer needed or not in a good state, tryPutIdleConn returns 817 // an error explaining why it wasn't registered. 818 // tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that. 819 func (t *Transport) tryPutIdleConn(pconn *persistConn) error { 820 if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { 821 return errKeepAlivesDisabled 822 } 823 if pconn.isBroken() { 824 return errConnBroken 825 } 826 pconn.markReused() 827 828 t.idleMu.Lock() 829 defer t.idleMu.Unlock() 830 831 // HTTP/2 (pconn.alt != nil) connections do not come out of the idle list, 832 // because multiple goroutines can use them simultaneously. 833 // If this is an HTTP/2 connection being “returned,” we're done. 834 if pconn.alt != nil && t.idleLRU.m[pconn] != nil { 835 return nil 836 } 837 838 // Deliver pconn to goroutine waiting for idle connection, if any. 839 // (They may be actively dialing, but this conn is ready first. 840 // Chrome calls this socket late binding. 841 // See https://insouciant.org/tech/connection-management-in-chromium/.) 842 key := pconn.cacheKey 843 if q, ok := t.idleConnWait[key]; ok { 844 done := false 845 if pconn.alt == nil { 846 // HTTP/1. 847 // Loop over the waiting list until we find a w that isn't done already, and hand it pconn. 848 for q.len() > 0 { 849 w := q.popFront() 850 if w.tryDeliver(pconn, nil) { 851 done = true 852 break 853 } 854 } 855 } else { 856 // HTTP/2. 857 // Can hand the same pconn to everyone in the waiting list, 858 // and we still won't be done: we want to put it in the idle 859 // list unconditionally, for any future clients too. 860 for q.len() > 0 { 861 w := q.popFront() 862 w.tryDeliver(pconn, nil) 863 } 864 } 865 if q.len() == 0 { 866 delete(t.idleConnWait, key) 867 } else { 868 t.idleConnWait[key] = q 869 } 870 if done { 871 return nil 872 } 873 } 874 875 if t.closeIdle { 876 return errCloseIdle 877 } 878 if t.idleConn == nil { 879 t.idleConn = make(map[connectMethodKey][]*persistConn) 880 } 881 idles := t.idleConn[key] 882 if len(idles) >= t.maxIdleConnsPerHost() { 883 return errTooManyIdleHost 884 } 885 for _, exist := range idles { 886 if exist == pconn { 887 log.Fatalf("dup idle pconn %p in freelist", pconn) 888 } 889 } 890 t.idleConn[key] = append(idles, pconn) 891 t.idleLRU.add(pconn) 892 if t.MaxIdleConns != 0 && t.idleLRU.len() > t.MaxIdleConns { 893 oldest := t.idleLRU.removeOldest() 894 oldest.close(errTooManyIdle) 895 t.removeIdleConnLocked(oldest) 896 } 897 898 // Set idle timer, but only for HTTP/1 (pconn.alt == nil). 899 // The HTTP/2 implementation manages the idle timer itself 900 // (see idleConnTimeout in h2_bundle.go). 901 if t.IdleConnTimeout > 0 && pconn.alt == nil { 902 if pconn.idleTimer != nil { 903 pconn.idleTimer.Reset(t.IdleConnTimeout) 904 } else { 905 pconn.idleTimer = time.AfterFunc(t.IdleConnTimeout, pconn.closeConnIfStillIdle) 906 } 907 } 908 pconn.idleAt = time.Now() 909 return nil 910 } 911 912 // queueForIdleConn queues w to receive the next idle connection for w.cm. 913 // As an optimization hint to the caller, queueForIdleConn reports whether 914 // it successfully delivered an already-idle connection. 915 func (t *Transport) queueForIdleConn(w *wantConn) (delivered bool) { 916 if t.DisableKeepAlives { 917 return false 918 } 919 920 t.idleMu.Lock() 921 defer t.idleMu.Unlock() 922 923 // Stop closing connections that become idle - we might want one. 924 // (That is, undo the effect of t.CloseIdleConnections.) 925 t.closeIdle = false 926 927 if w == nil { 928 // Happens in test hook. 929 return false 930 } 931 932 // If IdleConnTimeout is set, calculate the oldest 933 // persistConn.idleAt time we're willing to use a cached idle 934 // conn. 935 var oldTime time.Time 936 if t.IdleConnTimeout > 0 { 937 oldTime = time.Now().Add(-t.IdleConnTimeout) 938 } 939 940 // Look for most recently-used idle connection. 941 if list, ok := t.idleConn[w.key]; ok { 942 stop := false 943 delivered := false 944 for len(list) > 0 && !stop { 945 pconn := list[len(list)-1] 946 947 // See whether this connection has been idle too long, considering 948 // only the wall time (the Round(0)), in case this is a laptop or VM 949 // coming out of suspend with previously cached idle connections. 950 tooOld := !oldTime.IsZero() && pconn.idleAt.Round(0).Before(oldTime) 951 if tooOld { 952 // Async cleanup. Launch in its own goroutine (as if a 953 // time.AfterFunc called it); it acquires idleMu, which we're 954 // holding, and does a synchronous net.Conn.Close. 955 go pconn.closeConnIfStillIdle() 956 } 957 if pconn.isBroken() || tooOld { 958 // If either persistConn.readLoop has marked the connection 959 // broken, but Transport.removeIdleConn has not yet removed it 960 // from the idle list, or if this persistConn is too old (it was 961 // idle too long), then ignore it and look for another. In both 962 // cases it's already in the process of being closed. 963 list = list[:len(list)-1] 964 continue 965 } 966 delivered = w.tryDeliver(pconn, nil) 967 if delivered { 968 if pconn.alt != nil { 969 // HTTP/2: multiple clients can share pconn. 970 // Leave it in the list. 971 } else { 972 // HTTP/1: only one client can use pconn. 973 // Remove it from the list. 974 t.idleLRU.remove(pconn) 975 list = list[:len(list)-1] 976 } 977 } 978 stop = true 979 } 980 if len(list) > 0 { 981 t.idleConn[w.key] = list 982 } else { 983 delete(t.idleConn, w.key) 984 } 985 if stop { 986 return delivered 987 } 988 } 989 990 // Register to receive next connection that becomes idle. 991 if t.idleConnWait == nil { 992 t.idleConnWait = make(map[connectMethodKey]wantConnQueue) 993 } 994 q := t.idleConnWait[w.key] 995 q.cleanFront() 996 q.pushBack(w) 997 t.idleConnWait[w.key] = q 998 return false 999 } 1000 1001 // removeIdleConn marks pconn as dead. 1002 func (t *Transport) removeIdleConn(pconn *persistConn) bool { 1003 t.idleMu.Lock() 1004 defer t.idleMu.Unlock() 1005 return t.removeIdleConnLocked(pconn) 1006 } 1007 1008 // t.idleMu must be held. 1009 func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool { 1010 if pconn.idleTimer != nil { 1011 pconn.idleTimer.Stop() 1012 } 1013 t.idleLRU.remove(pconn) 1014 key := pconn.cacheKey 1015 pconns := t.idleConn[key] 1016 var removed bool 1017 switch len(pconns) { 1018 case 0: 1019 // Nothing 1020 case 1: 1021 if pconns[0] == pconn { 1022 delete(t.idleConn, key) 1023 removed = true 1024 } 1025 default: 1026 for i, v := range pconns { 1027 if v != pconn { 1028 continue 1029 } 1030 // Slide down, keeping most recently-used 1031 // conns at the end. 1032 copy(pconns[i:], pconns[i+1:]) 1033 t.idleConn[key] = pconns[:len(pconns)-1] 1034 removed = true 1035 break 1036 } 1037 } 1038 return removed 1039 } 1040 1041 func (t *Transport) setReqCanceler(r *Request, fn func(error)) { 1042 t.reqMu.Lock() 1043 defer t.reqMu.Unlock() 1044 if t.reqCanceler == nil { 1045 t.reqCanceler = make(map[*Request]func(error)) 1046 } 1047 if fn != nil { 1048 t.reqCanceler[r] = fn 1049 } else { 1050 delete(t.reqCanceler, r) 1051 } 1052 } 1053 1054 // replaceReqCanceler replaces an existing cancel function. If there is no cancel function 1055 // for the request, we don't set the function and return false. 1056 // Since CancelRequest will clear the canceler, we can use the return value to detect if 1057 // the request was canceled since the last setReqCancel call. 1058 func (t *Transport) replaceReqCanceler(r *Request, fn func(error)) bool { 1059 t.reqMu.Lock() 1060 defer t.reqMu.Unlock() 1061 _, ok := t.reqCanceler[r] 1062 if !ok { 1063 return false 1064 } 1065 if fn != nil { 1066 t.reqCanceler[r] = fn 1067 } else { 1068 delete(t.reqCanceler, r) 1069 } 1070 return true 1071 } 1072 1073 var zeroDialer net.Dialer 1074 1075 func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error) { 1076 if t.DialContext != nil { 1077 return t.DialContext(ctx, network, addr) 1078 } 1079 if t.Dial != nil { 1080 c, err := t.Dial(network, addr) 1081 if c == nil && err == nil { 1082 err = errors.New("net/http: Transport.Dial hook returned (nil, nil)") 1083 } 1084 return c, err 1085 } 1086 return zeroDialer.DialContext(ctx, network, addr) 1087 } 1088 1089 // A wantConn records state about a wanted connection 1090 // (that is, an active call to getConn). 1091 // The conn may be gotten by dialing or by finding an idle connection, 1092 // or a cancellation may make the conn no longer wanted. 1093 // These three options are racing against each other and use 1094 // wantConn to coordinate and agree about the winning outcome. 1095 type wantConn struct { 1096 cm connectMethod 1097 key connectMethodKey // cm.key() 1098 ctx context.Context // context for dial 1099 ready chan struct{} // closed when pc, err pair is delivered 1100 1101 // hooks for testing to know when dials are done 1102 // beforeDial is called in the getConn goroutine when the dial is queued. 1103 // afterDial is called when the dial is completed or cancelled. 1104 beforeDial func() 1105 afterDial func() 1106 1107 mu sync.Mutex // protects pc, err, close(ready) 1108 pc *persistConn 1109 err error 1110 } 1111 1112 // waiting reports whether w is still waiting for an answer (connection or error). 1113 func (w *wantConn) waiting() bool { 1114 select { 1115 case <-w.ready: 1116 return false 1117 default: 1118 return true 1119 } 1120 } 1121 1122 // tryDeliver attempts to deliver pc, err to w and reports whether it succeeded. 1123 func (w *wantConn) tryDeliver(pc *persistConn, err error) bool { 1124 w.mu.Lock() 1125 defer w.mu.Unlock() 1126 1127 if w.pc != nil || w.err != nil { 1128 return false 1129 } 1130 1131 w.pc = pc 1132 w.err = err 1133 if w.pc == nil && w.err == nil { 1134 panic("net/http: internal error: misuse of tryDeliver") 1135 } 1136 close(w.ready) 1137 return true 1138 } 1139 1140 // cancel marks w as no longer wanting a result (for example, due to cancellation). 1141 // If a connection has been delivered already, cancel returns it with t.putOrCloseIdleConn. 1142 func (w *wantConn) cancel(t *Transport, err error) { 1143 w.mu.Lock() 1144 if w.pc == nil && w.err == nil { 1145 close(w.ready) // catch misbehavior in future delivery 1146 } 1147 pc := w.pc 1148 w.pc = nil 1149 w.err = err 1150 w.mu.Unlock() 1151 1152 if pc != nil { 1153 t.putOrCloseIdleConn(pc) 1154 } 1155 } 1156 1157 // A wantConnQueue is a queue of wantConns. 1158 type wantConnQueue struct { 1159 // This is a queue, not a deque. 1160 // It is split into two stages - head[headPos:] and tail. 1161 // popFront is trivial (headPos++) on the first stage, and 1162 // pushBack is trivial (append) on the second stage. 1163 // If the first stage is empty, popFront can swap the 1164 // first and second stages to remedy the situation. 1165 // 1166 // This two-stage split is analogous to the use of two lists 1167 // in Okasaki's purely functional queue but without the 1168 // overhead of reversing the list when swapping stages. 1169 head []*wantConn 1170 headPos int 1171 tail []*wantConn 1172 } 1173 1174 // len returns the number of items in the queue. 1175 func (q *wantConnQueue) len() int { 1176 return len(q.head) - q.headPos + len(q.tail) 1177 } 1178 1179 // pushBack adds w to the back of the queue. 1180 func (q *wantConnQueue) pushBack(w *wantConn) { 1181 q.tail = append(q.tail, w) 1182 } 1183 1184 // popFront removes and returns the wantConn at the front of the queue. 1185 func (q *wantConnQueue) popFront() *wantConn { 1186 if q.headPos >= len(q.head) { 1187 if len(q.tail) == 0 { 1188 return nil 1189 } 1190 // Pick up tail as new head, clear tail. 1191 q.head, q.headPos, q.tail = q.tail, 0, q.head[:0] 1192 } 1193 w := q.head[q.headPos] 1194 q.head[q.headPos] = nil 1195 q.headPos++ 1196 return w 1197 } 1198 1199 // peekFront returns the wantConn at the front of the queue without removing it. 1200 func (q *wantConnQueue) peekFront() *wantConn { 1201 if q.headPos < len(q.head) { 1202 return q.head[q.headPos] 1203 } 1204 if len(q.tail) > 0 { 1205 return q.tail[0] 1206 } 1207 return nil 1208 } 1209 1210 // cleanFront pops any wantConns that are no longer waiting from the head of the 1211 // queue, reporting whether any were popped. 1212 func (q *wantConnQueue) cleanFront() (cleaned bool) { 1213 for { 1214 w := q.peekFront() 1215 if w == nil || w.waiting() { 1216 return cleaned 1217 } 1218 q.popFront() 1219 cleaned = true 1220 } 1221 } 1222 1223 func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error) { 1224 if t.DialTLSContext != nil { 1225 conn, err = t.DialTLSContext(ctx, network, addr) 1226 } else { 1227 conn, err = t.DialTLS(network, addr) 1228 } 1229 if conn == nil && err == nil { 1230 err = errors.New("net/http: Transport.DialTLS or DialTLSContext returned (nil, nil)") 1231 } 1232 return 1233 } 1234 1235 // getConn dials and creates a new persistConn to the target as 1236 // specified in the connectMethod. This includes doing a proxy CONNECT 1237 // and/or setting up TLS. If this doesn't return an error, the persistConn 1238 // is ready to write requests to. 1239 func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error) { 1240 req := treq.Request 1241 trace := treq.trace 1242 ctx := req.Context() 1243 if trace != nil && trace.GetConn != nil { 1244 trace.GetConn(cm.addr()) 1245 } 1246 1247 w := &wantConn{ 1248 cm: cm, 1249 key: cm.key(), 1250 ctx: ctx, 1251 ready: make(chan struct{}, 1), 1252 beforeDial: testHookPrePendingDial, 1253 afterDial: testHookPostPendingDial, 1254 } 1255 defer func() { 1256 if err != nil { 1257 w.cancel(t, err) 1258 } 1259 }() 1260 1261 // Queue for idle connection. 1262 if delivered := t.queueForIdleConn(w); delivered { 1263 pc := w.pc 1264 // Trace only for HTTP/1. 1265 // HTTP/2 calls trace.GotConn itself. 1266 if pc.alt == nil && trace != nil && trace.GotConn != nil { 1267 trace.GotConn(pc.gotIdleConnTrace(pc.idleAt)) 1268 } 1269 // set request canceler to some non-nil function so we 1270 // can detect whether it was cleared between now and when 1271 // we enter roundTrip 1272 t.setReqCanceler(req, func(error) {}) 1273 return pc, nil 1274 } 1275 1276 cancelc := make(chan error, 1) 1277 t.setReqCanceler(req, func(err error) { cancelc <- err }) 1278 1279 // Queue for permission to dial. 1280 t.queueForDial(w) 1281 1282 // Wait for completion or cancellation. 1283 select { 1284 case <-w.ready: 1285 // Trace success but only for HTTP/1. 1286 // HTTP/2 calls trace.GotConn itself. 1287 if w.pc != nil && w.pc.alt == nil && trace != nil && trace.GotConn != nil { 1288 trace.GotConn(httptrace.GotConnInfo{Conn: w.pc.conn, Reused: w.pc.isReused()}) 1289 } 1290 if w.err != nil { 1291 // If the request has been cancelled, that's probably 1292 // what caused w.err; if so, prefer to return the 1293 // cancellation error (see golang.org/issue/16049). 1294 select { 1295 case <-req.Cancel: 1296 return nil, errRequestCanceledConn 1297 case <-req.Context().Done(): 1298 return nil, req.Context().Err() 1299 case err := <-cancelc: 1300 if err == errRequestCanceled { 1301 err = errRequestCanceledConn 1302 } 1303 return nil, err 1304 default: 1305 // return below 1306 } 1307 } 1308 return w.pc, w.err 1309 case <-req.Cancel: 1310 return nil, errRequestCanceledConn 1311 case <-req.Context().Done(): 1312 return nil, req.Context().Err() 1313 case err := <-cancelc: 1314 if err == errRequestCanceled { 1315 err = errRequestCanceledConn 1316 } 1317 return nil, err 1318 } 1319 } 1320 1321 // queueForDial queues w to wait for permission to begin dialing. 1322 // Once w receives permission to dial, it will do so in a separate goroutine. 1323 func (t *Transport) queueForDial(w *wantConn) { 1324 w.beforeDial() 1325 if t.MaxConnsPerHost <= 0 { 1326 go t.dialConnFor(w) 1327 return 1328 } 1329 1330 t.connsPerHostMu.Lock() 1331 defer t.connsPerHostMu.Unlock() 1332 1333 if n := t.connsPerHost[w.key]; n < t.MaxConnsPerHost { 1334 if t.connsPerHost == nil { 1335 t.connsPerHost = make(map[connectMethodKey]int) 1336 } 1337 t.connsPerHost[w.key] = n + 1 1338 go t.dialConnFor(w) 1339 return 1340 } 1341 1342 if t.connsPerHostWait == nil { 1343 t.connsPerHostWait = make(map[connectMethodKey]wantConnQueue) 1344 } 1345 q := t.connsPerHostWait[w.key] 1346 q.cleanFront() 1347 q.pushBack(w) 1348 t.connsPerHostWait[w.key] = q 1349 } 1350 1351 // dialConnFor dials on behalf of w and delivers the result to w. 1352 // dialConnFor has received permission to dial w.cm and is counted in t.connCount[w.cm.key()]. 1353 // If the dial is cancelled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()]. 1354 func (t *Transport) dialConnFor(w *wantConn) { 1355 defer w.afterDial() 1356 1357 pc, err := t.dialConn(w.ctx, w.cm) 1358 delivered := w.tryDeliver(pc, err) 1359 if err == nil && (!delivered || pc.alt != nil) { 1360 // pconn was not passed to w, 1361 // or it is HTTP/2 and can be shared. 1362 // Add to the idle connection pool. 1363 t.putOrCloseIdleConn(pc) 1364 } 1365 if err != nil { 1366 t.decConnsPerHost(w.key) 1367 } 1368 } 1369 1370 // decConnsPerHost decrements the per-host connection count for key, 1371 // which may in turn give a different waiting goroutine permission to dial. 1372 func (t *Transport) decConnsPerHost(key connectMethodKey) { 1373 if t.MaxConnsPerHost <= 0 { 1374 return 1375 } 1376 1377 t.connsPerHostMu.Lock() 1378 defer t.connsPerHostMu.Unlock() 1379 n := t.connsPerHost[key] 1380 if n == 0 { 1381 // Shouldn't happen, but if it does, the counting is buggy and could 1382 // easily lead to a silent deadlock, so report the problem loudly. 1383 panic("net/http: internal error: connCount underflow") 1384 } 1385 1386 // Can we hand this count to a goroutine still waiting to dial? 1387 // (Some goroutines on the wait list may have timed out or 1388 // gotten a connection another way. If they're all gone, 1389 // we don't want to kick off any spurious dial operations.) 1390 if q := t.connsPerHostWait[key]; q.len() > 0 { 1391 done := false 1392 for q.len() > 0 { 1393 w := q.popFront() 1394 if w.waiting() { 1395 go t.dialConnFor(w) 1396 done = true 1397 break 1398 } 1399 } 1400 if q.len() == 0 { 1401 delete(t.connsPerHostWait, key) 1402 } else { 1403 // q is a value (like a slice), so we have to store 1404 // the updated q back into the map. 1405 t.connsPerHostWait[key] = q 1406 } 1407 if done { 1408 return 1409 } 1410 } 1411 1412 // Otherwise, decrement the recorded count. 1413 if n--; n == 0 { 1414 delete(t.connsPerHost, key) 1415 } else { 1416 t.connsPerHost[key] = n 1417 } 1418 } 1419 1420 // Add TLS to a persistent connection, i.e. negotiate a TLS session. If pconn is already a TLS 1421 // tunnel, this function establishes a nested TLS session inside the encrypted channel. 1422 // The remote endpoint's name may be overridden by TLSClientConfig.ServerName. 1423 func (pconn *persistConn) addTLS(name string, trace *httptrace.ClientTrace) error { 1424 // Initiate TLS and check remote host name against certificate. 1425 cfg := cloneTLSConfig(pconn.t.TLSClientConfig) 1426 if cfg.ServerName == "" { 1427 cfg.ServerName = name 1428 } 1429 if pconn.cacheKey.onlyH1 { 1430 cfg.NextProtos = nil 1431 } 1432 plainConn := pconn.conn 1433 tlsConn := tls.Client(plainConn, cfg) 1434 errc := make(chan error, 2) 1435 var timer *time.Timer // for canceling TLS handshake 1436 if d := pconn.t.TLSHandshakeTimeout; d != 0 { 1437 timer = time.AfterFunc(d, func() { 1438 errc <- tlsHandshakeTimeoutError{} 1439 }) 1440 } 1441 go func() { 1442 if trace != nil && trace.TLSHandshakeStart != nil { 1443 trace.TLSHandshakeStart() 1444 } 1445 err := tlsConn.Handshake() 1446 if timer != nil { 1447 timer.Stop() 1448 } 1449 errc <- err 1450 }() 1451 if err := <-errc; err != nil { 1452 plainConn.Close() 1453 if trace != nil && trace.TLSHandshakeDone != nil { 1454 trace.TLSHandshakeDone(tls.ConnectionState{}, err) 1455 } 1456 return err 1457 } 1458 cs := tlsConn.ConnectionState() 1459 if trace != nil && trace.TLSHandshakeDone != nil { 1460 trace.TLSHandshakeDone(cs, nil) 1461 } 1462 pconn.tlsState = &cs 1463 pconn.conn = tlsConn 1464 return nil 1465 } 1466 1467 func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error) { 1468 pconn = &persistConn{ 1469 t: t, 1470 cacheKey: cm.key(), 1471 reqch: make(chan requestAndChan, 1), 1472 writech: make(chan writeRequest, 1), 1473 closech: make(chan struct{}), 1474 writeErrCh: make(chan error, 1), 1475 writeLoopDone: make(chan struct{}), 1476 } 1477 trace := httptrace.ContextClientTrace(ctx) 1478 wrapErr := func(err error) error { 1479 if cm.proxyURL != nil { 1480 // Return a typed error, per Issue 16997 1481 return &net.OpError{Op: "proxyconnect", Net: "tcp", Err: err} 1482 } 1483 return err 1484 } 1485 if cm.scheme() == "https" && t.hasCustomTLSDialer() { 1486 var err error 1487 pconn.conn, err = t.customDialTLS(ctx, "tcp", cm.addr()) 1488 if err != nil { 1489 return nil, wrapErr(err) 1490 } 1491 if tc, ok := pconn.conn.(*tls.Conn); ok { 1492 // Handshake here, in case DialTLS didn't. TLSNextProto below 1493 // depends on it for knowing the connection state. 1494 if trace != nil && trace.TLSHandshakeStart != nil { 1495 trace.TLSHandshakeStart() 1496 } 1497 if err := tc.Handshake(); err != nil { 1498 go pconn.conn.Close() 1499 if trace != nil && trace.TLSHandshakeDone != nil { 1500 trace.TLSHandshakeDone(tls.ConnectionState{}, err) 1501 } 1502 return nil, err 1503 } 1504 cs := tc.ConnectionState() 1505 if trace != nil && trace.TLSHandshakeDone != nil { 1506 trace.TLSHandshakeDone(cs, nil) 1507 } 1508 pconn.tlsState = &cs 1509 } 1510 } else { 1511 conn, err := t.dial(ctx, "tcp", cm.addr()) 1512 if err != nil { 1513 return nil, wrapErr(err) 1514 } 1515 pconn.conn = conn 1516 if cm.scheme() == "https" { 1517 var firstTLSHost string 1518 if firstTLSHost, _, err = net.SplitHostPort(cm.addr()); err != nil { 1519 return nil, wrapErr(err) 1520 } 1521 if err = pconn.addTLS(firstTLSHost, trace); err != nil { 1522 return nil, wrapErr(err) 1523 } 1524 } 1525 } 1526 1527 // Proxy setup. 1528 switch { 1529 case cm.proxyURL == nil: 1530 // Do nothing. Not using a proxy. 1531 case cm.proxyURL.Scheme == "socks5": 1532 conn := pconn.conn 1533 d := socksNewDialer("tcp", conn.RemoteAddr().String()) 1534 if u := cm.proxyURL.User; u != nil { 1535 auth := &socksUsernamePassword{ 1536 Username: u.Username(), 1537 } 1538 auth.Password, _ = u.Password() 1539 d.AuthMethods = []socksAuthMethod{ 1540 socksAuthMethodNotRequired, 1541 socksAuthMethodUsernamePassword, 1542 } 1543 d.Authenticate = auth.Authenticate 1544 } 1545 if _, err := d.DialWithConn(ctx, conn, "tcp", cm.targetAddr); err != nil { 1546 conn.Close() 1547 return nil, err 1548 } 1549 case cm.targetScheme == "http": 1550 pconn.isProxy = true 1551 if pa := cm.proxyAuth(); pa != "" { 1552 pconn.mutateHeaderFunc = func(h Header) { 1553 h.Set("Proxy-Authorization", pa) 1554 } 1555 } 1556 case cm.targetScheme == "https": 1557 conn := pconn.conn 1558 hdr := t.ProxyConnectHeader 1559 if hdr == nil { 1560 hdr = make(Header) 1561 } 1562 if pa := cm.proxyAuth(); pa != "" { 1563 hdr = hdr.Clone() 1564 hdr.Set("Proxy-Authorization", pa) 1565 } 1566 connectReq := &Request{ 1567 Method: "CONNECT", 1568 URL: &url.URL{Opaque: cm.targetAddr}, 1569 Host: cm.targetAddr, 1570 Header: hdr, 1571 } 1572 1573 // If there's no done channel (no deadline or cancellation 1574 // from the caller possible), at least set some (long) 1575 // timeout here. This will make sure we don't block forever 1576 // and leak a goroutine if the connection stops replying 1577 // after the TCP connect. 1578 connectCtx := ctx 1579 if ctx.Done() == nil { 1580 newCtx, cancel := context.WithTimeout(ctx, 1*time.Minute) 1581 defer cancel() 1582 connectCtx = newCtx 1583 } 1584 1585 didReadResponse := make(chan struct{}) // closed after CONNECT write+read is done or fails 1586 var ( 1587 resp *Response 1588 err error // write or read error 1589 ) 1590 // Write the CONNECT request & read the response. 1591 go func() { 1592 defer close(didReadResponse) 1593 err = connectReq.Write(conn) 1594 if err != nil { 1595 return 1596 } 1597 // Okay to use and discard buffered reader here, because 1598 // TLS server will not speak until spoken to. 1599 br := bufio.NewReader(conn) 1600 resp, err = ReadResponse(br, connectReq) 1601 }() 1602 select { 1603 case <-connectCtx.Done(): 1604 conn.Close() 1605 <-didReadResponse 1606 return nil, connectCtx.Err() 1607 case <-didReadResponse: 1608 // resp or err now set 1609 } 1610 if err != nil { 1611 conn.Close() 1612 return nil, err 1613 } 1614 if resp.StatusCode != 200 { 1615 f := strings.SplitN(resp.Status, " ", 2) 1616 conn.Close() 1617 if len(f) < 2 { 1618 return nil, errors.New("unknown status code") 1619 } 1620 return nil, errors.New(f[1]) 1621 } 1622 } 1623 1624 if cm.proxyURL != nil && cm.targetScheme == "https" { 1625 if err := pconn.addTLS(cm.tlsHost(), trace); err != nil { 1626 return nil, err 1627 } 1628 } 1629 1630 if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" { 1631 if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; ok { 1632 return &persistConn{t: t, cacheKey: pconn.cacheKey, alt: next(cm.targetAddr, pconn.conn.(*tls.Conn))}, nil 1633 } 1634 } 1635 1636 pconn.br = bufio.NewReaderSize(pconn, t.readBufferSize()) 1637 pconn.bw = bufio.NewWriterSize(persistConnWriter{pconn}, t.writeBufferSize()) 1638 1639 go pconn.readLoop() 1640 go pconn.writeLoop() 1641 return pconn, nil 1642 } 1643 1644 // persistConnWriter is the io.Writer written to by pc.bw. 1645 // It accumulates the number of bytes written to the underlying conn, 1646 // so the retry logic can determine whether any bytes made it across 1647 // the wire. 1648 // This is exactly 1 pointer field wide so it can go into an interface 1649 // without allocation. 1650 type persistConnWriter struct { 1651 pc *persistConn 1652 } 1653 1654 func (w persistConnWriter) Write(p []byte) (n int, err error) { 1655 n, err = w.pc.conn.Write(p) 1656 w.pc.nwrite += int64(n) 1657 return 1658 } 1659 1660 // ReadFrom exposes persistConnWriter's underlying Conn to io.Copy and if 1661 // the Conn implements io.ReaderFrom, it can take advantage of optimizations 1662 // such as sendfile. 1663 func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error) { 1664 n, err = io.Copy(w.pc.conn, r) 1665 w.pc.nwrite += n 1666 return 1667 } 1668 1669 var _ io.ReaderFrom = (*persistConnWriter)(nil) 1670 1671 // connectMethod is the map key (in its String form) for keeping persistent 1672 // TCP connections alive for subsequent HTTP requests. 1673 // 1674 // A connect method may be of the following types: 1675 // 1676 // connectMethod.key().String() Description 1677 // ------------------------------ ------------------------- 1678 // |http|foo.com http directly to server, no proxy 1679 // |https|foo.com https directly to server, no proxy 1680 // |https,h1|foo.com https directly to server w/o HTTP/2, no proxy 1681 // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com 1682 // http://proxy.com|http http to proxy, http to anywhere after that 1683 // socks5://proxy.com|http|foo.com socks5 to proxy, then http to foo.com 1684 // socks5://proxy.com|https|foo.com socks5 to proxy, then https to foo.com 1685 // https://proxy.com|https|foo.com https to proxy, then CONNECT to foo.com 1686 // https://proxy.com|http https to proxy, http to anywhere after that 1687 // 1688 type connectMethod struct { 1689 proxyURL *url.URL // nil for no proxy, else full proxy URL 1690 targetScheme string // "http" or "https" 1691 // If proxyURL specifies an http or https proxy, and targetScheme is http (not https), 1692 // then targetAddr is not included in the connect method key, because the socket can 1693 // be reused for different targetAddr values. 1694 targetAddr string 1695 onlyH1 bool // whether to disable HTTP/2 and force HTTP/1 1696 } 1697 1698 func (cm *connectMethod) key() connectMethodKey { 1699 proxyStr := "" 1700 targetAddr := cm.targetAddr 1701 if cm.proxyURL != nil { 1702 proxyStr = cm.proxyURL.String() 1703 if (cm.proxyURL.Scheme == "http" || cm.proxyURL.Scheme == "https") && cm.targetScheme == "http" { 1704 targetAddr = "" 1705 } 1706 } 1707 return connectMethodKey{ 1708 proxy: proxyStr, 1709 scheme: cm.targetScheme, 1710 addr: targetAddr, 1711 onlyH1: cm.onlyH1, 1712 } 1713 } 1714 1715 // scheme returns the first hop scheme: http, https, or socks5 1716 func (cm *connectMethod) scheme() string { 1717 if cm.proxyURL != nil { 1718 return cm.proxyURL.Scheme 1719 } 1720 return cm.targetScheme 1721 } 1722 1723 // addr returns the first hop "host:port" to which we need to TCP connect. 1724 func (cm *connectMethod) addr() string { 1725 if cm.proxyURL != nil { 1726 return canonicalAddr(cm.proxyURL) 1727 } 1728 return cm.targetAddr 1729 } 1730 1731 // tlsHost returns the host name to match against the peer's 1732 // TLS certificate. 1733 func (cm *connectMethod) tlsHost() string { 1734 h := cm.targetAddr 1735 if hasPort(h) { 1736 h = h[:strings.LastIndex(h, ":")] 1737 } 1738 return h 1739 } 1740 1741 // connectMethodKey is the map key version of connectMethod, with a 1742 // stringified proxy URL (or the empty string) instead of a pointer to 1743 // a URL. 1744 type connectMethodKey struct { 1745 proxy, scheme, addr string 1746 onlyH1 bool 1747 } 1748 1749 func (k connectMethodKey) String() string { 1750 // Only used by tests. 1751 var h1 string 1752 if k.onlyH1 { 1753 h1 = ",h1" 1754 } 1755 return fmt.Sprintf("%s|%s%s|%s", k.proxy, k.scheme, h1, k.addr) 1756 } 1757 1758 // persistConn wraps a connection, usually a persistent one 1759 // (but may be used for non-keep-alive requests as well) 1760 type persistConn struct { 1761 // alt optionally specifies the TLS NextProto RoundTripper. 1762 // This is used for HTTP/2 today and future protocols later. 1763 // If it's non-nil, the rest of the fields are unused. 1764 alt RoundTripper 1765 1766 t *Transport 1767 cacheKey connectMethodKey 1768 conn net.Conn 1769 tlsState *tls.ConnectionState 1770 br *bufio.Reader // from conn 1771 bw *bufio.Writer // to conn 1772 nwrite int64 // bytes written 1773 reqch chan requestAndChan // written by roundTrip; read by readLoop 1774 writech chan writeRequest // written by roundTrip; read by writeLoop 1775 closech chan struct{} // closed when conn closed 1776 isProxy bool 1777 sawEOF bool // whether we've seen EOF from conn; owned by readLoop 1778 readLimit int64 // bytes allowed to be read; owned by readLoop 1779 // writeErrCh passes the request write error (usually nil) 1780 // from the writeLoop goroutine to the readLoop which passes 1781 // it off to the res.Body reader, which then uses it to decide 1782 // whether or not a connection can be reused. Issue 7569. 1783 writeErrCh chan error 1784 1785 writeLoopDone chan struct{} // closed when write loop ends 1786 1787 // Both guarded by Transport.idleMu: 1788 idleAt time.Time // time it last become idle 1789 idleTimer *time.Timer // holding an AfterFunc to close it 1790 1791 mu sync.Mutex // guards following fields 1792 numExpectedResponses int 1793 closed error // set non-nil when conn is closed, before closech is closed 1794 canceledErr error // set non-nil if conn is canceled 1795 broken bool // an error has happened on this connection; marked broken so it's not reused. 1796 reused bool // whether conn has had successful request/response and is being reused. 1797 // mutateHeaderFunc is an optional func to modify extra 1798 // headers on each outbound request before it's written. (the 1799 // original Request given to RoundTrip is not modified) 1800 mutateHeaderFunc func(Header) 1801 } 1802 1803 func (pc *persistConn) maxHeaderResponseSize() int64 { 1804 if v := pc.t.MaxResponseHeaderBytes; v != 0 { 1805 return v 1806 } 1807 return 10 << 20 // conservative default; same as http2 1808 } 1809 1810 func (pc *persistConn) Read(p []byte) (n int, err error) { 1811 if pc.readLimit <= 0 { 1812 return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize()) 1813 } 1814 if int64(len(p)) > pc.readLimit { 1815 p = p[:pc.readLimit] 1816 } 1817 n, err = pc.conn.Read(p) 1818 if err == io.EOF { 1819 pc.sawEOF = true 1820 } 1821 pc.readLimit -= int64(n) 1822 return 1823 } 1824 1825 // isBroken reports whether this connection is in a known broken state. 1826 func (pc *persistConn) isBroken() bool { 1827 pc.mu.Lock() 1828 b := pc.closed != nil 1829 pc.mu.Unlock() 1830 return b 1831 } 1832 1833 // canceled returns non-nil if the connection was closed due to 1834 // CancelRequest or due to context cancellation. 1835 func (pc *persistConn) canceled() error { 1836 pc.mu.Lock() 1837 defer pc.mu.Unlock() 1838 return pc.canceledErr 1839 } 1840 1841 // isReused reports whether this connection has been used before. 1842 func (pc *persistConn) isReused() bool { 1843 pc.mu.Lock() 1844 r := pc.reused 1845 pc.mu.Unlock() 1846 return r 1847 } 1848 1849 func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo) { 1850 pc.mu.Lock() 1851 defer pc.mu.Unlock() 1852 t.Reused = pc.reused 1853 t.Conn = pc.conn 1854 t.WasIdle = true 1855 if !idleAt.IsZero() { 1856 t.IdleTime = time.Since(idleAt) 1857 } 1858 return 1859 } 1860 1861 func (pc *persistConn) cancelRequest(err error) { 1862 pc.mu.Lock() 1863 defer pc.mu.Unlock() 1864 pc.canceledErr = err 1865 pc.closeLocked(errRequestCanceled) 1866 } 1867 1868 // closeConnIfStillIdle closes the connection if it's still sitting idle. 1869 // This is what's called by the persistConn's idleTimer, and is run in its 1870 // own goroutine. 1871 func (pc *persistConn) closeConnIfStillIdle() { 1872 t := pc.t 1873 t.idleMu.Lock() 1874 defer t.idleMu.Unlock() 1875 if _, ok := t.idleLRU.m[pc]; !ok { 1876 // Not idle. 1877 return 1878 } 1879 t.removeIdleConnLocked(pc) 1880 pc.close(errIdleConnTimeout) 1881 } 1882 1883 // mapRoundTripError returns the appropriate error value for 1884 // persistConn.roundTrip. 1885 // 1886 // The provided err is the first error that (*persistConn).roundTrip 1887 // happened to receive from its select statement. 1888 // 1889 // The startBytesWritten value should be the value of pc.nwrite before the roundTrip 1890 // started writing the request. 1891 func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error { 1892 if err == nil { 1893 return nil 1894 } 1895 1896 // If the request was canceled, that's better than network 1897 // failures that were likely the result of tearing down the 1898 // connection. 1899 if cerr := pc.canceled(); cerr != nil { 1900 return cerr 1901 } 1902 1903 // See if an error was set explicitly. 1904 req.mu.Lock() 1905 reqErr := req.err 1906 req.mu.Unlock() 1907 if reqErr != nil { 1908 return reqErr 1909 } 1910 1911 if err == errServerClosedIdle { 1912 // Don't decorate 1913 return err 1914 } 1915 1916 if _, ok := err.(transportReadFromServerError); ok { 1917 // Don't decorate 1918 return err 1919 } 1920 if pc.isBroken() { 1921 <-pc.writeLoopDone 1922 if pc.nwrite == startBytesWritten { 1923 return nothingWrittenError{err} 1924 } 1925 return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %v", err) 1926 } 1927 return err 1928 } 1929 1930 // errCallerOwnsConn is an internal sentinel error used when we hand 1931 // off a writable response.Body to the caller. We use this to prevent 1932 // closing a net.Conn that is now owned by the caller. 1933 var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn") 1934 1935 func (pc *persistConn) readLoop() { 1936 closeErr := errReadLoopExiting // default value, if not changed below 1937 defer func() { 1938 pc.close(closeErr) 1939 pc.t.removeIdleConn(pc) 1940 }() 1941 1942 tryPutIdleConn := func(trace *httptrace.ClientTrace) bool { 1943 if err := pc.t.tryPutIdleConn(pc); err != nil { 1944 closeErr = err 1945 if trace != nil && trace.PutIdleConn != nil && err != errKeepAlivesDisabled { 1946 trace.PutIdleConn(err) 1947 } 1948 return false 1949 } 1950 if trace != nil && trace.PutIdleConn != nil { 1951 trace.PutIdleConn(nil) 1952 } 1953 return true 1954 } 1955 1956 // eofc is used to block caller goroutines reading from Response.Body 1957 // at EOF until this goroutines has (potentially) added the connection 1958 // back to the idle pool. 1959 eofc := make(chan struct{}) 1960 defer close(eofc) // unblock reader on errors 1961 1962 // Read this once, before loop starts. (to avoid races in tests) 1963 testHookMu.Lock() 1964 testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead 1965 testHookMu.Unlock() 1966 1967 alive := true 1968 for alive { 1969 pc.readLimit = pc.maxHeaderResponseSize() 1970 _, err := pc.br.Peek(1) 1971 1972 pc.mu.Lock() 1973 if pc.numExpectedResponses == 0 { 1974 pc.readLoopPeekFailLocked(err) 1975 pc.mu.Unlock() 1976 return 1977 } 1978 pc.mu.Unlock() 1979 1980 rc := <-pc.reqch 1981 trace := httptrace.ContextClientTrace(rc.req.Context()) 1982 1983 var resp *Response 1984 if err == nil { 1985 resp, err = pc.readResponse(rc, trace) 1986 } else { 1987 err = transportReadFromServerError{err} 1988 closeErr = err 1989 } 1990 1991 if err != nil { 1992 if pc.readLimit <= 0 { 1993 err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize()) 1994 } 1995 1996 select { 1997 case rc.ch <- responseAndError{err: err}: 1998 case <-rc.callerGone: 1999 return 2000 } 2001 return 2002 } 2003 pc.readLimit = maxInt64 // effectively no limit for response bodies 2004 2005 pc.mu.Lock() 2006 pc.numExpectedResponses-- 2007 pc.mu.Unlock() 2008 2009 bodyWritable := resp.bodyIsWritable() 2010 hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 2011 2012 if resp.Close || rc.req.Close || resp.StatusCode <= 199 || bodyWritable { 2013 // Don't do keep-alive on error if either party requested a close 2014 // or we get an unexpected informational (1xx) response. 2015 // StatusCode 100 is already handled above. 2016 alive = false 2017 } 2018 2019 if !hasBody || bodyWritable { 2020 pc.t.setReqCanceler(rc.req, nil) 2021 2022 // Put the idle conn back into the pool before we send the response 2023 // so if they process it quickly and make another request, they'll 2024 // get this same conn. But we use the unbuffered channel 'rc' 2025 // to guarantee that persistConn.roundTrip got out of its select 2026 // potentially waiting for this persistConn to close. 2027 // but after 2028 alive = alive && 2029 !pc.sawEOF && 2030 pc.wroteRequest() && 2031 tryPutIdleConn(trace) 2032 2033 if bodyWritable { 2034 closeErr = errCallerOwnsConn 2035 } 2036 2037 select { 2038 case rc.ch <- responseAndError{res: resp}: 2039 case <-rc.callerGone: 2040 return 2041 } 2042 2043 // Now that they've read from the unbuffered channel, they're safely 2044 // out of the select that also waits on this goroutine to die, so 2045 // we're allowed to exit now if needed (if alive is false) 2046 testHookReadLoopBeforeNextRead() 2047 continue 2048 } 2049 2050 waitForBodyRead := make(chan bool, 2) 2051 body := &bodyEOFSignal{ 2052 body: resp.Body, 2053 earlyCloseFn: func() error { 2054 waitForBodyRead <- false 2055 <-eofc // will be closed by deferred call at the end of the function 2056 return nil 2057 2058 }, 2059 fn: func(err error) error { 2060 isEOF := err == io.EOF 2061 waitForBodyRead <- isEOF 2062 if isEOF { 2063 <-eofc // see comment above eofc declaration 2064 } else if err != nil { 2065 if cerr := pc.canceled(); cerr != nil { 2066 return cerr 2067 } 2068 } 2069 return err 2070 }, 2071 } 2072 2073 resp.Body = body 2074 if rc.addedGzip && strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") { 2075 resp.Body = &gzipReader{body: body} 2076 resp.Header.Del("Content-Encoding") 2077 resp.Header.Del("Content-Length") 2078 resp.ContentLength = -1 2079 resp.Uncompressed = true 2080 } 2081 2082 select { 2083 case rc.ch <- responseAndError{res: resp}: 2084 case <-rc.callerGone: 2085 return 2086 } 2087 2088 // Before looping back to the top of this function and peeking on 2089 // the bufio.Reader, wait for the caller goroutine to finish 2090 // reading the response body. (or for cancellation or death) 2091 select { 2092 case bodyEOF := <-waitForBodyRead: 2093 pc.t.setReqCanceler(rc.req, nil) // before pc might return to idle pool 2094 alive = alive && 2095 bodyEOF && 2096 !pc.sawEOF && 2097 pc.wroteRequest() && 2098 tryPutIdleConn(trace) 2099 if bodyEOF { 2100 eofc <- struct{}{} 2101 } 2102 case <-rc.req.Cancel: 2103 alive = false 2104 pc.t.CancelRequest(rc.req) 2105 case <-rc.req.Context().Done(): 2106 alive = false 2107 pc.t.cancelRequest(rc.req, rc.req.Context().Err()) 2108 case <-pc.closech: 2109 alive = false 2110 } 2111 2112 testHookReadLoopBeforeNextRead() 2113 } 2114 } 2115 2116 func (pc *persistConn) readLoopPeekFailLocked(peekErr error) { 2117 if pc.closed != nil { 2118 return 2119 } 2120 if n := pc.br.Buffered(); n > 0 { 2121 buf, _ := pc.br.Peek(n) 2122 if is408Message(buf) { 2123 pc.closeLocked(errServerClosedIdle) 2124 return 2125 } else { 2126 log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr) 2127 } 2128 } 2129 if peekErr == io.EOF { 2130 // common case. 2131 pc.closeLocked(errServerClosedIdle) 2132 } else { 2133 pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %v", peekErr)) 2134 } 2135 } 2136 2137 // is408Message reports whether buf has the prefix of an 2138 // HTTP 408 Request Timeout response. 2139 // See golang.org/issue/32310. 2140 func is408Message(buf []byte) bool { 2141 if len(buf) < len("HTTP/1.x 408") { 2142 return false 2143 } 2144 if string(buf[:7]) != "HTTP/1." { 2145 return false 2146 } 2147 return string(buf[8:12]) == " 408" 2148 } 2149 2150 // readResponse reads an HTTP response (or two, in the case of "Expect: 2151 // 100-continue") from the server. It returns the final non-100 one. 2152 // trace is optional. 2153 func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error) { 2154 if trace != nil && trace.GotFirstResponseByte != nil { 2155 if peek, err := pc.br.Peek(1); err == nil && len(peek) == 1 { 2156 trace.GotFirstResponseByte() 2157 } 2158 } 2159 num1xx := 0 // number of informational 1xx headers received 2160 const max1xxResponses = 5 // arbitrary bound on number of informational responses 2161 2162 continueCh := rc.continueCh 2163 for { 2164 resp, err = ReadResponse(pc.br, rc.req) 2165 if err != nil { 2166 return 2167 } 2168 resCode := resp.StatusCode 2169 if continueCh != nil { 2170 if resCode == 100 { 2171 if trace != nil && trace.Got100Continue != nil { 2172 trace.Got100Continue() 2173 } 2174 continueCh <- struct{}{} 2175 continueCh = nil 2176 } else if resCode >= 200 { 2177 close(continueCh) 2178 continueCh = nil 2179 } 2180 } 2181 is1xx := 100 <= resCode && resCode <= 199 2182 // treat 101 as a terminal status, see issue 26161 2183 is1xxNonTerminal := is1xx && resCode != StatusSwitchingProtocols 2184 if is1xxNonTerminal { 2185 num1xx++ 2186 if num1xx > max1xxResponses { 2187 return nil, errors.New("net/http: too many 1xx informational responses") 2188 } 2189 pc.readLimit = pc.maxHeaderResponseSize() // reset the limit 2190 if trace != nil && trace.Got1xxResponse != nil { 2191 if err := trace.Got1xxResponse(resCode, textproto.MIMEHeader(resp.Header)); err != nil { 2192 return nil, err 2193 } 2194 } 2195 continue 2196 } 2197 break 2198 } 2199 if resp.isProtocolSwitch() { 2200 resp.Body = newReadWriteCloserBody(pc.br, pc.conn) 2201 } 2202 2203 resp.TLS = pc.tlsState 2204 return 2205 } 2206 2207 // waitForContinue returns the function to block until 2208 // any response, timeout or connection close. After any of them, 2209 // the function returns a bool which indicates if the body should be sent. 2210 func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool { 2211 if continueCh == nil { 2212 return nil 2213 } 2214 return func() bool { 2215 timer := time.NewTimer(pc.t.ExpectContinueTimeout) 2216 defer timer.Stop() 2217 2218 select { 2219 case _, ok := <-continueCh: 2220 return ok 2221 case <-timer.C: 2222 return true 2223 case <-pc.closech: 2224 return false 2225 } 2226 } 2227 } 2228 2229 func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser { 2230 body := &readWriteCloserBody{ReadWriteCloser: rwc} 2231 if br.Buffered() != 0 { 2232 body.br = br 2233 } 2234 return body 2235 } 2236 2237 // readWriteCloserBody is the Response.Body type used when we want to 2238 // give users write access to the Body through the underlying 2239 // connection (TCP, unless using custom dialers). This is then 2240 // the concrete type for a Response.Body on the 101 Switching 2241 // Protocols response, as used by WebSockets, h2c, etc. 2242 type readWriteCloserBody struct { 2243 br *bufio.Reader // used until empty 2244 io.ReadWriteCloser 2245 } 2246 2247 func (b *readWriteCloserBody) Read(p []byte) (n int, err error) { 2248 if b.br != nil { 2249 if n := b.br.Buffered(); len(p) > n { 2250 p = p[:n] 2251 } 2252 n, err = b.br.Read(p) 2253 if b.br.Buffered() == 0 { 2254 b.br = nil 2255 } 2256 return n, err 2257 } 2258 return b.ReadWriteCloser.Read(p) 2259 } 2260 2261 // nothingWrittenError wraps a write errors which ended up writing zero bytes. 2262 type nothingWrittenError struct { 2263 error 2264 } 2265 2266 func (pc *persistConn) writeLoop() { 2267 defer close(pc.writeLoopDone) 2268 for { 2269 select { 2270 case wr := <-pc.writech: 2271 startBytesWritten := pc.nwrite 2272 err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh)) 2273 if bre, ok := err.(requestBodyReadError); ok { 2274 err = bre.error 2275 // Errors reading from the user's 2276 // Request.Body are high priority. 2277 // Set it here before sending on the 2278 // channels below or calling 2279 // pc.close() which tears town 2280 // connections and causes other 2281 // errors. 2282 wr.req.setError(err) 2283 } 2284 if err == nil { 2285 err = pc.bw.Flush() 2286 } 2287 if err != nil { 2288 wr.req.Request.closeBody() 2289 if pc.nwrite == startBytesWritten { 2290 err = nothingWrittenError{err} 2291 } 2292 } 2293 pc.writeErrCh <- err // to the body reader, which might recycle us 2294 wr.ch <- err // to the roundTrip function 2295 if err != nil { 2296 pc.close(err) 2297 return 2298 } 2299 case <-pc.closech: 2300 return 2301 } 2302 } 2303 } 2304 2305 // maxWriteWaitBeforeConnReuse is how long the a Transport RoundTrip 2306 // will wait to see the Request's Body.Write result after getting a 2307 // response from the server. See comments in (*persistConn).wroteRequest. 2308 const maxWriteWaitBeforeConnReuse = 50 * time.Millisecond 2309 2310 // wroteRequest is a check before recycling a connection that the previous write 2311 // (from writeLoop above) happened and was successful. 2312 func (pc *persistConn) wroteRequest() bool { 2313 select { 2314 case err := <-pc.writeErrCh: 2315 // Common case: the write happened well before the response, so 2316 // avoid creating a timer. 2317 return err == nil 2318 default: 2319 // Rare case: the request was written in writeLoop above but 2320 // before it could send to pc.writeErrCh, the reader read it 2321 // all, processed it, and called us here. In this case, give the 2322 // write goroutine a bit of time to finish its send. 2323 // 2324 // Less rare case: We also get here in the legitimate case of 2325 // Issue 7569, where the writer is still writing (or stalled), 2326 // but the server has already replied. In this case, we don't 2327 // want to wait too long, and we want to return false so this 2328 // connection isn't re-used. 2329 t := time.NewTimer(maxWriteWaitBeforeConnReuse) 2330 defer t.Stop() 2331 select { 2332 case err := <-pc.writeErrCh: 2333 return err == nil 2334 case <-t.C: 2335 return false 2336 } 2337 } 2338 } 2339 2340 // responseAndError is how the goroutine reading from an HTTP/1 server 2341 // communicates with the goroutine doing the RoundTrip. 2342 type responseAndError struct { 2343 res *Response // else use this response (see res method) 2344 err error 2345 } 2346 2347 type requestAndChan struct { 2348 req *Request 2349 ch chan responseAndError // unbuffered; always send in select on callerGone 2350 2351 // whether the Transport (as opposed to the user client code) 2352 // added the Accept-Encoding gzip header. If the Transport 2353 // set it, only then do we transparently decode the gzip. 2354 addedGzip bool 2355 2356 // Optional blocking chan for Expect: 100-continue (for send). 2357 // If the request has an "Expect: 100-continue" header and 2358 // the server responds 100 Continue, readLoop send a value 2359 // to writeLoop via this chan. 2360 continueCh chan<- struct{} 2361 2362 callerGone <-chan struct{} // closed when roundTrip caller has returned 2363 } 2364 2365 // A writeRequest is sent by the readLoop's goroutine to the 2366 // writeLoop's goroutine to write a request while the read loop 2367 // concurrently waits on both the write response and the server's 2368 // reply. 2369 type writeRequest struct { 2370 req *transportRequest 2371 ch chan<- error 2372 2373 // Optional blocking chan for Expect: 100-continue (for receive). 2374 // If not nil, writeLoop blocks sending request body until 2375 // it receives from this chan. 2376 continueCh <-chan struct{} 2377 } 2378 2379 type httpError struct { 2380 err string 2381 timeout bool 2382 } 2383 2384 func (e *httpError) Error() string { return e.err } 2385 func (e *httpError) Timeout() bool { return e.timeout } 2386 func (e *httpError) Temporary() bool { return true } 2387 2388 var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true} 2389 2390 // errRequestCanceled is set to be identical to the one from h2 to facilitate 2391 // testing. 2392 var errRequestCanceled = http2errRequestCanceled 2393 var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify? 2394 2395 func nop() {} 2396 2397 // testHooks. Always non-nil. 2398 var ( 2399 testHookEnterRoundTrip = nop 2400 testHookWaitResLoop = nop 2401 testHookRoundTripRetried = nop 2402 testHookPrePendingDial = nop 2403 testHookPostPendingDial = nop 2404 2405 testHookMu sync.Locker = fakeLocker{} // guards following 2406 testHookReadLoopBeforeNextRead = nop 2407 ) 2408 2409 func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { 2410 testHookEnterRoundTrip() 2411 if !pc.t.replaceReqCanceler(req.Request, pc.cancelRequest) { 2412 pc.t.putOrCloseIdleConn(pc) 2413 return nil, errRequestCanceled 2414 } 2415 pc.mu.Lock() 2416 pc.numExpectedResponses++ 2417 headerFn := pc.mutateHeaderFunc 2418 pc.mu.Unlock() 2419 2420 if headerFn != nil { 2421 headerFn(req.extraHeaders()) 2422 } 2423 2424 // Ask for a compressed version if the caller didn't set their 2425 // own value for Accept-Encoding. We only attempt to 2426 // uncompress the gzip stream if we were the layer that 2427 // requested it. 2428 requestedGzip := false 2429 if !pc.t.DisableCompression && 2430 req.Header.Get("Accept-Encoding") == "" && 2431 req.Header.Get("Range") == "" && 2432 req.Method != "HEAD" { 2433 // Request gzip only, not deflate. Deflate is ambiguous and 2434 // not as universally supported anyway. 2435 // See: https://zlib.net/zlib_faq.html#faq39 2436 // 2437 // Note that we don't request this for HEAD requests, 2438 // due to a bug in nginx: 2439 // https://trac.nginx.org/nginx/ticket/358 2440 // https://golang.org/issue/5522 2441 // 2442 // We don't request gzip if the request is for a range, since 2443 // auto-decoding a portion of a gzipped document will just fail 2444 // anyway. See https://golang.org/issue/8923 2445 requestedGzip = true 2446 req.extraHeaders().Set("Accept-Encoding", "gzip") 2447 } 2448 2449 var continueCh chan struct{} 2450 if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() { 2451 continueCh = make(chan struct{}, 1) 2452 } 2453 2454 if pc.t.DisableKeepAlives && !req.wantsClose() { 2455 req.extraHeaders().Set("Connection", "close") 2456 } 2457 2458 gone := make(chan struct{}) 2459 defer close(gone) 2460 2461 defer func() { 2462 if err != nil { 2463 pc.t.setReqCanceler(req.Request, nil) 2464 } 2465 }() 2466 2467 const debugRoundTrip = false 2468 2469 // Write the request concurrently with waiting for a response, 2470 // in case the server decides to reply before reading our full 2471 // request body. 2472 startBytesWritten := pc.nwrite 2473 writeErrCh := make(chan error, 1) 2474 pc.writech <- writeRequest{req, writeErrCh, continueCh} 2475 2476 resc := make(chan responseAndError) 2477 pc.reqch <- requestAndChan{ 2478 req: req.Request, 2479 ch: resc, 2480 addedGzip: requestedGzip, 2481 continueCh: continueCh, 2482 callerGone: gone, 2483 } 2484 2485 var respHeaderTimer <-chan time.Time 2486 cancelChan := req.Request.Cancel 2487 ctxDoneChan := req.Context().Done() 2488 for { 2489 testHookWaitResLoop() 2490 select { 2491 case err := <-writeErrCh: 2492 if debugRoundTrip { 2493 req.logf("writeErrCh resv: %T/%#v", err, err) 2494 } 2495 if err != nil { 2496 pc.close(fmt.Errorf("write error: %v", err)) 2497 return nil, pc.mapRoundTripError(req, startBytesWritten, err) 2498 } 2499 if d := pc.t.ResponseHeaderTimeout; d > 0 { 2500 if debugRoundTrip { 2501 req.logf("starting timer for %v", d) 2502 } 2503 timer := time.NewTimer(d) 2504 defer timer.Stop() // prevent leaks 2505 respHeaderTimer = timer.C 2506 } 2507 case <-pc.closech: 2508 if debugRoundTrip { 2509 req.logf("closech recv: %T %#v", pc.closed, pc.closed) 2510 } 2511 return nil, pc.mapRoundTripError(req, startBytesWritten, pc.closed) 2512 case <-respHeaderTimer: 2513 if debugRoundTrip { 2514 req.logf("timeout waiting for response headers.") 2515 } 2516 pc.close(errTimeout) 2517 return nil, errTimeout 2518 case re := <-resc: 2519 if (re.res == nil) == (re.err == nil) { 2520 panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", re.res == nil)) 2521 } 2522 if debugRoundTrip { 2523 req.logf("resc recv: %p, %T/%#v", re.res, re.err, re.err) 2524 } 2525 if re.err != nil { 2526 return nil, pc.mapRoundTripError(req, startBytesWritten, re.err) 2527 } 2528 return re.res, nil 2529 case <-cancelChan: 2530 pc.t.CancelRequest(req.Request) 2531 cancelChan = nil 2532 case <-ctxDoneChan: 2533 pc.t.cancelRequest(req.Request, req.Context().Err()) 2534 cancelChan = nil 2535 ctxDoneChan = nil 2536 } 2537 } 2538 } 2539 2540 // tLogKey is a context WithValue key for test debugging contexts containing 2541 // a t.Logf func. See export_test.go's Request.WithT method. 2542 type tLogKey struct{} 2543 2544 func (tr *transportRequest) logf(format string, args ...interface{}) { 2545 if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...interface{})); ok { 2546 logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...) 2547 } 2548 } 2549 2550 // markReused marks this connection as having been successfully used for a 2551 // request and response. 2552 func (pc *persistConn) markReused() { 2553 pc.mu.Lock() 2554 pc.reused = true 2555 pc.mu.Unlock() 2556 } 2557 2558 // close closes the underlying TCP connection and closes 2559 // the pc.closech channel. 2560 // 2561 // The provided err is only for testing and debugging; in normal 2562 // circumstances it should never be seen by users. 2563 func (pc *persistConn) close(err error) { 2564 pc.mu.Lock() 2565 defer pc.mu.Unlock() 2566 pc.closeLocked(err) 2567 } 2568 2569 func (pc *persistConn) closeLocked(err error) { 2570 if err == nil { 2571 panic("nil error") 2572 } 2573 pc.broken = true 2574 if pc.closed == nil { 2575 pc.closed = err 2576 pc.t.decConnsPerHost(pc.cacheKey) 2577 // Close HTTP/1 (pc.alt == nil) connection. 2578 // HTTP/2 closes its connection itself. 2579 if pc.alt == nil { 2580 if err != errCallerOwnsConn { 2581 pc.conn.Close() 2582 } 2583 close(pc.closech) 2584 } 2585 } 2586 pc.mutateHeaderFunc = nil 2587 } 2588 2589 var portMap = map[string]string{ 2590 "http": "80", 2591 "https": "443", 2592 "socks5": "1080", 2593 } 2594 2595 // canonicalAddr returns url.Host but always with a ":port" suffix 2596 func canonicalAddr(url *url.URL) string { 2597 addr := url.Hostname() 2598 if v, err := idnaASCII(addr); err == nil { 2599 addr = v 2600 } 2601 port := url.Port() 2602 if port == "" { 2603 port = portMap[url.Scheme] 2604 } 2605 return net.JoinHostPort(addr, port) 2606 } 2607 2608 // bodyEOFSignal is used by the HTTP/1 transport when reading response 2609 // bodies to make sure we see the end of a response body before 2610 // proceeding and reading on the connection again. 2611 // 2612 // It wraps a ReadCloser but runs fn (if non-nil) at most 2613 // once, right before its final (error-producing) Read or Close call 2614 // returns. fn should return the new error to return from Read or Close. 2615 // 2616 // If earlyCloseFn is non-nil and Close is called before io.EOF is 2617 // seen, earlyCloseFn is called instead of fn, and its return value is 2618 // the return value from Close. 2619 type bodyEOFSignal struct { 2620 body io.ReadCloser 2621 mu sync.Mutex // guards following 4 fields 2622 closed bool // whether Close has been called 2623 rerr error // sticky Read error 2624 fn func(error) error // err will be nil on Read io.EOF 2625 earlyCloseFn func() error // optional alt Close func used if io.EOF not seen 2626 } 2627 2628 var errReadOnClosedResBody = errors.New("http: read on closed response body") 2629 2630 func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { 2631 es.mu.Lock() 2632 closed, rerr := es.closed, es.rerr 2633 es.mu.Unlock() 2634 if closed { 2635 return 0, errReadOnClosedResBody 2636 } 2637 if rerr != nil { 2638 return 0, rerr 2639 } 2640 2641 n, err = es.body.Read(p) 2642 if err != nil { 2643 es.mu.Lock() 2644 defer es.mu.Unlock() 2645 if es.rerr == nil { 2646 es.rerr = err 2647 } 2648 err = es.condfn(err) 2649 } 2650 return 2651 } 2652 2653 func (es *bodyEOFSignal) Close() error { 2654 es.mu.Lock() 2655 defer es.mu.Unlock() 2656 if es.closed { 2657 return nil 2658 } 2659 es.closed = true 2660 if es.earlyCloseFn != nil && es.rerr != io.EOF { 2661 return es.earlyCloseFn() 2662 } 2663 err := es.body.Close() 2664 return es.condfn(err) 2665 } 2666 2667 // caller must hold es.mu. 2668 func (es *bodyEOFSignal) condfn(err error) error { 2669 if es.fn == nil { 2670 return err 2671 } 2672 err = es.fn(err) 2673 es.fn = nil 2674 return err 2675 } 2676 2677 // gzipReader wraps a response body so it can lazily 2678 // call gzip.NewReader on the first call to Read 2679 type gzipReader struct { 2680 body *bodyEOFSignal // underlying HTTP/1 response body framing 2681 zr *gzip.Reader // lazily-initialized gzip reader 2682 zerr error // any error from gzip.NewReader; sticky 2683 } 2684 2685 func (gz *gzipReader) Read(p []byte) (n int, err error) { 2686 if gz.zr == nil { 2687 if gz.zerr == nil { 2688 gz.zr, gz.zerr = gzip.NewReader(gz.body) 2689 } 2690 if gz.zerr != nil { 2691 return 0, gz.zerr 2692 } 2693 } 2694 2695 gz.body.mu.Lock() 2696 if gz.body.closed { 2697 err = errReadOnClosedResBody 2698 } 2699 gz.body.mu.Unlock() 2700 2701 if err != nil { 2702 return 0, err 2703 } 2704 return gz.zr.Read(p) 2705 } 2706 2707 func (gz *gzipReader) Close() error { 2708 return gz.body.Close() 2709 } 2710 2711 type tlsHandshakeTimeoutError struct{} 2712 2713 func (tlsHandshakeTimeoutError) Timeout() bool { return true } 2714 func (tlsHandshakeTimeoutError) Temporary() bool { return true } 2715 func (tlsHandshakeTimeoutError) Error() string { return "net/http: TLS handshake timeout" } 2716 2717 // fakeLocker is a sync.Locker which does nothing. It's used to guard 2718 // test-only fields when not under test, to avoid runtime atomic 2719 // overhead. 2720 type fakeLocker struct{} 2721 2722 func (fakeLocker) Lock() {} 2723 func (fakeLocker) Unlock() {} 2724 2725 // cloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if 2726 // cfg is nil. This is safe to call even if cfg is in active use by a TLS 2727 // client or server. 2728 func cloneTLSConfig(cfg *tls.Config) *tls.Config { 2729 if cfg == nil { 2730 return &tls.Config{} 2731 } 2732 return cfg.Clone() 2733 } 2734 2735 type connLRU struct { 2736 ll *list.List // list.Element.Value type is of *persistConn 2737 m map[*persistConn]*list.Element 2738 } 2739 2740 // add adds pc to the head of the linked list. 2741 func (cl *connLRU) add(pc *persistConn) { 2742 if cl.ll == nil { 2743 cl.ll = list.New() 2744 cl.m = make(map[*persistConn]*list.Element) 2745 } 2746 ele := cl.ll.PushFront(pc) 2747 if _, ok := cl.m[pc]; ok { 2748 panic("persistConn was already in LRU") 2749 } 2750 cl.m[pc] = ele 2751 } 2752 2753 func (cl *connLRU) removeOldest() *persistConn { 2754 ele := cl.ll.Back() 2755 pc := ele.Value.(*persistConn) 2756 cl.ll.Remove(ele) 2757 delete(cl.m, pc) 2758 return pc 2759 } 2760 2761 // remove removes pc from cl. 2762 func (cl *connLRU) remove(pc *persistConn) { 2763 if ele, ok := cl.m[pc]; ok { 2764 cl.ll.Remove(ele) 2765 delete(cl.m, pc) 2766 } 2767 } 2768 2769 // len returns the number of items in the cache. 2770 func (cl *connLRU) len() int { 2771 return len(cl.m) 2772 }