server.go 49 KB

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