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