server.go 49 KB

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