transport.go 37 KB

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