server.go 51 KB

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