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

View as plain text