server.go 54 KB

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