transport.go 55 KB

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