transport.go 71 KB

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