transport.go 50 KB

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