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