server.go 47 KB

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