You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2284 lines
63 KiB

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