server.go 47 KB

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