Source file src/net/http/transport.go

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

View as plain text