server.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. "github.com/bradfitz/http2/hpack"
  23. )
  24. // TODO: finish GOAWAY support. Consider each incoming frame type and whether
  25. // it should be ignored during a shutdown race.
  26. // Server is an HTTP/2 server.
  27. type Server struct {
  28. // MaxStreams optionally ...
  29. MaxStreams int
  30. }
  31. var testHookOnConn func() // for testing
  32. // ConfigureServer adds HTTP/2 support to a net/http Server.
  33. //
  34. // The configuration conf may be nil.
  35. //
  36. // ConfigureServer must be called before s begins serving.
  37. func ConfigureServer(s *http.Server, conf *Server) {
  38. if conf == nil {
  39. conf = new(Server)
  40. }
  41. if s.TLSConfig == nil {
  42. s.TLSConfig = new(tls.Config)
  43. }
  44. haveNPN := false
  45. for _, p := range s.TLSConfig.NextProtos {
  46. if p == npnProto {
  47. haveNPN = true
  48. break
  49. }
  50. }
  51. if !haveNPN {
  52. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  53. }
  54. if s.TLSNextProto == nil {
  55. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  56. }
  57. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  58. if testHookOnConn != nil {
  59. testHookOnConn()
  60. }
  61. conf.handleConn(hs, c, h)
  62. }
  63. }
  64. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  65. sc := &serverConn{
  66. hs: hs,
  67. conn: c,
  68. handler: h,
  69. framer: NewFramer(c, c), // TODO: write to a (custom?) buffered writer that can alternate when it's in buffered mode.
  70. streams: make(map[uint32]*stream),
  71. canonHeader: make(map[string]string),
  72. readFrameCh: make(chan frameAndProcessed),
  73. readFrameErrCh: make(chan error, 1), // must be buffered for 1
  74. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  75. writeFrameCh: make(chan frameWriteMsg, 1), // may be 0 or 1, but more is useless. (max 1 in flight)
  76. wroteFrameCh: make(chan struct{}, 1),
  77. flow: newFlow(initialWindowSize),
  78. doneServing: make(chan struct{}),
  79. maxWriteFrameSize: initialMaxFrameSize,
  80. initialWindowSize: initialWindowSize,
  81. serveG: newGoroutineLock(),
  82. }
  83. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  84. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  85. sc.serve()
  86. }
  87. // frameAndProcessed coordinates the readFrames and serve goroutines, since
  88. // the Framer interface only permits the most recently-read Frame from being
  89. // accessed. The serve goroutine sends on processed to signal to the readFrames
  90. // goroutine that another frame may be read.
  91. type frameAndProcessed struct {
  92. f Frame
  93. processed chan struct{}
  94. }
  95. type serverConn struct {
  96. // Immutable:
  97. hs *http.Server
  98. conn net.Conn
  99. handler http.Handler
  100. framer *Framer
  101. hpackDecoder *hpack.Decoder
  102. doneServing chan struct{} // closed when serverConn.serve ends
  103. readFrameCh chan frameAndProcessed // written by serverConn.readFrames
  104. readFrameErrCh chan error
  105. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  106. writeFrameCh chan frameWriteMsg // from serve -> writeFrames
  107. wroteFrameCh chan struct{} // from writeFrames -> serve, tickles more sends on writeFrameCh
  108. serveG goroutineLock // used to verify funcs are on serve()
  109. writeG goroutineLock // used to verify things running on writeLoop
  110. flow *flow // connection-wide (not stream-specific) flow control
  111. // Everything following is owned by the serve loop; use serveG.check():
  112. maxStreamID uint32 // max ever seen
  113. streams map[uint32]*stream
  114. maxWriteFrameSize uint32 // TODO: update this when settings come in
  115. initialWindowSize int32
  116. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  117. sentGoAway bool
  118. req requestParam // non-zero while reading request headers
  119. writingFrame bool // sent on writeFrameCh but haven't heard back on wroteFrameCh yet
  120. writeQueue []frameWriteMsg // TODO: proper scheduler, not a queue
  121. // Owned by the writeFrames goroutine; use writeG.check():
  122. headerWriteBuf bytes.Buffer
  123. hpackEncoder *hpack.Encoder
  124. }
  125. // requestParam is the state of the next request, initialized over
  126. // potentially several frames HEADERS + zero or more CONTINUATION
  127. // frames.
  128. type requestParam struct {
  129. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  130. // frames for a request (but not DATA).
  131. stream *stream
  132. header http.Header
  133. method, path string
  134. scheme, authority string
  135. sawRegularHeader bool // saw a non-pseudo header already
  136. invalidHeader bool // an invalid header was seen
  137. }
  138. type stream struct {
  139. id uint32
  140. state streamState // owned by serverConn's processing loop
  141. flow *flow // limits writing from Handler to client
  142. body *pipe // non-nil if expecting DATA frames
  143. bodyBytes int64 // body bytes seen so far
  144. declBodyBytes int64 // or -1 if undeclared
  145. }
  146. func (sc *serverConn) state(streamID uint32) streamState {
  147. sc.serveG.check()
  148. // http://http2.github.io/http2-spec/#rfc.section.5.1
  149. if st, ok := sc.streams[streamID]; ok {
  150. return st.state
  151. }
  152. // "The first use of a new stream identifier implicitly closes all
  153. // streams in the "idle" state that might have been initiated by
  154. // that peer with a lower-valued stream identifier. For example, if
  155. // a client sends a HEADERS frame on stream 7 without ever sending a
  156. // frame on stream 5, then stream 5 transitions to the "closed"
  157. // state when the first frame for stream 7 is sent or received."
  158. if streamID <= sc.maxStreamID {
  159. return stateClosed
  160. }
  161. return stateIdle
  162. }
  163. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  164. if VerboseLogs {
  165. sc.logf(format, args...)
  166. }
  167. }
  168. func (sc *serverConn) logf(format string, args ...interface{}) {
  169. if lg := sc.hs.ErrorLog; lg != nil {
  170. lg.Printf(format, args...)
  171. } else {
  172. log.Printf(format, args...)
  173. }
  174. }
  175. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  176. if err == nil {
  177. return
  178. }
  179. str := err.Error()
  180. if strings.Contains(str, "use of closed network connection") {
  181. // Boring, expected errors.
  182. sc.vlogf(format, args...)
  183. } else {
  184. sc.logf(format, args...)
  185. }
  186. }
  187. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  188. sc.serveG.check()
  189. switch {
  190. case !validHeader(f.Name):
  191. sc.req.invalidHeader = true
  192. case strings.HasPrefix(f.Name, ":"):
  193. if sc.req.sawRegularHeader {
  194. sc.logf("pseudo-header after regular header")
  195. sc.req.invalidHeader = true
  196. return
  197. }
  198. var dst *string
  199. switch f.Name {
  200. case ":method":
  201. dst = &sc.req.method
  202. case ":path":
  203. dst = &sc.req.path
  204. case ":scheme":
  205. dst = &sc.req.scheme
  206. case ":authority":
  207. dst = &sc.req.authority
  208. default:
  209. // 8.1.2.1 Pseudo-Header Fields
  210. // "Endpoints MUST treat a request or response
  211. // that contains undefined or invalid
  212. // pseudo-header fields as malformed (Section
  213. // 8.1.2.6)."
  214. sc.logf("invalid pseudo-header %q", f.Name)
  215. sc.req.invalidHeader = true
  216. return
  217. }
  218. if *dst != "" {
  219. sc.logf("duplicate pseudo-header %q sent", f.Name)
  220. sc.req.invalidHeader = true
  221. return
  222. }
  223. *dst = f.Value
  224. case f.Name == "cookie":
  225. sc.req.sawRegularHeader = true
  226. if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 {
  227. s[0] = s[0] + "; " + f.Value
  228. } else {
  229. sc.req.header.Add("Cookie", f.Value)
  230. }
  231. default:
  232. sc.req.sawRegularHeader = true
  233. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  234. }
  235. }
  236. func (sc *serverConn) canonicalHeader(v string) string {
  237. sc.serveG.check()
  238. // TODO: use a sync.Pool instead of putting the cache on *serverConn?
  239. cv, ok := sc.canonHeader[v]
  240. if !ok {
  241. cv = http.CanonicalHeaderKey(v)
  242. sc.canonHeader[v] = cv
  243. }
  244. return cv
  245. }
  246. // readFrames is the loop that reads incoming frames.
  247. // It's run on its own goroutine.
  248. func (sc *serverConn) readFrames() {
  249. processed := make(chan struct{}, 1)
  250. for {
  251. f, err := sc.framer.ReadFrame()
  252. if err != nil {
  253. sc.readFrameErrCh <- err // BEFORE the close
  254. close(sc.readFrameCh)
  255. return
  256. }
  257. sc.readFrameCh <- frameAndProcessed{f, processed}
  258. <-processed
  259. }
  260. }
  261. // writeFrames is the loop that writes frames to the peer
  262. // and is responsible for prioritization and buffering.
  263. // It's run on its own goroutine.
  264. func (sc *serverConn) writeFrames() {
  265. sc.writeG = newGoroutineLock()
  266. for wm := range sc.writeFrameCh {
  267. err := wm.write(sc, wm.v)
  268. if ch := wm.done; ch != nil {
  269. select {
  270. case ch <- err:
  271. default:
  272. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.v))
  273. }
  274. }
  275. sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler
  276. }
  277. }
  278. func (sc *serverConn) serve() {
  279. sc.serveG.check()
  280. defer sc.conn.Close()
  281. defer close(sc.doneServing)
  282. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  283. // Read the client preface
  284. buf := make([]byte, len(ClientPreface))
  285. // TODO: timeout reading from the client
  286. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  287. sc.logf("error reading client preface: %v", err)
  288. return
  289. }
  290. if !bytes.Equal(buf, clientPreface) {
  291. sc.logf("bogus greeting from client: %q", buf)
  292. return
  293. }
  294. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  295. f, err := sc.framer.ReadFrame() // TODO: timeout
  296. if err != nil {
  297. sc.logf("error reading initial frame from client: %v", err)
  298. return
  299. }
  300. sf, ok := f.(*SettingsFrame)
  301. if !ok {
  302. sc.logf("invalid initial frame type %T received from client", f)
  303. return
  304. }
  305. if err := sf.ForeachSetting(sc.processSetting); err != nil {
  306. sc.logf("initial settings error: %v", err)
  307. return
  308. }
  309. // TODO: don't send two network packets for our SETTINGS + our
  310. // ACK of their settings. But if we make framer write to a
  311. // *bufio.Writer, that increases the per-connection memory
  312. // overhead, and there could be many idle conns. So maybe some
  313. // liveswitchWriter-like thing where we only switch to a
  314. // *bufio Writer when we really need one temporarily, else go
  315. // back to an unbuffered writes by default.
  316. if err := sc.framer.WriteSettings( /* TODO: actual settings */ ); err != nil {
  317. sc.logf("error writing server's initial settings: %v", err)
  318. return
  319. }
  320. if err := sc.framer.WriteSettingsAck(); err != nil {
  321. sc.logf("error writing server's ack of client's settings: %v", err)
  322. return
  323. }
  324. go sc.readFrames() // closed by defer sc.conn.Close above
  325. go sc.writeFrames()
  326. defer close(sc.writeFrameCh) // shuts down writeFrames loop
  327. for {
  328. select {
  329. case wm := <-sc.wantWriteFrameCh:
  330. sc.enqueueFrameWrite(wm)
  331. case <-sc.wroteFrameCh:
  332. sc.writingFrame = false
  333. sc.scheduleFrameWrite()
  334. case fp, ok := <-sc.readFrameCh:
  335. if !ok {
  336. err := <-sc.readFrameErrCh
  337. if err != io.EOF {
  338. errstr := err.Error()
  339. if !strings.Contains(errstr, "use of closed network connection") {
  340. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  341. }
  342. }
  343. return
  344. }
  345. f := fp.f
  346. sc.vlogf("got %v: %#v", f.Header(), f)
  347. err := sc.processFrame(f)
  348. fp.processed <- struct{}{} // let readFrames proceed
  349. switch ev := err.(type) {
  350. case nil:
  351. // nothing.
  352. case StreamError:
  353. if err := sc.resetStreamInLoop(ev); err != nil {
  354. sc.logf("Error writing RSTSTream: %v", err)
  355. return
  356. }
  357. case ConnectionError:
  358. sc.logf("Disconnecting; %v", ev)
  359. return
  360. case goAwayFlowError:
  361. if err := sc.goAway(ErrCodeFlowControl); err != nil {
  362. sc.condlogf(err, "failed to GOAWAY: %v", err)
  363. return
  364. }
  365. default:
  366. sc.logf("Disconnection due to other error: %v", err)
  367. return
  368. }
  369. }
  370. }
  371. }
  372. func (sc *serverConn) enqueueFrameWrite(wm frameWriteMsg) {
  373. sc.serveG.check()
  374. // Fast path for common case:
  375. if !sc.writingFrame {
  376. sc.writingFrame = true
  377. sc.writeFrameCh <- wm
  378. return
  379. }
  380. sc.writeQueue = append(sc.writeQueue, wm) // TODO: proper scheduler
  381. }
  382. func (sc *serverConn) scheduleFrameWrite() {
  383. sc.serveG.check()
  384. if len(sc.writeQueue) == 0 {
  385. // TODO: flush Framer's underlying buffered writer, once that's added
  386. return
  387. }
  388. // TODO: proper scheduler
  389. wm := sc.writeQueue[0]
  390. // shift it all down. kinda lame. will be removed later anyway.
  391. copy(sc.writeQueue, sc.writeQueue[1:])
  392. sc.writeQueue = sc.writeQueue[:len(sc.writeQueue)-1]
  393. sc.writingFrame = true
  394. sc.writeFrameCh <- wm
  395. }
  396. func (sc *serverConn) goAway(code ErrCode) error {
  397. sc.serveG.check()
  398. sc.sentGoAway = true
  399. return sc.framer.WriteGoAway(sc.maxStreamID, code, nil)
  400. }
  401. func (sc *serverConn) resetStreamInLoop(se StreamError) error {
  402. sc.serveG.check()
  403. if err := sc.framer.WriteRSTStream(se.streamID, uint32(se.code)); err != nil {
  404. return err
  405. }
  406. delete(sc.streams, se.streamID)
  407. return nil
  408. }
  409. func (sc *serverConn) curHeaderStreamID() uint32 {
  410. sc.serveG.check()
  411. st := sc.req.stream
  412. if st == nil {
  413. return 0
  414. }
  415. return st.id
  416. }
  417. func (sc *serverConn) processFrame(f Frame) error {
  418. sc.serveG.check()
  419. if s := sc.curHeaderStreamID(); s != 0 {
  420. if cf, ok := f.(*ContinuationFrame); !ok {
  421. return ConnectionError(ErrCodeProtocol)
  422. } else if cf.Header().StreamID != s {
  423. return ConnectionError(ErrCodeProtocol)
  424. }
  425. }
  426. switch f := f.(type) {
  427. case *SettingsFrame:
  428. return sc.processSettings(f)
  429. case *HeadersFrame:
  430. return sc.processHeaders(f)
  431. case *ContinuationFrame:
  432. return sc.processContinuation(f)
  433. case *WindowUpdateFrame:
  434. return sc.processWindowUpdate(f)
  435. case *PingFrame:
  436. return sc.processPing(f)
  437. case *DataFrame:
  438. return sc.processData(f)
  439. default:
  440. log.Printf("Ignoring unknown frame %#v", f)
  441. return nil
  442. }
  443. }
  444. func (sc *serverConn) processPing(f *PingFrame) error {
  445. sc.serveG.check()
  446. if f.Flags.Has(FlagSettingsAck) {
  447. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  448. // containing this flag."
  449. return nil
  450. }
  451. if f.StreamID != 0 {
  452. // "PING frames are not associated with any individual
  453. // stream. If a PING frame is received with a stream
  454. // identifier field value other than 0x0, the recipient MUST
  455. // respond with a connection error (Section 5.4.1) of type
  456. // PROTOCOL_ERROR."
  457. return ConnectionError(ErrCodeProtocol)
  458. }
  459. return sc.framer.WritePing(true, f.Data)
  460. }
  461. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  462. sc.serveG.check()
  463. switch {
  464. case f.StreamID != 0: // stream-level flow control
  465. st := sc.streams[f.StreamID]
  466. if st == nil {
  467. // "WINDOW_UPDATE can be sent by a peer that has sent a
  468. // frame bearing the END_STREAM flag. This means that a
  469. // receiver could receive a WINDOW_UPDATE frame on a "half
  470. // closed (remote)" or "closed" stream. A receiver MUST
  471. // NOT treat this as an error, see Section 5.1."
  472. return nil
  473. }
  474. if !st.flow.add(int32(f.Increment)) {
  475. return StreamError{f.StreamID, ErrCodeFlowControl}
  476. }
  477. default: // connection-level flow control
  478. if !sc.flow.add(int32(f.Increment)) {
  479. return goAwayFlowError{}
  480. }
  481. }
  482. return nil
  483. }
  484. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  485. sc.serveG.check()
  486. return f.ForeachSetting(sc.processSetting)
  487. }
  488. func (sc *serverConn) processSetting(s Setting) error {
  489. sc.serveG.check()
  490. sc.vlogf("processing setting %v", s)
  491. switch s.ID {
  492. case SettingInitialWindowSize:
  493. return sc.processSettingInitialWindowSize(s.Val)
  494. }
  495. log.Printf("TODO: handle %v", s)
  496. return nil
  497. }
  498. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  499. sc.serveG.check()
  500. if val > (1<<31 - 1) {
  501. // 6.5.2 Defined SETTINGS Parameters
  502. // "Values above the maximum flow control window size of
  503. // 231-1 MUST be treated as a connection error (Section
  504. // 5.4.1) of type FLOW_CONTROL_ERROR."
  505. return ConnectionError(ErrCodeFlowControl)
  506. }
  507. // "A SETTINGS frame can alter the initial flow control window
  508. // size for all current streams. When the value of
  509. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  510. // adjust the size of all stream flow control windows that it
  511. // maintains by the difference between the new value and the
  512. // old value."
  513. old := sc.initialWindowSize
  514. sc.initialWindowSize = int32(val)
  515. growth := sc.initialWindowSize - old // may be negative
  516. for _, st := range sc.streams {
  517. if !st.flow.add(growth) {
  518. // 6.9.2 Initial Flow Control Window Size
  519. // "An endpoint MUST treat a change to
  520. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  521. // control window to exceed the maximum size as a
  522. // connection error (Section 5.4.1) of type
  523. // FLOW_CONTROL_ERROR."
  524. return ConnectionError(ErrCodeFlowControl)
  525. }
  526. }
  527. return nil
  528. }
  529. func (sc *serverConn) processData(f *DataFrame) error {
  530. sc.serveG.check()
  531. // "If a DATA frame is received whose stream is not in "open"
  532. // or "half closed (local)" state, the recipient MUST respond
  533. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  534. id := f.Header().StreamID
  535. st, ok := sc.streams[id]
  536. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  537. return StreamError{id, ErrCodeStreamClosed}
  538. }
  539. if st.body == nil {
  540. // Not expecting data.
  541. // TODO: which error code?
  542. return StreamError{id, ErrCodeStreamClosed}
  543. }
  544. data := f.Data()
  545. // Sender sending more than they'd declared?
  546. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  547. st.body.Close(fmt.Errorf("Sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  548. return StreamError{id, ErrCodeStreamClosed}
  549. }
  550. if len(data) > 0 {
  551. // TODO: verify they're allowed to write with the flow control
  552. // window we'd advertised to them.
  553. // TODO: verify n from Write
  554. if _, err := st.body.Write(data); err != nil {
  555. return StreamError{id, ErrCodeStreamClosed}
  556. }
  557. st.bodyBytes += int64(len(data))
  558. }
  559. if f.Header().Flags.Has(FlagDataEndStream) {
  560. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  561. st.body.Close(fmt.Errorf("Request declared a Content-Length of %d but only wrote %d bytes",
  562. st.declBodyBytes, st.bodyBytes))
  563. } else {
  564. st.body.Close(io.EOF)
  565. }
  566. }
  567. return nil
  568. }
  569. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  570. sc.serveG.check()
  571. id := f.Header().StreamID
  572. if sc.sentGoAway {
  573. // Ignore.
  574. return nil
  575. }
  576. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  577. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  578. // Streams initiated by a client MUST use odd-numbered
  579. // stream identifiers. [...] The identifier of a newly
  580. // established stream MUST be numerically greater than all
  581. // streams that the initiating endpoint has opened or
  582. // reserved. [...] An endpoint that receives an unexpected
  583. // stream identifier MUST respond with a connection error
  584. // (Section 5.4.1) of type PROTOCOL_ERROR.
  585. return ConnectionError(ErrCodeProtocol)
  586. }
  587. if id > sc.maxStreamID {
  588. sc.maxStreamID = id
  589. }
  590. st := &stream{
  591. id: id,
  592. state: stateOpen,
  593. flow: newFlow(sc.initialWindowSize),
  594. }
  595. if f.Header().Flags.Has(FlagHeadersEndStream) {
  596. st.state = stateHalfClosedRemote
  597. }
  598. sc.streams[id] = st
  599. sc.req = requestParam{
  600. stream: st,
  601. header: make(http.Header),
  602. }
  603. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  604. }
  605. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  606. sc.serveG.check()
  607. st := sc.streams[f.Header().StreamID]
  608. if st == nil || sc.curHeaderStreamID() != st.id {
  609. return ConnectionError(ErrCodeProtocol)
  610. }
  611. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  612. }
  613. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  614. sc.serveG.check()
  615. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  616. // TODO: convert to stream error I assume?
  617. return err
  618. }
  619. if !end {
  620. return nil
  621. }
  622. if err := sc.hpackDecoder.Close(); err != nil {
  623. // TODO: convert to stream error I assume?
  624. return err
  625. }
  626. rw, req, err := sc.newWriterAndRequest()
  627. sc.req = requestParam{}
  628. if err != nil {
  629. return err
  630. }
  631. st.body = req.Body.(*requestBody).pipe // may be nil
  632. st.declBodyBytes = req.ContentLength
  633. go sc.runHandler(rw, req)
  634. return nil
  635. }
  636. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  637. sc.serveG.check()
  638. rp := &sc.req
  639. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  640. (rp.scheme != "https" && rp.scheme != "http") {
  641. // See 8.1.2.6 Malformed Requests and Responses:
  642. //
  643. // Malformed requests or responses that are detected
  644. // MUST be treated as a stream error (Section 5.4.2)
  645. // of type PROTOCOL_ERROR."
  646. //
  647. // 8.1.2.3 Request Pseudo-Header Fields
  648. // "All HTTP/2 requests MUST include exactly one valid
  649. // value for the :method, :scheme, and :path
  650. // pseudo-header fields"
  651. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  652. }
  653. var tlsState *tls.ConnectionState // make this non-nil if https
  654. if rp.scheme == "https" {
  655. // TODO: get from sc's ConnectionState
  656. tlsState = &tls.ConnectionState{}
  657. }
  658. authority := rp.authority
  659. if authority == "" {
  660. authority = rp.header.Get("Host")
  661. }
  662. bodyOpen := rp.stream.state == stateOpen
  663. body := &requestBody{
  664. sc: sc,
  665. streamID: rp.stream.id,
  666. }
  667. url, err := url.ParseRequestURI(rp.path)
  668. if err != nil {
  669. // TODO: find the right error code?
  670. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  671. }
  672. req := &http.Request{
  673. Method: rp.method,
  674. URL: url,
  675. RemoteAddr: sc.conn.RemoteAddr().String(),
  676. Header: rp.header,
  677. RequestURI: rp.path,
  678. Proto: "HTTP/2.0",
  679. ProtoMajor: 2,
  680. ProtoMinor: 0,
  681. TLS: tlsState,
  682. Host: authority,
  683. Body: body,
  684. }
  685. if bodyOpen {
  686. body.pipe = &pipe{
  687. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  688. }
  689. body.pipe.c.L = &body.pipe.m
  690. if vv, ok := rp.header["Content-Length"]; ok {
  691. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  692. } else {
  693. req.ContentLength = -1
  694. }
  695. }
  696. rws := responseWriterStatePool.Get().(*responseWriterState)
  697. bwSave := rws.bw
  698. *rws = responseWriterState{} // zero all the fields
  699. rws.bw = bwSave
  700. rws.bw.Reset(chunkWriter{rws})
  701. rws.sc = sc
  702. rws.streamID = rp.stream.id
  703. rws.req = req
  704. rws.body = body
  705. rws.chunkWrittenCh = make(chan error, 1)
  706. rw := &responseWriter{rws: rws}
  707. return rw, req, nil
  708. }
  709. const handlerChunkWriteSize = 4 << 10
  710. var responseWriterStatePool = sync.Pool{
  711. New: func() interface{} {
  712. rws := &responseWriterState{}
  713. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  714. return rws
  715. },
  716. }
  717. // Run on its own goroutine.
  718. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  719. defer rw.handlerDone()
  720. // TODO: catch panics like net/http.Server
  721. sc.handler.ServeHTTP(rw, req)
  722. }
  723. type frameWriteMsg struct {
  724. // write runs on the writeFrames goroutine.
  725. write func(sc *serverConn, v interface{}) error
  726. v interface{} // passed to write
  727. cost uint32 // number of flow control bytes required
  728. streamID uint32 // used for prioritization
  729. // done, if non-nil, must be a buffered channel with space for
  730. // 1 message and is sent the return value from write (or an
  731. // earlier error) when the frame has been written.
  732. done chan error
  733. }
  734. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  735. type headerWriteReq struct {
  736. streamID uint32
  737. httpResCode int
  738. h http.Header // may be nil
  739. endStream bool
  740. contentType string
  741. contentLength string
  742. }
  743. // called from handler goroutines.
  744. // h may be nil.
  745. func (sc *serverConn) writeHeader(req headerWriteReq) {
  746. var errc chan error
  747. if req.h != nil {
  748. // If there's a header map (which we don't own), so we have to block on
  749. // waiting for this frame to be written, so an http.Flush mid-handler
  750. // writes out the correct value of keys, before a handler later potentially
  751. // mutates it.
  752. errc = make(chan error, 1)
  753. }
  754. sc.wantWriteFrameCh <- frameWriteMsg{
  755. write: (*serverConn).writeHeaderInLoop,
  756. v: req,
  757. streamID: req.streamID,
  758. done: errc,
  759. }
  760. if errc != nil {
  761. <-errc
  762. }
  763. }
  764. func (sc *serverConn) writeHeaderInLoop(v interface{}) error {
  765. sc.writeG.check()
  766. req := v.(headerWriteReq)
  767. sc.headerWriteBuf.Reset()
  768. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(req.httpResCode)})
  769. for k, vv := range req.h {
  770. for _, v := range vv {
  771. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  772. if k == "Transfer-Encoding" && v != "trailers" {
  773. continue
  774. }
  775. // TODO: for gargage, cache lowercase copies of headers at
  776. // least for common ones and/or popular recent ones for
  777. // this serverConn. LRU?
  778. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: strings.ToLower(k), Value: v})
  779. }
  780. }
  781. if req.contentType != "" {
  782. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-type", Value: req.contentType})
  783. }
  784. if req.contentLength != "" {
  785. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-length", Value: req.contentLength})
  786. }
  787. headerBlock := sc.headerWriteBuf.Bytes()
  788. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  789. // we'll need continuation ones.
  790. panic("TODO")
  791. }
  792. return sc.framer.WriteHeaders(HeadersFrameParam{
  793. StreamID: req.streamID,
  794. BlockFragment: headerBlock,
  795. EndStream: req.endStream,
  796. EndHeaders: true, // no continuation yet
  797. })
  798. }
  799. func (sc *serverConn) writeDataInLoop(v interface{}) error {
  800. sc.writeG.check()
  801. rws := v.(*responseWriterState)
  802. return sc.framer.WriteData(rws.streamID, rws.curChunkIsFinal, rws.curChunk)
  803. }
  804. type windowUpdateReq struct {
  805. streamID uint32
  806. n uint32
  807. }
  808. // called from handler goroutines
  809. func (sc *serverConn) sendWindowUpdate(streamID uint32, n int) {
  810. const maxUint32 = 2147483647
  811. for n >= maxUint32 {
  812. sc.wantWriteFrameCh <- frameWriteMsg{
  813. write: (*serverConn).sendWindowUpdateInLoop,
  814. v: windowUpdateReq{streamID, maxUint32},
  815. streamID: streamID,
  816. }
  817. n -= maxUint32
  818. }
  819. if n > 0 {
  820. sc.wantWriteFrameCh <- frameWriteMsg{
  821. write: (*serverConn).sendWindowUpdateInLoop,
  822. v: windowUpdateReq{streamID, uint32(n)},
  823. streamID: streamID,
  824. }
  825. }
  826. }
  827. func (sc *serverConn) sendWindowUpdateInLoop(v interface{}) error {
  828. sc.writeG.check()
  829. wu := v.(windowUpdateReq)
  830. if err := sc.framer.WriteWindowUpdate(0, wu.n); err != nil {
  831. return err
  832. }
  833. if err := sc.framer.WriteWindowUpdate(wu.streamID, wu.n); err != nil {
  834. return err
  835. }
  836. return nil
  837. }
  838. type requestBody struct {
  839. sc *serverConn
  840. streamID uint32
  841. closed bool
  842. pipe *pipe // non-nil if we have a HTTP entity message body
  843. }
  844. var errClosedBody = errors.New("body closed by handler")
  845. func (b *requestBody) Close() error {
  846. if b.pipe != nil {
  847. b.pipe.Close(errClosedBody)
  848. }
  849. b.closed = true
  850. return nil
  851. }
  852. func (b *requestBody) Read(p []byte) (n int, err error) {
  853. if b.pipe == nil {
  854. return 0, io.EOF
  855. }
  856. n, err = b.pipe.Read(p)
  857. if n > 0 {
  858. b.sc.sendWindowUpdate(b.streamID, n)
  859. // TODO: tell b.sc to send back 'n' flow control quota credits to the sender
  860. }
  861. return
  862. }
  863. // responseWriter is the http.ResponseWriter implementation. It's
  864. // intentionally small (1 pointer wide) to minimize garbage. The
  865. // responseWriterState pointer inside is zeroed at the end of a
  866. // request (in handlerDone) and calls on the responseWriter thereafter
  867. // simply crash (caller's mistake), but the much larger responseWriterState
  868. // and buffers are reused between multiple requests.
  869. type responseWriter struct {
  870. rws *responseWriterState
  871. }
  872. // Optional http.ResponseWriter interfaces implemented.
  873. var (
  874. _ http.Flusher = (*responseWriter)(nil)
  875. _ stringWriter = (*responseWriter)(nil)
  876. // TODO: hijacker for websockets?
  877. )
  878. type responseWriterState struct {
  879. // immutable within a request:
  880. sc *serverConn
  881. streamID uint32
  882. req *http.Request
  883. body *requestBody // to close at end of request, if DATA frames didn't
  884. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  885. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  886. // mutated by http.Handler goroutine:
  887. handlerHeader http.Header // nil until called
  888. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  889. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  890. status int // status code passed to WriteHeader
  891. wroteContinue bool // 100 Continue response was written
  892. sentHeader bool // have we sent the header frame?
  893. handlerDone bool // handler has finished
  894. curChunk []byte // current chunk we're writing
  895. curChunkIsFinal bool
  896. chunkWrittenCh chan error
  897. }
  898. type chunkWriter struct{ rws *responseWriterState }
  899. // chunkWriter.Write is called from bufio.Writer. Because bufio.Writer passes through large
  900. // writes, we break them up here if they're too big.
  901. func (cw chunkWriter) Write(p []byte) (n int, err error) {
  902. for len(p) > 0 {
  903. chunk := p
  904. if len(chunk) > handlerChunkWriteSize {
  905. chunk = chunk[:handlerChunkWriteSize]
  906. }
  907. _, err = cw.rws.writeChunk(chunk)
  908. if err != nil {
  909. return
  910. }
  911. n += len(chunk)
  912. p = p[len(chunk):]
  913. }
  914. return n, nil
  915. }
  916. // writeChunk writes small (max 4k, or handlerChunkWriteSize) chunks.
  917. // It's also responsible for sending the HEADER response.
  918. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  919. if !rws.wroteHeader {
  920. rws.writeHeader(200)
  921. }
  922. if !rws.sentHeader {
  923. rws.sentHeader = true
  924. var ctype, clen string // implicit ones, if we can calculate it
  925. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  926. clen = strconv.Itoa(len(p))
  927. }
  928. if rws.snapHeader.Get("Content-Type") == "" {
  929. ctype = http.DetectContentType(p)
  930. }
  931. rws.sc.writeHeader(headerWriteReq{
  932. streamID: rws.streamID,
  933. httpResCode: rws.status,
  934. h: rws.snapHeader,
  935. endStream: rws.handlerDone && len(p) == 0,
  936. contentType: ctype,
  937. contentLength: clen,
  938. })
  939. }
  940. if len(p) == 0 && !rws.handlerDone {
  941. return
  942. }
  943. rws.curChunk = p
  944. rws.curChunkIsFinal = rws.handlerDone
  945. // TODO: await flow control tokens for both stream and conn
  946. rws.sc.wantWriteFrameCh <- frameWriteMsg{
  947. cost: uint32(len(p)),
  948. streamID: rws.streamID,
  949. write: (*serverConn).writeDataInLoop,
  950. done: rws.chunkWrittenCh,
  951. v: rws, // writeDataInLoop uses only rws.curChunk and rws.curChunkIsFinal
  952. }
  953. err = <-rws.chunkWrittenCh // block until it's written
  954. return len(p), err
  955. }
  956. func (w *responseWriter) Flush() {
  957. rws := w.rws
  958. if rws == nil {
  959. panic("Header called after Handler finished")
  960. }
  961. if rws.bw.Buffered() > 0 {
  962. if err := rws.bw.Flush(); err != nil {
  963. // Ignore the error. The frame writer already knows.
  964. return
  965. }
  966. } else {
  967. // The bufio.Writer won't call chunkWriter.Write
  968. // (writeChunk with zero bytes, so we have to do it
  969. // ourselves to force the HTTP response header and/or
  970. // final DATA frame (with END_STREAM) to be sent.
  971. rws.writeChunk(nil)
  972. }
  973. }
  974. func (w *responseWriter) Header() http.Header {
  975. rws := w.rws
  976. if rws == nil {
  977. panic("Header called after Handler finished")
  978. }
  979. if rws.handlerHeader == nil {
  980. rws.handlerHeader = make(http.Header)
  981. }
  982. return rws.handlerHeader
  983. }
  984. func (w *responseWriter) WriteHeader(code int) {
  985. rws := w.rws
  986. if rws == nil {
  987. panic("WriteHeader called after Handler finished")
  988. }
  989. rws.writeHeader(code)
  990. }
  991. func (rws *responseWriterState) writeHeader(code int) {
  992. if !rws.wroteHeader {
  993. rws.wroteHeader = true
  994. rws.status = code
  995. if len(rws.handlerHeader) > 0 {
  996. rws.snapHeader = cloneHeader(rws.handlerHeader)
  997. }
  998. }
  999. }
  1000. func cloneHeader(h http.Header) http.Header {
  1001. h2 := make(http.Header, len(h))
  1002. for k, vv := range h {
  1003. vv2 := make([]string, len(vv))
  1004. copy(vv2, vv)
  1005. h2[k] = vv2
  1006. }
  1007. return h2
  1008. }
  1009. // The Life Of A Write is like this:
  1010. //
  1011. // TODO: copy/adapt the similar comment from Go's http server.go
  1012. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1013. return w.write(len(p), p, "")
  1014. }
  1015. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1016. return w.write(len(s), nil, s)
  1017. }
  1018. // either dataB or dataS is non-zero.
  1019. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1020. rws := w.rws
  1021. if rws == nil {
  1022. panic("Write called after Handler finished")
  1023. }
  1024. if !rws.wroteHeader {
  1025. w.WriteHeader(200)
  1026. }
  1027. if dataB != nil {
  1028. return rws.bw.Write(dataB)
  1029. } else {
  1030. return rws.bw.WriteString(dataS)
  1031. }
  1032. }
  1033. func (w *responseWriter) handlerDone() {
  1034. rws := w.rws
  1035. if rws == nil {
  1036. panic("handlerDone called twice")
  1037. }
  1038. rws.handlerDone = true
  1039. w.Flush()
  1040. w.rws = nil
  1041. responseWriterStatePool.Put(rws)
  1042. }