server.go 51 KB

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