transport.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  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. func bodyAndLength(req *http.Request) (body io.Reader, contentLen int64) {
  560. body = req.Body
  561. if body == nil {
  562. return nil, 0
  563. }
  564. if req.ContentLength != 0 {
  565. return req.Body, req.ContentLength
  566. }
  567. // Don't try to sniff the size if they're doing an expect
  568. // request (Issue 16002):
  569. if req.Header.Get("Expect") == "100-continue" {
  570. return req.Body, -1
  571. }
  572. // We have a body but a zero content length. Test to see if
  573. // it's actually zero or just unset.
  574. var buf [1]byte
  575. n, rerr := body.Read(buf[:])
  576. if rerr != nil && rerr != io.EOF {
  577. return errorReader{rerr}, -1
  578. }
  579. if n == 1 {
  580. // Oh, guess there is data in this Body Reader after all.
  581. // The ContentLength field just wasn't set.
  582. // Stitch the Body back together again, re-attaching our
  583. // consumed byte.
  584. if rerr == io.EOF {
  585. return bytes.NewReader(buf[:]), 1
  586. }
  587. return io.MultiReader(bytes.NewReader(buf[:]), body), -1
  588. }
  589. // Body is actually zero bytes.
  590. return nil, 0
  591. }
  592. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  593. if err := checkConnHeaders(req); err != nil {
  594. return nil, err
  595. }
  596. if cc.idleTimer != nil {
  597. cc.idleTimer.Stop()
  598. }
  599. trailers, err := commaSeparatedTrailers(req)
  600. if err != nil {
  601. return nil, err
  602. }
  603. hasTrailers := trailers != ""
  604. cc.mu.Lock()
  605. cc.lastActive = time.Now()
  606. if cc.closed || !cc.canTakeNewRequestLocked() {
  607. cc.mu.Unlock()
  608. return nil, errClientConnUnusable
  609. }
  610. body, contentLen := bodyAndLength(req)
  611. hasBody := body != nil
  612. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  613. var requestedGzip bool
  614. if !cc.t.disableCompression() &&
  615. req.Header.Get("Accept-Encoding") == "" &&
  616. req.Header.Get("Range") == "" &&
  617. req.Method != "HEAD" {
  618. // Request gzip only, not deflate. Deflate is ambiguous and
  619. // not as universally supported anyway.
  620. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  621. //
  622. // Note that we don't request this for HEAD requests,
  623. // due to a bug in nginx:
  624. // http://trac.nginx.org/nginx/ticket/358
  625. // https://golang.org/issue/5522
  626. //
  627. // We don't request gzip if the request is for a range, since
  628. // auto-decoding a portion of a gzipped document will just fail
  629. // anyway. See https://golang.org/issue/8923
  630. requestedGzip = true
  631. }
  632. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  633. // sent by writeRequestBody below, along with any Trailers,
  634. // again in form HEADERS{1}, CONTINUATION{0,})
  635. hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
  636. if err != nil {
  637. cc.mu.Unlock()
  638. return nil, err
  639. }
  640. cs := cc.newStream()
  641. cs.req = req
  642. cs.trace = requestTrace(req)
  643. cs.requestedGzip = requestedGzip
  644. bodyWriter := cc.t.getBodyWriterState(cs, body)
  645. cs.on100 = bodyWriter.on100
  646. cc.wmu.Lock()
  647. endStream := !hasBody && !hasTrailers
  648. werr := cc.writeHeaders(cs.ID, endStream, hdrs)
  649. cc.wmu.Unlock()
  650. traceWroteHeaders(cs.trace)
  651. cc.mu.Unlock()
  652. if werr != nil {
  653. if hasBody {
  654. req.Body.Close() // per RoundTripper contract
  655. bodyWriter.cancel()
  656. }
  657. cc.forgetStreamID(cs.ID)
  658. // Don't bother sending a RST_STREAM (our write already failed;
  659. // no need to keep writing)
  660. traceWroteRequest(cs.trace, werr)
  661. return nil, werr
  662. }
  663. var respHeaderTimer <-chan time.Time
  664. if hasBody {
  665. bodyWriter.scheduleBodyWrite()
  666. } else {
  667. traceWroteRequest(cs.trace, nil)
  668. if d := cc.responseHeaderTimeout(); d != 0 {
  669. timer := time.NewTimer(d)
  670. defer timer.Stop()
  671. respHeaderTimer = timer.C
  672. }
  673. }
  674. readLoopResCh := cs.resc
  675. bodyWritten := false
  676. ctx := reqContext(req)
  677. handleReadLoopResponse := func(re resAndError) (*http.Response, error) {
  678. res := re.res
  679. if re.err != nil || res.StatusCode > 299 {
  680. // On error or status code 3xx, 4xx, 5xx, etc abort any
  681. // ongoing write, assuming that the server doesn't care
  682. // about our request body. If the server replied with 1xx or
  683. // 2xx, however, then assume the server DOES potentially
  684. // want our body (e.g. full-duplex streaming:
  685. // golang.org/issue/13444). If it turns out the server
  686. // doesn't, they'll RST_STREAM us soon enough. This is a
  687. // heuristic to avoid adding knobs to Transport. Hopefully
  688. // we can keep it.
  689. bodyWriter.cancel()
  690. cs.abortRequestBodyWrite(errStopReqBodyWrite)
  691. }
  692. if re.err != nil {
  693. cc.forgetStreamID(cs.ID)
  694. return nil, re.err
  695. }
  696. res.Request = req
  697. res.TLS = cc.tlsState
  698. return res, nil
  699. }
  700. for {
  701. select {
  702. case re := <-readLoopResCh:
  703. return handleReadLoopResponse(re)
  704. case <-respHeaderTimer:
  705. cc.forgetStreamID(cs.ID)
  706. if !hasBody || bodyWritten {
  707. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  708. } else {
  709. bodyWriter.cancel()
  710. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  711. }
  712. return nil, errTimeout
  713. case <-ctx.Done():
  714. cc.forgetStreamID(cs.ID)
  715. if !hasBody || bodyWritten {
  716. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  717. } else {
  718. bodyWriter.cancel()
  719. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  720. }
  721. return nil, ctx.Err()
  722. case <-req.Cancel:
  723. cc.forgetStreamID(cs.ID)
  724. if !hasBody || bodyWritten {
  725. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  726. } else {
  727. bodyWriter.cancel()
  728. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  729. }
  730. return nil, errRequestCanceled
  731. case <-cs.peerReset:
  732. // processResetStream already removed the
  733. // stream from the streams map; no need for
  734. // forgetStreamID.
  735. return nil, cs.resetErr
  736. case err := <-bodyWriter.resc:
  737. // Prefer the read loop's response, if available. Issue 16102.
  738. select {
  739. case re := <-readLoopResCh:
  740. return handleReadLoopResponse(re)
  741. default:
  742. }
  743. if err != nil {
  744. return nil, err
  745. }
  746. bodyWritten = true
  747. if d := cc.responseHeaderTimeout(); d != 0 {
  748. timer := time.NewTimer(d)
  749. defer timer.Stop()
  750. respHeaderTimer = timer.C
  751. }
  752. }
  753. }
  754. }
  755. // requires cc.wmu be held
  756. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error {
  757. first := true // first frame written (HEADERS is first, then CONTINUATION)
  758. frameSize := int(cc.maxFrameSize)
  759. for len(hdrs) > 0 && cc.werr == nil {
  760. chunk := hdrs
  761. if len(chunk) > frameSize {
  762. chunk = chunk[:frameSize]
  763. }
  764. hdrs = hdrs[len(chunk):]
  765. endHeaders := len(hdrs) == 0
  766. if first {
  767. cc.fr.WriteHeaders(HeadersFrameParam{
  768. StreamID: streamID,
  769. BlockFragment: chunk,
  770. EndStream: endStream,
  771. EndHeaders: endHeaders,
  772. })
  773. first = false
  774. } else {
  775. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  776. }
  777. }
  778. // TODO(bradfitz): this Flush could potentially block (as
  779. // could the WriteHeaders call(s) above), which means they
  780. // wouldn't respond to Request.Cancel being readable. That's
  781. // rare, but this should probably be in a goroutine.
  782. cc.bw.Flush()
  783. return cc.werr
  784. }
  785. // internal error values; they don't escape to callers
  786. var (
  787. // abort request body write; don't send cancel
  788. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  789. // abort request body write, but send stream reset of cancel.
  790. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  791. )
  792. func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  793. cc := cs.cc
  794. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  795. buf := cc.frameScratchBuffer()
  796. defer cc.putFrameScratchBuffer(buf)
  797. defer func() {
  798. traceWroteRequest(cs.trace, err)
  799. // TODO: write h12Compare test showing whether
  800. // Request.Body is closed by the Transport,
  801. // and in multiple cases: server replies <=299 and >299
  802. // while still writing request body
  803. cerr := bodyCloser.Close()
  804. if err == nil {
  805. err = cerr
  806. }
  807. }()
  808. req := cs.req
  809. hasTrailers := req.Trailer != nil
  810. var sawEOF bool
  811. for !sawEOF {
  812. n, err := body.Read(buf)
  813. if err == io.EOF {
  814. sawEOF = true
  815. err = nil
  816. } else if err != nil {
  817. return err
  818. }
  819. remain := buf[:n]
  820. for len(remain) > 0 && err == nil {
  821. var allowed int32
  822. allowed, err = cs.awaitFlowControl(len(remain))
  823. switch {
  824. case err == errStopReqBodyWrite:
  825. return err
  826. case err == errStopReqBodyWriteAndCancel:
  827. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  828. return err
  829. case err != nil:
  830. return err
  831. }
  832. cc.wmu.Lock()
  833. data := remain[:allowed]
  834. remain = remain[allowed:]
  835. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  836. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  837. if err == nil {
  838. // TODO(bradfitz): this flush is for latency, not bandwidth.
  839. // Most requests won't need this. Make this opt-in or
  840. // opt-out? Use some heuristic on the body type? Nagel-like
  841. // timers? Based on 'n'? Only last chunk of this for loop,
  842. // unless flow control tokens are low? For now, always.
  843. // If we change this, see comment below.
  844. err = cc.bw.Flush()
  845. }
  846. cc.wmu.Unlock()
  847. }
  848. if err != nil {
  849. return err
  850. }
  851. }
  852. if sentEnd {
  853. // Already sent END_STREAM (which implies we have no
  854. // trailers) and flushed, because currently all
  855. // WriteData frames above get a flush. So we're done.
  856. return nil
  857. }
  858. var trls []byte
  859. if hasTrailers {
  860. cc.mu.Lock()
  861. defer cc.mu.Unlock()
  862. trls = cc.encodeTrailers(req)
  863. }
  864. cc.wmu.Lock()
  865. defer cc.wmu.Unlock()
  866. // Two ways to send END_STREAM: either with trailers, or
  867. // with an empty DATA frame.
  868. if len(trls) > 0 {
  869. err = cc.writeHeaders(cs.ID, true, trls)
  870. } else {
  871. err = cc.fr.WriteData(cs.ID, true, nil)
  872. }
  873. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  874. err = ferr
  875. }
  876. return err
  877. }
  878. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  879. // control tokens from the server.
  880. // It returns either the non-zero number of tokens taken or an error
  881. // if the stream is dead.
  882. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  883. cc := cs.cc
  884. cc.mu.Lock()
  885. defer cc.mu.Unlock()
  886. for {
  887. if cc.closed {
  888. return 0, errClientConnClosed
  889. }
  890. if cs.stopReqBody != nil {
  891. return 0, cs.stopReqBody
  892. }
  893. if err := cs.checkResetOrDone(); err != nil {
  894. return 0, err
  895. }
  896. if a := cs.flow.available(); a > 0 {
  897. take := a
  898. if int(take) > maxBytes {
  899. take = int32(maxBytes) // can't truncate int; take is int32
  900. }
  901. if take > int32(cc.maxFrameSize) {
  902. take = int32(cc.maxFrameSize)
  903. }
  904. cs.flow.take(take)
  905. return take, nil
  906. }
  907. cc.cond.Wait()
  908. }
  909. }
  910. type badStringError struct {
  911. what string
  912. str string
  913. }
  914. func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  915. // requires cc.mu be held.
  916. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  917. cc.hbuf.Reset()
  918. host := req.Host
  919. if host == "" {
  920. host = req.URL.Host
  921. }
  922. host, err := httplex.PunycodeHostPort(host)
  923. if err != nil {
  924. return nil, err
  925. }
  926. var path string
  927. if req.Method != "CONNECT" {
  928. path = req.URL.RequestURI()
  929. if !validPseudoPath(path) {
  930. orig := path
  931. path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  932. if !validPseudoPath(path) {
  933. if req.URL.Opaque != "" {
  934. return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  935. } else {
  936. return nil, fmt.Errorf("invalid request :path %q", orig)
  937. }
  938. }
  939. }
  940. }
  941. // Check for any invalid headers and return an error before we
  942. // potentially pollute our hpack state. (We want to be able to
  943. // continue to reuse the hpack encoder for future requests)
  944. for k, vv := range req.Header {
  945. if !httplex.ValidHeaderFieldName(k) {
  946. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  947. }
  948. for _, v := range vv {
  949. if !httplex.ValidHeaderFieldValue(v) {
  950. return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  951. }
  952. }
  953. }
  954. // 8.1.2.3 Request Pseudo-Header Fields
  955. // The :path pseudo-header field includes the path and query parts of the
  956. // target URI (the path-absolute production and optionally a '?' character
  957. // followed by the query production (see Sections 3.3 and 3.4 of
  958. // [RFC3986]).
  959. cc.writeHeader(":authority", host)
  960. cc.writeHeader(":method", req.Method)
  961. if req.Method != "CONNECT" {
  962. cc.writeHeader(":path", path)
  963. cc.writeHeader(":scheme", req.URL.Scheme)
  964. }
  965. if trailers != "" {
  966. cc.writeHeader("trailer", trailers)
  967. }
  968. var didUA bool
  969. for k, vv := range req.Header {
  970. lowKey := strings.ToLower(k)
  971. switch lowKey {
  972. case "host", "content-length":
  973. // Host is :authority, already sent.
  974. // Content-Length is automatic, set below.
  975. continue
  976. case "connection", "proxy-connection", "transfer-encoding", "upgrade", "keep-alive":
  977. // Per 8.1.2.2 Connection-Specific Header
  978. // Fields, don't send connection-specific
  979. // fields. We have already checked if any
  980. // are error-worthy so just ignore the rest.
  981. continue
  982. case "user-agent":
  983. // Match Go's http1 behavior: at most one
  984. // User-Agent. If set to nil or empty string,
  985. // then omit it. Otherwise if not mentioned,
  986. // include the default (below).
  987. didUA = true
  988. if len(vv) < 1 {
  989. continue
  990. }
  991. vv = vv[:1]
  992. if vv[0] == "" {
  993. continue
  994. }
  995. }
  996. for _, v := range vv {
  997. cc.writeHeader(lowKey, v)
  998. }
  999. }
  1000. if shouldSendReqContentLength(req.Method, contentLength) {
  1001. cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10))
  1002. }
  1003. if addGzipHeader {
  1004. cc.writeHeader("accept-encoding", "gzip")
  1005. }
  1006. if !didUA {
  1007. cc.writeHeader("user-agent", defaultUserAgent)
  1008. }
  1009. return cc.hbuf.Bytes(), nil
  1010. }
  1011. // shouldSendReqContentLength reports whether the http2.Transport should send
  1012. // a "content-length" request header. This logic is basically a copy of the net/http
  1013. // transferWriter.shouldSendContentLength.
  1014. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1015. // -1 means unknown.
  1016. func shouldSendReqContentLength(method string, contentLength int64) bool {
  1017. if contentLength > 0 {
  1018. return true
  1019. }
  1020. if contentLength < 0 {
  1021. return false
  1022. }
  1023. // For zero bodies, whether we send a content-length depends on the method.
  1024. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  1025. switch method {
  1026. case "POST", "PUT", "PATCH":
  1027. return true
  1028. default:
  1029. return false
  1030. }
  1031. }
  1032. // requires cc.mu be held.
  1033. func (cc *ClientConn) encodeTrailers(req *http.Request) []byte {
  1034. cc.hbuf.Reset()
  1035. for k, vv := range req.Trailer {
  1036. // Transfer-Encoding, etc.. have already been filter at the
  1037. // start of RoundTrip
  1038. lowKey := strings.ToLower(k)
  1039. for _, v := range vv {
  1040. cc.writeHeader(lowKey, v)
  1041. }
  1042. }
  1043. return cc.hbuf.Bytes()
  1044. }
  1045. func (cc *ClientConn) writeHeader(name, value string) {
  1046. if VerboseLogs {
  1047. log.Printf("http2: Transport encoding header %q = %q", name, value)
  1048. }
  1049. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1050. }
  1051. type resAndError struct {
  1052. res *http.Response
  1053. err error
  1054. }
  1055. // requires cc.mu be held.
  1056. func (cc *ClientConn) newStream() *clientStream {
  1057. cs := &clientStream{
  1058. cc: cc,
  1059. ID: cc.nextStreamID,
  1060. resc: make(chan resAndError, 1),
  1061. peerReset: make(chan struct{}),
  1062. done: make(chan struct{}),
  1063. }
  1064. cs.flow.add(int32(cc.initialWindowSize))
  1065. cs.flow.setConnFlow(&cc.flow)
  1066. cs.inflow.add(transportDefaultStreamFlow)
  1067. cs.inflow.setConnFlow(&cc.inflow)
  1068. cc.nextStreamID += 2
  1069. cc.streams[cs.ID] = cs
  1070. return cs
  1071. }
  1072. func (cc *ClientConn) forgetStreamID(id uint32) {
  1073. cc.streamByID(id, true)
  1074. }
  1075. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1076. cc.mu.Lock()
  1077. defer cc.mu.Unlock()
  1078. cs := cc.streams[id]
  1079. if andRemove && cs != nil && !cc.closed {
  1080. cc.lastActive = time.Now()
  1081. delete(cc.streams, id)
  1082. if len(cc.streams) == 0 && cc.idleTimer != nil {
  1083. cc.idleTimer.Reset(cc.idleTimeout)
  1084. }
  1085. close(cs.done)
  1086. cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  1087. }
  1088. return cs
  1089. }
  1090. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1091. type clientConnReadLoop struct {
  1092. cc *ClientConn
  1093. activeRes map[uint32]*clientStream // keyed by streamID
  1094. closeWhenIdle bool
  1095. }
  1096. // readLoop runs in its own goroutine and reads and dispatches frames.
  1097. func (cc *ClientConn) readLoop() {
  1098. rl := &clientConnReadLoop{
  1099. cc: cc,
  1100. activeRes: make(map[uint32]*clientStream),
  1101. }
  1102. defer rl.cleanup()
  1103. cc.readerErr = rl.run()
  1104. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1105. cc.wmu.Lock()
  1106. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1107. cc.wmu.Unlock()
  1108. }
  1109. }
  1110. // GoAwayError is returned by the Transport when the server closes the
  1111. // TCP connection after sending a GOAWAY frame.
  1112. type GoAwayError struct {
  1113. LastStreamID uint32
  1114. ErrCode ErrCode
  1115. DebugData string
  1116. }
  1117. func (e GoAwayError) Error() string {
  1118. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1119. e.LastStreamID, e.ErrCode, e.DebugData)
  1120. }
  1121. func isEOFOrNetReadError(err error) bool {
  1122. if err == io.EOF {
  1123. return true
  1124. }
  1125. ne, ok := err.(*net.OpError)
  1126. return ok && ne.Op == "read"
  1127. }
  1128. func (rl *clientConnReadLoop) cleanup() {
  1129. cc := rl.cc
  1130. defer cc.tconn.Close()
  1131. defer cc.t.connPool().MarkDead(cc)
  1132. defer close(cc.readerDone)
  1133. if cc.idleTimer != nil {
  1134. cc.idleTimer.Stop()
  1135. }
  1136. // Close any response bodies if the server closes prematurely.
  1137. // TODO: also do this if we've written the headers but not
  1138. // gotten a response yet.
  1139. err := cc.readerErr
  1140. cc.mu.Lock()
  1141. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1142. err = GoAwayError{
  1143. LastStreamID: cc.goAway.LastStreamID,
  1144. ErrCode: cc.goAway.ErrCode,
  1145. DebugData: cc.goAwayDebug,
  1146. }
  1147. } else if err == io.EOF {
  1148. err = io.ErrUnexpectedEOF
  1149. }
  1150. for _, cs := range rl.activeRes {
  1151. cs.bufPipe.CloseWithError(err)
  1152. }
  1153. for _, cs := range cc.streams {
  1154. select {
  1155. case cs.resc <- resAndError{err: err}:
  1156. default:
  1157. }
  1158. close(cs.done)
  1159. }
  1160. cc.closed = true
  1161. cc.cond.Broadcast()
  1162. cc.mu.Unlock()
  1163. }
  1164. func (rl *clientConnReadLoop) run() error {
  1165. cc := rl.cc
  1166. rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1167. gotReply := false // ever saw a HEADERS reply
  1168. gotSettings := false
  1169. for {
  1170. f, err := cc.fr.ReadFrame()
  1171. if err != nil {
  1172. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1173. }
  1174. if se, ok := err.(StreamError); ok {
  1175. if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil {
  1176. cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1177. if se.Cause == nil {
  1178. se.Cause = cc.fr.errDetail
  1179. }
  1180. rl.endStreamError(cs, se)
  1181. }
  1182. continue
  1183. } else if err != nil {
  1184. return err
  1185. }
  1186. if VerboseLogs {
  1187. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1188. }
  1189. if !gotSettings {
  1190. if _, ok := f.(*SettingsFrame); !ok {
  1191. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1192. return ConnectionError(ErrCodeProtocol)
  1193. }
  1194. gotSettings = true
  1195. }
  1196. maybeIdle := false // whether frame might transition us to idle
  1197. switch f := f.(type) {
  1198. case *MetaHeadersFrame:
  1199. err = rl.processHeaders(f)
  1200. maybeIdle = true
  1201. gotReply = true
  1202. case *DataFrame:
  1203. err = rl.processData(f)
  1204. maybeIdle = true
  1205. case *GoAwayFrame:
  1206. err = rl.processGoAway(f)
  1207. maybeIdle = true
  1208. case *RSTStreamFrame:
  1209. err = rl.processResetStream(f)
  1210. maybeIdle = true
  1211. case *SettingsFrame:
  1212. err = rl.processSettings(f)
  1213. case *PushPromiseFrame:
  1214. err = rl.processPushPromise(f)
  1215. case *WindowUpdateFrame:
  1216. err = rl.processWindowUpdate(f)
  1217. case *PingFrame:
  1218. err = rl.processPing(f)
  1219. default:
  1220. cc.logf("Transport: unhandled response frame type %T", f)
  1221. }
  1222. if err != nil {
  1223. if VerboseLogs {
  1224. cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  1225. }
  1226. return err
  1227. }
  1228. if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 {
  1229. cc.closeIfIdle()
  1230. }
  1231. }
  1232. }
  1233. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  1234. cc := rl.cc
  1235. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1236. if cs == nil {
  1237. // We'd get here if we canceled a request while the
  1238. // server had its response still in flight. So if this
  1239. // was just something we canceled, ignore it.
  1240. return nil
  1241. }
  1242. if !cs.firstByte {
  1243. if cs.trace != nil {
  1244. // TODO(bradfitz): move first response byte earlier,
  1245. // when we first read the 9 byte header, not waiting
  1246. // until all the HEADERS+CONTINUATION frames have been
  1247. // merged. This works for now.
  1248. traceFirstResponseByte(cs.trace)
  1249. }
  1250. cs.firstByte = true
  1251. }
  1252. if !cs.pastHeaders {
  1253. cs.pastHeaders = true
  1254. } else {
  1255. return rl.processTrailers(cs, f)
  1256. }
  1257. res, err := rl.handleResponse(cs, f)
  1258. if err != nil {
  1259. if _, ok := err.(ConnectionError); ok {
  1260. return err
  1261. }
  1262. // Any other error type is a stream error.
  1263. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  1264. cs.resc <- resAndError{err: err}
  1265. return nil // return nil from process* funcs to keep conn alive
  1266. }
  1267. if res == nil {
  1268. // (nil, nil) special case. See handleResponse docs.
  1269. return nil
  1270. }
  1271. if res.Body != noBody {
  1272. rl.activeRes[cs.ID] = cs
  1273. }
  1274. cs.resTrailer = &res.Trailer
  1275. cs.resc <- resAndError{res: res}
  1276. return nil
  1277. }
  1278. // may return error types nil, or ConnectionError. Any other error value
  1279. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  1280. // is the detail.
  1281. //
  1282. // As a special case, handleResponse may return (nil, nil) to skip the
  1283. // frame (currently only used for 100 expect continue). This special
  1284. // case is going away after Issue 13851 is fixed.
  1285. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  1286. if f.Truncated {
  1287. return nil, errResponseHeaderListSize
  1288. }
  1289. status := f.PseudoValue("status")
  1290. if status == "" {
  1291. return nil, errors.New("missing status pseudo header")
  1292. }
  1293. statusCode, err := strconv.Atoi(status)
  1294. if err != nil {
  1295. return nil, errors.New("malformed non-numeric status pseudo header")
  1296. }
  1297. if statusCode == 100 {
  1298. traceGot100Continue(cs.trace)
  1299. if cs.on100 != nil {
  1300. cs.on100() // forces any write delay timer to fire
  1301. }
  1302. cs.pastHeaders = false // do it all again
  1303. return nil, nil
  1304. }
  1305. header := make(http.Header)
  1306. res := &http.Response{
  1307. Proto: "HTTP/2.0",
  1308. ProtoMajor: 2,
  1309. Header: header,
  1310. StatusCode: statusCode,
  1311. Status: status + " " + http.StatusText(statusCode),
  1312. }
  1313. for _, hf := range f.RegularFields() {
  1314. key := http.CanonicalHeaderKey(hf.Name)
  1315. if key == "Trailer" {
  1316. t := res.Trailer
  1317. if t == nil {
  1318. t = make(http.Header)
  1319. res.Trailer = t
  1320. }
  1321. foreachHeaderElement(hf.Value, func(v string) {
  1322. t[http.CanonicalHeaderKey(v)] = nil
  1323. })
  1324. } else {
  1325. header[key] = append(header[key], hf.Value)
  1326. }
  1327. }
  1328. streamEnded := f.StreamEnded()
  1329. isHead := cs.req.Method == "HEAD"
  1330. if !streamEnded || isHead {
  1331. res.ContentLength = -1
  1332. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1333. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1334. res.ContentLength = clen64
  1335. } else {
  1336. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1337. // more safe smuggling-wise to ignore.
  1338. }
  1339. } else if len(clens) > 1 {
  1340. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1341. // more safe smuggling-wise to ignore.
  1342. }
  1343. }
  1344. if streamEnded || isHead {
  1345. res.Body = noBody
  1346. return res, nil
  1347. }
  1348. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  1349. cs.bufPipe = pipe{b: buf}
  1350. cs.bytesRemain = res.ContentLength
  1351. res.Body = transportResponseBody{cs}
  1352. go cs.awaitRequestCancel(cs.req)
  1353. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1354. res.Header.Del("Content-Encoding")
  1355. res.Header.Del("Content-Length")
  1356. res.ContentLength = -1
  1357. res.Body = &gzipReader{body: res.Body}
  1358. setResponseUncompressed(res)
  1359. }
  1360. return res, nil
  1361. }
  1362. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  1363. if cs.pastTrailers {
  1364. // Too many HEADERS frames for this stream.
  1365. return ConnectionError(ErrCodeProtocol)
  1366. }
  1367. cs.pastTrailers = true
  1368. if !f.StreamEnded() {
  1369. // We expect that any headers for trailers also
  1370. // has END_STREAM.
  1371. return ConnectionError(ErrCodeProtocol)
  1372. }
  1373. if len(f.PseudoFields()) > 0 {
  1374. // No pseudo header fields are defined for trailers.
  1375. // TODO: ConnectionError might be overly harsh? Check.
  1376. return ConnectionError(ErrCodeProtocol)
  1377. }
  1378. trailer := make(http.Header)
  1379. for _, hf := range f.RegularFields() {
  1380. key := http.CanonicalHeaderKey(hf.Name)
  1381. trailer[key] = append(trailer[key], hf.Value)
  1382. }
  1383. cs.trailer = trailer
  1384. rl.endStream(cs)
  1385. return nil
  1386. }
  1387. // transportResponseBody is the concrete type of Transport.RoundTrip's
  1388. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1389. // On Close it sends RST_STREAM if EOF wasn't already seen.
  1390. type transportResponseBody struct {
  1391. cs *clientStream
  1392. }
  1393. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1394. cs := b.cs
  1395. cc := cs.cc
  1396. if cs.readErr != nil {
  1397. return 0, cs.readErr
  1398. }
  1399. n, err = b.cs.bufPipe.Read(p)
  1400. if cs.bytesRemain != -1 {
  1401. if int64(n) > cs.bytesRemain {
  1402. n = int(cs.bytesRemain)
  1403. if err == nil {
  1404. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1405. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1406. }
  1407. cs.readErr = err
  1408. return int(cs.bytesRemain), err
  1409. }
  1410. cs.bytesRemain -= int64(n)
  1411. if err == io.EOF && cs.bytesRemain > 0 {
  1412. err = io.ErrUnexpectedEOF
  1413. cs.readErr = err
  1414. return n, err
  1415. }
  1416. }
  1417. if n == 0 {
  1418. // No flow control tokens to send back.
  1419. return
  1420. }
  1421. cc.mu.Lock()
  1422. defer cc.mu.Unlock()
  1423. var connAdd, streamAdd int32
  1424. // Check the conn-level first, before the stream-level.
  1425. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  1426. connAdd = transportDefaultConnFlow - v
  1427. cc.inflow.add(connAdd)
  1428. }
  1429. if err == nil { // No need to refresh if the stream is over or failed.
  1430. // Consider any buffered body data (read from the conn but not
  1431. // consumed by the client) when computing flow control for this
  1432. // stream.
  1433. v := int(cs.inflow.available()) + cs.bufPipe.Len()
  1434. if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  1435. streamAdd = int32(transportDefaultStreamFlow - v)
  1436. cs.inflow.add(streamAdd)
  1437. }
  1438. }
  1439. if connAdd != 0 || streamAdd != 0 {
  1440. cc.wmu.Lock()
  1441. defer cc.wmu.Unlock()
  1442. if connAdd != 0 {
  1443. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  1444. }
  1445. if streamAdd != 0 {
  1446. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  1447. }
  1448. cc.bw.Flush()
  1449. }
  1450. return
  1451. }
  1452. var errClosedResponseBody = errors.New("http2: response body closed")
  1453. func (b transportResponseBody) Close() error {
  1454. cs := b.cs
  1455. cc := cs.cc
  1456. serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
  1457. unread := cs.bufPipe.Len()
  1458. if unread > 0 || !serverSentStreamEnd {
  1459. cc.mu.Lock()
  1460. cc.wmu.Lock()
  1461. if !serverSentStreamEnd {
  1462. cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
  1463. }
  1464. // Return connection-level flow control.
  1465. if unread > 0 {
  1466. cc.inflow.add(int32(unread))
  1467. cc.fr.WriteWindowUpdate(0, uint32(unread))
  1468. }
  1469. cc.bw.Flush()
  1470. cc.wmu.Unlock()
  1471. cc.mu.Unlock()
  1472. }
  1473. cs.bufPipe.BreakWithError(errClosedResponseBody)
  1474. return nil
  1475. }
  1476. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  1477. cc := rl.cc
  1478. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1479. data := f.Data()
  1480. if cs == nil {
  1481. cc.mu.Lock()
  1482. neverSent := cc.nextStreamID
  1483. cc.mu.Unlock()
  1484. if f.StreamID >= neverSent {
  1485. // We never asked for this.
  1486. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  1487. return ConnectionError(ErrCodeProtocol)
  1488. }
  1489. // We probably did ask for this, but canceled. Just ignore it.
  1490. // TODO: be stricter here? only silently ignore things which
  1491. // we canceled, but not things which were closed normally
  1492. // by the peer? Tough without accumulating too much state.
  1493. // But at least return their flow control:
  1494. if f.Length > 0 {
  1495. cc.mu.Lock()
  1496. cc.inflow.add(int32(f.Length))
  1497. cc.mu.Unlock()
  1498. cc.wmu.Lock()
  1499. cc.fr.WriteWindowUpdate(0, uint32(f.Length))
  1500. cc.bw.Flush()
  1501. cc.wmu.Unlock()
  1502. }
  1503. return nil
  1504. }
  1505. if f.Length > 0 {
  1506. if len(data) > 0 && cs.bufPipe.b == nil {
  1507. // Data frame after it's already closed?
  1508. cc.logf("http2: Transport received DATA frame for closed stream; closing connection")
  1509. return ConnectionError(ErrCodeProtocol)
  1510. }
  1511. // Check connection-level flow control.
  1512. cc.mu.Lock()
  1513. if cs.inflow.available() >= int32(f.Length) {
  1514. cs.inflow.take(int32(f.Length))
  1515. } else {
  1516. cc.mu.Unlock()
  1517. return ConnectionError(ErrCodeFlowControl)
  1518. }
  1519. // Return any padded flow control now, since we won't
  1520. // refund it later on body reads.
  1521. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1522. cs.inflow.add(pad)
  1523. cc.inflow.add(pad)
  1524. cc.wmu.Lock()
  1525. cc.fr.WriteWindowUpdate(0, uint32(pad))
  1526. cc.fr.WriteWindowUpdate(cs.ID, uint32(pad))
  1527. cc.bw.Flush()
  1528. cc.wmu.Unlock()
  1529. }
  1530. cc.mu.Unlock()
  1531. if len(data) > 0 {
  1532. if _, err := cs.bufPipe.Write(data); err != nil {
  1533. rl.endStreamError(cs, err)
  1534. return err
  1535. }
  1536. }
  1537. }
  1538. if f.StreamEnded() {
  1539. rl.endStream(cs)
  1540. }
  1541. return nil
  1542. }
  1543. var errInvalidTrailers = errors.New("http2: invalid trailers")
  1544. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  1545. // TODO: check that any declared content-length matches, like
  1546. // server.go's (*stream).endStream method.
  1547. rl.endStreamError(cs, nil)
  1548. }
  1549. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  1550. var code func()
  1551. if err == nil {
  1552. err = io.EOF
  1553. code = cs.copyTrailers
  1554. }
  1555. cs.bufPipe.closeWithErrorAndCode(err, code)
  1556. delete(rl.activeRes, cs.ID)
  1557. if isConnectionCloseRequest(cs.req) {
  1558. rl.closeWhenIdle = true
  1559. }
  1560. select {
  1561. case cs.resc <- resAndError{err: err}:
  1562. default:
  1563. }
  1564. }
  1565. func (cs *clientStream) copyTrailers() {
  1566. for k, vv := range cs.trailer {
  1567. t := cs.resTrailer
  1568. if *t == nil {
  1569. *t = make(http.Header)
  1570. }
  1571. (*t)[k] = vv
  1572. }
  1573. }
  1574. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  1575. cc := rl.cc
  1576. cc.t.connPool().MarkDead(cc)
  1577. if f.ErrCode != 0 {
  1578. // TODO: deal with GOAWAY more. particularly the error code
  1579. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  1580. }
  1581. cc.setGoAway(f)
  1582. return nil
  1583. }
  1584. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  1585. cc := rl.cc
  1586. cc.mu.Lock()
  1587. defer cc.mu.Unlock()
  1588. if f.IsAck() {
  1589. if cc.wantSettingsAck {
  1590. cc.wantSettingsAck = false
  1591. return nil
  1592. }
  1593. return ConnectionError(ErrCodeProtocol)
  1594. }
  1595. err := f.ForeachSetting(func(s Setting) error {
  1596. switch s.ID {
  1597. case SettingMaxFrameSize:
  1598. cc.maxFrameSize = s.Val
  1599. case SettingMaxConcurrentStreams:
  1600. cc.maxConcurrentStreams = s.Val
  1601. case SettingInitialWindowSize:
  1602. // Values above the maximum flow-control
  1603. // window size of 2^31-1 MUST be treated as a
  1604. // connection error (Section 5.4.1) of type
  1605. // FLOW_CONTROL_ERROR.
  1606. if s.Val > math.MaxInt32 {
  1607. return ConnectionError(ErrCodeFlowControl)
  1608. }
  1609. // Adjust flow control of currently-open
  1610. // frames by the difference of the old initial
  1611. // window size and this one.
  1612. delta := int32(s.Val) - int32(cc.initialWindowSize)
  1613. for _, cs := range cc.streams {
  1614. cs.flow.add(delta)
  1615. }
  1616. cc.cond.Broadcast()
  1617. cc.initialWindowSize = s.Val
  1618. default:
  1619. // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  1620. cc.vlogf("Unhandled Setting: %v", s)
  1621. }
  1622. return nil
  1623. })
  1624. if err != nil {
  1625. return err
  1626. }
  1627. cc.wmu.Lock()
  1628. defer cc.wmu.Unlock()
  1629. cc.fr.WriteSettingsAck()
  1630. cc.bw.Flush()
  1631. return cc.werr
  1632. }
  1633. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  1634. cc := rl.cc
  1635. cs := cc.streamByID(f.StreamID, false)
  1636. if f.StreamID != 0 && cs == nil {
  1637. return nil
  1638. }
  1639. cc.mu.Lock()
  1640. defer cc.mu.Unlock()
  1641. fl := &cc.flow
  1642. if cs != nil {
  1643. fl = &cs.flow
  1644. }
  1645. if !fl.add(int32(f.Increment)) {
  1646. return ConnectionError(ErrCodeFlowControl)
  1647. }
  1648. cc.cond.Broadcast()
  1649. return nil
  1650. }
  1651. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1652. cs := rl.cc.streamByID(f.StreamID, true)
  1653. if cs == nil {
  1654. // TODO: return error if server tries to RST_STEAM an idle stream
  1655. return nil
  1656. }
  1657. select {
  1658. case <-cs.peerReset:
  1659. // Already reset.
  1660. // This is the only goroutine
  1661. // which closes this, so there
  1662. // isn't a race.
  1663. default:
  1664. err := streamError(cs.ID, f.ErrCode)
  1665. cs.resetErr = err
  1666. close(cs.peerReset)
  1667. cs.bufPipe.CloseWithError(err)
  1668. cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  1669. }
  1670. delete(rl.activeRes, cs.ID)
  1671. return nil
  1672. }
  1673. // Ping sends a PING frame to the server and waits for the ack.
  1674. // Public implementation is in go17.go and not_go17.go
  1675. func (cc *ClientConn) ping(ctx contextContext) error {
  1676. c := make(chan struct{})
  1677. // Generate a random payload
  1678. var p [8]byte
  1679. for {
  1680. if _, err := rand.Read(p[:]); err != nil {
  1681. return err
  1682. }
  1683. cc.mu.Lock()
  1684. // check for dup before insert
  1685. if _, found := cc.pings[p]; !found {
  1686. cc.pings[p] = c
  1687. cc.mu.Unlock()
  1688. break
  1689. }
  1690. cc.mu.Unlock()
  1691. }
  1692. cc.wmu.Lock()
  1693. if err := cc.fr.WritePing(false, p); err != nil {
  1694. cc.wmu.Unlock()
  1695. return err
  1696. }
  1697. if err := cc.bw.Flush(); err != nil {
  1698. cc.wmu.Unlock()
  1699. return err
  1700. }
  1701. cc.wmu.Unlock()
  1702. select {
  1703. case <-c:
  1704. return nil
  1705. case <-ctx.Done():
  1706. return ctx.Err()
  1707. case <-cc.readerDone:
  1708. // connection closed
  1709. return cc.readerErr
  1710. }
  1711. }
  1712. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1713. if f.IsAck() {
  1714. cc := rl.cc
  1715. cc.mu.Lock()
  1716. defer cc.mu.Unlock()
  1717. // If ack, notify listener if any
  1718. if c, ok := cc.pings[f.Data]; ok {
  1719. close(c)
  1720. delete(cc.pings, f.Data)
  1721. }
  1722. return nil
  1723. }
  1724. cc := rl.cc
  1725. cc.wmu.Lock()
  1726. defer cc.wmu.Unlock()
  1727. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1728. return err
  1729. }
  1730. return cc.bw.Flush()
  1731. }
  1732. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1733. // We told the peer we don't want them.
  1734. // Spec says:
  1735. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1736. // setting of the peer endpoint is set to 0. An endpoint that
  1737. // has set this setting and has received acknowledgement MUST
  1738. // treat the receipt of a PUSH_PROMISE frame as a connection
  1739. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1740. return ConnectionError(ErrCodeProtocol)
  1741. }
  1742. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1743. // TODO: map err to more interesting error codes, once the
  1744. // HTTP community comes up with some. But currently for
  1745. // RST_STREAM there's no equivalent to GOAWAY frame's debug
  1746. // data, and the error codes are all pretty vague ("cancel").
  1747. cc.wmu.Lock()
  1748. cc.fr.WriteRSTStream(streamID, code)
  1749. cc.bw.Flush()
  1750. cc.wmu.Unlock()
  1751. }
  1752. var (
  1753. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  1754. errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
  1755. )
  1756. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1757. cc.t.logf(format, args...)
  1758. }
  1759. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1760. cc.t.vlogf(format, args...)
  1761. }
  1762. func (t *Transport) vlogf(format string, args ...interface{}) {
  1763. if VerboseLogs {
  1764. t.logf(format, args...)
  1765. }
  1766. }
  1767. func (t *Transport) logf(format string, args ...interface{}) {
  1768. log.Printf(format, args...)
  1769. }
  1770. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1771. func strSliceContains(ss []string, s string) bool {
  1772. for _, v := range ss {
  1773. if v == s {
  1774. return true
  1775. }
  1776. }
  1777. return false
  1778. }
  1779. type erringRoundTripper struct{ err error }
  1780. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1781. // gzipReader wraps a response body so it can lazily
  1782. // call gzip.NewReader on the first call to Read
  1783. type gzipReader struct {
  1784. body io.ReadCloser // underlying Response.Body
  1785. zr *gzip.Reader // lazily-initialized gzip reader
  1786. zerr error // sticky error
  1787. }
  1788. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1789. if gz.zerr != nil {
  1790. return 0, gz.zerr
  1791. }
  1792. if gz.zr == nil {
  1793. gz.zr, err = gzip.NewReader(gz.body)
  1794. if err != nil {
  1795. gz.zerr = err
  1796. return 0, err
  1797. }
  1798. }
  1799. return gz.zr.Read(p)
  1800. }
  1801. func (gz *gzipReader) Close() error {
  1802. return gz.body.Close()
  1803. }
  1804. type errorReader struct{ err error }
  1805. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  1806. // bodyWriterState encapsulates various state around the Transport's writing
  1807. // of the request body, particularly regarding doing delayed writes of the body
  1808. // when the request contains "Expect: 100-continue".
  1809. type bodyWriterState struct {
  1810. cs *clientStream
  1811. timer *time.Timer // if non-nil, we're doing a delayed write
  1812. fnonce *sync.Once // to call fn with
  1813. fn func() // the code to run in the goroutine, writing the body
  1814. resc chan error // result of fn's execution
  1815. delay time.Duration // how long we should delay a delayed write for
  1816. }
  1817. func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
  1818. s.cs = cs
  1819. if body == nil {
  1820. return
  1821. }
  1822. resc := make(chan error, 1)
  1823. s.resc = resc
  1824. s.fn = func() {
  1825. resc <- cs.writeRequestBody(body, cs.req.Body)
  1826. }
  1827. s.delay = t.expectContinueTimeout()
  1828. if s.delay == 0 ||
  1829. !httplex.HeaderValuesContainsToken(
  1830. cs.req.Header["Expect"],
  1831. "100-continue") {
  1832. return
  1833. }
  1834. s.fnonce = new(sync.Once)
  1835. // Arm the timer with a very large duration, which we'll
  1836. // intentionally lower later. It has to be large now because
  1837. // we need a handle to it before writing the headers, but the
  1838. // s.delay value is defined to not start until after the
  1839. // request headers were written.
  1840. const hugeDuration = 365 * 24 * time.Hour
  1841. s.timer = time.AfterFunc(hugeDuration, func() {
  1842. s.fnonce.Do(s.fn)
  1843. })
  1844. return
  1845. }
  1846. func (s bodyWriterState) cancel() {
  1847. if s.timer != nil {
  1848. s.timer.Stop()
  1849. }
  1850. }
  1851. func (s bodyWriterState) on100() {
  1852. if s.timer == nil {
  1853. // If we didn't do a delayed write, ignore the server's
  1854. // bogus 100 continue response.
  1855. return
  1856. }
  1857. s.timer.Stop()
  1858. go func() { s.fnonce.Do(s.fn) }()
  1859. }
  1860. // scheduleBodyWrite starts writing the body, either immediately (in
  1861. // the common case) or after the delay timeout. It should not be
  1862. // called until after the headers have been written.
  1863. func (s bodyWriterState) scheduleBodyWrite() {
  1864. if s.timer == nil {
  1865. // We're not doing a delayed write (see
  1866. // getBodyWriterState), so just start the writing
  1867. // goroutine immediately.
  1868. go s.fn()
  1869. return
  1870. }
  1871. traceWait100Continue(s.cs.trace)
  1872. if s.timer.Stop() {
  1873. s.timer.Reset(s.delay)
  1874. }
  1875. }
  1876. // isConnectionCloseRequest reports whether req should use its own
  1877. // connection for a single request and then close the connection.
  1878. func isConnectionCloseRequest(req *http.Request) bool {
  1879. return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close")
  1880. }