transport.go 45 KB

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