server.go 63 KB

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