server.go 48 KB

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