server.go 52 KB

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