server.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  1. // Copyright 2014 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. // TODO: replace all <-sc.doneServing with reads from the stream's cw
  5. // instead, and make sure that on close we close all open
  6. // streams. then remove doneServing?
  7. // TODO: finish GOAWAY support. Consider each incoming frame type and
  8. // whether it should be ignored during a shutdown race.
  9. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make
  10. // configurable? or maximum number of idle clients and remove the
  11. // oldest?
  12. // TODO: turn off the serve goroutine when idle, so
  13. // an idle conn only has the readFrames goroutine active. (which could
  14. // also be optimized probably to pin less memory in crypto/tls). This
  15. // would involve tracking when the serve goroutine is active (atomic
  16. // int32 read/CAS probably?) and starting it up when frames arrive,
  17. // and shutting it down when all handlers exit. the occasional PING
  18. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  19. // (which is a no-op if already running) and then queue the PING write
  20. // as normal. The serve loop would then exit in most cases (if no
  21. // Handlers running) and not be woken up again until the PING packet
  22. // returns.
  23. // TODO (maybe): add a mechanism for Handlers to going into
  24. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  25. // handler, and continue to be able to read from the
  26. // Request.Body. This would be a somewhat semantic change from HTTP/1
  27. // (or at least what we expose in net/http), so I'd probably want to
  28. // add it there too. For now, this package says that returning from
  29. // the Handler ServeHTTP function means you're both done reading and
  30. // done writing, without a way to stop just one or the other.
  31. package http2
  32. import (
  33. "bufio"
  34. "bytes"
  35. "crypto/tls"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "log"
  40. "net"
  41. "net/http"
  42. "net/url"
  43. "strconv"
  44. "strings"
  45. "sync"
  46. "time"
  47. "golang.org/x/net/http2/hpack"
  48. )
  49. const (
  50. prefaceTimeout = 10 * time.Second
  51. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  52. handlerChunkWriteSize = 4 << 10
  53. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  54. )
  55. var (
  56. errClientDisconnected = errors.New("client disconnected")
  57. errClosedBody = errors.New("body closed by handler")
  58. errStreamClosed = errors.New("http2: stream closed")
  59. )
  60. var responseWriterStatePool = sync.Pool{
  61. New: func() interface{} {
  62. rws := &responseWriterState{}
  63. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  64. return rws
  65. },
  66. }
  67. // Test hooks.
  68. var (
  69. testHookOnConn func()
  70. testHookGetServerConn func(*serverConn)
  71. testHookOnPanicMu *sync.Mutex // nil except in tests
  72. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  73. )
  74. // Server is an HTTP/2 server.
  75. type Server struct {
  76. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  77. // which may run at a time over all connections.
  78. // Negative or zero no limit.
  79. // TODO: implement
  80. MaxHandlers int
  81. // MaxConcurrentStreams optionally specifies the number of
  82. // concurrent streams that each client may have open at a
  83. // time. This is unrelated to the number of http.Handler goroutines
  84. // which may be active globally, which is MaxHandlers.
  85. // If zero, MaxConcurrentStreams defaults to at least 100, per
  86. // the HTTP/2 spec's recommendations.
  87. MaxConcurrentStreams uint32
  88. // MaxReadFrameSize optionally specifies the largest frame
  89. // this server is willing to read. A valid value is between
  90. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  91. // default value is used.
  92. MaxReadFrameSize uint32
  93. // PermitProhibitedCipherSuites, if true, permits the use of
  94. // cipher suites prohibited by the HTTP/2 spec.
  95. PermitProhibitedCipherSuites bool
  96. }
  97. func (s *Server) maxReadFrameSize() uint32 {
  98. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  99. return v
  100. }
  101. return defaultMaxReadFrameSize
  102. }
  103. func (s *Server) maxConcurrentStreams() uint32 {
  104. if v := s.MaxConcurrentStreams; v > 0 {
  105. return v
  106. }
  107. return defaultMaxStreams
  108. }
  109. // ConfigureServer adds HTTP/2 support to a net/http Server.
  110. //
  111. // The configuration conf may be nil.
  112. //
  113. // ConfigureServer must be called before s begins serving.
  114. func ConfigureServer(s *http.Server, conf *Server) error {
  115. if conf == nil {
  116. conf = new(Server)
  117. }
  118. if s.TLSConfig == nil {
  119. s.TLSConfig = new(tls.Config)
  120. } else if s.TLSConfig.CipherSuites != nil {
  121. // If they already provided a CipherSuite list, return
  122. // an error if it has a bad order or is missing
  123. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  124. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  125. haveRequired := false
  126. sawBad := false
  127. for i, cs := range s.TLSConfig.CipherSuites {
  128. if cs == requiredCipher {
  129. haveRequired = true
  130. }
  131. if isBadCipher(cs) {
  132. sawBad = true
  133. } else if sawBad {
  134. return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
  135. }
  136. }
  137. if !haveRequired {
  138. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  139. }
  140. }
  141. // Note: not setting MinVersion to tls.VersionTLS12,
  142. // as we don't want to interfere with HTTP/1.1 traffic
  143. // on the user's server. We enforce TLS 1.2 later once
  144. // we accept a connection. Ideally this should be done
  145. // during next-proto selection, but using TLS <1.2 with
  146. // HTTP/2 is still the client's bug.
  147. s.TLSConfig.PreferServerCipherSuites = true
  148. haveNPN := false
  149. for _, p := range s.TLSConfig.NextProtos {
  150. if p == NextProtoTLS {
  151. haveNPN = true
  152. break
  153. }
  154. }
  155. if !haveNPN {
  156. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  157. }
  158. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  159. // to switch to "h2".
  160. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  161. if s.TLSNextProto == nil {
  162. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  163. }
  164. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  165. if testHookOnConn != nil {
  166. testHookOnConn()
  167. }
  168. conf.handleConn(hs, c, h)
  169. }
  170. s.TLSNextProto[NextProtoTLS] = protoHandler
  171. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  172. return nil
  173. }
  174. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  175. sc := &serverConn{
  176. srv: srv,
  177. hs: hs,
  178. conn: c,
  179. remoteAddrStr: c.RemoteAddr().String(),
  180. bw: newBufferedWriter(c),
  181. handler: h,
  182. streams: make(map[uint32]*stream),
  183. readFrameCh: make(chan readFrameResult),
  184. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  185. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  186. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  187. doneServing: make(chan struct{}),
  188. advMaxStreams: srv.maxConcurrentStreams(),
  189. writeSched: writeScheduler{
  190. maxFrameSize: initialMaxFrameSize,
  191. },
  192. initialWindowSize: initialWindowSize,
  193. headerTableSize: initialHeaderTableSize,
  194. serveG: newGoroutineLock(),
  195. pushEnabled: true,
  196. }
  197. sc.flow.add(initialWindowSize)
  198. sc.inflow.add(initialWindowSize)
  199. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  200. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  201. sc.hpackDecoder.SetMaxStringLength(sc.maxHeaderStringLen())
  202. fr := NewFramer(sc.bw, c)
  203. fr.SetMaxReadFrameSize(srv.maxReadFrameSize())
  204. sc.framer = fr
  205. if tc, ok := c.(*tls.Conn); ok {
  206. sc.tlsState = new(tls.ConnectionState)
  207. *sc.tlsState = tc.ConnectionState()
  208. // 9.2 Use of TLS Features
  209. // An implementation of HTTP/2 over TLS MUST use TLS
  210. // 1.2 or higher with the restrictions on feature set
  211. // and cipher suite described in this section. Due to
  212. // implementation limitations, it might not be
  213. // possible to fail TLS negotiation. An endpoint MUST
  214. // immediately terminate an HTTP/2 connection that
  215. // does not meet the TLS requirements described in
  216. // this section with a connection error (Section
  217. // 5.4.1) of type INADEQUATE_SECURITY.
  218. if sc.tlsState.Version < tls.VersionTLS12 {
  219. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  220. return
  221. }
  222. if sc.tlsState.ServerName == "" {
  223. // Client must use SNI, but we don't enforce that anymore,
  224. // since it was causing problems when connecting to bare IP
  225. // addresses during development.
  226. //
  227. // TODO: optionally enforce? Or enforce at the time we receive
  228. // a new request, and verify the the ServerName matches the :authority?
  229. // But that precludes proxy situations, perhaps.
  230. //
  231. // So for now, do nothing here again.
  232. }
  233. if !srv.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  234. // "Endpoints MAY choose to generate a connection error
  235. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  236. // the prohibited cipher suites are negotiated."
  237. //
  238. // We choose that. In my opinion, the spec is weak
  239. // here. It also says both parties must support at least
  240. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  241. // excuses here. If we really must, we could allow an
  242. // "AllowInsecureWeakCiphers" option on the server later.
  243. // Let's see how it plays out first.
  244. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  245. return
  246. }
  247. }
  248. if hook := testHookGetServerConn; hook != nil {
  249. hook(sc)
  250. }
  251. sc.serve()
  252. }
  253. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  254. func isBadCipher(cipher uint16) bool {
  255. switch cipher {
  256. case tls.TLS_RSA_WITH_RC4_128_SHA,
  257. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  258. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  259. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  260. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  261. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  262. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  263. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  264. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  265. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  266. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  267. // Reject cipher suites from Appendix A.
  268. // "This list includes those cipher suites that do not
  269. // offer an ephemeral key exchange and those that are
  270. // based on the TLS null, stream or block cipher type"
  271. return true
  272. default:
  273. return false
  274. }
  275. }
  276. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  277. sc.vlogf("REJECTING conn: %v, %s", err, debug)
  278. // ignoring errors. hanging up anyway.
  279. sc.framer.WriteGoAway(0, err, []byte(debug))
  280. sc.bw.Flush()
  281. sc.conn.Close()
  282. }
  283. type serverConn struct {
  284. // Immutable:
  285. srv *Server
  286. hs *http.Server
  287. conn net.Conn
  288. bw *bufferedWriter // writing to conn
  289. handler http.Handler
  290. framer *Framer
  291. hpackDecoder *hpack.Decoder
  292. doneServing chan struct{} // closed when serverConn.serve ends
  293. readFrameCh chan readFrameResult // written by serverConn.readFrames
  294. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  295. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  296. bodyReadCh chan bodyReadMsg // from handlers -> serve
  297. testHookCh chan func(int) // code to run on the serve loop
  298. flow flow // conn-wide (not stream-specific) outbound flow control
  299. inflow flow // conn-wide inbound flow control
  300. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  301. remoteAddrStr string
  302. // Everything following is owned by the serve loop; use serveG.check():
  303. serveG goroutineLock // used to verify funcs are on serve()
  304. pushEnabled bool
  305. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  306. needToSendSettingsAck bool
  307. unackedSettings int // how many SETTINGS have we sent without ACKs?
  308. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  309. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  310. curOpenStreams uint32 // client's number of open streams
  311. maxStreamID uint32 // max ever seen
  312. streams map[uint32]*stream
  313. initialWindowSize int32
  314. headerTableSize uint32
  315. peerMaxHeaderListSize uint32 // zero means unknown (default)
  316. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  317. req requestParam // non-zero while reading request headers
  318. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  319. needsFrameFlush bool // last frame write wasn't a flush
  320. writeSched writeScheduler
  321. inGoAway bool // we've started to or sent GOAWAY
  322. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  323. goAwayCode ErrCode
  324. shutdownTimerCh <-chan time.Time // nil until used
  325. shutdownTimer *time.Timer // nil until used
  326. // Owned by the writeFrameAsync goroutine:
  327. headerWriteBuf bytes.Buffer
  328. hpackEncoder *hpack.Encoder
  329. }
  330. func (sc *serverConn) maxHeaderStringLen() int {
  331. v := sc.maxHeaderListSize()
  332. if uint32(int(v)) == v {
  333. return int(v)
  334. }
  335. // They had a crazy big number for MaxHeaderBytes anyway,
  336. // so give them unlimited header lengths:
  337. return 0
  338. }
  339. func (sc *serverConn) maxHeaderListSize() uint32 {
  340. n := sc.hs.MaxHeaderBytes
  341. if n <= 0 {
  342. n = http.DefaultMaxHeaderBytes
  343. }
  344. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  345. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  346. const perFieldOverhead = 32 // per http2 spec
  347. const typicalHeaders = 10 // conservative
  348. return uint32(n + typicalHeaders*perFieldOverhead)
  349. }
  350. // requestParam is the state of the next request, initialized over
  351. // potentially several frames HEADERS + zero or more CONTINUATION
  352. // frames.
  353. type requestParam struct {
  354. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  355. // frames for a request (but not DATA).
  356. stream *stream
  357. header http.Header
  358. method, path string
  359. scheme, authority string
  360. sawRegularHeader bool // saw a non-pseudo header already
  361. invalidHeader bool // an invalid header was seen
  362. headerListSize int64 // actually uint32, but easier math this way
  363. }
  364. // stream represents a stream. This is the minimal metadata needed by
  365. // the serve goroutine. Most of the actual stream state is owned by
  366. // the http.Handler's goroutine in the responseWriter. Because the
  367. // responseWriter's responseWriterState is recycled at the end of a
  368. // handler, this struct intentionally has no pointer to the
  369. // *responseWriter{,State} itself, as the Handler ending nils out the
  370. // responseWriter's state field.
  371. type stream struct {
  372. // immutable:
  373. id uint32
  374. body *pipe // non-nil if expecting DATA frames
  375. cw closeWaiter // closed wait stream transitions to closed state
  376. // owned by serverConn's serve loop:
  377. bodyBytes int64 // body bytes seen so far
  378. declBodyBytes int64 // or -1 if undeclared
  379. flow flow // limits writing from Handler to client
  380. inflow flow // what the client is allowed to POST/etc to us
  381. parent *stream // or nil
  382. weight uint8
  383. state streamState
  384. sentReset bool // only true once detached from streams map
  385. gotReset bool // only true once detacted from streams map
  386. }
  387. func (sc *serverConn) Framer() *Framer { return sc.framer }
  388. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  389. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  390. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  391. return sc.hpackEncoder, &sc.headerWriteBuf
  392. }
  393. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  394. sc.serveG.check()
  395. // http://http2.github.io/http2-spec/#rfc.section.5.1
  396. if st, ok := sc.streams[streamID]; ok {
  397. return st.state, st
  398. }
  399. // "The first use of a new stream identifier implicitly closes all
  400. // streams in the "idle" state that might have been initiated by
  401. // that peer with a lower-valued stream identifier. For example, if
  402. // a client sends a HEADERS frame on stream 7 without ever sending a
  403. // frame on stream 5, then stream 5 transitions to the "closed"
  404. // state when the first frame for stream 7 is sent or received."
  405. if streamID <= sc.maxStreamID {
  406. return stateClosed, nil
  407. }
  408. return stateIdle, nil
  409. }
  410. // setConnState calls the net/http ConnState hook for this connection, if configured.
  411. // Note that the net/http package does StateNew and StateClosed for us.
  412. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  413. func (sc *serverConn) setConnState(state http.ConnState) {
  414. if sc.hs.ConnState != nil {
  415. sc.hs.ConnState(sc.conn, state)
  416. }
  417. }
  418. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  419. if VerboseLogs {
  420. sc.logf(format, args...)
  421. }
  422. }
  423. func (sc *serverConn) logf(format string, args ...interface{}) {
  424. if lg := sc.hs.ErrorLog; lg != nil {
  425. lg.Printf(format, args...)
  426. } else {
  427. log.Printf(format, args...)
  428. }
  429. }
  430. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  431. if err == nil {
  432. return
  433. }
  434. str := err.Error()
  435. if err == io.EOF || strings.Contains(str, "use of closed network connection") {
  436. // Boring, expected errors.
  437. sc.vlogf(format, args...)
  438. } else {
  439. sc.logf(format, args...)
  440. }
  441. }
  442. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  443. sc.serveG.check()
  444. sc.vlogf("got header field %+v", f)
  445. switch {
  446. case !validHeader(f.Name):
  447. sc.req.invalidHeader = true
  448. case strings.HasPrefix(f.Name, ":"):
  449. if sc.req.sawRegularHeader {
  450. sc.logf("pseudo-header after regular header")
  451. sc.req.invalidHeader = true
  452. return
  453. }
  454. var dst *string
  455. switch f.Name {
  456. case ":method":
  457. dst = &sc.req.method
  458. case ":path":
  459. dst = &sc.req.path
  460. case ":scheme":
  461. dst = &sc.req.scheme
  462. case ":authority":
  463. dst = &sc.req.authority
  464. default:
  465. // 8.1.2.1 Pseudo-Header Fields
  466. // "Endpoints MUST treat a request or response
  467. // that contains undefined or invalid
  468. // pseudo-header fields as malformed (Section
  469. // 8.1.2.6)."
  470. sc.logf("invalid pseudo-header %q", f.Name)
  471. sc.req.invalidHeader = true
  472. return
  473. }
  474. if *dst != "" {
  475. sc.logf("duplicate pseudo-header %q sent", f.Name)
  476. sc.req.invalidHeader = true
  477. return
  478. }
  479. *dst = f.Value
  480. default:
  481. sc.req.sawRegularHeader = true
  482. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  483. const headerFieldOverhead = 32 // per spec
  484. sc.req.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead
  485. if sc.req.headerListSize > int64(sc.maxHeaderListSize()) {
  486. sc.hpackDecoder.SetEmitEnabled(false)
  487. }
  488. }
  489. }
  490. func (sc *serverConn) canonicalHeader(v string) string {
  491. sc.serveG.check()
  492. cv, ok := commonCanonHeader[v]
  493. if ok {
  494. return cv
  495. }
  496. cv, ok = sc.canonHeader[v]
  497. if ok {
  498. return cv
  499. }
  500. if sc.canonHeader == nil {
  501. sc.canonHeader = make(map[string]string)
  502. }
  503. cv = http.CanonicalHeaderKey(v)
  504. sc.canonHeader[v] = cv
  505. return cv
  506. }
  507. type readFrameResult struct {
  508. f Frame // valid until readMore is called
  509. err error
  510. // readMore should be called once the consumer no longer needs or
  511. // retains f. After readMore, f is invalid and more frames can be
  512. // read.
  513. readMore func()
  514. }
  515. // readFrames is the loop that reads incoming frames.
  516. // It takes care to only read one frame at a time, blocking until the
  517. // consumer is done with the frame.
  518. // It's run on its own goroutine.
  519. func (sc *serverConn) readFrames() {
  520. gate := make(gate)
  521. for {
  522. f, err := sc.framer.ReadFrame()
  523. select {
  524. case sc.readFrameCh <- readFrameResult{f, err, gate.Done}:
  525. case <-sc.doneServing:
  526. return
  527. }
  528. select {
  529. case <-gate:
  530. case <-sc.doneServing:
  531. return
  532. }
  533. }
  534. }
  535. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  536. type frameWriteResult struct {
  537. wm frameWriteMsg // what was written (or attempted)
  538. err error // result of the writeFrame call
  539. }
  540. // writeFrameAsync runs in its own goroutine and writes a single frame
  541. // and then reports when it's done.
  542. // At most one goroutine can be running writeFrameAsync at a time per
  543. // serverConn.
  544. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  545. err := wm.write.writeFrame(sc)
  546. sc.wroteFrameCh <- frameWriteResult{wm, err}
  547. }
  548. func (sc *serverConn) closeAllStreamsOnConnClose() {
  549. sc.serveG.check()
  550. for _, st := range sc.streams {
  551. sc.closeStream(st, errClientDisconnected)
  552. }
  553. }
  554. func (sc *serverConn) stopShutdownTimer() {
  555. sc.serveG.check()
  556. if t := sc.shutdownTimer; t != nil {
  557. t.Stop()
  558. }
  559. }
  560. func (sc *serverConn) notePanic() {
  561. if testHookOnPanicMu != nil {
  562. testHookOnPanicMu.Lock()
  563. defer testHookOnPanicMu.Unlock()
  564. }
  565. if testHookOnPanic != nil {
  566. if e := recover(); e != nil {
  567. if testHookOnPanic(sc, e) {
  568. panic(e)
  569. }
  570. }
  571. }
  572. }
  573. func (sc *serverConn) serve() {
  574. sc.serveG.check()
  575. defer sc.notePanic()
  576. defer sc.conn.Close()
  577. defer sc.closeAllStreamsOnConnClose()
  578. defer sc.stopShutdownTimer()
  579. defer close(sc.doneServing) // unblocks handlers trying to send
  580. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  581. sc.writeFrame(frameWriteMsg{
  582. write: writeSettings{
  583. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  584. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  585. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  586. // TODO: more actual settings, notably
  587. // SettingInitialWindowSize, but then we also
  588. // want to bump up the conn window size the
  589. // same amount here right after the settings
  590. },
  591. })
  592. sc.unackedSettings++
  593. if err := sc.readPreface(); err != nil {
  594. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  595. return
  596. }
  597. // Now that we've got the preface, get us out of the
  598. // "StateNew" state. We can't go directly to idle, though.
  599. // Active means we read some data and anticipate a request. We'll
  600. // do another Active when we get a HEADERS frame.
  601. sc.setConnState(http.StateActive)
  602. sc.setConnState(http.StateIdle)
  603. go sc.readFrames() // closed by defer sc.conn.Close above
  604. settingsTimer := time.NewTimer(firstSettingsTimeout)
  605. loopNum := 0
  606. for {
  607. loopNum++
  608. select {
  609. case wm := <-sc.wantWriteFrameCh:
  610. sc.writeFrame(wm)
  611. case res := <-sc.wroteFrameCh:
  612. sc.wroteFrame(res)
  613. case res := <-sc.readFrameCh:
  614. if !sc.processFrameFromReader(res) {
  615. return
  616. }
  617. res.readMore()
  618. if settingsTimer.C != nil {
  619. settingsTimer.Stop()
  620. settingsTimer.C = nil
  621. }
  622. case m := <-sc.bodyReadCh:
  623. sc.noteBodyRead(m.st, m.n)
  624. case <-settingsTimer.C:
  625. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  626. return
  627. case <-sc.shutdownTimerCh:
  628. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  629. return
  630. case fn := <-sc.testHookCh:
  631. fn(loopNum)
  632. }
  633. }
  634. }
  635. // readPreface reads the ClientPreface greeting from the peer
  636. // or returns an error on timeout or an invalid greeting.
  637. func (sc *serverConn) readPreface() error {
  638. errc := make(chan error, 1)
  639. go func() {
  640. // Read the client preface
  641. buf := make([]byte, len(ClientPreface))
  642. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  643. errc <- err
  644. } else if !bytes.Equal(buf, clientPreface) {
  645. errc <- fmt.Errorf("bogus greeting %q", buf)
  646. } else {
  647. errc <- nil
  648. }
  649. }()
  650. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  651. defer timer.Stop()
  652. select {
  653. case <-timer.C:
  654. return errors.New("timeout waiting for client preface")
  655. case err := <-errc:
  656. if err == nil {
  657. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  658. }
  659. return err
  660. }
  661. }
  662. var errChanPool = sync.Pool{
  663. New: func() interface{} { return make(chan error, 1) },
  664. }
  665. // writeDataFromHandler writes the data described in req to stream.id.
  666. //
  667. // The flow control currently happens in the Handler where it waits
  668. // for 1 or more bytes to be available to then write here. So at this
  669. // point we know that we have flow control. But this might have to
  670. // change when priority is implemented, so the serve goroutine knows
  671. // the total amount of bytes waiting to be sent and can can have more
  672. // scheduling decisions available.
  673. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData) error {
  674. ch := errChanPool.Get().(chan error)
  675. err := sc.writeFrameFromHandler(frameWriteMsg{
  676. write: writeData,
  677. stream: stream,
  678. done: ch,
  679. })
  680. if err != nil {
  681. return err
  682. }
  683. select {
  684. case err = <-ch:
  685. case <-sc.doneServing:
  686. return errClientDisconnected
  687. case <-stream.cw:
  688. // If both ch and stream.cw were ready (as might
  689. // happen on the final Write after an http.Handler
  690. // ends), prefer the write result. Otherwise this
  691. // might just be us successfully closing the stream.
  692. // The writeFrameAsync and serve goroutines guarantee
  693. // that the ch send will happen before the stream.cw
  694. // close.
  695. select {
  696. case err = <-ch:
  697. default:
  698. return errStreamClosed
  699. }
  700. }
  701. errChanPool.Put(ch)
  702. return err
  703. }
  704. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  705. // if the connection has gone away.
  706. //
  707. // This must not be run from the serve goroutine itself, else it might
  708. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  709. // buffered and is read by serve itself). If you're on the serve
  710. // goroutine, call writeFrame instead.
  711. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  712. sc.serveG.checkNotOn() // NOT
  713. select {
  714. case sc.wantWriteFrameCh <- wm:
  715. return nil
  716. case <-sc.doneServing:
  717. // Serve loop is gone.
  718. // Client has closed their connection to the server.
  719. return errClientDisconnected
  720. }
  721. }
  722. // writeFrame schedules a frame to write and sends it if there's nothing
  723. // already being written.
  724. //
  725. // There is no pushback here (the serve goroutine never blocks). It's
  726. // the http.Handlers that block, waiting for their previous frames to
  727. // make it onto the wire
  728. //
  729. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  730. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  731. sc.serveG.check()
  732. sc.writeSched.add(wm)
  733. sc.scheduleFrameWrite()
  734. }
  735. // startFrameWrite starts a goroutine to write wm (in a separate
  736. // goroutine since that might block on the network), and updates the
  737. // serve goroutine's state about the world, updated from info in wm.
  738. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  739. sc.serveG.check()
  740. if sc.writingFrame {
  741. panic("internal error: can only be writing one frame at a time")
  742. }
  743. st := wm.stream
  744. if st != nil {
  745. switch st.state {
  746. case stateHalfClosedLocal:
  747. panic("internal error: attempt to send frame on half-closed-local stream")
  748. case stateClosed:
  749. if st.sentReset || st.gotReset {
  750. // Skip this frame.
  751. sc.scheduleFrameWrite()
  752. return
  753. }
  754. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  755. }
  756. }
  757. sc.writingFrame = true
  758. sc.needsFrameFlush = true
  759. go sc.writeFrameAsync(wm)
  760. }
  761. // wroteFrame is called on the serve goroutine with the result of
  762. // whatever happened on writeFrameAsync.
  763. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  764. sc.serveG.check()
  765. if !sc.writingFrame {
  766. panic("internal error: expected to be already writing a frame")
  767. }
  768. sc.writingFrame = false
  769. wm := res.wm
  770. st := wm.stream
  771. closeStream := endsStream(wm.write)
  772. // Reply (if requested) to the blocked ServeHTTP goroutine.
  773. if ch := wm.done; ch != nil {
  774. select {
  775. case ch <- res.err:
  776. default:
  777. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  778. }
  779. }
  780. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  781. if closeStream {
  782. if st == nil {
  783. panic("internal error: expecting non-nil stream")
  784. }
  785. switch st.state {
  786. case stateOpen:
  787. // Here we would go to stateHalfClosedLocal in
  788. // theory, but since our handler is done and
  789. // the net/http package provides no mechanism
  790. // for finishing writing to a ResponseWriter
  791. // while still reading data (see possible TODO
  792. // at top of this file), we go into closed
  793. // state here anyway, after telling the peer
  794. // we're hanging up on them.
  795. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  796. errCancel := StreamError{st.id, ErrCodeCancel}
  797. sc.resetStream(errCancel)
  798. case stateHalfClosedRemote:
  799. sc.closeStream(st, nil)
  800. }
  801. }
  802. sc.scheduleFrameWrite()
  803. }
  804. // scheduleFrameWrite tickles the frame writing scheduler.
  805. //
  806. // If a frame is already being written, nothing happens. This will be called again
  807. // when the frame is done being written.
  808. //
  809. // If a frame isn't being written we need to send one, the best frame
  810. // to send is selected, preferring first things that aren't
  811. // stream-specific (e.g. ACKing settings), and then finding the
  812. // highest priority stream.
  813. //
  814. // If a frame isn't being written and there's nothing else to send, we
  815. // flush the write buffer.
  816. func (sc *serverConn) scheduleFrameWrite() {
  817. sc.serveG.check()
  818. if sc.writingFrame {
  819. return
  820. }
  821. if sc.needToSendGoAway {
  822. sc.needToSendGoAway = false
  823. sc.startFrameWrite(frameWriteMsg{
  824. write: &writeGoAway{
  825. maxStreamID: sc.maxStreamID,
  826. code: sc.goAwayCode,
  827. },
  828. })
  829. return
  830. }
  831. if sc.needToSendSettingsAck {
  832. sc.needToSendSettingsAck = false
  833. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  834. return
  835. }
  836. if !sc.inGoAway {
  837. if wm, ok := sc.writeSched.take(); ok {
  838. sc.startFrameWrite(wm)
  839. return
  840. }
  841. }
  842. if sc.needsFrameFlush {
  843. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  844. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  845. return
  846. }
  847. }
  848. func (sc *serverConn) goAway(code ErrCode) {
  849. sc.serveG.check()
  850. if sc.inGoAway {
  851. return
  852. }
  853. if code != ErrCodeNo {
  854. sc.shutDownIn(250 * time.Millisecond)
  855. } else {
  856. // TODO: configurable
  857. sc.shutDownIn(1 * time.Second)
  858. }
  859. sc.inGoAway = true
  860. sc.needToSendGoAway = true
  861. sc.goAwayCode = code
  862. sc.scheduleFrameWrite()
  863. }
  864. func (sc *serverConn) shutDownIn(d time.Duration) {
  865. sc.serveG.check()
  866. sc.shutdownTimer = time.NewTimer(d)
  867. sc.shutdownTimerCh = sc.shutdownTimer.C
  868. }
  869. func (sc *serverConn) resetStream(se StreamError) {
  870. sc.serveG.check()
  871. sc.writeFrame(frameWriteMsg{write: se})
  872. if st, ok := sc.streams[se.StreamID]; ok {
  873. st.sentReset = true
  874. sc.closeStream(st, se)
  875. }
  876. }
  877. // curHeaderStreamID returns the stream ID of the header block we're
  878. // currently in the middle of reading. If this returns non-zero, the
  879. // next frame must be a CONTINUATION with this stream id.
  880. func (sc *serverConn) curHeaderStreamID() uint32 {
  881. sc.serveG.check()
  882. st := sc.req.stream
  883. if st == nil {
  884. return 0
  885. }
  886. return st.id
  887. }
  888. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  889. // frame-reading goroutine.
  890. // processFrameFromReader returns whether the connection should be kept open.
  891. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  892. sc.serveG.check()
  893. err := res.err
  894. if err != nil {
  895. if err == ErrFrameTooLarge {
  896. sc.goAway(ErrCodeFrameSize)
  897. return true // goAway will close the loop
  898. }
  899. clientGone := err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  900. if clientGone {
  901. // TODO: could we also get into this state if
  902. // the peer does a half close
  903. // (e.g. CloseWrite) because they're done
  904. // sending frames but they're still wanting
  905. // our open replies? Investigate.
  906. // TODO: add CloseWrite to crypto/tls.Conn first
  907. // so we have a way to test this? I suppose
  908. // just for testing we could have a non-TLS mode.
  909. return false
  910. }
  911. } else {
  912. f := res.f
  913. sc.vlogf("got %v: %#v", f.Header(), f)
  914. err = sc.processFrame(f)
  915. if err == nil {
  916. return true
  917. }
  918. }
  919. switch ev := err.(type) {
  920. case StreamError:
  921. sc.resetStream(ev)
  922. return true
  923. case goAwayFlowError:
  924. sc.goAway(ErrCodeFlowControl)
  925. return true
  926. case ConnectionError:
  927. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  928. sc.goAway(ErrCode(ev))
  929. return true // goAway will handle shutdown
  930. default:
  931. if res.err != nil {
  932. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  933. } else {
  934. sc.logf("disconnection due to other error: %v", err)
  935. }
  936. return false
  937. }
  938. }
  939. func (sc *serverConn) processFrame(f Frame) error {
  940. sc.serveG.check()
  941. // First frame received must be SETTINGS.
  942. if !sc.sawFirstSettings {
  943. if _, ok := f.(*SettingsFrame); !ok {
  944. return ConnectionError(ErrCodeProtocol)
  945. }
  946. sc.sawFirstSettings = true
  947. }
  948. if s := sc.curHeaderStreamID(); s != 0 {
  949. if cf, ok := f.(*ContinuationFrame); !ok {
  950. return ConnectionError(ErrCodeProtocol)
  951. } else if cf.Header().StreamID != s {
  952. return ConnectionError(ErrCodeProtocol)
  953. }
  954. }
  955. switch f := f.(type) {
  956. case *SettingsFrame:
  957. return sc.processSettings(f)
  958. case *HeadersFrame:
  959. return sc.processHeaders(f)
  960. case *ContinuationFrame:
  961. return sc.processContinuation(f)
  962. case *WindowUpdateFrame:
  963. return sc.processWindowUpdate(f)
  964. case *PingFrame:
  965. return sc.processPing(f)
  966. case *DataFrame:
  967. return sc.processData(f)
  968. case *RSTStreamFrame:
  969. return sc.processResetStream(f)
  970. case *PriorityFrame:
  971. return sc.processPriority(f)
  972. case *PushPromiseFrame:
  973. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  974. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  975. return ConnectionError(ErrCodeProtocol)
  976. default:
  977. sc.vlogf("Ignoring frame: %v", f.Header())
  978. return nil
  979. }
  980. }
  981. func (sc *serverConn) processPing(f *PingFrame) error {
  982. sc.serveG.check()
  983. if f.Flags.Has(FlagSettingsAck) {
  984. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  985. // containing this flag."
  986. return nil
  987. }
  988. if f.StreamID != 0 {
  989. // "PING frames are not associated with any individual
  990. // stream. If a PING frame is received with a stream
  991. // identifier field value other than 0x0, the recipient MUST
  992. // respond with a connection error (Section 5.4.1) of type
  993. // PROTOCOL_ERROR."
  994. return ConnectionError(ErrCodeProtocol)
  995. }
  996. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  997. return nil
  998. }
  999. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1000. sc.serveG.check()
  1001. switch {
  1002. case f.StreamID != 0: // stream-level flow control
  1003. st := sc.streams[f.StreamID]
  1004. if st == nil {
  1005. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1006. // frame bearing the END_STREAM flag. This means that a
  1007. // receiver could receive a WINDOW_UPDATE frame on a "half
  1008. // closed (remote)" or "closed" stream. A receiver MUST
  1009. // NOT treat this as an error, see Section 5.1."
  1010. return nil
  1011. }
  1012. if !st.flow.add(int32(f.Increment)) {
  1013. return StreamError{f.StreamID, ErrCodeFlowControl}
  1014. }
  1015. default: // connection-level flow control
  1016. if !sc.flow.add(int32(f.Increment)) {
  1017. return goAwayFlowError{}
  1018. }
  1019. }
  1020. sc.scheduleFrameWrite()
  1021. return nil
  1022. }
  1023. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1024. sc.serveG.check()
  1025. state, st := sc.state(f.StreamID)
  1026. if state == stateIdle {
  1027. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1028. // stream in the "idle" state. If a RST_STREAM frame
  1029. // identifying an idle stream is received, the
  1030. // recipient MUST treat this as a connection error
  1031. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1032. return ConnectionError(ErrCodeProtocol)
  1033. }
  1034. if st != nil {
  1035. st.gotReset = true
  1036. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1037. }
  1038. return nil
  1039. }
  1040. func (sc *serverConn) closeStream(st *stream, err error) {
  1041. sc.serveG.check()
  1042. if st.state == stateIdle || st.state == stateClosed {
  1043. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1044. }
  1045. st.state = stateClosed
  1046. sc.curOpenStreams--
  1047. if sc.curOpenStreams == 0 {
  1048. sc.setConnState(http.StateIdle)
  1049. }
  1050. delete(sc.streams, st.id)
  1051. if p := st.body; p != nil {
  1052. p.Close(err)
  1053. }
  1054. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1055. sc.writeSched.forgetStream(st.id)
  1056. }
  1057. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1058. sc.serveG.check()
  1059. if f.IsAck() {
  1060. sc.unackedSettings--
  1061. if sc.unackedSettings < 0 {
  1062. // Why is the peer ACKing settings we never sent?
  1063. // The spec doesn't mention this case, but
  1064. // hang up on them anyway.
  1065. return ConnectionError(ErrCodeProtocol)
  1066. }
  1067. return nil
  1068. }
  1069. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1070. return err
  1071. }
  1072. sc.needToSendSettingsAck = true
  1073. sc.scheduleFrameWrite()
  1074. return nil
  1075. }
  1076. func (sc *serverConn) processSetting(s Setting) error {
  1077. sc.serveG.check()
  1078. if err := s.Valid(); err != nil {
  1079. return err
  1080. }
  1081. sc.vlogf("processing setting %v", s)
  1082. switch s.ID {
  1083. case SettingHeaderTableSize:
  1084. sc.headerTableSize = s.Val
  1085. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1086. case SettingEnablePush:
  1087. sc.pushEnabled = s.Val != 0
  1088. case SettingMaxConcurrentStreams:
  1089. sc.clientMaxStreams = s.Val
  1090. case SettingInitialWindowSize:
  1091. return sc.processSettingInitialWindowSize(s.Val)
  1092. case SettingMaxFrameSize:
  1093. sc.writeSched.maxFrameSize = s.Val
  1094. case SettingMaxHeaderListSize:
  1095. sc.peerMaxHeaderListSize = s.Val
  1096. default:
  1097. // Unknown setting: "An endpoint that receives a SETTINGS
  1098. // frame with any unknown or unsupported identifier MUST
  1099. // ignore that setting."
  1100. }
  1101. return nil
  1102. }
  1103. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1104. sc.serveG.check()
  1105. // Note: val already validated to be within range by
  1106. // processSetting's Valid call.
  1107. // "A SETTINGS frame can alter the initial flow control window
  1108. // size for all current streams. When the value of
  1109. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1110. // adjust the size of all stream flow control windows that it
  1111. // maintains by the difference between the new value and the
  1112. // old value."
  1113. old := sc.initialWindowSize
  1114. sc.initialWindowSize = int32(val)
  1115. growth := sc.initialWindowSize - old // may be negative
  1116. for _, st := range sc.streams {
  1117. if !st.flow.add(growth) {
  1118. // 6.9.2 Initial Flow Control Window Size
  1119. // "An endpoint MUST treat a change to
  1120. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1121. // control window to exceed the maximum size as a
  1122. // connection error (Section 5.4.1) of type
  1123. // FLOW_CONTROL_ERROR."
  1124. return ConnectionError(ErrCodeFlowControl)
  1125. }
  1126. }
  1127. return nil
  1128. }
  1129. func (sc *serverConn) processData(f *DataFrame) error {
  1130. sc.serveG.check()
  1131. // "If a DATA frame is received whose stream is not in "open"
  1132. // or "half closed (local)" state, the recipient MUST respond
  1133. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1134. id := f.Header().StreamID
  1135. st, ok := sc.streams[id]
  1136. if !ok || st.state != stateOpen {
  1137. // This includes sending a RST_STREAM if the stream is
  1138. // in stateHalfClosedLocal (which currently means that
  1139. // the http.Handler returned, so it's done reading &
  1140. // done writing). Try to stop the client from sending
  1141. // more DATA.
  1142. return StreamError{id, ErrCodeStreamClosed}
  1143. }
  1144. if st.body == nil {
  1145. panic("internal error: should have a body in this state")
  1146. }
  1147. data := f.Data()
  1148. // Sender sending more than they'd declared?
  1149. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1150. st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1151. return StreamError{id, ErrCodeStreamClosed}
  1152. }
  1153. if len(data) > 0 {
  1154. // Check whether the client has flow control quota.
  1155. if int(st.inflow.available()) < len(data) {
  1156. return StreamError{id, ErrCodeFlowControl}
  1157. }
  1158. st.inflow.take(int32(len(data)))
  1159. wrote, err := st.body.Write(data)
  1160. if err != nil {
  1161. return StreamError{id, ErrCodeStreamClosed}
  1162. }
  1163. if wrote != len(data) {
  1164. panic("internal error: bad Writer")
  1165. }
  1166. st.bodyBytes += int64(len(data))
  1167. }
  1168. if f.StreamEnded() {
  1169. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1170. st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1171. st.declBodyBytes, st.bodyBytes))
  1172. } else {
  1173. st.body.Close(io.EOF)
  1174. }
  1175. st.state = stateHalfClosedRemote
  1176. }
  1177. return nil
  1178. }
  1179. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1180. sc.serveG.check()
  1181. id := f.Header().StreamID
  1182. if sc.inGoAway {
  1183. // Ignore.
  1184. return nil
  1185. }
  1186. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1187. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  1188. // Streams initiated by a client MUST use odd-numbered
  1189. // stream identifiers. [...] The identifier of a newly
  1190. // established stream MUST be numerically greater than all
  1191. // streams that the initiating endpoint has opened or
  1192. // reserved. [...] An endpoint that receives an unexpected
  1193. // stream identifier MUST respond with a connection error
  1194. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1195. return ConnectionError(ErrCodeProtocol)
  1196. }
  1197. if id > sc.maxStreamID {
  1198. sc.maxStreamID = id
  1199. }
  1200. st := &stream{
  1201. id: id,
  1202. state: stateOpen,
  1203. }
  1204. if f.StreamEnded() {
  1205. st.state = stateHalfClosedRemote
  1206. }
  1207. st.cw.Init()
  1208. st.flow.conn = &sc.flow // link to conn-level counter
  1209. st.flow.add(sc.initialWindowSize)
  1210. st.inflow.conn = &sc.inflow // link to conn-level counter
  1211. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1212. sc.streams[id] = st
  1213. if f.HasPriority() {
  1214. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1215. }
  1216. sc.curOpenStreams++
  1217. if sc.curOpenStreams == 1 {
  1218. sc.setConnState(http.StateActive)
  1219. }
  1220. sc.req = requestParam{
  1221. stream: st,
  1222. header: make(http.Header),
  1223. }
  1224. sc.hpackDecoder.SetEmitEnabled(true)
  1225. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1226. }
  1227. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1228. sc.serveG.check()
  1229. st := sc.streams[f.Header().StreamID]
  1230. if st == nil || sc.curHeaderStreamID() != st.id {
  1231. return ConnectionError(ErrCodeProtocol)
  1232. }
  1233. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1234. }
  1235. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1236. sc.serveG.check()
  1237. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1238. return ConnectionError(ErrCodeCompression)
  1239. }
  1240. if !end {
  1241. return nil
  1242. }
  1243. if err := sc.hpackDecoder.Close(); err != nil {
  1244. return ConnectionError(ErrCodeCompression)
  1245. }
  1246. defer sc.resetPendingRequest()
  1247. if sc.curOpenStreams > sc.advMaxStreams {
  1248. // "Endpoints MUST NOT exceed the limit set by their
  1249. // peer. An endpoint that receives a HEADERS frame
  1250. // that causes their advertised concurrent stream
  1251. // limit to be exceeded MUST treat this as a stream
  1252. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1253. // REFUSED_STREAM."
  1254. if sc.unackedSettings == 0 {
  1255. // They should know better.
  1256. return StreamError{st.id, ErrCodeProtocol}
  1257. }
  1258. // Assume it's a network race, where they just haven't
  1259. // received our last SETTINGS update. But actually
  1260. // this can't happen yet, because we don't yet provide
  1261. // a way for users to adjust server parameters at
  1262. // runtime.
  1263. return StreamError{st.id, ErrCodeRefusedStream}
  1264. }
  1265. rw, req, err := sc.newWriterAndRequest()
  1266. if err != nil {
  1267. return err
  1268. }
  1269. st.body = req.Body.(*requestBody).pipe // may be nil
  1270. st.declBodyBytes = req.ContentLength
  1271. handler := sc.handler.ServeHTTP
  1272. if !sc.hpackDecoder.EmitEnabled() {
  1273. // Their header list was too long. Send a 431 error.
  1274. handler = handleHeaderListTooLong
  1275. }
  1276. go sc.runHandler(rw, req, handler)
  1277. return nil
  1278. }
  1279. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1280. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1281. return nil
  1282. }
  1283. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1284. st, ok := streams[streamID]
  1285. if !ok {
  1286. // TODO: not quite correct (this streamID might
  1287. // already exist in the dep tree, but be closed), but
  1288. // close enough for now.
  1289. return
  1290. }
  1291. st.weight = priority.Weight
  1292. parent := streams[priority.StreamDep] // might be nil
  1293. if parent == st {
  1294. // if client tries to set this stream to be the parent of itself
  1295. // ignore and keep going
  1296. return
  1297. }
  1298. // section 5.3.3: If a stream is made dependent on one of its
  1299. // own dependencies, the formerly dependent stream is first
  1300. // moved to be dependent on the reprioritized stream's previous
  1301. // parent. The moved dependency retains its weight.
  1302. for piter := parent; piter != nil; piter = piter.parent {
  1303. if piter == st {
  1304. parent.parent = st.parent
  1305. break
  1306. }
  1307. }
  1308. st.parent = parent
  1309. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1310. for _, openStream := range streams {
  1311. if openStream != st && openStream.parent == st.parent {
  1312. openStream.parent = st
  1313. }
  1314. }
  1315. }
  1316. }
  1317. // resetPendingRequest zeros out all state related to a HEADERS frame
  1318. // and its zero or more CONTINUATION frames sent to start a new
  1319. // request.
  1320. func (sc *serverConn) resetPendingRequest() {
  1321. sc.serveG.check()
  1322. sc.req = requestParam{}
  1323. }
  1324. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1325. sc.serveG.check()
  1326. rp := &sc.req
  1327. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1328. (rp.scheme != "https" && rp.scheme != "http") {
  1329. // See 8.1.2.6 Malformed Requests and Responses:
  1330. //
  1331. // Malformed requests or responses that are detected
  1332. // MUST be treated as a stream error (Section 5.4.2)
  1333. // of type PROTOCOL_ERROR."
  1334. //
  1335. // 8.1.2.3 Request Pseudo-Header Fields
  1336. // "All HTTP/2 requests MUST include exactly one valid
  1337. // value for the :method, :scheme, and :path
  1338. // pseudo-header fields"
  1339. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1340. }
  1341. var tlsState *tls.ConnectionState // nil if not scheme https
  1342. if rp.scheme == "https" {
  1343. tlsState = sc.tlsState
  1344. }
  1345. authority := rp.authority
  1346. if authority == "" {
  1347. authority = rp.header.Get("Host")
  1348. }
  1349. needsContinue := rp.header.Get("Expect") == "100-continue"
  1350. if needsContinue {
  1351. rp.header.Del("Expect")
  1352. }
  1353. // Merge Cookie headers into one "; "-delimited value.
  1354. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1355. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1356. }
  1357. bodyOpen := rp.stream.state == stateOpen
  1358. body := &requestBody{
  1359. conn: sc,
  1360. stream: rp.stream,
  1361. needsContinue: needsContinue,
  1362. }
  1363. // TODO: handle asterisk '*' requests + test
  1364. url, err := url.ParseRequestURI(rp.path)
  1365. if err != nil {
  1366. // TODO: find the right error code?
  1367. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1368. }
  1369. req := &http.Request{
  1370. Method: rp.method,
  1371. URL: url,
  1372. RemoteAddr: sc.remoteAddrStr,
  1373. Header: rp.header,
  1374. RequestURI: rp.path,
  1375. Proto: "HTTP/2.0",
  1376. ProtoMajor: 2,
  1377. ProtoMinor: 0,
  1378. TLS: tlsState,
  1379. Host: authority,
  1380. Body: body,
  1381. }
  1382. if bodyOpen {
  1383. body.pipe = &pipe{
  1384. b: buffer{buf: make([]byte, initialWindowSize)}, // TODO: share/remove XXX
  1385. }
  1386. body.pipe.c.L = &body.pipe.m
  1387. if vv, ok := rp.header["Content-Length"]; ok {
  1388. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1389. } else {
  1390. req.ContentLength = -1
  1391. }
  1392. }
  1393. rws := responseWriterStatePool.Get().(*responseWriterState)
  1394. bwSave := rws.bw
  1395. *rws = responseWriterState{} // zero all the fields
  1396. rws.conn = sc
  1397. rws.bw = bwSave
  1398. rws.bw.Reset(chunkWriter{rws})
  1399. rws.stream = rp.stream
  1400. rws.req = req
  1401. rws.body = body
  1402. rw := &responseWriter{rws: rws}
  1403. return rw, req, nil
  1404. }
  1405. // Run on its own goroutine.
  1406. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1407. defer rw.handlerDone()
  1408. // TODO: catch panics like net/http.Server
  1409. handler(rw, req)
  1410. }
  1411. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1412. // 10.5.1 Limits on Header Block Size:
  1413. // .. "A server that receives a larger header block than it is
  1414. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1415. // Large) status code"
  1416. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1417. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1418. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1419. }
  1420. // called from handler goroutines.
  1421. // h may be nil.
  1422. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1423. sc.serveG.checkNotOn() // NOT on
  1424. var errc chan error
  1425. if headerData.h != nil {
  1426. // If there's a header map (which we don't own), so we have to block on
  1427. // waiting for this frame to be written, so an http.Flush mid-handler
  1428. // writes out the correct value of keys, before a handler later potentially
  1429. // mutates it.
  1430. errc = errChanPool.Get().(chan error)
  1431. }
  1432. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1433. write: headerData,
  1434. stream: st,
  1435. done: errc,
  1436. }); err != nil {
  1437. return err
  1438. }
  1439. if errc != nil {
  1440. select {
  1441. case err := <-errc:
  1442. errChanPool.Put(errc)
  1443. return err
  1444. case <-sc.doneServing:
  1445. return errClientDisconnected
  1446. case <-st.cw:
  1447. return errStreamClosed
  1448. }
  1449. }
  1450. return nil
  1451. }
  1452. // called from handler goroutines.
  1453. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1454. sc.writeFrameFromHandler(frameWriteMsg{
  1455. write: write100ContinueHeadersFrame{st.id},
  1456. stream: st,
  1457. })
  1458. }
  1459. // A bodyReadMsg tells the server loop that the http.Handler read n
  1460. // bytes of the DATA from the client on the given stream.
  1461. type bodyReadMsg struct {
  1462. st *stream
  1463. n int
  1464. }
  1465. // called from handler goroutines.
  1466. // Notes that the handler for the given stream ID read n bytes of its body
  1467. // and schedules flow control tokens to be sent.
  1468. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1469. sc.serveG.checkNotOn() // NOT on
  1470. sc.bodyReadCh <- bodyReadMsg{st, n}
  1471. }
  1472. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1473. sc.serveG.check()
  1474. sc.sendWindowUpdate(nil, n) // conn-level
  1475. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1476. // Don't send this WINDOW_UPDATE if the stream is closed
  1477. // remotely.
  1478. sc.sendWindowUpdate(st, n)
  1479. }
  1480. }
  1481. // st may be nil for conn-level
  1482. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1483. sc.serveG.check()
  1484. // "The legal range for the increment to the flow control
  1485. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1486. // A Go Read call on 64-bit machines could in theory read
  1487. // a larger Read than this. Very unlikely, but we handle it here
  1488. // rather than elsewhere for now.
  1489. const maxUint31 = 1<<31 - 1
  1490. for n >= maxUint31 {
  1491. sc.sendWindowUpdate32(st, maxUint31)
  1492. n -= maxUint31
  1493. }
  1494. sc.sendWindowUpdate32(st, int32(n))
  1495. }
  1496. // st may be nil for conn-level
  1497. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1498. sc.serveG.check()
  1499. if n == 0 {
  1500. return
  1501. }
  1502. if n < 0 {
  1503. panic("negative update")
  1504. }
  1505. var streamID uint32
  1506. if st != nil {
  1507. streamID = st.id
  1508. }
  1509. sc.writeFrame(frameWriteMsg{
  1510. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1511. stream: st,
  1512. })
  1513. var ok bool
  1514. if st == nil {
  1515. ok = sc.inflow.add(n)
  1516. } else {
  1517. ok = st.inflow.add(n)
  1518. }
  1519. if !ok {
  1520. panic("internal error; sent too many window updates without decrements?")
  1521. }
  1522. }
  1523. type requestBody struct {
  1524. stream *stream
  1525. conn *serverConn
  1526. closed bool
  1527. pipe *pipe // non-nil if we have a HTTP entity message body
  1528. needsContinue bool // need to send a 100-continue
  1529. }
  1530. func (b *requestBody) Close() error {
  1531. if b.pipe != nil {
  1532. b.pipe.Close(errClosedBody)
  1533. }
  1534. b.closed = true
  1535. return nil
  1536. }
  1537. func (b *requestBody) Read(p []byte) (n int, err error) {
  1538. if b.needsContinue {
  1539. b.needsContinue = false
  1540. b.conn.write100ContinueHeaders(b.stream)
  1541. }
  1542. if b.pipe == nil {
  1543. return 0, io.EOF
  1544. }
  1545. n, err = b.pipe.Read(p)
  1546. if n > 0 {
  1547. b.conn.noteBodyReadFromHandler(b.stream, n)
  1548. }
  1549. return
  1550. }
  1551. // responseWriter is the http.ResponseWriter implementation. It's
  1552. // intentionally small (1 pointer wide) to minimize garbage. The
  1553. // responseWriterState pointer inside is zeroed at the end of a
  1554. // request (in handlerDone) and calls on the responseWriter thereafter
  1555. // simply crash (caller's mistake), but the much larger responseWriterState
  1556. // and buffers are reused between multiple requests.
  1557. type responseWriter struct {
  1558. rws *responseWriterState
  1559. }
  1560. // Optional http.ResponseWriter interfaces implemented.
  1561. var (
  1562. _ http.CloseNotifier = (*responseWriter)(nil)
  1563. _ http.Flusher = (*responseWriter)(nil)
  1564. _ stringWriter = (*responseWriter)(nil)
  1565. )
  1566. type responseWriterState struct {
  1567. // immutable within a request:
  1568. stream *stream
  1569. req *http.Request
  1570. body *requestBody // to close at end of request, if DATA frames didn't
  1571. conn *serverConn
  1572. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1573. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1574. // mutated by http.Handler goroutine:
  1575. handlerHeader http.Header // nil until called
  1576. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1577. status int // status code passed to WriteHeader
  1578. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1579. sentHeader bool // have we sent the header frame?
  1580. handlerDone bool // handler has finished
  1581. curWrite writeData
  1582. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1583. closeNotifierCh chan bool // nil until first used
  1584. }
  1585. type chunkWriter struct{ rws *responseWriterState }
  1586. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1587. // writeChunk writes chunks from the bufio.Writer. But because
  1588. // bufio.Writer may bypass its chunking, sometimes p may be
  1589. // arbitrarily large.
  1590. //
  1591. // writeChunk is also responsible (on the first chunk) for sending the
  1592. // HEADER response.
  1593. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1594. if !rws.wroteHeader {
  1595. rws.writeHeader(200)
  1596. }
  1597. if !rws.sentHeader {
  1598. rws.sentHeader = true
  1599. var ctype, clen string // implicit ones, if we can calculate it
  1600. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1601. clen = strconv.Itoa(len(p))
  1602. }
  1603. if rws.snapHeader.Get("Content-Type") == "" {
  1604. ctype = http.DetectContentType(p)
  1605. }
  1606. endStream := rws.handlerDone && len(p) == 0
  1607. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1608. streamID: rws.stream.id,
  1609. httpResCode: rws.status,
  1610. h: rws.snapHeader,
  1611. endStream: endStream,
  1612. contentType: ctype,
  1613. contentLength: clen,
  1614. })
  1615. if err != nil {
  1616. return 0, err
  1617. }
  1618. if endStream {
  1619. return 0, nil
  1620. }
  1621. }
  1622. if len(p) == 0 && !rws.handlerDone {
  1623. return 0, nil
  1624. }
  1625. // Reuse curWrite (which as a pointer fits into the
  1626. // 'writeFramer' interface value) for each write to avoid an
  1627. // allocation per write.
  1628. curWrite := &rws.curWrite
  1629. curWrite.streamID = rws.stream.id
  1630. curWrite.p = p
  1631. curWrite.endStream = rws.handlerDone
  1632. if err := rws.conn.writeDataFromHandler(rws.stream, curWrite); err != nil {
  1633. return 0, err
  1634. }
  1635. return len(p), nil
  1636. }
  1637. func (w *responseWriter) Flush() {
  1638. rws := w.rws
  1639. if rws == nil {
  1640. panic("Header called after Handler finished")
  1641. }
  1642. if rws.bw.Buffered() > 0 {
  1643. if err := rws.bw.Flush(); err != nil {
  1644. // Ignore the error. The frame writer already knows.
  1645. return
  1646. }
  1647. } else {
  1648. // The bufio.Writer won't call chunkWriter.Write
  1649. // (writeChunk with zero bytes, so we have to do it
  1650. // ourselves to force the HTTP response header and/or
  1651. // final DATA frame (with END_STREAM) to be sent.
  1652. rws.writeChunk(nil)
  1653. }
  1654. }
  1655. func (w *responseWriter) CloseNotify() <-chan bool {
  1656. rws := w.rws
  1657. if rws == nil {
  1658. panic("CloseNotify called after Handler finished")
  1659. }
  1660. rws.closeNotifierMu.Lock()
  1661. ch := rws.closeNotifierCh
  1662. if ch == nil {
  1663. ch = make(chan bool, 1)
  1664. rws.closeNotifierCh = ch
  1665. go func() {
  1666. rws.stream.cw.Wait() // wait for close
  1667. ch <- true
  1668. }()
  1669. }
  1670. rws.closeNotifierMu.Unlock()
  1671. return ch
  1672. }
  1673. func (w *responseWriter) Header() http.Header {
  1674. rws := w.rws
  1675. if rws == nil {
  1676. panic("Header called after Handler finished")
  1677. }
  1678. if rws.handlerHeader == nil {
  1679. rws.handlerHeader = make(http.Header)
  1680. }
  1681. return rws.handlerHeader
  1682. }
  1683. func (w *responseWriter) WriteHeader(code int) {
  1684. rws := w.rws
  1685. if rws == nil {
  1686. panic("WriteHeader called after Handler finished")
  1687. }
  1688. rws.writeHeader(code)
  1689. }
  1690. func (rws *responseWriterState) writeHeader(code int) {
  1691. if !rws.wroteHeader {
  1692. rws.wroteHeader = true
  1693. rws.status = code
  1694. if len(rws.handlerHeader) > 0 {
  1695. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1696. }
  1697. }
  1698. }
  1699. func cloneHeader(h http.Header) http.Header {
  1700. h2 := make(http.Header, len(h))
  1701. for k, vv := range h {
  1702. vv2 := make([]string, len(vv))
  1703. copy(vv2, vv)
  1704. h2[k] = vv2
  1705. }
  1706. return h2
  1707. }
  1708. // The Life Of A Write is like this:
  1709. //
  1710. // * Handler calls w.Write or w.WriteString ->
  1711. // * -> rws.bw (*bufio.Writer) ->
  1712. // * (Handler migth call Flush)
  1713. // * -> chunkWriter{rws}
  1714. // * -> responseWriterState.writeChunk(p []byte)
  1715. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1716. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1717. return w.write(len(p), p, "")
  1718. }
  1719. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1720. return w.write(len(s), nil, s)
  1721. }
  1722. // either dataB or dataS is non-zero.
  1723. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1724. rws := w.rws
  1725. if rws == nil {
  1726. panic("Write called after Handler finished")
  1727. }
  1728. if !rws.wroteHeader {
  1729. w.WriteHeader(200)
  1730. }
  1731. if dataB != nil {
  1732. return rws.bw.Write(dataB)
  1733. } else {
  1734. return rws.bw.WriteString(dataS)
  1735. }
  1736. }
  1737. func (w *responseWriter) handlerDone() {
  1738. rws := w.rws
  1739. if rws == nil {
  1740. panic("handlerDone called twice")
  1741. }
  1742. rws.handlerDone = true
  1743. w.Flush()
  1744. w.rws = nil
  1745. responseWriterStatePool.Put(rws)
  1746. }