transport.go 56 KB

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