PageRenderTime 56ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/golang.org/x/net/http2/transport.go

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