server.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  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. errStreamBroken = errors.New("http2: stream broken")
  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 struct{}, 1), // buffered; one send in reading goroutine
  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 struct{} // 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. // writeFrameAsync runs in its own goroutine and writes a single frame
  536. // and then reports when it's done.
  537. // At most one goroutine can be running writeFrameAsync at a time per
  538. // serverConn.
  539. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  540. err := wm.write.writeFrame(sc)
  541. if ch := wm.done; ch != nil {
  542. select {
  543. case ch <- err:
  544. default:
  545. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  546. }
  547. }
  548. sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler
  549. }
  550. func (sc *serverConn) closeAllStreamsOnConnClose() {
  551. sc.serveG.check()
  552. for _, st := range sc.streams {
  553. sc.closeStream(st, errClientDisconnected)
  554. }
  555. }
  556. func (sc *serverConn) stopShutdownTimer() {
  557. sc.serveG.check()
  558. if t := sc.shutdownTimer; t != nil {
  559. t.Stop()
  560. }
  561. }
  562. func (sc *serverConn) notePanic() {
  563. if testHookOnPanicMu != nil {
  564. testHookOnPanicMu.Lock()
  565. defer testHookOnPanicMu.Unlock()
  566. }
  567. if testHookOnPanic != nil {
  568. if e := recover(); e != nil {
  569. if testHookOnPanic(sc, e) {
  570. panic(e)
  571. }
  572. }
  573. }
  574. }
  575. func (sc *serverConn) serve() {
  576. sc.serveG.check()
  577. defer sc.notePanic()
  578. defer sc.conn.Close()
  579. defer sc.closeAllStreamsOnConnClose()
  580. defer sc.stopShutdownTimer()
  581. defer close(sc.doneServing) // unblocks handlers trying to send
  582. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  583. sc.writeFrame(frameWriteMsg{
  584. write: writeSettings{
  585. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  586. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  587. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  588. // TODO: more actual settings, notably
  589. // SettingInitialWindowSize, but then we also
  590. // want to bump up the conn window size the
  591. // same amount here right after the settings
  592. },
  593. })
  594. sc.unackedSettings++
  595. if err := sc.readPreface(); err != nil {
  596. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  597. return
  598. }
  599. // Now that we've got the preface, get us out of the
  600. // "StateNew" state. We can't go directly to idle, though.
  601. // Active means we read some data and anticipate a request. We'll
  602. // do another Active when we get a HEADERS frame.
  603. sc.setConnState(http.StateActive)
  604. sc.setConnState(http.StateIdle)
  605. go sc.readFrames() // closed by defer sc.conn.Close above
  606. settingsTimer := time.NewTimer(firstSettingsTimeout)
  607. loopNum := 0
  608. for {
  609. loopNum++
  610. select {
  611. case wm := <-sc.wantWriteFrameCh:
  612. sc.writeFrame(wm)
  613. case <-sc.wroteFrameCh:
  614. if sc.writingFrame != true {
  615. panic("internal error: expected to be already writing a frame")
  616. }
  617. sc.writingFrame = false
  618. sc.scheduleFrameWrite()
  619. case res := <-sc.readFrameCh:
  620. if !sc.processFrameFromReader(res) {
  621. return
  622. }
  623. res.readMore()
  624. if settingsTimer.C != nil {
  625. settingsTimer.Stop()
  626. settingsTimer.C = nil
  627. }
  628. case m := <-sc.bodyReadCh:
  629. sc.noteBodyRead(m.st, m.n)
  630. case <-settingsTimer.C:
  631. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  632. return
  633. case <-sc.shutdownTimerCh:
  634. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  635. return
  636. case fn := <-sc.testHookCh:
  637. fn(loopNum)
  638. }
  639. }
  640. }
  641. // readPreface reads the ClientPreface greeting from the peer
  642. // or returns an error on timeout or an invalid greeting.
  643. func (sc *serverConn) readPreface() error {
  644. errc := make(chan error, 1)
  645. go func() {
  646. // Read the client preface
  647. buf := make([]byte, len(ClientPreface))
  648. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  649. errc <- err
  650. } else if !bytes.Equal(buf, clientPreface) {
  651. errc <- fmt.Errorf("bogus greeting %q", buf)
  652. } else {
  653. errc <- nil
  654. }
  655. }()
  656. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  657. defer timer.Stop()
  658. select {
  659. case <-timer.C:
  660. return errors.New("timeout waiting for client preface")
  661. case err := <-errc:
  662. if err == nil {
  663. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  664. }
  665. return err
  666. }
  667. }
  668. var errChanPool = sync.Pool{
  669. New: func() interface{} { return make(chan error, 1) },
  670. }
  671. // writeDataFromHandler writes the data described in req to stream.id.
  672. //
  673. // The flow control currently happens in the Handler where it waits
  674. // for 1 or more bytes to be available to then write here. So at this
  675. // point we know that we have flow control. But this might have to
  676. // change when priority is implemented, so the serve goroutine knows
  677. // the total amount of bytes waiting to be sent and can can have more
  678. // scheduling decisions available.
  679. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData) error {
  680. ch := errChanPool.Get().(chan error)
  681. sc.writeFrameFromHandler(frameWriteMsg{
  682. write: writeData,
  683. stream: stream,
  684. done: ch,
  685. })
  686. select {
  687. case err := <-ch:
  688. errChanPool.Put(ch)
  689. return err
  690. case <-sc.doneServing:
  691. return errClientDisconnected
  692. case <-stream.cw:
  693. return errStreamBroken
  694. }
  695. }
  696. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  697. // if the connection has gone away.
  698. //
  699. // This must not be run from the serve goroutine itself, else it might
  700. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  701. // buffered and is read by serve itself). If you're on the serve
  702. // goroutine, call writeFrame instead.
  703. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) {
  704. sc.serveG.checkNotOn() // NOT
  705. var scheduled bool
  706. select {
  707. case sc.wantWriteFrameCh <- wm:
  708. scheduled = true
  709. case <-sc.doneServing:
  710. // Client has closed their connection to the server.
  711. case <-wm.stream.cw:
  712. // Stream closed.
  713. }
  714. // Don't block writers expecting a reply.
  715. if !scheduled && wm.done != nil {
  716. select {
  717. case wm.done <- errStreamBroken:
  718. default:
  719. panic("expected buffered channel")
  720. }
  721. }
  722. }
  723. // writeFrame schedules a frame to write and sends it if there's nothing
  724. // already being written.
  725. //
  726. // There is no pushback here (the serve goroutine never blocks). It's
  727. // the http.Handlers that block, waiting for their previous frames to
  728. // make it onto the wire
  729. //
  730. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  731. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  732. sc.serveG.check()
  733. sc.writeSched.add(wm)
  734. sc.scheduleFrameWrite()
  735. }
  736. // startFrameWrite starts a goroutine to write wm (in a separate
  737. // goroutine since that might block on the network), and updates the
  738. // serve goroutine's state about the world, updated from info in wm.
  739. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  740. sc.serveG.check()
  741. if sc.writingFrame {
  742. panic("internal error: can only be writing one frame at a time")
  743. }
  744. sc.writingFrame = true
  745. st := wm.stream
  746. if st != nil {
  747. switch st.state {
  748. case stateHalfClosedLocal:
  749. panic("internal error: attempt to send frame on half-closed-local stream")
  750. case stateClosed:
  751. if st.sentReset || st.gotReset {
  752. // Skip this frame. But fake the frame write to reschedule:
  753. sc.wroteFrameCh <- struct{}{}
  754. return
  755. }
  756. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  757. }
  758. }
  759. sc.needsFrameFlush = true
  760. if endsStream(wm.write) {
  761. if st == nil {
  762. panic("internal error: expecting non-nil stream")
  763. }
  764. switch st.state {
  765. case stateOpen:
  766. // Here we would go to stateHalfClosedLocal in
  767. // theory, but since our handler is done and
  768. // the net/http package provides no mechanism
  769. // for finishing writing to a ResponseWriter
  770. // while still reading data (see possible TODO
  771. // at top of this file), we go into closed
  772. // state here anyway, after telling the peer
  773. // we're hanging up on them.
  774. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  775. errCancel := StreamError{st.id, ErrCodeCancel}
  776. sc.resetStream(errCancel)
  777. case stateHalfClosedRemote:
  778. sc.closeStream(st, nil)
  779. }
  780. }
  781. go sc.writeFrameAsync(wm)
  782. }
  783. // scheduleFrameWrite tickles the frame writing scheduler.
  784. //
  785. // If a frame is already being written, nothing happens. This will be called again
  786. // when the frame is done being written.
  787. //
  788. // If a frame isn't being written we need to send one, the best frame
  789. // to send is selected, preferring first things that aren't
  790. // stream-specific (e.g. ACKing settings), and then finding the
  791. // highest priority stream.
  792. //
  793. // If a frame isn't being written and there's nothing else to send, we
  794. // flush the write buffer.
  795. func (sc *serverConn) scheduleFrameWrite() {
  796. sc.serveG.check()
  797. if sc.writingFrame {
  798. return
  799. }
  800. if sc.needToSendGoAway {
  801. sc.needToSendGoAway = false
  802. sc.startFrameWrite(frameWriteMsg{
  803. write: &writeGoAway{
  804. maxStreamID: sc.maxStreamID,
  805. code: sc.goAwayCode,
  806. },
  807. })
  808. return
  809. }
  810. if sc.needToSendSettingsAck {
  811. sc.needToSendSettingsAck = false
  812. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  813. return
  814. }
  815. if !sc.inGoAway {
  816. if wm, ok := sc.writeSched.take(); ok {
  817. sc.startFrameWrite(wm)
  818. return
  819. }
  820. }
  821. if sc.needsFrameFlush {
  822. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  823. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  824. return
  825. }
  826. }
  827. func (sc *serverConn) goAway(code ErrCode) {
  828. sc.serveG.check()
  829. if sc.inGoAway {
  830. return
  831. }
  832. if code != ErrCodeNo {
  833. sc.shutDownIn(250 * time.Millisecond)
  834. } else {
  835. // TODO: configurable
  836. sc.shutDownIn(1 * time.Second)
  837. }
  838. sc.inGoAway = true
  839. sc.needToSendGoAway = true
  840. sc.goAwayCode = code
  841. sc.scheduleFrameWrite()
  842. }
  843. func (sc *serverConn) shutDownIn(d time.Duration) {
  844. sc.serveG.check()
  845. sc.shutdownTimer = time.NewTimer(d)
  846. sc.shutdownTimerCh = sc.shutdownTimer.C
  847. }
  848. func (sc *serverConn) resetStream(se StreamError) {
  849. sc.serveG.check()
  850. sc.writeFrame(frameWriteMsg{write: se})
  851. if st, ok := sc.streams[se.StreamID]; ok {
  852. st.sentReset = true
  853. sc.closeStream(st, se)
  854. }
  855. }
  856. // curHeaderStreamID returns the stream ID of the header block we're
  857. // currently in the middle of reading. If this returns non-zero, the
  858. // next frame must be a CONTINUATION with this stream id.
  859. func (sc *serverConn) curHeaderStreamID() uint32 {
  860. sc.serveG.check()
  861. st := sc.req.stream
  862. if st == nil {
  863. return 0
  864. }
  865. return st.id
  866. }
  867. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  868. // frame-reading goroutine.
  869. // processFrameFromReader returns whether the connection should be kept open.
  870. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  871. sc.serveG.check()
  872. err := res.err
  873. if err != nil {
  874. if err == ErrFrameTooLarge {
  875. sc.goAway(ErrCodeFrameSize)
  876. return true // goAway will close the loop
  877. }
  878. clientGone := err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  879. if clientGone {
  880. // TODO: could we also get into this state if
  881. // the peer does a half close
  882. // (e.g. CloseWrite) because they're done
  883. // sending frames but they're still wanting
  884. // our open replies? Investigate.
  885. // TODO: add CloseWrite to crypto/tls.Conn first
  886. // so we have a way to test this? I suppose
  887. // just for testing we could have a non-TLS mode.
  888. return false
  889. }
  890. } else {
  891. f := res.f
  892. sc.vlogf("got %v: %#v", f.Header(), f)
  893. err = sc.processFrame(f)
  894. if err == nil {
  895. return true
  896. }
  897. }
  898. switch ev := err.(type) {
  899. case StreamError:
  900. sc.resetStream(ev)
  901. return true
  902. case goAwayFlowError:
  903. sc.goAway(ErrCodeFlowControl)
  904. return true
  905. case ConnectionError:
  906. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  907. sc.goAway(ErrCode(ev))
  908. return true // goAway will handle shutdown
  909. default:
  910. if res.err != nil {
  911. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  912. } else {
  913. sc.logf("disconnection due to other error: %v", err)
  914. }
  915. return false
  916. }
  917. }
  918. func (sc *serverConn) processFrame(f Frame) error {
  919. sc.serveG.check()
  920. // First frame received must be SETTINGS.
  921. if !sc.sawFirstSettings {
  922. if _, ok := f.(*SettingsFrame); !ok {
  923. return ConnectionError(ErrCodeProtocol)
  924. }
  925. sc.sawFirstSettings = true
  926. }
  927. if s := sc.curHeaderStreamID(); s != 0 {
  928. if cf, ok := f.(*ContinuationFrame); !ok {
  929. return ConnectionError(ErrCodeProtocol)
  930. } else if cf.Header().StreamID != s {
  931. return ConnectionError(ErrCodeProtocol)
  932. }
  933. }
  934. switch f := f.(type) {
  935. case *SettingsFrame:
  936. return sc.processSettings(f)
  937. case *HeadersFrame:
  938. return sc.processHeaders(f)
  939. case *ContinuationFrame:
  940. return sc.processContinuation(f)
  941. case *WindowUpdateFrame:
  942. return sc.processWindowUpdate(f)
  943. case *PingFrame:
  944. return sc.processPing(f)
  945. case *DataFrame:
  946. return sc.processData(f)
  947. case *RSTStreamFrame:
  948. return sc.processResetStream(f)
  949. case *PriorityFrame:
  950. return sc.processPriority(f)
  951. case *PushPromiseFrame:
  952. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  953. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  954. return ConnectionError(ErrCodeProtocol)
  955. default:
  956. sc.vlogf("Ignoring frame: %v", f.Header())
  957. return nil
  958. }
  959. }
  960. func (sc *serverConn) processPing(f *PingFrame) error {
  961. sc.serveG.check()
  962. if f.Flags.Has(FlagSettingsAck) {
  963. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  964. // containing this flag."
  965. return nil
  966. }
  967. if f.StreamID != 0 {
  968. // "PING frames are not associated with any individual
  969. // stream. If a PING frame is received with a stream
  970. // identifier field value other than 0x0, the recipient MUST
  971. // respond with a connection error (Section 5.4.1) of type
  972. // PROTOCOL_ERROR."
  973. return ConnectionError(ErrCodeProtocol)
  974. }
  975. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  976. return nil
  977. }
  978. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  979. sc.serveG.check()
  980. switch {
  981. case f.StreamID != 0: // stream-level flow control
  982. st := sc.streams[f.StreamID]
  983. if st == nil {
  984. // "WINDOW_UPDATE can be sent by a peer that has sent a
  985. // frame bearing the END_STREAM flag. This means that a
  986. // receiver could receive a WINDOW_UPDATE frame on a "half
  987. // closed (remote)" or "closed" stream. A receiver MUST
  988. // NOT treat this as an error, see Section 5.1."
  989. return nil
  990. }
  991. if !st.flow.add(int32(f.Increment)) {
  992. return StreamError{f.StreamID, ErrCodeFlowControl}
  993. }
  994. default: // connection-level flow control
  995. if !sc.flow.add(int32(f.Increment)) {
  996. return goAwayFlowError{}
  997. }
  998. }
  999. sc.scheduleFrameWrite()
  1000. return nil
  1001. }
  1002. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1003. sc.serveG.check()
  1004. state, st := sc.state(f.StreamID)
  1005. if state == stateIdle {
  1006. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1007. // stream in the "idle" state. If a RST_STREAM frame
  1008. // identifying an idle stream is received, the
  1009. // recipient MUST treat this as a connection error
  1010. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1011. return ConnectionError(ErrCodeProtocol)
  1012. }
  1013. if st != nil {
  1014. st.gotReset = true
  1015. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1016. }
  1017. return nil
  1018. }
  1019. func (sc *serverConn) closeStream(st *stream, err error) {
  1020. sc.serveG.check()
  1021. if st.state == stateIdle || st.state == stateClosed {
  1022. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1023. }
  1024. st.state = stateClosed
  1025. sc.curOpenStreams--
  1026. if sc.curOpenStreams == 0 {
  1027. sc.setConnState(http.StateIdle)
  1028. }
  1029. delete(sc.streams, st.id)
  1030. if p := st.body; p != nil {
  1031. p.Close(err)
  1032. }
  1033. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1034. sc.writeSched.forgetStream(st.id)
  1035. }
  1036. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1037. sc.serveG.check()
  1038. if f.IsAck() {
  1039. sc.unackedSettings--
  1040. if sc.unackedSettings < 0 {
  1041. // Why is the peer ACKing settings we never sent?
  1042. // The spec doesn't mention this case, but
  1043. // hang up on them anyway.
  1044. return ConnectionError(ErrCodeProtocol)
  1045. }
  1046. return nil
  1047. }
  1048. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1049. return err
  1050. }
  1051. sc.needToSendSettingsAck = true
  1052. sc.scheduleFrameWrite()
  1053. return nil
  1054. }
  1055. func (sc *serverConn) processSetting(s Setting) error {
  1056. sc.serveG.check()
  1057. if err := s.Valid(); err != nil {
  1058. return err
  1059. }
  1060. sc.vlogf("processing setting %v", s)
  1061. switch s.ID {
  1062. case SettingHeaderTableSize:
  1063. sc.headerTableSize = s.Val
  1064. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1065. case SettingEnablePush:
  1066. sc.pushEnabled = s.Val != 0
  1067. case SettingMaxConcurrentStreams:
  1068. sc.clientMaxStreams = s.Val
  1069. case SettingInitialWindowSize:
  1070. return sc.processSettingInitialWindowSize(s.Val)
  1071. case SettingMaxFrameSize:
  1072. sc.writeSched.maxFrameSize = s.Val
  1073. case SettingMaxHeaderListSize:
  1074. sc.peerMaxHeaderListSize = s.Val
  1075. default:
  1076. // Unknown setting: "An endpoint that receives a SETTINGS
  1077. // frame with any unknown or unsupported identifier MUST
  1078. // ignore that setting."
  1079. }
  1080. return nil
  1081. }
  1082. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1083. sc.serveG.check()
  1084. // Note: val already validated to be within range by
  1085. // processSetting's Valid call.
  1086. // "A SETTINGS frame can alter the initial flow control window
  1087. // size for all current streams. When the value of
  1088. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1089. // adjust the size of all stream flow control windows that it
  1090. // maintains by the difference between the new value and the
  1091. // old value."
  1092. old := sc.initialWindowSize
  1093. sc.initialWindowSize = int32(val)
  1094. growth := sc.initialWindowSize - old // may be negative
  1095. for _, st := range sc.streams {
  1096. if !st.flow.add(growth) {
  1097. // 6.9.2 Initial Flow Control Window Size
  1098. // "An endpoint MUST treat a change to
  1099. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1100. // control window to exceed the maximum size as a
  1101. // connection error (Section 5.4.1) of type
  1102. // FLOW_CONTROL_ERROR."
  1103. return ConnectionError(ErrCodeFlowControl)
  1104. }
  1105. }
  1106. return nil
  1107. }
  1108. func (sc *serverConn) processData(f *DataFrame) error {
  1109. sc.serveG.check()
  1110. // "If a DATA frame is received whose stream is not in "open"
  1111. // or "half closed (local)" state, the recipient MUST respond
  1112. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1113. id := f.Header().StreamID
  1114. st, ok := sc.streams[id]
  1115. if !ok || st.state != stateOpen {
  1116. // This includes sending a RST_STREAM if the stream is
  1117. // in stateHalfClosedLocal (which currently means that
  1118. // the http.Handler returned, so it's done reading &
  1119. // done writing). Try to stop the client from sending
  1120. // more DATA.
  1121. return StreamError{id, ErrCodeStreamClosed}
  1122. }
  1123. if st.body == nil {
  1124. panic("internal error: should have a body in this state")
  1125. }
  1126. data := f.Data()
  1127. // Sender sending more than they'd declared?
  1128. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1129. st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1130. return StreamError{id, ErrCodeStreamClosed}
  1131. }
  1132. if len(data) > 0 {
  1133. // Check whether the client has flow control quota.
  1134. if int(st.inflow.available()) < len(data) {
  1135. return StreamError{id, ErrCodeFlowControl}
  1136. }
  1137. st.inflow.take(int32(len(data)))
  1138. wrote, err := st.body.Write(data)
  1139. if err != nil {
  1140. return StreamError{id, ErrCodeStreamClosed}
  1141. }
  1142. if wrote != len(data) {
  1143. panic("internal error: bad Writer")
  1144. }
  1145. st.bodyBytes += int64(len(data))
  1146. }
  1147. if f.StreamEnded() {
  1148. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1149. st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1150. st.declBodyBytes, st.bodyBytes))
  1151. } else {
  1152. st.body.Close(io.EOF)
  1153. }
  1154. st.state = stateHalfClosedRemote
  1155. }
  1156. return nil
  1157. }
  1158. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1159. sc.serveG.check()
  1160. id := f.Header().StreamID
  1161. if sc.inGoAway {
  1162. // Ignore.
  1163. return nil
  1164. }
  1165. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1166. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  1167. // Streams initiated by a client MUST use odd-numbered
  1168. // stream identifiers. [...] The identifier of a newly
  1169. // established stream MUST be numerically greater than all
  1170. // streams that the initiating endpoint has opened or
  1171. // reserved. [...] An endpoint that receives an unexpected
  1172. // stream identifier MUST respond with a connection error
  1173. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1174. return ConnectionError(ErrCodeProtocol)
  1175. }
  1176. if id > sc.maxStreamID {
  1177. sc.maxStreamID = id
  1178. }
  1179. st := &stream{
  1180. id: id,
  1181. state: stateOpen,
  1182. }
  1183. if f.StreamEnded() {
  1184. st.state = stateHalfClosedRemote
  1185. }
  1186. st.cw.Init()
  1187. st.flow.conn = &sc.flow // link to conn-level counter
  1188. st.flow.add(sc.initialWindowSize)
  1189. st.inflow.conn = &sc.inflow // link to conn-level counter
  1190. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1191. sc.streams[id] = st
  1192. if f.HasPriority() {
  1193. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1194. }
  1195. sc.curOpenStreams++
  1196. if sc.curOpenStreams == 1 {
  1197. sc.setConnState(http.StateActive)
  1198. }
  1199. sc.req = requestParam{
  1200. stream: st,
  1201. header: make(http.Header),
  1202. }
  1203. sc.hpackDecoder.SetEmitEnabled(true)
  1204. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1205. }
  1206. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1207. sc.serveG.check()
  1208. st := sc.streams[f.Header().StreamID]
  1209. if st == nil || sc.curHeaderStreamID() != st.id {
  1210. return ConnectionError(ErrCodeProtocol)
  1211. }
  1212. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1213. }
  1214. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1215. sc.serveG.check()
  1216. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1217. return ConnectionError(ErrCodeCompression)
  1218. }
  1219. if !end {
  1220. return nil
  1221. }
  1222. if err := sc.hpackDecoder.Close(); err != nil {
  1223. return ConnectionError(ErrCodeCompression)
  1224. }
  1225. defer sc.resetPendingRequest()
  1226. if sc.curOpenStreams > sc.advMaxStreams {
  1227. // "Endpoints MUST NOT exceed the limit set by their
  1228. // peer. An endpoint that receives a HEADERS frame
  1229. // that causes their advertised concurrent stream
  1230. // limit to be exceeded MUST treat this as a stream
  1231. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1232. // REFUSED_STREAM."
  1233. if sc.unackedSettings == 0 {
  1234. // They should know better.
  1235. return StreamError{st.id, ErrCodeProtocol}
  1236. }
  1237. // Assume it's a network race, where they just haven't
  1238. // received our last SETTINGS update. But actually
  1239. // this can't happen yet, because we don't yet provide
  1240. // a way for users to adjust server parameters at
  1241. // runtime.
  1242. return StreamError{st.id, ErrCodeRefusedStream}
  1243. }
  1244. rw, req, err := sc.newWriterAndRequest()
  1245. if err != nil {
  1246. return err
  1247. }
  1248. st.body = req.Body.(*requestBody).pipe // may be nil
  1249. st.declBodyBytes = req.ContentLength
  1250. handler := sc.handler.ServeHTTP
  1251. if !sc.hpackDecoder.EmitEnabled() {
  1252. // Their header list was too long. Send a 431 error.
  1253. handler = handleHeaderListTooLong
  1254. }
  1255. go sc.runHandler(rw, req, handler)
  1256. return nil
  1257. }
  1258. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1259. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1260. return nil
  1261. }
  1262. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1263. st, ok := streams[streamID]
  1264. if !ok {
  1265. // TODO: not quite correct (this streamID might
  1266. // already exist in the dep tree, but be closed), but
  1267. // close enough for now.
  1268. return
  1269. }
  1270. st.weight = priority.Weight
  1271. parent := streams[priority.StreamDep] // might be nil
  1272. if parent == st {
  1273. // if client tries to set this stream to be the parent of itself
  1274. // ignore and keep going
  1275. return
  1276. }
  1277. // section 5.3.3: If a stream is made dependent on one of its
  1278. // own dependencies, the formerly dependent stream is first
  1279. // moved to be dependent on the reprioritized stream's previous
  1280. // parent. The moved dependency retains its weight.
  1281. for piter := parent; piter != nil; piter = piter.parent {
  1282. if piter == st {
  1283. parent.parent = st.parent
  1284. break
  1285. }
  1286. }
  1287. st.parent = parent
  1288. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1289. for _, openStream := range streams {
  1290. if openStream != st && openStream.parent == st.parent {
  1291. openStream.parent = st
  1292. }
  1293. }
  1294. }
  1295. }
  1296. // resetPendingRequest zeros out all state related to a HEADERS frame
  1297. // and its zero or more CONTINUATION frames sent to start a new
  1298. // request.
  1299. func (sc *serverConn) resetPendingRequest() {
  1300. sc.serveG.check()
  1301. sc.req = requestParam{}
  1302. }
  1303. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1304. sc.serveG.check()
  1305. rp := &sc.req
  1306. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1307. (rp.scheme != "https" && rp.scheme != "http") {
  1308. // See 8.1.2.6 Malformed Requests and Responses:
  1309. //
  1310. // Malformed requests or responses that are detected
  1311. // MUST be treated as a stream error (Section 5.4.2)
  1312. // of type PROTOCOL_ERROR."
  1313. //
  1314. // 8.1.2.3 Request Pseudo-Header Fields
  1315. // "All HTTP/2 requests MUST include exactly one valid
  1316. // value for the :method, :scheme, and :path
  1317. // pseudo-header fields"
  1318. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1319. }
  1320. var tlsState *tls.ConnectionState // nil if not scheme https
  1321. if rp.scheme == "https" {
  1322. tlsState = sc.tlsState
  1323. }
  1324. authority := rp.authority
  1325. if authority == "" {
  1326. authority = rp.header.Get("Host")
  1327. }
  1328. needsContinue := rp.header.Get("Expect") == "100-continue"
  1329. if needsContinue {
  1330. rp.header.Del("Expect")
  1331. }
  1332. // Merge Cookie headers into one "; "-delimited value.
  1333. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1334. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1335. }
  1336. bodyOpen := rp.stream.state == stateOpen
  1337. body := &requestBody{
  1338. conn: sc,
  1339. stream: rp.stream,
  1340. needsContinue: needsContinue,
  1341. }
  1342. // TODO: handle asterisk '*' requests + test
  1343. url, err := url.ParseRequestURI(rp.path)
  1344. if err != nil {
  1345. // TODO: find the right error code?
  1346. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1347. }
  1348. req := &http.Request{
  1349. Method: rp.method,
  1350. URL: url,
  1351. RemoteAddr: sc.remoteAddrStr,
  1352. Header: rp.header,
  1353. RequestURI: rp.path,
  1354. Proto: "HTTP/2.0",
  1355. ProtoMajor: 2,
  1356. ProtoMinor: 0,
  1357. TLS: tlsState,
  1358. Host: authority,
  1359. Body: body,
  1360. }
  1361. if bodyOpen {
  1362. body.pipe = &pipe{
  1363. b: buffer{buf: make([]byte, initialWindowSize)}, // TODO: share/remove XXX
  1364. }
  1365. body.pipe.c.L = &body.pipe.m
  1366. if vv, ok := rp.header["Content-Length"]; ok {
  1367. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1368. } else {
  1369. req.ContentLength = -1
  1370. }
  1371. }
  1372. rws := responseWriterStatePool.Get().(*responseWriterState)
  1373. bwSave := rws.bw
  1374. *rws = responseWriterState{} // zero all the fields
  1375. rws.conn = sc
  1376. rws.bw = bwSave
  1377. rws.bw.Reset(chunkWriter{rws})
  1378. rws.stream = rp.stream
  1379. rws.req = req
  1380. rws.body = body
  1381. rw := &responseWriter{rws: rws}
  1382. return rw, req, nil
  1383. }
  1384. // Run on its own goroutine.
  1385. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1386. defer rw.handlerDone()
  1387. // TODO: catch panics like net/http.Server
  1388. handler(rw, req)
  1389. }
  1390. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1391. // 10.5.1 Limits on Header Block Size:
  1392. // .. "A server that receives a larger header block than it is
  1393. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1394. // Large) status code"
  1395. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1396. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1397. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1398. }
  1399. // called from handler goroutines.
  1400. // h may be nil.
  1401. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) {
  1402. sc.serveG.checkNotOn() // NOT on
  1403. var errc chan error
  1404. if headerData.h != nil {
  1405. // If there's a header map (which we don't own), so we have to block on
  1406. // waiting for this frame to be written, so an http.Flush mid-handler
  1407. // writes out the correct value of keys, before a handler later potentially
  1408. // mutates it.
  1409. errc = errChanPool.Get().(chan error)
  1410. }
  1411. sc.writeFrameFromHandler(frameWriteMsg{
  1412. write: headerData,
  1413. stream: st,
  1414. done: errc,
  1415. })
  1416. if errc != nil {
  1417. select {
  1418. case <-errc:
  1419. // Ignore. Just for synchronization.
  1420. // Any error will be handled in the writing goroutine.
  1421. errChanPool.Put(errc)
  1422. case <-sc.doneServing:
  1423. // Client has closed the connection.
  1424. case <-st.cw:
  1425. // Client did RST_STREAM, etc. (but conn still alive)
  1426. }
  1427. }
  1428. }
  1429. // called from handler goroutines.
  1430. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1431. sc.writeFrameFromHandler(frameWriteMsg{
  1432. write: write100ContinueHeadersFrame{st.id},
  1433. stream: st,
  1434. })
  1435. }
  1436. // A bodyReadMsg tells the server loop that the http.Handler read n
  1437. // bytes of the DATA from the client on the given stream.
  1438. type bodyReadMsg struct {
  1439. st *stream
  1440. n int
  1441. }
  1442. // called from handler goroutines.
  1443. // Notes that the handler for the given stream ID read n bytes of its body
  1444. // and schedules flow control tokens to be sent.
  1445. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1446. sc.serveG.checkNotOn() // NOT on
  1447. sc.bodyReadCh <- bodyReadMsg{st, n}
  1448. }
  1449. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1450. sc.serveG.check()
  1451. sc.sendWindowUpdate(nil, n) // conn-level
  1452. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1453. // Don't send this WINDOW_UPDATE if the stream is closed
  1454. // remotely.
  1455. sc.sendWindowUpdate(st, n)
  1456. }
  1457. }
  1458. // st may be nil for conn-level
  1459. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1460. sc.serveG.check()
  1461. // "The legal range for the increment to the flow control
  1462. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1463. // A Go Read call on 64-bit machines could in theory read
  1464. // a larger Read than this. Very unlikely, but we handle it here
  1465. // rather than elsewhere for now.
  1466. const maxUint31 = 1<<31 - 1
  1467. for n >= maxUint31 {
  1468. sc.sendWindowUpdate32(st, maxUint31)
  1469. n -= maxUint31
  1470. }
  1471. sc.sendWindowUpdate32(st, int32(n))
  1472. }
  1473. // st may be nil for conn-level
  1474. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1475. sc.serveG.check()
  1476. if n == 0 {
  1477. return
  1478. }
  1479. if n < 0 {
  1480. panic("negative update")
  1481. }
  1482. var streamID uint32
  1483. if st != nil {
  1484. streamID = st.id
  1485. }
  1486. sc.writeFrame(frameWriteMsg{
  1487. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1488. stream: st,
  1489. })
  1490. var ok bool
  1491. if st == nil {
  1492. ok = sc.inflow.add(n)
  1493. } else {
  1494. ok = st.inflow.add(n)
  1495. }
  1496. if !ok {
  1497. panic("internal error; sent too many window updates without decrements?")
  1498. }
  1499. }
  1500. type requestBody struct {
  1501. stream *stream
  1502. conn *serverConn
  1503. closed bool
  1504. pipe *pipe // non-nil if we have a HTTP entity message body
  1505. needsContinue bool // need to send a 100-continue
  1506. }
  1507. func (b *requestBody) Close() error {
  1508. if b.pipe != nil {
  1509. b.pipe.Close(errClosedBody)
  1510. }
  1511. b.closed = true
  1512. return nil
  1513. }
  1514. func (b *requestBody) Read(p []byte) (n int, err error) {
  1515. if b.needsContinue {
  1516. b.needsContinue = false
  1517. b.conn.write100ContinueHeaders(b.stream)
  1518. }
  1519. if b.pipe == nil {
  1520. return 0, io.EOF
  1521. }
  1522. n, err = b.pipe.Read(p)
  1523. if n > 0 {
  1524. b.conn.noteBodyReadFromHandler(b.stream, n)
  1525. }
  1526. return
  1527. }
  1528. // responseWriter is the http.ResponseWriter implementation. It's
  1529. // intentionally small (1 pointer wide) to minimize garbage. The
  1530. // responseWriterState pointer inside is zeroed at the end of a
  1531. // request (in handlerDone) and calls on the responseWriter thereafter
  1532. // simply crash (caller's mistake), but the much larger responseWriterState
  1533. // and buffers are reused between multiple requests.
  1534. type responseWriter struct {
  1535. rws *responseWriterState
  1536. }
  1537. // Optional http.ResponseWriter interfaces implemented.
  1538. var (
  1539. _ http.CloseNotifier = (*responseWriter)(nil)
  1540. _ http.Flusher = (*responseWriter)(nil)
  1541. _ stringWriter = (*responseWriter)(nil)
  1542. )
  1543. type responseWriterState struct {
  1544. // immutable within a request:
  1545. stream *stream
  1546. req *http.Request
  1547. body *requestBody // to close at end of request, if DATA frames didn't
  1548. conn *serverConn
  1549. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1550. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1551. // mutated by http.Handler goroutine:
  1552. handlerHeader http.Header // nil until called
  1553. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1554. status int // status code passed to WriteHeader
  1555. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1556. sentHeader bool // have we sent the header frame?
  1557. handlerDone bool // handler has finished
  1558. curWrite writeData
  1559. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1560. closeNotifierCh chan bool // nil until first used
  1561. }
  1562. type chunkWriter struct{ rws *responseWriterState }
  1563. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1564. // writeChunk writes chunks from the bufio.Writer. But because
  1565. // bufio.Writer may bypass its chunking, sometimes p may be
  1566. // arbitrarily large.
  1567. //
  1568. // writeChunk is also responsible (on the first chunk) for sending the
  1569. // HEADER response.
  1570. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1571. if !rws.wroteHeader {
  1572. rws.writeHeader(200)
  1573. }
  1574. if !rws.sentHeader {
  1575. rws.sentHeader = true
  1576. var ctype, clen string // implicit ones, if we can calculate it
  1577. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1578. clen = strconv.Itoa(len(p))
  1579. }
  1580. if rws.snapHeader.Get("Content-Type") == "" {
  1581. ctype = http.DetectContentType(p)
  1582. }
  1583. endStream := rws.handlerDone && len(p) == 0
  1584. rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1585. streamID: rws.stream.id,
  1586. httpResCode: rws.status,
  1587. h: rws.snapHeader,
  1588. endStream: endStream,
  1589. contentType: ctype,
  1590. contentLength: clen,
  1591. })
  1592. if endStream {
  1593. return 0, nil
  1594. }
  1595. }
  1596. if len(p) == 0 && !rws.handlerDone {
  1597. return 0, nil
  1598. }
  1599. curWrite := &rws.curWrite
  1600. curWrite.streamID = rws.stream.id
  1601. curWrite.p = p
  1602. curWrite.endStream = rws.handlerDone
  1603. if err := rws.conn.writeDataFromHandler(rws.stream, curWrite); err != nil {
  1604. return 0, err
  1605. }
  1606. return len(p), nil
  1607. }
  1608. func (w *responseWriter) Flush() {
  1609. rws := w.rws
  1610. if rws == nil {
  1611. panic("Header called after Handler finished")
  1612. }
  1613. if rws.bw.Buffered() > 0 {
  1614. if err := rws.bw.Flush(); err != nil {
  1615. // Ignore the error. The frame writer already knows.
  1616. return
  1617. }
  1618. } else {
  1619. // The bufio.Writer won't call chunkWriter.Write
  1620. // (writeChunk with zero bytes, so we have to do it
  1621. // ourselves to force the HTTP response header and/or
  1622. // final DATA frame (with END_STREAM) to be sent.
  1623. rws.writeChunk(nil)
  1624. }
  1625. }
  1626. func (w *responseWriter) CloseNotify() <-chan bool {
  1627. rws := w.rws
  1628. if rws == nil {
  1629. panic("CloseNotify called after Handler finished")
  1630. }
  1631. rws.closeNotifierMu.Lock()
  1632. ch := rws.closeNotifierCh
  1633. if ch == nil {
  1634. ch = make(chan bool, 1)
  1635. rws.closeNotifierCh = ch
  1636. go func() {
  1637. rws.stream.cw.Wait() // wait for close
  1638. ch <- true
  1639. }()
  1640. }
  1641. rws.closeNotifierMu.Unlock()
  1642. return ch
  1643. }
  1644. func (w *responseWriter) Header() http.Header {
  1645. rws := w.rws
  1646. if rws == nil {
  1647. panic("Header called after Handler finished")
  1648. }
  1649. if rws.handlerHeader == nil {
  1650. rws.handlerHeader = make(http.Header)
  1651. }
  1652. return rws.handlerHeader
  1653. }
  1654. func (w *responseWriter) WriteHeader(code int) {
  1655. rws := w.rws
  1656. if rws == nil {
  1657. panic("WriteHeader called after Handler finished")
  1658. }
  1659. rws.writeHeader(code)
  1660. }
  1661. func (rws *responseWriterState) writeHeader(code int) {
  1662. if !rws.wroteHeader {
  1663. rws.wroteHeader = true
  1664. rws.status = code
  1665. if len(rws.handlerHeader) > 0 {
  1666. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1667. }
  1668. }
  1669. }
  1670. func cloneHeader(h http.Header) http.Header {
  1671. h2 := make(http.Header, len(h))
  1672. for k, vv := range h {
  1673. vv2 := make([]string, len(vv))
  1674. copy(vv2, vv)
  1675. h2[k] = vv2
  1676. }
  1677. return h2
  1678. }
  1679. // The Life Of A Write is like this:
  1680. //
  1681. // * Handler calls w.Write or w.WriteString ->
  1682. // * -> rws.bw (*bufio.Writer) ->
  1683. // * (Handler migth call Flush)
  1684. // * -> chunkWriter{rws}
  1685. // * -> responseWriterState.writeChunk(p []byte)
  1686. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1687. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1688. return w.write(len(p), p, "")
  1689. }
  1690. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1691. return w.write(len(s), nil, s)
  1692. }
  1693. // either dataB or dataS is non-zero.
  1694. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1695. rws := w.rws
  1696. if rws == nil {
  1697. panic("Write called after Handler finished")
  1698. }
  1699. if !rws.wroteHeader {
  1700. w.WriteHeader(200)
  1701. }
  1702. if dataB != nil {
  1703. return rws.bw.Write(dataB)
  1704. } else {
  1705. return rws.bw.WriteString(dataS)
  1706. }
  1707. }
  1708. func (w *responseWriter) handlerDone() {
  1709. rws := w.rws
  1710. if rws == nil {
  1711. panic("handlerDone called twice")
  1712. }
  1713. rws.handlerDone = true
  1714. w.Flush()
  1715. w.rws = nil
  1716. responseWriterStatePool.Put(rws)
  1717. }