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

View as plain text