server.go 42 KB

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