transport.go 46 KB

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