server.go 48 KB

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