transport.go 63 KB

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