transport.go 77 KB

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