server.go 47 KB

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