github.com/Psiphon-Labs/net@v0.0.0-20191204183604-f5d60dada742/http2/transport.go (about)

     1  // Copyright 2015 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  // Transport code.
     6  
     7  package http2
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"compress/gzip"
    13  	"context"
    14  	"crypto/rand"
    15  	"crypto/tls"
    16  	"errors"
    17  	"fmt"
    18  	"io"
    19  	"io/ioutil"
    20  	"log"
    21  	"math"
    22  	mathrand "math/rand"
    23  	"net"
    24  	"net/http"
    25  	"net/http/httptrace"
    26  	"net/textproto"
    27  	"sort"
    28  	"strconv"
    29  	"strings"
    30  	"sync"
    31  	"sync/atomic"
    32  	"time"
    33  
    34  	"github.com/Psiphon-Labs/net/http/httpguts"
    35  	"github.com/Psiphon-Labs/net/http2/hpack"
    36  	"github.com/Psiphon-Labs/net/idna"
    37  )
    38  
    39  const (
    40  	// transportDefaultConnFlow is how many connection-level flow control
    41  	// tokens we give the server at start-up, past the default 64k.
    42  	transportDefaultConnFlow = 1 << 30
    43  
    44  	// transportDefaultStreamFlow is how many stream-level flow
    45  	// control tokens we announce to the peer, and how many bytes
    46  	// we buffer per stream.
    47  	transportDefaultStreamFlow = 4 << 20
    48  
    49  	// transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
    50  	// a stream-level WINDOW_UPDATE for at a time.
    51  	transportDefaultStreamMinRefresh = 4 << 10
    52  
    53  	defaultUserAgent = "Go-http-client/2.0"
    54  )
    55  
    56  // Transport is an HTTP/2 Transport.
    57  //
    58  // A Transport internally caches connections to servers. It is safe
    59  // for concurrent use by multiple goroutines.
    60  type Transport struct {
    61  	// DialTLS specifies an optional dial function for creating
    62  	// TLS connections for requests.
    63  	//
    64  	// If DialTLS is nil, tls.Dial is used.
    65  	//
    66  	// If the returned net.Conn has a ConnectionState method like tls.Conn,
    67  	// it will be used to set http.Response.TLS.
    68  	DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
    69  
    70  	// TLSClientConfig specifies the TLS configuration to use with
    71  	// tls.Client. If nil, the default configuration is used.
    72  	TLSClientConfig *tls.Config
    73  
    74  	// ConnPool optionally specifies an alternate connection pool to use.
    75  	// If nil, the default is used.
    76  	ConnPool ClientConnPool
    77  
    78  	// DisableCompression, if true, prevents the Transport from
    79  	// requesting compression with an "Accept-Encoding: gzip"
    80  	// request header when the Request contains no existing
    81  	// Accept-Encoding value. If the Transport requests gzip on
    82  	// its own and gets a gzipped response, it's transparently
    83  	// decoded in the Response.Body. However, if the user
    84  	// explicitly requested gzip it is not automatically
    85  	// uncompressed.
    86  	DisableCompression bool
    87  
    88  	// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
    89  	// plain-text "http" scheme. Note that this does not enable h2c support.
    90  	AllowHTTP bool
    91  
    92  	// MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
    93  	// send in the initial settings frame. It is how many bytes
    94  	// of response headers are allowed. Unlike the http2 spec, zero here
    95  	// means to use a default limit (currently 10MB). If you actually
    96  	// want to advertise an ulimited value to the peer, Transport
    97  	// interprets the highest possible value here (0xffffffff or 1<<32-1)
    98  	// to mean no limit.
    99  	MaxHeaderListSize uint32
   100  
   101  	// StrictMaxConcurrentStreams controls whether the server's
   102  	// SETTINGS_MAX_CONCURRENT_STREAMS should be respected
   103  	// globally. If false, new TCP connections are created to the
   104  	// server as needed to keep each under the per-connection
   105  	// SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
   106  	// server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
   107  	// a global limit and callers of RoundTrip block when needed,
   108  	// waiting for their turn.
   109  	StrictMaxConcurrentStreams bool
   110  
   111  	// t1, if non-nil, is the standard library Transport using
   112  	// this transport. Its settings are used (but not its
   113  	// RoundTrip method, etc).
   114  	t1 *http.Transport
   115  
   116  	connPoolOnce  sync.Once
   117  	connPoolOrDef ClientConnPool // non-nil version of ConnPool
   118  }
   119  
   120  func (t *Transport) maxHeaderListSize() uint32 {
   121  	if t.MaxHeaderListSize == 0 {
   122  		return 10 << 20
   123  	}
   124  	if t.MaxHeaderListSize == 0xffffffff {
   125  		return 0
   126  	}
   127  	return t.MaxHeaderListSize
   128  }
   129  
   130  func (t *Transport) disableCompression() bool {
   131  	return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
   132  }
   133  
   134  // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
   135  // It returns an error if t1 has already been HTTP/2-enabled.
   136  func ConfigureTransport(t1 *http.Transport) error {
   137  	_, err := configureTransport(t1)
   138  	return err
   139  }
   140  
   141  func configureTransport(t1 *http.Transport) (*Transport, error) {
   142  	connPool := new(clientConnPool)
   143  	t2 := &Transport{
   144  		ConnPool: noDialClientConnPool{connPool},
   145  		t1:       t1,
   146  	}
   147  	connPool.t = t2
   148  	if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
   149  		return nil, err
   150  	}
   151  	if t1.TLSClientConfig == nil {
   152  		t1.TLSClientConfig = new(tls.Config)
   153  	}
   154  	if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
   155  		t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
   156  	}
   157  	if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
   158  		t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
   159  	}
   160  	upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
   161  		addr := authorityAddr("https", authority)
   162  		if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
   163  			go c.Close()
   164  			return erringRoundTripper{err}
   165  		} else if !used {
   166  			// Turns out we don't need this c.
   167  			// For example, two goroutines made requests to the same host
   168  			// at the same time, both kicking off TCP dials. (since protocol
   169  			// was unknown)
   170  			go c.Close()
   171  		}
   172  		return t2
   173  	}
   174  	if m := t1.TLSNextProto; len(m) == 0 {
   175  		t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
   176  			"h2": upgradeFn,
   177  		}
   178  	} else {
   179  		m["h2"] = upgradeFn
   180  	}
   181  	return t2, nil
   182  }
   183  
   184  func (t *Transport) connPool() ClientConnPool {
   185  	t.connPoolOnce.Do(t.initConnPool)
   186  	return t.connPoolOrDef
   187  }
   188  
   189  func (t *Transport) initConnPool() {
   190  	if t.ConnPool != nil {
   191  		t.connPoolOrDef = t.ConnPool
   192  	} else {
   193  		t.connPoolOrDef = &clientConnPool{t: t}
   194  	}
   195  }
   196  
   197  // ClientConn is the state of a single HTTP/2 client connection to an
   198  // HTTP/2 server.
   199  type ClientConn struct {
   200  	t         *Transport
   201  	tconn     net.Conn             // usually *tls.Conn, except specialized impls
   202  	tlsState  *tls.ConnectionState // nil only for specialized impls
   203  	reused    uint32               // whether conn is being reused; atomic
   204  	singleUse bool                 // whether being used for a single http.Request
   205  
   206  	// readLoop goroutine fields:
   207  	readerDone chan struct{} // closed on error
   208  	readerErr  error         // set before readerDone is closed
   209  
   210  	idleTimeout time.Duration // or 0 for never
   211  	idleTimer   *time.Timer
   212  
   213  	mu              sync.Mutex // guards following
   214  	cond            *sync.Cond // hold mu; broadcast on flow/closed changes
   215  	flow            flow       // our conn-level flow control quota (cs.flow is per stream)
   216  	inflow          flow       // peer's conn-level flow control
   217  	closing         bool
   218  	closed          bool
   219  	wantSettingsAck bool                     // we sent a SETTINGS frame and haven't heard back
   220  	goAway          *GoAwayFrame             // if non-nil, the GoAwayFrame we received
   221  	goAwayDebug     string                   // goAway frame's debug data, retained as a string
   222  	streams         map[uint32]*clientStream // client-initiated
   223  	nextStreamID    uint32
   224  	pendingRequests int                       // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
   225  	pings           map[[8]byte]chan struct{} // in flight ping data to notification channel
   226  	bw              *bufio.Writer
   227  	br              *bufio.Reader
   228  	fr              *Framer
   229  	lastActive      time.Time
   230  	// Settings from peer: (also guarded by mu)
   231  	maxFrameSize          uint32
   232  	maxConcurrentStreams  uint32
   233  	peerMaxHeaderListSize uint64
   234  	initialWindowSize     uint32
   235  
   236  	hbuf    bytes.Buffer // HPACK encoder writes into this
   237  	henc    *hpack.Encoder
   238  	freeBuf [][]byte
   239  
   240  	wmu  sync.Mutex // held while writing; acquire AFTER mu if holding both
   241  	werr error      // first write error that has occurred
   242  }
   243  
   244  // clientStream is the state for a single HTTP/2 stream. One of these
   245  // is created for each Transport.RoundTrip call.
   246  type clientStream struct {
   247  	cc            *ClientConn
   248  	req           *http.Request
   249  	trace         *httptrace.ClientTrace // or nil
   250  	ID            uint32
   251  	resc          chan resAndError
   252  	bufPipe       pipe // buffered pipe with the flow-controlled response payload
   253  	startedWrite  bool // started request body write; guarded by cc.mu
   254  	requestedGzip bool
   255  	on100         func() // optional code to run if get a 100 continue response
   256  
   257  	flow        flow  // guarded by cc.mu
   258  	inflow      flow  // guarded by cc.mu
   259  	bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
   260  	readErr     error // sticky read error; owned by transportResponseBody.Read
   261  	stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
   262  	didReset    bool  // whether we sent a RST_STREAM to the server; guarded by cc.mu
   263  
   264  	peerReset chan struct{} // closed on peer reset
   265  	resetErr  error         // populated before peerReset is closed
   266  
   267  	done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
   268  
   269  	// owned by clientConnReadLoop:
   270  	firstByte    bool  // got the first response byte
   271  	pastHeaders  bool  // got first MetaHeadersFrame (actual headers)
   272  	pastTrailers bool  // got optional second MetaHeadersFrame (trailers)
   273  	num1xx       uint8 // number of 1xx responses seen
   274  
   275  	trailer    http.Header  // accumulated trailers
   276  	resTrailer *http.Header // client's Response.Trailer
   277  }
   278  
   279  // awaitRequestCancel waits for the user to cancel a request or for the done
   280  // channel to be signaled. A non-nil error is returned only if the request was
   281  // canceled.
   282  func awaitRequestCancel(req *http.Request, done <-chan struct{}) error {
   283  	ctx := req.Context()
   284  	if req.Cancel == nil && ctx.Done() == nil {
   285  		return nil
   286  	}
   287  	select {
   288  	case <-req.Cancel:
   289  		return errRequestCanceled
   290  	case <-ctx.Done():
   291  		return ctx.Err()
   292  	case <-done:
   293  		return nil
   294  	}
   295  }
   296  
   297  var got1xxFuncForTests func(int, textproto.MIMEHeader) error
   298  
   299  // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
   300  // if any. It returns nil if not set or if the Go version is too old.
   301  func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
   302  	if fn := got1xxFuncForTests; fn != nil {
   303  		return fn
   304  	}
   305  	return traceGot1xxResponseFunc(cs.trace)
   306  }
   307  
   308  // awaitRequestCancel waits for the user to cancel a request, its context to
   309  // expire, or for the request to be done (any way it might be removed from the
   310  // cc.streams map: peer reset, successful completion, TCP connection breakage,
   311  // etc). If the request is canceled, then cs will be canceled and closed.
   312  func (cs *clientStream) awaitRequestCancel(req *http.Request) {
   313  	if err := awaitRequestCancel(req, cs.done); err != nil {
   314  		cs.cancelStream()
   315  		cs.bufPipe.CloseWithError(err)
   316  	}
   317  }
   318  
   319  func (cs *clientStream) cancelStream() {
   320  	cc := cs.cc
   321  	cc.mu.Lock()
   322  	didReset := cs.didReset
   323  	cs.didReset = true
   324  	cc.mu.Unlock()
   325  
   326  	if !didReset {
   327  		cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
   328  		cc.forgetStreamID(cs.ID)
   329  	}
   330  }
   331  
   332  // checkResetOrDone reports any error sent in a RST_STREAM frame by the
   333  // server, or errStreamClosed if the stream is complete.
   334  func (cs *clientStream) checkResetOrDone() error {
   335  	select {
   336  	case <-cs.peerReset:
   337  		return cs.resetErr
   338  	case <-cs.done:
   339  		return errStreamClosed
   340  	default:
   341  		return nil
   342  	}
   343  }
   344  
   345  func (cs *clientStream) getStartedWrite() bool {
   346  	cc := cs.cc
   347  	cc.mu.Lock()
   348  	defer cc.mu.Unlock()
   349  	return cs.startedWrite
   350  }
   351  
   352  func (cs *clientStream) abortRequestBodyWrite(err error) {
   353  	if err == nil {
   354  		panic("nil error")
   355  	}
   356  	cc := cs.cc
   357  	cc.mu.Lock()
   358  	cs.stopReqBody = err
   359  	cc.cond.Broadcast()
   360  	cc.mu.Unlock()
   361  }
   362  
   363  type stickyErrWriter struct {
   364  	w   io.Writer
   365  	err *error
   366  }
   367  
   368  func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
   369  	if *sew.err != nil {
   370  		return 0, *sew.err
   371  	}
   372  	n, err = sew.w.Write(p)
   373  	*sew.err = err
   374  	return
   375  }
   376  
   377  // noCachedConnError is the concrete type of ErrNoCachedConn, which
   378  // needs to be detected by net/http regardless of whether it's its
   379  // bundled version (in h2_bundle.go with a rewritten type name) or
   380  // from a user's x/net/http2. As such, as it has a unique method name
   381  // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
   382  // isNoCachedConnError.
   383  type noCachedConnError struct{}
   384  
   385  func (noCachedConnError) IsHTTP2NoCachedConnError() {}
   386  func (noCachedConnError) Error() string             { return "http2: no cached connection was available" }
   387  
   388  // isNoCachedConnError reports whether err is of type noCachedConnError
   389  // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
   390  // may coexist in the same running program.
   391  func isNoCachedConnError(err error) bool {
   392  	_, ok := err.(interface {
   393  		IsHTTP2NoCachedConnError()
   394  	})
   395  	return ok
   396  }
   397  
   398  var ErrNoCachedConn error = noCachedConnError{}
   399  
   400  // RoundTripOpt are options for the Transport.RoundTripOpt method.
   401  type RoundTripOpt struct {
   402  	// OnlyCachedConn controls whether RoundTripOpt may
   403  	// create a new TCP connection. If set true and
   404  	// no cached connection is available, RoundTripOpt
   405  	// will return ErrNoCachedConn.
   406  	OnlyCachedConn bool
   407  }
   408  
   409  func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
   410  	return t.RoundTripOpt(req, RoundTripOpt{})
   411  }
   412  
   413  // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
   414  // and returns a host:port. The port 443 is added if needed.
   415  func authorityAddr(scheme string, authority string) (addr string) {
   416  	host, port, err := net.SplitHostPort(authority)
   417  	if err != nil { // authority didn't have a port
   418  		port = "443"
   419  		if scheme == "http" {
   420  			port = "80"
   421  		}
   422  		host = authority
   423  	}
   424  	if a, err := idna.ToASCII(host); err == nil {
   425  		host = a
   426  	}
   427  	// IPv6 address literal, without a port:
   428  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
   429  		return host + ":" + port
   430  	}
   431  	return net.JoinHostPort(host, port)
   432  }
   433  
   434  // RoundTripOpt is like RoundTrip, but takes options.
   435  func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
   436  	if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
   437  		return nil, errors.New("http2: unsupported scheme")
   438  	}
   439  
   440  	addr := authorityAddr(req.URL.Scheme, req.URL.Host)
   441  	for retry := 0; ; retry++ {
   442  		cc, err := t.connPool().GetClientConn(req, addr)
   443  		if err != nil {
   444  			t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
   445  			return nil, err
   446  		}
   447  		reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
   448  		traceGotConn(req, cc, reused)
   449  		res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req)
   450  		if err != nil && retry <= 6 {
   451  			if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil {
   452  				// After the first retry, do exponential backoff with 10% jitter.
   453  				if retry == 0 {
   454  					continue
   455  				}
   456  				backoff := float64(uint(1) << (uint(retry) - 1))
   457  				backoff += backoff * (0.1 * mathrand.Float64())
   458  				select {
   459  				case <-time.After(time.Second * time.Duration(backoff)):
   460  					continue
   461  				case <-req.Context().Done():
   462  					return nil, req.Context().Err()
   463  				}
   464  			}
   465  		}
   466  		if err != nil {
   467  			t.vlogf("RoundTrip failure: %v", err)
   468  			return nil, err
   469  		}
   470  		return res, nil
   471  	}
   472  }
   473  
   474  // CloseIdleConnections closes any connections which were previously
   475  // connected from previous requests but are now sitting idle.
   476  // It does not interrupt any connections currently in use.
   477  func (t *Transport) CloseIdleConnections() {
   478  	if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
   479  		cp.closeIdleConnections()
   480  	}
   481  }
   482  
   483  var (
   484  	errClientConnClosed    = errors.New("http2: client conn is closed")
   485  	errClientConnUnusable  = errors.New("http2: client conn not usable")
   486  	errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
   487  )
   488  
   489  // shouldRetryRequest is called by RoundTrip when a request fails to get
   490  // response headers. It is always called with a non-nil error.
   491  // It returns either a request to retry (either the same request, or a
   492  // modified clone), or an error if the request can't be replayed.
   493  func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) {
   494  	if !canRetryError(err) {
   495  		return nil, err
   496  	}
   497  	// If the Body is nil (or http.NoBody), it's safe to reuse
   498  	// this request and its Body.
   499  	if req.Body == nil || req.Body == http.NoBody {
   500  		return req, nil
   501  	}
   502  
   503  	// If the request body can be reset back to its original
   504  	// state via the optional req.GetBody, do that.
   505  	if req.GetBody != nil {
   506  		// TODO: consider a req.Body.Close here? or audit that all caller paths do?
   507  		body, err := req.GetBody()
   508  		if err != nil {
   509  			return nil, err
   510  		}
   511  		newReq := *req
   512  		newReq.Body = body
   513  		return &newReq, nil
   514  	}
   515  
   516  	// The Request.Body can't reset back to the beginning, but we
   517  	// don't seem to have started to read from it yet, so reuse
   518  	// the request directly. The "afterBodyWrite" means the
   519  	// bodyWrite process has started, which becomes true before
   520  	// the first Read.
   521  	if !afterBodyWrite {
   522  		return req, nil
   523  	}
   524  
   525  	return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
   526  }
   527  
   528  func canRetryError(err error) bool {
   529  	if err == errClientConnUnusable || err == errClientConnGotGoAway {
   530  		return true
   531  	}
   532  	if se, ok := err.(StreamError); ok {
   533  		return se.Code == ErrCodeRefusedStream
   534  	}
   535  	return false
   536  }
   537  
   538  func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
   539  	host, _, err := net.SplitHostPort(addr)
   540  	if err != nil {
   541  		return nil, err
   542  	}
   543  	tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
   544  	if err != nil {
   545  		return nil, err
   546  	}
   547  	return t.newClientConn(tconn, singleUse)
   548  }
   549  
   550  func (t *Transport) newTLSConfig(host string) *tls.Config {
   551  	cfg := new(tls.Config)
   552  	if t.TLSClientConfig != nil {
   553  		*cfg = *t.TLSClientConfig.Clone()
   554  	}
   555  	if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
   556  		cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
   557  	}
   558  	if cfg.ServerName == "" {
   559  		cfg.ServerName = host
   560  	}
   561  	return cfg
   562  }
   563  
   564  func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
   565  	if t.DialTLS != nil {
   566  		return t.DialTLS
   567  	}
   568  	return t.dialTLSDefault
   569  }
   570  
   571  func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
   572  	cn, err := tls.Dial(network, addr, cfg)
   573  	if err != nil {
   574  		return nil, err
   575  	}
   576  	if err := cn.Handshake(); err != nil {
   577  		return nil, err
   578  	}
   579  	if !cfg.InsecureSkipVerify {
   580  		if err := cn.VerifyHostname(cfg.ServerName); err != nil {
   581  			return nil, err
   582  		}
   583  	}
   584  	state := cn.ConnectionState()
   585  	if p := state.NegotiatedProtocol; p != NextProtoTLS {
   586  		return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
   587  	}
   588  	if !state.NegotiatedProtocolIsMutual {
   589  		return nil, errors.New("http2: could not negotiate protocol mutually")
   590  	}
   591  	return cn, nil
   592  }
   593  
   594  // disableKeepAlives reports whether connections should be closed as
   595  // soon as possible after handling the first request.
   596  func (t *Transport) disableKeepAlives() bool {
   597  	return t.t1 != nil && t.t1.DisableKeepAlives
   598  }
   599  
   600  func (t *Transport) expectContinueTimeout() time.Duration {
   601  	if t.t1 == nil {
   602  		return 0
   603  	}
   604  	return t.t1.ExpectContinueTimeout
   605  }
   606  
   607  func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
   608  	return t.newClientConn(c, false)
   609  }
   610  
   611  func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
   612  	cc := &ClientConn{
   613  		t:                     t,
   614  		tconn:                 c,
   615  		readerDone:            make(chan struct{}),
   616  		nextStreamID:          1,
   617  		maxFrameSize:          16 << 10,           // spec default
   618  		initialWindowSize:     65535,              // spec default
   619  		maxConcurrentStreams:  1000,               // "infinite", per spec. 1000 seems good enough.
   620  		peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
   621  		streams:               make(map[uint32]*clientStream),
   622  		singleUse:             singleUse,
   623  		wantSettingsAck:       true,
   624  		pings:                 make(map[[8]byte]chan struct{}),
   625  	}
   626  	if d := t.idleConnTimeout(); d != 0 {
   627  		cc.idleTimeout = d
   628  		cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
   629  	}
   630  	if VerboseLogs {
   631  		t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
   632  	}
   633  
   634  	cc.cond = sync.NewCond(&cc.mu)
   635  	cc.flow.add(int32(initialWindowSize))
   636  
   637  	// TODO: adjust this writer size to account for frame size +
   638  	// MTU + crypto/tls record padding.
   639  	cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
   640  	cc.br = bufio.NewReader(c)
   641  	cc.fr = NewFramer(cc.bw, cc.br)
   642  	cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
   643  	cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
   644  
   645  	// TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
   646  	// henc in response to SETTINGS frames?
   647  	cc.henc = hpack.NewEncoder(&cc.hbuf)
   648  
   649  	if t.AllowHTTP {
   650  		cc.nextStreamID = 3
   651  	}
   652  
   653  	if cs, ok := c.(connectionStater); ok {
   654  		state := cs.ConnectionState()
   655  		cc.tlsState = &state
   656  	}
   657  
   658  	initialSettings := []Setting{
   659  		{ID: SettingEnablePush, Val: 0},
   660  		{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
   661  	}
   662  	if max := t.maxHeaderListSize(); max != 0 {
   663  		initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
   664  	}
   665  
   666  	cc.bw.Write(clientPreface)
   667  	cc.fr.WriteSettings(initialSettings...)
   668  	cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
   669  	cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
   670  	cc.bw.Flush()
   671  	if cc.werr != nil {
   672  		return nil, cc.werr
   673  	}
   674  
   675  	go cc.readLoop()
   676  	return cc, nil
   677  }
   678  
   679  func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
   680  	cc.mu.Lock()
   681  	defer cc.mu.Unlock()
   682  
   683  	old := cc.goAway
   684  	cc.goAway = f
   685  
   686  	// Merge the previous and current GoAway error frames.
   687  	if cc.goAwayDebug == "" {
   688  		cc.goAwayDebug = string(f.DebugData())
   689  	}
   690  	if old != nil && old.ErrCode != ErrCodeNo {
   691  		cc.goAway.ErrCode = old.ErrCode
   692  	}
   693  	last := f.LastStreamID
   694  	for streamID, cs := range cc.streams {
   695  		if streamID > last {
   696  			select {
   697  			case cs.resc <- resAndError{err: errClientConnGotGoAway}:
   698  			default:
   699  			}
   700  		}
   701  	}
   702  }
   703  
   704  // CanTakeNewRequest reports whether the connection can take a new request,
   705  // meaning it has not been closed or received or sent a GOAWAY.
   706  func (cc *ClientConn) CanTakeNewRequest() bool {
   707  	cc.mu.Lock()
   708  	defer cc.mu.Unlock()
   709  	return cc.canTakeNewRequestLocked()
   710  }
   711  
   712  // clientConnIdleState describes the suitability of a client
   713  // connection to initiate a new RoundTrip request.
   714  type clientConnIdleState struct {
   715  	canTakeNewRequest bool
   716  	freshConn         bool // whether it's unused by any previous request
   717  }
   718  
   719  func (cc *ClientConn) idleState() clientConnIdleState {
   720  	cc.mu.Lock()
   721  	defer cc.mu.Unlock()
   722  	return cc.idleStateLocked()
   723  }
   724  
   725  func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
   726  	if cc.singleUse && cc.nextStreamID > 1 {
   727  		return
   728  	}
   729  	var maxConcurrentOkay bool
   730  	if cc.t.StrictMaxConcurrentStreams {
   731  		// We'll tell the caller we can take a new request to
   732  		// prevent the caller from dialing a new TCP
   733  		// connection, but then we'll block later before
   734  		// writing it.
   735  		maxConcurrentOkay = true
   736  	} else {
   737  		maxConcurrentOkay = int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams)
   738  	}
   739  
   740  	st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
   741  		int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32
   742  	st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest
   743  	return
   744  }
   745  
   746  func (cc *ClientConn) canTakeNewRequestLocked() bool {
   747  	st := cc.idleStateLocked()
   748  	return st.canTakeNewRequest
   749  }
   750  
   751  // onIdleTimeout is called from a time.AfterFunc goroutine. It will
   752  // only be called when we're idle, but because we're coming from a new
   753  // goroutine, there could be a new request coming in at the same time,
   754  // so this simply calls the synchronized closeIfIdle to shut down this
   755  // connection. The timer could just call closeIfIdle, but this is more
   756  // clear.
   757  func (cc *ClientConn) onIdleTimeout() {
   758  	cc.closeIfIdle()
   759  }
   760  
   761  func (cc *ClientConn) closeIfIdle() {
   762  	cc.mu.Lock()
   763  	if len(cc.streams) > 0 {
   764  		cc.mu.Unlock()
   765  		return
   766  	}
   767  	cc.closed = true
   768  	nextID := cc.nextStreamID
   769  	// TODO: do clients send GOAWAY too? maybe? Just Close:
   770  	cc.mu.Unlock()
   771  
   772  	if VerboseLogs {
   773  		cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
   774  	}
   775  	cc.tconn.Close()
   776  }
   777  
   778  var shutdownEnterWaitStateHook = func() {}
   779  
   780  // Shutdown gracefully close the client connection, waiting for running streams to complete.
   781  func (cc *ClientConn) Shutdown(ctx context.Context) error {
   782  	if err := cc.sendGoAway(); err != nil {
   783  		return err
   784  	}
   785  	// Wait for all in-flight streams to complete or connection to close
   786  	done := make(chan error, 1)
   787  	cancelled := false // guarded by cc.mu
   788  	go func() {
   789  		cc.mu.Lock()
   790  		defer cc.mu.Unlock()
   791  		for {
   792  			if len(cc.streams) == 0 || cc.closed {
   793  				cc.closed = true
   794  				done <- cc.tconn.Close()
   795  				break
   796  			}
   797  			if cancelled {
   798  				break
   799  			}
   800  			cc.cond.Wait()
   801  		}
   802  	}()
   803  	shutdownEnterWaitStateHook()
   804  	select {
   805  	case err := <-done:
   806  		return err
   807  	case <-ctx.Done():
   808  		cc.mu.Lock()
   809  		// Free the goroutine above
   810  		cancelled = true
   811  		cc.cond.Broadcast()
   812  		cc.mu.Unlock()
   813  		return ctx.Err()
   814  	}
   815  }
   816  
   817  func (cc *ClientConn) sendGoAway() error {
   818  	cc.mu.Lock()
   819  	defer cc.mu.Unlock()
   820  	cc.wmu.Lock()
   821  	defer cc.wmu.Unlock()
   822  	if cc.closing {
   823  		// GOAWAY sent already
   824  		return nil
   825  	}
   826  	// Send a graceful shutdown frame to server
   827  	maxStreamID := cc.nextStreamID
   828  	if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
   829  		return err
   830  	}
   831  	if err := cc.bw.Flush(); err != nil {
   832  		return err
   833  	}
   834  	// Prevent new requests
   835  	cc.closing = true
   836  	return nil
   837  }
   838  
   839  // Close closes the client connection immediately.
   840  //
   841  // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
   842  func (cc *ClientConn) Close() error {
   843  	cc.mu.Lock()
   844  	defer cc.cond.Broadcast()
   845  	defer cc.mu.Unlock()
   846  	err := errors.New("http2: client connection force closed via ClientConn.Close")
   847  	for id, cs := range cc.streams {
   848  		select {
   849  		case cs.resc <- resAndError{err: err}:
   850  		default:
   851  		}
   852  		cs.bufPipe.CloseWithError(err)
   853  		delete(cc.streams, id)
   854  	}
   855  	cc.closed = true
   856  	return cc.tconn.Close()
   857  }
   858  
   859  // [Psiphon]
   860  // Request body sizes are typically under 64K; allocating 512K is problematic
   861  // in low-memory environments.
   862  //const maxAllocFrameSize = 512 << 10
   863  const maxAllocFrameSize = 64 << 10
   864  
   865  // frameBuffer returns a scratch buffer suitable for writing DATA frames.
   866  // They're capped at the min of the peer's max frame size or 512KB
   867  // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
   868  // bufers.
   869  func (cc *ClientConn) frameScratchBuffer() []byte {
   870  	cc.mu.Lock()
   871  	size := cc.maxFrameSize
   872  	if size > maxAllocFrameSize {
   873  		size = maxAllocFrameSize
   874  	}
   875  	for i, buf := range cc.freeBuf {
   876  		if len(buf) >= int(size) {
   877  			cc.freeBuf[i] = nil
   878  			cc.mu.Unlock()
   879  			return buf[:size]
   880  		}
   881  	}
   882  	cc.mu.Unlock()
   883  	return make([]byte, size)
   884  }
   885  
   886  func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
   887  	cc.mu.Lock()
   888  	defer cc.mu.Unlock()
   889  	const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
   890  	if len(cc.freeBuf) < maxBufs {
   891  		cc.freeBuf = append(cc.freeBuf, buf)
   892  		return
   893  	}
   894  	for i, old := range cc.freeBuf {
   895  		if old == nil {
   896  			cc.freeBuf[i] = buf
   897  			return
   898  		}
   899  	}
   900  	// forget about it.
   901  }
   902  
   903  // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
   904  // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
   905  var errRequestCanceled = errors.New("net/http: request canceled")
   906  
   907  func commaSeparatedTrailers(req *http.Request) (string, error) {
   908  	keys := make([]string, 0, len(req.Trailer))
   909  	for k := range req.Trailer {
   910  		k = http.CanonicalHeaderKey(k)
   911  		switch k {
   912  		case "Transfer-Encoding", "Trailer", "Content-Length":
   913  			return "", &badStringError{"invalid Trailer key", k}
   914  		}
   915  		keys = append(keys, k)
   916  	}
   917  	if len(keys) > 0 {
   918  		sort.Strings(keys)
   919  		return strings.Join(keys, ","), nil
   920  	}
   921  	return "", nil
   922  }
   923  
   924  func (cc *ClientConn) responseHeaderTimeout() time.Duration {
   925  	if cc.t.t1 != nil {
   926  		return cc.t.t1.ResponseHeaderTimeout
   927  	}
   928  	// No way to do this (yet?) with just an http2.Transport. Probably
   929  	// no need. Request.Cancel this is the new way. We only need to support
   930  	// this for compatibility with the old http.Transport fields when
   931  	// we're doing transparent http2.
   932  	return 0
   933  }
   934  
   935  // checkConnHeaders checks whether req has any invalid connection-level headers.
   936  // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
   937  // Certain headers are special-cased as okay but not transmitted later.
   938  func checkConnHeaders(req *http.Request) error {
   939  	if v := req.Header.Get("Upgrade"); v != "" {
   940  		return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
   941  	}
   942  	if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
   943  		return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
   944  	}
   945  	if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) {
   946  		return fmt.Errorf("http2: invalid Connection request header: %q", vv)
   947  	}
   948  	return nil
   949  }
   950  
   951  // actualContentLength returns a sanitized version of
   952  // req.ContentLength, where 0 actually means zero (not unknown) and -1
   953  // means unknown.
   954  func actualContentLength(req *http.Request) int64 {
   955  	if req.Body == nil || req.Body == http.NoBody {
   956  		return 0
   957  	}
   958  	if req.ContentLength != 0 {
   959  		return req.ContentLength
   960  	}
   961  	return -1
   962  }
   963  
   964  func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
   965  	resp, _, err := cc.roundTrip(req)
   966  	return resp, err
   967  }
   968  
   969  func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) {
   970  	if err := checkConnHeaders(req); err != nil {
   971  		return nil, false, err
   972  	}
   973  	if cc.idleTimer != nil {
   974  		cc.idleTimer.Stop()
   975  	}
   976  
   977  	trailers, err := commaSeparatedTrailers(req)
   978  	if err != nil {
   979  		return nil, false, err
   980  	}
   981  	hasTrailers := trailers != ""
   982  
   983  	cc.mu.Lock()
   984  	if err := cc.awaitOpenSlotForRequest(req); err != nil {
   985  		cc.mu.Unlock()
   986  		return nil, false, err
   987  	}
   988  
   989  	body := req.Body
   990  	contentLen := actualContentLength(req)
   991  	hasBody := contentLen != 0
   992  
   993  	// TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
   994  	var requestedGzip bool
   995  	if !cc.t.disableCompression() &&
   996  		req.Header.Get("Accept-Encoding") == "" &&
   997  		req.Header.Get("Range") == "" &&
   998  		req.Method != "HEAD" {
   999  		// Request gzip only, not deflate. Deflate is ambiguous and
  1000  		// not as universally supported anyway.
  1001  		// See: https://zlib.net/zlib_faq.html#faq39
  1002  		//
  1003  		// Note that we don't request this for HEAD requests,
  1004  		// due to a bug in nginx:
  1005  		//   http://trac.nginx.org/nginx/ticket/358
  1006  		//   https://golang.org/issue/5522
  1007  		//
  1008  		// We don't request gzip if the request is for a range, since
  1009  		// auto-decoding a portion of a gzipped document will just fail
  1010  		// anyway. See https://golang.org/issue/8923
  1011  		requestedGzip = true
  1012  	}
  1013  
  1014  	// we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  1015  	// sent by writeRequestBody below, along with any Trailers,
  1016  	// again in form HEADERS{1}, CONTINUATION{0,})
  1017  	hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
  1018  	if err != nil {
  1019  		cc.mu.Unlock()
  1020  		return nil, false, err
  1021  	}
  1022  
  1023  	cs := cc.newStream()
  1024  	cs.req = req
  1025  	cs.trace = httptrace.ContextClientTrace(req.Context())
  1026  	cs.requestedGzip = requestedGzip
  1027  	bodyWriter := cc.t.getBodyWriterState(cs, body)
  1028  	cs.on100 = bodyWriter.on100
  1029  
  1030  	cc.wmu.Lock()
  1031  	endStream := !hasBody && !hasTrailers
  1032  	werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  1033  	cc.wmu.Unlock()
  1034  	traceWroteHeaders(cs.trace)
  1035  	cc.mu.Unlock()
  1036  
  1037  	if werr != nil {
  1038  		if hasBody {
  1039  			req.Body.Close() // per RoundTripper contract
  1040  			bodyWriter.cancel()
  1041  		}
  1042  		cc.forgetStreamID(cs.ID)
  1043  		// Don't bother sending a RST_STREAM (our write already failed;
  1044  		// no need to keep writing)
  1045  		traceWroteRequest(cs.trace, werr)
  1046  		return nil, false, werr
  1047  	}
  1048  
  1049  	var respHeaderTimer <-chan time.Time
  1050  	if hasBody {
  1051  		bodyWriter.scheduleBodyWrite()
  1052  	} else {
  1053  		traceWroteRequest(cs.trace, nil)
  1054  		if d := cc.responseHeaderTimeout(); d != 0 {
  1055  			timer := time.NewTimer(d)
  1056  			defer timer.Stop()
  1057  			respHeaderTimer = timer.C
  1058  		}
  1059  	}
  1060  
  1061  	readLoopResCh := cs.resc
  1062  	bodyWritten := false
  1063  	ctx := req.Context()
  1064  
  1065  	handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) {
  1066  		res := re.res
  1067  		if re.err != nil || res.StatusCode > 299 {
  1068  			// On error or status code 3xx, 4xx, 5xx, etc abort any
  1069  			// ongoing write, assuming that the server doesn't care
  1070  			// about our request body. If the server replied with 1xx or
  1071  			// 2xx, however, then assume the server DOES potentially
  1072  			// want our body (e.g. full-duplex streaming:
  1073  			// golang.org/issue/13444). If it turns out the server
  1074  			// doesn't, they'll RST_STREAM us soon enough. This is a
  1075  			// heuristic to avoid adding knobs to Transport. Hopefully
  1076  			// we can keep it.
  1077  			bodyWriter.cancel()
  1078  			cs.abortRequestBodyWrite(errStopReqBodyWrite)
  1079  		}
  1080  		if re.err != nil {
  1081  			cc.forgetStreamID(cs.ID)
  1082  			return nil, cs.getStartedWrite(), re.err
  1083  		}
  1084  		res.Request = req
  1085  		res.TLS = cc.tlsState
  1086  		return res, false, nil
  1087  	}
  1088  
  1089  	for {
  1090  		select {
  1091  		case re := <-readLoopResCh:
  1092  			return handleReadLoopResponse(re)
  1093  		case <-respHeaderTimer:
  1094  			if !hasBody || bodyWritten {
  1095  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1096  			} else {
  1097  				bodyWriter.cancel()
  1098  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1099  			}
  1100  			cc.forgetStreamID(cs.ID)
  1101  			return nil, cs.getStartedWrite(), errTimeout
  1102  		case <-ctx.Done():
  1103  			if !hasBody || bodyWritten {
  1104  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1105  			} else {
  1106  				bodyWriter.cancel()
  1107  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1108  			}
  1109  			cc.forgetStreamID(cs.ID)
  1110  			return nil, cs.getStartedWrite(), ctx.Err()
  1111  		case <-req.Cancel:
  1112  			if !hasBody || bodyWritten {
  1113  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1114  			} else {
  1115  				bodyWriter.cancel()
  1116  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1117  			}
  1118  			cc.forgetStreamID(cs.ID)
  1119  			return nil, cs.getStartedWrite(), errRequestCanceled
  1120  		case <-cs.peerReset:
  1121  			// processResetStream already removed the
  1122  			// stream from the streams map; no need for
  1123  			// forgetStreamID.
  1124  			return nil, cs.getStartedWrite(), cs.resetErr
  1125  		case err := <-bodyWriter.resc:
  1126  			// Prefer the read loop's response, if available. Issue 16102.
  1127  			select {
  1128  			case re := <-readLoopResCh:
  1129  				return handleReadLoopResponse(re)
  1130  			default:
  1131  			}
  1132  			if err != nil {
  1133  				cc.forgetStreamID(cs.ID)
  1134  				return nil, cs.getStartedWrite(), err
  1135  			}
  1136  			bodyWritten = true
  1137  			if d := cc.responseHeaderTimeout(); d != 0 {
  1138  				timer := time.NewTimer(d)
  1139  				defer timer.Stop()
  1140  				respHeaderTimer = timer.C
  1141  			}
  1142  		}
  1143  	}
  1144  }
  1145  
  1146  // awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
  1147  // Must hold cc.mu.
  1148  func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
  1149  	var waitingForConn chan struct{}
  1150  	var waitingForConnErr error // guarded by cc.mu
  1151  	for {
  1152  		cc.lastActive = time.Now()
  1153  		if cc.closed || !cc.canTakeNewRequestLocked() {
  1154  			if waitingForConn != nil {
  1155  				close(waitingForConn)
  1156  			}
  1157  			return errClientConnUnusable
  1158  		}
  1159  		if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
  1160  			if waitingForConn != nil {
  1161  				close(waitingForConn)
  1162  			}
  1163  			return nil
  1164  		}
  1165  		// Unfortunately, we cannot wait on a condition variable and channel at
  1166  		// the same time, so instead, we spin up a goroutine to check if the
  1167  		// request is canceled while we wait for a slot to open in the connection.
  1168  		if waitingForConn == nil {
  1169  			waitingForConn = make(chan struct{})
  1170  			go func() {
  1171  				if err := awaitRequestCancel(req, waitingForConn); err != nil {
  1172  					cc.mu.Lock()
  1173  					waitingForConnErr = err
  1174  					cc.cond.Broadcast()
  1175  					cc.mu.Unlock()
  1176  				}
  1177  			}()
  1178  		}
  1179  		cc.pendingRequests++
  1180  		cc.cond.Wait()
  1181  		cc.pendingRequests--
  1182  		if waitingForConnErr != nil {
  1183  			return waitingForConnErr
  1184  		}
  1185  	}
  1186  }
  1187  
  1188  // requires cc.wmu be held
  1189  func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  1190  	first := true // first frame written (HEADERS is first, then CONTINUATION)
  1191  	for len(hdrs) > 0 && cc.werr == nil {
  1192  		chunk := hdrs
  1193  		if len(chunk) > maxFrameSize {
  1194  			chunk = chunk[:maxFrameSize]
  1195  		}
  1196  		hdrs = hdrs[len(chunk):]
  1197  		endHeaders := len(hdrs) == 0
  1198  		if first {
  1199  			cc.fr.WriteHeaders(HeadersFrameParam{
  1200  				StreamID:      streamID,
  1201  				BlockFragment: chunk,
  1202  				EndStream:     endStream,
  1203  				EndHeaders:    endHeaders,
  1204  			})
  1205  			first = false
  1206  		} else {
  1207  			cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  1208  		}
  1209  	}
  1210  	// TODO(bradfitz): this Flush could potentially block (as
  1211  	// could the WriteHeaders call(s) above), which means they
  1212  	// wouldn't respond to Request.Cancel being readable. That's
  1213  	// rare, but this should probably be in a goroutine.
  1214  	cc.bw.Flush()
  1215  	return cc.werr
  1216  }
  1217  
  1218  // internal error values; they don't escape to callers
  1219  var (
  1220  	// abort request body write; don't send cancel
  1221  	errStopReqBodyWrite = errors.New("http2: aborting request body write")
  1222  
  1223  	// abort request body write, but send stream reset of cancel.
  1224  	errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  1225  
  1226  	errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
  1227  )
  1228  
  1229  func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  1230  	cc := cs.cc
  1231  	sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  1232  	buf := cc.frameScratchBuffer()
  1233  	defer cc.putFrameScratchBuffer(buf)
  1234  
  1235  	defer func() {
  1236  		traceWroteRequest(cs.trace, err)
  1237  		// TODO: write h12Compare test showing whether
  1238  		// Request.Body is closed by the Transport,
  1239  		// and in multiple cases: server replies <=299 and >299
  1240  		// while still writing request body
  1241  		cerr := bodyCloser.Close()
  1242  		if err == nil {
  1243  			err = cerr
  1244  		}
  1245  	}()
  1246  
  1247  	req := cs.req
  1248  	hasTrailers := req.Trailer != nil
  1249  	remainLen := actualContentLength(req)
  1250  	hasContentLen := remainLen != -1
  1251  
  1252  	var sawEOF bool
  1253  	for !sawEOF {
  1254  		n, err := body.Read(buf[:len(buf)-1])
  1255  		if hasContentLen {
  1256  			remainLen -= int64(n)
  1257  			if remainLen == 0 && err == nil {
  1258  				// The request body's Content-Length was predeclared and
  1259  				// we just finished reading it all, but the underlying io.Reader
  1260  				// returned the final chunk with a nil error (which is one of
  1261  				// the two valid things a Reader can do at EOF). Because we'd prefer
  1262  				// to send the END_STREAM bit early, double-check that we're actually
  1263  				// at EOF. Subsequent reads should return (0, EOF) at this point.
  1264  				// If either value is different, we return an error in one of two ways below.
  1265  				var n1 int
  1266  				n1, err = body.Read(buf[n:])
  1267  				remainLen -= int64(n1)
  1268  			}
  1269  			if remainLen < 0 {
  1270  				err = errReqBodyTooLong
  1271  				cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1272  				return err
  1273  			}
  1274  		}
  1275  		if err == io.EOF {
  1276  			sawEOF = true
  1277  			err = nil
  1278  		} else if err != nil {
  1279  			cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1280  			return err
  1281  		}
  1282  
  1283  		remain := buf[:n]
  1284  		for len(remain) > 0 && err == nil {
  1285  			var allowed int32
  1286  			allowed, err = cs.awaitFlowControl(len(remain))
  1287  			switch {
  1288  			case err == errStopReqBodyWrite:
  1289  				return err
  1290  			case err == errStopReqBodyWriteAndCancel:
  1291  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1292  				return err
  1293  			case err != nil:
  1294  				return err
  1295  			}
  1296  			cc.wmu.Lock()
  1297  			data := remain[:allowed]
  1298  			remain = remain[allowed:]
  1299  			sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  1300  			err = cc.fr.WriteData(cs.ID, sentEnd, data)
  1301  			if err == nil {
  1302  				// TODO(bradfitz): this flush is for latency, not bandwidth.
  1303  				// Most requests won't need this. Make this opt-in or
  1304  				// opt-out?  Use some heuristic on the body type? Nagel-like
  1305  				// timers?  Based on 'n'? Only last chunk of this for loop,
  1306  				// unless flow control tokens are low? For now, always.
  1307  				// If we change this, see comment below.
  1308  				err = cc.bw.Flush()
  1309  			}
  1310  			cc.wmu.Unlock()
  1311  		}
  1312  		if err != nil {
  1313  			return err
  1314  		}
  1315  	}
  1316  
  1317  	if sentEnd {
  1318  		// Already sent END_STREAM (which implies we have no
  1319  		// trailers) and flushed, because currently all
  1320  		// WriteData frames above get a flush. So we're done.
  1321  		return nil
  1322  	}
  1323  
  1324  	var trls []byte
  1325  	if hasTrailers {
  1326  		cc.mu.Lock()
  1327  		trls, err = cc.encodeTrailers(req)
  1328  		cc.mu.Unlock()
  1329  		if err != nil {
  1330  			cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
  1331  			cc.forgetStreamID(cs.ID)
  1332  			return err
  1333  		}
  1334  	}
  1335  
  1336  	cc.mu.Lock()
  1337  	maxFrameSize := int(cc.maxFrameSize)
  1338  	cc.mu.Unlock()
  1339  
  1340  	cc.wmu.Lock()
  1341  	defer cc.wmu.Unlock()
  1342  
  1343  	// Two ways to send END_STREAM: either with trailers, or
  1344  	// with an empty DATA frame.
  1345  	if len(trls) > 0 {
  1346  		err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1347  	} else {
  1348  		err = cc.fr.WriteData(cs.ID, true, nil)
  1349  	}
  1350  	if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1351  		err = ferr
  1352  	}
  1353  	return err
  1354  }
  1355  
  1356  // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1357  // control tokens from the server.
  1358  // It returns either the non-zero number of tokens taken or an error
  1359  // if the stream is dead.
  1360  func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1361  	cc := cs.cc
  1362  	cc.mu.Lock()
  1363  	defer cc.mu.Unlock()
  1364  	for {
  1365  		if cc.closed {
  1366  			return 0, errClientConnClosed
  1367  		}
  1368  		if cs.stopReqBody != nil {
  1369  			return 0, cs.stopReqBody
  1370  		}
  1371  		if err := cs.checkResetOrDone(); err != nil {
  1372  			return 0, err
  1373  		}
  1374  		if a := cs.flow.available(); a > 0 {
  1375  			take := a
  1376  			if int(take) > maxBytes {
  1377  
  1378  				take = int32(maxBytes) // can't truncate int; take is int32
  1379  			}
  1380  			if take > int32(cc.maxFrameSize) {
  1381  				take = int32(cc.maxFrameSize)
  1382  			}
  1383  			cs.flow.take(take)
  1384  			return take, nil
  1385  		}
  1386  		cc.cond.Wait()
  1387  	}
  1388  }
  1389  
  1390  type badStringError struct {
  1391  	what string
  1392  	str  string
  1393  }
  1394  
  1395  func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  1396  
  1397  // requires cc.mu be held.
  1398  func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1399  	cc.hbuf.Reset()
  1400  
  1401  	host := req.Host
  1402  	if host == "" {
  1403  		host = req.URL.Host
  1404  	}
  1405  	host, err := httpguts.PunycodeHostPort(host)
  1406  	if err != nil {
  1407  		return nil, err
  1408  	}
  1409  
  1410  	var path string
  1411  	if req.Method != "CONNECT" {
  1412  		path = req.URL.RequestURI()
  1413  		if !validPseudoPath(path) {
  1414  			orig := path
  1415  			path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1416  			if !validPseudoPath(path) {
  1417  				if req.URL.Opaque != "" {
  1418  					return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1419  				} else {
  1420  					return nil, fmt.Errorf("invalid request :path %q", orig)
  1421  				}
  1422  			}
  1423  		}
  1424  	}
  1425  
  1426  	// Check for any invalid headers and return an error before we
  1427  	// potentially pollute our hpack state. (We want to be able to
  1428  	// continue to reuse the hpack encoder for future requests)
  1429  	for k, vv := range req.Header {
  1430  		if !httpguts.ValidHeaderFieldName(k) {
  1431  			return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1432  		}
  1433  		for _, v := range vv {
  1434  			if !httpguts.ValidHeaderFieldValue(v) {
  1435  				return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  1436  			}
  1437  		}
  1438  	}
  1439  
  1440  	enumerateHeaders := func(f func(name, value string)) {
  1441  		// 8.1.2.3 Request Pseudo-Header Fields
  1442  		// The :path pseudo-header field includes the path and query parts of the
  1443  		// target URI (the path-absolute production and optionally a '?' character
  1444  		// followed by the query production (see Sections 3.3 and 3.4 of
  1445  		// [RFC3986]).
  1446  		f(":authority", host)
  1447  		m := req.Method
  1448  		if m == "" {
  1449  			m = http.MethodGet
  1450  		}
  1451  		f(":method", m)
  1452  		if req.Method != "CONNECT" {
  1453  			f(":path", path)
  1454  			f(":scheme", req.URL.Scheme)
  1455  		}
  1456  		if trailers != "" {
  1457  			f("trailer", trailers)
  1458  		}
  1459  
  1460  		var didUA bool
  1461  		for k, vv := range req.Header {
  1462  			if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") {
  1463  				// Host is :authority, already sent.
  1464  				// Content-Length is automatic, set below.
  1465  				continue
  1466  			} else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") ||
  1467  				strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") ||
  1468  				strings.EqualFold(k, "keep-alive") {
  1469  				// Per 8.1.2.2 Connection-Specific Header
  1470  				// Fields, don't send connection-specific
  1471  				// fields. We have already checked if any
  1472  				// are error-worthy so just ignore the rest.
  1473  				continue
  1474  			} else if strings.EqualFold(k, "user-agent") {
  1475  				// Match Go's http1 behavior: at most one
  1476  				// User-Agent. If set to nil or empty string,
  1477  				// then omit it. Otherwise if not mentioned,
  1478  				// include the default (below).
  1479  				didUA = true
  1480  				if len(vv) < 1 {
  1481  					continue
  1482  				}
  1483  				vv = vv[:1]
  1484  				if vv[0] == "" {
  1485  					continue
  1486  				}
  1487  
  1488  			}
  1489  
  1490  			for _, v := range vv {
  1491  				f(k, v)
  1492  			}
  1493  		}
  1494  		if shouldSendReqContentLength(req.Method, contentLength) {
  1495  			f("content-length", strconv.FormatInt(contentLength, 10))
  1496  		}
  1497  		if addGzipHeader {
  1498  			f("accept-encoding", "gzip")
  1499  		}
  1500  		if !didUA {
  1501  			f("user-agent", defaultUserAgent)
  1502  		}
  1503  	}
  1504  
  1505  	// Do a first pass over the headers counting bytes to ensure
  1506  	// we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1507  	// separate pass before encoding the headers to prevent
  1508  	// modifying the hpack state.
  1509  	hlSize := uint64(0)
  1510  	enumerateHeaders(func(name, value string) {
  1511  		hf := hpack.HeaderField{Name: name, Value: value}
  1512  		hlSize += uint64(hf.Size())
  1513  	})
  1514  
  1515  	if hlSize > cc.peerMaxHeaderListSize {
  1516  		return nil, errRequestHeaderListSize
  1517  	}
  1518  
  1519  	trace := httptrace.ContextClientTrace(req.Context())
  1520  	traceHeaders := traceHasWroteHeaderField(trace)
  1521  
  1522  	// Header list size is ok. Write the headers.
  1523  	enumerateHeaders(func(name, value string) {
  1524  		name = strings.ToLower(name)
  1525  		cc.writeHeader(name, value)
  1526  		if traceHeaders {
  1527  			traceWroteHeaderField(trace, name, value)
  1528  		}
  1529  	})
  1530  
  1531  	return cc.hbuf.Bytes(), nil
  1532  }
  1533  
  1534  // shouldSendReqContentLength reports whether the http2.Transport should send
  1535  // a "content-length" request header. This logic is basically a copy of the net/http
  1536  // transferWriter.shouldSendContentLength.
  1537  // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1538  // -1 means unknown.
  1539  func shouldSendReqContentLength(method string, contentLength int64) bool {
  1540  	if contentLength > 0 {
  1541  		return true
  1542  	}
  1543  	if contentLength < 0 {
  1544  		return false
  1545  	}
  1546  	// For zero bodies, whether we send a content-length depends on the method.
  1547  	// It also kinda doesn't matter for http2 either way, with END_STREAM.
  1548  	switch method {
  1549  	case "POST", "PUT", "PATCH":
  1550  		return true
  1551  	default:
  1552  		return false
  1553  	}
  1554  }
  1555  
  1556  // requires cc.mu be held.
  1557  func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
  1558  	cc.hbuf.Reset()
  1559  
  1560  	hlSize := uint64(0)
  1561  	for k, vv := range req.Trailer {
  1562  		for _, v := range vv {
  1563  			hf := hpack.HeaderField{Name: k, Value: v}
  1564  			hlSize += uint64(hf.Size())
  1565  		}
  1566  	}
  1567  	if hlSize > cc.peerMaxHeaderListSize {
  1568  		return nil, errRequestHeaderListSize
  1569  	}
  1570  
  1571  	for k, vv := range req.Trailer {
  1572  		// Transfer-Encoding, etc.. have already been filtered at the
  1573  		// start of RoundTrip
  1574  		lowKey := strings.ToLower(k)
  1575  		for _, v := range vv {
  1576  			cc.writeHeader(lowKey, v)
  1577  		}
  1578  	}
  1579  	return cc.hbuf.Bytes(), nil
  1580  }
  1581  
  1582  func (cc *ClientConn) writeHeader(name, value string) {
  1583  	if VerboseLogs {
  1584  		log.Printf("http2: Transport encoding header %q = %q", name, value)
  1585  	}
  1586  	cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1587  }
  1588  
  1589  type resAndError struct {
  1590  	res *http.Response
  1591  	err error
  1592  }
  1593  
  1594  // requires cc.mu be held.
  1595  func (cc *ClientConn) newStream() *clientStream {
  1596  	cs := &clientStream{
  1597  		cc:        cc,
  1598  		ID:        cc.nextStreamID,
  1599  		resc:      make(chan resAndError, 1),
  1600  		peerReset: make(chan struct{}),
  1601  		done:      make(chan struct{}),
  1602  	}
  1603  	cs.flow.add(int32(cc.initialWindowSize))
  1604  	cs.flow.setConnFlow(&cc.flow)
  1605  	cs.inflow.add(transportDefaultStreamFlow)
  1606  	cs.inflow.setConnFlow(&cc.inflow)
  1607  	cc.nextStreamID += 2
  1608  	cc.streams[cs.ID] = cs
  1609  	return cs
  1610  }
  1611  
  1612  func (cc *ClientConn) forgetStreamID(id uint32) {
  1613  	cc.streamByID(id, true)
  1614  }
  1615  
  1616  func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1617  	cc.mu.Lock()
  1618  	defer cc.mu.Unlock()
  1619  	cs := cc.streams[id]
  1620  	if andRemove && cs != nil && !cc.closed {
  1621  		cc.lastActive = time.Now()
  1622  		delete(cc.streams, id)
  1623  		if len(cc.streams) == 0 && cc.idleTimer != nil {
  1624  			cc.idleTimer.Reset(cc.idleTimeout)
  1625  		}
  1626  		close(cs.done)
  1627  		// Wake up checkResetOrDone via clientStream.awaitFlowControl and
  1628  		// wake up RoundTrip if there is a pending request.
  1629  		cc.cond.Broadcast()
  1630  	}
  1631  	return cs
  1632  }
  1633  
  1634  // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1635  type clientConnReadLoop struct {
  1636  	cc            *ClientConn
  1637  	closeWhenIdle bool
  1638  }
  1639  
  1640  // readLoop runs in its own goroutine and reads and dispatches frames.
  1641  func (cc *ClientConn) readLoop() {
  1642  	rl := &clientConnReadLoop{cc: cc}
  1643  	defer rl.cleanup()
  1644  	cc.readerErr = rl.run()
  1645  	if ce, ok := cc.readerErr.(ConnectionError); ok {
  1646  		cc.wmu.Lock()
  1647  		cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1648  		cc.wmu.Unlock()
  1649  	}
  1650  }
  1651  
  1652  // GoAwayError is returned by the Transport when the server closes the
  1653  // TCP connection after sending a GOAWAY frame.
  1654  type GoAwayError struct {
  1655  	LastStreamID uint32
  1656  	ErrCode      ErrCode
  1657  	DebugData    string
  1658  }
  1659  
  1660  func (e GoAwayError) Error() string {
  1661  	return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1662  		e.LastStreamID, e.ErrCode, e.DebugData)
  1663  }
  1664  
  1665  func isEOFOrNetReadError(err error) bool {
  1666  	if err == io.EOF {
  1667  		return true
  1668  	}
  1669  	ne, ok := err.(*net.OpError)
  1670  	return ok && ne.Op == "read"
  1671  }
  1672  
  1673  func (rl *clientConnReadLoop) cleanup() {
  1674  	cc := rl.cc
  1675  	defer cc.tconn.Close()
  1676  	defer cc.t.connPool().MarkDead(cc)
  1677  	defer close(cc.readerDone)
  1678  
  1679  	if cc.idleTimer != nil {
  1680  		cc.idleTimer.Stop()
  1681  	}
  1682  
  1683  	// Close any response bodies if the server closes prematurely.
  1684  	// TODO: also do this if we've written the headers but not
  1685  	// gotten a response yet.
  1686  	err := cc.readerErr
  1687  	cc.mu.Lock()
  1688  	if cc.goAway != nil && isEOFOrNetReadError(err) {
  1689  		err = GoAwayError{
  1690  			LastStreamID: cc.goAway.LastStreamID,
  1691  			ErrCode:      cc.goAway.ErrCode,
  1692  			DebugData:    cc.goAwayDebug,
  1693  		}
  1694  	} else if err == io.EOF {
  1695  		err = io.ErrUnexpectedEOF
  1696  	}
  1697  	for _, cs := range cc.streams {
  1698  		cs.bufPipe.CloseWithError(err) // no-op if already closed
  1699  		select {
  1700  		case cs.resc <- resAndError{err: err}:
  1701  		default:
  1702  		}
  1703  		close(cs.done)
  1704  	}
  1705  	cc.closed = true
  1706  	cc.cond.Broadcast()
  1707  	cc.mu.Unlock()
  1708  }
  1709  
  1710  func (rl *clientConnReadLoop) run() error {
  1711  	cc := rl.cc
  1712  	rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1713  	gotReply := false // ever saw a HEADERS reply
  1714  	gotSettings := false
  1715  	for {
  1716  		f, err := cc.fr.ReadFrame()
  1717  		if err != nil {
  1718  			cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1719  		}
  1720  		if se, ok := err.(StreamError); ok {
  1721  			if cs := cc.streamByID(se.StreamID, false); cs != nil {
  1722  				cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1723  				cs.cc.forgetStreamID(cs.ID)
  1724  				if se.Cause == nil {
  1725  					se.Cause = cc.fr.errDetail
  1726  				}
  1727  				rl.endStreamError(cs, se)
  1728  			}
  1729  			continue
  1730  		} else if err != nil {
  1731  			return err
  1732  		}
  1733  		if VerboseLogs {
  1734  			cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1735  		}
  1736  		if !gotSettings {
  1737  			if _, ok := f.(*SettingsFrame); !ok {
  1738  				cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1739  				return ConnectionError(ErrCodeProtocol)
  1740  			}
  1741  			gotSettings = true
  1742  		}
  1743  		maybeIdle := false // whether frame might transition us to idle
  1744  
  1745  		switch f := f.(type) {
  1746  		case *MetaHeadersFrame:
  1747  			err = rl.processHeaders(f)
  1748  			maybeIdle = true
  1749  			gotReply = true
  1750  		case *DataFrame:
  1751  			err = rl.processData(f)
  1752  			maybeIdle = true
  1753  		case *GoAwayFrame:
  1754  			err = rl.processGoAway(f)
  1755  			maybeIdle = true
  1756  		case *RSTStreamFrame:
  1757  			err = rl.processResetStream(f)
  1758  			maybeIdle = true
  1759  		case *SettingsFrame:
  1760  			err = rl.processSettings(f)
  1761  		case *PushPromiseFrame:
  1762  			err = rl.processPushPromise(f)
  1763  		case *WindowUpdateFrame:
  1764  			err = rl.processWindowUpdate(f)
  1765  		case *PingFrame:
  1766  			err = rl.processPing(f)
  1767  		default:
  1768  			cc.logf("Transport: unhandled response frame type %T", f)
  1769  		}
  1770  		if err != nil {
  1771  			if VerboseLogs {
  1772  				cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  1773  			}
  1774  			return err
  1775  		}
  1776  		if rl.closeWhenIdle && gotReply && maybeIdle {
  1777  			cc.closeIfIdle()
  1778  		}
  1779  	}
  1780  }
  1781  
  1782  func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  1783  	cc := rl.cc
  1784  	cs := cc.streamByID(f.StreamID, false)
  1785  	if cs == nil {
  1786  		// We'd get here if we canceled a request while the
  1787  		// server had its response still in flight. So if this
  1788  		// was just something we canceled, ignore it.
  1789  		return nil
  1790  	}
  1791  	if f.StreamEnded() {
  1792  		// Issue 20521: If the stream has ended, streamByID() causes
  1793  		// clientStream.done to be closed, which causes the request's bodyWriter
  1794  		// to be closed with an errStreamClosed, which may be received by
  1795  		// clientConn.RoundTrip before the result of processing these headers.
  1796  		// Deferring stream closure allows the header processing to occur first.
  1797  		// clientConn.RoundTrip may still receive the bodyWriter error first, but
  1798  		// the fix for issue 16102 prioritises any response.
  1799  		//
  1800  		// Issue 22413: If there is no request body, we should close the
  1801  		// stream before writing to cs.resc so that the stream is closed
  1802  		// immediately once RoundTrip returns.
  1803  		if cs.req.Body != nil {
  1804  			defer cc.forgetStreamID(f.StreamID)
  1805  		} else {
  1806  			cc.forgetStreamID(f.StreamID)
  1807  		}
  1808  	}
  1809  	if !cs.firstByte {
  1810  		if cs.trace != nil {
  1811  			// TODO(bradfitz): move first response byte earlier,
  1812  			// when we first read the 9 byte header, not waiting
  1813  			// until all the HEADERS+CONTINUATION frames have been
  1814  			// merged. This works for now.
  1815  			traceFirstResponseByte(cs.trace)
  1816  		}
  1817  		cs.firstByte = true
  1818  	}
  1819  	if !cs.pastHeaders {
  1820  		cs.pastHeaders = true
  1821  	} else {
  1822  		return rl.processTrailers(cs, f)
  1823  	}
  1824  
  1825  	res, err := rl.handleResponse(cs, f)
  1826  	if err != nil {
  1827  		if _, ok := err.(ConnectionError); ok {
  1828  			return err
  1829  		}
  1830  		// Any other error type is a stream error.
  1831  		cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  1832  		cc.forgetStreamID(cs.ID)
  1833  		cs.resc <- resAndError{err: err}
  1834  		return nil // return nil from process* funcs to keep conn alive
  1835  	}
  1836  	if res == nil {
  1837  		// (nil, nil) special case. See handleResponse docs.
  1838  		return nil
  1839  	}
  1840  	cs.resTrailer = &res.Trailer
  1841  	cs.resc <- resAndError{res: res}
  1842  	return nil
  1843  }
  1844  
  1845  // may return error types nil, or ConnectionError. Any other error value
  1846  // is a StreamError of type ErrCodeProtocol. The returned error in that case
  1847  // is the detail.
  1848  //
  1849  // As a special case, handleResponse may return (nil, nil) to skip the
  1850  // frame (currently only used for 1xx responses).
  1851  func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  1852  	if f.Truncated {
  1853  		return nil, errResponseHeaderListSize
  1854  	}
  1855  
  1856  	status := f.PseudoValue("status")
  1857  	if status == "" {
  1858  		return nil, errors.New("malformed response from server: missing status pseudo header")
  1859  	}
  1860  	statusCode, err := strconv.Atoi(status)
  1861  	if err != nil {
  1862  		return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  1863  	}
  1864  
  1865  	header := make(http.Header)
  1866  	res := &http.Response{
  1867  		Proto:      "HTTP/2.0",
  1868  		ProtoMajor: 2,
  1869  		Header:     header,
  1870  		StatusCode: statusCode,
  1871  		Status:     status + " " + http.StatusText(statusCode),
  1872  	}
  1873  	for _, hf := range f.RegularFields() {
  1874  		key := http.CanonicalHeaderKey(hf.Name)
  1875  		if key == "Trailer" {
  1876  			t := res.Trailer
  1877  			if t == nil {
  1878  				t = make(http.Header)
  1879  				res.Trailer = t
  1880  			}
  1881  			foreachHeaderElement(hf.Value, func(v string) {
  1882  				t[http.CanonicalHeaderKey(v)] = nil
  1883  			})
  1884  		} else {
  1885  			header[key] = append(header[key], hf.Value)
  1886  		}
  1887  	}
  1888  
  1889  	if statusCode >= 100 && statusCode <= 199 {
  1890  		cs.num1xx++
  1891  		const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
  1892  		if cs.num1xx > max1xxResponses {
  1893  			return nil, errors.New("http2: too many 1xx informational responses")
  1894  		}
  1895  		if fn := cs.get1xxTraceFunc(); fn != nil {
  1896  			if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
  1897  				return nil, err
  1898  			}
  1899  		}
  1900  		if statusCode == 100 {
  1901  			traceGot100Continue(cs.trace)
  1902  			if cs.on100 != nil {
  1903  				cs.on100() // forces any write delay timer to fire
  1904  			}
  1905  		}
  1906  		cs.pastHeaders = false // do it all again
  1907  		return nil, nil
  1908  	}
  1909  
  1910  	streamEnded := f.StreamEnded()
  1911  	isHead := cs.req.Method == "HEAD"
  1912  	if !streamEnded || isHead {
  1913  		res.ContentLength = -1
  1914  		if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1915  			if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1916  				res.ContentLength = clen64
  1917  			} else {
  1918  				// TODO: care? unlike http/1, it won't mess up our framing, so it's
  1919  				// more safe smuggling-wise to ignore.
  1920  			}
  1921  		} else if len(clens) > 1 {
  1922  			// TODO: care? unlike http/1, it won't mess up our framing, so it's
  1923  			// more safe smuggling-wise to ignore.
  1924  		}
  1925  	}
  1926  
  1927  	if streamEnded || isHead {
  1928  		res.Body = noBody
  1929  		return res, nil
  1930  	}
  1931  
  1932  	cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
  1933  	cs.bytesRemain = res.ContentLength
  1934  	res.Body = transportResponseBody{cs}
  1935  	go cs.awaitRequestCancel(cs.req)
  1936  
  1937  	if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1938  		res.Header.Del("Content-Encoding")
  1939  		res.Header.Del("Content-Length")
  1940  		res.ContentLength = -1
  1941  		res.Body = &gzipReader{body: res.Body}
  1942  		res.Uncompressed = true
  1943  	}
  1944  	return res, nil
  1945  }
  1946  
  1947  func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  1948  	if cs.pastTrailers {
  1949  		// Too many HEADERS frames for this stream.
  1950  		return ConnectionError(ErrCodeProtocol)
  1951  	}
  1952  	cs.pastTrailers = true
  1953  	if !f.StreamEnded() {
  1954  		// We expect that any headers for trailers also
  1955  		// has END_STREAM.
  1956  		return ConnectionError(ErrCodeProtocol)
  1957  	}
  1958  	if len(f.PseudoFields()) > 0 {
  1959  		// No pseudo header fields are defined for trailers.
  1960  		// TODO: ConnectionError might be overly harsh? Check.
  1961  		return ConnectionError(ErrCodeProtocol)
  1962  	}
  1963  
  1964  	trailer := make(http.Header)
  1965  	for _, hf := range f.RegularFields() {
  1966  		key := http.CanonicalHeaderKey(hf.Name)
  1967  		trailer[key] = append(trailer[key], hf.Value)
  1968  	}
  1969  	cs.trailer = trailer
  1970  
  1971  	rl.endStream(cs)
  1972  	return nil
  1973  }
  1974  
  1975  // transportResponseBody is the concrete type of Transport.RoundTrip's
  1976  // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1977  // On Close it sends RST_STREAM if EOF wasn't already seen.
  1978  type transportResponseBody struct {
  1979  	cs *clientStream
  1980  }
  1981  
  1982  func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1983  	cs := b.cs
  1984  	cc := cs.cc
  1985  
  1986  	if cs.readErr != nil {
  1987  		return 0, cs.readErr
  1988  	}
  1989  	n, err = b.cs.bufPipe.Read(p)
  1990  	if cs.bytesRemain != -1 {
  1991  		if int64(n) > cs.bytesRemain {
  1992  			n = int(cs.bytesRemain)
  1993  			if err == nil {
  1994  				err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1995  				cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1996  			}
  1997  			cs.readErr = err
  1998  			return int(cs.bytesRemain), err
  1999  		}
  2000  		cs.bytesRemain -= int64(n)
  2001  		if err == io.EOF && cs.bytesRemain > 0 {
  2002  			err = io.ErrUnexpectedEOF
  2003  			cs.readErr = err
  2004  			return n, err
  2005  		}
  2006  	}
  2007  	if n == 0 {
  2008  		// No flow control tokens to send back.
  2009  		return
  2010  	}
  2011  
  2012  	cc.mu.Lock()
  2013  	defer cc.mu.Unlock()
  2014  
  2015  	var connAdd, streamAdd int32
  2016  	// Check the conn-level first, before the stream-level.
  2017  	if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  2018  		connAdd = transportDefaultConnFlow - v
  2019  		cc.inflow.add(connAdd)
  2020  	}
  2021  	if err == nil { // No need to refresh if the stream is over or failed.
  2022  		// Consider any buffered body data (read from the conn but not
  2023  		// consumed by the client) when computing flow control for this
  2024  		// stream.
  2025  		v := int(cs.inflow.available()) + cs.bufPipe.Len()
  2026  		if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  2027  			streamAdd = int32(transportDefaultStreamFlow - v)
  2028  			cs.inflow.add(streamAdd)
  2029  		}
  2030  	}
  2031  	if connAdd != 0 || streamAdd != 0 {
  2032  		cc.wmu.Lock()
  2033  		defer cc.wmu.Unlock()
  2034  		if connAdd != 0 {
  2035  			cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  2036  		}
  2037  		if streamAdd != 0 {
  2038  			cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  2039  		}
  2040  		cc.bw.Flush()
  2041  	}
  2042  	return
  2043  }
  2044  
  2045  var errClosedResponseBody = errors.New("http2: response body closed")
  2046  
  2047  func (b transportResponseBody) Close() error {
  2048  	cs := b.cs
  2049  	cc := cs.cc
  2050  
  2051  	serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
  2052  	unread := cs.bufPipe.Len()
  2053  
  2054  	if unread > 0 || !serverSentStreamEnd {
  2055  		cc.mu.Lock()
  2056  		cc.wmu.Lock()
  2057  		if !serverSentStreamEnd {
  2058  			cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
  2059  			cs.didReset = true
  2060  		}
  2061  		// Return connection-level flow control.
  2062  		if unread > 0 {
  2063  			cc.inflow.add(int32(unread))
  2064  			cc.fr.WriteWindowUpdate(0, uint32(unread))
  2065  		}
  2066  		cc.bw.Flush()
  2067  		cc.wmu.Unlock()
  2068  		cc.mu.Unlock()
  2069  	}
  2070  
  2071  	cs.bufPipe.BreakWithError(errClosedResponseBody)
  2072  	cc.forgetStreamID(cs.ID)
  2073  	return nil
  2074  }
  2075  
  2076  func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  2077  	cc := rl.cc
  2078  	cs := cc.streamByID(f.StreamID, f.StreamEnded())
  2079  	data := f.Data()
  2080  	if cs == nil {
  2081  		cc.mu.Lock()
  2082  		neverSent := cc.nextStreamID
  2083  		cc.mu.Unlock()
  2084  		if f.StreamID >= neverSent {
  2085  			// We never asked for this.
  2086  			cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  2087  			return ConnectionError(ErrCodeProtocol)
  2088  		}
  2089  		// We probably did ask for this, but canceled. Just ignore it.
  2090  		// TODO: be stricter here? only silently ignore things which
  2091  		// we canceled, but not things which were closed normally
  2092  		// by the peer? Tough without accumulating too much state.
  2093  
  2094  		// But at least return their flow control:
  2095  		if f.Length > 0 {
  2096  			cc.mu.Lock()
  2097  			cc.inflow.add(int32(f.Length))
  2098  			cc.mu.Unlock()
  2099  
  2100  			cc.wmu.Lock()
  2101  			cc.fr.WriteWindowUpdate(0, uint32(f.Length))
  2102  			cc.bw.Flush()
  2103  			cc.wmu.Unlock()
  2104  		}
  2105  		return nil
  2106  	}
  2107  	if !cs.firstByte {
  2108  		cc.logf("protocol error: received DATA before a HEADERS frame")
  2109  		rl.endStreamError(cs, StreamError{
  2110  			StreamID: f.StreamID,
  2111  			Code:     ErrCodeProtocol,
  2112  		})
  2113  		return nil
  2114  	}
  2115  	if f.Length > 0 {
  2116  		if cs.req.Method == "HEAD" && len(data) > 0 {
  2117  			cc.logf("protocol error: received DATA on a HEAD request")
  2118  			rl.endStreamError(cs, StreamError{
  2119  				StreamID: f.StreamID,
  2120  				Code:     ErrCodeProtocol,
  2121  			})
  2122  			return nil
  2123  		}
  2124  		// Check connection-level flow control.
  2125  		cc.mu.Lock()
  2126  		if cs.inflow.available() >= int32(f.Length) {
  2127  			cs.inflow.take(int32(f.Length))
  2128  		} else {
  2129  			cc.mu.Unlock()
  2130  			return ConnectionError(ErrCodeFlowControl)
  2131  		}
  2132  		// Return any padded flow control now, since we won't
  2133  		// refund it later on body reads.
  2134  		var refund int
  2135  		if pad := int(f.Length) - len(data); pad > 0 {
  2136  			refund += pad
  2137  		}
  2138  		// Return len(data) now if the stream is already closed,
  2139  		// since data will never be read.
  2140  		didReset := cs.didReset
  2141  		if didReset {
  2142  			refund += len(data)
  2143  		}
  2144  		if refund > 0 {
  2145  			cc.inflow.add(int32(refund))
  2146  			cc.wmu.Lock()
  2147  			cc.fr.WriteWindowUpdate(0, uint32(refund))
  2148  			if !didReset {
  2149  				cs.inflow.add(int32(refund))
  2150  				cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
  2151  			}
  2152  			cc.bw.Flush()
  2153  			cc.wmu.Unlock()
  2154  		}
  2155  		cc.mu.Unlock()
  2156  
  2157  		if len(data) > 0 && !didReset {
  2158  			if _, err := cs.bufPipe.Write(data); err != nil {
  2159  				rl.endStreamError(cs, err)
  2160  				return err
  2161  			}
  2162  		}
  2163  	}
  2164  
  2165  	if f.StreamEnded() {
  2166  		rl.endStream(cs)
  2167  	}
  2168  	return nil
  2169  }
  2170  
  2171  var errInvalidTrailers = errors.New("http2: invalid trailers")
  2172  
  2173  func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  2174  	// TODO: check that any declared content-length matches, like
  2175  	// server.go's (*stream).endStream method.
  2176  	rl.endStreamError(cs, nil)
  2177  }
  2178  
  2179  func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  2180  	var code func()
  2181  	if err == nil {
  2182  		err = io.EOF
  2183  		code = cs.copyTrailers
  2184  	}
  2185  	if isConnectionCloseRequest(cs.req) {
  2186  		rl.closeWhenIdle = true
  2187  	}
  2188  	cs.bufPipe.closeWithErrorAndCode(err, code)
  2189  
  2190  	select {
  2191  	case cs.resc <- resAndError{err: err}:
  2192  	default:
  2193  	}
  2194  }
  2195  
  2196  func (cs *clientStream) copyTrailers() {
  2197  	for k, vv := range cs.trailer {
  2198  		t := cs.resTrailer
  2199  		if *t == nil {
  2200  			*t = make(http.Header)
  2201  		}
  2202  		(*t)[k] = vv
  2203  	}
  2204  }
  2205  
  2206  func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  2207  	cc := rl.cc
  2208  	cc.t.connPool().MarkDead(cc)
  2209  	if f.ErrCode != 0 {
  2210  		// TODO: deal with GOAWAY more. particularly the error code
  2211  		cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  2212  	}
  2213  	cc.setGoAway(f)
  2214  	return nil
  2215  }
  2216  
  2217  func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  2218  	cc := rl.cc
  2219  	cc.mu.Lock()
  2220  	defer cc.mu.Unlock()
  2221  
  2222  	if f.IsAck() {
  2223  		if cc.wantSettingsAck {
  2224  			cc.wantSettingsAck = false
  2225  			return nil
  2226  		}
  2227  		return ConnectionError(ErrCodeProtocol)
  2228  	}
  2229  
  2230  	err := f.ForeachSetting(func(s Setting) error {
  2231  		switch s.ID {
  2232  		case SettingMaxFrameSize:
  2233  			cc.maxFrameSize = s.Val
  2234  		case SettingMaxConcurrentStreams:
  2235  			cc.maxConcurrentStreams = s.Val
  2236  		case SettingMaxHeaderListSize:
  2237  			cc.peerMaxHeaderListSize = uint64(s.Val)
  2238  		case SettingInitialWindowSize:
  2239  			// Values above the maximum flow-control
  2240  			// window size of 2^31-1 MUST be treated as a
  2241  			// connection error (Section 5.4.1) of type
  2242  			// FLOW_CONTROL_ERROR.
  2243  			if s.Val > math.MaxInt32 {
  2244  				return ConnectionError(ErrCodeFlowControl)
  2245  			}
  2246  
  2247  			// Adjust flow control of currently-open
  2248  			// frames by the difference of the old initial
  2249  			// window size and this one.
  2250  			delta := int32(s.Val) - int32(cc.initialWindowSize)
  2251  			for _, cs := range cc.streams {
  2252  				cs.flow.add(delta)
  2253  			}
  2254  			cc.cond.Broadcast()
  2255  
  2256  			cc.initialWindowSize = s.Val
  2257  		default:
  2258  			// TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  2259  			cc.vlogf("Unhandled Setting: %v", s)
  2260  		}
  2261  		return nil
  2262  	})
  2263  	if err != nil {
  2264  		return err
  2265  	}
  2266  
  2267  	cc.wmu.Lock()
  2268  	defer cc.wmu.Unlock()
  2269  
  2270  	cc.fr.WriteSettingsAck()
  2271  	cc.bw.Flush()
  2272  	return cc.werr
  2273  }
  2274  
  2275  func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  2276  	cc := rl.cc
  2277  	cs := cc.streamByID(f.StreamID, false)
  2278  	if f.StreamID != 0 && cs == nil {
  2279  		return nil
  2280  	}
  2281  
  2282  	cc.mu.Lock()
  2283  	defer cc.mu.Unlock()
  2284  
  2285  	fl := &cc.flow
  2286  	if cs != nil {
  2287  		fl = &cs.flow
  2288  	}
  2289  	if !fl.add(int32(f.Increment)) {
  2290  		return ConnectionError(ErrCodeFlowControl)
  2291  	}
  2292  	cc.cond.Broadcast()
  2293  	return nil
  2294  }
  2295  
  2296  func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  2297  	cs := rl.cc.streamByID(f.StreamID, true)
  2298  	if cs == nil {
  2299  		// TODO: return error if server tries to RST_STEAM an idle stream
  2300  		return nil
  2301  	}
  2302  	select {
  2303  	case <-cs.peerReset:
  2304  		// Already reset.
  2305  		// This is the only goroutine
  2306  		// which closes this, so there
  2307  		// isn't a race.
  2308  	default:
  2309  		err := streamError(cs.ID, f.ErrCode)
  2310  		cs.resetErr = err
  2311  		close(cs.peerReset)
  2312  		cs.bufPipe.CloseWithError(err)
  2313  		cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  2314  	}
  2315  	return nil
  2316  }
  2317  
  2318  // Ping sends a PING frame to the server and waits for the ack.
  2319  func (cc *ClientConn) Ping(ctx context.Context) error {
  2320  	c := make(chan struct{})
  2321  	// Generate a random payload
  2322  	var p [8]byte
  2323  	for {
  2324  		if _, err := rand.Read(p[:]); err != nil {
  2325  			return err
  2326  		}
  2327  		cc.mu.Lock()
  2328  		// check for dup before insert
  2329  		if _, found := cc.pings[p]; !found {
  2330  			cc.pings[p] = c
  2331  			cc.mu.Unlock()
  2332  			break
  2333  		}
  2334  		cc.mu.Unlock()
  2335  	}
  2336  	cc.wmu.Lock()
  2337  	if err := cc.fr.WritePing(false, p); err != nil {
  2338  		cc.wmu.Unlock()
  2339  		return err
  2340  	}
  2341  	if err := cc.bw.Flush(); err != nil {
  2342  		cc.wmu.Unlock()
  2343  		return err
  2344  	}
  2345  	cc.wmu.Unlock()
  2346  	select {
  2347  	case <-c:
  2348  		return nil
  2349  	case <-ctx.Done():
  2350  		return ctx.Err()
  2351  	case <-cc.readerDone:
  2352  		// connection closed
  2353  		return cc.readerErr
  2354  	}
  2355  }
  2356  
  2357  func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  2358  	if f.IsAck() {
  2359  		cc := rl.cc
  2360  		cc.mu.Lock()
  2361  		defer cc.mu.Unlock()
  2362  		// If ack, notify listener if any
  2363  		if c, ok := cc.pings[f.Data]; ok {
  2364  			close(c)
  2365  			delete(cc.pings, f.Data)
  2366  		}
  2367  		return nil
  2368  	}
  2369  	cc := rl.cc
  2370  	cc.wmu.Lock()
  2371  	defer cc.wmu.Unlock()
  2372  	if err := cc.fr.WritePing(true, f.Data); err != nil {
  2373  		return err
  2374  	}
  2375  	return cc.bw.Flush()
  2376  }
  2377  
  2378  func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  2379  	// We told the peer we don't want them.
  2380  	// Spec says:
  2381  	// "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  2382  	// setting of the peer endpoint is set to 0. An endpoint that
  2383  	// has set this setting and has received acknowledgement MUST
  2384  	// treat the receipt of a PUSH_PROMISE frame as a connection
  2385  	// error (Section 5.4.1) of type PROTOCOL_ERROR."
  2386  	return ConnectionError(ErrCodeProtocol)
  2387  }
  2388  
  2389  func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  2390  	// TODO: map err to more interesting error codes, once the
  2391  	// HTTP community comes up with some. But currently for
  2392  	// RST_STREAM there's no equivalent to GOAWAY frame's debug
  2393  	// data, and the error codes are all pretty vague ("cancel").
  2394  	cc.wmu.Lock()
  2395  	cc.fr.WriteRSTStream(streamID, code)
  2396  	cc.bw.Flush()
  2397  	cc.wmu.Unlock()
  2398  }
  2399  
  2400  var (
  2401  	errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  2402  	errRequestHeaderListSize  = errors.New("http2: request header list larger than peer's advertised limit")
  2403  	errPseudoTrailers         = errors.New("http2: invalid pseudo header in trailers")
  2404  )
  2405  
  2406  func (cc *ClientConn) logf(format string, args ...interface{}) {
  2407  	cc.t.logf(format, args...)
  2408  }
  2409  
  2410  func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  2411  	cc.t.vlogf(format, args...)
  2412  }
  2413  
  2414  func (t *Transport) vlogf(format string, args ...interface{}) {
  2415  	if VerboseLogs {
  2416  		t.logf(format, args...)
  2417  	}
  2418  }
  2419  
  2420  func (t *Transport) logf(format string, args ...interface{}) {
  2421  	log.Printf(format, args...)
  2422  }
  2423  
  2424  var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  2425  
  2426  func strSliceContains(ss []string, s string) bool {
  2427  	for _, v := range ss {
  2428  		if v == s {
  2429  			return true
  2430  		}
  2431  	}
  2432  	return false
  2433  }
  2434  
  2435  type erringRoundTripper struct{ err error }
  2436  
  2437  func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  2438  
  2439  // gzipReader wraps a response body so it can lazily
  2440  // call gzip.NewReader on the first call to Read
  2441  type gzipReader struct {
  2442  	body io.ReadCloser // underlying Response.Body
  2443  	zr   *gzip.Reader  // lazily-initialized gzip reader
  2444  	zerr error         // sticky error
  2445  }
  2446  
  2447  func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2448  	if gz.zerr != nil {
  2449  		return 0, gz.zerr
  2450  	}
  2451  	if gz.zr == nil {
  2452  		gz.zr, err = gzip.NewReader(gz.body)
  2453  		if err != nil {
  2454  			gz.zerr = err
  2455  			return 0, err
  2456  		}
  2457  	}
  2458  	return gz.zr.Read(p)
  2459  }
  2460  
  2461  func (gz *gzipReader) Close() error {
  2462  	return gz.body.Close()
  2463  }
  2464  
  2465  type errorReader struct{ err error }
  2466  
  2467  func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  2468  
  2469  // bodyWriterState encapsulates various state around the Transport's writing
  2470  // of the request body, particularly regarding doing delayed writes of the body
  2471  // when the request contains "Expect: 100-continue".
  2472  type bodyWriterState struct {
  2473  	cs     *clientStream
  2474  	timer  *time.Timer   // if non-nil, we're doing a delayed write
  2475  	fnonce *sync.Once    // to call fn with
  2476  	fn     func()        // the code to run in the goroutine, writing the body
  2477  	resc   chan error    // result of fn's execution
  2478  	delay  time.Duration // how long we should delay a delayed write for
  2479  }
  2480  
  2481  func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
  2482  	s.cs = cs
  2483  	if body == nil {
  2484  		return
  2485  	}
  2486  	resc := make(chan error, 1)
  2487  	s.resc = resc
  2488  	s.fn = func() {
  2489  		cs.cc.mu.Lock()
  2490  		cs.startedWrite = true
  2491  		cs.cc.mu.Unlock()
  2492  		resc <- cs.writeRequestBody(body, cs.req.Body)
  2493  	}
  2494  	s.delay = t.expectContinueTimeout()
  2495  	if s.delay == 0 ||
  2496  		!httpguts.HeaderValuesContainsToken(
  2497  			cs.req.Header["Expect"],
  2498  			"100-continue") {
  2499  		return
  2500  	}
  2501  	s.fnonce = new(sync.Once)
  2502  
  2503  	// Arm the timer with a very large duration, which we'll
  2504  	// intentionally lower later. It has to be large now because
  2505  	// we need a handle to it before writing the headers, but the
  2506  	// s.delay value is defined to not start until after the
  2507  	// request headers were written.
  2508  	const hugeDuration = 365 * 24 * time.Hour
  2509  	s.timer = time.AfterFunc(hugeDuration, func() {
  2510  		s.fnonce.Do(s.fn)
  2511  	})
  2512  	return
  2513  }
  2514  
  2515  func (s bodyWriterState) cancel() {
  2516  	if s.timer != nil {
  2517  		s.timer.Stop()
  2518  	}
  2519  }
  2520  
  2521  func (s bodyWriterState) on100() {
  2522  	if s.timer == nil {
  2523  		// If we didn't do a delayed write, ignore the server's
  2524  		// bogus 100 continue response.
  2525  		return
  2526  	}
  2527  	s.timer.Stop()
  2528  	go func() { s.fnonce.Do(s.fn) }()
  2529  }
  2530  
  2531  // scheduleBodyWrite starts writing the body, either immediately (in
  2532  // the common case) or after the delay timeout. It should not be
  2533  // called until after the headers have been written.
  2534  func (s bodyWriterState) scheduleBodyWrite() {
  2535  	if s.timer == nil {
  2536  		// We're not doing a delayed write (see
  2537  		// getBodyWriterState), so just start the writing
  2538  		// goroutine immediately.
  2539  		go s.fn()
  2540  		return
  2541  	}
  2542  	traceWait100Continue(s.cs.trace)
  2543  	if s.timer.Stop() {
  2544  		s.timer.Reset(s.delay)
  2545  	}
  2546  }
  2547  
  2548  // isConnectionCloseRequest reports whether req should use its own
  2549  // connection for a single request and then close the connection.
  2550  func isConnectionCloseRequest(req *http.Request) bool {
  2551  	return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
  2552  }
  2553  
  2554  // registerHTTPSProtocol calls Transport.RegisterProtocol but
  2555  // converting panics into errors.
  2556  func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
  2557  	defer func() {
  2558  		if e := recover(); e != nil {
  2559  			err = fmt.Errorf("%v", e)
  2560  		}
  2561  	}()
  2562  	t.RegisterProtocol("https", rt)
  2563  	return nil
  2564  }
  2565  
  2566  // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
  2567  // if there's already has a cached connection to the host.
  2568  // (The field is exported so it can be accessed via reflect from net/http; tested
  2569  // by TestNoDialH2RoundTripperType)
  2570  type noDialH2RoundTripper struct{ *Transport }
  2571  
  2572  func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  2573  	res, err := rt.Transport.RoundTrip(req)
  2574  	if isNoCachedConnError(err) {
  2575  		return nil, http.ErrSkipAltProtocol
  2576  	}
  2577  	return res, err
  2578  }
  2579  
  2580  func (t *Transport) idleConnTimeout() time.Duration {
  2581  	if t.t1 != nil {
  2582  		return t.t1.IdleConnTimeout
  2583  	}
  2584  	return 0
  2585  }
  2586  
  2587  func traceGetConn(req *http.Request, hostPort string) {
  2588  	trace := httptrace.ContextClientTrace(req.Context())
  2589  	if trace == nil || trace.GetConn == nil {
  2590  		return
  2591  	}
  2592  	trace.GetConn(hostPort)
  2593  }
  2594  
  2595  func traceGotConn(req *http.Request, cc *ClientConn, reused bool) {
  2596  	trace := httptrace.ContextClientTrace(req.Context())
  2597  	if trace == nil || trace.GotConn == nil {
  2598  		return
  2599  	}
  2600  	ci := httptrace.GotConnInfo{Conn: cc.tconn}
  2601  	ci.Reused = reused
  2602  	cc.mu.Lock()
  2603  	ci.WasIdle = len(cc.streams) == 0 && reused
  2604  	if ci.WasIdle && !cc.lastActive.IsZero() {
  2605  		ci.IdleTime = time.Now().Sub(cc.lastActive)
  2606  	}
  2607  	cc.mu.Unlock()
  2608  
  2609  	trace.GotConn(ci)
  2610  }
  2611  
  2612  func traceWroteHeaders(trace *httptrace.ClientTrace) {
  2613  	if trace != nil && trace.WroteHeaders != nil {
  2614  		trace.WroteHeaders()
  2615  	}
  2616  }
  2617  
  2618  func traceGot100Continue(trace *httptrace.ClientTrace) {
  2619  	if trace != nil && trace.Got100Continue != nil {
  2620  		trace.Got100Continue()
  2621  	}
  2622  }
  2623  
  2624  func traceWait100Continue(trace *httptrace.ClientTrace) {
  2625  	if trace != nil && trace.Wait100Continue != nil {
  2626  		trace.Wait100Continue()
  2627  	}
  2628  }
  2629  
  2630  func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
  2631  	if trace != nil && trace.WroteRequest != nil {
  2632  		trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
  2633  	}
  2634  }
  2635  
  2636  func traceFirstResponseByte(trace *httptrace.ClientTrace) {
  2637  	if trace != nil && trace.GotFirstResponseByte != nil {
  2638  		trace.GotFirstResponseByte()
  2639  	}
  2640  }