...
Run Format

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

View as plain text