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