server.go 45 KB

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