transport.go 88 KB

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