server.go 54 KB

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