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