transport.go 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203
  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/fs"
  17. "log"
  18. "math"
  19. "math/bits"
  20. mathrand "math/rand"
  21. "net"
  22. "net/http"
  23. "net/http/httptrace"
  24. "net/textproto"
  25. "os"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "golang.org/x/net/http/httpguts"
  33. "golang.org/x/net/http2/hpack"
  34. "golang.org/x/net/idna"
  35. )
  36. const (
  37. // transportDefaultConnFlow is how many connection-level flow control
  38. // tokens we give the server at start-up, past the default 64k.
  39. transportDefaultConnFlow = 1 << 30
  40. // transportDefaultStreamFlow is how many stream-level flow
  41. // control tokens we announce to the peer, and how many bytes
  42. // we buffer per stream.
  43. transportDefaultStreamFlow = 4 << 20
  44. defaultUserAgent = "Go-http-client/2.0"
  45. // initialMaxConcurrentStreams is a connections maxConcurrentStreams until
  46. // it's received servers initial SETTINGS frame, which corresponds with the
  47. // spec's minimum recommended value.
  48. initialMaxConcurrentStreams = 100
  49. // defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
  50. // if the server doesn't include one in its initial SETTINGS frame.
  51. defaultMaxConcurrentStreams = 1000
  52. )
  53. // Transport is an HTTP/2 Transport.
  54. //
  55. // A Transport internally caches connections to servers. It is safe
  56. // for concurrent use by multiple goroutines.
  57. type Transport struct {
  58. // DialTLSContext specifies an optional dial function with context for
  59. // creating TLS connections for requests.
  60. //
  61. // If DialTLSContext and DialTLS is nil, tls.Dial is used.
  62. //
  63. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  64. // it will be used to set http.Response.TLS.
  65. DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
  66. // DialTLS specifies an optional dial function for creating
  67. // TLS connections for requests.
  68. //
  69. // If DialTLSContext and DialTLS is nil, tls.Dial is used.
  70. //
  71. // Deprecated: Use DialTLSContext instead, which allows the transport
  72. // to cancel dials as soon as they are no longer needed.
  73. // If both are set, DialTLSContext takes priority.
  74. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  75. // TLSClientConfig specifies the TLS configuration to use with
  76. // tls.Client. If nil, the default configuration is used.
  77. TLSClientConfig *tls.Config
  78. // ConnPool optionally specifies an alternate connection pool to use.
  79. // If nil, the default is used.
  80. ConnPool ClientConnPool
  81. // DisableCompression, if true, prevents the Transport from
  82. // requesting compression with an "Accept-Encoding: gzip"
  83. // request header when the Request contains no existing
  84. // Accept-Encoding value. If the Transport requests gzip on
  85. // its own and gets a gzipped response, it's transparently
  86. // decoded in the Response.Body. However, if the user
  87. // explicitly requested gzip it is not automatically
  88. // uncompressed.
  89. DisableCompression bool
  90. // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
  91. // plain-text "http" scheme. Note that this does not enable h2c support.
  92. AllowHTTP bool
  93. // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
  94. // send in the initial settings frame. It is how many bytes
  95. // of response headers are allowed. Unlike the http2 spec, zero here
  96. // means to use a default limit (currently 10MB). If you actually
  97. // want to advertise an unlimited value to the peer, Transport
  98. // interprets the highest possible value here (0xffffffff or 1<<32-1)
  99. // to mean no limit.
  100. MaxHeaderListSize uint32
  101. // MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
  102. // initial settings frame. It is the size in bytes of the largest frame
  103. // payload that the sender is willing to receive. If 0, no setting is
  104. // sent, and the value is provided by the peer, which should be 16384
  105. // according to the spec:
  106. // https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
  107. // Values are bounded in the range 16k to 16M.
  108. MaxReadFrameSize uint32
  109. // MaxDecoderHeaderTableSize optionally specifies the http2
  110. // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
  111. // informs the remote endpoint of the maximum size of the header compression
  112. // table used to decode header blocks, in octets. If zero, the default value
  113. // of 4096 is used.
  114. MaxDecoderHeaderTableSize uint32
  115. // MaxEncoderHeaderTableSize optionally specifies an upper limit for the
  116. // header compression table used for encoding request headers. Received
  117. // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
  118. // the default value of 4096 is used.
  119. MaxEncoderHeaderTableSize uint32
  120. // StrictMaxConcurrentStreams controls whether the server's
  121. // SETTINGS_MAX_CONCURRENT_STREAMS should be respected
  122. // globally. If false, new TCP connections are created to the
  123. // server as needed to keep each under the per-connection
  124. // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
  125. // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
  126. // a global limit and callers of RoundTrip block when needed,
  127. // waiting for their turn.
  128. StrictMaxConcurrentStreams bool
  129. // ReadIdleTimeout is the timeout after which a health check using ping
  130. // frame will be carried out if no frame is received on the connection.
  131. // Note that a ping response will is considered a received frame, so if
  132. // there is no other traffic on the connection, the health check will
  133. // be performed every ReadIdleTimeout interval.
  134. // If zero, no health check is performed.
  135. ReadIdleTimeout time.Duration
  136. // PingTimeout is the timeout after which the connection will be closed
  137. // if a response to Ping is not received.
  138. // Defaults to 15s.
  139. PingTimeout time.Duration
  140. // WriteByteTimeout is the timeout after which the connection will be
  141. // closed no data can be written to it. The timeout begins when data is
  142. // available to write, and is extended whenever any bytes are written.
  143. WriteByteTimeout time.Duration
  144. // CountError, if non-nil, is called on HTTP/2 transport errors.
  145. // It's intended to increment a metric for monitoring, such
  146. // as an expvar or Prometheus metric.
  147. // The errType consists of only ASCII word characters.
  148. CountError func(errType string)
  149. // t1, if non-nil, is the standard library Transport using
  150. // this transport. Its settings are used (but not its
  151. // RoundTrip method, etc).
  152. t1 *http.Transport
  153. connPoolOnce sync.Once
  154. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  155. }
  156. func (t *Transport) maxHeaderListSize() uint32 {
  157. if t.MaxHeaderListSize == 0 {
  158. return 10 << 20
  159. }
  160. if t.MaxHeaderListSize == 0xffffffff {
  161. return 0
  162. }
  163. return t.MaxHeaderListSize
  164. }
  165. func (t *Transport) maxFrameReadSize() uint32 {
  166. if t.MaxReadFrameSize == 0 {
  167. return 0 // use the default provided by the peer
  168. }
  169. if t.MaxReadFrameSize < minMaxFrameSize {
  170. return minMaxFrameSize
  171. }
  172. if t.MaxReadFrameSize > maxFrameSize {
  173. return maxFrameSize
  174. }
  175. return t.MaxReadFrameSize
  176. }
  177. func (t *Transport) disableCompression() bool {
  178. return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
  179. }
  180. func (t *Transport) pingTimeout() time.Duration {
  181. if t.PingTimeout == 0 {
  182. return 15 * time.Second
  183. }
  184. return t.PingTimeout
  185. }
  186. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  187. // It returns an error if t1 has already been HTTP/2-enabled.
  188. //
  189. // Use ConfigureTransports instead to configure the HTTP/2 Transport.
  190. func ConfigureTransport(t1 *http.Transport) error {
  191. _, err := ConfigureTransports(t1)
  192. return err
  193. }
  194. // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
  195. // It returns a new HTTP/2 Transport for further configuration.
  196. // It returns an error if t1 has already been HTTP/2-enabled.
  197. func ConfigureTransports(t1 *http.Transport) (*Transport, error) {
  198. return configureTransports(t1)
  199. }
  200. func configureTransports(t1 *http.Transport) (*Transport, error) {
  201. connPool := new(clientConnPool)
  202. t2 := &Transport{
  203. ConnPool: noDialClientConnPool{connPool},
  204. t1: t1,
  205. }
  206. connPool.t = t2
  207. if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
  208. return nil, err
  209. }
  210. if t1.TLSClientConfig == nil {
  211. t1.TLSClientConfig = new(tls.Config)
  212. }
  213. if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
  214. t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
  215. }
  216. if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
  217. t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
  218. }
  219. upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
  220. addr := authorityAddr("https", authority)
  221. if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
  222. go c.Close()
  223. return erringRoundTripper{err}
  224. } else if !used {
  225. // Turns out we don't need this c.
  226. // For example, two goroutines made requests to the same host
  227. // at the same time, both kicking off TCP dials. (since protocol
  228. // was unknown)
  229. go c.Close()
  230. }
  231. return t2
  232. }
  233. if m := t1.TLSNextProto; len(m) == 0 {
  234. t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
  235. "h2": upgradeFn,
  236. }
  237. } else {
  238. m["h2"] = upgradeFn
  239. }
  240. return t2, nil
  241. }
  242. func (t *Transport) connPool() ClientConnPool {
  243. t.connPoolOnce.Do(t.initConnPool)
  244. return t.connPoolOrDef
  245. }
  246. func (t *Transport) initConnPool() {
  247. if t.ConnPool != nil {
  248. t.connPoolOrDef = t.ConnPool
  249. } else {
  250. t.connPoolOrDef = &clientConnPool{t: t}
  251. }
  252. }
  253. // ClientConn is the state of a single HTTP/2 client connection to an
  254. // HTTP/2 server.
  255. type ClientConn struct {
  256. t *Transport
  257. tconn net.Conn // usually *tls.Conn, except specialized impls
  258. tlsState *tls.ConnectionState // nil only for specialized impls
  259. reused uint32 // whether conn is being reused; atomic
  260. singleUse bool // whether being used for a single http.Request
  261. getConnCalled bool // used by clientConnPool
  262. // readLoop goroutine fields:
  263. readerDone chan struct{} // closed on error
  264. readerErr error // set before readerDone is closed
  265. idleTimeout time.Duration // or 0 for never
  266. idleTimer *time.Timer
  267. mu sync.Mutex // guards following
  268. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  269. flow outflow // our conn-level flow control quota (cs.outflow is per stream)
  270. inflow inflow // peer's conn-level flow control
  271. doNotReuse bool // whether conn is marked to not be reused for any future requests
  272. closing bool
  273. closed bool
  274. seenSettings bool // true if we've seen a settings frame, false otherwise
  275. wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
  276. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  277. goAwayDebug string // goAway frame's debug data, retained as a string
  278. streams map[uint32]*clientStream // client-initiated
  279. streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip
  280. nextStreamID uint32
  281. pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
  282. pings map[[8]byte]chan struct{} // in flight ping data to notification channel
  283. br *bufio.Reader
  284. lastActive time.Time
  285. lastIdle time.Time // time last idle
  286. // Settings from peer: (also guarded by wmu)
  287. maxFrameSize uint32
  288. maxConcurrentStreams uint32
  289. peerMaxHeaderListSize uint64
  290. peerMaxHeaderTableSize uint32
  291. initialWindowSize uint32
  292. // reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
  293. // Write to reqHeaderMu to lock it, read from it to unlock.
  294. // Lock reqmu BEFORE mu or wmu.
  295. reqHeaderMu chan struct{}
  296. // wmu is held while writing.
  297. // Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
  298. // Only acquire both at the same time when changing peer settings.
  299. wmu sync.Mutex
  300. bw *bufio.Writer
  301. fr *Framer
  302. werr error // first write error that has occurred
  303. hbuf bytes.Buffer // HPACK encoder writes into this
  304. henc *hpack.Encoder
  305. }
  306. // clientStream is the state for a single HTTP/2 stream. One of these
  307. // is created for each Transport.RoundTrip call.
  308. type clientStream struct {
  309. cc *ClientConn
  310. // Fields of Request that we may access even after the response body is closed.
  311. ctx context.Context
  312. reqCancel <-chan struct{}
  313. trace *httptrace.ClientTrace // or nil
  314. ID uint32
  315. bufPipe pipe // buffered pipe with the flow-controlled response payload
  316. requestedGzip bool
  317. isHead bool
  318. abortOnce sync.Once
  319. abort chan struct{} // closed to signal stream should end immediately
  320. abortErr error // set if abort is closed
  321. peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
  322. donec chan struct{} // closed after the stream is in the closed state
  323. on100 chan struct{} // buffered; written to if a 100 is received
  324. respHeaderRecv chan struct{} // closed when headers are received
  325. res *http.Response // set if respHeaderRecv is closed
  326. flow outflow // guarded by cc.mu
  327. inflow inflow // guarded by cc.mu
  328. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  329. readErr error // sticky read error; owned by transportResponseBody.Read
  330. reqBody io.ReadCloser
  331. reqBodyContentLength int64 // -1 means unknown
  332. reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done
  333. // owned by writeRequest:
  334. sentEndStream bool // sent an END_STREAM flag to the peer
  335. sentHeaders bool
  336. // owned by clientConnReadLoop:
  337. firstByte bool // got the first response byte
  338. pastHeaders bool // got first MetaHeadersFrame (actual headers)
  339. pastTrailers bool // got optional second MetaHeadersFrame (trailers)
  340. num1xx uint8 // number of 1xx responses seen
  341. readClosed bool // peer sent an END_STREAM flag
  342. readAborted bool // read loop reset the stream
  343. trailer http.Header // accumulated trailers
  344. resTrailer *http.Header // client's Response.Trailer
  345. }
  346. var got1xxFuncForTests func(int, textproto.MIMEHeader) error
  347. // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
  348. // if any. It returns nil if not set or if the Go version is too old.
  349. func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
  350. if fn := got1xxFuncForTests; fn != nil {
  351. return fn
  352. }
  353. return traceGot1xxResponseFunc(cs.trace)
  354. }
  355. func (cs *clientStream) abortStream(err error) {
  356. cs.cc.mu.Lock()
  357. defer cs.cc.mu.Unlock()
  358. cs.abortStreamLocked(err)
  359. }
  360. func (cs *clientStream) abortStreamLocked(err error) {
  361. cs.abortOnce.Do(func() {
  362. cs.abortErr = err
  363. close(cs.abort)
  364. })
  365. if cs.reqBody != nil {
  366. cs.closeReqBodyLocked()
  367. }
  368. // TODO(dneil): Clean up tests where cs.cc.cond is nil.
  369. if cs.cc.cond != nil {
  370. // Wake up writeRequestBody if it is waiting on flow control.
  371. cs.cc.cond.Broadcast()
  372. }
  373. }
  374. func (cs *clientStream) abortRequestBodyWrite() {
  375. cc := cs.cc
  376. cc.mu.Lock()
  377. defer cc.mu.Unlock()
  378. if cs.reqBody != nil && cs.reqBodyClosed == nil {
  379. cs.closeReqBodyLocked()
  380. cc.cond.Broadcast()
  381. }
  382. }
  383. func (cs *clientStream) closeReqBodyLocked() {
  384. if cs.reqBodyClosed != nil {
  385. return
  386. }
  387. cs.reqBodyClosed = make(chan struct{})
  388. reqBodyClosed := cs.reqBodyClosed
  389. go func() {
  390. cs.reqBody.Close()
  391. close(reqBodyClosed)
  392. }()
  393. }
  394. type stickyErrWriter struct {
  395. conn net.Conn
  396. timeout time.Duration
  397. err *error
  398. }
  399. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  400. if *sew.err != nil {
  401. return 0, *sew.err
  402. }
  403. for {
  404. if sew.timeout != 0 {
  405. sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
  406. }
  407. nn, err := sew.conn.Write(p[n:])
  408. n += nn
  409. if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
  410. // Keep extending the deadline so long as we're making progress.
  411. continue
  412. }
  413. if sew.timeout != 0 {
  414. sew.conn.SetWriteDeadline(time.Time{})
  415. }
  416. *sew.err = err
  417. return n, err
  418. }
  419. }
  420. // noCachedConnError is the concrete type of ErrNoCachedConn, which
  421. // needs to be detected by net/http regardless of whether it's its
  422. // bundled version (in h2_bundle.go with a rewritten type name) or
  423. // from a user's x/net/http2. As such, as it has a unique method name
  424. // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
  425. // isNoCachedConnError.
  426. type noCachedConnError struct{}
  427. func (noCachedConnError) IsHTTP2NoCachedConnError() {}
  428. func (noCachedConnError) Error() string { return "http2: no cached connection was available" }
  429. // isNoCachedConnError reports whether err is of type noCachedConnError
  430. // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
  431. // may coexist in the same running program.
  432. func isNoCachedConnError(err error) bool {
  433. _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
  434. return ok
  435. }
  436. var ErrNoCachedConn error = noCachedConnError{}
  437. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  438. type RoundTripOpt struct {
  439. // OnlyCachedConn controls whether RoundTripOpt may
  440. // create a new TCP connection. If set true and
  441. // no cached connection is available, RoundTripOpt
  442. // will return ErrNoCachedConn.
  443. OnlyCachedConn bool
  444. }
  445. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  446. return t.RoundTripOpt(req, RoundTripOpt{})
  447. }
  448. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  449. // and returns a host:port. The port 443 is added if needed.
  450. func authorityAddr(scheme string, authority string) (addr string) {
  451. host, port, err := net.SplitHostPort(authority)
  452. if err != nil { // authority didn't have a port
  453. host = authority
  454. port = ""
  455. }
  456. if port == "" { // authority's port was empty
  457. port = "443"
  458. if scheme == "http" {
  459. port = "80"
  460. }
  461. }
  462. if a, err := idna.ToASCII(host); err == nil {
  463. host = a
  464. }
  465. // IPv6 address literal, without a port:
  466. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  467. return host + ":" + port
  468. }
  469. return net.JoinHostPort(host, port)
  470. }
  471. var retryBackoffHook func(time.Duration) *time.Timer
  472. func backoffNewTimer(d time.Duration) *time.Timer {
  473. if retryBackoffHook != nil {
  474. return retryBackoffHook(d)
  475. }
  476. return time.NewTimer(d)
  477. }
  478. // RoundTripOpt is like RoundTrip, but takes options.
  479. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  480. if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
  481. return nil, errors.New("http2: unsupported scheme")
  482. }
  483. addr := authorityAddr(req.URL.Scheme, req.URL.Host)
  484. for retry := 0; ; retry++ {
  485. cc, err := t.connPool().GetClientConn(req, addr)
  486. if err != nil {
  487. t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
  488. return nil, err
  489. }
  490. reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
  491. traceGotConn(req, cc, reused)
  492. res, err := cc.RoundTrip(req)
  493. if err != nil && retry <= 6 {
  494. roundTripErr := err
  495. if req, err = shouldRetryRequest(req, err); err == nil {
  496. // After the first retry, do exponential backoff with 10% jitter.
  497. if retry == 0 {
  498. t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  499. continue
  500. }
  501. backoff := float64(uint(1) << (uint(retry) - 1))
  502. backoff += backoff * (0.1 * mathrand.Float64())
  503. d := time.Second * time.Duration(backoff)
  504. timer := backoffNewTimer(d)
  505. select {
  506. case <-timer.C:
  507. t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  508. continue
  509. case <-req.Context().Done():
  510. timer.Stop()
  511. err = req.Context().Err()
  512. }
  513. }
  514. }
  515. if err != nil {
  516. t.vlogf("RoundTrip failure: %v", err)
  517. return nil, err
  518. }
  519. return res, nil
  520. }
  521. }
  522. // CloseIdleConnections closes any connections which were previously
  523. // connected from previous requests but are now sitting idle.
  524. // It does not interrupt any connections currently in use.
  525. func (t *Transport) CloseIdleConnections() {
  526. if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
  527. cp.closeIdleConnections()
  528. }
  529. }
  530. var (
  531. errClientConnClosed = errors.New("http2: client conn is closed")
  532. errClientConnUnusable = errors.New("http2: client conn not usable")
  533. errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
  534. )
  535. // shouldRetryRequest is called by RoundTrip when a request fails to get
  536. // response headers. It is always called with a non-nil error.
  537. // It returns either a request to retry (either the same request, or a
  538. // modified clone), or an error if the request can't be replayed.
  539. func shouldRetryRequest(req *http.Request, err error) (*http.Request, error) {
  540. if !canRetryError(err) {
  541. return nil, err
  542. }
  543. // If the Body is nil (or http.NoBody), it's safe to reuse
  544. // this request and its Body.
  545. if req.Body == nil || req.Body == http.NoBody {
  546. return req, nil
  547. }
  548. // If the request body can be reset back to its original
  549. // state via the optional req.GetBody, do that.
  550. if req.GetBody != nil {
  551. body, err := req.GetBody()
  552. if err != nil {
  553. return nil, err
  554. }
  555. newReq := *req
  556. newReq.Body = body
  557. return &newReq, nil
  558. }
  559. // The Request.Body can't reset back to the beginning, but we
  560. // don't seem to have started to read from it yet, so reuse
  561. // the request directly.
  562. if err == errClientConnUnusable {
  563. return req, nil
  564. }
  565. return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
  566. }
  567. func canRetryError(err error) bool {
  568. if err == errClientConnUnusable || err == errClientConnGotGoAway {
  569. return true
  570. }
  571. if se, ok := err.(StreamError); ok {
  572. if se.Code == ErrCodeProtocol && se.Cause == errFromPeer {
  573. // See golang/go#47635, golang/go#42777
  574. return true
  575. }
  576. return se.Code == ErrCodeRefusedStream
  577. }
  578. return false
  579. }
  580. func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) {
  581. host, _, err := net.SplitHostPort(addr)
  582. if err != nil {
  583. return nil, err
  584. }
  585. tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
  586. if err != nil {
  587. return nil, err
  588. }
  589. return t.newClientConn(tconn, singleUse)
  590. }
  591. func (t *Transport) newTLSConfig(host string) *tls.Config {
  592. cfg := new(tls.Config)
  593. if t.TLSClientConfig != nil {
  594. *cfg = *t.TLSClientConfig.Clone()
  595. }
  596. if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
  597. cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
  598. }
  599. if cfg.ServerName == "" {
  600. cfg.ServerName = host
  601. }
  602. return cfg
  603. }
  604. func (t *Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
  605. if t.DialTLSContext != nil {
  606. return t.DialTLSContext(ctx, network, addr, tlsCfg)
  607. } else if t.DialTLS != nil {
  608. return t.DialTLS(network, addr, tlsCfg)
  609. }
  610. tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
  611. if err != nil {
  612. return nil, err
  613. }
  614. state := tlsCn.ConnectionState()
  615. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  616. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  617. }
  618. if !state.NegotiatedProtocolIsMutual {
  619. return nil, errors.New("http2: could not negotiate protocol mutually")
  620. }
  621. return tlsCn, nil
  622. }
  623. // disableKeepAlives reports whether connections should be closed as
  624. // soon as possible after handling the first request.
  625. func (t *Transport) disableKeepAlives() bool {
  626. return t.t1 != nil && t.t1.DisableKeepAlives
  627. }
  628. func (t *Transport) expectContinueTimeout() time.Duration {
  629. if t.t1 == nil {
  630. return 0
  631. }
  632. return t.t1.ExpectContinueTimeout
  633. }
  634. func (t *Transport) maxDecoderHeaderTableSize() uint32 {
  635. if v := t.MaxDecoderHeaderTableSize; v > 0 {
  636. return v
  637. }
  638. return initialHeaderTableSize
  639. }
  640. func (t *Transport) maxEncoderHeaderTableSize() uint32 {
  641. if v := t.MaxEncoderHeaderTableSize; v > 0 {
  642. return v
  643. }
  644. return initialHeaderTableSize
  645. }
  646. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  647. return t.newClientConn(c, t.disableKeepAlives())
  648. }
  649. func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
  650. cc := &ClientConn{
  651. t: t,
  652. tconn: c,
  653. readerDone: make(chan struct{}),
  654. nextStreamID: 1,
  655. maxFrameSize: 16 << 10, // spec default
  656. initialWindowSize: 65535, // spec default
  657. maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
  658. peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
  659. streams: make(map[uint32]*clientStream),
  660. singleUse: singleUse,
  661. wantSettingsAck: true,
  662. pings: make(map[[8]byte]chan struct{}),
  663. reqHeaderMu: make(chan struct{}, 1),
  664. }
  665. if d := t.idleConnTimeout(); d != 0 {
  666. cc.idleTimeout = d
  667. cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
  668. }
  669. if VerboseLogs {
  670. t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
  671. }
  672. cc.cond = sync.NewCond(&cc.mu)
  673. cc.flow.add(int32(initialWindowSize))
  674. // TODO: adjust this writer size to account for frame size +
  675. // MTU + crypto/tls record padding.
  676. cc.bw = bufio.NewWriter(stickyErrWriter{
  677. conn: c,
  678. timeout: t.WriteByteTimeout,
  679. err: &cc.werr,
  680. })
  681. cc.br = bufio.NewReader(c)
  682. cc.fr = NewFramer(cc.bw, cc.br)
  683. if t.maxFrameReadSize() != 0 {
  684. cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
  685. }
  686. if t.CountError != nil {
  687. cc.fr.countError = t.CountError
  688. }
  689. maxHeaderTableSize := t.maxDecoderHeaderTableSize()
  690. cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
  691. cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
  692. cc.henc = hpack.NewEncoder(&cc.hbuf)
  693. cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
  694. cc.peerMaxHeaderTableSize = initialHeaderTableSize
  695. if t.AllowHTTP {
  696. cc.nextStreamID = 3
  697. }
  698. if cs, ok := c.(connectionStater); ok {
  699. state := cs.ConnectionState()
  700. cc.tlsState = &state
  701. }
  702. initialSettings := []Setting{
  703. {ID: SettingEnablePush, Val: 0},
  704. {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  705. }
  706. if max := t.maxFrameReadSize(); max != 0 {
  707. initialSettings = append(initialSettings, Setting{ID: SettingMaxFrameSize, Val: max})
  708. }
  709. if max := t.maxHeaderListSize(); max != 0 {
  710. initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
  711. }
  712. if maxHeaderTableSize != initialHeaderTableSize {
  713. initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: maxHeaderTableSize})
  714. }
  715. cc.bw.Write(clientPreface)
  716. cc.fr.WriteSettings(initialSettings...)
  717. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  718. cc.inflow.init(transportDefaultConnFlow + initialWindowSize)
  719. cc.bw.Flush()
  720. if cc.werr != nil {
  721. cc.Close()
  722. return nil, cc.werr
  723. }
  724. go cc.readLoop()
  725. return cc, nil
  726. }
  727. func (cc *ClientConn) healthCheck() {
  728. pingTimeout := cc.t.pingTimeout()
  729. // We don't need to periodically ping in the health check, because the readLoop of ClientConn will
  730. // trigger the healthCheck again if there is no frame received.
  731. ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
  732. defer cancel()
  733. cc.vlogf("http2: Transport sending health check")
  734. err := cc.Ping(ctx)
  735. if err != nil {
  736. cc.vlogf("http2: Transport health check failure: %v", err)
  737. cc.closeForLostPing()
  738. } else {
  739. cc.vlogf("http2: Transport health check success")
  740. }
  741. }
  742. // SetDoNotReuse marks cc as not reusable for future HTTP requests.
  743. func (cc *ClientConn) SetDoNotReuse() {
  744. cc.mu.Lock()
  745. defer cc.mu.Unlock()
  746. cc.doNotReuse = true
  747. }
  748. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  749. cc.mu.Lock()
  750. defer cc.mu.Unlock()
  751. old := cc.goAway
  752. cc.goAway = f
  753. // Merge the previous and current GoAway error frames.
  754. if cc.goAwayDebug == "" {
  755. cc.goAwayDebug = string(f.DebugData())
  756. }
  757. if old != nil && old.ErrCode != ErrCodeNo {
  758. cc.goAway.ErrCode = old.ErrCode
  759. }
  760. last := f.LastStreamID
  761. for streamID, cs := range cc.streams {
  762. if streamID > last {
  763. cs.abortStreamLocked(errClientConnGotGoAway)
  764. }
  765. }
  766. }
  767. // CanTakeNewRequest reports whether the connection can take a new request,
  768. // meaning it has not been closed or received or sent a GOAWAY.
  769. //
  770. // If the caller is going to immediately make a new request on this
  771. // connection, use ReserveNewRequest instead.
  772. func (cc *ClientConn) CanTakeNewRequest() bool {
  773. cc.mu.Lock()
  774. defer cc.mu.Unlock()
  775. return cc.canTakeNewRequestLocked()
  776. }
  777. // ReserveNewRequest is like CanTakeNewRequest but also reserves a
  778. // concurrent stream in cc. The reservation is decremented on the
  779. // next call to RoundTrip.
  780. func (cc *ClientConn) ReserveNewRequest() bool {
  781. cc.mu.Lock()
  782. defer cc.mu.Unlock()
  783. if st := cc.idleStateLocked(); !st.canTakeNewRequest {
  784. return false
  785. }
  786. cc.streamsReserved++
  787. return true
  788. }
  789. // ClientConnState describes the state of a ClientConn.
  790. type ClientConnState struct {
  791. // Closed is whether the connection is closed.
  792. Closed bool
  793. // Closing is whether the connection is in the process of
  794. // closing. It may be closing due to shutdown, being a
  795. // single-use connection, being marked as DoNotReuse, or
  796. // having received a GOAWAY frame.
  797. Closing bool
  798. // StreamsActive is how many streams are active.
  799. StreamsActive int
  800. // StreamsReserved is how many streams have been reserved via
  801. // ClientConn.ReserveNewRequest.
  802. StreamsReserved int
  803. // StreamsPending is how many requests have been sent in excess
  804. // of the peer's advertised MaxConcurrentStreams setting and
  805. // are waiting for other streams to complete.
  806. StreamsPending int
  807. // MaxConcurrentStreams is how many concurrent streams the
  808. // peer advertised as acceptable. Zero means no SETTINGS
  809. // frame has been received yet.
  810. MaxConcurrentStreams uint32
  811. // LastIdle, if non-zero, is when the connection last
  812. // transitioned to idle state.
  813. LastIdle time.Time
  814. }
  815. // State returns a snapshot of cc's state.
  816. func (cc *ClientConn) State() ClientConnState {
  817. cc.wmu.Lock()
  818. maxConcurrent := cc.maxConcurrentStreams
  819. if !cc.seenSettings {
  820. maxConcurrent = 0
  821. }
  822. cc.wmu.Unlock()
  823. cc.mu.Lock()
  824. defer cc.mu.Unlock()
  825. return ClientConnState{
  826. Closed: cc.closed,
  827. Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
  828. StreamsActive: len(cc.streams),
  829. StreamsReserved: cc.streamsReserved,
  830. StreamsPending: cc.pendingRequests,
  831. LastIdle: cc.lastIdle,
  832. MaxConcurrentStreams: maxConcurrent,
  833. }
  834. }
  835. // clientConnIdleState describes the suitability of a client
  836. // connection to initiate a new RoundTrip request.
  837. type clientConnIdleState struct {
  838. canTakeNewRequest bool
  839. }
  840. func (cc *ClientConn) idleState() clientConnIdleState {
  841. cc.mu.Lock()
  842. defer cc.mu.Unlock()
  843. return cc.idleStateLocked()
  844. }
  845. func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
  846. if cc.singleUse && cc.nextStreamID > 1 {
  847. return
  848. }
  849. var maxConcurrentOkay bool
  850. if cc.t.StrictMaxConcurrentStreams {
  851. // We'll tell the caller we can take a new request to
  852. // prevent the caller from dialing a new TCP
  853. // connection, but then we'll block later before
  854. // writing it.
  855. maxConcurrentOkay = true
  856. } else {
  857. maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
  858. }
  859. st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
  860. !cc.doNotReuse &&
  861. int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
  862. !cc.tooIdleLocked()
  863. return
  864. }
  865. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  866. st := cc.idleStateLocked()
  867. return st.canTakeNewRequest
  868. }
  869. // tooIdleLocked reports whether this connection has been been sitting idle
  870. // for too much wall time.
  871. func (cc *ClientConn) tooIdleLocked() bool {
  872. // The Round(0) strips the monontonic clock reading so the
  873. // times are compared based on their wall time. We don't want
  874. // to reuse a connection that's been sitting idle during
  875. // VM/laptop suspend if monotonic time was also frozen.
  876. return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
  877. }
  878. // onIdleTimeout is called from a time.AfterFunc goroutine. It will
  879. // only be called when we're idle, but because we're coming from a new
  880. // goroutine, there could be a new request coming in at the same time,
  881. // so this simply calls the synchronized closeIfIdle to shut down this
  882. // connection. The timer could just call closeIfIdle, but this is more
  883. // clear.
  884. func (cc *ClientConn) onIdleTimeout() {
  885. cc.closeIfIdle()
  886. }
  887. func (cc *ClientConn) closeConn() {
  888. t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
  889. defer t.Stop()
  890. cc.tconn.Close()
  891. }
  892. // A tls.Conn.Close can hang for a long time if the peer is unresponsive.
  893. // Try to shut it down more aggressively.
  894. func (cc *ClientConn) forceCloseConn() {
  895. tc, ok := cc.tconn.(*tls.Conn)
  896. if !ok {
  897. return
  898. }
  899. if nc := tlsUnderlyingConn(tc); nc != nil {
  900. nc.Close()
  901. }
  902. }
  903. func (cc *ClientConn) closeIfIdle() {
  904. cc.mu.Lock()
  905. if len(cc.streams) > 0 || cc.streamsReserved > 0 {
  906. cc.mu.Unlock()
  907. return
  908. }
  909. cc.closed = true
  910. nextID := cc.nextStreamID
  911. // TODO: do clients send GOAWAY too? maybe? Just Close:
  912. cc.mu.Unlock()
  913. if VerboseLogs {
  914. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
  915. }
  916. cc.closeConn()
  917. }
  918. func (cc *ClientConn) isDoNotReuseAndIdle() bool {
  919. cc.mu.Lock()
  920. defer cc.mu.Unlock()
  921. return cc.doNotReuse && len(cc.streams) == 0
  922. }
  923. var shutdownEnterWaitStateHook = func() {}
  924. // Shutdown gracefully closes the client connection, waiting for running streams to complete.
  925. func (cc *ClientConn) Shutdown(ctx context.Context) error {
  926. if err := cc.sendGoAway(); err != nil {
  927. return err
  928. }
  929. // Wait for all in-flight streams to complete or connection to close
  930. done := make(chan struct{})
  931. cancelled := false // guarded by cc.mu
  932. go func() {
  933. cc.mu.Lock()
  934. defer cc.mu.Unlock()
  935. for {
  936. if len(cc.streams) == 0 || cc.closed {
  937. cc.closed = true
  938. close(done)
  939. break
  940. }
  941. if cancelled {
  942. break
  943. }
  944. cc.cond.Wait()
  945. }
  946. }()
  947. shutdownEnterWaitStateHook()
  948. select {
  949. case <-done:
  950. cc.closeConn()
  951. return nil
  952. case <-ctx.Done():
  953. cc.mu.Lock()
  954. // Free the goroutine above
  955. cancelled = true
  956. cc.cond.Broadcast()
  957. cc.mu.Unlock()
  958. return ctx.Err()
  959. }
  960. }
  961. func (cc *ClientConn) sendGoAway() error {
  962. cc.mu.Lock()
  963. closing := cc.closing
  964. cc.closing = true
  965. maxStreamID := cc.nextStreamID
  966. cc.mu.Unlock()
  967. if closing {
  968. // GOAWAY sent already
  969. return nil
  970. }
  971. cc.wmu.Lock()
  972. defer cc.wmu.Unlock()
  973. // Send a graceful shutdown frame to server
  974. if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
  975. return err
  976. }
  977. if err := cc.bw.Flush(); err != nil {
  978. return err
  979. }
  980. // Prevent new requests
  981. return nil
  982. }
  983. // closes the client connection immediately. In-flight requests are interrupted.
  984. // err is sent to streams.
  985. func (cc *ClientConn) closeForError(err error) {
  986. cc.mu.Lock()
  987. cc.closed = true
  988. for _, cs := range cc.streams {
  989. cs.abortStreamLocked(err)
  990. }
  991. cc.cond.Broadcast()
  992. cc.mu.Unlock()
  993. cc.closeConn()
  994. }
  995. // Close closes the client connection immediately.
  996. //
  997. // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
  998. func (cc *ClientConn) Close() error {
  999. err := errors.New("http2: client connection force closed via ClientConn.Close")
  1000. cc.closeForError(err)
  1001. return nil
  1002. }
  1003. // closes the client connection immediately. In-flight requests are interrupted.
  1004. func (cc *ClientConn) closeForLostPing() {
  1005. err := errors.New("http2: client connection lost")
  1006. if f := cc.t.CountError; f != nil {
  1007. f("conn_close_lost_ping")
  1008. }
  1009. cc.closeForError(err)
  1010. }
  1011. // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  1012. // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  1013. var errRequestCanceled = errors.New("net/http: request canceled")
  1014. func commaSeparatedTrailers(req *http.Request) (string, error) {
  1015. keys := make([]string, 0, len(req.Trailer))
  1016. for k := range req.Trailer {
  1017. k = canonicalHeader(k)
  1018. switch k {
  1019. case "Transfer-Encoding", "Trailer", "Content-Length":
  1020. return "", fmt.Errorf("invalid Trailer key %q", k)
  1021. }
  1022. keys = append(keys, k)
  1023. }
  1024. if len(keys) > 0 {
  1025. sort.Strings(keys)
  1026. return strings.Join(keys, ","), nil
  1027. }
  1028. return "", nil
  1029. }
  1030. func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  1031. if cc.t.t1 != nil {
  1032. return cc.t.t1.ResponseHeaderTimeout
  1033. }
  1034. // No way to do this (yet?) with just an http2.Transport. Probably
  1035. // no need. Request.Cancel this is the new way. We only need to support
  1036. // this for compatibility with the old http.Transport fields when
  1037. // we're doing transparent http2.
  1038. return 0
  1039. }
  1040. // checkConnHeaders checks whether req has any invalid connection-level headers.
  1041. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  1042. // Certain headers are special-cased as okay but not transmitted later.
  1043. func checkConnHeaders(req *http.Request) error {
  1044. if v := req.Header.Get("Upgrade"); v != "" {
  1045. return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
  1046. }
  1047. if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
  1048. return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
  1049. }
  1050. if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !asciiEqualFold(vv[0], "close") && !asciiEqualFold(vv[0], "keep-alive")) {
  1051. return fmt.Errorf("http2: invalid Connection request header: %q", vv)
  1052. }
  1053. return nil
  1054. }
  1055. // actualContentLength returns a sanitized version of
  1056. // req.ContentLength, where 0 actually means zero (not unknown) and -1
  1057. // means unknown.
  1058. func actualContentLength(req *http.Request) int64 {
  1059. if req.Body == nil || req.Body == http.NoBody {
  1060. return 0
  1061. }
  1062. if req.ContentLength != 0 {
  1063. return req.ContentLength
  1064. }
  1065. return -1
  1066. }
  1067. func (cc *ClientConn) decrStreamReservations() {
  1068. cc.mu.Lock()
  1069. defer cc.mu.Unlock()
  1070. cc.decrStreamReservationsLocked()
  1071. }
  1072. func (cc *ClientConn) decrStreamReservationsLocked() {
  1073. if cc.streamsReserved > 0 {
  1074. cc.streamsReserved--
  1075. }
  1076. }
  1077. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  1078. ctx := req.Context()
  1079. cs := &clientStream{
  1080. cc: cc,
  1081. ctx: ctx,
  1082. reqCancel: req.Cancel,
  1083. isHead: req.Method == "HEAD",
  1084. reqBody: req.Body,
  1085. reqBodyContentLength: actualContentLength(req),
  1086. trace: httptrace.ContextClientTrace(ctx),
  1087. peerClosed: make(chan struct{}),
  1088. abort: make(chan struct{}),
  1089. respHeaderRecv: make(chan struct{}),
  1090. donec: make(chan struct{}),
  1091. }
  1092. go cs.doRequest(req)
  1093. waitDone := func() error {
  1094. select {
  1095. case <-cs.donec:
  1096. return nil
  1097. case <-ctx.Done():
  1098. return ctx.Err()
  1099. case <-cs.reqCancel:
  1100. return errRequestCanceled
  1101. }
  1102. }
  1103. handleResponseHeaders := func() (*http.Response, error) {
  1104. res := cs.res
  1105. if res.StatusCode > 299 {
  1106. // On error or status code 3xx, 4xx, 5xx, etc abort any
  1107. // ongoing write, assuming that the server doesn't care
  1108. // about our request body. If the server replied with 1xx or
  1109. // 2xx, however, then assume the server DOES potentially
  1110. // want our body (e.g. full-duplex streaming:
  1111. // golang.org/issue/13444). If it turns out the server
  1112. // doesn't, they'll RST_STREAM us soon enough. This is a
  1113. // heuristic to avoid adding knobs to Transport. Hopefully
  1114. // we can keep it.
  1115. cs.abortRequestBodyWrite()
  1116. }
  1117. res.Request = req
  1118. res.TLS = cc.tlsState
  1119. if res.Body == noBody && actualContentLength(req) == 0 {
  1120. // If there isn't a request or response body still being
  1121. // written, then wait for the stream to be closed before
  1122. // RoundTrip returns.
  1123. if err := waitDone(); err != nil {
  1124. return nil, err
  1125. }
  1126. }
  1127. return res, nil
  1128. }
  1129. cancelRequest := func(cs *clientStream, err error) error {
  1130. cs.cc.mu.Lock()
  1131. bodyClosed := cs.reqBodyClosed
  1132. cs.cc.mu.Unlock()
  1133. // Wait for the request body to be closed.
  1134. //
  1135. // If nothing closed the body before now, abortStreamLocked
  1136. // will have started a goroutine to close it.
  1137. //
  1138. // Closing the body before returning avoids a race condition
  1139. // with net/http checking its readTrackingBody to see if the
  1140. // body was read from or closed. See golang/go#60041.
  1141. //
  1142. // The body is closed in a separate goroutine without the
  1143. // connection mutex held, but dropping the mutex before waiting
  1144. // will keep us from holding it indefinitely if the body
  1145. // close is slow for some reason.
  1146. if bodyClosed != nil {
  1147. <-bodyClosed
  1148. }
  1149. return err
  1150. }
  1151. for {
  1152. select {
  1153. case <-cs.respHeaderRecv:
  1154. return handleResponseHeaders()
  1155. case <-cs.abort:
  1156. select {
  1157. case <-cs.respHeaderRecv:
  1158. // If both cs.respHeaderRecv and cs.abort are signaling,
  1159. // pick respHeaderRecv. The server probably wrote the
  1160. // response and immediately reset the stream.
  1161. // golang.org/issue/49645
  1162. return handleResponseHeaders()
  1163. default:
  1164. waitDone()
  1165. return nil, cs.abortErr
  1166. }
  1167. case <-ctx.Done():
  1168. err := ctx.Err()
  1169. cs.abortStream(err)
  1170. return nil, cancelRequest(cs, err)
  1171. case <-cs.reqCancel:
  1172. cs.abortStream(errRequestCanceled)
  1173. return nil, cancelRequest(cs, errRequestCanceled)
  1174. }
  1175. }
  1176. }
  1177. // doRequest runs for the duration of the request lifetime.
  1178. //
  1179. // It sends the request and performs post-request cleanup (closing Request.Body, etc.).
  1180. func (cs *clientStream) doRequest(req *http.Request) {
  1181. err := cs.writeRequest(req)
  1182. cs.cleanupWriteRequest(err)
  1183. }
  1184. // writeRequest sends a request.
  1185. //
  1186. // It returns nil after the request is written, the response read,
  1187. // and the request stream is half-closed by the peer.
  1188. //
  1189. // It returns non-nil if the request ends otherwise.
  1190. // If the returned error is StreamError, the error Code may be used in resetting the stream.
  1191. func (cs *clientStream) writeRequest(req *http.Request) (err error) {
  1192. cc := cs.cc
  1193. ctx := cs.ctx
  1194. if err := checkConnHeaders(req); err != nil {
  1195. return err
  1196. }
  1197. // Acquire the new-request lock by writing to reqHeaderMu.
  1198. // This lock guards the critical section covering allocating a new stream ID
  1199. // (requires mu) and creating the stream (requires wmu).
  1200. if cc.reqHeaderMu == nil {
  1201. panic("RoundTrip on uninitialized ClientConn") // for tests
  1202. }
  1203. select {
  1204. case cc.reqHeaderMu <- struct{}{}:
  1205. case <-cs.reqCancel:
  1206. return errRequestCanceled
  1207. case <-ctx.Done():
  1208. return ctx.Err()
  1209. }
  1210. cc.mu.Lock()
  1211. if cc.idleTimer != nil {
  1212. cc.idleTimer.Stop()
  1213. }
  1214. cc.decrStreamReservationsLocked()
  1215. if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
  1216. cc.mu.Unlock()
  1217. <-cc.reqHeaderMu
  1218. return err
  1219. }
  1220. cc.addStreamLocked(cs) // assigns stream ID
  1221. if isConnectionCloseRequest(req) {
  1222. cc.doNotReuse = true
  1223. }
  1224. cc.mu.Unlock()
  1225. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  1226. if !cc.t.disableCompression() &&
  1227. req.Header.Get("Accept-Encoding") == "" &&
  1228. req.Header.Get("Range") == "" &&
  1229. !cs.isHead {
  1230. // Request gzip only, not deflate. Deflate is ambiguous and
  1231. // not as universally supported anyway.
  1232. // See: https://zlib.net/zlib_faq.html#faq39
  1233. //
  1234. // Note that we don't request this for HEAD requests,
  1235. // due to a bug in nginx:
  1236. // http://trac.nginx.org/nginx/ticket/358
  1237. // https://golang.org/issue/5522
  1238. //
  1239. // We don't request gzip if the request is for a range, since
  1240. // auto-decoding a portion of a gzipped document will just fail
  1241. // anyway. See https://golang.org/issue/8923
  1242. cs.requestedGzip = true
  1243. }
  1244. continueTimeout := cc.t.expectContinueTimeout()
  1245. if continueTimeout != 0 {
  1246. if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
  1247. continueTimeout = 0
  1248. } else {
  1249. cs.on100 = make(chan struct{}, 1)
  1250. }
  1251. }
  1252. // Past this point (where we send request headers), it is possible for
  1253. // RoundTrip to return successfully. Since the RoundTrip contract permits
  1254. // the caller to "mutate or reuse" the Request after closing the Response's Body,
  1255. // we must take care when referencing the Request from here on.
  1256. err = cs.encodeAndWriteHeaders(req)
  1257. <-cc.reqHeaderMu
  1258. if err != nil {
  1259. return err
  1260. }
  1261. hasBody := cs.reqBodyContentLength != 0
  1262. if !hasBody {
  1263. cs.sentEndStream = true
  1264. } else {
  1265. if continueTimeout != 0 {
  1266. traceWait100Continue(cs.trace)
  1267. timer := time.NewTimer(continueTimeout)
  1268. select {
  1269. case <-timer.C:
  1270. err = nil
  1271. case <-cs.on100:
  1272. err = nil
  1273. case <-cs.abort:
  1274. err = cs.abortErr
  1275. case <-ctx.Done():
  1276. err = ctx.Err()
  1277. case <-cs.reqCancel:
  1278. err = errRequestCanceled
  1279. }
  1280. timer.Stop()
  1281. if err != nil {
  1282. traceWroteRequest(cs.trace, err)
  1283. return err
  1284. }
  1285. }
  1286. if err = cs.writeRequestBody(req); err != nil {
  1287. if err != errStopReqBodyWrite {
  1288. traceWroteRequest(cs.trace, err)
  1289. return err
  1290. }
  1291. } else {
  1292. cs.sentEndStream = true
  1293. }
  1294. }
  1295. traceWroteRequest(cs.trace, err)
  1296. var respHeaderTimer <-chan time.Time
  1297. var respHeaderRecv chan struct{}
  1298. if d := cc.responseHeaderTimeout(); d != 0 {
  1299. timer := time.NewTimer(d)
  1300. defer timer.Stop()
  1301. respHeaderTimer = timer.C
  1302. respHeaderRecv = cs.respHeaderRecv
  1303. }
  1304. // Wait until the peer half-closes its end of the stream,
  1305. // or until the request is aborted (via context, error, or otherwise),
  1306. // whichever comes first.
  1307. for {
  1308. select {
  1309. case <-cs.peerClosed:
  1310. return nil
  1311. case <-respHeaderTimer:
  1312. return errTimeout
  1313. case <-respHeaderRecv:
  1314. respHeaderRecv = nil
  1315. respHeaderTimer = nil // keep waiting for END_STREAM
  1316. case <-cs.abort:
  1317. return cs.abortErr
  1318. case <-ctx.Done():
  1319. return ctx.Err()
  1320. case <-cs.reqCancel:
  1321. return errRequestCanceled
  1322. }
  1323. }
  1324. }
  1325. func (cs *clientStream) encodeAndWriteHeaders(req *http.Request) error {
  1326. cc := cs.cc
  1327. ctx := cs.ctx
  1328. cc.wmu.Lock()
  1329. defer cc.wmu.Unlock()
  1330. // If the request was canceled while waiting for cc.mu, just quit.
  1331. select {
  1332. case <-cs.abort:
  1333. return cs.abortErr
  1334. case <-ctx.Done():
  1335. return ctx.Err()
  1336. case <-cs.reqCancel:
  1337. return errRequestCanceled
  1338. default:
  1339. }
  1340. // Encode headers.
  1341. //
  1342. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  1343. // sent by writeRequestBody below, along with any Trailers,
  1344. // again in form HEADERS{1}, CONTINUATION{0,})
  1345. trailers, err := commaSeparatedTrailers(req)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. hasTrailers := trailers != ""
  1350. contentLen := actualContentLength(req)
  1351. hasBody := contentLen != 0
  1352. hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
  1353. if err != nil {
  1354. return err
  1355. }
  1356. // Write the request.
  1357. endStream := !hasBody && !hasTrailers
  1358. cs.sentHeaders = true
  1359. err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  1360. traceWroteHeaders(cs.trace)
  1361. return err
  1362. }
  1363. // cleanupWriteRequest performs post-request tasks.
  1364. //
  1365. // If err (the result of writeRequest) is non-nil and the stream is not closed,
  1366. // cleanupWriteRequest will send a reset to the peer.
  1367. func (cs *clientStream) cleanupWriteRequest(err error) {
  1368. cc := cs.cc
  1369. if cs.ID == 0 {
  1370. // We were canceled before creating the stream, so return our reservation.
  1371. cc.decrStreamReservations()
  1372. }
  1373. // TODO: write h12Compare test showing whether
  1374. // Request.Body is closed by the Transport,
  1375. // and in multiple cases: server replies <=299 and >299
  1376. // while still writing request body
  1377. cc.mu.Lock()
  1378. mustCloseBody := false
  1379. if cs.reqBody != nil && cs.reqBodyClosed == nil {
  1380. mustCloseBody = true
  1381. cs.reqBodyClosed = make(chan struct{})
  1382. }
  1383. bodyClosed := cs.reqBodyClosed
  1384. cc.mu.Unlock()
  1385. if mustCloseBody {
  1386. cs.reqBody.Close()
  1387. close(bodyClosed)
  1388. }
  1389. if bodyClosed != nil {
  1390. <-bodyClosed
  1391. }
  1392. if err != nil && cs.sentEndStream {
  1393. // If the connection is closed immediately after the response is read,
  1394. // we may be aborted before finishing up here. If the stream was closed
  1395. // cleanly on both sides, there is no error.
  1396. select {
  1397. case <-cs.peerClosed:
  1398. err = nil
  1399. default:
  1400. }
  1401. }
  1402. if err != nil {
  1403. cs.abortStream(err) // possibly redundant, but harmless
  1404. if cs.sentHeaders {
  1405. if se, ok := err.(StreamError); ok {
  1406. if se.Cause != errFromPeer {
  1407. cc.writeStreamReset(cs.ID, se.Code, err)
  1408. }
  1409. } else {
  1410. cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1411. }
  1412. }
  1413. cs.bufPipe.CloseWithError(err) // no-op if already closed
  1414. } else {
  1415. if cs.sentHeaders && !cs.sentEndStream {
  1416. cc.writeStreamReset(cs.ID, ErrCodeNo, nil)
  1417. }
  1418. cs.bufPipe.CloseWithError(errRequestCanceled)
  1419. }
  1420. if cs.ID != 0 {
  1421. cc.forgetStreamID(cs.ID)
  1422. }
  1423. cc.wmu.Lock()
  1424. werr := cc.werr
  1425. cc.wmu.Unlock()
  1426. if werr != nil {
  1427. cc.Close()
  1428. }
  1429. close(cs.donec)
  1430. }
  1431. // awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
  1432. // Must hold cc.mu.
  1433. func (cc *ClientConn) awaitOpenSlotForStreamLocked(cs *clientStream) error {
  1434. for {
  1435. cc.lastActive = time.Now()
  1436. if cc.closed || !cc.canTakeNewRequestLocked() {
  1437. return errClientConnUnusable
  1438. }
  1439. cc.lastIdle = time.Time{}
  1440. if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
  1441. return nil
  1442. }
  1443. cc.pendingRequests++
  1444. cc.cond.Wait()
  1445. cc.pendingRequests--
  1446. select {
  1447. case <-cs.abort:
  1448. return cs.abortErr
  1449. default:
  1450. }
  1451. }
  1452. }
  1453. // requires cc.wmu be held
  1454. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  1455. first := true // first frame written (HEADERS is first, then CONTINUATION)
  1456. for len(hdrs) > 0 && cc.werr == nil {
  1457. chunk := hdrs
  1458. if len(chunk) > maxFrameSize {
  1459. chunk = chunk[:maxFrameSize]
  1460. }
  1461. hdrs = hdrs[len(chunk):]
  1462. endHeaders := len(hdrs) == 0
  1463. if first {
  1464. cc.fr.WriteHeaders(HeadersFrameParam{
  1465. StreamID: streamID,
  1466. BlockFragment: chunk,
  1467. EndStream: endStream,
  1468. EndHeaders: endHeaders,
  1469. })
  1470. first = false
  1471. } else {
  1472. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  1473. }
  1474. }
  1475. cc.bw.Flush()
  1476. return cc.werr
  1477. }
  1478. // internal error values; they don't escape to callers
  1479. var (
  1480. // abort request body write; don't send cancel
  1481. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  1482. // abort request body write, but send stream reset of cancel.
  1483. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  1484. errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
  1485. )
  1486. // frameScratchBufferLen returns the length of a buffer to use for
  1487. // outgoing request bodies to read/write to/from.
  1488. //
  1489. // It returns max(1, min(peer's advertised max frame size,
  1490. // Request.ContentLength+1, 512KB)).
  1491. func (cs *clientStream) frameScratchBufferLen(maxFrameSize int) int {
  1492. const max = 512 << 10
  1493. n := int64(maxFrameSize)
  1494. if n > max {
  1495. n = max
  1496. }
  1497. if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
  1498. // Add an extra byte past the declared content-length to
  1499. // give the caller's Request.Body io.Reader a chance to
  1500. // give us more bytes than they declared, so we can catch it
  1501. // early.
  1502. n = cl + 1
  1503. }
  1504. if n < 1 {
  1505. return 1
  1506. }
  1507. return int(n) // doesn't truncate; max is 512K
  1508. }
  1509. // Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running
  1510. // streaming requests using small frame sizes occupy large buffers initially allocated for prior
  1511. // requests needing big buffers. The size ranges are as follows:
  1512. // {0 KB, 16 KB], {16 KB, 32 KB], {32 KB, 64 KB], {64 KB, 128 KB], {128 KB, 256 KB],
  1513. // {256 KB, 512 KB], {512 KB, infinity}
  1514. // In practice, the maximum scratch buffer size should not exceed 512 KB due to
  1515. // frameScratchBufferLen(maxFrameSize), thus the "infinity pool" should never be used.
  1516. // It exists mainly as a safety measure, for potential future increases in max buffer size.
  1517. var bufPools [7]sync.Pool // of *[]byte
  1518. func bufPoolIndex(size int) int {
  1519. if size <= 16384 {
  1520. return 0
  1521. }
  1522. size -= 1
  1523. bits := bits.Len(uint(size))
  1524. index := bits - 14
  1525. if index >= len(bufPools) {
  1526. return len(bufPools) - 1
  1527. }
  1528. return index
  1529. }
  1530. func (cs *clientStream) writeRequestBody(req *http.Request) (err error) {
  1531. cc := cs.cc
  1532. body := cs.reqBody
  1533. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  1534. hasTrailers := req.Trailer != nil
  1535. remainLen := cs.reqBodyContentLength
  1536. hasContentLen := remainLen != -1
  1537. cc.mu.Lock()
  1538. maxFrameSize := int(cc.maxFrameSize)
  1539. cc.mu.Unlock()
  1540. // Scratch buffer for reading into & writing from.
  1541. scratchLen := cs.frameScratchBufferLen(maxFrameSize)
  1542. var buf []byte
  1543. index := bufPoolIndex(scratchLen)
  1544. if bp, ok := bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
  1545. defer bufPools[index].Put(bp)
  1546. buf = *bp
  1547. } else {
  1548. buf = make([]byte, scratchLen)
  1549. defer bufPools[index].Put(&buf)
  1550. }
  1551. var sawEOF bool
  1552. for !sawEOF {
  1553. n, err := body.Read(buf)
  1554. if hasContentLen {
  1555. remainLen -= int64(n)
  1556. if remainLen == 0 && err == nil {
  1557. // The request body's Content-Length was predeclared and
  1558. // we just finished reading it all, but the underlying io.Reader
  1559. // returned the final chunk with a nil error (which is one of
  1560. // the two valid things a Reader can do at EOF). Because we'd prefer
  1561. // to send the END_STREAM bit early, double-check that we're actually
  1562. // at EOF. Subsequent reads should return (0, EOF) at this point.
  1563. // If either value is different, we return an error in one of two ways below.
  1564. var scratch [1]byte
  1565. var n1 int
  1566. n1, err = body.Read(scratch[:])
  1567. remainLen -= int64(n1)
  1568. }
  1569. if remainLen < 0 {
  1570. err = errReqBodyTooLong
  1571. return err
  1572. }
  1573. }
  1574. if err != nil {
  1575. cc.mu.Lock()
  1576. bodyClosed := cs.reqBodyClosed != nil
  1577. cc.mu.Unlock()
  1578. switch {
  1579. case bodyClosed:
  1580. return errStopReqBodyWrite
  1581. case err == io.EOF:
  1582. sawEOF = true
  1583. err = nil
  1584. default:
  1585. return err
  1586. }
  1587. }
  1588. remain := buf[:n]
  1589. for len(remain) > 0 && err == nil {
  1590. var allowed int32
  1591. allowed, err = cs.awaitFlowControl(len(remain))
  1592. if err != nil {
  1593. return err
  1594. }
  1595. cc.wmu.Lock()
  1596. data := remain[:allowed]
  1597. remain = remain[allowed:]
  1598. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  1599. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  1600. if err == nil {
  1601. // TODO(bradfitz): this flush is for latency, not bandwidth.
  1602. // Most requests won't need this. Make this opt-in or
  1603. // opt-out? Use some heuristic on the body type? Nagel-like
  1604. // timers? Based on 'n'? Only last chunk of this for loop,
  1605. // unless flow control tokens are low? For now, always.
  1606. // If we change this, see comment below.
  1607. err = cc.bw.Flush()
  1608. }
  1609. cc.wmu.Unlock()
  1610. }
  1611. if err != nil {
  1612. return err
  1613. }
  1614. }
  1615. if sentEnd {
  1616. // Already sent END_STREAM (which implies we have no
  1617. // trailers) and flushed, because currently all
  1618. // WriteData frames above get a flush. So we're done.
  1619. return nil
  1620. }
  1621. // Since the RoundTrip contract permits the caller to "mutate or reuse"
  1622. // a request after the Response's Body is closed, verify that this hasn't
  1623. // happened before accessing the trailers.
  1624. cc.mu.Lock()
  1625. trailer := req.Trailer
  1626. err = cs.abortErr
  1627. cc.mu.Unlock()
  1628. if err != nil {
  1629. return err
  1630. }
  1631. cc.wmu.Lock()
  1632. defer cc.wmu.Unlock()
  1633. var trls []byte
  1634. if len(trailer) > 0 {
  1635. trls, err = cc.encodeTrailers(trailer)
  1636. if err != nil {
  1637. return err
  1638. }
  1639. }
  1640. // Two ways to send END_STREAM: either with trailers, or
  1641. // with an empty DATA frame.
  1642. if len(trls) > 0 {
  1643. err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1644. } else {
  1645. err = cc.fr.WriteData(cs.ID, true, nil)
  1646. }
  1647. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1648. err = ferr
  1649. }
  1650. return err
  1651. }
  1652. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1653. // control tokens from the server.
  1654. // It returns either the non-zero number of tokens taken or an error
  1655. // if the stream is dead.
  1656. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1657. cc := cs.cc
  1658. ctx := cs.ctx
  1659. cc.mu.Lock()
  1660. defer cc.mu.Unlock()
  1661. for {
  1662. if cc.closed {
  1663. return 0, errClientConnClosed
  1664. }
  1665. if cs.reqBodyClosed != nil {
  1666. return 0, errStopReqBodyWrite
  1667. }
  1668. select {
  1669. case <-cs.abort:
  1670. return 0, cs.abortErr
  1671. case <-ctx.Done():
  1672. return 0, ctx.Err()
  1673. case <-cs.reqCancel:
  1674. return 0, errRequestCanceled
  1675. default:
  1676. }
  1677. if a := cs.flow.available(); a > 0 {
  1678. take := a
  1679. if int(take) > maxBytes {
  1680. take = int32(maxBytes) // can't truncate int; take is int32
  1681. }
  1682. if take > int32(cc.maxFrameSize) {
  1683. take = int32(cc.maxFrameSize)
  1684. }
  1685. cs.flow.take(take)
  1686. return take, nil
  1687. }
  1688. cc.cond.Wait()
  1689. }
  1690. }
  1691. var errNilRequestURL = errors.New("http2: Request.URI is nil")
  1692. // requires cc.wmu be held.
  1693. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1694. cc.hbuf.Reset()
  1695. if req.URL == nil {
  1696. return nil, errNilRequestURL
  1697. }
  1698. host := req.Host
  1699. if host == "" {
  1700. host = req.URL.Host
  1701. }
  1702. host, err := httpguts.PunycodeHostPort(host)
  1703. if err != nil {
  1704. return nil, err
  1705. }
  1706. if !httpguts.ValidHostHeader(host) {
  1707. return nil, errors.New("http2: invalid Host header")
  1708. }
  1709. var path string
  1710. if req.Method != "CONNECT" {
  1711. path = req.URL.RequestURI()
  1712. if !validPseudoPath(path) {
  1713. orig := path
  1714. path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1715. if !validPseudoPath(path) {
  1716. if req.URL.Opaque != "" {
  1717. return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1718. } else {
  1719. return nil, fmt.Errorf("invalid request :path %q", orig)
  1720. }
  1721. }
  1722. }
  1723. }
  1724. // Check for any invalid headers and return an error before we
  1725. // potentially pollute our hpack state. (We want to be able to
  1726. // continue to reuse the hpack encoder for future requests)
  1727. for k, vv := range req.Header {
  1728. if !httpguts.ValidHeaderFieldName(k) {
  1729. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1730. }
  1731. for _, v := range vv {
  1732. if !httpguts.ValidHeaderFieldValue(v) {
  1733. // Don't include the value in the error, because it may be sensitive.
  1734. return nil, fmt.Errorf("invalid HTTP header value for header %q", k)
  1735. }
  1736. }
  1737. }
  1738. enumerateHeaders := func(f func(name, value string)) {
  1739. // 8.1.2.3 Request Pseudo-Header Fields
  1740. // The :path pseudo-header field includes the path and query parts of the
  1741. // target URI (the path-absolute production and optionally a '?' character
  1742. // followed by the query production, see Sections 3.3 and 3.4 of
  1743. // [RFC3986]).
  1744. f(":authority", host)
  1745. m := req.Method
  1746. if m == "" {
  1747. m = http.MethodGet
  1748. }
  1749. f(":method", m)
  1750. if req.Method != "CONNECT" {
  1751. f(":path", path)
  1752. f(":scheme", req.URL.Scheme)
  1753. }
  1754. if trailers != "" {
  1755. f("trailer", trailers)
  1756. }
  1757. var didUA bool
  1758. for k, vv := range req.Header {
  1759. if asciiEqualFold(k, "host") || asciiEqualFold(k, "content-length") {
  1760. // Host is :authority, already sent.
  1761. // Content-Length is automatic, set below.
  1762. continue
  1763. } else if asciiEqualFold(k, "connection") ||
  1764. asciiEqualFold(k, "proxy-connection") ||
  1765. asciiEqualFold(k, "transfer-encoding") ||
  1766. asciiEqualFold(k, "upgrade") ||
  1767. asciiEqualFold(k, "keep-alive") {
  1768. // Per 8.1.2.2 Connection-Specific Header
  1769. // Fields, don't send connection-specific
  1770. // fields. We have already checked if any
  1771. // are error-worthy so just ignore the rest.
  1772. continue
  1773. } else if asciiEqualFold(k, "user-agent") {
  1774. // Match Go's http1 behavior: at most one
  1775. // User-Agent. If set to nil or empty string,
  1776. // then omit it. Otherwise if not mentioned,
  1777. // include the default (below).
  1778. didUA = true
  1779. if len(vv) < 1 {
  1780. continue
  1781. }
  1782. vv = vv[:1]
  1783. if vv[0] == "" {
  1784. continue
  1785. }
  1786. } else if asciiEqualFold(k, "cookie") {
  1787. // Per 8.1.2.5 To allow for better compression efficiency, the
  1788. // Cookie header field MAY be split into separate header fields,
  1789. // each with one or more cookie-pairs.
  1790. for _, v := range vv {
  1791. for {
  1792. p := strings.IndexByte(v, ';')
  1793. if p < 0 {
  1794. break
  1795. }
  1796. f("cookie", v[:p])
  1797. p++
  1798. // strip space after semicolon if any.
  1799. for p+1 <= len(v) && v[p] == ' ' {
  1800. p++
  1801. }
  1802. v = v[p:]
  1803. }
  1804. if len(v) > 0 {
  1805. f("cookie", v)
  1806. }
  1807. }
  1808. continue
  1809. }
  1810. for _, v := range vv {
  1811. f(k, v)
  1812. }
  1813. }
  1814. if shouldSendReqContentLength(req.Method, contentLength) {
  1815. f("content-length", strconv.FormatInt(contentLength, 10))
  1816. }
  1817. if addGzipHeader {
  1818. f("accept-encoding", "gzip")
  1819. }
  1820. if !didUA {
  1821. f("user-agent", defaultUserAgent)
  1822. }
  1823. }
  1824. // Do a first pass over the headers counting bytes to ensure
  1825. // we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1826. // separate pass before encoding the headers to prevent
  1827. // modifying the hpack state.
  1828. hlSize := uint64(0)
  1829. enumerateHeaders(func(name, value string) {
  1830. hf := hpack.HeaderField{Name: name, Value: value}
  1831. hlSize += uint64(hf.Size())
  1832. })
  1833. if hlSize > cc.peerMaxHeaderListSize {
  1834. return nil, errRequestHeaderListSize
  1835. }
  1836. trace := httptrace.ContextClientTrace(req.Context())
  1837. traceHeaders := traceHasWroteHeaderField(trace)
  1838. // Header list size is ok. Write the headers.
  1839. enumerateHeaders(func(name, value string) {
  1840. name, ascii := lowerHeader(name)
  1841. if !ascii {
  1842. // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  1843. // field names have to be ASCII characters (just as in HTTP/1.x).
  1844. return
  1845. }
  1846. cc.writeHeader(name, value)
  1847. if traceHeaders {
  1848. traceWroteHeaderField(trace, name, value)
  1849. }
  1850. })
  1851. return cc.hbuf.Bytes(), nil
  1852. }
  1853. // shouldSendReqContentLength reports whether the http2.Transport should send
  1854. // a "content-length" request header. This logic is basically a copy of the net/http
  1855. // transferWriter.shouldSendContentLength.
  1856. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1857. // -1 means unknown.
  1858. func shouldSendReqContentLength(method string, contentLength int64) bool {
  1859. if contentLength > 0 {
  1860. return true
  1861. }
  1862. if contentLength < 0 {
  1863. return false
  1864. }
  1865. // For zero bodies, whether we send a content-length depends on the method.
  1866. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  1867. switch method {
  1868. case "POST", "PUT", "PATCH":
  1869. return true
  1870. default:
  1871. return false
  1872. }
  1873. }
  1874. // requires cc.wmu be held.
  1875. func (cc *ClientConn) encodeTrailers(trailer http.Header) ([]byte, error) {
  1876. cc.hbuf.Reset()
  1877. hlSize := uint64(0)
  1878. for k, vv := range trailer {
  1879. for _, v := range vv {
  1880. hf := hpack.HeaderField{Name: k, Value: v}
  1881. hlSize += uint64(hf.Size())
  1882. }
  1883. }
  1884. if hlSize > cc.peerMaxHeaderListSize {
  1885. return nil, errRequestHeaderListSize
  1886. }
  1887. for k, vv := range trailer {
  1888. lowKey, ascii := lowerHeader(k)
  1889. if !ascii {
  1890. // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  1891. // field names have to be ASCII characters (just as in HTTP/1.x).
  1892. continue
  1893. }
  1894. // Transfer-Encoding, etc.. have already been filtered at the
  1895. // start of RoundTrip
  1896. for _, v := range vv {
  1897. cc.writeHeader(lowKey, v)
  1898. }
  1899. }
  1900. return cc.hbuf.Bytes(), nil
  1901. }
  1902. func (cc *ClientConn) writeHeader(name, value string) {
  1903. if VerboseLogs {
  1904. log.Printf("http2: Transport encoding header %q = %q", name, value)
  1905. }
  1906. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1907. }
  1908. type resAndError struct {
  1909. _ incomparable
  1910. res *http.Response
  1911. err error
  1912. }
  1913. // requires cc.mu be held.
  1914. func (cc *ClientConn) addStreamLocked(cs *clientStream) {
  1915. cs.flow.add(int32(cc.initialWindowSize))
  1916. cs.flow.setConnFlow(&cc.flow)
  1917. cs.inflow.init(transportDefaultStreamFlow)
  1918. cs.ID = cc.nextStreamID
  1919. cc.nextStreamID += 2
  1920. cc.streams[cs.ID] = cs
  1921. if cs.ID == 0 {
  1922. panic("assigned stream ID 0")
  1923. }
  1924. }
  1925. func (cc *ClientConn) forgetStreamID(id uint32) {
  1926. cc.mu.Lock()
  1927. slen := len(cc.streams)
  1928. delete(cc.streams, id)
  1929. if len(cc.streams) != slen-1 {
  1930. panic("forgetting unknown stream id")
  1931. }
  1932. cc.lastActive = time.Now()
  1933. if len(cc.streams) == 0 && cc.idleTimer != nil {
  1934. cc.idleTimer.Reset(cc.idleTimeout)
  1935. cc.lastIdle = time.Now()
  1936. }
  1937. // Wake up writeRequestBody via clientStream.awaitFlowControl and
  1938. // wake up RoundTrip if there is a pending request.
  1939. cc.cond.Broadcast()
  1940. closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
  1941. if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
  1942. if VerboseLogs {
  1943. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
  1944. }
  1945. cc.closed = true
  1946. defer cc.closeConn()
  1947. }
  1948. cc.mu.Unlock()
  1949. }
  1950. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1951. type clientConnReadLoop struct {
  1952. _ incomparable
  1953. cc *ClientConn
  1954. }
  1955. // readLoop runs in its own goroutine and reads and dispatches frames.
  1956. func (cc *ClientConn) readLoop() {
  1957. rl := &clientConnReadLoop{cc: cc}
  1958. defer rl.cleanup()
  1959. cc.readerErr = rl.run()
  1960. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1961. cc.wmu.Lock()
  1962. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1963. cc.wmu.Unlock()
  1964. }
  1965. }
  1966. // GoAwayError is returned by the Transport when the server closes the
  1967. // TCP connection after sending a GOAWAY frame.
  1968. type GoAwayError struct {
  1969. LastStreamID uint32
  1970. ErrCode ErrCode
  1971. DebugData string
  1972. }
  1973. func (e GoAwayError) Error() string {
  1974. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1975. e.LastStreamID, e.ErrCode, e.DebugData)
  1976. }
  1977. func isEOFOrNetReadError(err error) bool {
  1978. if err == io.EOF {
  1979. return true
  1980. }
  1981. ne, ok := err.(*net.OpError)
  1982. return ok && ne.Op == "read"
  1983. }
  1984. func (rl *clientConnReadLoop) cleanup() {
  1985. cc := rl.cc
  1986. cc.t.connPool().MarkDead(cc)
  1987. defer cc.closeConn()
  1988. defer close(cc.readerDone)
  1989. if cc.idleTimer != nil {
  1990. cc.idleTimer.Stop()
  1991. }
  1992. // Close any response bodies if the server closes prematurely.
  1993. // TODO: also do this if we've written the headers but not
  1994. // gotten a response yet.
  1995. err := cc.readerErr
  1996. cc.mu.Lock()
  1997. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1998. err = GoAwayError{
  1999. LastStreamID: cc.goAway.LastStreamID,
  2000. ErrCode: cc.goAway.ErrCode,
  2001. DebugData: cc.goAwayDebug,
  2002. }
  2003. } else if err == io.EOF {
  2004. err = io.ErrUnexpectedEOF
  2005. }
  2006. cc.closed = true
  2007. for _, cs := range cc.streams {
  2008. select {
  2009. case <-cs.peerClosed:
  2010. // The server closed the stream before closing the conn,
  2011. // so no need to interrupt it.
  2012. default:
  2013. cs.abortStreamLocked(err)
  2014. }
  2015. }
  2016. cc.cond.Broadcast()
  2017. cc.mu.Unlock()
  2018. }
  2019. // countReadFrameError calls Transport.CountError with a string
  2020. // representing err.
  2021. func (cc *ClientConn) countReadFrameError(err error) {
  2022. f := cc.t.CountError
  2023. if f == nil || err == nil {
  2024. return
  2025. }
  2026. if ce, ok := err.(ConnectionError); ok {
  2027. errCode := ErrCode(ce)
  2028. f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
  2029. return
  2030. }
  2031. if errors.Is(err, io.EOF) {
  2032. f("read_frame_eof")
  2033. return
  2034. }
  2035. if errors.Is(err, io.ErrUnexpectedEOF) {
  2036. f("read_frame_unexpected_eof")
  2037. return
  2038. }
  2039. if errors.Is(err, ErrFrameTooLarge) {
  2040. f("read_frame_too_large")
  2041. return
  2042. }
  2043. f("read_frame_other")
  2044. }
  2045. func (rl *clientConnReadLoop) run() error {
  2046. cc := rl.cc
  2047. gotSettings := false
  2048. readIdleTimeout := cc.t.ReadIdleTimeout
  2049. var t *time.Timer
  2050. if readIdleTimeout != 0 {
  2051. t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
  2052. defer t.Stop()
  2053. }
  2054. for {
  2055. f, err := cc.fr.ReadFrame()
  2056. if t != nil {
  2057. t.Reset(readIdleTimeout)
  2058. }
  2059. if err != nil {
  2060. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  2061. }
  2062. if se, ok := err.(StreamError); ok {
  2063. if cs := rl.streamByID(se.StreamID); cs != nil {
  2064. if se.Cause == nil {
  2065. se.Cause = cc.fr.errDetail
  2066. }
  2067. rl.endStreamError(cs, se)
  2068. }
  2069. continue
  2070. } else if err != nil {
  2071. cc.countReadFrameError(err)
  2072. return err
  2073. }
  2074. if VerboseLogs {
  2075. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  2076. }
  2077. if !gotSettings {
  2078. if _, ok := f.(*SettingsFrame); !ok {
  2079. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  2080. return ConnectionError(ErrCodeProtocol)
  2081. }
  2082. gotSettings = true
  2083. }
  2084. switch f := f.(type) {
  2085. case *MetaHeadersFrame:
  2086. err = rl.processHeaders(f)
  2087. case *DataFrame:
  2088. err = rl.processData(f)
  2089. case *GoAwayFrame:
  2090. err = rl.processGoAway(f)
  2091. case *RSTStreamFrame:
  2092. err = rl.processResetStream(f)
  2093. case *SettingsFrame:
  2094. err = rl.processSettings(f)
  2095. case *PushPromiseFrame:
  2096. err = rl.processPushPromise(f)
  2097. case *WindowUpdateFrame:
  2098. err = rl.processWindowUpdate(f)
  2099. case *PingFrame:
  2100. err = rl.processPing(f)
  2101. default:
  2102. cc.logf("Transport: unhandled response frame type %T", f)
  2103. }
  2104. if err != nil {
  2105. if VerboseLogs {
  2106. cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  2107. }
  2108. return err
  2109. }
  2110. }
  2111. }
  2112. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  2113. cs := rl.streamByID(f.StreamID)
  2114. if cs == nil {
  2115. // We'd get here if we canceled a request while the
  2116. // server had its response still in flight. So if this
  2117. // was just something we canceled, ignore it.
  2118. return nil
  2119. }
  2120. if cs.readClosed {
  2121. rl.endStreamError(cs, StreamError{
  2122. StreamID: f.StreamID,
  2123. Code: ErrCodeProtocol,
  2124. Cause: errors.New("protocol error: headers after END_STREAM"),
  2125. })
  2126. return nil
  2127. }
  2128. if !cs.firstByte {
  2129. if cs.trace != nil {
  2130. // TODO(bradfitz): move first response byte earlier,
  2131. // when we first read the 9 byte header, not waiting
  2132. // until all the HEADERS+CONTINUATION frames have been
  2133. // merged. This works for now.
  2134. traceFirstResponseByte(cs.trace)
  2135. }
  2136. cs.firstByte = true
  2137. }
  2138. if !cs.pastHeaders {
  2139. cs.pastHeaders = true
  2140. } else {
  2141. return rl.processTrailers(cs, f)
  2142. }
  2143. res, err := rl.handleResponse(cs, f)
  2144. if err != nil {
  2145. if _, ok := err.(ConnectionError); ok {
  2146. return err
  2147. }
  2148. // Any other error type is a stream error.
  2149. rl.endStreamError(cs, StreamError{
  2150. StreamID: f.StreamID,
  2151. Code: ErrCodeProtocol,
  2152. Cause: err,
  2153. })
  2154. return nil // return nil from process* funcs to keep conn alive
  2155. }
  2156. if res == nil {
  2157. // (nil, nil) special case. See handleResponse docs.
  2158. return nil
  2159. }
  2160. cs.resTrailer = &res.Trailer
  2161. cs.res = res
  2162. close(cs.respHeaderRecv)
  2163. if f.StreamEnded() {
  2164. rl.endStream(cs)
  2165. }
  2166. return nil
  2167. }
  2168. // may return error types nil, or ConnectionError. Any other error value
  2169. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  2170. // is the detail.
  2171. //
  2172. // As a special case, handleResponse may return (nil, nil) to skip the
  2173. // frame (currently only used for 1xx responses).
  2174. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  2175. if f.Truncated {
  2176. return nil, errResponseHeaderListSize
  2177. }
  2178. status := f.PseudoValue("status")
  2179. if status == "" {
  2180. return nil, errors.New("malformed response from server: missing status pseudo header")
  2181. }
  2182. statusCode, err := strconv.Atoi(status)
  2183. if err != nil {
  2184. return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  2185. }
  2186. regularFields := f.RegularFields()
  2187. strs := make([]string, len(regularFields))
  2188. header := make(http.Header, len(regularFields))
  2189. res := &http.Response{
  2190. Proto: "HTTP/2.0",
  2191. ProtoMajor: 2,
  2192. Header: header,
  2193. StatusCode: statusCode,
  2194. Status: status + " " + http.StatusText(statusCode),
  2195. }
  2196. for _, hf := range regularFields {
  2197. key := canonicalHeader(hf.Name)
  2198. if key == "Trailer" {
  2199. t := res.Trailer
  2200. if t == nil {
  2201. t = make(http.Header)
  2202. res.Trailer = t
  2203. }
  2204. foreachHeaderElement(hf.Value, func(v string) {
  2205. t[canonicalHeader(v)] = nil
  2206. })
  2207. } else {
  2208. vv := header[key]
  2209. if vv == nil && len(strs) > 0 {
  2210. // More than likely this will be a single-element key.
  2211. // Most headers aren't multi-valued.
  2212. // Set the capacity on strs[0] to 1, so any future append
  2213. // won't extend the slice into the other strings.
  2214. vv, strs = strs[:1:1], strs[1:]
  2215. vv[0] = hf.Value
  2216. header[key] = vv
  2217. } else {
  2218. header[key] = append(vv, hf.Value)
  2219. }
  2220. }
  2221. }
  2222. if statusCode >= 100 && statusCode <= 199 {
  2223. if f.StreamEnded() {
  2224. return nil, errors.New("1xx informational response with END_STREAM flag")
  2225. }
  2226. cs.num1xx++
  2227. const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
  2228. if cs.num1xx > max1xxResponses {
  2229. return nil, errors.New("http2: too many 1xx informational responses")
  2230. }
  2231. if fn := cs.get1xxTraceFunc(); fn != nil {
  2232. if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
  2233. return nil, err
  2234. }
  2235. }
  2236. if statusCode == 100 {
  2237. traceGot100Continue(cs.trace)
  2238. select {
  2239. case cs.on100 <- struct{}{}:
  2240. default:
  2241. }
  2242. }
  2243. cs.pastHeaders = false // do it all again
  2244. return nil, nil
  2245. }
  2246. res.ContentLength = -1
  2247. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  2248. if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
  2249. res.ContentLength = int64(cl)
  2250. } else {
  2251. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  2252. // more safe smuggling-wise to ignore.
  2253. }
  2254. } else if len(clens) > 1 {
  2255. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  2256. // more safe smuggling-wise to ignore.
  2257. } else if f.StreamEnded() && !cs.isHead {
  2258. res.ContentLength = 0
  2259. }
  2260. if cs.isHead {
  2261. res.Body = noBody
  2262. return res, nil
  2263. }
  2264. if f.StreamEnded() {
  2265. if res.ContentLength > 0 {
  2266. res.Body = missingBody{}
  2267. } else {
  2268. res.Body = noBody
  2269. }
  2270. return res, nil
  2271. }
  2272. cs.bufPipe.setBuffer(&dataBuffer{expected: res.ContentLength})
  2273. cs.bytesRemain = res.ContentLength
  2274. res.Body = transportResponseBody{cs}
  2275. if cs.requestedGzip && asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
  2276. res.Header.Del("Content-Encoding")
  2277. res.Header.Del("Content-Length")
  2278. res.ContentLength = -1
  2279. res.Body = &gzipReader{body: res.Body}
  2280. res.Uncompressed = true
  2281. }
  2282. return res, nil
  2283. }
  2284. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  2285. if cs.pastTrailers {
  2286. // Too many HEADERS frames for this stream.
  2287. return ConnectionError(ErrCodeProtocol)
  2288. }
  2289. cs.pastTrailers = true
  2290. if !f.StreamEnded() {
  2291. // We expect that any headers for trailers also
  2292. // has END_STREAM.
  2293. return ConnectionError(ErrCodeProtocol)
  2294. }
  2295. if len(f.PseudoFields()) > 0 {
  2296. // No pseudo header fields are defined for trailers.
  2297. // TODO: ConnectionError might be overly harsh? Check.
  2298. return ConnectionError(ErrCodeProtocol)
  2299. }
  2300. trailer := make(http.Header)
  2301. for _, hf := range f.RegularFields() {
  2302. key := canonicalHeader(hf.Name)
  2303. trailer[key] = append(trailer[key], hf.Value)
  2304. }
  2305. cs.trailer = trailer
  2306. rl.endStream(cs)
  2307. return nil
  2308. }
  2309. // transportResponseBody is the concrete type of Transport.RoundTrip's
  2310. // Response.Body. It is an io.ReadCloser.
  2311. type transportResponseBody struct {
  2312. cs *clientStream
  2313. }
  2314. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  2315. cs := b.cs
  2316. cc := cs.cc
  2317. if cs.readErr != nil {
  2318. return 0, cs.readErr
  2319. }
  2320. n, err = b.cs.bufPipe.Read(p)
  2321. if cs.bytesRemain != -1 {
  2322. if int64(n) > cs.bytesRemain {
  2323. n = int(cs.bytesRemain)
  2324. if err == nil {
  2325. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  2326. cs.abortStream(err)
  2327. }
  2328. cs.readErr = err
  2329. return int(cs.bytesRemain), err
  2330. }
  2331. cs.bytesRemain -= int64(n)
  2332. if err == io.EOF && cs.bytesRemain > 0 {
  2333. err = io.ErrUnexpectedEOF
  2334. cs.readErr = err
  2335. return n, err
  2336. }
  2337. }
  2338. if n == 0 {
  2339. // No flow control tokens to send back.
  2340. return
  2341. }
  2342. cc.mu.Lock()
  2343. connAdd := cc.inflow.add(n)
  2344. var streamAdd int32
  2345. if err == nil { // No need to refresh if the stream is over or failed.
  2346. streamAdd = cs.inflow.add(n)
  2347. }
  2348. cc.mu.Unlock()
  2349. if connAdd != 0 || streamAdd != 0 {
  2350. cc.wmu.Lock()
  2351. defer cc.wmu.Unlock()
  2352. if connAdd != 0 {
  2353. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  2354. }
  2355. if streamAdd != 0 {
  2356. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  2357. }
  2358. cc.bw.Flush()
  2359. }
  2360. return
  2361. }
  2362. var errClosedResponseBody = errors.New("http2: response body closed")
  2363. func (b transportResponseBody) Close() error {
  2364. cs := b.cs
  2365. cc := cs.cc
  2366. cs.bufPipe.BreakWithError(errClosedResponseBody)
  2367. cs.abortStream(errClosedResponseBody)
  2368. unread := cs.bufPipe.Len()
  2369. if unread > 0 {
  2370. cc.mu.Lock()
  2371. // Return connection-level flow control.
  2372. connAdd := cc.inflow.add(unread)
  2373. cc.mu.Unlock()
  2374. // TODO(dneil): Acquiring this mutex can block indefinitely.
  2375. // Move flow control return to a goroutine?
  2376. cc.wmu.Lock()
  2377. // Return connection-level flow control.
  2378. if connAdd > 0 {
  2379. cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  2380. }
  2381. cc.bw.Flush()
  2382. cc.wmu.Unlock()
  2383. }
  2384. select {
  2385. case <-cs.donec:
  2386. case <-cs.ctx.Done():
  2387. // See golang/go#49366: The net/http package can cancel the
  2388. // request context after the response body is fully read.
  2389. // Don't treat this as an error.
  2390. return nil
  2391. case <-cs.reqCancel:
  2392. return errRequestCanceled
  2393. }
  2394. return nil
  2395. }
  2396. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  2397. cc := rl.cc
  2398. cs := rl.streamByID(f.StreamID)
  2399. data := f.Data()
  2400. if cs == nil {
  2401. cc.mu.Lock()
  2402. neverSent := cc.nextStreamID
  2403. cc.mu.Unlock()
  2404. if f.StreamID >= neverSent {
  2405. // We never asked for this.
  2406. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  2407. return ConnectionError(ErrCodeProtocol)
  2408. }
  2409. // We probably did ask for this, but canceled. Just ignore it.
  2410. // TODO: be stricter here? only silently ignore things which
  2411. // we canceled, but not things which were closed normally
  2412. // by the peer? Tough without accumulating too much state.
  2413. // But at least return their flow control:
  2414. if f.Length > 0 {
  2415. cc.mu.Lock()
  2416. ok := cc.inflow.take(f.Length)
  2417. connAdd := cc.inflow.add(int(f.Length))
  2418. cc.mu.Unlock()
  2419. if !ok {
  2420. return ConnectionError(ErrCodeFlowControl)
  2421. }
  2422. if connAdd > 0 {
  2423. cc.wmu.Lock()
  2424. cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  2425. cc.bw.Flush()
  2426. cc.wmu.Unlock()
  2427. }
  2428. }
  2429. return nil
  2430. }
  2431. if cs.readClosed {
  2432. cc.logf("protocol error: received DATA after END_STREAM")
  2433. rl.endStreamError(cs, StreamError{
  2434. StreamID: f.StreamID,
  2435. Code: ErrCodeProtocol,
  2436. })
  2437. return nil
  2438. }
  2439. if !cs.firstByte {
  2440. cc.logf("protocol error: received DATA before a HEADERS frame")
  2441. rl.endStreamError(cs, StreamError{
  2442. StreamID: f.StreamID,
  2443. Code: ErrCodeProtocol,
  2444. })
  2445. return nil
  2446. }
  2447. if f.Length > 0 {
  2448. if cs.isHead && len(data) > 0 {
  2449. cc.logf("protocol error: received DATA on a HEAD request")
  2450. rl.endStreamError(cs, StreamError{
  2451. StreamID: f.StreamID,
  2452. Code: ErrCodeProtocol,
  2453. })
  2454. return nil
  2455. }
  2456. // Check connection-level flow control.
  2457. cc.mu.Lock()
  2458. if !takeInflows(&cc.inflow, &cs.inflow, f.Length) {
  2459. cc.mu.Unlock()
  2460. return ConnectionError(ErrCodeFlowControl)
  2461. }
  2462. // Return any padded flow control now, since we won't
  2463. // refund it later on body reads.
  2464. var refund int
  2465. if pad := int(f.Length) - len(data); pad > 0 {
  2466. refund += pad
  2467. }
  2468. didReset := false
  2469. var err error
  2470. if len(data) > 0 {
  2471. if _, err = cs.bufPipe.Write(data); err != nil {
  2472. // Return len(data) now if the stream is already closed,
  2473. // since data will never be read.
  2474. didReset = true
  2475. refund += len(data)
  2476. }
  2477. }
  2478. sendConn := cc.inflow.add(refund)
  2479. var sendStream int32
  2480. if !didReset {
  2481. sendStream = cs.inflow.add(refund)
  2482. }
  2483. cc.mu.Unlock()
  2484. if sendConn > 0 || sendStream > 0 {
  2485. cc.wmu.Lock()
  2486. if sendConn > 0 {
  2487. cc.fr.WriteWindowUpdate(0, uint32(sendConn))
  2488. }
  2489. if sendStream > 0 {
  2490. cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
  2491. }
  2492. cc.bw.Flush()
  2493. cc.wmu.Unlock()
  2494. }
  2495. if err != nil {
  2496. rl.endStreamError(cs, err)
  2497. return nil
  2498. }
  2499. }
  2500. if f.StreamEnded() {
  2501. rl.endStream(cs)
  2502. }
  2503. return nil
  2504. }
  2505. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  2506. // TODO: check that any declared content-length matches, like
  2507. // server.go's (*stream).endStream method.
  2508. if !cs.readClosed {
  2509. cs.readClosed = true
  2510. // Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a
  2511. // race condition: The caller can read io.EOF from Response.Body
  2512. // and close the body before we close cs.peerClosed, causing
  2513. // cleanupWriteRequest to send a RST_STREAM.
  2514. rl.cc.mu.Lock()
  2515. defer rl.cc.mu.Unlock()
  2516. cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
  2517. close(cs.peerClosed)
  2518. }
  2519. }
  2520. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  2521. cs.readAborted = true
  2522. cs.abortStream(err)
  2523. }
  2524. func (rl *clientConnReadLoop) streamByID(id uint32) *clientStream {
  2525. rl.cc.mu.Lock()
  2526. defer rl.cc.mu.Unlock()
  2527. cs := rl.cc.streams[id]
  2528. if cs != nil && !cs.readAborted {
  2529. return cs
  2530. }
  2531. return nil
  2532. }
  2533. func (cs *clientStream) copyTrailers() {
  2534. for k, vv := range cs.trailer {
  2535. t := cs.resTrailer
  2536. if *t == nil {
  2537. *t = make(http.Header)
  2538. }
  2539. (*t)[k] = vv
  2540. }
  2541. }
  2542. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  2543. cc := rl.cc
  2544. cc.t.connPool().MarkDead(cc)
  2545. if f.ErrCode != 0 {
  2546. // TODO: deal with GOAWAY more. particularly the error code
  2547. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  2548. if fn := cc.t.CountError; fn != nil {
  2549. fn("recv_goaway_" + f.ErrCode.stringToken())
  2550. }
  2551. }
  2552. cc.setGoAway(f)
  2553. return nil
  2554. }
  2555. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  2556. cc := rl.cc
  2557. // Locking both mu and wmu here allows frame encoding to read settings with only wmu held.
  2558. // Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless.
  2559. cc.wmu.Lock()
  2560. defer cc.wmu.Unlock()
  2561. if err := rl.processSettingsNoWrite(f); err != nil {
  2562. return err
  2563. }
  2564. if !f.IsAck() {
  2565. cc.fr.WriteSettingsAck()
  2566. cc.bw.Flush()
  2567. }
  2568. return nil
  2569. }
  2570. func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error {
  2571. cc := rl.cc
  2572. cc.mu.Lock()
  2573. defer cc.mu.Unlock()
  2574. if f.IsAck() {
  2575. if cc.wantSettingsAck {
  2576. cc.wantSettingsAck = false
  2577. return nil
  2578. }
  2579. return ConnectionError(ErrCodeProtocol)
  2580. }
  2581. var seenMaxConcurrentStreams bool
  2582. err := f.ForeachSetting(func(s Setting) error {
  2583. switch s.ID {
  2584. case SettingMaxFrameSize:
  2585. cc.maxFrameSize = s.Val
  2586. case SettingMaxConcurrentStreams:
  2587. cc.maxConcurrentStreams = s.Val
  2588. seenMaxConcurrentStreams = true
  2589. case SettingMaxHeaderListSize:
  2590. cc.peerMaxHeaderListSize = uint64(s.Val)
  2591. case SettingInitialWindowSize:
  2592. // Values above the maximum flow-control
  2593. // window size of 2^31-1 MUST be treated as a
  2594. // connection error (Section 5.4.1) of type
  2595. // FLOW_CONTROL_ERROR.
  2596. if s.Val > math.MaxInt32 {
  2597. return ConnectionError(ErrCodeFlowControl)
  2598. }
  2599. // Adjust flow control of currently-open
  2600. // frames by the difference of the old initial
  2601. // window size and this one.
  2602. delta := int32(s.Val) - int32(cc.initialWindowSize)
  2603. for _, cs := range cc.streams {
  2604. cs.flow.add(delta)
  2605. }
  2606. cc.cond.Broadcast()
  2607. cc.initialWindowSize = s.Val
  2608. case SettingHeaderTableSize:
  2609. cc.henc.SetMaxDynamicTableSize(s.Val)
  2610. cc.peerMaxHeaderTableSize = s.Val
  2611. default:
  2612. cc.vlogf("Unhandled Setting: %v", s)
  2613. }
  2614. return nil
  2615. })
  2616. if err != nil {
  2617. return err
  2618. }
  2619. if !cc.seenSettings {
  2620. if !seenMaxConcurrentStreams {
  2621. // This was the servers initial SETTINGS frame and it
  2622. // didn't contain a MAX_CONCURRENT_STREAMS field so
  2623. // increase the number of concurrent streams this
  2624. // connection can establish to our default.
  2625. cc.maxConcurrentStreams = defaultMaxConcurrentStreams
  2626. }
  2627. cc.seenSettings = true
  2628. }
  2629. return nil
  2630. }
  2631. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  2632. cc := rl.cc
  2633. cs := rl.streamByID(f.StreamID)
  2634. if f.StreamID != 0 && cs == nil {
  2635. return nil
  2636. }
  2637. cc.mu.Lock()
  2638. defer cc.mu.Unlock()
  2639. fl := &cc.flow
  2640. if cs != nil {
  2641. fl = &cs.flow
  2642. }
  2643. if !fl.add(int32(f.Increment)) {
  2644. return ConnectionError(ErrCodeFlowControl)
  2645. }
  2646. cc.cond.Broadcast()
  2647. return nil
  2648. }
  2649. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  2650. cs := rl.streamByID(f.StreamID)
  2651. if cs == nil {
  2652. // TODO: return error if server tries to RST_STREAM an idle stream
  2653. return nil
  2654. }
  2655. serr := streamError(cs.ID, f.ErrCode)
  2656. serr.Cause = errFromPeer
  2657. if f.ErrCode == ErrCodeProtocol {
  2658. rl.cc.SetDoNotReuse()
  2659. }
  2660. if fn := cs.cc.t.CountError; fn != nil {
  2661. fn("recv_rststream_" + f.ErrCode.stringToken())
  2662. }
  2663. cs.abortStream(serr)
  2664. cs.bufPipe.CloseWithError(serr)
  2665. return nil
  2666. }
  2667. // Ping sends a PING frame to the server and waits for the ack.
  2668. func (cc *ClientConn) Ping(ctx context.Context) error {
  2669. c := make(chan struct{})
  2670. // Generate a random payload
  2671. var p [8]byte
  2672. for {
  2673. if _, err := rand.Read(p[:]); err != nil {
  2674. return err
  2675. }
  2676. cc.mu.Lock()
  2677. // check for dup before insert
  2678. if _, found := cc.pings[p]; !found {
  2679. cc.pings[p] = c
  2680. cc.mu.Unlock()
  2681. break
  2682. }
  2683. cc.mu.Unlock()
  2684. }
  2685. errc := make(chan error, 1)
  2686. go func() {
  2687. cc.wmu.Lock()
  2688. defer cc.wmu.Unlock()
  2689. if err := cc.fr.WritePing(false, p); err != nil {
  2690. errc <- err
  2691. return
  2692. }
  2693. if err := cc.bw.Flush(); err != nil {
  2694. errc <- err
  2695. return
  2696. }
  2697. }()
  2698. select {
  2699. case <-c:
  2700. return nil
  2701. case err := <-errc:
  2702. return err
  2703. case <-ctx.Done():
  2704. return ctx.Err()
  2705. case <-cc.readerDone:
  2706. // connection closed
  2707. return cc.readerErr
  2708. }
  2709. }
  2710. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  2711. if f.IsAck() {
  2712. cc := rl.cc
  2713. cc.mu.Lock()
  2714. defer cc.mu.Unlock()
  2715. // If ack, notify listener if any
  2716. if c, ok := cc.pings[f.Data]; ok {
  2717. close(c)
  2718. delete(cc.pings, f.Data)
  2719. }
  2720. return nil
  2721. }
  2722. cc := rl.cc
  2723. cc.wmu.Lock()
  2724. defer cc.wmu.Unlock()
  2725. if err := cc.fr.WritePing(true, f.Data); err != nil {
  2726. return err
  2727. }
  2728. return cc.bw.Flush()
  2729. }
  2730. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  2731. // We told the peer we don't want them.
  2732. // Spec says:
  2733. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  2734. // setting of the peer endpoint is set to 0. An endpoint that
  2735. // has set this setting and has received acknowledgement MUST
  2736. // treat the receipt of a PUSH_PROMISE frame as a connection
  2737. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  2738. return ConnectionError(ErrCodeProtocol)
  2739. }
  2740. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  2741. // TODO: map err to more interesting error codes, once the
  2742. // HTTP community comes up with some. But currently for
  2743. // RST_STREAM there's no equivalent to GOAWAY frame's debug
  2744. // data, and the error codes are all pretty vague ("cancel").
  2745. cc.wmu.Lock()
  2746. cc.fr.WriteRSTStream(streamID, code)
  2747. cc.bw.Flush()
  2748. cc.wmu.Unlock()
  2749. }
  2750. var (
  2751. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  2752. errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
  2753. )
  2754. func (cc *ClientConn) logf(format string, args ...interface{}) {
  2755. cc.t.logf(format, args...)
  2756. }
  2757. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  2758. cc.t.vlogf(format, args...)
  2759. }
  2760. func (t *Transport) vlogf(format string, args ...interface{}) {
  2761. if VerboseLogs {
  2762. t.logf(format, args...)
  2763. }
  2764. }
  2765. func (t *Transport) logf(format string, args ...interface{}) {
  2766. log.Printf(format, args...)
  2767. }
  2768. var noBody io.ReadCloser = noBodyReader{}
  2769. type noBodyReader struct{}
  2770. func (noBodyReader) Close() error { return nil }
  2771. func (noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
  2772. type missingBody struct{}
  2773. func (missingBody) Close() error { return nil }
  2774. func (missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
  2775. func strSliceContains(ss []string, s string) bool {
  2776. for _, v := range ss {
  2777. if v == s {
  2778. return true
  2779. }
  2780. }
  2781. return false
  2782. }
  2783. type erringRoundTripper struct{ err error }
  2784. func (rt erringRoundTripper) RoundTripErr() error { return rt.err }
  2785. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  2786. // gzipReader wraps a response body so it can lazily
  2787. // call gzip.NewReader on the first call to Read
  2788. type gzipReader struct {
  2789. _ incomparable
  2790. body io.ReadCloser // underlying Response.Body
  2791. zr *gzip.Reader // lazily-initialized gzip reader
  2792. zerr error // sticky error
  2793. }
  2794. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2795. if gz.zerr != nil {
  2796. return 0, gz.zerr
  2797. }
  2798. if gz.zr == nil {
  2799. gz.zr, err = gzip.NewReader(gz.body)
  2800. if err != nil {
  2801. gz.zerr = err
  2802. return 0, err
  2803. }
  2804. }
  2805. return gz.zr.Read(p)
  2806. }
  2807. func (gz *gzipReader) Close() error {
  2808. if err := gz.body.Close(); err != nil {
  2809. return err
  2810. }
  2811. gz.zerr = fs.ErrClosed
  2812. return nil
  2813. }
  2814. type errorReader struct{ err error }
  2815. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  2816. // isConnectionCloseRequest reports whether req should use its own
  2817. // connection for a single request and then close the connection.
  2818. func isConnectionCloseRequest(req *http.Request) bool {
  2819. return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
  2820. }
  2821. // registerHTTPSProtocol calls Transport.RegisterProtocol but
  2822. // converting panics into errors.
  2823. func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
  2824. defer func() {
  2825. if e := recover(); e != nil {
  2826. err = fmt.Errorf("%v", e)
  2827. }
  2828. }()
  2829. t.RegisterProtocol("https", rt)
  2830. return nil
  2831. }
  2832. // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
  2833. // if there's already has a cached connection to the host.
  2834. // (The field is exported so it can be accessed via reflect from net/http; tested
  2835. // by TestNoDialH2RoundTripperType)
  2836. type noDialH2RoundTripper struct{ *Transport }
  2837. func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  2838. res, err := rt.Transport.RoundTrip(req)
  2839. if isNoCachedConnError(err) {
  2840. return nil, http.ErrSkipAltProtocol
  2841. }
  2842. return res, err
  2843. }
  2844. func (t *Transport) idleConnTimeout() time.Duration {
  2845. if t.t1 != nil {
  2846. return t.t1.IdleConnTimeout
  2847. }
  2848. return 0
  2849. }
  2850. func traceGetConn(req *http.Request, hostPort string) {
  2851. trace := httptrace.ContextClientTrace(req.Context())
  2852. if trace == nil || trace.GetConn == nil {
  2853. return
  2854. }
  2855. trace.GetConn(hostPort)
  2856. }
  2857. func traceGotConn(req *http.Request, cc *ClientConn, reused bool) {
  2858. trace := httptrace.ContextClientTrace(req.Context())
  2859. if trace == nil || trace.GotConn == nil {
  2860. return
  2861. }
  2862. ci := httptrace.GotConnInfo{Conn: cc.tconn}
  2863. ci.Reused = reused
  2864. cc.mu.Lock()
  2865. ci.WasIdle = len(cc.streams) == 0 && reused
  2866. if ci.WasIdle && !cc.lastActive.IsZero() {
  2867. ci.IdleTime = time.Since(cc.lastActive)
  2868. }
  2869. cc.mu.Unlock()
  2870. trace.GotConn(ci)
  2871. }
  2872. func traceWroteHeaders(trace *httptrace.ClientTrace) {
  2873. if trace != nil && trace.WroteHeaders != nil {
  2874. trace.WroteHeaders()
  2875. }
  2876. }
  2877. func traceGot100Continue(trace *httptrace.ClientTrace) {
  2878. if trace != nil && trace.Got100Continue != nil {
  2879. trace.Got100Continue()
  2880. }
  2881. }
  2882. func traceWait100Continue(trace *httptrace.ClientTrace) {
  2883. if trace != nil && trace.Wait100Continue != nil {
  2884. trace.Wait100Continue()
  2885. }
  2886. }
  2887. func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
  2888. if trace != nil && trace.WroteRequest != nil {
  2889. trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
  2890. }
  2891. }
  2892. func traceFirstResponseByte(trace *httptrace.ClientTrace) {
  2893. if trace != nil && trace.GotFirstResponseByte != nil {
  2894. trace.GotFirstResponseByte()
  2895. }
  2896. }