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

View as plain text