github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/transport.go (about)

     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 2616.
     6  //
     7  // This is the low-level Transport implementation of RoundTripper.
     8  // The high-level interface is in client.go.
     9  
    10  package http
    11  
    12  import (
    13  	"bufio"
    14  	"compress/gzip"
    15  	"container/list"
    16  	"context"
    17  	"crypto/tls"
    18  	"errors"
    19  	"fmt"
    20  	"io"
    21  	"log"
    22  	"net"
    23  	"net/http/httptrace"
    24  	"net/url"
    25  	"os"
    26  	"strings"
    27  	"sync"
    28  	"sync/atomic"
    29  	"time"
    30  
    31  	"golang_org/x/net/lex/httplex"
    32  	"golang_org/x/net/proxy"
    33  )
    34  
    35  // DefaultTransport is the default implementation of Transport and is
    36  // used by DefaultClient. It establishes network connections as needed
    37  // and caches them for reuse by subsequent calls. It uses HTTP proxies
    38  // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
    39  // $no_proxy) environment variables.
    40  var DefaultTransport RoundTripper = &Transport{
    41  	Proxy: ProxyFromEnvironment,
    42  	DialContext: (&net.Dialer{
    43  		Timeout:   30 * time.Second,
    44  		KeepAlive: 30 * time.Second,
    45  		DualStack: true,
    46  	}).DialContext,
    47  	MaxIdleConns:          100,
    48  	IdleConnTimeout:       90 * time.Second,
    49  	TLSHandshakeTimeout:   10 * time.Second,
    50  	ExpectContinueTimeout: 1 * time.Second,
    51  }
    52  
    53  // DefaultMaxIdleConnsPerHost is the default value of Transport's
    54  // MaxIdleConnsPerHost.
    55  const DefaultMaxIdleConnsPerHost = 2
    56  
    57  // Transport is an implementation of RoundTripper that supports HTTP,
    58  // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
    59  //
    60  // By default, Transport caches connections for future re-use.
    61  // This may leave many open connections when accessing many hosts.
    62  // This behavior can be managed using Transport's CloseIdleConnections method
    63  // and the MaxIdleConnsPerHost and DisableKeepAlives fields.
    64  //
    65  // Transports should be reused instead of created as needed.
    66  // Transports are safe for concurrent use by multiple goroutines.
    67  //
    68  // A Transport is a low-level primitive for making HTTP and HTTPS requests.
    69  // For high-level functionality, such as cookies and redirects, see Client.
    70  //
    71  // Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
    72  // for HTTPS URLs, depending on whether the server supports HTTP/2,
    73  // and how the Transport is configured. The DefaultTransport supports HTTP/2.
    74  // To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
    75  // and call ConfigureTransport. See the package docs for more about HTTP/2.
    76  type Transport struct {
    77  	idleMu     sync.Mutex
    78  	wantIdle   bool                                // user has requested to close all idle conns
    79  	idleConn   map[connectMethodKey][]*persistConn // most recently used at end
    80  	idleConnCh map[connectMethodKey]chan *persistConn
    81  	idleLRU    connLRU
    82  
    83  	reqMu       sync.Mutex
    84  	reqCanceler map[*Request]func(error)
    85  
    86  	altMu    sync.Mutex   // guards changing altProto only
    87  	altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme
    88  
    89  	// Proxy specifies a function to return a proxy for a given
    90  	// Request. If the function returns a non-nil error, the
    91  	// request is aborted with the provided error.
    92  	// If Proxy is nil or returns a nil *URL, no proxy is used.
    93  	Proxy func(*Request) (*url.URL, error)
    94  
    95  	// DialContext specifies the dial function for creating unencrypted TCP connections.
    96  	// If DialContext is nil (and the deprecated Dial below is also nil),
    97  	// then the transport dials using package net.
    98  	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
    99  
   100  	// Dial specifies the dial function for creating unencrypted TCP connections.
   101  	//
   102  	// Deprecated: Use DialContext instead, which allows the transport
   103  	// to cancel dials as soon as they are no longer needed.
   104  	// If both are set, DialContext takes priority.
   105  	Dial func(network, addr string) (net.Conn, error)
   106  
   107  	// DialTLS specifies an optional dial function for creating
   108  	// TLS connections for non-proxied HTTPS requests.
   109  	//
   110  	// If DialTLS is nil, Dial and TLSClientConfig are used.
   111  	//
   112  	// If DialTLS is set, the Dial hook is not used for HTTPS
   113  	// requests and the TLSClientConfig and TLSHandshakeTimeout
   114  	// are ignored. The returned net.Conn is assumed to already be
   115  	// past the TLS handshake.
   116  	DialTLS func(network, addr string) (net.Conn, error)
   117  
   118  	// TLSClientConfig specifies the TLS configuration to use with
   119  	// tls.Client.
   120  	// If nil, the default configuration is used.
   121  	// If non-nil, HTTP/2 support may not be enabled by default.
   122  	TLSClientConfig *tls.Config
   123  
   124  	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
   125  	// wait for a TLS handshake. Zero means no timeout.
   126  	TLSHandshakeTimeout time.Duration
   127  
   128  	// DisableKeepAlives, if true, prevents re-use of TCP connections
   129  	// between different HTTP requests.
   130  	DisableKeepAlives bool
   131  
   132  	// DisableCompression, if true, prevents the Transport from
   133  	// requesting compression with an "Accept-Encoding: gzip"
   134  	// request header when the Request contains no existing
   135  	// Accept-Encoding value. If the Transport requests gzip on
   136  	// its own and gets a gzipped response, it's transparently
   137  	// decoded in the Response.Body. However, if the user
   138  	// explicitly requested gzip it is not automatically
   139  	// uncompressed.
   140  	DisableCompression bool
   141  
   142  	// MaxIdleConns controls the maximum number of idle (keep-alive)
   143  	// connections across all hosts. Zero means no limit.
   144  	MaxIdleConns int
   145  
   146  	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
   147  	// (keep-alive) connections to keep per-host. If zero,
   148  	// DefaultMaxIdleConnsPerHost is used.
   149  	MaxIdleConnsPerHost int
   150  
   151  	// IdleConnTimeout is the maximum amount of time an idle
   152  	// (keep-alive) connection will remain idle before closing
   153  	// itself.
   154  	// Zero means no limit.
   155  	IdleConnTimeout time.Duration
   156  
   157  	// ResponseHeaderTimeout, if non-zero, specifies the amount of
   158  	// time to wait for a server's response headers after fully
   159  	// writing the request (including its body, if any). This
   160  	// time does not include the time to read the response body.
   161  	ResponseHeaderTimeout time.Duration
   162  
   163  	// ExpectContinueTimeout, if non-zero, specifies the amount of
   164  	// time to wait for a server's first response headers after fully
   165  	// writing the request headers if the request has an
   166  	// "Expect: 100-continue" header. Zero means no timeout and
   167  	// causes the body to be sent immediately, without
   168  	// waiting for the server to approve.
   169  	// This time does not include the time to send the request header.
   170  	ExpectContinueTimeout time.Duration
   171  
   172  	// TLSNextProto specifies how the Transport switches to an
   173  	// alternate protocol (such as HTTP/2) after a TLS NPN/ALPN
   174  	// protocol negotiation. If Transport dials an TLS connection
   175  	// with a non-empty protocol name and TLSNextProto contains a
   176  	// map entry for that key (such as "h2"), then the func is
   177  	// called with the request's authority (such as "example.com"
   178  	// or "example.com:1234") and the TLS connection. The function
   179  	// must return a RoundTripper that then handles the request.
   180  	// If TLSNextProto is not nil, HTTP/2 support is not enabled
   181  	// automatically.
   182  	TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
   183  
   184  	// ProxyConnectHeader optionally specifies headers to send to
   185  	// proxies during CONNECT requests.
   186  	ProxyConnectHeader Header
   187  
   188  	// MaxResponseHeaderBytes specifies a limit on how many
   189  	// response bytes are allowed in the server's response
   190  	// header.
   191  	//
   192  	// Zero means to use a default limit.
   193  	MaxResponseHeaderBytes int64
   194  
   195  	// nextProtoOnce guards initialization of TLSNextProto and
   196  	// h2transport (via onceSetNextProtoDefaults)
   197  	nextProtoOnce sync.Once
   198  	h2transport   *http2Transport // non-nil if http2 wired up
   199  
   200  	// TODO: tunable on max per-host TCP dials in flight (Issue 13957)
   201  }
   202  
   203  // onceSetNextProtoDefaults initializes TLSNextProto.
   204  // It must be called via t.nextProtoOnce.Do.
   205  func (t *Transport) onceSetNextProtoDefaults() {
   206  	if strings.Contains(os.Getenv("GODEBUG"), "http2client=0") {
   207  		return
   208  	}
   209  	if t.TLSNextProto != nil {
   210  		// This is the documented way to disable http2 on a
   211  		// Transport.
   212  		return
   213  	}
   214  	if t.TLSClientConfig != nil || t.Dial != nil || t.DialTLS != nil {
   215  		// Be conservative and don't automatically enable
   216  		// http2 if they've specified a custom TLS config or
   217  		// custom dialers. Let them opt-in themselves via
   218  		// http2.ConfigureTransport so we don't surprise them
   219  		// by modifying their tls.Config. Issue 14275.
   220  		return
   221  	}
   222  	t2, err := http2configureTransport(t)
   223  	if err != nil {
   224  		log.Printf("Error enabling Transport HTTP/2 support: %v", err)
   225  		return
   226  	}
   227  	t.h2transport = t2
   228  
   229  	// Auto-configure the http2.Transport's MaxHeaderListSize from
   230  	// the http.Transport's MaxResponseHeaderBytes. They don't
   231  	// exactly mean the same thing, but they're close.
   232  	//
   233  	// TODO: also add this to x/net/http2.Configure Transport, behind
   234  	// a +build go1.7 build tag:
   235  	if limit1 := t.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 {
   236  		const h2max = 1<<32 - 1
   237  		if limit1 >= h2max {
   238  			t2.MaxHeaderListSize = h2max
   239  		} else {
   240  			t2.MaxHeaderListSize = uint32(limit1)
   241  		}
   242  	}
   243  }
   244  
   245  // ProxyFromEnvironment returns the URL of the proxy to use for a
   246  // given request, as indicated by the environment variables
   247  // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
   248  // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
   249  // requests.
   250  //
   251  // The environment values may be either a complete URL or a
   252  // "host[:port]", in which case the "http" scheme is assumed.
   253  // An error is returned if the value is a different form.
   254  //
   255  // A nil URL and nil error are returned if no proxy is defined in the
   256  // environment, or a proxy should not be used for the given request,
   257  // as defined by NO_PROXY.
   258  //
   259  // As a special case, if req.URL.Host is "localhost" (with or without
   260  // a port number), then a nil URL and nil error will be returned.
   261  func ProxyFromEnvironment(req *Request) (*url.URL, error) {
   262  	var proxy string
   263  	if req.URL.Scheme == "https" {
   264  		proxy = httpsProxyEnv.Get()
   265  	}
   266  	if proxy == "" {
   267  		proxy = httpProxyEnv.Get()
   268  		if proxy != "" && os.Getenv("REQUEST_METHOD") != "" {
   269  			return nil, errors.New("net/http: refusing to use HTTP_PROXY value in CGI environment; see golang.org/s/cgihttpproxy")
   270  		}
   271  	}
   272  	if proxy == "" {
   273  		return nil, nil
   274  	}
   275  	if !useProxy(canonicalAddr(req.URL)) {
   276  		return nil, nil
   277  	}
   278  	proxyURL, err := url.Parse(proxy)
   279  	if err != nil ||
   280  		(proxyURL.Scheme != "http" &&
   281  			proxyURL.Scheme != "https" &&
   282  			proxyURL.Scheme != "socks5") {
   283  		// proxy was bogus. Try prepending "http://" to it and
   284  		// see if that parses correctly. If not, we fall
   285  		// through and complain about the original one.
   286  		if proxyURL, err := url.Parse("http://" + proxy); err == nil {
   287  			return proxyURL, nil
   288  		}
   289  
   290  	}
   291  	if err != nil {
   292  		return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
   293  	}
   294  	return proxyURL, nil
   295  }
   296  
   297  // ProxyURL returns a proxy function (for use in a Transport)
   298  // that always returns the same URL.
   299  func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
   300  	return func(*Request) (*url.URL, error) {
   301  		return fixedURL, nil
   302  	}
   303  }
   304  
   305  // transportRequest is a wrapper around a *Request that adds
   306  // optional extra headers to write and stores any error to return
   307  // from roundTrip.
   308  type transportRequest struct {
   309  	*Request                        // original request, not to be mutated
   310  	extra    Header                 // extra headers to write, or nil
   311  	trace    *httptrace.ClientTrace // optional
   312  
   313  	mu  sync.Mutex // guards err
   314  	err error      // first setError value for mapRoundTripError to consider
   315  }
   316  
   317  func (tr *transportRequest) extraHeaders() Header {
   318  	if tr.extra == nil {
   319  		tr.extra = make(Header)
   320  	}
   321  	return tr.extra
   322  }
   323  
   324  func (tr *transportRequest) setError(err error) {
   325  	tr.mu.Lock()
   326  	if tr.err == nil {
   327  		tr.err = err
   328  	}
   329  	tr.mu.Unlock()
   330  }
   331  
   332  // RoundTrip implements the RoundTripper interface.
   333  //
   334  // For higher-level HTTP client support (such as handling of cookies
   335  // and redirects), see Get, Post, and the Client type.
   336  func (t *Transport) RoundTrip(req *Request) (*Response, error) {
   337  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   338  	ctx := req.Context()
   339  	trace := httptrace.ContextClientTrace(ctx)
   340  
   341  	if req.URL == nil {
   342  		req.closeBody()
   343  		return nil, errors.New("http: nil Request.URL")
   344  	}
   345  	if req.Header == nil {
   346  		req.closeBody()
   347  		return nil, errors.New("http: nil Request.Header")
   348  	}
   349  	scheme := req.URL.Scheme
   350  	isHTTP := scheme == "http" || scheme == "https"
   351  	if isHTTP {
   352  		for k, vv := range req.Header {
   353  			if !httplex.ValidHeaderFieldName(k) {
   354  				return nil, fmt.Errorf("net/http: invalid header field name %q", k)
   355  			}
   356  			for _, v := range vv {
   357  				if !httplex.ValidHeaderFieldValue(v) {
   358  					return nil, fmt.Errorf("net/http: invalid header field value %q for key %v", v, k)
   359  				}
   360  			}
   361  		}
   362  	}
   363  
   364  	altProto, _ := t.altProto.Load().(map[string]RoundTripper)
   365  	if altRT := altProto[scheme]; altRT != nil {
   366  		if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol {
   367  			return resp, err
   368  		}
   369  	}
   370  	if !isHTTP {
   371  		req.closeBody()
   372  		return nil, &badStringError{"unsupported protocol scheme", scheme}
   373  	}
   374  	if req.Method != "" && !validMethod(req.Method) {
   375  		return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
   376  	}
   377  	if req.URL.Host == "" {
   378  		req.closeBody()
   379  		return nil, errors.New("http: no Host in request URL")
   380  	}
   381  
   382  	for {
   383  		// treq gets modified by roundTrip, so we need to recreate for each retry.
   384  		treq := &transportRequest{Request: req, trace: trace}
   385  		cm, err := t.connectMethodForRequest(treq)
   386  		if err != nil {
   387  			req.closeBody()
   388  			return nil, err
   389  		}
   390  
   391  		// Get the cached or newly-created connection to either the
   392  		// host (for http or https), the http proxy, or the http proxy
   393  		// pre-CONNECTed to https server. In any case, we'll be ready
   394  		// to send it requests.
   395  		pconn, err := t.getConn(treq, cm)
   396  		if err != nil {
   397  			t.setReqCanceler(req, nil)
   398  			req.closeBody()
   399  			return nil, err
   400  		}
   401  
   402  		var resp *Response
   403  		if pconn.alt != nil {
   404  			// HTTP/2 path.
   405  			t.setReqCanceler(req, nil) // not cancelable with CancelRequest
   406  			resp, err = pconn.alt.RoundTrip(req)
   407  		} else {
   408  			resp, err = pconn.roundTrip(treq)
   409  		}
   410  		if err == nil {
   411  			return resp, nil
   412  		}
   413  		if !pconn.shouldRetryRequest(req, err) {
   414  			// Issue 16465: return underlying net.Conn.Read error from peek,
   415  			// as we've historically done.
   416  			if e, ok := err.(transportReadFromServerError); ok {
   417  				err = e.err
   418  			}
   419  			return nil, err
   420  		}
   421  		testHookRoundTripRetried()
   422  	}
   423  }
   424  
   425  // shouldRetryRequest reports whether we should retry sending a failed
   426  // HTTP request on a new connection. The non-nil input error is the
   427  // error from roundTrip.
   428  func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool {
   429  	if err == http2ErrNoCachedConn {
   430  		// Issue 16582: if the user started a bunch of
   431  		// requests at once, they can all pick the same conn
   432  		// and violate the server's max concurrent streams.
   433  		// Instead, match the HTTP/1 behavior for now and dial
   434  		// again to get a new TCP connection, rather than failing
   435  		// this request.
   436  		return true
   437  	}
   438  	if err == errMissingHost {
   439  		// User error.
   440  		return false
   441  	}
   442  	if !pc.isReused() {
   443  		// This was a fresh connection. There's no reason the server
   444  		// should've hung up on us.
   445  		//
   446  		// Also, if we retried now, we could loop forever
   447  		// creating new connections and retrying if the server
   448  		// is just hanging up on us because it doesn't like
   449  		// our request (as opposed to sending an error).
   450  		return false
   451  	}
   452  	if _, ok := err.(nothingWrittenError); ok {
   453  		// We never wrote anything, so it's safe to retry.
   454  		return true
   455  	}
   456  	if !req.isReplayable() {
   457  		// Don't retry non-idempotent requests.
   458  		return false
   459  	}
   460  	if _, ok := err.(transportReadFromServerError); ok {
   461  		// We got some non-EOF net.Conn.Read failure reading
   462  		// the 1st response byte from the server.
   463  		return true
   464  	}
   465  	if err == errServerClosedIdle {
   466  		// The server replied with io.EOF while we were trying to
   467  		// read the response. Probably an unfortunately keep-alive
   468  		// timeout, just as the client was writing a request.
   469  		return true
   470  	}
   471  	return false // conservatively
   472  }
   473  
   474  // ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
   475  var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
   476  
   477  // RegisterProtocol registers a new protocol with scheme.
   478  // The Transport will pass requests using the given scheme to rt.
   479  // It is rt's responsibility to simulate HTTP request semantics.
   480  //
   481  // RegisterProtocol can be used by other packages to provide
   482  // implementations of protocol schemes like "ftp" or "file".
   483  //
   484  // If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will
   485  // handle the RoundTrip itself for that one request, as if the
   486  // protocol were not registered.
   487  func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
   488  	t.altMu.Lock()
   489  	defer t.altMu.Unlock()
   490  	oldMap, _ := t.altProto.Load().(map[string]RoundTripper)
   491  	if _, exists := oldMap[scheme]; exists {
   492  		panic("protocol " + scheme + " already registered")
   493  	}
   494  	newMap := make(map[string]RoundTripper)
   495  	for k, v := range oldMap {
   496  		newMap[k] = v
   497  	}
   498  	newMap[scheme] = rt
   499  	t.altProto.Store(newMap)
   500  }
   501  
   502  // CloseIdleConnections closes any connections which were previously
   503  // connected from previous requests but are now sitting idle in
   504  // a "keep-alive" state. It does not interrupt any connections currently
   505  // in use.
   506  func (t *Transport) CloseIdleConnections() {
   507  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   508  	t.idleMu.Lock()
   509  	m := t.idleConn
   510  	t.idleConn = nil
   511  	t.idleConnCh = nil
   512  	t.wantIdle = true
   513  	t.idleLRU = connLRU{}
   514  	t.idleMu.Unlock()
   515  	for _, conns := range m {
   516  		for _, pconn := range conns {
   517  			pconn.close(errCloseIdleConns)
   518  		}
   519  	}
   520  	if t2 := t.h2transport; t2 != nil {
   521  		t2.CloseIdleConnections()
   522  	}
   523  }
   524  
   525  // CancelRequest cancels an in-flight request by closing its connection.
   526  // CancelRequest should only be called after RoundTrip has returned.
   527  //
   528  // Deprecated: Use Request.WithContext to create a request with a
   529  // cancelable context instead. CancelRequest cannot cancel HTTP/2
   530  // requests.
   531  func (t *Transport) CancelRequest(req *Request) {
   532  	t.cancelRequest(req, errRequestCanceled)
   533  }
   534  
   535  // Cancel an in-flight request, recording the error value.
   536  func (t *Transport) cancelRequest(req *Request, err error) {
   537  	t.reqMu.Lock()
   538  	cancel := t.reqCanceler[req]
   539  	delete(t.reqCanceler, req)
   540  	t.reqMu.Unlock()
   541  	if cancel != nil {
   542  		cancel(err)
   543  	}
   544  }
   545  
   546  //
   547  // Private implementation past this point.
   548  //
   549  
   550  var (
   551  	httpProxyEnv = &envOnce{
   552  		names: []string{"HTTP_PROXY", "http_proxy"},
   553  	}
   554  	httpsProxyEnv = &envOnce{
   555  		names: []string{"HTTPS_PROXY", "https_proxy"},
   556  	}
   557  	noProxyEnv = &envOnce{
   558  		names: []string{"NO_PROXY", "no_proxy"},
   559  	}
   560  )
   561  
   562  // envOnce looks up an environment variable (optionally by multiple
   563  // names) once. It mitigates expensive lookups on some platforms
   564  // (e.g. Windows).
   565  type envOnce struct {
   566  	names []string
   567  	once  sync.Once
   568  	val   string
   569  }
   570  
   571  func (e *envOnce) Get() string {
   572  	e.once.Do(e.init)
   573  	return e.val
   574  }
   575  
   576  func (e *envOnce) init() {
   577  	for _, n := range e.names {
   578  		e.val = os.Getenv(n)
   579  		if e.val != "" {
   580  			return
   581  		}
   582  	}
   583  }
   584  
   585  // reset is used by tests
   586  func (e *envOnce) reset() {
   587  	e.once = sync.Once{}
   588  	e.val = ""
   589  }
   590  
   591  func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) {
   592  	if port := treq.URL.Port(); !validPort(port) {
   593  		return cm, fmt.Errorf("invalid URL port %q", port)
   594  	}
   595  	cm.targetScheme = treq.URL.Scheme
   596  	cm.targetAddr = canonicalAddr(treq.URL)
   597  	if t.Proxy != nil {
   598  		cm.proxyURL, err = t.Proxy(treq.Request)
   599  		if err == nil && cm.proxyURL != nil {
   600  			if port := cm.proxyURL.Port(); !validPort(port) {
   601  				return cm, fmt.Errorf("invalid proxy URL port %q", port)
   602  			}
   603  		}
   604  	}
   605  	return cm, err
   606  }
   607  
   608  // proxyAuth returns the Proxy-Authorization header to set
   609  // on requests, if applicable.
   610  func (cm *connectMethod) proxyAuth() string {
   611  	if cm.proxyURL == nil {
   612  		return ""
   613  	}
   614  	if u := cm.proxyURL.User; u != nil {
   615  		username := u.Username()
   616  		password, _ := u.Password()
   617  		return "Basic " + basicAuth(username, password)
   618  	}
   619  	return ""
   620  }
   621  
   622  // error values for debugging and testing, not seen by users.
   623  var (
   624  	errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
   625  	errConnBroken         = errors.New("http: putIdleConn: connection is in bad state")
   626  	errWantIdle           = errors.New("http: putIdleConn: CloseIdleConnections was called")
   627  	errTooManyIdle        = errors.New("http: putIdleConn: too many idle connections")
   628  	errTooManyIdleHost    = errors.New("http: putIdleConn: too many idle connections for host")
   629  	errCloseIdleConns     = errors.New("http: CloseIdleConnections called")
   630  	errReadLoopExiting    = errors.New("http: persistConn.readLoop exiting")
   631  	errServerClosedIdle   = errors.New("http: server closed idle connection")
   632  	errIdleConnTimeout    = errors.New("http: idle connection timeout")
   633  	errNotCachingH2Conn   = errors.New("http: not caching alternate protocol's connections")
   634  )
   635  
   636  // transportReadFromServerError is used by Transport.readLoop when the
   637  // 1 byte peek read fails and we're actually anticipating a response.
   638  // Usually this is just due to the inherent keep-alive shut down race,
   639  // where the server closed the connection at the same time the client
   640  // wrote. The underlying err field is usually io.EOF or some
   641  // ECONNRESET sort of thing which varies by platform. But it might be
   642  // the user's custom net.Conn.Read error too, so we carry it along for
   643  // them to return from Transport.RoundTrip.
   644  type transportReadFromServerError struct {
   645  	err error
   646  }
   647  
   648  func (e transportReadFromServerError) Error() string {
   649  	return fmt.Sprintf("net/http: Transport failed to read from server: %v", e.err)
   650  }
   651  
   652  func (t *Transport) putOrCloseIdleConn(pconn *persistConn) {
   653  	if err := t.tryPutIdleConn(pconn); err != nil {
   654  		pconn.close(err)
   655  	}
   656  }
   657  
   658  func (t *Transport) maxIdleConnsPerHost() int {
   659  	if v := t.MaxIdleConnsPerHost; v != 0 {
   660  		return v
   661  	}
   662  	return DefaultMaxIdleConnsPerHost
   663  }
   664  
   665  // tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
   666  // a new request.
   667  // If pconn is no longer needed or not in a good state, tryPutIdleConn returns
   668  // an error explaining why it wasn't registered.
   669  // tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that.
   670  func (t *Transport) tryPutIdleConn(pconn *persistConn) error {
   671  	if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
   672  		return errKeepAlivesDisabled
   673  	}
   674  	if pconn.isBroken() {
   675  		return errConnBroken
   676  	}
   677  	if pconn.alt != nil {
   678  		return errNotCachingH2Conn
   679  	}
   680  	pconn.markReused()
   681  	key := pconn.cacheKey
   682  
   683  	t.idleMu.Lock()
   684  	defer t.idleMu.Unlock()
   685  
   686  	waitingDialer := t.idleConnCh[key]
   687  	select {
   688  	case waitingDialer <- pconn:
   689  		// We're done with this pconn and somebody else is
   690  		// currently waiting for a conn of this type (they're
   691  		// actively dialing, but this conn is ready
   692  		// first). Chrome calls this socket late binding. See
   693  		// https://insouciant.org/tech/connection-management-in-chromium/
   694  		return nil
   695  	default:
   696  		if waitingDialer != nil {
   697  			// They had populated this, but their dial won
   698  			// first, so we can clean up this map entry.
   699  			delete(t.idleConnCh, key)
   700  		}
   701  	}
   702  	if t.wantIdle {
   703  		return errWantIdle
   704  	}
   705  	if t.idleConn == nil {
   706  		t.idleConn = make(map[connectMethodKey][]*persistConn)
   707  	}
   708  	idles := t.idleConn[key]
   709  	if len(idles) >= t.maxIdleConnsPerHost() {
   710  		return errTooManyIdleHost
   711  	}
   712  	for _, exist := range idles {
   713  		if exist == pconn {
   714  			log.Fatalf("dup idle pconn %p in freelist", pconn)
   715  		}
   716  	}
   717  	t.idleConn[key] = append(idles, pconn)
   718  	t.idleLRU.add(pconn)
   719  	if t.MaxIdleConns != 0 && t.idleLRU.len() > t.MaxIdleConns {
   720  		oldest := t.idleLRU.removeOldest()
   721  		oldest.close(errTooManyIdle)
   722  		t.removeIdleConnLocked(oldest)
   723  	}
   724  	if t.IdleConnTimeout > 0 {
   725  		if pconn.idleTimer != nil {
   726  			pconn.idleTimer.Reset(t.IdleConnTimeout)
   727  		} else {
   728  			pconn.idleTimer = time.AfterFunc(t.IdleConnTimeout, pconn.closeConnIfStillIdle)
   729  		}
   730  	}
   731  	pconn.idleAt = time.Now()
   732  	return nil
   733  }
   734  
   735  // getIdleConnCh returns a channel to receive and return idle
   736  // persistent connection for the given connectMethod.
   737  // It may return nil, if persistent connections are not being used.
   738  func (t *Transport) getIdleConnCh(cm connectMethod) chan *persistConn {
   739  	if t.DisableKeepAlives {
   740  		return nil
   741  	}
   742  	key := cm.key()
   743  	t.idleMu.Lock()
   744  	defer t.idleMu.Unlock()
   745  	t.wantIdle = false
   746  	if t.idleConnCh == nil {
   747  		t.idleConnCh = make(map[connectMethodKey]chan *persistConn)
   748  	}
   749  	ch, ok := t.idleConnCh[key]
   750  	if !ok {
   751  		ch = make(chan *persistConn)
   752  		t.idleConnCh[key] = ch
   753  	}
   754  	return ch
   755  }
   756  
   757  func (t *Transport) getIdleConn(cm connectMethod) (pconn *persistConn, idleSince time.Time) {
   758  	key := cm.key()
   759  	t.idleMu.Lock()
   760  	defer t.idleMu.Unlock()
   761  	for {
   762  		pconns, ok := t.idleConn[key]
   763  		if !ok {
   764  			return nil, time.Time{}
   765  		}
   766  		if len(pconns) == 1 {
   767  			pconn = pconns[0]
   768  			delete(t.idleConn, key)
   769  		} else {
   770  			// 2 or more cached connections; use the most
   771  			// recently used one at the end.
   772  			pconn = pconns[len(pconns)-1]
   773  			t.idleConn[key] = pconns[:len(pconns)-1]
   774  		}
   775  		t.idleLRU.remove(pconn)
   776  		if pconn.isBroken() {
   777  			// There is a tiny window where this is
   778  			// possible, between the connecting dying and
   779  			// the persistConn readLoop calling
   780  			// Transport.removeIdleConn. Just skip it and
   781  			// carry on.
   782  			continue
   783  		}
   784  		if pconn.idleTimer != nil && !pconn.idleTimer.Stop() {
   785  			// We picked this conn at the ~same time it
   786  			// was expiring and it's trying to close
   787  			// itself in another goroutine. Don't use it.
   788  			continue
   789  		}
   790  		return pconn, pconn.idleAt
   791  	}
   792  }
   793  
   794  // removeIdleConn marks pconn as dead.
   795  func (t *Transport) removeIdleConn(pconn *persistConn) {
   796  	t.idleMu.Lock()
   797  	defer t.idleMu.Unlock()
   798  	t.removeIdleConnLocked(pconn)
   799  }
   800  
   801  // t.idleMu must be held.
   802  func (t *Transport) removeIdleConnLocked(pconn *persistConn) {
   803  	if pconn.idleTimer != nil {
   804  		pconn.idleTimer.Stop()
   805  	}
   806  	t.idleLRU.remove(pconn)
   807  	key := pconn.cacheKey
   808  	pconns := t.idleConn[key]
   809  	switch len(pconns) {
   810  	case 0:
   811  		// Nothing
   812  	case 1:
   813  		if pconns[0] == pconn {
   814  			delete(t.idleConn, key)
   815  		}
   816  	default:
   817  		for i, v := range pconns {
   818  			if v != pconn {
   819  				continue
   820  			}
   821  			// Slide down, keeping most recently-used
   822  			// conns at the end.
   823  			copy(pconns[i:], pconns[i+1:])
   824  			t.idleConn[key] = pconns[:len(pconns)-1]
   825  			break
   826  		}
   827  	}
   828  }
   829  
   830  func (t *Transport) setReqCanceler(r *Request, fn func(error)) {
   831  	t.reqMu.Lock()
   832  	defer t.reqMu.Unlock()
   833  	if t.reqCanceler == nil {
   834  		t.reqCanceler = make(map[*Request]func(error))
   835  	}
   836  	if fn != nil {
   837  		t.reqCanceler[r] = fn
   838  	} else {
   839  		delete(t.reqCanceler, r)
   840  	}
   841  }
   842  
   843  // replaceReqCanceler replaces an existing cancel function. If there is no cancel function
   844  // for the request, we don't set the function and return false.
   845  // Since CancelRequest will clear the canceler, we can use the return value to detect if
   846  // the request was canceled since the last setReqCancel call.
   847  func (t *Transport) replaceReqCanceler(r *Request, fn func(error)) bool {
   848  	t.reqMu.Lock()
   849  	defer t.reqMu.Unlock()
   850  	_, ok := t.reqCanceler[r]
   851  	if !ok {
   852  		return false
   853  	}
   854  	if fn != nil {
   855  		t.reqCanceler[r] = fn
   856  	} else {
   857  		delete(t.reqCanceler, r)
   858  	}
   859  	return true
   860  }
   861  
   862  var zeroDialer net.Dialer
   863  
   864  func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error) {
   865  	if t.DialContext != nil {
   866  		return t.DialContext(ctx, network, addr)
   867  	}
   868  	if t.Dial != nil {
   869  		c, err := t.Dial(network, addr)
   870  		if c == nil && err == nil {
   871  			err = errors.New("net/http: Transport.Dial hook returned (nil, nil)")
   872  		}
   873  		return c, err
   874  	}
   875  	return zeroDialer.DialContext(ctx, network, addr)
   876  }
   877  
   878  // getConn dials and creates a new persistConn to the target as
   879  // specified in the connectMethod. This includes doing a proxy CONNECT
   880  // and/or setting up TLS.  If this doesn't return an error, the persistConn
   881  // is ready to write requests to.
   882  func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (*persistConn, error) {
   883  	req := treq.Request
   884  	trace := treq.trace
   885  	ctx := req.Context()
   886  	if trace != nil && trace.GetConn != nil {
   887  		trace.GetConn(cm.addr())
   888  	}
   889  	if pc, idleSince := t.getIdleConn(cm); pc != nil {
   890  		if trace != nil && trace.GotConn != nil {
   891  			trace.GotConn(pc.gotIdleConnTrace(idleSince))
   892  		}
   893  		// set request canceler to some non-nil function so we
   894  		// can detect whether it was cleared between now and when
   895  		// we enter roundTrip
   896  		t.setReqCanceler(req, func(error) {})
   897  		return pc, nil
   898  	}
   899  
   900  	type dialRes struct {
   901  		pc  *persistConn
   902  		err error
   903  	}
   904  	dialc := make(chan dialRes)
   905  
   906  	// Copy these hooks so we don't race on the postPendingDial in
   907  	// the goroutine we launch. Issue 11136.
   908  	testHookPrePendingDial := testHookPrePendingDial
   909  	testHookPostPendingDial := testHookPostPendingDial
   910  
   911  	handlePendingDial := func() {
   912  		testHookPrePendingDial()
   913  		go func() {
   914  			if v := <-dialc; v.err == nil {
   915  				t.putOrCloseIdleConn(v.pc)
   916  			}
   917  			testHookPostPendingDial()
   918  		}()
   919  	}
   920  
   921  	cancelc := make(chan error, 1)
   922  	t.setReqCanceler(req, func(err error) { cancelc <- err })
   923  
   924  	go func() {
   925  		pc, err := t.dialConn(ctx, cm)
   926  		dialc <- dialRes{pc, err}
   927  	}()
   928  
   929  	idleConnCh := t.getIdleConnCh(cm)
   930  	select {
   931  	case v := <-dialc:
   932  		// Our dial finished.
   933  		if v.pc != nil {
   934  			if trace != nil && trace.GotConn != nil && v.pc.alt == nil {
   935  				trace.GotConn(httptrace.GotConnInfo{Conn: v.pc.conn})
   936  			}
   937  			return v.pc, nil
   938  		}
   939  		// Our dial failed. See why to return a nicer error
   940  		// value.
   941  		select {
   942  		case <-req.Cancel:
   943  			// It was an error due to cancelation, so prioritize that
   944  			// error value. (Issue 16049)
   945  			return nil, errRequestCanceledConn
   946  		case <-req.Context().Done():
   947  			return nil, req.Context().Err()
   948  		case err := <-cancelc:
   949  			if err == errRequestCanceled {
   950  				err = errRequestCanceledConn
   951  			}
   952  			return nil, err
   953  		default:
   954  			// It wasn't an error due to cancelation, so
   955  			// return the original error message:
   956  			return nil, v.err
   957  		}
   958  	case pc := <-idleConnCh:
   959  		// Another request finished first and its net.Conn
   960  		// became available before our dial. Or somebody
   961  		// else's dial that they didn't use.
   962  		// But our dial is still going, so give it away
   963  		// when it finishes:
   964  		handlePendingDial()
   965  		if trace != nil && trace.GotConn != nil {
   966  			trace.GotConn(httptrace.GotConnInfo{Conn: pc.conn, Reused: pc.isReused()})
   967  		}
   968  		return pc, nil
   969  	case <-req.Cancel:
   970  		handlePendingDial()
   971  		return nil, errRequestCanceledConn
   972  	case <-req.Context().Done():
   973  		handlePendingDial()
   974  		return nil, req.Context().Err()
   975  	case err := <-cancelc:
   976  		handlePendingDial()
   977  		if err == errRequestCanceled {
   978  			err = errRequestCanceledConn
   979  		}
   980  		return nil, err
   981  	}
   982  }
   983  
   984  type oneConnDialer <-chan net.Conn
   985  
   986  func newOneConnDialer(c net.Conn) proxy.Dialer {
   987  	ch := make(chan net.Conn, 1)
   988  	ch <- c
   989  	return oneConnDialer(ch)
   990  }
   991  
   992  func (d oneConnDialer) Dial(network, addr string) (net.Conn, error) {
   993  	select {
   994  	case c := <-d:
   995  		return c, nil
   996  	default:
   997  		return nil, io.EOF
   998  	}
   999  }
  1000  
  1001  func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (*persistConn, error) {
  1002  	pconn := &persistConn{
  1003  		t:             t,
  1004  		cacheKey:      cm.key(),
  1005  		reqch:         make(chan requestAndChan, 1),
  1006  		writech:       make(chan writeRequest, 1),
  1007  		closech:       make(chan struct{}),
  1008  		writeErrCh:    make(chan error, 1),
  1009  		writeLoopDone: make(chan struct{}),
  1010  	}
  1011  	trace := httptrace.ContextClientTrace(ctx)
  1012  	tlsDial := t.DialTLS != nil && cm.targetScheme == "https" && cm.proxyURL == nil
  1013  	if tlsDial {
  1014  		var err error
  1015  		pconn.conn, err = t.DialTLS("tcp", cm.addr())
  1016  		if err != nil {
  1017  			return nil, err
  1018  		}
  1019  		if pconn.conn == nil {
  1020  			return nil, errors.New("net/http: Transport.DialTLS returned (nil, nil)")
  1021  		}
  1022  		if tc, ok := pconn.conn.(*tls.Conn); ok {
  1023  			// Handshake here, in case DialTLS didn't. TLSNextProto below
  1024  			// depends on it for knowing the connection state.
  1025  			if trace != nil && trace.TLSHandshakeStart != nil {
  1026  				trace.TLSHandshakeStart()
  1027  			}
  1028  			if err := tc.Handshake(); err != nil {
  1029  				go pconn.conn.Close()
  1030  				if trace != nil && trace.TLSHandshakeDone != nil {
  1031  					trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1032  				}
  1033  				return nil, err
  1034  			}
  1035  			cs := tc.ConnectionState()
  1036  			if trace != nil && trace.TLSHandshakeDone != nil {
  1037  				trace.TLSHandshakeDone(cs, nil)
  1038  			}
  1039  			pconn.tlsState = &cs
  1040  		}
  1041  	} else {
  1042  		conn, err := t.dial(ctx, "tcp", cm.addr())
  1043  		if err != nil {
  1044  			if cm.proxyURL != nil {
  1045  				// Return a typed error, per Issue 16997:
  1046  				err = &net.OpError{Op: "proxyconnect", Net: "tcp", Err: err}
  1047  			}
  1048  			return nil, err
  1049  		}
  1050  		pconn.conn = conn
  1051  	}
  1052  
  1053  	// Proxy setup.
  1054  	switch {
  1055  	case cm.proxyURL == nil:
  1056  		// Do nothing. Not using a proxy.
  1057  	case cm.proxyURL.Scheme == "socks5":
  1058  		conn := pconn.conn
  1059  		var auth *proxy.Auth
  1060  		if u := cm.proxyURL.User; u != nil {
  1061  			auth = &proxy.Auth{}
  1062  			auth.User = u.Username()
  1063  			auth.Password, _ = u.Password()
  1064  		}
  1065  		p, err := proxy.SOCKS5("", cm.addr(), auth, newOneConnDialer(conn))
  1066  		if err != nil {
  1067  			conn.Close()
  1068  			return nil, err
  1069  		}
  1070  		if _, err := p.Dial("tcp", cm.targetAddr); err != nil {
  1071  			conn.Close()
  1072  			return nil, err
  1073  		}
  1074  	case cm.targetScheme == "http":
  1075  		pconn.isProxy = true
  1076  		if pa := cm.proxyAuth(); pa != "" {
  1077  			pconn.mutateHeaderFunc = func(h Header) {
  1078  				h.Set("Proxy-Authorization", pa)
  1079  			}
  1080  		}
  1081  	case cm.targetScheme == "https":
  1082  		conn := pconn.conn
  1083  		hdr := t.ProxyConnectHeader
  1084  		if hdr == nil {
  1085  			hdr = make(Header)
  1086  		}
  1087  		connectReq := &Request{
  1088  			Method: "CONNECT",
  1089  			URL:    &url.URL{Opaque: cm.targetAddr},
  1090  			Host:   cm.targetAddr,
  1091  			Header: hdr,
  1092  		}
  1093  		if pa := cm.proxyAuth(); pa != "" {
  1094  			connectReq.Header.Set("Proxy-Authorization", pa)
  1095  		}
  1096  		connectReq.Write(conn)
  1097  
  1098  		// Read response.
  1099  		// Okay to use and discard buffered reader here, because
  1100  		// TLS server will not speak until spoken to.
  1101  		br := bufio.NewReader(conn)
  1102  		resp, err := ReadResponse(br, connectReq)
  1103  		if err != nil {
  1104  			conn.Close()
  1105  			return nil, err
  1106  		}
  1107  		if resp.StatusCode != 200 {
  1108  			f := strings.SplitN(resp.Status, " ", 2)
  1109  			conn.Close()
  1110  			return nil, errors.New(f[1])
  1111  		}
  1112  	}
  1113  
  1114  	if cm.targetScheme == "https" && !tlsDial {
  1115  		// Initiate TLS and check remote host name against certificate.
  1116  		cfg := cloneTLSConfig(t.TLSClientConfig)
  1117  		if cfg.ServerName == "" {
  1118  			cfg.ServerName = cm.tlsHost()
  1119  		}
  1120  		plainConn := pconn.conn
  1121  		tlsConn := tls.Client(plainConn, cfg)
  1122  		errc := make(chan error, 2)
  1123  		var timer *time.Timer // for canceling TLS handshake
  1124  		if d := t.TLSHandshakeTimeout; d != 0 {
  1125  			timer = time.AfterFunc(d, func() {
  1126  				errc <- tlsHandshakeTimeoutError{}
  1127  			})
  1128  		}
  1129  		go func() {
  1130  			if trace != nil && trace.TLSHandshakeStart != nil {
  1131  				trace.TLSHandshakeStart()
  1132  			}
  1133  			err := tlsConn.Handshake()
  1134  			if timer != nil {
  1135  				timer.Stop()
  1136  			}
  1137  			errc <- err
  1138  		}()
  1139  		if err := <-errc; err != nil {
  1140  			plainConn.Close()
  1141  			if trace != nil && trace.TLSHandshakeDone != nil {
  1142  				trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1143  			}
  1144  			return nil, err
  1145  		}
  1146  		if !cfg.InsecureSkipVerify {
  1147  			if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  1148  				plainConn.Close()
  1149  				return nil, err
  1150  			}
  1151  		}
  1152  		cs := tlsConn.ConnectionState()
  1153  		if trace != nil && trace.TLSHandshakeDone != nil {
  1154  			trace.TLSHandshakeDone(cs, nil)
  1155  		}
  1156  		pconn.tlsState = &cs
  1157  		pconn.conn = tlsConn
  1158  	}
  1159  
  1160  	if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" {
  1161  		if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; ok {
  1162  			return &persistConn{alt: next(cm.targetAddr, pconn.conn.(*tls.Conn))}, nil
  1163  		}
  1164  	}
  1165  
  1166  	pconn.br = bufio.NewReader(pconn)
  1167  	pconn.bw = bufio.NewWriter(persistConnWriter{pconn})
  1168  	go pconn.readLoop()
  1169  	go pconn.writeLoop()
  1170  	return pconn, nil
  1171  }
  1172  
  1173  // persistConnWriter is the io.Writer written to by pc.bw.
  1174  // It accumulates the number of bytes written to the underlying conn,
  1175  // so the retry logic can determine whether any bytes made it across
  1176  // the wire.
  1177  // This is exactly 1 pointer field wide so it can go into an interface
  1178  // without allocation.
  1179  type persistConnWriter struct {
  1180  	pc *persistConn
  1181  }
  1182  
  1183  func (w persistConnWriter) Write(p []byte) (n int, err error) {
  1184  	n, err = w.pc.conn.Write(p)
  1185  	w.pc.nwrite += int64(n)
  1186  	return
  1187  }
  1188  
  1189  // useProxy reports whether requests to addr should use a proxy,
  1190  // according to the NO_PROXY or no_proxy environment variable.
  1191  // addr is always a canonicalAddr with a host and port.
  1192  func useProxy(addr string) bool {
  1193  	if len(addr) == 0 {
  1194  		return true
  1195  	}
  1196  	host, _, err := net.SplitHostPort(addr)
  1197  	if err != nil {
  1198  		return false
  1199  	}
  1200  	if host == "localhost" {
  1201  		return false
  1202  	}
  1203  	if ip := net.ParseIP(host); ip != nil {
  1204  		if ip.IsLoopback() {
  1205  			return false
  1206  		}
  1207  	}
  1208  
  1209  	no_proxy := noProxyEnv.Get()
  1210  	if no_proxy == "*" {
  1211  		return false
  1212  	}
  1213  
  1214  	addr = strings.ToLower(strings.TrimSpace(addr))
  1215  	if hasPort(addr) {
  1216  		addr = addr[:strings.LastIndex(addr, ":")]
  1217  	}
  1218  
  1219  	for _, p := range strings.Split(no_proxy, ",") {
  1220  		p = strings.ToLower(strings.TrimSpace(p))
  1221  		if len(p) == 0 {
  1222  			continue
  1223  		}
  1224  		if hasPort(p) {
  1225  			p = p[:strings.LastIndex(p, ":")]
  1226  		}
  1227  		if addr == p {
  1228  			return false
  1229  		}
  1230  		if len(p) == 0 {
  1231  			// There is no host part, likely the entry is malformed; ignore.
  1232  			continue
  1233  		}
  1234  		if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) {
  1235  			// no_proxy ".foo.com" matches "bar.foo.com" or "foo.com"
  1236  			return false
  1237  		}
  1238  		if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' {
  1239  			// no_proxy "foo.com" matches "bar.foo.com"
  1240  			return false
  1241  		}
  1242  	}
  1243  	return true
  1244  }
  1245  
  1246  // connectMethod is the map key (in its String form) for keeping persistent
  1247  // TCP connections alive for subsequent HTTP requests.
  1248  //
  1249  // A connect method may be of the following types:
  1250  //
  1251  // Cache key form                    Description
  1252  // -----------------                 -------------------------
  1253  // |http|foo.com                     http directly to server, no proxy
  1254  // |https|foo.com                    https directly to server, no proxy
  1255  // http://proxy.com|https|foo.com    http to proxy, then CONNECT to foo.com
  1256  // http://proxy.com|http             http to proxy, http to anywhere after that
  1257  // socks5://proxy.com|http|foo.com   socks5 to proxy, then http to foo.com
  1258  // socks5://proxy.com|https|foo.com  socks5 to proxy, then https to foo.com
  1259  //
  1260  // Note: no support to https to the proxy yet.
  1261  //
  1262  type connectMethod struct {
  1263  	proxyURL     *url.URL // nil for no proxy, else full proxy URL
  1264  	targetScheme string   // "http" or "https"
  1265  	targetAddr   string   // Not used if http proxy + http targetScheme (4th example in table)
  1266  }
  1267  
  1268  func (cm *connectMethod) key() connectMethodKey {
  1269  	proxyStr := ""
  1270  	targetAddr := cm.targetAddr
  1271  	if cm.proxyURL != nil {
  1272  		proxyStr = cm.proxyURL.String()
  1273  		if strings.HasPrefix(cm.proxyURL.Scheme, "http") && cm.targetScheme == "http" {
  1274  			targetAddr = ""
  1275  		}
  1276  	}
  1277  	return connectMethodKey{
  1278  		proxy:  proxyStr,
  1279  		scheme: cm.targetScheme,
  1280  		addr:   targetAddr,
  1281  	}
  1282  }
  1283  
  1284  // addr returns the first hop "host:port" to which we need to TCP connect.
  1285  func (cm *connectMethod) addr() string {
  1286  	if cm.proxyURL != nil {
  1287  		return canonicalAddr(cm.proxyURL)
  1288  	}
  1289  	return cm.targetAddr
  1290  }
  1291  
  1292  // tlsHost returns the host name to match against the peer's
  1293  // TLS certificate.
  1294  func (cm *connectMethod) tlsHost() string {
  1295  	h := cm.targetAddr
  1296  	if hasPort(h) {
  1297  		h = h[:strings.LastIndex(h, ":")]
  1298  	}
  1299  	return h
  1300  }
  1301  
  1302  // connectMethodKey is the map key version of connectMethod, with a
  1303  // stringified proxy URL (or the empty string) instead of a pointer to
  1304  // a URL.
  1305  type connectMethodKey struct {
  1306  	proxy, scheme, addr string
  1307  }
  1308  
  1309  func (k connectMethodKey) String() string {
  1310  	// Only used by tests.
  1311  	return fmt.Sprintf("%s|%s|%s", k.proxy, k.scheme, k.addr)
  1312  }
  1313  
  1314  // persistConn wraps a connection, usually a persistent one
  1315  // (but may be used for non-keep-alive requests as well)
  1316  type persistConn struct {
  1317  	// alt optionally specifies the TLS NextProto RoundTripper.
  1318  	// This is used for HTTP/2 today and future protocols later.
  1319  	// If it's non-nil, the rest of the fields are unused.
  1320  	alt RoundTripper
  1321  
  1322  	t         *Transport
  1323  	cacheKey  connectMethodKey
  1324  	conn      net.Conn
  1325  	tlsState  *tls.ConnectionState
  1326  	br        *bufio.Reader       // from conn
  1327  	bw        *bufio.Writer       // to conn
  1328  	nwrite    int64               // bytes written
  1329  	reqch     chan requestAndChan // written by roundTrip; read by readLoop
  1330  	writech   chan writeRequest   // written by roundTrip; read by writeLoop
  1331  	closech   chan struct{}       // closed when conn closed
  1332  	isProxy   bool
  1333  	sawEOF    bool  // whether we've seen EOF from conn; owned by readLoop
  1334  	readLimit int64 // bytes allowed to be read; owned by readLoop
  1335  	// writeErrCh passes the request write error (usually nil)
  1336  	// from the writeLoop goroutine to the readLoop which passes
  1337  	// it off to the res.Body reader, which then uses it to decide
  1338  	// whether or not a connection can be reused. Issue 7569.
  1339  	writeErrCh chan error
  1340  
  1341  	writeLoopDone chan struct{} // closed when write loop ends
  1342  
  1343  	// Both guarded by Transport.idleMu:
  1344  	idleAt    time.Time   // time it last become idle
  1345  	idleTimer *time.Timer // holding an AfterFunc to close it
  1346  
  1347  	mu                   sync.Mutex // guards following fields
  1348  	numExpectedResponses int
  1349  	closed               error // set non-nil when conn is closed, before closech is closed
  1350  	canceledErr          error // set non-nil if conn is canceled
  1351  	broken               bool  // an error has happened on this connection; marked broken so it's not reused.
  1352  	reused               bool  // whether conn has had successful request/response and is being reused.
  1353  	// mutateHeaderFunc is an optional func to modify extra
  1354  	// headers on each outbound request before it's written. (the
  1355  	// original Request given to RoundTrip is not modified)
  1356  	mutateHeaderFunc func(Header)
  1357  }
  1358  
  1359  func (pc *persistConn) maxHeaderResponseSize() int64 {
  1360  	if v := pc.t.MaxResponseHeaderBytes; v != 0 {
  1361  		return v
  1362  	}
  1363  	return 10 << 20 // conservative default; same as http2
  1364  }
  1365  
  1366  func (pc *persistConn) Read(p []byte) (n int, err error) {
  1367  	if pc.readLimit <= 0 {
  1368  		return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize())
  1369  	}
  1370  	if int64(len(p)) > pc.readLimit {
  1371  		p = p[:pc.readLimit]
  1372  	}
  1373  	n, err = pc.conn.Read(p)
  1374  	if err == io.EOF {
  1375  		pc.sawEOF = true
  1376  	}
  1377  	pc.readLimit -= int64(n)
  1378  	return
  1379  }
  1380  
  1381  // isBroken reports whether this connection is in a known broken state.
  1382  func (pc *persistConn) isBroken() bool {
  1383  	pc.mu.Lock()
  1384  	b := pc.closed != nil
  1385  	pc.mu.Unlock()
  1386  	return b
  1387  }
  1388  
  1389  // canceled returns non-nil if the connection was closed due to
  1390  // CancelRequest or due to context cancelation.
  1391  func (pc *persistConn) canceled() error {
  1392  	pc.mu.Lock()
  1393  	defer pc.mu.Unlock()
  1394  	return pc.canceledErr
  1395  }
  1396  
  1397  // isReused reports whether this connection is in a known broken state.
  1398  func (pc *persistConn) isReused() bool {
  1399  	pc.mu.Lock()
  1400  	r := pc.reused
  1401  	pc.mu.Unlock()
  1402  	return r
  1403  }
  1404  
  1405  func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo) {
  1406  	pc.mu.Lock()
  1407  	defer pc.mu.Unlock()
  1408  	t.Reused = pc.reused
  1409  	t.Conn = pc.conn
  1410  	t.WasIdle = true
  1411  	if !idleAt.IsZero() {
  1412  		t.IdleTime = time.Since(idleAt)
  1413  	}
  1414  	return
  1415  }
  1416  
  1417  func (pc *persistConn) cancelRequest(err error) {
  1418  	pc.mu.Lock()
  1419  	defer pc.mu.Unlock()
  1420  	pc.canceledErr = err
  1421  	pc.closeLocked(errRequestCanceled)
  1422  }
  1423  
  1424  // closeConnIfStillIdle closes the connection if it's still sitting idle.
  1425  // This is what's called by the persistConn's idleTimer, and is run in its
  1426  // own goroutine.
  1427  func (pc *persistConn) closeConnIfStillIdle() {
  1428  	t := pc.t
  1429  	t.idleMu.Lock()
  1430  	defer t.idleMu.Unlock()
  1431  	if _, ok := t.idleLRU.m[pc]; !ok {
  1432  		// Not idle.
  1433  		return
  1434  	}
  1435  	t.removeIdleConnLocked(pc)
  1436  	pc.close(errIdleConnTimeout)
  1437  }
  1438  
  1439  // mapRoundTripError returns the appropriate error value for
  1440  // persistConn.roundTrip.
  1441  //
  1442  // The provided err is the first error that (*persistConn).roundTrip
  1443  // happened to receive from its select statement.
  1444  //
  1445  // The startBytesWritten value should be the value of pc.nwrite before the roundTrip
  1446  // started writing the request.
  1447  func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error {
  1448  	if err == nil {
  1449  		return nil
  1450  	}
  1451  
  1452  	// If the request was canceled, that's better than network
  1453  	// failures that were likely the result of tearing down the
  1454  	// connection.
  1455  	if cerr := pc.canceled(); cerr != nil {
  1456  		return cerr
  1457  	}
  1458  
  1459  	// See if an error was set explicitly.
  1460  	req.mu.Lock()
  1461  	reqErr := req.err
  1462  	req.mu.Unlock()
  1463  	if reqErr != nil {
  1464  		return reqErr
  1465  	}
  1466  
  1467  	if err == errServerClosedIdle {
  1468  		// Don't decorate
  1469  		return err
  1470  	}
  1471  
  1472  	if _, ok := err.(transportReadFromServerError); ok {
  1473  		// Don't decorate
  1474  		return err
  1475  	}
  1476  	if pc.isBroken() {
  1477  		<-pc.writeLoopDone
  1478  		if pc.nwrite == startBytesWritten && req.outgoingLength() == 0 {
  1479  			return nothingWrittenError{err}
  1480  		}
  1481  		return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %v", err)
  1482  	}
  1483  	return err
  1484  }
  1485  
  1486  func (pc *persistConn) readLoop() {
  1487  	closeErr := errReadLoopExiting // default value, if not changed below
  1488  	defer func() {
  1489  		pc.close(closeErr)
  1490  		pc.t.removeIdleConn(pc)
  1491  	}()
  1492  
  1493  	tryPutIdleConn := func(trace *httptrace.ClientTrace) bool {
  1494  		if err := pc.t.tryPutIdleConn(pc); err != nil {
  1495  			closeErr = err
  1496  			if trace != nil && trace.PutIdleConn != nil && err != errKeepAlivesDisabled {
  1497  				trace.PutIdleConn(err)
  1498  			}
  1499  			return false
  1500  		}
  1501  		if trace != nil && trace.PutIdleConn != nil {
  1502  			trace.PutIdleConn(nil)
  1503  		}
  1504  		return true
  1505  	}
  1506  
  1507  	// eofc is used to block caller goroutines reading from Response.Body
  1508  	// at EOF until this goroutines has (potentially) added the connection
  1509  	// back to the idle pool.
  1510  	eofc := make(chan struct{})
  1511  	defer close(eofc) // unblock reader on errors
  1512  
  1513  	// Read this once, before loop starts. (to avoid races in tests)
  1514  	testHookMu.Lock()
  1515  	testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead
  1516  	testHookMu.Unlock()
  1517  
  1518  	alive := true
  1519  	for alive {
  1520  		pc.readLimit = pc.maxHeaderResponseSize()
  1521  		_, err := pc.br.Peek(1)
  1522  
  1523  		pc.mu.Lock()
  1524  		if pc.numExpectedResponses == 0 {
  1525  			pc.readLoopPeekFailLocked(err)
  1526  			pc.mu.Unlock()
  1527  			return
  1528  		}
  1529  		pc.mu.Unlock()
  1530  
  1531  		rc := <-pc.reqch
  1532  		trace := httptrace.ContextClientTrace(rc.req.Context())
  1533  
  1534  		var resp *Response
  1535  		if err == nil {
  1536  			resp, err = pc.readResponse(rc, trace)
  1537  		} else {
  1538  			err = transportReadFromServerError{err}
  1539  			closeErr = err
  1540  		}
  1541  
  1542  		if err != nil {
  1543  			if pc.readLimit <= 0 {
  1544  				err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize())
  1545  			}
  1546  
  1547  			// If we won't be able to retry this request later (from the
  1548  			// roundTrip goroutine), mark it as done now.
  1549  			// BEFORE the send on rc.ch, as the client might re-use the
  1550  			// same *Request pointer, and we don't want to set call
  1551  			// t.setReqCanceler from this persistConn while the Transport
  1552  			// potentially spins up a different persistConn for the
  1553  			// caller's subsequent request.
  1554  			if !pc.shouldRetryRequest(rc.req, err) {
  1555  				pc.t.setReqCanceler(rc.req, nil)
  1556  			}
  1557  			select {
  1558  			case rc.ch <- responseAndError{err: err}:
  1559  			case <-rc.callerGone:
  1560  				return
  1561  			}
  1562  			return
  1563  		}
  1564  		pc.readLimit = maxInt64 // effictively no limit for response bodies
  1565  
  1566  		pc.mu.Lock()
  1567  		pc.numExpectedResponses--
  1568  		pc.mu.Unlock()
  1569  
  1570  		hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0
  1571  
  1572  		if resp.Close || rc.req.Close || resp.StatusCode <= 199 {
  1573  			// Don't do keep-alive on error if either party requested a close
  1574  			// or we get an unexpected informational (1xx) response.
  1575  			// StatusCode 100 is already handled above.
  1576  			alive = false
  1577  		}
  1578  
  1579  		if !hasBody {
  1580  			pc.t.setReqCanceler(rc.req, nil)
  1581  
  1582  			// Put the idle conn back into the pool before we send the response
  1583  			// so if they process it quickly and make another request, they'll
  1584  			// get this same conn. But we use the unbuffered channel 'rc'
  1585  			// to guarantee that persistConn.roundTrip got out of its select
  1586  			// potentially waiting for this persistConn to close.
  1587  			// but after
  1588  			alive = alive &&
  1589  				!pc.sawEOF &&
  1590  				pc.wroteRequest() &&
  1591  				tryPutIdleConn(trace)
  1592  
  1593  			select {
  1594  			case rc.ch <- responseAndError{res: resp}:
  1595  			case <-rc.callerGone:
  1596  				return
  1597  			}
  1598  
  1599  			// Now that they've read from the unbuffered channel, they're safely
  1600  			// out of the select that also waits on this goroutine to die, so
  1601  			// we're allowed to exit now if needed (if alive is false)
  1602  			testHookReadLoopBeforeNextRead()
  1603  			continue
  1604  		}
  1605  
  1606  		waitForBodyRead := make(chan bool, 2)
  1607  		body := &bodyEOFSignal{
  1608  			body: resp.Body,
  1609  			earlyCloseFn: func() error {
  1610  				waitForBodyRead <- false
  1611  				return nil
  1612  
  1613  			},
  1614  			fn: func(err error) error {
  1615  				isEOF := err == io.EOF
  1616  				waitForBodyRead <- isEOF
  1617  				if isEOF {
  1618  					<-eofc // see comment above eofc declaration
  1619  				} else if err != nil {
  1620  					if cerr := pc.canceled(); cerr != nil {
  1621  						return cerr
  1622  					}
  1623  				}
  1624  				return err
  1625  			},
  1626  		}
  1627  
  1628  		resp.Body = body
  1629  		if rc.addedGzip && resp.Header.Get("Content-Encoding") == "gzip" {
  1630  			resp.Body = &gzipReader{body: body}
  1631  			resp.Header.Del("Content-Encoding")
  1632  			resp.Header.Del("Content-Length")
  1633  			resp.ContentLength = -1
  1634  			resp.Uncompressed = true
  1635  		}
  1636  
  1637  		select {
  1638  		case rc.ch <- responseAndError{res: resp}:
  1639  		case <-rc.callerGone:
  1640  			return
  1641  		}
  1642  
  1643  		// Before looping back to the top of this function and peeking on
  1644  		// the bufio.Reader, wait for the caller goroutine to finish
  1645  		// reading the response body. (or for cancelation or death)
  1646  		select {
  1647  		case bodyEOF := <-waitForBodyRead:
  1648  			pc.t.setReqCanceler(rc.req, nil) // before pc might return to idle pool
  1649  			alive = alive &&
  1650  				bodyEOF &&
  1651  				!pc.sawEOF &&
  1652  				pc.wroteRequest() &&
  1653  				tryPutIdleConn(trace)
  1654  			if bodyEOF {
  1655  				eofc <- struct{}{}
  1656  			}
  1657  		case <-rc.req.Cancel:
  1658  			alive = false
  1659  			pc.t.CancelRequest(rc.req)
  1660  		case <-rc.req.Context().Done():
  1661  			alive = false
  1662  			pc.t.cancelRequest(rc.req, rc.req.Context().Err())
  1663  		case <-pc.closech:
  1664  			alive = false
  1665  		}
  1666  
  1667  		testHookReadLoopBeforeNextRead()
  1668  	}
  1669  }
  1670  
  1671  func (pc *persistConn) readLoopPeekFailLocked(peekErr error) {
  1672  	if pc.closed != nil {
  1673  		return
  1674  	}
  1675  	if n := pc.br.Buffered(); n > 0 {
  1676  		buf, _ := pc.br.Peek(n)
  1677  		log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr)
  1678  	}
  1679  	if peekErr == io.EOF {
  1680  		// common case.
  1681  		pc.closeLocked(errServerClosedIdle)
  1682  	} else {
  1683  		pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %v", peekErr))
  1684  	}
  1685  }
  1686  
  1687  // readResponse reads an HTTP response (or two, in the case of "Expect:
  1688  // 100-continue") from the server. It returns the final non-100 one.
  1689  // trace is optional.
  1690  func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error) {
  1691  	if trace != nil && trace.GotFirstResponseByte != nil {
  1692  		if peek, err := pc.br.Peek(1); err == nil && len(peek) == 1 {
  1693  			trace.GotFirstResponseByte()
  1694  		}
  1695  	}
  1696  	resp, err = ReadResponse(pc.br, rc.req)
  1697  	if err != nil {
  1698  		return
  1699  	}
  1700  	if rc.continueCh != nil {
  1701  		if resp.StatusCode == 100 {
  1702  			if trace != nil && trace.Got100Continue != nil {
  1703  				trace.Got100Continue()
  1704  			}
  1705  			rc.continueCh <- struct{}{}
  1706  		} else {
  1707  			close(rc.continueCh)
  1708  		}
  1709  	}
  1710  	if resp.StatusCode == 100 {
  1711  		pc.readLimit = pc.maxHeaderResponseSize() // reset the limit
  1712  		resp, err = ReadResponse(pc.br, rc.req)
  1713  		if err != nil {
  1714  			return
  1715  		}
  1716  	}
  1717  	resp.TLS = pc.tlsState
  1718  	return
  1719  }
  1720  
  1721  // waitForContinue returns the function to block until
  1722  // any response, timeout or connection close. After any of them,
  1723  // the function returns a bool which indicates if the body should be sent.
  1724  func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool {
  1725  	if continueCh == nil {
  1726  		return nil
  1727  	}
  1728  	return func() bool {
  1729  		timer := time.NewTimer(pc.t.ExpectContinueTimeout)
  1730  		defer timer.Stop()
  1731  
  1732  		select {
  1733  		case _, ok := <-continueCh:
  1734  			return ok
  1735  		case <-timer.C:
  1736  			return true
  1737  		case <-pc.closech:
  1738  			return false
  1739  		}
  1740  	}
  1741  }
  1742  
  1743  // nothingWrittenError wraps a write errors which ended up writing zero bytes.
  1744  type nothingWrittenError struct {
  1745  	error
  1746  }
  1747  
  1748  func (pc *persistConn) writeLoop() {
  1749  	defer close(pc.writeLoopDone)
  1750  	for {
  1751  		select {
  1752  		case wr := <-pc.writech:
  1753  			startBytesWritten := pc.nwrite
  1754  			err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh))
  1755  			if bre, ok := err.(requestBodyReadError); ok {
  1756  				err = bre.error
  1757  				// Errors reading from the user's
  1758  				// Request.Body are high priority.
  1759  				// Set it here before sending on the
  1760  				// channels below or calling
  1761  				// pc.close() which tears town
  1762  				// connections and causes other
  1763  				// errors.
  1764  				wr.req.setError(err)
  1765  			}
  1766  			if err == nil {
  1767  				err = pc.bw.Flush()
  1768  			}
  1769  			if err != nil {
  1770  				wr.req.Request.closeBody()
  1771  				if pc.nwrite == startBytesWritten && wr.req.outgoingLength() == 0 {
  1772  					err = nothingWrittenError{err}
  1773  				}
  1774  			}
  1775  			pc.writeErrCh <- err // to the body reader, which might recycle us
  1776  			wr.ch <- err         // to the roundTrip function
  1777  			if err != nil {
  1778  				pc.close(err)
  1779  				return
  1780  			}
  1781  		case <-pc.closech:
  1782  			return
  1783  		}
  1784  	}
  1785  }
  1786  
  1787  // wroteRequest is a check before recycling a connection that the previous write
  1788  // (from writeLoop above) happened and was successful.
  1789  func (pc *persistConn) wroteRequest() bool {
  1790  	select {
  1791  	case err := <-pc.writeErrCh:
  1792  		// Common case: the write happened well before the response, so
  1793  		// avoid creating a timer.
  1794  		return err == nil
  1795  	default:
  1796  		// Rare case: the request was written in writeLoop above but
  1797  		// before it could send to pc.writeErrCh, the reader read it
  1798  		// all, processed it, and called us here. In this case, give the
  1799  		// write goroutine a bit of time to finish its send.
  1800  		//
  1801  		// Less rare case: We also get here in the legitimate case of
  1802  		// Issue 7569, where the writer is still writing (or stalled),
  1803  		// but the server has already replied. In this case, we don't
  1804  		// want to wait too long, and we want to return false so this
  1805  		// connection isn't re-used.
  1806  		select {
  1807  		case err := <-pc.writeErrCh:
  1808  			return err == nil
  1809  		case <-time.After(50 * time.Millisecond):
  1810  			return false
  1811  		}
  1812  	}
  1813  }
  1814  
  1815  // responseAndError is how the goroutine reading from an HTTP/1 server
  1816  // communicates with the goroutine doing the RoundTrip.
  1817  type responseAndError struct {
  1818  	res *Response // else use this response (see res method)
  1819  	err error
  1820  }
  1821  
  1822  type requestAndChan struct {
  1823  	req *Request
  1824  	ch  chan responseAndError // unbuffered; always send in select on callerGone
  1825  
  1826  	// whether the Transport (as opposed to the user client code)
  1827  	// added the Accept-Encoding gzip header. If the Transport
  1828  	// set it, only then do we transparently decode the gzip.
  1829  	addedGzip bool
  1830  
  1831  	// Optional blocking chan for Expect: 100-continue (for send).
  1832  	// If the request has an "Expect: 100-continue" header and
  1833  	// the server responds 100 Continue, readLoop send a value
  1834  	// to writeLoop via this chan.
  1835  	continueCh chan<- struct{}
  1836  
  1837  	callerGone <-chan struct{} // closed when roundTrip caller has returned
  1838  }
  1839  
  1840  // A writeRequest is sent by the readLoop's goroutine to the
  1841  // writeLoop's goroutine to write a request while the read loop
  1842  // concurrently waits on both the write response and the server's
  1843  // reply.
  1844  type writeRequest struct {
  1845  	req *transportRequest
  1846  	ch  chan<- error
  1847  
  1848  	// Optional blocking chan for Expect: 100-continue (for receive).
  1849  	// If not nil, writeLoop blocks sending request body until
  1850  	// it receives from this chan.
  1851  	continueCh <-chan struct{}
  1852  }
  1853  
  1854  type httpError struct {
  1855  	err     string
  1856  	timeout bool
  1857  }
  1858  
  1859  func (e *httpError) Error() string   { return e.err }
  1860  func (e *httpError) Timeout() bool   { return e.timeout }
  1861  func (e *httpError) Temporary() bool { return true }
  1862  
  1863  var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true}
  1864  var errRequestCanceled = errors.New("net/http: request canceled")
  1865  var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?
  1866  
  1867  func nop() {}
  1868  
  1869  // testHooks. Always non-nil.
  1870  var (
  1871  	testHookEnterRoundTrip   = nop
  1872  	testHookWaitResLoop      = nop
  1873  	testHookRoundTripRetried = nop
  1874  	testHookPrePendingDial   = nop
  1875  	testHookPostPendingDial  = nop
  1876  
  1877  	testHookMu                     sync.Locker = fakeLocker{} // guards following
  1878  	testHookReadLoopBeforeNextRead             = nop
  1879  )
  1880  
  1881  func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
  1882  	testHookEnterRoundTrip()
  1883  	if !pc.t.replaceReqCanceler(req.Request, pc.cancelRequest) {
  1884  		pc.t.putOrCloseIdleConn(pc)
  1885  		return nil, errRequestCanceled
  1886  	}
  1887  	pc.mu.Lock()
  1888  	pc.numExpectedResponses++
  1889  	headerFn := pc.mutateHeaderFunc
  1890  	pc.mu.Unlock()
  1891  
  1892  	if headerFn != nil {
  1893  		headerFn(req.extraHeaders())
  1894  	}
  1895  
  1896  	// Ask for a compressed version if the caller didn't set their
  1897  	// own value for Accept-Encoding. We only attempt to
  1898  	// uncompress the gzip stream if we were the layer that
  1899  	// requested it.
  1900  	requestedGzip := false
  1901  	if !pc.t.DisableCompression &&
  1902  		req.Header.Get("Accept-Encoding") == "" &&
  1903  		req.Header.Get("Range") == "" &&
  1904  		req.Method != "HEAD" {
  1905  		// Request gzip only, not deflate. Deflate is ambiguous and
  1906  		// not as universally supported anyway.
  1907  		// See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  1908  		//
  1909  		// Note that we don't request this for HEAD requests,
  1910  		// due to a bug in nginx:
  1911  		//   http://trac.nginx.org/nginx/ticket/358
  1912  		//   https://golang.org/issue/5522
  1913  		//
  1914  		// We don't request gzip if the request is for a range, since
  1915  		// auto-decoding a portion of a gzipped document will just fail
  1916  		// anyway. See https://golang.org/issue/8923
  1917  		requestedGzip = true
  1918  		req.extraHeaders().Set("Accept-Encoding", "gzip")
  1919  	}
  1920  
  1921  	var continueCh chan struct{}
  1922  	if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() {
  1923  		continueCh = make(chan struct{}, 1)
  1924  	}
  1925  
  1926  	if pc.t.DisableKeepAlives {
  1927  		req.extraHeaders().Set("Connection", "close")
  1928  	}
  1929  
  1930  	gone := make(chan struct{})
  1931  	defer close(gone)
  1932  
  1933  	defer func() {
  1934  		if err != nil {
  1935  			pc.t.setReqCanceler(req.Request, nil)
  1936  		}
  1937  	}()
  1938  
  1939  	const debugRoundTrip = false
  1940  
  1941  	// Write the request concurrently with waiting for a response,
  1942  	// in case the server decides to reply before reading our full
  1943  	// request body.
  1944  	startBytesWritten := pc.nwrite
  1945  	writeErrCh := make(chan error, 1)
  1946  	pc.writech <- writeRequest{req, writeErrCh, continueCh}
  1947  
  1948  	resc := make(chan responseAndError)
  1949  	pc.reqch <- requestAndChan{
  1950  		req:        req.Request,
  1951  		ch:         resc,
  1952  		addedGzip:  requestedGzip,
  1953  		continueCh: continueCh,
  1954  		callerGone: gone,
  1955  	}
  1956  
  1957  	var respHeaderTimer <-chan time.Time
  1958  	cancelChan := req.Request.Cancel
  1959  	ctxDoneChan := req.Context().Done()
  1960  	for {
  1961  		testHookWaitResLoop()
  1962  		select {
  1963  		case err := <-writeErrCh:
  1964  			if debugRoundTrip {
  1965  				req.logf("writeErrCh resv: %T/%#v", err, err)
  1966  			}
  1967  			if err != nil {
  1968  				pc.close(fmt.Errorf("write error: %v", err))
  1969  				return nil, pc.mapRoundTripError(req, startBytesWritten, err)
  1970  			}
  1971  			if d := pc.t.ResponseHeaderTimeout; d > 0 {
  1972  				if debugRoundTrip {
  1973  					req.logf("starting timer for %v", d)
  1974  				}
  1975  				timer := time.NewTimer(d)
  1976  				defer timer.Stop() // prevent leaks
  1977  				respHeaderTimer = timer.C
  1978  			}
  1979  		case <-pc.closech:
  1980  			if debugRoundTrip {
  1981  				req.logf("closech recv: %T %#v", pc.closed, pc.closed)
  1982  			}
  1983  			return nil, pc.mapRoundTripError(req, startBytesWritten, pc.closed)
  1984  		case <-respHeaderTimer:
  1985  			if debugRoundTrip {
  1986  				req.logf("timeout waiting for response headers.")
  1987  			}
  1988  			pc.close(errTimeout)
  1989  			return nil, errTimeout
  1990  		case re := <-resc:
  1991  			if (re.res == nil) == (re.err == nil) {
  1992  				panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", re.res == nil))
  1993  			}
  1994  			if debugRoundTrip {
  1995  				req.logf("resc recv: %p, %T/%#v", re.res, re.err, re.err)
  1996  			}
  1997  			if re.err != nil {
  1998  				return nil, pc.mapRoundTripError(req, startBytesWritten, re.err)
  1999  			}
  2000  			return re.res, nil
  2001  		case <-cancelChan:
  2002  			pc.t.CancelRequest(req.Request)
  2003  			cancelChan = nil
  2004  		case <-ctxDoneChan:
  2005  			pc.t.cancelRequest(req.Request, req.Context().Err())
  2006  			cancelChan = nil
  2007  			ctxDoneChan = nil
  2008  		}
  2009  	}
  2010  }
  2011  
  2012  // tLogKey is a context WithValue key for test debugging contexts containing
  2013  // a t.Logf func. See export_test.go's Request.WithT method.
  2014  type tLogKey struct{}
  2015  
  2016  func (r *transportRequest) logf(format string, args ...interface{}) {
  2017  	if logf, ok := r.Request.Context().Value(tLogKey{}).(func(string, ...interface{})); ok {
  2018  		logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...)
  2019  	}
  2020  }
  2021  
  2022  // markReused marks this connection as having been successfully used for a
  2023  // request and response.
  2024  func (pc *persistConn) markReused() {
  2025  	pc.mu.Lock()
  2026  	pc.reused = true
  2027  	pc.mu.Unlock()
  2028  }
  2029  
  2030  // close closes the underlying TCP connection and closes
  2031  // the pc.closech channel.
  2032  //
  2033  // The provided err is only for testing and debugging; in normal
  2034  // circumstances it should never be seen by users.
  2035  func (pc *persistConn) close(err error) {
  2036  	pc.mu.Lock()
  2037  	defer pc.mu.Unlock()
  2038  	pc.closeLocked(err)
  2039  }
  2040  
  2041  func (pc *persistConn) closeLocked(err error) {
  2042  	if err == nil {
  2043  		panic("nil error")
  2044  	}
  2045  	pc.broken = true
  2046  	if pc.closed == nil {
  2047  		pc.closed = err
  2048  		if pc.alt != nil {
  2049  			// Do nothing; can only get here via getConn's
  2050  			// handlePendingDial's putOrCloseIdleConn when
  2051  			// it turns out the abandoned connection in
  2052  			// flight ended up negotiating an alternate
  2053  			// protocol. We don't use the connection
  2054  			// freelist for http2. That's done by the
  2055  			// alternate protocol's RoundTripper.
  2056  		} else {
  2057  			pc.conn.Close()
  2058  			close(pc.closech)
  2059  		}
  2060  	}
  2061  	pc.mutateHeaderFunc = nil
  2062  }
  2063  
  2064  var portMap = map[string]string{
  2065  	"http":   "80",
  2066  	"https":  "443",
  2067  	"socks5": "1080",
  2068  }
  2069  
  2070  // canonicalAddr returns url.Host but always with a ":port" suffix
  2071  func canonicalAddr(url *url.URL) string {
  2072  	addr := url.Hostname()
  2073  	if v, err := idnaASCII(addr); err == nil {
  2074  		addr = v
  2075  	}
  2076  	port := url.Port()
  2077  	if port == "" {
  2078  		port = portMap[url.Scheme]
  2079  	}
  2080  	return net.JoinHostPort(addr, port)
  2081  }
  2082  
  2083  // bodyEOFSignal is used by the HTTP/1 transport when reading response
  2084  // bodies to make sure we see the end of a response body before
  2085  // proceeding and reading on the connection again.
  2086  //
  2087  // It wraps a ReadCloser but runs fn (if non-nil) at most
  2088  // once, right before its final (error-producing) Read or Close call
  2089  // returns. fn should return the new error to return from Read or Close.
  2090  //
  2091  // If earlyCloseFn is non-nil and Close is called before io.EOF is
  2092  // seen, earlyCloseFn is called instead of fn, and its return value is
  2093  // the return value from Close.
  2094  type bodyEOFSignal struct {
  2095  	body         io.ReadCloser
  2096  	mu           sync.Mutex        // guards following 4 fields
  2097  	closed       bool              // whether Close has been called
  2098  	rerr         error             // sticky Read error
  2099  	fn           func(error) error // err will be nil on Read io.EOF
  2100  	earlyCloseFn func() error      // optional alt Close func used if io.EOF not seen
  2101  }
  2102  
  2103  var errReadOnClosedResBody = errors.New("http: read on closed response body")
  2104  
  2105  func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
  2106  	es.mu.Lock()
  2107  	closed, rerr := es.closed, es.rerr
  2108  	es.mu.Unlock()
  2109  	if closed {
  2110  		return 0, errReadOnClosedResBody
  2111  	}
  2112  	if rerr != nil {
  2113  		return 0, rerr
  2114  	}
  2115  
  2116  	n, err = es.body.Read(p)
  2117  	if err != nil {
  2118  		es.mu.Lock()
  2119  		defer es.mu.Unlock()
  2120  		if es.rerr == nil {
  2121  			es.rerr = err
  2122  		}
  2123  		err = es.condfn(err)
  2124  	}
  2125  	return
  2126  }
  2127  
  2128  func (es *bodyEOFSignal) Close() error {
  2129  	es.mu.Lock()
  2130  	defer es.mu.Unlock()
  2131  	if es.closed {
  2132  		return nil
  2133  	}
  2134  	es.closed = true
  2135  	if es.earlyCloseFn != nil && es.rerr != io.EOF {
  2136  		return es.earlyCloseFn()
  2137  	}
  2138  	err := es.body.Close()
  2139  	return es.condfn(err)
  2140  }
  2141  
  2142  // caller must hold es.mu.
  2143  func (es *bodyEOFSignal) condfn(err error) error {
  2144  	if es.fn == nil {
  2145  		return err
  2146  	}
  2147  	err = es.fn(err)
  2148  	es.fn = nil
  2149  	return err
  2150  }
  2151  
  2152  // gzipReader wraps a response body so it can lazily
  2153  // call gzip.NewReader on the first call to Read
  2154  type gzipReader struct {
  2155  	body *bodyEOFSignal // underlying HTTP/1 response body framing
  2156  	zr   *gzip.Reader   // lazily-initialized gzip reader
  2157  	zerr error          // any error from gzip.NewReader; sticky
  2158  }
  2159  
  2160  func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2161  	if gz.zr == nil {
  2162  		if gz.zerr == nil {
  2163  			gz.zr, gz.zerr = gzip.NewReader(gz.body)
  2164  		}
  2165  		if gz.zerr != nil {
  2166  			return 0, gz.zerr
  2167  		}
  2168  	}
  2169  
  2170  	gz.body.mu.Lock()
  2171  	if gz.body.closed {
  2172  		err = errReadOnClosedResBody
  2173  	}
  2174  	gz.body.mu.Unlock()
  2175  
  2176  	if err != nil {
  2177  		return 0, err
  2178  	}
  2179  	return gz.zr.Read(p)
  2180  }
  2181  
  2182  func (gz *gzipReader) Close() error {
  2183  	return gz.body.Close()
  2184  }
  2185  
  2186  type readerAndCloser struct {
  2187  	io.Reader
  2188  	io.Closer
  2189  }
  2190  
  2191  type tlsHandshakeTimeoutError struct{}
  2192  
  2193  func (tlsHandshakeTimeoutError) Timeout() bool   { return true }
  2194  func (tlsHandshakeTimeoutError) Temporary() bool { return true }
  2195  func (tlsHandshakeTimeoutError) Error() string   { return "net/http: TLS handshake timeout" }
  2196  
  2197  // fakeLocker is a sync.Locker which does nothing. It's used to guard
  2198  // test-only fields when not under test, to avoid runtime atomic
  2199  // overhead.
  2200  type fakeLocker struct{}
  2201  
  2202  func (fakeLocker) Lock()   {}
  2203  func (fakeLocker) Unlock() {}
  2204  
  2205  // clneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if
  2206  // cfg is nil. This is safe to call even if cfg is in active use by a TLS
  2207  // client or server.
  2208  func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  2209  	if cfg == nil {
  2210  		return &tls.Config{}
  2211  	}
  2212  	return cfg.Clone()
  2213  }
  2214  
  2215  type connLRU struct {
  2216  	ll *list.List // list.Element.Value type is of *persistConn
  2217  	m  map[*persistConn]*list.Element
  2218  }
  2219  
  2220  // add adds pc to the head of the linked list.
  2221  func (cl *connLRU) add(pc *persistConn) {
  2222  	if cl.ll == nil {
  2223  		cl.ll = list.New()
  2224  		cl.m = make(map[*persistConn]*list.Element)
  2225  	}
  2226  	ele := cl.ll.PushFront(pc)
  2227  	if _, ok := cl.m[pc]; ok {
  2228  		panic("persistConn was already in LRU")
  2229  	}
  2230  	cl.m[pc] = ele
  2231  }
  2232  
  2233  func (cl *connLRU) removeOldest() *persistConn {
  2234  	ele := cl.ll.Back()
  2235  	pc := ele.Value.(*persistConn)
  2236  	cl.ll.Remove(ele)
  2237  	delete(cl.m, pc)
  2238  	return pc
  2239  }
  2240  
  2241  // remove removes pc from cl.
  2242  func (cl *connLRU) remove(pc *persistConn) {
  2243  	if ele, ok := cl.m[pc]; ok {
  2244  		cl.ll.Remove(ele)
  2245  		delete(cl.m, pc)
  2246  	}
  2247  }
  2248  
  2249  // len returns the number of items in the cache.
  2250  func (cl *connLRU) len() int {
  2251  	return len(cl.m)
  2252  }
  2253  
  2254  // validPort reports whether p (without the colon) is a valid port in
  2255  // a URL, per RFC 3986 Section 3.2.3, which says the port may be
  2256  // empty, or only contain digits.
  2257  func validPort(p string) bool {
  2258  	for _, r := range []byte(p) {
  2259  		if r < '0' || r > '9' {
  2260  			return false
  2261  		}
  2262  	}
  2263  	return true
  2264  }