server.go 47 KB

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