transport.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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/tls"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "log"
  16. "net"
  17. "net/http"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "golang.org/x/net/http2/hpack"
  22. )
  23. const (
  24. // transportDefaultConnFlow is how many connection-level flow control
  25. // tokens we give the server at start-up, past the default 64k.
  26. transportDefaultConnFlow = 1 << 30
  27. // transportDefaultStreamFlow is how many stream-level flow
  28. // control tokens we announce to the peer, and how many bytes
  29. // we buffer per stream.
  30. transportDefaultStreamFlow = 4 << 20
  31. // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
  32. // a stream-level WINDOW_UPDATE for at a time.
  33. transportDefaultStreamMinRefresh = 4 << 10
  34. )
  35. // Transport is an HTTP/2 Transport.
  36. //
  37. // A Transport internally caches connections to servers. It is safe
  38. // for concurrent use by multiple goroutines.
  39. type Transport struct {
  40. // DialTLS specifies an optional dial function for creating
  41. // TLS connections for requests.
  42. //
  43. // If DialTLS is nil, tls.Dial is used.
  44. //
  45. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  46. // it will be used to set http.Response.TLS.
  47. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  48. // TLSClientConfig specifies the TLS configuration to use with
  49. // tls.Client. If nil, the default configuration is used.
  50. TLSClientConfig *tls.Config
  51. // ConnPool optionally specifies an alternate connection pool to use.
  52. // If nil, the default is used.
  53. ConnPool ClientConnPool
  54. // DisableCompression, if true, prevents the Transport from
  55. // requesting compression with an "Accept-Encoding: gzip"
  56. // request header when the Request contains no existing
  57. // Accept-Encoding value. If the Transport requests gzip on
  58. // its own and gets a gzipped response, it's transparently
  59. // decoded in the Response.Body. However, if the user
  60. // explicitly requested gzip it is not automatically
  61. // uncompressed.
  62. DisableCompression bool
  63. connPoolOnce sync.Once
  64. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  65. }
  66. func (t *Transport) disableCompression() bool {
  67. if t.DisableCompression {
  68. return true
  69. }
  70. // TODO: also disable if this transport is somehow linked to an http1 Transport
  71. // and it's configured there?
  72. return false
  73. }
  74. var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6")
  75. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  76. // It requires Go 1.6 or later and returns an error if the net/http package is too old
  77. // or if t1 has already been HTTP/2-enabled.
  78. func ConfigureTransport(t1 *http.Transport) error {
  79. return configureTransport(t1) // in configure_transport.go (go1.6) or go15.go
  80. }
  81. func (t *Transport) connPool() ClientConnPool {
  82. t.connPoolOnce.Do(t.initConnPool)
  83. return t.connPoolOrDef
  84. }
  85. func (t *Transport) initConnPool() {
  86. if t.ConnPool != nil {
  87. t.connPoolOrDef = t.ConnPool
  88. } else {
  89. t.connPoolOrDef = &clientConnPool{t: t}
  90. }
  91. }
  92. // ClientConn is the state of a single HTTP/2 client connection to an
  93. // HTTP/2 server.
  94. type ClientConn struct {
  95. t *Transport
  96. tconn net.Conn // usually *tls.Conn, except specialized impls
  97. tlsState *tls.ConnectionState // nil only for specialized impls
  98. // readLoop goroutine fields:
  99. readerDone chan struct{} // closed on error
  100. readerErr error // set before readerDone is closed
  101. mu sync.Mutex // guards following
  102. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  103. flow flow // our conn-level flow control quota (cs.flow is per stream)
  104. inflow flow // peer's conn-level flow control
  105. closed bool
  106. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  107. streams map[uint32]*clientStream // client-initiated
  108. nextStreamID uint32
  109. bw *bufio.Writer
  110. br *bufio.Reader
  111. fr *Framer
  112. // Settings from peer:
  113. maxFrameSize uint32
  114. maxConcurrentStreams uint32
  115. initialWindowSize uint32
  116. hbuf bytes.Buffer // HPACK encoder writes into this
  117. henc *hpack.Encoder
  118. freeBuf [][]byte
  119. wmu sync.Mutex // held while writing; acquire AFTER wmu if holding both
  120. werr error // first write error that has occurred
  121. }
  122. // clientStream is the state for a single HTTP/2 stream. One of these
  123. // is created for each Transport.RoundTrip call.
  124. type clientStream struct {
  125. cc *ClientConn
  126. req *http.Request
  127. ID uint32
  128. resc chan resAndError
  129. bufPipe pipe // buffered pipe with the flow-controlled response payload
  130. requestedGzip bool
  131. flow flow // guarded by cc.mu
  132. inflow flow // guarded by cc.mu
  133. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  134. readErr error // sticky read error; owned by transportResponseBody.Read
  135. peerReset chan struct{} // closed on peer reset
  136. resetErr error // populated before peerReset is closed
  137. }
  138. // checkReset reports any error sent in a RST_STREAM frame by the
  139. // server.
  140. func (cs *clientStream) checkReset() error {
  141. select {
  142. case <-cs.peerReset:
  143. return cs.resetErr
  144. default:
  145. return nil
  146. }
  147. }
  148. type stickyErrWriter struct {
  149. w io.Writer
  150. err *error
  151. }
  152. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  153. if *sew.err != nil {
  154. return 0, *sew.err
  155. }
  156. n, err = sew.w.Write(p)
  157. *sew.err = err
  158. return
  159. }
  160. var ErrNoCachedConn = errors.New("http2: no cached connection was available")
  161. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  162. type RoundTripOpt struct {
  163. // OnlyCachedConn controls whether RoundTripOpt may
  164. // create a new TCP connection. If set true and
  165. // no cached connection is available, RoundTripOpt
  166. // will return ErrNoCachedConn.
  167. OnlyCachedConn bool
  168. }
  169. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  170. return t.RoundTripOpt(req, RoundTripOpt{})
  171. }
  172. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  173. // and returns a host:port. The port 443 is added if needed.
  174. func authorityAddr(authority string) (addr string) {
  175. if _, _, err := net.SplitHostPort(authority); err == nil {
  176. return authority
  177. }
  178. return net.JoinHostPort(authority, "443")
  179. }
  180. // RoundTripOpt is like RoundTrip, but takes options.
  181. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  182. if req.URL.Scheme != "https" {
  183. return nil, errors.New("http2: unsupported scheme")
  184. }
  185. addr := authorityAddr(req.URL.Host)
  186. for {
  187. cc, err := t.connPool().GetClientConn(req, addr)
  188. if err != nil {
  189. return nil, err
  190. }
  191. res, err := cc.RoundTrip(req)
  192. if shouldRetryRequest(req, err) {
  193. continue
  194. }
  195. if err != nil {
  196. return nil, err
  197. }
  198. return res, nil
  199. }
  200. }
  201. // CloseIdleConnections closes any connections which were previously
  202. // connected from previous requests but are now sitting idle.
  203. // It does not interrupt any connections currently in use.
  204. func (t *Transport) CloseIdleConnections() {
  205. if cp, ok := t.connPool().(*clientConnPool); ok {
  206. cp.closeIdleConnections()
  207. }
  208. }
  209. var (
  210. errClientConnClosed = errors.New("http2: client conn is closed")
  211. errClientConnUnusable = errors.New("http2: client conn not usable")
  212. )
  213. func shouldRetryRequest(req *http.Request, err error) bool {
  214. // TODO: retry GET requests (no bodies) more aggressively, if shutdown
  215. // before response.
  216. return err == errClientConnUnusable
  217. }
  218. func (t *Transport) dialClientConn(addr string) (*ClientConn, error) {
  219. host, _, err := net.SplitHostPort(addr)
  220. if err != nil {
  221. return nil, err
  222. }
  223. tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
  224. if err != nil {
  225. return nil, err
  226. }
  227. return t.NewClientConn(tconn)
  228. }
  229. func (t *Transport) newTLSConfig(host string) *tls.Config {
  230. cfg := new(tls.Config)
  231. if t.TLSClientConfig != nil {
  232. *cfg = *t.TLSClientConfig
  233. }
  234. cfg.NextProtos = []string{NextProtoTLS} // TODO: don't override if already in list
  235. cfg.ServerName = host
  236. return cfg
  237. }
  238. func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
  239. if t.DialTLS != nil {
  240. return t.DialTLS
  241. }
  242. return t.dialTLSDefault
  243. }
  244. func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
  245. cn, err := tls.Dial(network, addr, cfg)
  246. if err != nil {
  247. return nil, err
  248. }
  249. if err := cn.Handshake(); err != nil {
  250. return nil, err
  251. }
  252. if !cfg.InsecureSkipVerify {
  253. if err := cn.VerifyHostname(cfg.ServerName); err != nil {
  254. return nil, err
  255. }
  256. }
  257. state := cn.ConnectionState()
  258. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  259. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  260. }
  261. if !state.NegotiatedProtocolIsMutual {
  262. return nil, errors.New("http2: could not negotiate protocol mutually")
  263. }
  264. return cn, nil
  265. }
  266. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  267. if _, err := c.Write(clientPreface); err != nil {
  268. return nil, err
  269. }
  270. cc := &ClientConn{
  271. t: t,
  272. tconn: c,
  273. readerDone: make(chan struct{}),
  274. nextStreamID: 1,
  275. maxFrameSize: 16 << 10, // spec default
  276. initialWindowSize: 65535, // spec default
  277. maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
  278. streams: make(map[uint32]*clientStream),
  279. }
  280. cc.cond = sync.NewCond(&cc.mu)
  281. cc.flow.add(int32(initialWindowSize))
  282. // TODO: adjust this writer size to account for frame size +
  283. // MTU + crypto/tls record padding.
  284. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
  285. cc.br = bufio.NewReader(c)
  286. cc.fr = NewFramer(cc.bw, cc.br)
  287. cc.henc = hpack.NewEncoder(&cc.hbuf)
  288. type connectionStater interface {
  289. ConnectionState() tls.ConnectionState
  290. }
  291. if cs, ok := c.(connectionStater); ok {
  292. state := cs.ConnectionState()
  293. cc.tlsState = &state
  294. }
  295. cc.fr.WriteSettings(
  296. Setting{ID: SettingEnablePush, Val: 0},
  297. Setting{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  298. )
  299. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  300. cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
  301. cc.bw.Flush()
  302. if cc.werr != nil {
  303. return nil, cc.werr
  304. }
  305. // Read the obligatory SETTINGS frame
  306. f, err := cc.fr.ReadFrame()
  307. if err != nil {
  308. return nil, err
  309. }
  310. sf, ok := f.(*SettingsFrame)
  311. if !ok {
  312. return nil, fmt.Errorf("expected settings frame, got: %T", f)
  313. }
  314. cc.fr.WriteSettingsAck()
  315. cc.bw.Flush()
  316. sf.ForeachSetting(func(s Setting) error {
  317. switch s.ID {
  318. case SettingMaxFrameSize:
  319. cc.maxFrameSize = s.Val
  320. case SettingMaxConcurrentStreams:
  321. cc.maxConcurrentStreams = s.Val
  322. case SettingInitialWindowSize:
  323. cc.initialWindowSize = s.Val
  324. default:
  325. // TODO(bradfitz): handle more
  326. t.vlogf("Unhandled Setting: %v", s)
  327. }
  328. return nil
  329. })
  330. go cc.readLoop()
  331. return cc, nil
  332. }
  333. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  334. cc.mu.Lock()
  335. defer cc.mu.Unlock()
  336. cc.goAway = f
  337. }
  338. func (cc *ClientConn) CanTakeNewRequest() bool {
  339. cc.mu.Lock()
  340. defer cc.mu.Unlock()
  341. return cc.canTakeNewRequestLocked()
  342. }
  343. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  344. return cc.goAway == nil &&
  345. int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) &&
  346. cc.nextStreamID < 2147483647
  347. }
  348. func (cc *ClientConn) closeIfIdle() {
  349. cc.mu.Lock()
  350. if len(cc.streams) > 0 {
  351. cc.mu.Unlock()
  352. return
  353. }
  354. cc.closed = true
  355. // TODO: do clients send GOAWAY too? maybe? Just Close:
  356. cc.mu.Unlock()
  357. cc.tconn.Close()
  358. }
  359. const maxAllocFrameSize = 512 << 10
  360. // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  361. // They're capped at the min of the peer's max frame size or 512KB
  362. // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  363. // bufers.
  364. func (cc *ClientConn) frameScratchBuffer() []byte {
  365. cc.mu.Lock()
  366. size := cc.maxFrameSize
  367. if size > maxAllocFrameSize {
  368. size = maxAllocFrameSize
  369. }
  370. for i, buf := range cc.freeBuf {
  371. if len(buf) >= int(size) {
  372. cc.freeBuf[i] = nil
  373. cc.mu.Unlock()
  374. return buf[:size]
  375. }
  376. }
  377. cc.mu.Unlock()
  378. return make([]byte, size)
  379. }
  380. func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  381. cc.mu.Lock()
  382. defer cc.mu.Unlock()
  383. const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  384. if len(cc.freeBuf) < maxBufs {
  385. cc.freeBuf = append(cc.freeBuf, buf)
  386. return
  387. }
  388. for i, old := range cc.freeBuf {
  389. if old == nil {
  390. cc.freeBuf[i] = buf
  391. return
  392. }
  393. }
  394. // forget about it.
  395. }
  396. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  397. cc.mu.Lock()
  398. if cc.closed || !cc.canTakeNewRequestLocked() {
  399. cc.mu.Unlock()
  400. return nil, errClientConnUnusable
  401. }
  402. cs := cc.newStream()
  403. cs.req = req
  404. hasBody := req.Body != nil
  405. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  406. if !cc.t.disableCompression() &&
  407. req.Header.Get("Accept-Encoding") == "" &&
  408. req.Header.Get("Range") == "" &&
  409. req.Method != "HEAD" {
  410. // Request gzip only, not deflate. Deflate is ambiguous and
  411. // not as universally supported anyway.
  412. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  413. //
  414. // Note that we don't request this for HEAD requests,
  415. // due to a bug in nginx:
  416. // http://trac.nginx.org/nginx/ticket/358
  417. // https://golang.org/issue/5522
  418. //
  419. // We don't request gzip if the request is for a range, since
  420. // auto-decoding a portion of a gzipped document will just fail
  421. // anyway. See https://golang.org/issue/8923
  422. cs.requestedGzip = true
  423. }
  424. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,}
  425. hdrs := cc.encodeHeaders(req, cs.requestedGzip)
  426. first := true // first frame written (HEADERS is first, then CONTINUATION)
  427. cc.wmu.Lock()
  428. frameSize := int(cc.maxFrameSize)
  429. for len(hdrs) > 0 && cc.werr == nil {
  430. chunk := hdrs
  431. if len(chunk) > frameSize {
  432. chunk = chunk[:frameSize]
  433. }
  434. hdrs = hdrs[len(chunk):]
  435. endHeaders := len(hdrs) == 0
  436. if first {
  437. cc.fr.WriteHeaders(HeadersFrameParam{
  438. StreamID: cs.ID,
  439. BlockFragment: chunk,
  440. EndStream: !hasBody,
  441. EndHeaders: endHeaders,
  442. })
  443. first = false
  444. } else {
  445. cc.fr.WriteContinuation(cs.ID, endHeaders, chunk)
  446. }
  447. }
  448. cc.bw.Flush()
  449. werr := cc.werr
  450. cc.wmu.Unlock()
  451. cc.mu.Unlock()
  452. if werr != nil {
  453. return nil, werr
  454. }
  455. var bodyCopyErrc chan error
  456. var gotResHeaders chan struct{} // closed on resheaders
  457. if hasBody {
  458. bodyCopyErrc = make(chan error, 1)
  459. gotResHeaders = make(chan struct{})
  460. go func() {
  461. bodyCopyErrc <- cs.writeRequestBody(req.Body, gotResHeaders)
  462. }()
  463. }
  464. for {
  465. select {
  466. case re := <-cs.resc:
  467. if gotResHeaders != nil {
  468. close(gotResHeaders)
  469. }
  470. if re.err != nil {
  471. return nil, re.err
  472. }
  473. res := re.res
  474. res.Request = req
  475. res.TLS = cc.tlsState
  476. return res, nil
  477. case err := <-bodyCopyErrc:
  478. if err != nil {
  479. return nil, err
  480. }
  481. }
  482. }
  483. }
  484. var errServerResponseBeforeRequestBody = errors.New("http2: server sent response while still writing request body")
  485. func (cs *clientStream) writeRequestBody(body io.Reader, gotResHeaders <-chan struct{}) error {
  486. cc := cs.cc
  487. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  488. buf := cc.frameScratchBuffer()
  489. defer cc.putFrameScratchBuffer(buf)
  490. for !sentEnd {
  491. var sawEOF bool
  492. n, err := io.ReadFull(body, buf)
  493. if err == io.ErrUnexpectedEOF {
  494. sawEOF = true
  495. err = nil
  496. } else if err == io.EOF {
  497. break
  498. } else if err != nil {
  499. return err
  500. }
  501. toWrite := buf[:n]
  502. for len(toWrite) > 0 && err == nil {
  503. var allowed int32
  504. allowed, err = cs.awaitFlowControl(int32(len(toWrite)))
  505. if err != nil {
  506. return err
  507. }
  508. cc.wmu.Lock()
  509. select {
  510. case <-gotResHeaders:
  511. err = errServerResponseBeforeRequestBody
  512. case <-cs.peerReset:
  513. err = cs.resetErr
  514. default:
  515. data := toWrite[:allowed]
  516. toWrite = toWrite[allowed:]
  517. sentEnd = sawEOF && len(toWrite) == 0
  518. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  519. }
  520. cc.wmu.Unlock()
  521. }
  522. if err != nil {
  523. return err
  524. }
  525. }
  526. var err error
  527. cc.wmu.Lock()
  528. if !sentEnd {
  529. err = cc.fr.WriteData(cs.ID, true, nil)
  530. }
  531. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  532. err = ferr
  533. }
  534. cc.wmu.Unlock()
  535. return err
  536. }
  537. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  538. // control tokens from the server.
  539. // It returns either the non-zero number of tokens taken or an error
  540. // if the stream is dead.
  541. func (cs *clientStream) awaitFlowControl(maxBytes int32) (taken int32, err error) {
  542. cc := cs.cc
  543. cc.mu.Lock()
  544. defer cc.mu.Unlock()
  545. for {
  546. if cc.closed {
  547. return 0, errClientConnClosed
  548. }
  549. if err := cs.checkReset(); err != nil {
  550. return 0, err
  551. }
  552. if a := cs.flow.available(); a > 0 {
  553. take := a
  554. if take > maxBytes {
  555. take = maxBytes
  556. }
  557. if take > int32(cc.maxFrameSize) {
  558. take = int32(cc.maxFrameSize)
  559. }
  560. cs.flow.take(take)
  561. return take, nil
  562. }
  563. cc.cond.Wait()
  564. }
  565. }
  566. // requires cc.mu be held.
  567. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool) []byte {
  568. cc.hbuf.Reset()
  569. // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go
  570. host := req.Host
  571. if host == "" {
  572. host = req.URL.Host
  573. }
  574. // 8.1.2.3 Request Pseudo-Header Fields
  575. // The :path pseudo-header field includes the path and query parts of the
  576. // target URI (the path-absolute production and optionally a '?' character
  577. // followed by the query production (see Sections 3.3 and 3.4 of
  578. // [RFC3986]).
  579. cc.writeHeader(":authority", host) // probably not right for all sites
  580. cc.writeHeader(":method", req.Method)
  581. cc.writeHeader(":path", req.URL.RequestURI())
  582. cc.writeHeader(":scheme", "https")
  583. for k, vv := range req.Header {
  584. lowKey := strings.ToLower(k)
  585. if lowKey == "host" {
  586. continue
  587. }
  588. for _, v := range vv {
  589. cc.writeHeader(lowKey, v)
  590. }
  591. }
  592. if addGzipHeader {
  593. cc.writeHeader("accept-encoding", "gzip")
  594. }
  595. return cc.hbuf.Bytes()
  596. }
  597. func (cc *ClientConn) writeHeader(name, value string) {
  598. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  599. }
  600. type resAndError struct {
  601. res *http.Response
  602. err error
  603. }
  604. // requires cc.mu be held.
  605. func (cc *ClientConn) newStream() *clientStream {
  606. cs := &clientStream{
  607. cc: cc,
  608. ID: cc.nextStreamID,
  609. resc: make(chan resAndError, 1),
  610. peerReset: make(chan struct{}),
  611. }
  612. cs.flow.add(int32(cc.initialWindowSize))
  613. cs.flow.setConnFlow(&cc.flow)
  614. cs.inflow.add(transportDefaultStreamFlow)
  615. cs.inflow.setConnFlow(&cc.inflow)
  616. cc.nextStreamID += 2
  617. cc.streams[cs.ID] = cs
  618. return cs
  619. }
  620. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  621. cc.mu.Lock()
  622. defer cc.mu.Unlock()
  623. cs := cc.streams[id]
  624. if andRemove {
  625. delete(cc.streams, id)
  626. }
  627. return cs
  628. }
  629. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  630. type clientConnReadLoop struct {
  631. cc *ClientConn
  632. activeRes map[uint32]*clientStream // keyed by streamID
  633. // continueStreamID is the stream ID we're waiting for
  634. // continuation frames for.
  635. continueStreamID uint32
  636. hdec *hpack.Decoder
  637. // Fields reset on each HEADERS:
  638. nextRes *http.Response
  639. sawRegHeader bool // saw non-pseudo header
  640. reqMalformed error // non-nil once known to be malformed
  641. }
  642. // readLoop runs in its own goroutine and reads and dispatches frames.
  643. func (cc *ClientConn) readLoop() {
  644. rl := &clientConnReadLoop{
  645. cc: cc,
  646. activeRes: make(map[uint32]*clientStream),
  647. }
  648. // TODO: figure out henc size
  649. rl.hdec = hpack.NewDecoder(initialHeaderTableSize, rl.onNewHeaderField)
  650. defer rl.cleanup()
  651. cc.readerErr = rl.run()
  652. if ce, ok := cc.readerErr.(ConnectionError); ok {
  653. cc.wmu.Lock()
  654. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  655. cc.wmu.Unlock()
  656. }
  657. }
  658. func (rl *clientConnReadLoop) cleanup() {
  659. cc := rl.cc
  660. defer cc.tconn.Close()
  661. defer cc.t.connPool().MarkDead(cc)
  662. defer close(cc.readerDone)
  663. // Close any response bodies if the server closes prematurely.
  664. // TODO: also do this if we've written the headers but not
  665. // gotten a response yet.
  666. err := cc.readerErr
  667. if err == io.EOF {
  668. err = io.ErrUnexpectedEOF
  669. }
  670. cc.mu.Lock()
  671. for _, cs := range rl.activeRes {
  672. cs.bufPipe.CloseWithError(err)
  673. }
  674. for _, cs := range cc.streams {
  675. select {
  676. case cs.resc <- resAndError{err: err}:
  677. default:
  678. }
  679. }
  680. cc.closed = true
  681. cc.cond.Broadcast()
  682. cc.mu.Unlock()
  683. }
  684. func (rl *clientConnReadLoop) run() error {
  685. cc := rl.cc
  686. for {
  687. f, err := cc.fr.ReadFrame()
  688. if se, ok := err.(StreamError); ok {
  689. // TODO: deal with stream errors from the framer.
  690. return se
  691. } else if err != nil {
  692. return err
  693. }
  694. cc.vlogf("Transport received %v: %#v", f.Header(), f)
  695. streamID := f.Header().StreamID
  696. _, isContinue := f.(*ContinuationFrame)
  697. if isContinue {
  698. if streamID != rl.continueStreamID {
  699. cc.logf("Protocol violation: got CONTINUATION with id %d; want %d", streamID, rl.continueStreamID)
  700. return ConnectionError(ErrCodeProtocol)
  701. }
  702. } else if rl.continueStreamID != 0 {
  703. // Continue frames need to be adjacent in the stream
  704. // and we were in the middle of headers.
  705. cc.logf("Protocol violation: got %T for stream %d, want CONTINUATION for %d", f, streamID, rl.continueStreamID)
  706. return ConnectionError(ErrCodeProtocol)
  707. }
  708. switch f := f.(type) {
  709. case *HeadersFrame:
  710. err = rl.processHeaders(f)
  711. case *ContinuationFrame:
  712. err = rl.processContinuation(f)
  713. case *DataFrame:
  714. err = rl.processData(f)
  715. case *GoAwayFrame:
  716. err = rl.processGoAway(f)
  717. case *RSTStreamFrame:
  718. err = rl.processResetStream(f)
  719. case *SettingsFrame:
  720. err = rl.processSettings(f)
  721. case *PushPromiseFrame:
  722. err = rl.processPushPromise(f)
  723. case *WindowUpdateFrame:
  724. err = rl.processWindowUpdate(f)
  725. case *PingFrame:
  726. err = rl.processPing(f)
  727. default:
  728. cc.logf("Transport: unhandled response frame type %T", f)
  729. }
  730. if err != nil {
  731. return err
  732. }
  733. }
  734. }
  735. func (rl *clientConnReadLoop) processHeaders(f *HeadersFrame) error {
  736. rl.sawRegHeader = false
  737. rl.reqMalformed = nil
  738. rl.nextRes = &http.Response{
  739. Proto: "HTTP/2.0",
  740. ProtoMajor: 2,
  741. Header: make(http.Header),
  742. }
  743. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  744. }
  745. func (rl *clientConnReadLoop) processContinuation(f *ContinuationFrame) error {
  746. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  747. }
  748. func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID uint32, headersEnded, streamEnded bool) error {
  749. cc := rl.cc
  750. cs := cc.streamByID(streamID, streamEnded)
  751. if cs == nil {
  752. // We could return a ConnectionError(ErrCodeProtocol)
  753. // here, except that in the case of us canceling
  754. // client requests, we may also delete from the
  755. // streams map, in which case we forgot that we sent
  756. // this request. So, just ignore any responses for
  757. // now. They might've been in-flight before the
  758. // server got our RST_STREAM.
  759. return nil
  760. }
  761. _, err := rl.hdec.Write(frag)
  762. if err != nil {
  763. return err
  764. }
  765. if !headersEnded {
  766. rl.continueStreamID = cs.ID
  767. return nil
  768. }
  769. // HEADERS (or CONTINUATION) are now over.
  770. rl.continueStreamID = 0
  771. if rl.reqMalformed != nil {
  772. cs.resc <- resAndError{err: rl.reqMalformed}
  773. rl.cc.writeStreamReset(cs.ID, ErrCodeProtocol, rl.reqMalformed)
  774. return nil
  775. }
  776. res := rl.nextRes
  777. if !streamEnded || cs.req.Method == "HEAD" {
  778. res.ContentLength = -1
  779. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  780. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  781. res.ContentLength = clen64
  782. } else {
  783. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  784. // more safe smuggling-wise to ignore.
  785. }
  786. } else if len(clens) > 1 {
  787. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  788. // more safe smuggling-wise to ignore.
  789. }
  790. }
  791. if streamEnded {
  792. res.Body = noBody
  793. } else {
  794. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  795. cs.bufPipe = pipe{b: buf}
  796. cs.bytesRemain = res.ContentLength
  797. res.Body = transportResponseBody{cs}
  798. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  799. res.Header.Del("Content-Encoding")
  800. res.Header.Del("Content-Length")
  801. res.ContentLength = -1
  802. res.Body = &gzipReader{body: res.Body}
  803. }
  804. }
  805. rl.activeRes[cs.ID] = cs
  806. cs.resc <- resAndError{res: res}
  807. rl.nextRes = nil // unused now; will be reset next HEADERS frame
  808. return nil
  809. }
  810. // transportResponseBody is the concrete type of Transport.RoundTrip's
  811. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  812. // On Close it sends RST_STREAM if EOF wasn't already seen.
  813. type transportResponseBody struct {
  814. cs *clientStream
  815. }
  816. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  817. cs := b.cs
  818. cc := cs.cc
  819. if cs.readErr != nil {
  820. return 0, cs.readErr
  821. }
  822. n, err = b.cs.bufPipe.Read(p)
  823. if cs.bytesRemain != -1 {
  824. if int64(n) > cs.bytesRemain {
  825. n = int(cs.bytesRemain)
  826. if err == nil {
  827. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  828. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  829. }
  830. cs.readErr = err
  831. return int(cs.bytesRemain), err
  832. }
  833. cs.bytesRemain -= int64(n)
  834. if err == io.EOF && cs.bytesRemain > 0 {
  835. err = io.ErrUnexpectedEOF
  836. cs.readErr = err
  837. return n, err
  838. }
  839. }
  840. if n == 0 {
  841. // No flow control tokens to send back.
  842. return
  843. }
  844. cc.mu.Lock()
  845. defer cc.mu.Unlock()
  846. var connAdd, streamAdd int32
  847. // Check the conn-level first, before the stream-level.
  848. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  849. connAdd = transportDefaultConnFlow - v
  850. cc.inflow.add(connAdd)
  851. }
  852. if err == nil { // No need to refresh if the stream is over or failed.
  853. if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  854. streamAdd = transportDefaultStreamFlow - v
  855. cs.inflow.add(streamAdd)
  856. }
  857. }
  858. if connAdd != 0 || streamAdd != 0 {
  859. cc.wmu.Lock()
  860. defer cc.wmu.Unlock()
  861. if connAdd != 0 {
  862. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  863. }
  864. if streamAdd != 0 {
  865. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  866. }
  867. cc.bw.Flush()
  868. }
  869. return
  870. }
  871. func (b transportResponseBody) Close() error {
  872. if b.cs.bufPipe.Err() != io.EOF {
  873. // TODO: write test for this
  874. b.cs.cc.writeStreamReset(b.cs.ID, ErrCodeCancel, nil)
  875. }
  876. return nil
  877. }
  878. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  879. cc := rl.cc
  880. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  881. if cs == nil {
  882. return nil
  883. }
  884. data := f.Data()
  885. if VerboseLogs {
  886. rl.cc.logf("DATA: %q", data)
  887. }
  888. // Check connection-level flow control.
  889. cc.mu.Lock()
  890. if cs.inflow.available() >= int32(len(data)) {
  891. cs.inflow.take(int32(len(data)))
  892. } else {
  893. cc.mu.Unlock()
  894. return ConnectionError(ErrCodeFlowControl)
  895. }
  896. cc.mu.Unlock()
  897. if _, err := cs.bufPipe.Write(data); err != nil {
  898. return err
  899. }
  900. if f.StreamEnded() {
  901. cs.bufPipe.CloseWithError(io.EOF)
  902. delete(rl.activeRes, cs.ID)
  903. }
  904. return nil
  905. }
  906. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  907. cc := rl.cc
  908. cc.t.connPool().MarkDead(cc)
  909. if f.ErrCode != 0 {
  910. // TODO: deal with GOAWAY more. particularly the error code
  911. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  912. }
  913. cc.setGoAway(f)
  914. return nil
  915. }
  916. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  917. cc := rl.cc
  918. cc.mu.Lock()
  919. defer cc.mu.Unlock()
  920. return f.ForeachSetting(func(s Setting) error {
  921. switch s.ID {
  922. case SettingMaxFrameSize:
  923. cc.maxFrameSize = s.Val
  924. case SettingMaxConcurrentStreams:
  925. cc.maxConcurrentStreams = s.Val
  926. case SettingInitialWindowSize:
  927. // TODO: error if this is too large.
  928. // TODO: adjust flow control of still-open
  929. // frames by the difference of the old initial
  930. // window size and this one.
  931. cc.initialWindowSize = s.Val
  932. default:
  933. // TODO(bradfitz): handle more settings?
  934. cc.vlogf("Unhandled Setting: %v", s)
  935. }
  936. return nil
  937. })
  938. }
  939. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  940. cc := rl.cc
  941. cs := cc.streamByID(f.StreamID, false)
  942. if f.StreamID != 0 && cs == nil {
  943. return nil
  944. }
  945. cc.mu.Lock()
  946. defer cc.mu.Unlock()
  947. fl := &cc.flow
  948. if cs != nil {
  949. fl = &cs.flow
  950. }
  951. if !fl.add(int32(f.Increment)) {
  952. return ConnectionError(ErrCodeFlowControl)
  953. }
  954. cc.cond.Broadcast()
  955. return nil
  956. }
  957. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  958. cs := rl.cc.streamByID(f.StreamID, true)
  959. if cs == nil {
  960. // TODO: return error if server tries to RST_STEAM an idle stream
  961. return nil
  962. }
  963. select {
  964. case <-cs.peerReset:
  965. // Already reset.
  966. // This is the only goroutine
  967. // which closes this, so there
  968. // isn't a race.
  969. default:
  970. err := StreamError{cs.ID, f.ErrCode}
  971. cs.resetErr = err
  972. close(cs.peerReset)
  973. cs.bufPipe.CloseWithError(err)
  974. }
  975. delete(rl.activeRes, cs.ID)
  976. return nil
  977. }
  978. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  979. if f.IsAck() {
  980. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  981. // containing this flag."
  982. return nil
  983. }
  984. cc := rl.cc
  985. cc.wmu.Lock()
  986. defer cc.wmu.Unlock()
  987. if err := cc.fr.WritePing(true, f.Data); err != nil {
  988. return err
  989. }
  990. return cc.bw.Flush()
  991. }
  992. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  993. // We told the peer we don't want them.
  994. // Spec says:
  995. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  996. // setting of the peer endpoint is set to 0. An endpoint that
  997. // has set this setting and has received acknowledgement MUST
  998. // treat the receipt of a PUSH_PROMISE frame as a connection
  999. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1000. return ConnectionError(ErrCodeProtocol)
  1001. }
  1002. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1003. // TODO: do something with err? send it as a debug frame to the peer?
  1004. // But that's only in GOAWAY. Invent a new frame type? Is there one already?
  1005. cc.wmu.Lock()
  1006. cc.fr.WriteRSTStream(streamID, code)
  1007. cc.wmu.Unlock()
  1008. }
  1009. // onNewHeaderField runs on the readLoop goroutine whenever a new
  1010. // hpack header field is decoded.
  1011. func (rl *clientConnReadLoop) onNewHeaderField(f hpack.HeaderField) {
  1012. cc := rl.cc
  1013. if VerboseLogs {
  1014. cc.logf("Header field: %+v", f)
  1015. }
  1016. isPseudo := strings.HasPrefix(f.Name, ":")
  1017. if isPseudo {
  1018. if rl.sawRegHeader {
  1019. rl.reqMalformed = errors.New("http2: invalid pseudo header after regular header")
  1020. return
  1021. }
  1022. switch f.Name {
  1023. case ":status":
  1024. code, err := strconv.Atoi(f.Value)
  1025. if err != nil {
  1026. rl.reqMalformed = errors.New("http2: invalid :status")
  1027. return
  1028. }
  1029. rl.nextRes.Status = f.Value + " " + http.StatusText(code)
  1030. rl.nextRes.StatusCode = code
  1031. default:
  1032. // "Endpoints MUST NOT generate pseudo-header
  1033. // fields other than those defined in this
  1034. // document."
  1035. rl.reqMalformed = fmt.Errorf("http2: unknown response pseudo header %q", f.Name)
  1036. }
  1037. } else {
  1038. rl.sawRegHeader = true
  1039. rl.nextRes.Header.Add(http.CanonicalHeaderKey(f.Name), f.Value)
  1040. }
  1041. }
  1042. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1043. cc.t.logf(format, args...)
  1044. }
  1045. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1046. cc.t.vlogf(format, args...)
  1047. }
  1048. func (t *Transport) vlogf(format string, args ...interface{}) {
  1049. if VerboseLogs {
  1050. t.logf(format, args...)
  1051. }
  1052. }
  1053. func (t *Transport) logf(format string, args ...interface{}) {
  1054. log.Printf(format, args...)
  1055. }
  1056. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1057. func strSliceContains(ss []string, s string) bool {
  1058. for _, v := range ss {
  1059. if v == s {
  1060. return true
  1061. }
  1062. }
  1063. return false
  1064. }
  1065. type erringRoundTripper struct{ err error }
  1066. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1067. // gzipReader wraps a response body so it can lazily
  1068. // call gzip.NewReader on the first call to Read
  1069. type gzipReader struct {
  1070. body io.ReadCloser // underlying Response.Body
  1071. zr io.Reader // lazily-initialized gzip reader
  1072. }
  1073. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1074. if gz.zr == nil {
  1075. gz.zr, err = gzip.NewReader(gz.body)
  1076. if err != nil {
  1077. return 0, err
  1078. }
  1079. }
  1080. return gz.zr.Read(p)
  1081. }
  1082. func (gz *gzipReader) Close() error {
  1083. return gz.body.Close()
  1084. }