server.go 54 KB

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