transport.go 39 KB

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