server.go 53 KB

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