server.go 46 KB

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