Source file src/net/http/transport.go

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

View as plain text