transport.go 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  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. if waitingForConn != nil {
  853. close(waitingForConn)
  854. }
  855. return errClientConnUnusable
  856. }
  857. if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
  858. if waitingForConn != nil {
  859. close(waitingForConn)
  860. }
  861. return nil
  862. }
  863. // Unfortunately, we cannot wait on a condition variable and channel at
  864. // the same time, so instead, we spin up a goroutine to check if the
  865. // request is canceled while we wait for a slot to open in the connection.
  866. if waitingForConn == nil {
  867. waitingForConn = make(chan struct{})
  868. go func() {
  869. if err := awaitRequestCancel(req, waitingForConn); err != nil {
  870. cc.mu.Lock()
  871. waitingForConnErr = err
  872. cc.cond.Broadcast()
  873. cc.mu.Unlock()
  874. }
  875. }()
  876. }
  877. cc.pendingRequests++
  878. cc.cond.Wait()
  879. cc.pendingRequests--
  880. if waitingForConnErr != nil {
  881. return waitingForConnErr
  882. }
  883. }
  884. }
  885. // requires cc.wmu be held
  886. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  887. first := true // first frame written (HEADERS is first, then CONTINUATION)
  888. for len(hdrs) > 0 && cc.werr == nil {
  889. chunk := hdrs
  890. if len(chunk) > maxFrameSize {
  891. chunk = chunk[:maxFrameSize]
  892. }
  893. hdrs = hdrs[len(chunk):]
  894. endHeaders := len(hdrs) == 0
  895. if first {
  896. cc.fr.WriteHeaders(HeadersFrameParam{
  897. StreamID: streamID,
  898. BlockFragment: chunk,
  899. EndStream: endStream,
  900. EndHeaders: endHeaders,
  901. })
  902. first = false
  903. } else {
  904. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  905. }
  906. }
  907. // TODO(bradfitz): this Flush could potentially block (as
  908. // could the WriteHeaders call(s) above), which means they
  909. // wouldn't respond to Request.Cancel being readable. That's
  910. // rare, but this should probably be in a goroutine.
  911. cc.bw.Flush()
  912. return cc.werr
  913. }
  914. // internal error values; they don't escape to callers
  915. var (
  916. // abort request body write; don't send cancel
  917. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  918. // abort request body write, but send stream reset of cancel.
  919. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  920. )
  921. func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  922. cc := cs.cc
  923. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  924. buf := cc.frameScratchBuffer()
  925. defer cc.putFrameScratchBuffer(buf)
  926. defer func() {
  927. traceWroteRequest(cs.trace, err)
  928. // TODO: write h12Compare test showing whether
  929. // Request.Body is closed by the Transport,
  930. // and in multiple cases: server replies <=299 and >299
  931. // while still writing request body
  932. cerr := bodyCloser.Close()
  933. if err == nil {
  934. err = cerr
  935. }
  936. }()
  937. req := cs.req
  938. hasTrailers := req.Trailer != nil
  939. var sawEOF bool
  940. for !sawEOF {
  941. n, err := body.Read(buf)
  942. if err == io.EOF {
  943. sawEOF = true
  944. err = nil
  945. } else if err != nil {
  946. return err
  947. }
  948. remain := buf[:n]
  949. for len(remain) > 0 && err == nil {
  950. var allowed int32
  951. allowed, err = cs.awaitFlowControl(len(remain))
  952. switch {
  953. case err == errStopReqBodyWrite:
  954. return err
  955. case err == errStopReqBodyWriteAndCancel:
  956. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  957. return err
  958. case err != nil:
  959. return err
  960. }
  961. cc.wmu.Lock()
  962. data := remain[:allowed]
  963. remain = remain[allowed:]
  964. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  965. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  966. if err == nil {
  967. // TODO(bradfitz): this flush is for latency, not bandwidth.
  968. // Most requests won't need this. Make this opt-in or
  969. // opt-out? Use some heuristic on the body type? Nagel-like
  970. // timers? Based on 'n'? Only last chunk of this for loop,
  971. // unless flow control tokens are low? For now, always.
  972. // If we change this, see comment below.
  973. err = cc.bw.Flush()
  974. }
  975. cc.wmu.Unlock()
  976. }
  977. if err != nil {
  978. return err
  979. }
  980. }
  981. if sentEnd {
  982. // Already sent END_STREAM (which implies we have no
  983. // trailers) and flushed, because currently all
  984. // WriteData frames above get a flush. So we're done.
  985. return nil
  986. }
  987. var trls []byte
  988. if hasTrailers {
  989. cc.mu.Lock()
  990. trls, err = cc.encodeTrailers(req)
  991. cc.mu.Unlock()
  992. if err != nil {
  993. cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
  994. cc.forgetStreamID(cs.ID)
  995. return err
  996. }
  997. }
  998. cc.mu.Lock()
  999. maxFrameSize := int(cc.maxFrameSize)
  1000. cc.mu.Unlock()
  1001. cc.wmu.Lock()
  1002. defer cc.wmu.Unlock()
  1003. // Two ways to send END_STREAM: either with trailers, or
  1004. // with an empty DATA frame.
  1005. if len(trls) > 0 {
  1006. err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1007. } else {
  1008. err = cc.fr.WriteData(cs.ID, true, nil)
  1009. }
  1010. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1011. err = ferr
  1012. }
  1013. return err
  1014. }
  1015. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1016. // control tokens from the server.
  1017. // It returns either the non-zero number of tokens taken or an error
  1018. // if the stream is dead.
  1019. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1020. cc := cs.cc
  1021. cc.mu.Lock()
  1022. defer cc.mu.Unlock()
  1023. for {
  1024. if cc.closed {
  1025. return 0, errClientConnClosed
  1026. }
  1027. if cs.stopReqBody != nil {
  1028. return 0, cs.stopReqBody
  1029. }
  1030. if err := cs.checkResetOrDone(); err != nil {
  1031. return 0, err
  1032. }
  1033. if a := cs.flow.available(); a > 0 {
  1034. take := a
  1035. if int(take) > maxBytes {
  1036. take = int32(maxBytes) // can't truncate int; take is int32
  1037. }
  1038. if take > int32(cc.maxFrameSize) {
  1039. take = int32(cc.maxFrameSize)
  1040. }
  1041. cs.flow.take(take)
  1042. return take, nil
  1043. }
  1044. cc.cond.Wait()
  1045. }
  1046. }
  1047. type badStringError struct {
  1048. what string
  1049. str string
  1050. }
  1051. func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  1052. // requires cc.mu be held.
  1053. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1054. cc.hbuf.Reset()
  1055. host := req.Host
  1056. if host == "" {
  1057. host = req.URL.Host
  1058. }
  1059. host, err := httplex.PunycodeHostPort(host)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. var path string
  1064. if req.Method != "CONNECT" {
  1065. path = req.URL.RequestURI()
  1066. if !validPseudoPath(path) {
  1067. orig := path
  1068. path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1069. if !validPseudoPath(path) {
  1070. if req.URL.Opaque != "" {
  1071. return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1072. } else {
  1073. return nil, fmt.Errorf("invalid request :path %q", orig)
  1074. }
  1075. }
  1076. }
  1077. }
  1078. // Check for any invalid headers and return an error before we
  1079. // potentially pollute our hpack state. (We want to be able to
  1080. // continue to reuse the hpack encoder for future requests)
  1081. for k, vv := range req.Header {
  1082. if !httplex.ValidHeaderFieldName(k) {
  1083. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1084. }
  1085. for _, v := range vv {
  1086. if !httplex.ValidHeaderFieldValue(v) {
  1087. return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  1088. }
  1089. }
  1090. }
  1091. enumerateHeaders := func(f func(name, value string)) {
  1092. // 8.1.2.3 Request Pseudo-Header Fields
  1093. // The :path pseudo-header field includes the path and query parts of the
  1094. // target URI (the path-absolute production and optionally a '?' character
  1095. // followed by the query production (see Sections 3.3 and 3.4 of
  1096. // [RFC3986]).
  1097. f(":authority", host)
  1098. f(":method", req.Method)
  1099. if req.Method != "CONNECT" {
  1100. f(":path", path)
  1101. f(":scheme", req.URL.Scheme)
  1102. }
  1103. if trailers != "" {
  1104. f("trailer", trailers)
  1105. }
  1106. var didUA bool
  1107. for k, vv := range req.Header {
  1108. if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") {
  1109. // Host is :authority, already sent.
  1110. // Content-Length is automatic, set below.
  1111. continue
  1112. } else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") ||
  1113. strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") ||
  1114. strings.EqualFold(k, "keep-alive") {
  1115. // Per 8.1.2.2 Connection-Specific Header
  1116. // Fields, don't send connection-specific
  1117. // fields. We have already checked if any
  1118. // are error-worthy so just ignore the rest.
  1119. continue
  1120. } else if strings.EqualFold(k, "user-agent") {
  1121. // Match Go's http1 behavior: at most one
  1122. // User-Agent. If set to nil or empty string,
  1123. // then omit it. Otherwise if not mentioned,
  1124. // include the default (below).
  1125. didUA = true
  1126. if len(vv) < 1 {
  1127. continue
  1128. }
  1129. vv = vv[:1]
  1130. if vv[0] == "" {
  1131. continue
  1132. }
  1133. }
  1134. for _, v := range vv {
  1135. f(k, v)
  1136. }
  1137. }
  1138. if shouldSendReqContentLength(req.Method, contentLength) {
  1139. f("content-length", strconv.FormatInt(contentLength, 10))
  1140. }
  1141. if addGzipHeader {
  1142. f("accept-encoding", "gzip")
  1143. }
  1144. if !didUA {
  1145. f("user-agent", defaultUserAgent)
  1146. }
  1147. }
  1148. // Do a first pass over the headers counting bytes to ensure
  1149. // we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1150. // separate pass before encoding the headers to prevent
  1151. // modifying the hpack state.
  1152. hlSize := uint64(0)
  1153. enumerateHeaders(func(name, value string) {
  1154. hf := hpack.HeaderField{Name: name, Value: value}
  1155. hlSize += uint64(hf.Size())
  1156. })
  1157. if hlSize > cc.peerMaxHeaderListSize {
  1158. return nil, errRequestHeaderListSize
  1159. }
  1160. // Header list size is ok. Write the headers.
  1161. enumerateHeaders(func(name, value string) {
  1162. cc.writeHeader(strings.ToLower(name), value)
  1163. })
  1164. return cc.hbuf.Bytes(), nil
  1165. }
  1166. // shouldSendReqContentLength reports whether the http2.Transport should send
  1167. // a "content-length" request header. This logic is basically a copy of the net/http
  1168. // transferWriter.shouldSendContentLength.
  1169. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1170. // -1 means unknown.
  1171. func shouldSendReqContentLength(method string, contentLength int64) bool {
  1172. if contentLength > 0 {
  1173. return true
  1174. }
  1175. if contentLength < 0 {
  1176. return false
  1177. }
  1178. // For zero bodies, whether we send a content-length depends on the method.
  1179. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  1180. switch method {
  1181. case "POST", "PUT", "PATCH":
  1182. return true
  1183. default:
  1184. return false
  1185. }
  1186. }
  1187. // requires cc.mu be held.
  1188. func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
  1189. cc.hbuf.Reset()
  1190. hlSize := uint64(0)
  1191. for k, vv := range req.Trailer {
  1192. for _, v := range vv {
  1193. hf := hpack.HeaderField{Name: k, Value: v}
  1194. hlSize += uint64(hf.Size())
  1195. }
  1196. }
  1197. if hlSize > cc.peerMaxHeaderListSize {
  1198. return nil, errRequestHeaderListSize
  1199. }
  1200. for k, vv := range req.Trailer {
  1201. // Transfer-Encoding, etc.. have already been filtered at the
  1202. // start of RoundTrip
  1203. lowKey := strings.ToLower(k)
  1204. for _, v := range vv {
  1205. cc.writeHeader(lowKey, v)
  1206. }
  1207. }
  1208. return cc.hbuf.Bytes(), nil
  1209. }
  1210. func (cc *ClientConn) writeHeader(name, value string) {
  1211. if VerboseLogs {
  1212. log.Printf("http2: Transport encoding header %q = %q", name, value)
  1213. }
  1214. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1215. }
  1216. type resAndError struct {
  1217. res *http.Response
  1218. err error
  1219. }
  1220. // requires cc.mu be held.
  1221. func (cc *ClientConn) newStream() *clientStream {
  1222. cs := &clientStream{
  1223. cc: cc,
  1224. ID: cc.nextStreamID,
  1225. resc: make(chan resAndError, 1),
  1226. peerReset: make(chan struct{}),
  1227. done: make(chan struct{}),
  1228. }
  1229. cs.flow.add(int32(cc.initialWindowSize))
  1230. cs.flow.setConnFlow(&cc.flow)
  1231. cs.inflow.add(transportDefaultStreamFlow)
  1232. cs.inflow.setConnFlow(&cc.inflow)
  1233. cc.nextStreamID += 2
  1234. cc.streams[cs.ID] = cs
  1235. return cs
  1236. }
  1237. func (cc *ClientConn) forgetStreamID(id uint32) {
  1238. cc.streamByID(id, true)
  1239. }
  1240. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1241. cc.mu.Lock()
  1242. defer cc.mu.Unlock()
  1243. cs := cc.streams[id]
  1244. if andRemove && cs != nil && !cc.closed {
  1245. cc.lastActive = time.Now()
  1246. delete(cc.streams, id)
  1247. if len(cc.streams) == 0 && cc.idleTimer != nil {
  1248. cc.idleTimer.Reset(cc.idleTimeout)
  1249. }
  1250. close(cs.done)
  1251. // Wake up checkResetOrDone via clientStream.awaitFlowControl and
  1252. // wake up RoundTrip if there is a pending request.
  1253. cc.cond.Broadcast()
  1254. }
  1255. return cs
  1256. }
  1257. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1258. type clientConnReadLoop struct {
  1259. cc *ClientConn
  1260. closeWhenIdle bool
  1261. }
  1262. // readLoop runs in its own goroutine and reads and dispatches frames.
  1263. func (cc *ClientConn) readLoop() {
  1264. rl := &clientConnReadLoop{cc: cc}
  1265. defer rl.cleanup()
  1266. cc.readerErr = rl.run()
  1267. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1268. cc.wmu.Lock()
  1269. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1270. cc.wmu.Unlock()
  1271. }
  1272. }
  1273. // GoAwayError is returned by the Transport when the server closes the
  1274. // TCP connection after sending a GOAWAY frame.
  1275. type GoAwayError struct {
  1276. LastStreamID uint32
  1277. ErrCode ErrCode
  1278. DebugData string
  1279. }
  1280. func (e GoAwayError) Error() string {
  1281. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1282. e.LastStreamID, e.ErrCode, e.DebugData)
  1283. }
  1284. func isEOFOrNetReadError(err error) bool {
  1285. if err == io.EOF {
  1286. return true
  1287. }
  1288. ne, ok := err.(*net.OpError)
  1289. return ok && ne.Op == "read"
  1290. }
  1291. func (rl *clientConnReadLoop) cleanup() {
  1292. cc := rl.cc
  1293. defer cc.tconn.Close()
  1294. defer cc.t.connPool().MarkDead(cc)
  1295. defer close(cc.readerDone)
  1296. if cc.idleTimer != nil {
  1297. cc.idleTimer.Stop()
  1298. }
  1299. // Close any response bodies if the server closes prematurely.
  1300. // TODO: also do this if we've written the headers but not
  1301. // gotten a response yet.
  1302. err := cc.readerErr
  1303. cc.mu.Lock()
  1304. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1305. err = GoAwayError{
  1306. LastStreamID: cc.goAway.LastStreamID,
  1307. ErrCode: cc.goAway.ErrCode,
  1308. DebugData: cc.goAwayDebug,
  1309. }
  1310. } else if err == io.EOF {
  1311. err = io.ErrUnexpectedEOF
  1312. }
  1313. for _, cs := range cc.streams {
  1314. cs.bufPipe.CloseWithError(err) // no-op if already closed
  1315. select {
  1316. case cs.resc <- resAndError{err: err}:
  1317. default:
  1318. }
  1319. close(cs.done)
  1320. }
  1321. cc.closed = true
  1322. cc.cond.Broadcast()
  1323. cc.mu.Unlock()
  1324. }
  1325. func (rl *clientConnReadLoop) run() error {
  1326. cc := rl.cc
  1327. rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1328. gotReply := false // ever saw a HEADERS reply
  1329. gotSettings := false
  1330. for {
  1331. f, err := cc.fr.ReadFrame()
  1332. if err != nil {
  1333. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1334. }
  1335. if se, ok := err.(StreamError); ok {
  1336. if cs := cc.streamByID(se.StreamID, false); cs != nil {
  1337. cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1338. cs.cc.forgetStreamID(cs.ID)
  1339. if se.Cause == nil {
  1340. se.Cause = cc.fr.errDetail
  1341. }
  1342. rl.endStreamError(cs, se)
  1343. }
  1344. continue
  1345. } else if err != nil {
  1346. return err
  1347. }
  1348. if VerboseLogs {
  1349. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1350. }
  1351. if !gotSettings {
  1352. if _, ok := f.(*SettingsFrame); !ok {
  1353. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1354. return ConnectionError(ErrCodeProtocol)
  1355. }
  1356. gotSettings = true
  1357. }
  1358. maybeIdle := false // whether frame might transition us to idle
  1359. switch f := f.(type) {
  1360. case *MetaHeadersFrame:
  1361. err = rl.processHeaders(f)
  1362. maybeIdle = true
  1363. gotReply = true
  1364. case *DataFrame:
  1365. err = rl.processData(f)
  1366. maybeIdle = true
  1367. case *GoAwayFrame:
  1368. err = rl.processGoAway(f)
  1369. maybeIdle = true
  1370. case *RSTStreamFrame:
  1371. err = rl.processResetStream(f)
  1372. maybeIdle = true
  1373. case *SettingsFrame:
  1374. err = rl.processSettings(f)
  1375. case *PushPromiseFrame:
  1376. err = rl.processPushPromise(f)
  1377. case *WindowUpdateFrame:
  1378. err = rl.processWindowUpdate(f)
  1379. case *PingFrame:
  1380. err = rl.processPing(f)
  1381. default:
  1382. cc.logf("Transport: unhandled response frame type %T", f)
  1383. }
  1384. if err != nil {
  1385. if VerboseLogs {
  1386. cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  1387. }
  1388. return err
  1389. }
  1390. if rl.closeWhenIdle && gotReply && maybeIdle {
  1391. cc.closeIfIdle()
  1392. }
  1393. }
  1394. }
  1395. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  1396. cc := rl.cc
  1397. cs := cc.streamByID(f.StreamID, false)
  1398. if cs == nil {
  1399. // We'd get here if we canceled a request while the
  1400. // server had its response still in flight. So if this
  1401. // was just something we canceled, ignore it.
  1402. return nil
  1403. }
  1404. if f.StreamEnded() {
  1405. // Issue 20521: If the stream has ended, streamByID() causes
  1406. // clientStream.done to be closed, which causes the request's bodyWriter
  1407. // to be closed with an errStreamClosed, which may be received by
  1408. // clientConn.RoundTrip before the result of processing these headers.
  1409. // Deferring stream closure allows the header processing to occur first.
  1410. // clientConn.RoundTrip may still receive the bodyWriter error first, but
  1411. // the fix for issue 16102 prioritises any response.
  1412. //
  1413. // Issue 22413: If there is no request body, we should close the
  1414. // stream before writing to cs.resc so that the stream is closed
  1415. // immediately once RoundTrip returns.
  1416. if cs.req.Body != nil {
  1417. defer cc.forgetStreamID(f.StreamID)
  1418. } else {
  1419. cc.forgetStreamID(f.StreamID)
  1420. }
  1421. }
  1422. if !cs.firstByte {
  1423. if cs.trace != nil {
  1424. // TODO(bradfitz): move first response byte earlier,
  1425. // when we first read the 9 byte header, not waiting
  1426. // until all the HEADERS+CONTINUATION frames have been
  1427. // merged. This works for now.
  1428. traceFirstResponseByte(cs.trace)
  1429. }
  1430. cs.firstByte = true
  1431. }
  1432. if !cs.pastHeaders {
  1433. cs.pastHeaders = true
  1434. } else {
  1435. return rl.processTrailers(cs, f)
  1436. }
  1437. res, err := rl.handleResponse(cs, f)
  1438. if err != nil {
  1439. if _, ok := err.(ConnectionError); ok {
  1440. return err
  1441. }
  1442. // Any other error type is a stream error.
  1443. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  1444. cc.forgetStreamID(cs.ID)
  1445. cs.resc <- resAndError{err: err}
  1446. return nil // return nil from process* funcs to keep conn alive
  1447. }
  1448. if res == nil {
  1449. // (nil, nil) special case. See handleResponse docs.
  1450. return nil
  1451. }
  1452. cs.resTrailer = &res.Trailer
  1453. cs.resc <- resAndError{res: res}
  1454. return nil
  1455. }
  1456. // may return error types nil, or ConnectionError. Any other error value
  1457. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  1458. // is the detail.
  1459. //
  1460. // As a special case, handleResponse may return (nil, nil) to skip the
  1461. // frame (currently only used for 100 expect continue). This special
  1462. // case is going away after Issue 13851 is fixed.
  1463. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  1464. if f.Truncated {
  1465. return nil, errResponseHeaderListSize
  1466. }
  1467. status := f.PseudoValue("status")
  1468. if status == "" {
  1469. return nil, errors.New("malformed response from server: missing status pseudo header")
  1470. }
  1471. statusCode, err := strconv.Atoi(status)
  1472. if err != nil {
  1473. return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  1474. }
  1475. if statusCode == 100 {
  1476. traceGot100Continue(cs.trace)
  1477. if cs.on100 != nil {
  1478. cs.on100() // forces any write delay timer to fire
  1479. }
  1480. cs.pastHeaders = false // do it all again
  1481. return nil, nil
  1482. }
  1483. header := make(http.Header)
  1484. res := &http.Response{
  1485. Proto: "HTTP/2.0",
  1486. ProtoMajor: 2,
  1487. Header: header,
  1488. StatusCode: statusCode,
  1489. Status: status + " " + http.StatusText(statusCode),
  1490. }
  1491. for _, hf := range f.RegularFields() {
  1492. key := http.CanonicalHeaderKey(hf.Name)
  1493. if key == "Trailer" {
  1494. t := res.Trailer
  1495. if t == nil {
  1496. t = make(http.Header)
  1497. res.Trailer = t
  1498. }
  1499. foreachHeaderElement(hf.Value, func(v string) {
  1500. t[http.CanonicalHeaderKey(v)] = nil
  1501. })
  1502. } else {
  1503. header[key] = append(header[key], hf.Value)
  1504. }
  1505. }
  1506. streamEnded := f.StreamEnded()
  1507. isHead := cs.req.Method == "HEAD"
  1508. if !streamEnded || isHead {
  1509. res.ContentLength = -1
  1510. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1511. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1512. res.ContentLength = clen64
  1513. } else {
  1514. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1515. // more safe smuggling-wise to ignore.
  1516. }
  1517. } else if len(clens) > 1 {
  1518. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1519. // more safe smuggling-wise to ignore.
  1520. }
  1521. }
  1522. if streamEnded || isHead {
  1523. res.Body = noBody
  1524. return res, nil
  1525. }
  1526. cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
  1527. cs.bytesRemain = res.ContentLength
  1528. res.Body = transportResponseBody{cs}
  1529. go cs.awaitRequestCancel(cs.req)
  1530. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1531. res.Header.Del("Content-Encoding")
  1532. res.Header.Del("Content-Length")
  1533. res.ContentLength = -1
  1534. res.Body = &gzipReader{body: res.Body}
  1535. setResponseUncompressed(res)
  1536. }
  1537. return res, nil
  1538. }
  1539. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  1540. if cs.pastTrailers {
  1541. // Too many HEADERS frames for this stream.
  1542. return ConnectionError(ErrCodeProtocol)
  1543. }
  1544. cs.pastTrailers = true
  1545. if !f.StreamEnded() {
  1546. // We expect that any headers for trailers also
  1547. // has END_STREAM.
  1548. return ConnectionError(ErrCodeProtocol)
  1549. }
  1550. if len(f.PseudoFields()) > 0 {
  1551. // No pseudo header fields are defined for trailers.
  1552. // TODO: ConnectionError might be overly harsh? Check.
  1553. return ConnectionError(ErrCodeProtocol)
  1554. }
  1555. trailer := make(http.Header)
  1556. for _, hf := range f.RegularFields() {
  1557. key := http.CanonicalHeaderKey(hf.Name)
  1558. trailer[key] = append(trailer[key], hf.Value)
  1559. }
  1560. cs.trailer = trailer
  1561. rl.endStream(cs)
  1562. return nil
  1563. }
  1564. // transportResponseBody is the concrete type of Transport.RoundTrip's
  1565. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1566. // On Close it sends RST_STREAM if EOF wasn't already seen.
  1567. type transportResponseBody struct {
  1568. cs *clientStream
  1569. }
  1570. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1571. cs := b.cs
  1572. cc := cs.cc
  1573. if cs.readErr != nil {
  1574. return 0, cs.readErr
  1575. }
  1576. n, err = b.cs.bufPipe.Read(p)
  1577. if cs.bytesRemain != -1 {
  1578. if int64(n) > cs.bytesRemain {
  1579. n = int(cs.bytesRemain)
  1580. if err == nil {
  1581. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1582. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1583. }
  1584. cs.readErr = err
  1585. return int(cs.bytesRemain), err
  1586. }
  1587. cs.bytesRemain -= int64(n)
  1588. if err == io.EOF && cs.bytesRemain > 0 {
  1589. err = io.ErrUnexpectedEOF
  1590. cs.readErr = err
  1591. return n, err
  1592. }
  1593. }
  1594. if n == 0 {
  1595. // No flow control tokens to send back.
  1596. return
  1597. }
  1598. cc.mu.Lock()
  1599. defer cc.mu.Unlock()
  1600. var connAdd, streamAdd int32
  1601. // Check the conn-level first, before the stream-level.
  1602. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  1603. connAdd = transportDefaultConnFlow - v
  1604. cc.inflow.add(connAdd)
  1605. }
  1606. if err == nil { // No need to refresh if the stream is over or failed.
  1607. // Consider any buffered body data (read from the conn but not
  1608. // consumed by the client) when computing flow control for this
  1609. // stream.
  1610. v := int(cs.inflow.available()) + cs.bufPipe.Len()
  1611. if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  1612. streamAdd = int32(transportDefaultStreamFlow - v)
  1613. cs.inflow.add(streamAdd)
  1614. }
  1615. }
  1616. if connAdd != 0 || streamAdd != 0 {
  1617. cc.wmu.Lock()
  1618. defer cc.wmu.Unlock()
  1619. if connAdd != 0 {
  1620. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  1621. }
  1622. if streamAdd != 0 {
  1623. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  1624. }
  1625. cc.bw.Flush()
  1626. }
  1627. return
  1628. }
  1629. var errClosedResponseBody = errors.New("http2: response body closed")
  1630. func (b transportResponseBody) Close() error {
  1631. cs := b.cs
  1632. cc := cs.cc
  1633. serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
  1634. unread := cs.bufPipe.Len()
  1635. if unread > 0 || !serverSentStreamEnd {
  1636. cc.mu.Lock()
  1637. cc.wmu.Lock()
  1638. if !serverSentStreamEnd {
  1639. cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
  1640. cs.didReset = true
  1641. }
  1642. // Return connection-level flow control.
  1643. if unread > 0 {
  1644. cc.inflow.add(int32(unread))
  1645. cc.fr.WriteWindowUpdate(0, uint32(unread))
  1646. }
  1647. cc.bw.Flush()
  1648. cc.wmu.Unlock()
  1649. cc.mu.Unlock()
  1650. }
  1651. cs.bufPipe.BreakWithError(errClosedResponseBody)
  1652. cc.forgetStreamID(cs.ID)
  1653. return nil
  1654. }
  1655. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  1656. cc := rl.cc
  1657. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1658. data := f.Data()
  1659. if cs == nil {
  1660. cc.mu.Lock()
  1661. neverSent := cc.nextStreamID
  1662. cc.mu.Unlock()
  1663. if f.StreamID >= neverSent {
  1664. // We never asked for this.
  1665. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  1666. return ConnectionError(ErrCodeProtocol)
  1667. }
  1668. // We probably did ask for this, but canceled. Just ignore it.
  1669. // TODO: be stricter here? only silently ignore things which
  1670. // we canceled, but not things which were closed normally
  1671. // by the peer? Tough without accumulating too much state.
  1672. // But at least return their flow control:
  1673. if f.Length > 0 {
  1674. cc.mu.Lock()
  1675. cc.inflow.add(int32(f.Length))
  1676. cc.mu.Unlock()
  1677. cc.wmu.Lock()
  1678. cc.fr.WriteWindowUpdate(0, uint32(f.Length))
  1679. cc.bw.Flush()
  1680. cc.wmu.Unlock()
  1681. }
  1682. return nil
  1683. }
  1684. if !cs.firstByte {
  1685. cc.logf("protocol error: received DATA before a HEADERS frame")
  1686. rl.endStreamError(cs, StreamError{
  1687. StreamID: f.StreamID,
  1688. Code: ErrCodeProtocol,
  1689. })
  1690. return nil
  1691. }
  1692. if f.Length > 0 {
  1693. if cs.req.Method == "HEAD" && len(data) > 0 {
  1694. cc.logf("protocol error: received DATA on a HEAD request")
  1695. rl.endStreamError(cs, StreamError{
  1696. StreamID: f.StreamID,
  1697. Code: ErrCodeProtocol,
  1698. })
  1699. return nil
  1700. }
  1701. // Check connection-level flow control.
  1702. cc.mu.Lock()
  1703. if cs.inflow.available() >= int32(f.Length) {
  1704. cs.inflow.take(int32(f.Length))
  1705. } else {
  1706. cc.mu.Unlock()
  1707. return ConnectionError(ErrCodeFlowControl)
  1708. }
  1709. // Return any padded flow control now, since we won't
  1710. // refund it later on body reads.
  1711. var refund int
  1712. if pad := int(f.Length) - len(data); pad > 0 {
  1713. refund += pad
  1714. }
  1715. // Return len(data) now if the stream is already closed,
  1716. // since data will never be read.
  1717. didReset := cs.didReset
  1718. if didReset {
  1719. refund += len(data)
  1720. }
  1721. if refund > 0 {
  1722. cc.inflow.add(int32(refund))
  1723. cc.wmu.Lock()
  1724. cc.fr.WriteWindowUpdate(0, uint32(refund))
  1725. if !didReset {
  1726. cs.inflow.add(int32(refund))
  1727. cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
  1728. }
  1729. cc.bw.Flush()
  1730. cc.wmu.Unlock()
  1731. }
  1732. cc.mu.Unlock()
  1733. if len(data) > 0 && !didReset {
  1734. if _, err := cs.bufPipe.Write(data); err != nil {
  1735. rl.endStreamError(cs, err)
  1736. return err
  1737. }
  1738. }
  1739. }
  1740. if f.StreamEnded() {
  1741. rl.endStream(cs)
  1742. }
  1743. return nil
  1744. }
  1745. var errInvalidTrailers = errors.New("http2: invalid trailers")
  1746. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  1747. // TODO: check that any declared content-length matches, like
  1748. // server.go's (*stream).endStream method.
  1749. rl.endStreamError(cs, nil)
  1750. }
  1751. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  1752. var code func()
  1753. if err == nil {
  1754. err = io.EOF
  1755. code = cs.copyTrailers
  1756. }
  1757. if isConnectionCloseRequest(cs.req) {
  1758. rl.closeWhenIdle = true
  1759. }
  1760. cs.bufPipe.closeWithErrorAndCode(err, code)
  1761. select {
  1762. case cs.resc <- resAndError{err: err}:
  1763. default:
  1764. }
  1765. }
  1766. func (cs *clientStream) copyTrailers() {
  1767. for k, vv := range cs.trailer {
  1768. t := cs.resTrailer
  1769. if *t == nil {
  1770. *t = make(http.Header)
  1771. }
  1772. (*t)[k] = vv
  1773. }
  1774. }
  1775. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  1776. cc := rl.cc
  1777. cc.t.connPool().MarkDead(cc)
  1778. if f.ErrCode != 0 {
  1779. // TODO: deal with GOAWAY more. particularly the error code
  1780. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  1781. }
  1782. cc.setGoAway(f)
  1783. return nil
  1784. }
  1785. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  1786. cc := rl.cc
  1787. cc.mu.Lock()
  1788. defer cc.mu.Unlock()
  1789. if f.IsAck() {
  1790. if cc.wantSettingsAck {
  1791. cc.wantSettingsAck = false
  1792. return nil
  1793. }
  1794. return ConnectionError(ErrCodeProtocol)
  1795. }
  1796. err := f.ForeachSetting(func(s Setting) error {
  1797. switch s.ID {
  1798. case SettingMaxFrameSize:
  1799. cc.maxFrameSize = s.Val
  1800. case SettingMaxConcurrentStreams:
  1801. cc.maxConcurrentStreams = s.Val
  1802. case SettingMaxHeaderListSize:
  1803. cc.peerMaxHeaderListSize = uint64(s.Val)
  1804. case SettingInitialWindowSize:
  1805. // Values above the maximum flow-control
  1806. // window size of 2^31-1 MUST be treated as a
  1807. // connection error (Section 5.4.1) of type
  1808. // FLOW_CONTROL_ERROR.
  1809. if s.Val > math.MaxInt32 {
  1810. return ConnectionError(ErrCodeFlowControl)
  1811. }
  1812. // Adjust flow control of currently-open
  1813. // frames by the difference of the old initial
  1814. // window size and this one.
  1815. delta := int32(s.Val) - int32(cc.initialWindowSize)
  1816. for _, cs := range cc.streams {
  1817. cs.flow.add(delta)
  1818. }
  1819. cc.cond.Broadcast()
  1820. cc.initialWindowSize = s.Val
  1821. default:
  1822. // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  1823. cc.vlogf("Unhandled Setting: %v", s)
  1824. }
  1825. return nil
  1826. })
  1827. if err != nil {
  1828. return err
  1829. }
  1830. cc.wmu.Lock()
  1831. defer cc.wmu.Unlock()
  1832. cc.fr.WriteSettingsAck()
  1833. cc.bw.Flush()
  1834. return cc.werr
  1835. }
  1836. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  1837. cc := rl.cc
  1838. cs := cc.streamByID(f.StreamID, false)
  1839. if f.StreamID != 0 && cs == nil {
  1840. return nil
  1841. }
  1842. cc.mu.Lock()
  1843. defer cc.mu.Unlock()
  1844. fl := &cc.flow
  1845. if cs != nil {
  1846. fl = &cs.flow
  1847. }
  1848. if !fl.add(int32(f.Increment)) {
  1849. return ConnectionError(ErrCodeFlowControl)
  1850. }
  1851. cc.cond.Broadcast()
  1852. return nil
  1853. }
  1854. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1855. cs := rl.cc.streamByID(f.StreamID, true)
  1856. if cs == nil {
  1857. // TODO: return error if server tries to RST_STEAM an idle stream
  1858. return nil
  1859. }
  1860. select {
  1861. case <-cs.peerReset:
  1862. // Already reset.
  1863. // This is the only goroutine
  1864. // which closes this, so there
  1865. // isn't a race.
  1866. default:
  1867. err := streamError(cs.ID, f.ErrCode)
  1868. cs.resetErr = err
  1869. close(cs.peerReset)
  1870. cs.bufPipe.CloseWithError(err)
  1871. cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  1872. }
  1873. return nil
  1874. }
  1875. // Ping sends a PING frame to the server and waits for the ack.
  1876. // Public implementation is in go17.go and not_go17.go
  1877. func (cc *ClientConn) ping(ctx contextContext) error {
  1878. c := make(chan struct{})
  1879. // Generate a random payload
  1880. var p [8]byte
  1881. for {
  1882. if _, err := rand.Read(p[:]); err != nil {
  1883. return err
  1884. }
  1885. cc.mu.Lock()
  1886. // check for dup before insert
  1887. if _, found := cc.pings[p]; !found {
  1888. cc.pings[p] = c
  1889. cc.mu.Unlock()
  1890. break
  1891. }
  1892. cc.mu.Unlock()
  1893. }
  1894. cc.wmu.Lock()
  1895. if err := cc.fr.WritePing(false, p); err != nil {
  1896. cc.wmu.Unlock()
  1897. return err
  1898. }
  1899. if err := cc.bw.Flush(); err != nil {
  1900. cc.wmu.Unlock()
  1901. return err
  1902. }
  1903. cc.wmu.Unlock()
  1904. select {
  1905. case <-c:
  1906. return nil
  1907. case <-ctx.Done():
  1908. return ctx.Err()
  1909. case <-cc.readerDone:
  1910. // connection closed
  1911. return cc.readerErr
  1912. }
  1913. }
  1914. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1915. if f.IsAck() {
  1916. cc := rl.cc
  1917. cc.mu.Lock()
  1918. defer cc.mu.Unlock()
  1919. // If ack, notify listener if any
  1920. if c, ok := cc.pings[f.Data]; ok {
  1921. close(c)
  1922. delete(cc.pings, f.Data)
  1923. }
  1924. return nil
  1925. }
  1926. cc := rl.cc
  1927. cc.wmu.Lock()
  1928. defer cc.wmu.Unlock()
  1929. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1930. return err
  1931. }
  1932. return cc.bw.Flush()
  1933. }
  1934. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1935. // We told the peer we don't want them.
  1936. // Spec says:
  1937. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1938. // setting of the peer endpoint is set to 0. An endpoint that
  1939. // has set this setting and has received acknowledgement MUST
  1940. // treat the receipt of a PUSH_PROMISE frame as a connection
  1941. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1942. return ConnectionError(ErrCodeProtocol)
  1943. }
  1944. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1945. // TODO: map err to more interesting error codes, once the
  1946. // HTTP community comes up with some. But currently for
  1947. // RST_STREAM there's no equivalent to GOAWAY frame's debug
  1948. // data, and the error codes are all pretty vague ("cancel").
  1949. cc.wmu.Lock()
  1950. cc.fr.WriteRSTStream(streamID, code)
  1951. cc.bw.Flush()
  1952. cc.wmu.Unlock()
  1953. }
  1954. var (
  1955. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  1956. errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
  1957. errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
  1958. )
  1959. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1960. cc.t.logf(format, args...)
  1961. }
  1962. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1963. cc.t.vlogf(format, args...)
  1964. }
  1965. func (t *Transport) vlogf(format string, args ...interface{}) {
  1966. if VerboseLogs {
  1967. t.logf(format, args...)
  1968. }
  1969. }
  1970. func (t *Transport) logf(format string, args ...interface{}) {
  1971. log.Printf(format, args...)
  1972. }
  1973. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1974. func strSliceContains(ss []string, s string) bool {
  1975. for _, v := range ss {
  1976. if v == s {
  1977. return true
  1978. }
  1979. }
  1980. return false
  1981. }
  1982. type erringRoundTripper struct{ err error }
  1983. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1984. // gzipReader wraps a response body so it can lazily
  1985. // call gzip.NewReader on the first call to Read
  1986. type gzipReader struct {
  1987. body io.ReadCloser // underlying Response.Body
  1988. zr *gzip.Reader // lazily-initialized gzip reader
  1989. zerr error // sticky error
  1990. }
  1991. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1992. if gz.zerr != nil {
  1993. return 0, gz.zerr
  1994. }
  1995. if gz.zr == nil {
  1996. gz.zr, err = gzip.NewReader(gz.body)
  1997. if err != nil {
  1998. gz.zerr = err
  1999. return 0, err
  2000. }
  2001. }
  2002. return gz.zr.Read(p)
  2003. }
  2004. func (gz *gzipReader) Close() error {
  2005. return gz.body.Close()
  2006. }
  2007. type errorReader struct{ err error }
  2008. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  2009. // bodyWriterState encapsulates various state around the Transport's writing
  2010. // of the request body, particularly regarding doing delayed writes of the body
  2011. // when the request contains "Expect: 100-continue".
  2012. type bodyWriterState struct {
  2013. cs *clientStream
  2014. timer *time.Timer // if non-nil, we're doing a delayed write
  2015. fnonce *sync.Once // to call fn with
  2016. fn func() // the code to run in the goroutine, writing the body
  2017. resc chan error // result of fn's execution
  2018. delay time.Duration // how long we should delay a delayed write for
  2019. }
  2020. func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
  2021. s.cs = cs
  2022. if body == nil {
  2023. return
  2024. }
  2025. resc := make(chan error, 1)
  2026. s.resc = resc
  2027. s.fn = func() {
  2028. cs.cc.mu.Lock()
  2029. cs.startedWrite = true
  2030. cs.cc.mu.Unlock()
  2031. resc <- cs.writeRequestBody(body, cs.req.Body)
  2032. }
  2033. s.delay = t.expectContinueTimeout()
  2034. if s.delay == 0 ||
  2035. !httplex.HeaderValuesContainsToken(
  2036. cs.req.Header["Expect"],
  2037. "100-continue") {
  2038. return
  2039. }
  2040. s.fnonce = new(sync.Once)
  2041. // Arm the timer with a very large duration, which we'll
  2042. // intentionally lower later. It has to be large now because
  2043. // we need a handle to it before writing the headers, but the
  2044. // s.delay value is defined to not start until after the
  2045. // request headers were written.
  2046. const hugeDuration = 365 * 24 * time.Hour
  2047. s.timer = time.AfterFunc(hugeDuration, func() {
  2048. s.fnonce.Do(s.fn)
  2049. })
  2050. return
  2051. }
  2052. func (s bodyWriterState) cancel() {
  2053. if s.timer != nil {
  2054. s.timer.Stop()
  2055. }
  2056. }
  2057. func (s bodyWriterState) on100() {
  2058. if s.timer == nil {
  2059. // If we didn't do a delayed write, ignore the server's
  2060. // bogus 100 continue response.
  2061. return
  2062. }
  2063. s.timer.Stop()
  2064. go func() { s.fnonce.Do(s.fn) }()
  2065. }
  2066. // scheduleBodyWrite starts writing the body, either immediately (in
  2067. // the common case) or after the delay timeout. It should not be
  2068. // called until after the headers have been written.
  2069. func (s bodyWriterState) scheduleBodyWrite() {
  2070. if s.timer == nil {
  2071. // We're not doing a delayed write (see
  2072. // getBodyWriterState), so just start the writing
  2073. // goroutine immediately.
  2074. go s.fn()
  2075. return
  2076. }
  2077. traceWait100Continue(s.cs.trace)
  2078. if s.timer.Stop() {
  2079. s.timer.Reset(s.delay)
  2080. }
  2081. }
  2082. // isConnectionCloseRequest reports whether req should use its own
  2083. // connection for a single request and then close the connection.
  2084. func isConnectionCloseRequest(req *http.Request) bool {
  2085. return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close")
  2086. }