transport.go 64 KB

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