server.go 50 KB

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