transport.go 58 KB

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