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

View as plain text