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

View as plain text