transport.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  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. "crypto/tls"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "log"
  16. "math"
  17. "net"
  18. "net/http"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. "golang.org/x/net/http2/hpack"
  25. "golang.org/x/net/lex/httplex"
  26. )
  27. const (
  28. // transportDefaultConnFlow is how many connection-level flow control
  29. // tokens we give the server at start-up, past the default 64k.
  30. transportDefaultConnFlow = 1 << 30
  31. // transportDefaultStreamFlow is how many stream-level flow
  32. // control tokens we announce to the peer, and how many bytes
  33. // we buffer per stream.
  34. transportDefaultStreamFlow = 4 << 20
  35. // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
  36. // a stream-level WINDOW_UPDATE for at a time.
  37. transportDefaultStreamMinRefresh = 4 << 10
  38. defaultUserAgent = "Go-http-client/2.0"
  39. )
  40. // Transport is an HTTP/2 Transport.
  41. //
  42. // A Transport internally caches connections to servers. It is safe
  43. // for concurrent use by multiple goroutines.
  44. type Transport struct {
  45. // DialTLS specifies an optional dial function for creating
  46. // TLS connections for requests.
  47. //
  48. // If DialTLS is nil, tls.Dial is used.
  49. //
  50. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  51. // it will be used to set http.Response.TLS.
  52. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  53. // TLSClientConfig specifies the TLS configuration to use with
  54. // tls.Client. If nil, the default configuration is used.
  55. TLSClientConfig *tls.Config
  56. // ConnPool optionally specifies an alternate connection pool to use.
  57. // If nil, the default is used.
  58. ConnPool ClientConnPool
  59. // DisableCompression, if true, prevents the Transport from
  60. // requesting compression with an "Accept-Encoding: gzip"
  61. // request header when the Request contains no existing
  62. // Accept-Encoding value. If the Transport requests gzip on
  63. // its own and gets a gzipped response, it's transparently
  64. // decoded in the Response.Body. However, if the user
  65. // explicitly requested gzip it is not automatically
  66. // uncompressed.
  67. DisableCompression bool
  68. // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
  69. // plain-text "http" scheme. Note that this does not enable h2c support.
  70. AllowHTTP bool
  71. // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
  72. // send in the initial settings frame. It is how many bytes
  73. // of response headers are allow. Unlike the http2 spec, zero here
  74. // means to use a default limit (currently 10MB). If you actually
  75. // want to advertise an ulimited value to the peer, Transport
  76. // interprets the highest possible value here (0xffffffff or 1<<32-1)
  77. // to mean no limit.
  78. MaxHeaderListSize uint32
  79. // t1, if non-nil, is the standard library Transport using
  80. // this transport. Its settings are used (but not its
  81. // RoundTrip method, etc).
  82. t1 *http.Transport
  83. connPoolOnce sync.Once
  84. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  85. }
  86. func (t *Transport) maxHeaderListSize() uint32 {
  87. if t.MaxHeaderListSize == 0 {
  88. return 10 << 20
  89. }
  90. if t.MaxHeaderListSize == 0xffffffff {
  91. return 0
  92. }
  93. return t.MaxHeaderListSize
  94. }
  95. func (t *Transport) disableCompression() bool {
  96. return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
  97. }
  98. var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6")
  99. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  100. // It requires Go 1.6 or later and returns an error if the net/http package is too old
  101. // or if t1 has already been HTTP/2-enabled.
  102. func ConfigureTransport(t1 *http.Transport) error {
  103. _, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go
  104. return err
  105. }
  106. func (t *Transport) connPool() ClientConnPool {
  107. t.connPoolOnce.Do(t.initConnPool)
  108. return t.connPoolOrDef
  109. }
  110. func (t *Transport) initConnPool() {
  111. if t.ConnPool != nil {
  112. t.connPoolOrDef = t.ConnPool
  113. } else {
  114. t.connPoolOrDef = &clientConnPool{t: t}
  115. }
  116. }
  117. // ClientConn is the state of a single HTTP/2 client connection to an
  118. // HTTP/2 server.
  119. type ClientConn struct {
  120. t *Transport
  121. tconn net.Conn // usually *tls.Conn, except specialized impls
  122. tlsState *tls.ConnectionState // nil only for specialized impls
  123. singleUse bool // whether being used for a single http.Request
  124. // readLoop goroutine fields:
  125. readerDone chan struct{} // closed on error
  126. readerErr error // set before readerDone is closed
  127. mu sync.Mutex // guards following
  128. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  129. flow flow // our conn-level flow control quota (cs.flow is per stream)
  130. inflow flow // peer's conn-level flow control
  131. closed bool
  132. wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
  133. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  134. goAwayDebug string // goAway frame's debug data, retained as a string
  135. streams map[uint32]*clientStream // client-initiated
  136. nextStreamID uint32
  137. bw *bufio.Writer
  138. br *bufio.Reader
  139. fr *Framer
  140. lastActive time.Time
  141. // Settings from peer: (also guarded by mu)
  142. maxFrameSize uint32
  143. maxConcurrentStreams uint32
  144. initialWindowSize uint32
  145. hbuf bytes.Buffer // HPACK encoder writes into this
  146. henc *hpack.Encoder
  147. freeBuf [][]byte
  148. wmu sync.Mutex // held while writing; acquire AFTER mu if holding both
  149. werr error // first write error that has occurred
  150. }
  151. // clientStream is the state for a single HTTP/2 stream. One of these
  152. // is created for each Transport.RoundTrip call.
  153. type clientStream struct {
  154. cc *ClientConn
  155. req *http.Request
  156. trace *clientTrace // or nil
  157. ID uint32
  158. resc chan resAndError
  159. bufPipe pipe // buffered pipe with the flow-controlled response payload
  160. requestedGzip bool
  161. on100 func() // optional code to run if get a 100 continue response
  162. flow flow // guarded by cc.mu
  163. inflow flow // guarded by cc.mu
  164. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  165. readErr error // sticky read error; owned by transportResponseBody.Read
  166. stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
  167. peerReset chan struct{} // closed on peer reset
  168. resetErr error // populated before peerReset is closed
  169. done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
  170. // owned by clientConnReadLoop:
  171. firstByte bool // got the first response byte
  172. pastHeaders bool // got first MetaHeadersFrame (actual headers)
  173. pastTrailers bool // got optional second MetaHeadersFrame (trailers)
  174. trailer http.Header // accumulated trailers
  175. resTrailer *http.Header // client's Response.Trailer
  176. }
  177. // awaitRequestCancel runs in its own goroutine and waits for the user
  178. // to cancel a RoundTrip request, its context to expire, or for the
  179. // request to be done (any way it might be removed from the cc.streams
  180. // map: peer reset, successful completion, TCP connection breakage,
  181. // etc)
  182. func (cs *clientStream) awaitRequestCancel(req *http.Request) {
  183. ctx := reqContext(req)
  184. if req.Cancel == nil && ctx.Done() == nil {
  185. return
  186. }
  187. select {
  188. case <-req.Cancel:
  189. cs.bufPipe.CloseWithError(errRequestCanceled)
  190. cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  191. case <-ctx.Done():
  192. cs.bufPipe.CloseWithError(ctx.Err())
  193. cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  194. case <-cs.done:
  195. }
  196. }
  197. // checkResetOrDone reports any error sent in a RST_STREAM frame by the
  198. // server, or errStreamClosed if the stream is complete.
  199. func (cs *clientStream) checkResetOrDone() error {
  200. select {
  201. case <-cs.peerReset:
  202. return cs.resetErr
  203. case <-cs.done:
  204. return errStreamClosed
  205. default:
  206. return nil
  207. }
  208. }
  209. func (cs *clientStream) abortRequestBodyWrite(err error) {
  210. if err == nil {
  211. panic("nil error")
  212. }
  213. cc := cs.cc
  214. cc.mu.Lock()
  215. cs.stopReqBody = err
  216. cc.cond.Broadcast()
  217. cc.mu.Unlock()
  218. }
  219. type stickyErrWriter struct {
  220. w io.Writer
  221. err *error
  222. }
  223. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  224. if *sew.err != nil {
  225. return 0, *sew.err
  226. }
  227. n, err = sew.w.Write(p)
  228. *sew.err = err
  229. return
  230. }
  231. var ErrNoCachedConn = errors.New("http2: no cached connection was available")
  232. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  233. type RoundTripOpt struct {
  234. // OnlyCachedConn controls whether RoundTripOpt may
  235. // create a new TCP connection. If set true and
  236. // no cached connection is available, RoundTripOpt
  237. // will return ErrNoCachedConn.
  238. OnlyCachedConn bool
  239. }
  240. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  241. return t.RoundTripOpt(req, RoundTripOpt{})
  242. }
  243. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  244. // and returns a host:port. The port 443 is added if needed.
  245. func authorityAddr(scheme string, authority string) (addr string) {
  246. if _, _, err := net.SplitHostPort(authority); err == nil {
  247. return authority
  248. }
  249. port := "443"
  250. if scheme == "http" {
  251. port = "80"
  252. }
  253. return net.JoinHostPort(authority, port)
  254. }
  255. // RoundTripOpt is like RoundTrip, but takes options.
  256. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  257. if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
  258. return nil, errors.New("http2: unsupported scheme")
  259. }
  260. addr := authorityAddr(req.URL.Scheme, req.URL.Host)
  261. for {
  262. cc, err := t.connPool().GetClientConn(req, addr)
  263. if err != nil {
  264. t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
  265. return nil, err
  266. }
  267. traceGotConn(req, cc)
  268. res, err := cc.RoundTrip(req)
  269. if shouldRetryRequest(req, err) {
  270. continue
  271. }
  272. if err != nil {
  273. t.vlogf("RoundTrip failure: %v", err)
  274. return nil, err
  275. }
  276. return res, nil
  277. }
  278. }
  279. // CloseIdleConnections closes any connections which were previously
  280. // connected from previous requests but are now sitting idle.
  281. // It does not interrupt any connections currently in use.
  282. func (t *Transport) CloseIdleConnections() {
  283. if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
  284. cp.closeIdleConnections()
  285. }
  286. }
  287. var (
  288. errClientConnClosed = errors.New("http2: client conn is closed")
  289. errClientConnUnusable = errors.New("http2: client conn not usable")
  290. )
  291. func shouldRetryRequest(req *http.Request, err error) bool {
  292. // TODO: retry GET requests (no bodies) more aggressively, if shutdown
  293. // before response.
  294. return err == errClientConnUnusable
  295. }
  296. func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
  297. host, _, err := net.SplitHostPort(addr)
  298. if err != nil {
  299. return nil, err
  300. }
  301. tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
  302. if err != nil {
  303. return nil, err
  304. }
  305. return t.newClientConn(tconn, singleUse)
  306. }
  307. func (t *Transport) newTLSConfig(host string) *tls.Config {
  308. cfg := new(tls.Config)
  309. if t.TLSClientConfig != nil {
  310. *cfg = *t.TLSClientConfig
  311. }
  312. if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
  313. cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
  314. }
  315. if cfg.ServerName == "" {
  316. cfg.ServerName = host
  317. }
  318. return cfg
  319. }
  320. func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
  321. if t.DialTLS != nil {
  322. return t.DialTLS
  323. }
  324. return t.dialTLSDefault
  325. }
  326. func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
  327. cn, err := tls.Dial(network, addr, cfg)
  328. if err != nil {
  329. return nil, err
  330. }
  331. if err := cn.Handshake(); err != nil {
  332. return nil, err
  333. }
  334. if !cfg.InsecureSkipVerify {
  335. if err := cn.VerifyHostname(cfg.ServerName); err != nil {
  336. return nil, err
  337. }
  338. }
  339. state := cn.ConnectionState()
  340. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  341. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  342. }
  343. if !state.NegotiatedProtocolIsMutual {
  344. return nil, errors.New("http2: could not negotiate protocol mutually")
  345. }
  346. return cn, nil
  347. }
  348. // disableKeepAlives reports whether connections should be closed as
  349. // soon as possible after handling the first request.
  350. func (t *Transport) disableKeepAlives() bool {
  351. return t.t1 != nil && t.t1.DisableKeepAlives
  352. }
  353. func (t *Transport) expectContinueTimeout() time.Duration {
  354. if t.t1 == nil {
  355. return 0
  356. }
  357. return transportExpectContinueTimeout(t.t1)
  358. }
  359. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  360. return t.newClientConn(c, false)
  361. }
  362. func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
  363. cc := &ClientConn{
  364. t: t,
  365. tconn: c,
  366. readerDone: make(chan struct{}),
  367. nextStreamID: 1,
  368. maxFrameSize: 16 << 10, // spec default
  369. initialWindowSize: 65535, // spec default
  370. maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
  371. streams: make(map[uint32]*clientStream),
  372. singleUse: singleUse,
  373. wantSettingsAck: true,
  374. }
  375. if VerboseLogs {
  376. t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
  377. }
  378. cc.cond = sync.NewCond(&cc.mu)
  379. cc.flow.add(int32(initialWindowSize))
  380. // TODO: adjust this writer size to account for frame size +
  381. // MTU + crypto/tls record padding.
  382. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
  383. cc.br = bufio.NewReader(c)
  384. cc.fr = NewFramer(cc.bw, cc.br)
  385. cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  386. cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
  387. // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
  388. // henc in response to SETTINGS frames?
  389. cc.henc = hpack.NewEncoder(&cc.hbuf)
  390. if cs, ok := c.(connectionStater); ok {
  391. state := cs.ConnectionState()
  392. cc.tlsState = &state
  393. }
  394. initialSettings := []Setting{
  395. {ID: SettingEnablePush, Val: 0},
  396. {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  397. }
  398. if max := t.maxHeaderListSize(); max != 0 {
  399. initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
  400. }
  401. cc.bw.Write(clientPreface)
  402. cc.fr.WriteSettings(initialSettings...)
  403. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  404. cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
  405. cc.bw.Flush()
  406. if cc.werr != nil {
  407. return nil, cc.werr
  408. }
  409. go cc.readLoop()
  410. return cc, nil
  411. }
  412. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  413. cc.mu.Lock()
  414. defer cc.mu.Unlock()
  415. old := cc.goAway
  416. cc.goAway = f
  417. // Merge the previous and current GoAway error frames.
  418. if cc.goAwayDebug == "" {
  419. cc.goAwayDebug = string(f.DebugData())
  420. }
  421. if old != nil && old.ErrCode != ErrCodeNo {
  422. cc.goAway.ErrCode = old.ErrCode
  423. }
  424. }
  425. func (cc *ClientConn) CanTakeNewRequest() bool {
  426. cc.mu.Lock()
  427. defer cc.mu.Unlock()
  428. return cc.canTakeNewRequestLocked()
  429. }
  430. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  431. if cc.singleUse && cc.nextStreamID > 1 {
  432. return false
  433. }
  434. return cc.goAway == nil && !cc.closed &&
  435. int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) &&
  436. cc.nextStreamID < math.MaxInt32
  437. }
  438. func (cc *ClientConn) closeIfIdle() {
  439. cc.mu.Lock()
  440. if len(cc.streams) > 0 {
  441. cc.mu.Unlock()
  442. return
  443. }
  444. cc.closed = true
  445. nextID := cc.nextStreamID
  446. // TODO: do clients send GOAWAY too? maybe? Just Close:
  447. cc.mu.Unlock()
  448. if VerboseLogs {
  449. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
  450. }
  451. cc.tconn.Close()
  452. }
  453. const maxAllocFrameSize = 512 << 10
  454. // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  455. // They're capped at the min of the peer's max frame size or 512KB
  456. // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  457. // bufers.
  458. func (cc *ClientConn) frameScratchBuffer() []byte {
  459. cc.mu.Lock()
  460. size := cc.maxFrameSize
  461. if size > maxAllocFrameSize {
  462. size = maxAllocFrameSize
  463. }
  464. for i, buf := range cc.freeBuf {
  465. if len(buf) >= int(size) {
  466. cc.freeBuf[i] = nil
  467. cc.mu.Unlock()
  468. return buf[:size]
  469. }
  470. }
  471. cc.mu.Unlock()
  472. return make([]byte, size)
  473. }
  474. func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  475. cc.mu.Lock()
  476. defer cc.mu.Unlock()
  477. const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  478. if len(cc.freeBuf) < maxBufs {
  479. cc.freeBuf = append(cc.freeBuf, buf)
  480. return
  481. }
  482. for i, old := range cc.freeBuf {
  483. if old == nil {
  484. cc.freeBuf[i] = buf
  485. return
  486. }
  487. }
  488. // forget about it.
  489. }
  490. // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  491. // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  492. var errRequestCanceled = errors.New("net/http: request canceled")
  493. func commaSeparatedTrailers(req *http.Request) (string, error) {
  494. keys := make([]string, 0, len(req.Trailer))
  495. for k := range req.Trailer {
  496. k = http.CanonicalHeaderKey(k)
  497. switch k {
  498. case "Transfer-Encoding", "Trailer", "Content-Length":
  499. return "", &badStringError{"invalid Trailer key", k}
  500. }
  501. keys = append(keys, k)
  502. }
  503. if len(keys) > 0 {
  504. sort.Strings(keys)
  505. // TODO: could do better allocation-wise here, but trailers are rare,
  506. // so being lazy for now.
  507. return strings.Join(keys, ","), nil
  508. }
  509. return "", nil
  510. }
  511. func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  512. if cc.t.t1 != nil {
  513. return cc.t.t1.ResponseHeaderTimeout
  514. }
  515. // No way to do this (yet?) with just an http2.Transport. Probably
  516. // no need. Request.Cancel this is the new way. We only need to support
  517. // this for compatibility with the old http.Transport fields when
  518. // we're doing transparent http2.
  519. return 0
  520. }
  521. // checkConnHeaders checks whether req has any invalid connection-level headers.
  522. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  523. // Certain headers are special-cased as okay but not transmitted later.
  524. func checkConnHeaders(req *http.Request) error {
  525. if v := req.Header.Get("Upgrade"); v != "" {
  526. return errors.New("http2: invalid Upgrade request header")
  527. }
  528. if v := req.Header.Get("Transfer-Encoding"); (v != "" && v != "chunked") || len(req.Header["Transfer-Encoding"]) > 1 {
  529. return errors.New("http2: invalid Transfer-Encoding request header")
  530. }
  531. if v := req.Header.Get("Connection"); (v != "" && v != "close" && v != "keep-alive") || len(req.Header["Connection"]) > 1 {
  532. return errors.New("http2: invalid Connection request header")
  533. }
  534. return nil
  535. }
  536. // actualContentLength returns a sanitized version of
  537. // req.ContentLength, where 0 actually means zero (not unknown) and -1
  538. // means unknown.
  539. func actualContentLength(req *http.Request) int64 {
  540. if req.Body == nil {
  541. return 0
  542. }
  543. if req.ContentLength != 0 {
  544. return req.ContentLength
  545. }
  546. return -1
  547. }
  548. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  549. if err := checkConnHeaders(req); err != nil {
  550. return nil, err
  551. }
  552. trailers, err := commaSeparatedTrailers(req)
  553. if err != nil {
  554. return nil, err
  555. }
  556. hasTrailers := trailers != ""
  557. cc.mu.Lock()
  558. cc.lastActive = time.Now()
  559. if cc.closed || !cc.canTakeNewRequestLocked() {
  560. cc.mu.Unlock()
  561. return nil, errClientConnUnusable
  562. }
  563. body := req.Body
  564. hasBody := body != nil
  565. contentLen := actualContentLength(req)
  566. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  567. var requestedGzip bool
  568. if !cc.t.disableCompression() &&
  569. req.Header.Get("Accept-Encoding") == "" &&
  570. req.Header.Get("Range") == "" &&
  571. req.Method != "HEAD" {
  572. // Request gzip only, not deflate. Deflate is ambiguous and
  573. // not as universally supported anyway.
  574. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  575. //
  576. // Note that we don't request this for HEAD requests,
  577. // due to a bug in nginx:
  578. // http://trac.nginx.org/nginx/ticket/358
  579. // https://golang.org/issue/5522
  580. //
  581. // We don't request gzip if the request is for a range, since
  582. // auto-decoding a portion of a gzipped document will just fail
  583. // anyway. See https://golang.org/issue/8923
  584. requestedGzip = true
  585. }
  586. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  587. // sent by writeRequestBody below, along with any Trailers,
  588. // again in form HEADERS{1}, CONTINUATION{0,})
  589. hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
  590. if err != nil {
  591. cc.mu.Unlock()
  592. return nil, err
  593. }
  594. cs := cc.newStream()
  595. cs.req = req
  596. cs.trace = requestTrace(req)
  597. cs.requestedGzip = requestedGzip
  598. bodyWriter := cc.t.getBodyWriterState(cs, body)
  599. cs.on100 = bodyWriter.on100
  600. cc.wmu.Lock()
  601. endStream := !hasBody && !hasTrailers
  602. werr := cc.writeHeaders(cs.ID, endStream, hdrs)
  603. cc.wmu.Unlock()
  604. traceWroteHeaders(cs.trace)
  605. cc.mu.Unlock()
  606. if werr != nil {
  607. if hasBody {
  608. req.Body.Close() // per RoundTripper contract
  609. bodyWriter.cancel()
  610. }
  611. cc.forgetStreamID(cs.ID)
  612. // Don't bother sending a RST_STREAM (our write already failed;
  613. // no need to keep writing)
  614. traceWroteRequest(cs.trace, werr)
  615. return nil, werr
  616. }
  617. var respHeaderTimer <-chan time.Time
  618. if hasBody {
  619. bodyWriter.scheduleBodyWrite()
  620. } else {
  621. traceWroteRequest(cs.trace, nil)
  622. if d := cc.responseHeaderTimeout(); d != 0 {
  623. timer := time.NewTimer(d)
  624. defer timer.Stop()
  625. respHeaderTimer = timer.C
  626. }
  627. }
  628. readLoopResCh := cs.resc
  629. bodyWritten := false
  630. ctx := reqContext(req)
  631. handleReadLoopResponse := func(re resAndError) (*http.Response, error) {
  632. res := re.res
  633. if re.err != nil || res.StatusCode > 299 {
  634. // On error or status code 3xx, 4xx, 5xx, etc abort any
  635. // ongoing write, assuming that the server doesn't care
  636. // about our request body. If the server replied with 1xx or
  637. // 2xx, however, then assume the server DOES potentially
  638. // want our body (e.g. full-duplex streaming:
  639. // golang.org/issue/13444). If it turns out the server
  640. // doesn't, they'll RST_STREAM us soon enough. This is a
  641. // heuristic to avoid adding knobs to Transport. Hopefully
  642. // we can keep it.
  643. bodyWriter.cancel()
  644. cs.abortRequestBodyWrite(errStopReqBodyWrite)
  645. }
  646. if re.err != nil {
  647. cc.forgetStreamID(cs.ID)
  648. return nil, re.err
  649. }
  650. res.Request = req
  651. res.TLS = cc.tlsState
  652. return res, nil
  653. }
  654. for {
  655. select {
  656. case re := <-readLoopResCh:
  657. return handleReadLoopResponse(re)
  658. case <-respHeaderTimer:
  659. cc.forgetStreamID(cs.ID)
  660. if !hasBody || bodyWritten {
  661. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  662. } else {
  663. bodyWriter.cancel()
  664. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  665. }
  666. return nil, errTimeout
  667. case <-ctx.Done():
  668. cc.forgetStreamID(cs.ID)
  669. if !hasBody || bodyWritten {
  670. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  671. } else {
  672. bodyWriter.cancel()
  673. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  674. }
  675. return nil, ctx.Err()
  676. case <-req.Cancel:
  677. cc.forgetStreamID(cs.ID)
  678. if !hasBody || bodyWritten {
  679. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  680. } else {
  681. bodyWriter.cancel()
  682. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  683. }
  684. return nil, errRequestCanceled
  685. case <-cs.peerReset:
  686. // processResetStream already removed the
  687. // stream from the streams map; no need for
  688. // forgetStreamID.
  689. return nil, cs.resetErr
  690. case err := <-bodyWriter.resc:
  691. // Prefer the read loop's response, if available. Issue 16102.
  692. select {
  693. case re := <-readLoopResCh:
  694. return handleReadLoopResponse(re)
  695. default:
  696. }
  697. if err != nil {
  698. return nil, err
  699. }
  700. bodyWritten = true
  701. if d := cc.responseHeaderTimeout(); d != 0 {
  702. timer := time.NewTimer(d)
  703. defer timer.Stop()
  704. respHeaderTimer = timer.C
  705. }
  706. }
  707. }
  708. }
  709. // requires cc.wmu be held
  710. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error {
  711. first := true // first frame written (HEADERS is first, then CONTINUATION)
  712. frameSize := int(cc.maxFrameSize)
  713. for len(hdrs) > 0 && cc.werr == nil {
  714. chunk := hdrs
  715. if len(chunk) > frameSize {
  716. chunk = chunk[:frameSize]
  717. }
  718. hdrs = hdrs[len(chunk):]
  719. endHeaders := len(hdrs) == 0
  720. if first {
  721. cc.fr.WriteHeaders(HeadersFrameParam{
  722. StreamID: streamID,
  723. BlockFragment: chunk,
  724. EndStream: endStream,
  725. EndHeaders: endHeaders,
  726. })
  727. first = false
  728. } else {
  729. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  730. }
  731. }
  732. // TODO(bradfitz): this Flush could potentially block (as
  733. // could the WriteHeaders call(s) above), which means they
  734. // wouldn't respond to Request.Cancel being readable. That's
  735. // rare, but this should probably be in a goroutine.
  736. cc.bw.Flush()
  737. return cc.werr
  738. }
  739. // internal error values; they don't escape to callers
  740. var (
  741. // abort request body write; don't send cancel
  742. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  743. // abort request body write, but send stream reset of cancel.
  744. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  745. )
  746. func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  747. cc := cs.cc
  748. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  749. buf := cc.frameScratchBuffer()
  750. defer cc.putFrameScratchBuffer(buf)
  751. defer func() {
  752. traceWroteRequest(cs.trace, err)
  753. // TODO: write h12Compare test showing whether
  754. // Request.Body is closed by the Transport,
  755. // and in multiple cases: server replies <=299 and >299
  756. // while still writing request body
  757. cerr := bodyCloser.Close()
  758. if err == nil {
  759. err = cerr
  760. }
  761. }()
  762. req := cs.req
  763. hasTrailers := req.Trailer != nil
  764. var sawEOF bool
  765. for !sawEOF {
  766. n, err := body.Read(buf)
  767. if err == io.EOF {
  768. sawEOF = true
  769. err = nil
  770. } else if err != nil {
  771. return err
  772. }
  773. remain := buf[:n]
  774. for len(remain) > 0 && err == nil {
  775. var allowed int32
  776. allowed, err = cs.awaitFlowControl(len(remain))
  777. switch {
  778. case err == errStopReqBodyWrite:
  779. return err
  780. case err == errStopReqBodyWriteAndCancel:
  781. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  782. return err
  783. case err != nil:
  784. return err
  785. }
  786. cc.wmu.Lock()
  787. data := remain[:allowed]
  788. remain = remain[allowed:]
  789. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  790. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  791. if err == nil {
  792. // TODO(bradfitz): this flush is for latency, not bandwidth.
  793. // Most requests won't need this. Make this opt-in or
  794. // opt-out? Use some heuristic on the body type? Nagel-like
  795. // timers? Based on 'n'? Only last chunk of this for loop,
  796. // unless flow control tokens are low? For now, always.
  797. // If we change this, see comment below.
  798. err = cc.bw.Flush()
  799. }
  800. cc.wmu.Unlock()
  801. }
  802. if err != nil {
  803. return err
  804. }
  805. }
  806. if sentEnd {
  807. // Already sent END_STREAM (which implies we have no
  808. // trailers) and flushed, because currently all
  809. // WriteData frames above get a flush. So we're done.
  810. return nil
  811. }
  812. var trls []byte
  813. if hasTrailers {
  814. cc.mu.Lock()
  815. defer cc.mu.Unlock()
  816. trls = cc.encodeTrailers(req)
  817. }
  818. cc.wmu.Lock()
  819. defer cc.wmu.Unlock()
  820. // Two ways to send END_STREAM: either with trailers, or
  821. // with an empty DATA frame.
  822. if len(trls) > 0 {
  823. err = cc.writeHeaders(cs.ID, true, trls)
  824. } else {
  825. err = cc.fr.WriteData(cs.ID, true, nil)
  826. }
  827. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  828. err = ferr
  829. }
  830. return err
  831. }
  832. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  833. // control tokens from the server.
  834. // It returns either the non-zero number of tokens taken or an error
  835. // if the stream is dead.
  836. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  837. cc := cs.cc
  838. cc.mu.Lock()
  839. defer cc.mu.Unlock()
  840. for {
  841. if cc.closed {
  842. return 0, errClientConnClosed
  843. }
  844. if cs.stopReqBody != nil {
  845. return 0, cs.stopReqBody
  846. }
  847. if err := cs.checkResetOrDone(); err != nil {
  848. return 0, err
  849. }
  850. if a := cs.flow.available(); a > 0 {
  851. take := a
  852. if int(take) > maxBytes {
  853. take = int32(maxBytes) // can't truncate int; take is int32
  854. }
  855. if take > int32(cc.maxFrameSize) {
  856. take = int32(cc.maxFrameSize)
  857. }
  858. cs.flow.take(take)
  859. return take, nil
  860. }
  861. cc.cond.Wait()
  862. }
  863. }
  864. type badStringError struct {
  865. what string
  866. str string
  867. }
  868. func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  869. // requires cc.mu be held.
  870. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  871. cc.hbuf.Reset()
  872. host := req.Host
  873. if host == "" {
  874. host = req.URL.Host
  875. }
  876. // Check for any invalid headers and return an error before we
  877. // potentially pollute our hpack state. (We want to be able to
  878. // continue to reuse the hpack encoder for future requests)
  879. for k, vv := range req.Header {
  880. if !httplex.ValidHeaderFieldName(k) {
  881. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  882. }
  883. for _, v := range vv {
  884. if !httplex.ValidHeaderFieldValue(v) {
  885. return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  886. }
  887. }
  888. }
  889. // 8.1.2.3 Request Pseudo-Header Fields
  890. // The :path pseudo-header field includes the path and query parts of the
  891. // target URI (the path-absolute production and optionally a '?' character
  892. // followed by the query production (see Sections 3.3 and 3.4 of
  893. // [RFC3986]).
  894. cc.writeHeader(":authority", host)
  895. cc.writeHeader(":method", req.Method)
  896. if req.Method != "CONNECT" {
  897. cc.writeHeader(":path", req.URL.RequestURI())
  898. cc.writeHeader(":scheme", "https")
  899. }
  900. if trailers != "" {
  901. cc.writeHeader("trailer", trailers)
  902. }
  903. var didUA bool
  904. for k, vv := range req.Header {
  905. lowKey := strings.ToLower(k)
  906. switch lowKey {
  907. case "host", "content-length":
  908. // Host is :authority, already sent.
  909. // Content-Length is automatic, set below.
  910. continue
  911. case "connection", "proxy-connection", "transfer-encoding", "upgrade", "keep-alive":
  912. // Per 8.1.2.2 Connection-Specific Header
  913. // Fields, don't send connection-specific
  914. // fields. We have already checked if any
  915. // are error-worthy so just ignore the rest.
  916. continue
  917. case "user-agent":
  918. // Match Go's http1 behavior: at most one
  919. // User-Agent. If set to nil or empty string,
  920. // then omit it. Otherwise if not mentioned,
  921. // include the default (below).
  922. didUA = true
  923. if len(vv) < 1 {
  924. continue
  925. }
  926. vv = vv[:1]
  927. if vv[0] == "" {
  928. continue
  929. }
  930. }
  931. for _, v := range vv {
  932. cc.writeHeader(lowKey, v)
  933. }
  934. }
  935. if shouldSendReqContentLength(req.Method, contentLength) {
  936. cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10))
  937. }
  938. if addGzipHeader {
  939. cc.writeHeader("accept-encoding", "gzip")
  940. }
  941. if !didUA {
  942. cc.writeHeader("user-agent", defaultUserAgent)
  943. }
  944. return cc.hbuf.Bytes(), nil
  945. }
  946. // shouldSendReqContentLength reports whether the http2.Transport should send
  947. // a "content-length" request header. This logic is basically a copy of the net/http
  948. // transferWriter.shouldSendContentLength.
  949. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  950. // -1 means unknown.
  951. func shouldSendReqContentLength(method string, contentLength int64) bool {
  952. if contentLength > 0 {
  953. return true
  954. }
  955. if contentLength < 0 {
  956. return false
  957. }
  958. // For zero bodies, whether we send a content-length depends on the method.
  959. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  960. switch method {
  961. case "POST", "PUT", "PATCH":
  962. return true
  963. default:
  964. return false
  965. }
  966. }
  967. // requires cc.mu be held.
  968. func (cc *ClientConn) encodeTrailers(req *http.Request) []byte {
  969. cc.hbuf.Reset()
  970. for k, vv := range req.Trailer {
  971. // Transfer-Encoding, etc.. have already been filter at the
  972. // start of RoundTrip
  973. lowKey := strings.ToLower(k)
  974. for _, v := range vv {
  975. cc.writeHeader(lowKey, v)
  976. }
  977. }
  978. return cc.hbuf.Bytes()
  979. }
  980. func (cc *ClientConn) writeHeader(name, value string) {
  981. if VerboseLogs {
  982. log.Printf("http2: Transport encoding header %q = %q", name, value)
  983. }
  984. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  985. }
  986. type resAndError struct {
  987. res *http.Response
  988. err error
  989. }
  990. // requires cc.mu be held.
  991. func (cc *ClientConn) newStream() *clientStream {
  992. cs := &clientStream{
  993. cc: cc,
  994. ID: cc.nextStreamID,
  995. resc: make(chan resAndError, 1),
  996. peerReset: make(chan struct{}),
  997. done: make(chan struct{}),
  998. }
  999. cs.flow.add(int32(cc.initialWindowSize))
  1000. cs.flow.setConnFlow(&cc.flow)
  1001. cs.inflow.add(transportDefaultStreamFlow)
  1002. cs.inflow.setConnFlow(&cc.inflow)
  1003. cc.nextStreamID += 2
  1004. cc.streams[cs.ID] = cs
  1005. return cs
  1006. }
  1007. func (cc *ClientConn) forgetStreamID(id uint32) {
  1008. cc.streamByID(id, true)
  1009. }
  1010. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1011. cc.mu.Lock()
  1012. defer cc.mu.Unlock()
  1013. cs := cc.streams[id]
  1014. if andRemove && cs != nil && !cc.closed {
  1015. cc.lastActive = time.Now()
  1016. delete(cc.streams, id)
  1017. close(cs.done)
  1018. cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  1019. }
  1020. return cs
  1021. }
  1022. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1023. type clientConnReadLoop struct {
  1024. cc *ClientConn
  1025. activeRes map[uint32]*clientStream // keyed by streamID
  1026. closeWhenIdle bool
  1027. }
  1028. // readLoop runs in its own goroutine and reads and dispatches frames.
  1029. func (cc *ClientConn) readLoop() {
  1030. rl := &clientConnReadLoop{
  1031. cc: cc,
  1032. activeRes: make(map[uint32]*clientStream),
  1033. }
  1034. defer rl.cleanup()
  1035. cc.readerErr = rl.run()
  1036. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1037. cc.wmu.Lock()
  1038. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1039. cc.wmu.Unlock()
  1040. }
  1041. }
  1042. // GoAwayError is returned by the Transport when the server closes the
  1043. // TCP connection after sending a GOAWAY frame.
  1044. type GoAwayError struct {
  1045. LastStreamID uint32
  1046. ErrCode ErrCode
  1047. DebugData string
  1048. }
  1049. func (e GoAwayError) Error() string {
  1050. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1051. e.LastStreamID, e.ErrCode, e.DebugData)
  1052. }
  1053. func isEOFOrNetReadError(err error) bool {
  1054. if err == io.EOF {
  1055. return true
  1056. }
  1057. ne, ok := err.(*net.OpError)
  1058. return ok && ne.Op == "read"
  1059. }
  1060. func (rl *clientConnReadLoop) cleanup() {
  1061. cc := rl.cc
  1062. defer cc.tconn.Close()
  1063. defer cc.t.connPool().MarkDead(cc)
  1064. defer close(cc.readerDone)
  1065. // Close any response bodies if the server closes prematurely.
  1066. // TODO: also do this if we've written the headers but not
  1067. // gotten a response yet.
  1068. err := cc.readerErr
  1069. cc.mu.Lock()
  1070. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1071. err = GoAwayError{
  1072. LastStreamID: cc.goAway.LastStreamID,
  1073. ErrCode: cc.goAway.ErrCode,
  1074. DebugData: cc.goAwayDebug,
  1075. }
  1076. } else if err == io.EOF {
  1077. err = io.ErrUnexpectedEOF
  1078. }
  1079. for _, cs := range rl.activeRes {
  1080. cs.bufPipe.CloseWithError(err)
  1081. }
  1082. for _, cs := range cc.streams {
  1083. select {
  1084. case cs.resc <- resAndError{err: err}:
  1085. default:
  1086. }
  1087. close(cs.done)
  1088. }
  1089. cc.closed = true
  1090. cc.cond.Broadcast()
  1091. cc.mu.Unlock()
  1092. }
  1093. func (rl *clientConnReadLoop) run() error {
  1094. cc := rl.cc
  1095. rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1096. gotReply := false // ever saw a HEADERS reply
  1097. gotSettings := false
  1098. for {
  1099. f, err := cc.fr.ReadFrame()
  1100. if err != nil {
  1101. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1102. }
  1103. if se, ok := err.(StreamError); ok {
  1104. if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil {
  1105. cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1106. if se.Cause == nil {
  1107. se.Cause = cc.fr.errDetail
  1108. }
  1109. rl.endStreamError(cs, se)
  1110. }
  1111. continue
  1112. } else if err != nil {
  1113. return err
  1114. }
  1115. if VerboseLogs {
  1116. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1117. }
  1118. if !gotSettings {
  1119. if _, ok := f.(*SettingsFrame); !ok {
  1120. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1121. return ConnectionError(ErrCodeProtocol)
  1122. }
  1123. gotSettings = true
  1124. }
  1125. maybeIdle := false // whether frame might transition us to idle
  1126. switch f := f.(type) {
  1127. case *MetaHeadersFrame:
  1128. err = rl.processHeaders(f)
  1129. maybeIdle = true
  1130. gotReply = true
  1131. case *DataFrame:
  1132. err = rl.processData(f)
  1133. maybeIdle = true
  1134. case *GoAwayFrame:
  1135. err = rl.processGoAway(f)
  1136. maybeIdle = true
  1137. case *RSTStreamFrame:
  1138. err = rl.processResetStream(f)
  1139. maybeIdle = true
  1140. case *SettingsFrame:
  1141. err = rl.processSettings(f)
  1142. case *PushPromiseFrame:
  1143. err = rl.processPushPromise(f)
  1144. case *WindowUpdateFrame:
  1145. err = rl.processWindowUpdate(f)
  1146. case *PingFrame:
  1147. err = rl.processPing(f)
  1148. default:
  1149. cc.logf("Transport: unhandled response frame type %T", f)
  1150. }
  1151. if err != nil {
  1152. if VerboseLogs {
  1153. cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  1154. }
  1155. return err
  1156. }
  1157. if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 {
  1158. cc.closeIfIdle()
  1159. }
  1160. }
  1161. }
  1162. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  1163. cc := rl.cc
  1164. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1165. if cs == nil {
  1166. // We'd get here if we canceled a request while the
  1167. // server had its response still in flight. So if this
  1168. // was just something we canceled, ignore it.
  1169. return nil
  1170. }
  1171. if !cs.firstByte {
  1172. if cs.trace != nil {
  1173. // TODO(bradfitz): move first response byte earlier,
  1174. // when we first read the 9 byte header, not waiting
  1175. // until all the HEADERS+CONTINUATION frames have been
  1176. // merged. This works for now.
  1177. traceFirstResponseByte(cs.trace)
  1178. }
  1179. cs.firstByte = true
  1180. }
  1181. if !cs.pastHeaders {
  1182. cs.pastHeaders = true
  1183. } else {
  1184. return rl.processTrailers(cs, f)
  1185. }
  1186. res, err := rl.handleResponse(cs, f)
  1187. if err != nil {
  1188. if _, ok := err.(ConnectionError); ok {
  1189. return err
  1190. }
  1191. // Any other error type is a stream error.
  1192. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  1193. cs.resc <- resAndError{err: err}
  1194. return nil // return nil from process* funcs to keep conn alive
  1195. }
  1196. if res == nil {
  1197. // (nil, nil) special case. See handleResponse docs.
  1198. return nil
  1199. }
  1200. if res.Body != noBody {
  1201. rl.activeRes[cs.ID] = cs
  1202. }
  1203. cs.resTrailer = &res.Trailer
  1204. cs.resc <- resAndError{res: res}
  1205. return nil
  1206. }
  1207. // may return error types nil, or ConnectionError. Any other error value
  1208. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  1209. // is the detail.
  1210. //
  1211. // As a special case, handleResponse may return (nil, nil) to skip the
  1212. // frame (currently only used for 100 expect continue). This special
  1213. // case is going away after Issue 13851 is fixed.
  1214. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  1215. if f.Truncated {
  1216. return nil, errResponseHeaderListSize
  1217. }
  1218. status := f.PseudoValue("status")
  1219. if status == "" {
  1220. return nil, errors.New("missing status pseudo header")
  1221. }
  1222. statusCode, err := strconv.Atoi(status)
  1223. if err != nil {
  1224. return nil, errors.New("malformed non-numeric status pseudo header")
  1225. }
  1226. if statusCode == 100 {
  1227. traceGot100Continue(cs.trace)
  1228. if cs.on100 != nil {
  1229. cs.on100() // forces any write delay timer to fire
  1230. }
  1231. cs.pastHeaders = false // do it all again
  1232. return nil, nil
  1233. }
  1234. header := make(http.Header)
  1235. res := &http.Response{
  1236. Proto: "HTTP/2.0",
  1237. ProtoMajor: 2,
  1238. Header: header,
  1239. StatusCode: statusCode,
  1240. Status: status + " " + http.StatusText(statusCode),
  1241. }
  1242. for _, hf := range f.RegularFields() {
  1243. key := http.CanonicalHeaderKey(hf.Name)
  1244. if key == "Trailer" {
  1245. t := res.Trailer
  1246. if t == nil {
  1247. t = make(http.Header)
  1248. res.Trailer = t
  1249. }
  1250. foreachHeaderElement(hf.Value, func(v string) {
  1251. t[http.CanonicalHeaderKey(v)] = nil
  1252. })
  1253. } else {
  1254. header[key] = append(header[key], hf.Value)
  1255. }
  1256. }
  1257. streamEnded := f.StreamEnded()
  1258. isHead := cs.req.Method == "HEAD"
  1259. if !streamEnded || isHead {
  1260. res.ContentLength = -1
  1261. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1262. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1263. res.ContentLength = clen64
  1264. } else {
  1265. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1266. // more safe smuggling-wise to ignore.
  1267. }
  1268. } else if len(clens) > 1 {
  1269. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1270. // more safe smuggling-wise to ignore.
  1271. }
  1272. }
  1273. if streamEnded || isHead {
  1274. res.Body = noBody
  1275. return res, nil
  1276. }
  1277. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  1278. cs.bufPipe = pipe{b: buf}
  1279. cs.bytesRemain = res.ContentLength
  1280. res.Body = transportResponseBody{cs}
  1281. go cs.awaitRequestCancel(cs.req)
  1282. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1283. res.Header.Del("Content-Encoding")
  1284. res.Header.Del("Content-Length")
  1285. res.ContentLength = -1
  1286. res.Body = &gzipReader{body: res.Body}
  1287. setResponseUncompressed(res)
  1288. }
  1289. return res, nil
  1290. }
  1291. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  1292. if cs.pastTrailers {
  1293. // Too many HEADERS frames for this stream.
  1294. return ConnectionError(ErrCodeProtocol)
  1295. }
  1296. cs.pastTrailers = true
  1297. if !f.StreamEnded() {
  1298. // We expect that any headers for trailers also
  1299. // has END_STREAM.
  1300. return ConnectionError(ErrCodeProtocol)
  1301. }
  1302. if len(f.PseudoFields()) > 0 {
  1303. // No pseudo header fields are defined for trailers.
  1304. // TODO: ConnectionError might be overly harsh? Check.
  1305. return ConnectionError(ErrCodeProtocol)
  1306. }
  1307. trailer := make(http.Header)
  1308. for _, hf := range f.RegularFields() {
  1309. key := http.CanonicalHeaderKey(hf.Name)
  1310. trailer[key] = append(trailer[key], hf.Value)
  1311. }
  1312. cs.trailer = trailer
  1313. rl.endStream(cs)
  1314. return nil
  1315. }
  1316. // transportResponseBody is the concrete type of Transport.RoundTrip's
  1317. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1318. // On Close it sends RST_STREAM if EOF wasn't already seen.
  1319. type transportResponseBody struct {
  1320. cs *clientStream
  1321. }
  1322. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1323. cs := b.cs
  1324. cc := cs.cc
  1325. if cs.readErr != nil {
  1326. return 0, cs.readErr
  1327. }
  1328. n, err = b.cs.bufPipe.Read(p)
  1329. if cs.bytesRemain != -1 {
  1330. if int64(n) > cs.bytesRemain {
  1331. n = int(cs.bytesRemain)
  1332. if err == nil {
  1333. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1334. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1335. }
  1336. cs.readErr = err
  1337. return int(cs.bytesRemain), err
  1338. }
  1339. cs.bytesRemain -= int64(n)
  1340. if err == io.EOF && cs.bytesRemain > 0 {
  1341. err = io.ErrUnexpectedEOF
  1342. cs.readErr = err
  1343. return n, err
  1344. }
  1345. }
  1346. if n == 0 {
  1347. // No flow control tokens to send back.
  1348. return
  1349. }
  1350. cc.mu.Lock()
  1351. defer cc.mu.Unlock()
  1352. var connAdd, streamAdd int32
  1353. // Check the conn-level first, before the stream-level.
  1354. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  1355. connAdd = transportDefaultConnFlow - v
  1356. cc.inflow.add(connAdd)
  1357. }
  1358. if err == nil { // No need to refresh if the stream is over or failed.
  1359. // Consider any buffered body data (read from the conn but not
  1360. // consumed by the client) when computing flow control for this
  1361. // stream.
  1362. v := int(cs.inflow.available()) + cs.bufPipe.Len()
  1363. if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  1364. streamAdd = int32(transportDefaultStreamFlow - v)
  1365. cs.inflow.add(streamAdd)
  1366. }
  1367. }
  1368. if connAdd != 0 || streamAdd != 0 {
  1369. cc.wmu.Lock()
  1370. defer cc.wmu.Unlock()
  1371. if connAdd != 0 {
  1372. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  1373. }
  1374. if streamAdd != 0 {
  1375. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  1376. }
  1377. cc.bw.Flush()
  1378. }
  1379. return
  1380. }
  1381. var errClosedResponseBody = errors.New("http2: response body closed")
  1382. func (b transportResponseBody) Close() error {
  1383. cs := b.cs
  1384. cc := cs.cc
  1385. serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
  1386. unread := cs.bufPipe.Len()
  1387. if unread > 0 || !serverSentStreamEnd {
  1388. cc.mu.Lock()
  1389. cc.wmu.Lock()
  1390. if !serverSentStreamEnd {
  1391. cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
  1392. }
  1393. // Return connection-level flow control.
  1394. if unread > 0 {
  1395. cc.inflow.add(int32(unread))
  1396. cc.fr.WriteWindowUpdate(0, uint32(unread))
  1397. }
  1398. cc.bw.Flush()
  1399. cc.wmu.Unlock()
  1400. cc.mu.Unlock()
  1401. }
  1402. cs.bufPipe.BreakWithError(errClosedResponseBody)
  1403. return nil
  1404. }
  1405. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  1406. cc := rl.cc
  1407. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1408. data := f.Data()
  1409. if cs == nil {
  1410. cc.mu.Lock()
  1411. neverSent := cc.nextStreamID
  1412. cc.mu.Unlock()
  1413. if f.StreamID >= neverSent {
  1414. // We never asked for this.
  1415. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  1416. return ConnectionError(ErrCodeProtocol)
  1417. }
  1418. // We probably did ask for this, but canceled. Just ignore it.
  1419. // TODO: be stricter here? only silently ignore things which
  1420. // we canceled, but not things which were closed normally
  1421. // by the peer? Tough without accumulating too much state.
  1422. // But at least return their flow control:
  1423. if f.Length > 0 {
  1424. cc.mu.Lock()
  1425. cc.inflow.add(int32(f.Length))
  1426. cc.mu.Unlock()
  1427. cc.wmu.Lock()
  1428. cc.fr.WriteWindowUpdate(0, uint32(f.Length))
  1429. cc.bw.Flush()
  1430. cc.wmu.Unlock()
  1431. }
  1432. return nil
  1433. }
  1434. if f.Length > 0 {
  1435. if len(data) > 0 && cs.bufPipe.b == nil {
  1436. // Data frame after it's already closed?
  1437. cc.logf("http2: Transport received DATA frame for closed stream; closing connection")
  1438. return ConnectionError(ErrCodeProtocol)
  1439. }
  1440. // Check connection-level flow control.
  1441. cc.mu.Lock()
  1442. if cs.inflow.available() >= int32(f.Length) {
  1443. cs.inflow.take(int32(f.Length))
  1444. } else {
  1445. cc.mu.Unlock()
  1446. return ConnectionError(ErrCodeFlowControl)
  1447. }
  1448. // Return any padded flow control now, since we won't
  1449. // refund it later on body reads.
  1450. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1451. cs.inflow.add(pad)
  1452. cc.inflow.add(pad)
  1453. cc.wmu.Lock()
  1454. cc.fr.WriteWindowUpdate(0, uint32(pad))
  1455. cc.fr.WriteWindowUpdate(cs.ID, uint32(pad))
  1456. cc.bw.Flush()
  1457. cc.wmu.Unlock()
  1458. }
  1459. cc.mu.Unlock()
  1460. if len(data) > 0 {
  1461. if _, err := cs.bufPipe.Write(data); err != nil {
  1462. rl.endStreamError(cs, err)
  1463. return err
  1464. }
  1465. }
  1466. }
  1467. if f.StreamEnded() {
  1468. rl.endStream(cs)
  1469. }
  1470. return nil
  1471. }
  1472. var errInvalidTrailers = errors.New("http2: invalid trailers")
  1473. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  1474. // TODO: check that any declared content-length matches, like
  1475. // server.go's (*stream).endStream method.
  1476. rl.endStreamError(cs, nil)
  1477. }
  1478. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  1479. var code func()
  1480. if err == nil {
  1481. err = io.EOF
  1482. code = cs.copyTrailers
  1483. }
  1484. cs.bufPipe.closeWithErrorAndCode(err, code)
  1485. delete(rl.activeRes, cs.ID)
  1486. if isConnectionCloseRequest(cs.req) {
  1487. rl.closeWhenIdle = true
  1488. }
  1489. select {
  1490. case cs.resc <- resAndError{err: err}:
  1491. default:
  1492. }
  1493. }
  1494. func (cs *clientStream) copyTrailers() {
  1495. for k, vv := range cs.trailer {
  1496. t := cs.resTrailer
  1497. if *t == nil {
  1498. *t = make(http.Header)
  1499. }
  1500. (*t)[k] = vv
  1501. }
  1502. }
  1503. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  1504. cc := rl.cc
  1505. cc.t.connPool().MarkDead(cc)
  1506. if f.ErrCode != 0 {
  1507. // TODO: deal with GOAWAY more. particularly the error code
  1508. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  1509. }
  1510. cc.setGoAway(f)
  1511. return nil
  1512. }
  1513. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  1514. cc := rl.cc
  1515. cc.mu.Lock()
  1516. defer cc.mu.Unlock()
  1517. if f.IsAck() {
  1518. if cc.wantSettingsAck {
  1519. cc.wantSettingsAck = false
  1520. return nil
  1521. }
  1522. return ConnectionError(ErrCodeProtocol)
  1523. }
  1524. err := f.ForeachSetting(func(s Setting) error {
  1525. switch s.ID {
  1526. case SettingMaxFrameSize:
  1527. cc.maxFrameSize = s.Val
  1528. case SettingMaxConcurrentStreams:
  1529. cc.maxConcurrentStreams = s.Val
  1530. case SettingInitialWindowSize:
  1531. // Values above the maximum flow-control
  1532. // window size of 2^31-1 MUST be treated as a
  1533. // connection error (Section 5.4.1) of type
  1534. // FLOW_CONTROL_ERROR.
  1535. if s.Val > math.MaxInt32 {
  1536. return ConnectionError(ErrCodeFlowControl)
  1537. }
  1538. // Adjust flow control of currently-open
  1539. // frames by the difference of the old initial
  1540. // window size and this one.
  1541. delta := int32(s.Val) - int32(cc.initialWindowSize)
  1542. for _, cs := range cc.streams {
  1543. cs.flow.add(delta)
  1544. }
  1545. cc.cond.Broadcast()
  1546. cc.initialWindowSize = s.Val
  1547. default:
  1548. // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  1549. cc.vlogf("Unhandled Setting: %v", s)
  1550. }
  1551. return nil
  1552. })
  1553. if err != nil {
  1554. return err
  1555. }
  1556. cc.wmu.Lock()
  1557. defer cc.wmu.Unlock()
  1558. cc.fr.WriteSettingsAck()
  1559. cc.bw.Flush()
  1560. return cc.werr
  1561. }
  1562. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  1563. cc := rl.cc
  1564. cs := cc.streamByID(f.StreamID, false)
  1565. if f.StreamID != 0 && cs == nil {
  1566. return nil
  1567. }
  1568. cc.mu.Lock()
  1569. defer cc.mu.Unlock()
  1570. fl := &cc.flow
  1571. if cs != nil {
  1572. fl = &cs.flow
  1573. }
  1574. if !fl.add(int32(f.Increment)) {
  1575. return ConnectionError(ErrCodeFlowControl)
  1576. }
  1577. cc.cond.Broadcast()
  1578. return nil
  1579. }
  1580. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1581. cs := rl.cc.streamByID(f.StreamID, true)
  1582. if cs == nil {
  1583. // TODO: return error if server tries to RST_STEAM an idle stream
  1584. return nil
  1585. }
  1586. select {
  1587. case <-cs.peerReset:
  1588. // Already reset.
  1589. // This is the only goroutine
  1590. // which closes this, so there
  1591. // isn't a race.
  1592. default:
  1593. err := streamError(cs.ID, f.ErrCode)
  1594. cs.resetErr = err
  1595. close(cs.peerReset)
  1596. cs.bufPipe.CloseWithError(err)
  1597. cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  1598. }
  1599. delete(rl.activeRes, cs.ID)
  1600. return nil
  1601. }
  1602. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1603. if f.IsAck() {
  1604. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1605. // containing this flag."
  1606. return nil
  1607. }
  1608. cc := rl.cc
  1609. cc.wmu.Lock()
  1610. defer cc.wmu.Unlock()
  1611. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1612. return err
  1613. }
  1614. return cc.bw.Flush()
  1615. }
  1616. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1617. // We told the peer we don't want them.
  1618. // Spec says:
  1619. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1620. // setting of the peer endpoint is set to 0. An endpoint that
  1621. // has set this setting and has received acknowledgement MUST
  1622. // treat the receipt of a PUSH_PROMISE frame as a connection
  1623. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1624. return ConnectionError(ErrCodeProtocol)
  1625. }
  1626. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1627. // TODO: map err to more interesting error codes, once the
  1628. // HTTP community comes up with some. But currently for
  1629. // RST_STREAM there's no equivalent to GOAWAY frame's debug
  1630. // data, and the error codes are all pretty vague ("cancel").
  1631. cc.wmu.Lock()
  1632. cc.fr.WriteRSTStream(streamID, code)
  1633. cc.bw.Flush()
  1634. cc.wmu.Unlock()
  1635. }
  1636. var (
  1637. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  1638. errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
  1639. )
  1640. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1641. cc.t.logf(format, args...)
  1642. }
  1643. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1644. cc.t.vlogf(format, args...)
  1645. }
  1646. func (t *Transport) vlogf(format string, args ...interface{}) {
  1647. if VerboseLogs {
  1648. t.logf(format, args...)
  1649. }
  1650. }
  1651. func (t *Transport) logf(format string, args ...interface{}) {
  1652. log.Printf(format, args...)
  1653. }
  1654. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1655. func strSliceContains(ss []string, s string) bool {
  1656. for _, v := range ss {
  1657. if v == s {
  1658. return true
  1659. }
  1660. }
  1661. return false
  1662. }
  1663. type erringRoundTripper struct{ err error }
  1664. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1665. // gzipReader wraps a response body so it can lazily
  1666. // call gzip.NewReader on the first call to Read
  1667. type gzipReader struct {
  1668. body io.ReadCloser // underlying Response.Body
  1669. zr *gzip.Reader // lazily-initialized gzip reader
  1670. zerr error // sticky error
  1671. }
  1672. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1673. if gz.zerr != nil {
  1674. return 0, gz.zerr
  1675. }
  1676. if gz.zr == nil {
  1677. gz.zr, err = gzip.NewReader(gz.body)
  1678. if err != nil {
  1679. gz.zerr = err
  1680. return 0, err
  1681. }
  1682. }
  1683. return gz.zr.Read(p)
  1684. }
  1685. func (gz *gzipReader) Close() error {
  1686. return gz.body.Close()
  1687. }
  1688. type errorReader struct{ err error }
  1689. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  1690. // bodyWriterState encapsulates various state around the Transport's writing
  1691. // of the request body, particularly regarding doing delayed writes of the body
  1692. // when the request contains "Expect: 100-continue".
  1693. type bodyWriterState struct {
  1694. cs *clientStream
  1695. timer *time.Timer // if non-nil, we're doing a delayed write
  1696. fnonce *sync.Once // to call fn with
  1697. fn func() // the code to run in the goroutine, writing the body
  1698. resc chan error // result of fn's execution
  1699. delay time.Duration // how long we should delay a delayed write for
  1700. }
  1701. func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
  1702. s.cs = cs
  1703. if body == nil {
  1704. return
  1705. }
  1706. resc := make(chan error, 1)
  1707. s.resc = resc
  1708. s.fn = func() {
  1709. resc <- cs.writeRequestBody(body, cs.req.Body)
  1710. }
  1711. s.delay = t.expectContinueTimeout()
  1712. if s.delay == 0 ||
  1713. !httplex.HeaderValuesContainsToken(
  1714. cs.req.Header["Expect"],
  1715. "100-continue") {
  1716. return
  1717. }
  1718. s.fnonce = new(sync.Once)
  1719. // Arm the timer with a very large duration, which we'll
  1720. // intentionally lower later. It has to be large now because
  1721. // we need a handle to it before writing the headers, but the
  1722. // s.delay value is defined to not start until after the
  1723. // request headers were written.
  1724. const hugeDuration = 365 * 24 * time.Hour
  1725. s.timer = time.AfterFunc(hugeDuration, func() {
  1726. s.fnonce.Do(s.fn)
  1727. })
  1728. return
  1729. }
  1730. func (s bodyWriterState) cancel() {
  1731. if s.timer != nil {
  1732. s.timer.Stop()
  1733. }
  1734. }
  1735. func (s bodyWriterState) on100() {
  1736. if s.timer == nil {
  1737. // If we didn't do a delayed write, ignore the server's
  1738. // bogus 100 continue response.
  1739. return
  1740. }
  1741. s.timer.Stop()
  1742. go func() { s.fnonce.Do(s.fn) }()
  1743. }
  1744. // scheduleBodyWrite starts writing the body, either immediately (in
  1745. // the common case) or after the delay timeout. It should not be
  1746. // called until after the headers have been written.
  1747. func (s bodyWriterState) scheduleBodyWrite() {
  1748. if s.timer == nil {
  1749. // We're not doing a delayed write (see
  1750. // getBodyWriterState), so just start the writing
  1751. // goroutine immediately.
  1752. go s.fn()
  1753. return
  1754. }
  1755. traceWait100Continue(s.cs.trace)
  1756. if s.timer.Stop() {
  1757. s.timer.Reset(s.delay)
  1758. }
  1759. }
  1760. // isConnectionCloseRequest reports whether req should use its own
  1761. // connection for a single request and then close the connection.
  1762. func isConnectionCloseRequest(req *http.Request) bool {
  1763. return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close")
  1764. }