server.go 55 KB

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