transport.go 75 KB

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