server.go 45 KB

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