transport.go 67 KB

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