server.go 42 KB

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