server.go 53 KB

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