server.go 45 KB

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