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