server.go 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173
  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. // TODO: replace all <-sc.doneServing with reads from the stream's cw
  5. // instead, and make sure that on close we close all open
  6. // streams. then remove doneServing?
  7. // TODO: re-audit GOAWAY support. Consider each incoming frame type and
  8. // whether it should be ignored during graceful shutdown.
  9. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make
  10. // configurable? or maximum number of idle clients and remove the
  11. // oldest?
  12. // TODO: turn off the serve goroutine when idle, so
  13. // an idle conn only has the readFrames goroutine active. (which could
  14. // also be optimized probably to pin less memory in crypto/tls). This
  15. // would involve tracking when the serve goroutine is active (atomic
  16. // int32 read/CAS probably?) and starting it up when frames arrive,
  17. // and shutting it down when all handlers exit. the occasional PING
  18. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  19. // (which is a no-op if already running) and then queue the PING write
  20. // as normal. The serve loop would then exit in most cases (if no
  21. // Handlers running) and not be woken up again until the PING packet
  22. // returns.
  23. // TODO (maybe): add a mechanism for Handlers to going into
  24. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  25. // handler, and continue to be able to read from the
  26. // Request.Body. This would be a somewhat semantic change from HTTP/1
  27. // (or at least what we expose in net/http), so I'd probably want to
  28. // add it there too. For now, this package says that returning from
  29. // the Handler ServeHTTP function means you're both done reading and
  30. // done writing, without a way to stop just one or the other.
  31. package http2
  32. import (
  33. "bufio"
  34. "bytes"
  35. "crypto/tls"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "log"
  40. "net"
  41. "net/http"
  42. "net/textproto"
  43. "net/url"
  44. "os"
  45. "reflect"
  46. "runtime"
  47. "sort"
  48. "strconv"
  49. "strings"
  50. "sync"
  51. "time"
  52. "golang.org/x/net/http2/hpack"
  53. )
  54. const (
  55. prefaceTimeout = 10 * time.Second
  56. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  57. handlerChunkWriteSize = 4 << 10
  58. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  59. )
  60. var (
  61. errClientDisconnected = errors.New("client disconnected")
  62. errClosedBody = errors.New("body closed by handler")
  63. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  64. errStreamClosed = errors.New("http2: stream closed")
  65. )
  66. var responseWriterStatePool = sync.Pool{
  67. New: func() interface{} {
  68. rws := &responseWriterState{}
  69. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  70. return rws
  71. },
  72. }
  73. // Test hooks.
  74. var (
  75. testHookOnConn func()
  76. testHookGetServerConn func(*serverConn)
  77. testHookOnPanicMu *sync.Mutex // nil except in tests
  78. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  79. )
  80. // Server is an HTTP/2 server.
  81. type Server struct {
  82. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  83. // which may run at a time over all connections.
  84. // Negative or zero no limit.
  85. // TODO: implement
  86. MaxHandlers int
  87. // MaxConcurrentStreams optionally specifies the number of
  88. // concurrent streams that each client may have open at a
  89. // time. This is unrelated to the number of http.Handler goroutines
  90. // which may be active globally, which is MaxHandlers.
  91. // If zero, MaxConcurrentStreams defaults to at least 100, per
  92. // the HTTP/2 spec's recommendations.
  93. MaxConcurrentStreams uint32
  94. // MaxReadFrameSize optionally specifies the largest frame
  95. // this server is willing to read. A valid value is between
  96. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  97. // default value is used.
  98. MaxReadFrameSize uint32
  99. // PermitProhibitedCipherSuites, if true, permits the use of
  100. // cipher suites prohibited by the HTTP/2 spec.
  101. PermitProhibitedCipherSuites bool
  102. }
  103. func (s *Server) maxReadFrameSize() uint32 {
  104. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  105. return v
  106. }
  107. return defaultMaxReadFrameSize
  108. }
  109. func (s *Server) maxConcurrentStreams() uint32 {
  110. if v := s.MaxConcurrentStreams; v > 0 {
  111. return v
  112. }
  113. return defaultMaxStreams
  114. }
  115. // ConfigureServer adds HTTP/2 support to a net/http Server.
  116. //
  117. // The configuration conf may be nil.
  118. //
  119. // ConfigureServer must be called before s begins serving.
  120. func ConfigureServer(s *http.Server, conf *Server) error {
  121. if conf == nil {
  122. conf = new(Server)
  123. }
  124. if s.TLSConfig == nil {
  125. s.TLSConfig = new(tls.Config)
  126. } else if s.TLSConfig.CipherSuites != nil {
  127. // If they already provided a CipherSuite list, return
  128. // an error if it has a bad order or is missing
  129. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  130. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  131. haveRequired := false
  132. sawBad := false
  133. for i, cs := range s.TLSConfig.CipherSuites {
  134. if cs == requiredCipher {
  135. haveRequired = true
  136. }
  137. if isBadCipher(cs) {
  138. sawBad = true
  139. } else if sawBad {
  140. return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
  141. }
  142. }
  143. if !haveRequired {
  144. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  145. }
  146. }
  147. // Note: not setting MinVersion to tls.VersionTLS12,
  148. // as we don't want to interfere with HTTP/1.1 traffic
  149. // on the user's server. We enforce TLS 1.2 later once
  150. // we accept a connection. Ideally this should be done
  151. // during next-proto selection, but using TLS <1.2 with
  152. // HTTP/2 is still the client's bug.
  153. s.TLSConfig.PreferServerCipherSuites = true
  154. haveNPN := false
  155. for _, p := range s.TLSConfig.NextProtos {
  156. if p == NextProtoTLS {
  157. haveNPN = true
  158. break
  159. }
  160. }
  161. if !haveNPN {
  162. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  163. }
  164. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  165. // to switch to "h2".
  166. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  167. if s.TLSNextProto == nil {
  168. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  169. }
  170. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  171. if testHookOnConn != nil {
  172. testHookOnConn()
  173. }
  174. conf.ServeConn(c, &ServeConnOpts{
  175. Handler: h,
  176. BaseConfig: hs,
  177. })
  178. }
  179. s.TLSNextProto[NextProtoTLS] = protoHandler
  180. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  181. return nil
  182. }
  183. // ServeConnOpts are options for the Server.ServeConn method.
  184. type ServeConnOpts struct {
  185. // BaseConfig optionally sets the base configuration
  186. // for values. If nil, defaults are used.
  187. BaseConfig *http.Server
  188. // Handler specifies which handler to use for processing
  189. // requests. If nil, BaseConfig.Handler is used. If BaseConfig
  190. // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
  191. Handler http.Handler
  192. }
  193. func (o *ServeConnOpts) baseConfig() *http.Server {
  194. if o != nil && o.BaseConfig != nil {
  195. return o.BaseConfig
  196. }
  197. return new(http.Server)
  198. }
  199. func (o *ServeConnOpts) handler() http.Handler {
  200. if o != nil {
  201. if o.Handler != nil {
  202. return o.Handler
  203. }
  204. if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
  205. return o.BaseConfig.Handler
  206. }
  207. }
  208. return http.DefaultServeMux
  209. }
  210. // ServeConn serves HTTP/2 requests on the provided connection and
  211. // blocks until the connection is no longer readable.
  212. //
  213. // ServeConn starts speaking HTTP/2 assuming that c has not had any
  214. // reads or writes. It writes its initial settings frame and expects
  215. // to be able to read the preface and settings frame from the
  216. // client. If c has a ConnectionState method like a *tls.Conn, the
  217. // ConnectionState is used to verify the TLS ciphersuite and to set
  218. // the Request.TLS field in Handlers.
  219. //
  220. // ServeConn does not support h2c by itself. Any h2c support must be
  221. // implemented in terms of providing a suitably-behaving net.Conn.
  222. //
  223. // The opts parameter is optional. If nil, default values are used.
  224. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
  225. sc := &serverConn{
  226. srv: s,
  227. hs: opts.baseConfig(),
  228. conn: c,
  229. remoteAddrStr: c.RemoteAddr().String(),
  230. bw: newBufferedWriter(c),
  231. handler: opts.handler(),
  232. streams: make(map[uint32]*stream),
  233. readFrameCh: make(chan readFrameResult),
  234. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  235. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  236. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  237. doneServing: make(chan struct{}),
  238. advMaxStreams: s.maxConcurrentStreams(),
  239. writeSched: writeScheduler{
  240. maxFrameSize: initialMaxFrameSize,
  241. },
  242. initialWindowSize: initialWindowSize,
  243. headerTableSize: initialHeaderTableSize,
  244. serveG: newGoroutineLock(),
  245. pushEnabled: true,
  246. }
  247. sc.flow.add(initialWindowSize)
  248. sc.inflow.add(initialWindowSize)
  249. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  250. fr := NewFramer(sc.bw, c)
  251. fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  252. fr.MaxHeaderListSize = sc.maxHeaderListSize()
  253. fr.SetMaxReadFrameSize(s.maxReadFrameSize())
  254. sc.framer = fr
  255. if tc, ok := c.(connectionStater); ok {
  256. sc.tlsState = new(tls.ConnectionState)
  257. *sc.tlsState = tc.ConnectionState()
  258. // 9.2 Use of TLS Features
  259. // An implementation of HTTP/2 over TLS MUST use TLS
  260. // 1.2 or higher with the restrictions on feature set
  261. // and cipher suite described in this section. Due to
  262. // implementation limitations, it might not be
  263. // possible to fail TLS negotiation. An endpoint MUST
  264. // immediately terminate an HTTP/2 connection that
  265. // does not meet the TLS requirements described in
  266. // this section with a connection error (Section
  267. // 5.4.1) of type INADEQUATE_SECURITY.
  268. if sc.tlsState.Version < tls.VersionTLS12 {
  269. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  270. return
  271. }
  272. if sc.tlsState.ServerName == "" {
  273. // Client must use SNI, but we don't enforce that anymore,
  274. // since it was causing problems when connecting to bare IP
  275. // addresses during development.
  276. //
  277. // TODO: optionally enforce? Or enforce at the time we receive
  278. // a new request, and verify the the ServerName matches the :authority?
  279. // But that precludes proxy situations, perhaps.
  280. //
  281. // So for now, do nothing here again.
  282. }
  283. if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  284. // "Endpoints MAY choose to generate a connection error
  285. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  286. // the prohibited cipher suites are negotiated."
  287. //
  288. // We choose that. In my opinion, the spec is weak
  289. // here. It also says both parties must support at least
  290. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  291. // excuses here. If we really must, we could allow an
  292. // "AllowInsecureWeakCiphers" option on the server later.
  293. // Let's see how it plays out first.
  294. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  295. return
  296. }
  297. }
  298. if hook := testHookGetServerConn; hook != nil {
  299. hook(sc)
  300. }
  301. sc.serve()
  302. }
  303. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  304. func isBadCipher(cipher uint16) bool {
  305. switch cipher {
  306. case tls.TLS_RSA_WITH_RC4_128_SHA,
  307. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  308. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  309. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  310. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  311. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  312. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  313. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  314. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  315. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  316. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  317. // Reject cipher suites from Appendix A.
  318. // "This list includes those cipher suites that do not
  319. // offer an ephemeral key exchange and those that are
  320. // based on the TLS null, stream or block cipher type"
  321. return true
  322. default:
  323. return false
  324. }
  325. }
  326. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  327. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  328. // ignoring errors. hanging up anyway.
  329. sc.framer.WriteGoAway(0, err, []byte(debug))
  330. sc.bw.Flush()
  331. sc.conn.Close()
  332. }
  333. type serverConn struct {
  334. // Immutable:
  335. srv *Server
  336. hs *http.Server
  337. conn net.Conn
  338. bw *bufferedWriter // writing to conn
  339. handler http.Handler
  340. framer *Framer
  341. doneServing chan struct{} // closed when serverConn.serve ends
  342. readFrameCh chan readFrameResult // written by serverConn.readFrames
  343. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  344. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  345. bodyReadCh chan bodyReadMsg // from handlers -> serve
  346. testHookCh chan func(int) // code to run on the serve loop
  347. flow flow // conn-wide (not stream-specific) outbound flow control
  348. inflow flow // conn-wide inbound flow control
  349. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  350. remoteAddrStr string
  351. // Everything following is owned by the serve loop; use serveG.check():
  352. serveG goroutineLock // used to verify funcs are on serve()
  353. pushEnabled bool
  354. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  355. needToSendSettingsAck bool
  356. unackedSettings int // how many SETTINGS have we sent without ACKs?
  357. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  358. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  359. curOpenStreams uint32 // client's number of open streams
  360. maxStreamID uint32 // max ever seen
  361. streams map[uint32]*stream
  362. initialWindowSize int32
  363. headerTableSize uint32
  364. peerMaxHeaderListSize uint32 // zero means unknown (default)
  365. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  366. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  367. needsFrameFlush bool // last frame write wasn't a flush
  368. writeSched writeScheduler
  369. inGoAway bool // we've started to or sent GOAWAY
  370. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  371. goAwayCode ErrCode
  372. shutdownTimerCh <-chan time.Time // nil until used
  373. shutdownTimer *time.Timer // nil until used
  374. freeRequestBodyBuf []byte // if non-nil, a free initialWindowSize buffer for getRequestBodyBuf
  375. // Owned by the writeFrameAsync goroutine:
  376. headerWriteBuf bytes.Buffer
  377. hpackEncoder *hpack.Encoder
  378. }
  379. func (sc *serverConn) maxHeaderListSize() uint32 {
  380. n := sc.hs.MaxHeaderBytes
  381. if n <= 0 {
  382. n = http.DefaultMaxHeaderBytes
  383. }
  384. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  385. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  386. const perFieldOverhead = 32 // per http2 spec
  387. const typicalHeaders = 10 // conservative
  388. return uint32(n + typicalHeaders*perFieldOverhead)
  389. }
  390. // stream represents a stream. This is the minimal metadata needed by
  391. // the serve goroutine. Most of the actual stream state is owned by
  392. // the http.Handler's goroutine in the responseWriter. Because the
  393. // responseWriter's responseWriterState is recycled at the end of a
  394. // handler, this struct intentionally has no pointer to the
  395. // *responseWriter{,State} itself, as the Handler ending nils out the
  396. // responseWriter's state field.
  397. type stream struct {
  398. // immutable:
  399. sc *serverConn
  400. id uint32
  401. body *pipe // non-nil if expecting DATA frames
  402. cw closeWaiter // closed wait stream transitions to closed state
  403. // owned by serverConn's serve loop:
  404. bodyBytes int64 // body bytes seen so far
  405. declBodyBytes int64 // or -1 if undeclared
  406. flow flow // limits writing from Handler to client
  407. inflow flow // what the client is allowed to POST/etc to us
  408. parent *stream // or nil
  409. numTrailerValues int64
  410. weight uint8
  411. state streamState
  412. sentReset bool // only true once detached from streams map
  413. gotReset bool // only true once detacted from streams map
  414. gotTrailerHeader bool // HEADER frame for trailers was seen
  415. reqBuf []byte
  416. trailer http.Header // accumulated trailers
  417. reqTrailer http.Header // handler's Request.Trailer
  418. }
  419. func (sc *serverConn) Framer() *Framer { return sc.framer }
  420. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  421. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  422. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  423. return sc.hpackEncoder, &sc.headerWriteBuf
  424. }
  425. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  426. sc.serveG.check()
  427. // http://http2.github.io/http2-spec/#rfc.section.5.1
  428. if st, ok := sc.streams[streamID]; ok {
  429. return st.state, st
  430. }
  431. // "The first use of a new stream identifier implicitly closes all
  432. // streams in the "idle" state that might have been initiated by
  433. // that peer with a lower-valued stream identifier. For example, if
  434. // a client sends a HEADERS frame on stream 7 without ever sending a
  435. // frame on stream 5, then stream 5 transitions to the "closed"
  436. // state when the first frame for stream 7 is sent or received."
  437. if streamID <= sc.maxStreamID {
  438. return stateClosed, nil
  439. }
  440. return stateIdle, nil
  441. }
  442. // setConnState calls the net/http ConnState hook for this connection, if configured.
  443. // Note that the net/http package does StateNew and StateClosed for us.
  444. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  445. func (sc *serverConn) setConnState(state http.ConnState) {
  446. if sc.hs.ConnState != nil {
  447. sc.hs.ConnState(sc.conn, state)
  448. }
  449. }
  450. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  451. if VerboseLogs {
  452. sc.logf(format, args...)
  453. }
  454. }
  455. func (sc *serverConn) logf(format string, args ...interface{}) {
  456. if lg := sc.hs.ErrorLog; lg != nil {
  457. lg.Printf(format, args...)
  458. } else {
  459. log.Printf(format, args...)
  460. }
  461. }
  462. // errno returns v's underlying uintptr, else 0.
  463. //
  464. // TODO: remove this helper function once http2 can use build
  465. // tags. See comment in isClosedConnError.
  466. func errno(v error) uintptr {
  467. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  468. return uintptr(rv.Uint())
  469. }
  470. return 0
  471. }
  472. // isClosedConnError reports whether err is an error from use of a closed
  473. // network connection.
  474. func isClosedConnError(err error) bool {
  475. if err == nil {
  476. return false
  477. }
  478. // TODO: remove this string search and be more like the Windows
  479. // case below. That might involve modifying the standard library
  480. // to return better error types.
  481. str := err.Error()
  482. if strings.Contains(str, "use of closed network connection") {
  483. return true
  484. }
  485. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  486. // build tags, so I can't make an http2_windows.go file with
  487. // Windows-specific stuff. Fix that and move this, once we
  488. // have a way to bundle this into std's net/http somehow.
  489. if runtime.GOOS == "windows" {
  490. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  491. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  492. const WSAECONNABORTED = 10053
  493. const WSAECONNRESET = 10054
  494. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  495. return true
  496. }
  497. }
  498. }
  499. }
  500. return false
  501. }
  502. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  503. if err == nil {
  504. return
  505. }
  506. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
  507. // Boring, expected errors.
  508. sc.vlogf(format, args...)
  509. } else {
  510. sc.logf(format, args...)
  511. }
  512. }
  513. func (sc *serverConn) canonicalHeader(v string) string {
  514. sc.serveG.check()
  515. cv, ok := commonCanonHeader[v]
  516. if ok {
  517. return cv
  518. }
  519. cv, ok = sc.canonHeader[v]
  520. if ok {
  521. return cv
  522. }
  523. if sc.canonHeader == nil {
  524. sc.canonHeader = make(map[string]string)
  525. }
  526. cv = http.CanonicalHeaderKey(v)
  527. sc.canonHeader[v] = cv
  528. return cv
  529. }
  530. type readFrameResult struct {
  531. f Frame // valid until readMore is called
  532. err error
  533. // readMore should be called once the consumer no longer needs or
  534. // retains f. After readMore, f is invalid and more frames can be
  535. // read.
  536. readMore func()
  537. }
  538. // readFrames is the loop that reads incoming frames.
  539. // It takes care to only read one frame at a time, blocking until the
  540. // consumer is done with the frame.
  541. // It's run on its own goroutine.
  542. func (sc *serverConn) readFrames() {
  543. gate := make(gate)
  544. for {
  545. f, err := sc.framer.ReadFrame()
  546. select {
  547. case sc.readFrameCh <- readFrameResult{f, err, gate.Done}:
  548. case <-sc.doneServing:
  549. return
  550. }
  551. select {
  552. case <-gate:
  553. case <-sc.doneServing:
  554. return
  555. }
  556. if terminalReadFrameError(err) {
  557. return
  558. }
  559. }
  560. }
  561. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  562. type frameWriteResult struct {
  563. wm frameWriteMsg // what was written (or attempted)
  564. err error // result of the writeFrame call
  565. }
  566. // writeFrameAsync runs in its own goroutine and writes a single frame
  567. // and then reports when it's done.
  568. // At most one goroutine can be running writeFrameAsync at a time per
  569. // serverConn.
  570. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  571. err := wm.write.writeFrame(sc)
  572. sc.wroteFrameCh <- frameWriteResult{wm, err}
  573. }
  574. func (sc *serverConn) closeAllStreamsOnConnClose() {
  575. sc.serveG.check()
  576. for _, st := range sc.streams {
  577. sc.closeStream(st, errClientDisconnected)
  578. }
  579. }
  580. func (sc *serverConn) stopShutdownTimer() {
  581. sc.serveG.check()
  582. if t := sc.shutdownTimer; t != nil {
  583. t.Stop()
  584. }
  585. }
  586. func (sc *serverConn) notePanic() {
  587. // Note: this is for serverConn.serve panicking, not http.Handler code.
  588. if testHookOnPanicMu != nil {
  589. testHookOnPanicMu.Lock()
  590. defer testHookOnPanicMu.Unlock()
  591. }
  592. if testHookOnPanic != nil {
  593. if e := recover(); e != nil {
  594. if testHookOnPanic(sc, e) {
  595. panic(e)
  596. }
  597. }
  598. }
  599. }
  600. func (sc *serverConn) serve() {
  601. sc.serveG.check()
  602. defer sc.notePanic()
  603. defer sc.conn.Close()
  604. defer sc.closeAllStreamsOnConnClose()
  605. defer sc.stopShutdownTimer()
  606. defer close(sc.doneServing) // unblocks handlers trying to send
  607. if VerboseLogs {
  608. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  609. }
  610. sc.writeFrame(frameWriteMsg{
  611. write: writeSettings{
  612. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  613. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  614. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  615. // TODO: more actual settings, notably
  616. // SettingInitialWindowSize, but then we also
  617. // want to bump up the conn window size the
  618. // same amount here right after the settings
  619. },
  620. })
  621. sc.unackedSettings++
  622. if err := sc.readPreface(); err != nil {
  623. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  624. return
  625. }
  626. // Now that we've got the preface, get us out of the
  627. // "StateNew" state. We can't go directly to idle, though.
  628. // Active means we read some data and anticipate a request. We'll
  629. // do another Active when we get a HEADERS frame.
  630. sc.setConnState(http.StateActive)
  631. sc.setConnState(http.StateIdle)
  632. go sc.readFrames() // closed by defer sc.conn.Close above
  633. settingsTimer := time.NewTimer(firstSettingsTimeout)
  634. loopNum := 0
  635. for {
  636. loopNum++
  637. select {
  638. case wm := <-sc.wantWriteFrameCh:
  639. sc.writeFrame(wm)
  640. case res := <-sc.wroteFrameCh:
  641. sc.wroteFrame(res)
  642. case res := <-sc.readFrameCh:
  643. if !sc.processFrameFromReader(res) {
  644. return
  645. }
  646. res.readMore()
  647. if settingsTimer.C != nil {
  648. settingsTimer.Stop()
  649. settingsTimer.C = nil
  650. }
  651. case m := <-sc.bodyReadCh:
  652. sc.noteBodyRead(m.st, m.n)
  653. case <-settingsTimer.C:
  654. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  655. return
  656. case <-sc.shutdownTimerCh:
  657. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  658. return
  659. case fn := <-sc.testHookCh:
  660. fn(loopNum)
  661. }
  662. }
  663. }
  664. // readPreface reads the ClientPreface greeting from the peer
  665. // or returns an error on timeout or an invalid greeting.
  666. func (sc *serverConn) readPreface() error {
  667. errc := make(chan error, 1)
  668. go func() {
  669. // Read the client preface
  670. buf := make([]byte, len(ClientPreface))
  671. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  672. errc <- err
  673. } else if !bytes.Equal(buf, clientPreface) {
  674. errc <- fmt.Errorf("bogus greeting %q", buf)
  675. } else {
  676. errc <- nil
  677. }
  678. }()
  679. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  680. defer timer.Stop()
  681. select {
  682. case <-timer.C:
  683. return errors.New("timeout waiting for client preface")
  684. case err := <-errc:
  685. if err == nil {
  686. if VerboseLogs {
  687. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  688. }
  689. }
  690. return err
  691. }
  692. }
  693. var errChanPool = sync.Pool{
  694. New: func() interface{} { return make(chan error, 1) },
  695. }
  696. var writeDataPool = sync.Pool{
  697. New: func() interface{} { return new(writeData) },
  698. }
  699. // writeDataFromHandler writes DATA response frames from a handler on
  700. // the given stream.
  701. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  702. ch := errChanPool.Get().(chan error)
  703. writeArg := writeDataPool.Get().(*writeData)
  704. *writeArg = writeData{stream.id, data, endStream}
  705. err := sc.writeFrameFromHandler(frameWriteMsg{
  706. write: writeArg,
  707. stream: stream,
  708. done: ch,
  709. })
  710. if err != nil {
  711. return err
  712. }
  713. var frameWriteDone bool // the frame write is done (successfully or not)
  714. select {
  715. case err = <-ch:
  716. frameWriteDone = true
  717. case <-sc.doneServing:
  718. return errClientDisconnected
  719. case <-stream.cw:
  720. // If both ch and stream.cw were ready (as might
  721. // happen on the final Write after an http.Handler
  722. // ends), prefer the write result. Otherwise this
  723. // might just be us successfully closing the stream.
  724. // The writeFrameAsync and serve goroutines guarantee
  725. // that the ch send will happen before the stream.cw
  726. // close.
  727. select {
  728. case err = <-ch:
  729. frameWriteDone = true
  730. default:
  731. return errStreamClosed
  732. }
  733. }
  734. errChanPool.Put(ch)
  735. if frameWriteDone {
  736. writeDataPool.Put(writeArg)
  737. }
  738. return err
  739. }
  740. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  741. // if the connection has gone away.
  742. //
  743. // This must not be run from the serve goroutine itself, else it might
  744. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  745. // buffered and is read by serve itself). If you're on the serve
  746. // goroutine, call writeFrame instead.
  747. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  748. sc.serveG.checkNotOn() // NOT
  749. select {
  750. case sc.wantWriteFrameCh <- wm:
  751. return nil
  752. case <-sc.doneServing:
  753. // Serve loop is gone.
  754. // Client has closed their connection to the server.
  755. return errClientDisconnected
  756. }
  757. }
  758. // writeFrame schedules a frame to write and sends it if there's nothing
  759. // already being written.
  760. //
  761. // There is no pushback here (the serve goroutine never blocks). It's
  762. // the http.Handlers that block, waiting for their previous frames to
  763. // make it onto the wire
  764. //
  765. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  766. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  767. sc.serveG.check()
  768. sc.writeSched.add(wm)
  769. sc.scheduleFrameWrite()
  770. }
  771. // startFrameWrite starts a goroutine to write wm (in a separate
  772. // goroutine since that might block on the network), and updates the
  773. // serve goroutine's state about the world, updated from info in wm.
  774. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  775. sc.serveG.check()
  776. if sc.writingFrame {
  777. panic("internal error: can only be writing one frame at a time")
  778. }
  779. st := wm.stream
  780. if st != nil {
  781. switch st.state {
  782. case stateHalfClosedLocal:
  783. panic("internal error: attempt to send frame on half-closed-local stream")
  784. case stateClosed:
  785. if st.sentReset || st.gotReset {
  786. // Skip this frame.
  787. sc.scheduleFrameWrite()
  788. return
  789. }
  790. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  791. }
  792. }
  793. sc.writingFrame = true
  794. sc.needsFrameFlush = true
  795. go sc.writeFrameAsync(wm)
  796. }
  797. // errHandlerPanicked is the error given to any callers blocked in a read from
  798. // Request.Body when the main goroutine panics. Since most handlers read in the
  799. // the main ServeHTTP goroutine, this will show up rarely.
  800. var errHandlerPanicked = errors.New("http2: handler panicked")
  801. // wroteFrame is called on the serve goroutine with the result of
  802. // whatever happened on writeFrameAsync.
  803. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  804. sc.serveG.check()
  805. if !sc.writingFrame {
  806. panic("internal error: expected to be already writing a frame")
  807. }
  808. sc.writingFrame = false
  809. wm := res.wm
  810. st := wm.stream
  811. closeStream := endsStream(wm.write)
  812. if _, ok := wm.write.(handlerPanicRST); ok {
  813. sc.closeStream(st, errHandlerPanicked)
  814. }
  815. // Reply (if requested) to the blocked ServeHTTP goroutine.
  816. if ch := wm.done; ch != nil {
  817. select {
  818. case ch <- res.err:
  819. default:
  820. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  821. }
  822. }
  823. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  824. if closeStream {
  825. if st == nil {
  826. panic("internal error: expecting non-nil stream")
  827. }
  828. switch st.state {
  829. case stateOpen:
  830. // Here we would go to stateHalfClosedLocal in
  831. // theory, but since our handler is done and
  832. // the net/http package provides no mechanism
  833. // for finishing writing to a ResponseWriter
  834. // while still reading data (see possible TODO
  835. // at top of this file), we go into closed
  836. // state here anyway, after telling the peer
  837. // we're hanging up on them.
  838. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  839. errCancel := StreamError{st.id, ErrCodeCancel}
  840. sc.resetStream(errCancel)
  841. case stateHalfClosedRemote:
  842. sc.closeStream(st, errHandlerComplete)
  843. }
  844. }
  845. sc.scheduleFrameWrite()
  846. }
  847. // scheduleFrameWrite tickles the frame writing scheduler.
  848. //
  849. // If a frame is already being written, nothing happens. This will be called again
  850. // when the frame is done being written.
  851. //
  852. // If a frame isn't being written we need to send one, the best frame
  853. // to send is selected, preferring first things that aren't
  854. // stream-specific (e.g. ACKing settings), and then finding the
  855. // highest priority stream.
  856. //
  857. // If a frame isn't being written and there's nothing else to send, we
  858. // flush the write buffer.
  859. func (sc *serverConn) scheduleFrameWrite() {
  860. sc.serveG.check()
  861. if sc.writingFrame {
  862. return
  863. }
  864. if sc.needToSendGoAway {
  865. sc.needToSendGoAway = false
  866. sc.startFrameWrite(frameWriteMsg{
  867. write: &writeGoAway{
  868. maxStreamID: sc.maxStreamID,
  869. code: sc.goAwayCode,
  870. },
  871. })
  872. return
  873. }
  874. if sc.needToSendSettingsAck {
  875. sc.needToSendSettingsAck = false
  876. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  877. return
  878. }
  879. if !sc.inGoAway {
  880. if wm, ok := sc.writeSched.take(); ok {
  881. sc.startFrameWrite(wm)
  882. return
  883. }
  884. }
  885. if sc.needsFrameFlush {
  886. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  887. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  888. return
  889. }
  890. }
  891. func (sc *serverConn) goAway(code ErrCode) {
  892. sc.serveG.check()
  893. if sc.inGoAway {
  894. return
  895. }
  896. if code != ErrCodeNo {
  897. sc.shutDownIn(250 * time.Millisecond)
  898. } else {
  899. // TODO: configurable
  900. sc.shutDownIn(1 * time.Second)
  901. }
  902. sc.inGoAway = true
  903. sc.needToSendGoAway = true
  904. sc.goAwayCode = code
  905. sc.scheduleFrameWrite()
  906. }
  907. func (sc *serverConn) shutDownIn(d time.Duration) {
  908. sc.serveG.check()
  909. sc.shutdownTimer = time.NewTimer(d)
  910. sc.shutdownTimerCh = sc.shutdownTimer.C
  911. }
  912. func (sc *serverConn) resetStream(se StreamError) {
  913. sc.serveG.check()
  914. sc.writeFrame(frameWriteMsg{write: se})
  915. if st, ok := sc.streams[se.StreamID]; ok {
  916. st.sentReset = true
  917. sc.closeStream(st, se)
  918. }
  919. }
  920. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  921. // frame-reading goroutine.
  922. // processFrameFromReader returns whether the connection should be kept open.
  923. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  924. sc.serveG.check()
  925. err := res.err
  926. if err != nil {
  927. if err == ErrFrameTooLarge {
  928. sc.goAway(ErrCodeFrameSize)
  929. return true // goAway will close the loop
  930. }
  931. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  932. if clientGone {
  933. // TODO: could we also get into this state if
  934. // the peer does a half close
  935. // (e.g. CloseWrite) because they're done
  936. // sending frames but they're still wanting
  937. // our open replies? Investigate.
  938. // TODO: add CloseWrite to crypto/tls.Conn first
  939. // so we have a way to test this? I suppose
  940. // just for testing we could have a non-TLS mode.
  941. return false
  942. }
  943. } else {
  944. f := res.f
  945. if VerboseLogs {
  946. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  947. }
  948. err = sc.processFrame(f)
  949. if err == nil {
  950. return true
  951. }
  952. }
  953. switch ev := err.(type) {
  954. case StreamError:
  955. sc.resetStream(ev)
  956. return true
  957. case goAwayFlowError:
  958. sc.goAway(ErrCodeFlowControl)
  959. return true
  960. case ConnectionError:
  961. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  962. sc.goAway(ErrCode(ev))
  963. return true // goAway will handle shutdown
  964. default:
  965. if res.err != nil {
  966. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  967. } else {
  968. sc.logf("http2: server closing client connection: %v", err)
  969. }
  970. return false
  971. }
  972. }
  973. func (sc *serverConn) processFrame(f Frame) error {
  974. sc.serveG.check()
  975. // First frame received must be SETTINGS.
  976. if !sc.sawFirstSettings {
  977. if _, ok := f.(*SettingsFrame); !ok {
  978. return ConnectionError(ErrCodeProtocol)
  979. }
  980. sc.sawFirstSettings = true
  981. }
  982. switch f := f.(type) {
  983. case *SettingsFrame:
  984. return sc.processSettings(f)
  985. case *MetaHeadersFrame:
  986. return sc.processHeaders(f)
  987. case *WindowUpdateFrame:
  988. return sc.processWindowUpdate(f)
  989. case *PingFrame:
  990. return sc.processPing(f)
  991. case *DataFrame:
  992. return sc.processData(f)
  993. case *RSTStreamFrame:
  994. return sc.processResetStream(f)
  995. case *PriorityFrame:
  996. return sc.processPriority(f)
  997. case *PushPromiseFrame:
  998. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  999. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1000. return ConnectionError(ErrCodeProtocol)
  1001. default:
  1002. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1003. return nil
  1004. }
  1005. }
  1006. func (sc *serverConn) processPing(f *PingFrame) error {
  1007. sc.serveG.check()
  1008. if f.IsAck() {
  1009. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1010. // containing this flag."
  1011. return nil
  1012. }
  1013. if f.StreamID != 0 {
  1014. // "PING frames are not associated with any individual
  1015. // stream. If a PING frame is received with a stream
  1016. // identifier field value other than 0x0, the recipient MUST
  1017. // respond with a connection error (Section 5.4.1) of type
  1018. // PROTOCOL_ERROR."
  1019. return ConnectionError(ErrCodeProtocol)
  1020. }
  1021. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  1022. return nil
  1023. }
  1024. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1025. sc.serveG.check()
  1026. switch {
  1027. case f.StreamID != 0: // stream-level flow control
  1028. st := sc.streams[f.StreamID]
  1029. if st == nil {
  1030. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1031. // frame bearing the END_STREAM flag. This means that a
  1032. // receiver could receive a WINDOW_UPDATE frame on a "half
  1033. // closed (remote)" or "closed" stream. A receiver MUST
  1034. // NOT treat this as an error, see Section 5.1."
  1035. return nil
  1036. }
  1037. if !st.flow.add(int32(f.Increment)) {
  1038. return StreamError{f.StreamID, ErrCodeFlowControl}
  1039. }
  1040. default: // connection-level flow control
  1041. if !sc.flow.add(int32(f.Increment)) {
  1042. return goAwayFlowError{}
  1043. }
  1044. }
  1045. sc.scheduleFrameWrite()
  1046. return nil
  1047. }
  1048. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1049. sc.serveG.check()
  1050. state, st := sc.state(f.StreamID)
  1051. if state == stateIdle {
  1052. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1053. // stream in the "idle" state. If a RST_STREAM frame
  1054. // identifying an idle stream is received, the
  1055. // recipient MUST treat this as a connection error
  1056. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1057. return ConnectionError(ErrCodeProtocol)
  1058. }
  1059. if st != nil {
  1060. st.gotReset = true
  1061. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1062. }
  1063. return nil
  1064. }
  1065. func (sc *serverConn) closeStream(st *stream, err error) {
  1066. sc.serveG.check()
  1067. if st.state == stateIdle || st.state == stateClosed {
  1068. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1069. }
  1070. st.state = stateClosed
  1071. sc.curOpenStreams--
  1072. if sc.curOpenStreams == 0 {
  1073. sc.setConnState(http.StateIdle)
  1074. }
  1075. delete(sc.streams, st.id)
  1076. if p := st.body; p != nil {
  1077. p.CloseWithError(err)
  1078. }
  1079. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1080. sc.writeSched.forgetStream(st.id)
  1081. if st.reqBuf != nil {
  1082. // Stash this request body buffer (64k) away for reuse
  1083. // by a future POST/PUT/etc.
  1084. //
  1085. // TODO(bradfitz): share on the server? sync.Pool?
  1086. // Server requires locks and might hurt contention.
  1087. // sync.Pool might work, or might be worse, depending
  1088. // on goroutine CPU migrations. (get and put on
  1089. // separate CPUs). Maybe a mix of strategies. But
  1090. // this is an easy win for now.
  1091. sc.freeRequestBodyBuf = st.reqBuf
  1092. }
  1093. }
  1094. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1095. sc.serveG.check()
  1096. if f.IsAck() {
  1097. sc.unackedSettings--
  1098. if sc.unackedSettings < 0 {
  1099. // Why is the peer ACKing settings we never sent?
  1100. // The spec doesn't mention this case, but
  1101. // hang up on them anyway.
  1102. return ConnectionError(ErrCodeProtocol)
  1103. }
  1104. return nil
  1105. }
  1106. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1107. return err
  1108. }
  1109. sc.needToSendSettingsAck = true
  1110. sc.scheduleFrameWrite()
  1111. return nil
  1112. }
  1113. func (sc *serverConn) processSetting(s Setting) error {
  1114. sc.serveG.check()
  1115. if err := s.Valid(); err != nil {
  1116. return err
  1117. }
  1118. if VerboseLogs {
  1119. sc.vlogf("http2: server processing setting %v", s)
  1120. }
  1121. switch s.ID {
  1122. case SettingHeaderTableSize:
  1123. sc.headerTableSize = s.Val
  1124. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1125. case SettingEnablePush:
  1126. sc.pushEnabled = s.Val != 0
  1127. case SettingMaxConcurrentStreams:
  1128. sc.clientMaxStreams = s.Val
  1129. case SettingInitialWindowSize:
  1130. return sc.processSettingInitialWindowSize(s.Val)
  1131. case SettingMaxFrameSize:
  1132. sc.writeSched.maxFrameSize = s.Val
  1133. case SettingMaxHeaderListSize:
  1134. sc.peerMaxHeaderListSize = s.Val
  1135. default:
  1136. // Unknown setting: "An endpoint that receives a SETTINGS
  1137. // frame with any unknown or unsupported identifier MUST
  1138. // ignore that setting."
  1139. if VerboseLogs {
  1140. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1141. }
  1142. }
  1143. return nil
  1144. }
  1145. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1146. sc.serveG.check()
  1147. // Note: val already validated to be within range by
  1148. // processSetting's Valid call.
  1149. // "A SETTINGS frame can alter the initial flow control window
  1150. // size for all current streams. When the value of
  1151. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1152. // adjust the size of all stream flow control windows that it
  1153. // maintains by the difference between the new value and the
  1154. // old value."
  1155. old := sc.initialWindowSize
  1156. sc.initialWindowSize = int32(val)
  1157. growth := sc.initialWindowSize - old // may be negative
  1158. for _, st := range sc.streams {
  1159. if !st.flow.add(growth) {
  1160. // 6.9.2 Initial Flow Control Window Size
  1161. // "An endpoint MUST treat a change to
  1162. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1163. // control window to exceed the maximum size as a
  1164. // connection error (Section 5.4.1) of type
  1165. // FLOW_CONTROL_ERROR."
  1166. return ConnectionError(ErrCodeFlowControl)
  1167. }
  1168. }
  1169. return nil
  1170. }
  1171. func (sc *serverConn) processData(f *DataFrame) error {
  1172. sc.serveG.check()
  1173. // "If a DATA frame is received whose stream is not in "open"
  1174. // or "half closed (local)" state, the recipient MUST respond
  1175. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1176. id := f.Header().StreamID
  1177. st, ok := sc.streams[id]
  1178. if !ok || st.state != stateOpen || st.gotTrailerHeader {
  1179. // This includes sending a RST_STREAM if the stream is
  1180. // in stateHalfClosedLocal (which currently means that
  1181. // the http.Handler returned, so it's done reading &
  1182. // done writing). Try to stop the client from sending
  1183. // more DATA.
  1184. return StreamError{id, ErrCodeStreamClosed}
  1185. }
  1186. if st.body == nil {
  1187. panic("internal error: should have a body in this state")
  1188. }
  1189. data := f.Data()
  1190. // Sender sending more than they'd declared?
  1191. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1192. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1193. return StreamError{id, ErrCodeStreamClosed}
  1194. }
  1195. if len(data) > 0 {
  1196. // Check whether the client has flow control quota.
  1197. if int(st.inflow.available()) < len(data) {
  1198. return StreamError{id, ErrCodeFlowControl}
  1199. }
  1200. st.inflow.take(int32(len(data)))
  1201. wrote, err := st.body.Write(data)
  1202. if err != nil {
  1203. return StreamError{id, ErrCodeStreamClosed}
  1204. }
  1205. if wrote != len(data) {
  1206. panic("internal error: bad Writer")
  1207. }
  1208. st.bodyBytes += int64(len(data))
  1209. }
  1210. if f.StreamEnded() {
  1211. st.endStream()
  1212. }
  1213. return nil
  1214. }
  1215. // endStream closes a Request.Body's pipe. It is called when a DATA
  1216. // frame says a request body is over (or after trailers).
  1217. func (st *stream) endStream() {
  1218. sc := st.sc
  1219. sc.serveG.check()
  1220. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1221. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1222. st.declBodyBytes, st.bodyBytes))
  1223. } else {
  1224. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1225. st.body.CloseWithError(io.EOF)
  1226. }
  1227. st.state = stateHalfClosedRemote
  1228. }
  1229. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1230. // its Request.Body.Read just before it gets io.EOF.
  1231. func (st *stream) copyTrailersToHandlerRequest() {
  1232. for k, vv := range st.trailer {
  1233. if _, ok := st.reqTrailer[k]; ok {
  1234. // Only copy it over it was pre-declared.
  1235. st.reqTrailer[k] = vv
  1236. }
  1237. }
  1238. }
  1239. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1240. sc.serveG.check()
  1241. id := f.Header().StreamID
  1242. if sc.inGoAway {
  1243. // Ignore.
  1244. return nil
  1245. }
  1246. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1247. // Streams initiated by a client MUST use odd-numbered stream
  1248. // identifiers. [...] An endpoint that receives an unexpected
  1249. // stream identifier MUST respond with a connection error
  1250. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1251. if id%2 != 1 {
  1252. return ConnectionError(ErrCodeProtocol)
  1253. }
  1254. // A HEADERS frame can be used to create a new stream or
  1255. // send a trailer for an open one. If we already have a stream
  1256. // open, let it process its own HEADERS frame (trailers at this
  1257. // point, if it's valid).
  1258. st := sc.streams[f.Header().StreamID]
  1259. if st != nil {
  1260. return st.processTrailerHeaders(f)
  1261. }
  1262. // [...] The identifier of a newly established stream MUST be
  1263. // numerically greater than all streams that the initiating
  1264. // endpoint has opened or reserved. [...] An endpoint that
  1265. // receives an unexpected stream identifier MUST respond with
  1266. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1267. if id <= sc.maxStreamID {
  1268. return ConnectionError(ErrCodeProtocol)
  1269. }
  1270. sc.maxStreamID = id
  1271. st = &stream{
  1272. sc: sc,
  1273. id: id,
  1274. state: stateOpen,
  1275. }
  1276. if f.StreamEnded() {
  1277. st.state = stateHalfClosedRemote
  1278. }
  1279. st.cw.Init()
  1280. st.flow.conn = &sc.flow // link to conn-level counter
  1281. st.flow.add(sc.initialWindowSize)
  1282. st.inflow.conn = &sc.inflow // link to conn-level counter
  1283. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1284. sc.streams[id] = st
  1285. if f.HasPriority() {
  1286. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1287. }
  1288. sc.curOpenStreams++
  1289. if sc.curOpenStreams == 1 {
  1290. sc.setConnState(http.StateActive)
  1291. }
  1292. if sc.curOpenStreams > sc.advMaxStreams {
  1293. // "Endpoints MUST NOT exceed the limit set by their
  1294. // peer. An endpoint that receives a HEADERS frame
  1295. // that causes their advertised concurrent stream
  1296. // limit to be exceeded MUST treat this as a stream
  1297. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1298. // REFUSED_STREAM."
  1299. if sc.unackedSettings == 0 {
  1300. // They should know better.
  1301. return StreamError{st.id, ErrCodeProtocol}
  1302. }
  1303. // Assume it's a network race, where they just haven't
  1304. // received our last SETTINGS update. But actually
  1305. // this can't happen yet, because we don't yet provide
  1306. // a way for users to adjust server parameters at
  1307. // runtime.
  1308. return StreamError{st.id, ErrCodeRefusedStream}
  1309. }
  1310. rw, req, err := sc.newWriterAndRequest(st, f)
  1311. if err != nil {
  1312. return err
  1313. }
  1314. st.reqTrailer = req.Trailer
  1315. if st.reqTrailer != nil {
  1316. st.trailer = make(http.Header)
  1317. }
  1318. st.body = req.Body.(*requestBody).pipe // may be nil
  1319. st.declBodyBytes = req.ContentLength
  1320. handler := sc.handler.ServeHTTP
  1321. if f.Truncated {
  1322. // Their header list was too long. Send a 431 error.
  1323. handler = handleHeaderListTooLong
  1324. }
  1325. go sc.runHandler(rw, req, handler)
  1326. return nil
  1327. }
  1328. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1329. sc := st.sc
  1330. sc.serveG.check()
  1331. if st.gotTrailerHeader {
  1332. return ConnectionError(ErrCodeProtocol)
  1333. }
  1334. st.gotTrailerHeader = true
  1335. if !f.StreamEnded() {
  1336. return StreamError{st.id, ErrCodeProtocol}
  1337. }
  1338. if len(f.PseudoFields()) > 0 {
  1339. return StreamError{st.id, ErrCodeProtocol}
  1340. }
  1341. if st.trailer != nil {
  1342. for _, hf := range f.RegularFields() {
  1343. key := sc.canonicalHeader(hf.Name)
  1344. st.trailer[key] = append(st.trailer[key], hf.Value)
  1345. }
  1346. }
  1347. st.endStream()
  1348. return nil
  1349. }
  1350. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1351. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1352. return nil
  1353. }
  1354. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1355. st, ok := streams[streamID]
  1356. if !ok {
  1357. // TODO: not quite correct (this streamID might
  1358. // already exist in the dep tree, but be closed), but
  1359. // close enough for now.
  1360. return
  1361. }
  1362. st.weight = priority.Weight
  1363. parent := streams[priority.StreamDep] // might be nil
  1364. if parent == st {
  1365. // if client tries to set this stream to be the parent of itself
  1366. // ignore and keep going
  1367. return
  1368. }
  1369. // section 5.3.3: If a stream is made dependent on one of its
  1370. // own dependencies, the formerly dependent stream is first
  1371. // moved to be dependent on the reprioritized stream's previous
  1372. // parent. The moved dependency retains its weight.
  1373. for piter := parent; piter != nil; piter = piter.parent {
  1374. if piter == st {
  1375. parent.parent = st.parent
  1376. break
  1377. }
  1378. }
  1379. st.parent = parent
  1380. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1381. for _, openStream := range streams {
  1382. if openStream != st && openStream.parent == st.parent {
  1383. openStream.parent = st
  1384. }
  1385. }
  1386. }
  1387. }
  1388. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1389. sc.serveG.check()
  1390. method := f.PseudoValue("method")
  1391. path := f.PseudoValue("path")
  1392. scheme := f.PseudoValue("scheme")
  1393. authority := f.PseudoValue("authority")
  1394. isConnect := method == "CONNECT"
  1395. if isConnect {
  1396. if path != "" || scheme != "" || authority == "" {
  1397. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1398. }
  1399. } else if method == "" || path == "" ||
  1400. (scheme != "https" && scheme != "http") {
  1401. // See 8.1.2.6 Malformed Requests and Responses:
  1402. //
  1403. // Malformed requests or responses that are detected
  1404. // MUST be treated as a stream error (Section 5.4.2)
  1405. // of type PROTOCOL_ERROR."
  1406. //
  1407. // 8.1.2.3 Request Pseudo-Header Fields
  1408. // "All HTTP/2 requests MUST include exactly one valid
  1409. // value for the :method, :scheme, and :path
  1410. // pseudo-header fields"
  1411. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1412. }
  1413. bodyOpen := !f.StreamEnded()
  1414. if method == "HEAD" && bodyOpen {
  1415. // HEAD requests can't have bodies
  1416. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1417. }
  1418. var tlsState *tls.ConnectionState // nil if not scheme https
  1419. if scheme == "https" {
  1420. tlsState = sc.tlsState
  1421. }
  1422. header := make(http.Header)
  1423. for _, hf := range f.RegularFields() {
  1424. header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1425. }
  1426. if authority == "" {
  1427. authority = header.Get("Host")
  1428. }
  1429. needsContinue := header.Get("Expect") == "100-continue"
  1430. if needsContinue {
  1431. header.Del("Expect")
  1432. }
  1433. // Merge Cookie headers into one "; "-delimited value.
  1434. if cookies := header["Cookie"]; len(cookies) > 1 {
  1435. header.Set("Cookie", strings.Join(cookies, "; "))
  1436. }
  1437. // Setup Trailers
  1438. var trailer http.Header
  1439. for _, v := range header["Trailer"] {
  1440. for _, key := range strings.Split(v, ",") {
  1441. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1442. switch key {
  1443. case "Transfer-Encoding", "Trailer", "Content-Length":
  1444. // Bogus. (copy of http1 rules)
  1445. // Ignore.
  1446. default:
  1447. if trailer == nil {
  1448. trailer = make(http.Header)
  1449. }
  1450. trailer[key] = nil
  1451. }
  1452. }
  1453. }
  1454. delete(header, "Trailer")
  1455. body := &requestBody{
  1456. conn: sc,
  1457. stream: st,
  1458. needsContinue: needsContinue,
  1459. }
  1460. var url_ *url.URL
  1461. var requestURI string
  1462. if isConnect {
  1463. url_ = &url.URL{Host: authority}
  1464. requestURI = authority // mimic HTTP/1 server behavior
  1465. } else {
  1466. var err error
  1467. url_, err = url.ParseRequestURI(path)
  1468. if err != nil {
  1469. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1470. }
  1471. requestURI = path
  1472. }
  1473. req := &http.Request{
  1474. Method: method,
  1475. URL: url_,
  1476. RemoteAddr: sc.remoteAddrStr,
  1477. Header: header,
  1478. RequestURI: requestURI,
  1479. Proto: "HTTP/2.0",
  1480. ProtoMajor: 2,
  1481. ProtoMinor: 0,
  1482. TLS: tlsState,
  1483. Host: authority,
  1484. Body: body,
  1485. Trailer: trailer,
  1486. }
  1487. if bodyOpen {
  1488. st.reqBuf = sc.getRequestBodyBuf()
  1489. body.pipe = &pipe{
  1490. b: &fixedBuffer{buf: st.reqBuf},
  1491. }
  1492. if vv, ok := header["Content-Length"]; ok {
  1493. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1494. } else {
  1495. req.ContentLength = -1
  1496. }
  1497. }
  1498. rws := responseWriterStatePool.Get().(*responseWriterState)
  1499. bwSave := rws.bw
  1500. *rws = responseWriterState{} // zero all the fields
  1501. rws.conn = sc
  1502. rws.bw = bwSave
  1503. rws.bw.Reset(chunkWriter{rws})
  1504. rws.stream = st
  1505. rws.req = req
  1506. rws.body = body
  1507. rw := &responseWriter{rws: rws}
  1508. return rw, req, nil
  1509. }
  1510. func (sc *serverConn) getRequestBodyBuf() []byte {
  1511. sc.serveG.check()
  1512. if buf := sc.freeRequestBodyBuf; buf != nil {
  1513. sc.freeRequestBodyBuf = nil
  1514. return buf
  1515. }
  1516. return make([]byte, initialWindowSize)
  1517. }
  1518. // Run on its own goroutine.
  1519. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1520. didPanic := true
  1521. defer func() {
  1522. if didPanic {
  1523. e := recover()
  1524. // Same as net/http:
  1525. const size = 64 << 10
  1526. buf := make([]byte, size)
  1527. buf = buf[:runtime.Stack(buf, false)]
  1528. sc.writeFrameFromHandler(frameWriteMsg{
  1529. write: handlerPanicRST{rw.rws.stream.id},
  1530. stream: rw.rws.stream,
  1531. })
  1532. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1533. return
  1534. }
  1535. rw.handlerDone()
  1536. }()
  1537. handler(rw, req)
  1538. didPanic = false
  1539. }
  1540. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1541. // 10.5.1 Limits on Header Block Size:
  1542. // .. "A server that receives a larger header block than it is
  1543. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1544. // Large) status code"
  1545. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1546. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1547. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1548. }
  1549. // called from handler goroutines.
  1550. // h may be nil.
  1551. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1552. sc.serveG.checkNotOn() // NOT on
  1553. var errc chan error
  1554. if headerData.h != nil {
  1555. // If there's a header map (which we don't own), so we have to block on
  1556. // waiting for this frame to be written, so an http.Flush mid-handler
  1557. // writes out the correct value of keys, before a handler later potentially
  1558. // mutates it.
  1559. errc = errChanPool.Get().(chan error)
  1560. }
  1561. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1562. write: headerData,
  1563. stream: st,
  1564. done: errc,
  1565. }); err != nil {
  1566. return err
  1567. }
  1568. if errc != nil {
  1569. select {
  1570. case err := <-errc:
  1571. errChanPool.Put(errc)
  1572. return err
  1573. case <-sc.doneServing:
  1574. return errClientDisconnected
  1575. case <-st.cw:
  1576. return errStreamClosed
  1577. }
  1578. }
  1579. return nil
  1580. }
  1581. // called from handler goroutines.
  1582. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1583. sc.writeFrameFromHandler(frameWriteMsg{
  1584. write: write100ContinueHeadersFrame{st.id},
  1585. stream: st,
  1586. })
  1587. }
  1588. // A bodyReadMsg tells the server loop that the http.Handler read n
  1589. // bytes of the DATA from the client on the given stream.
  1590. type bodyReadMsg struct {
  1591. st *stream
  1592. n int
  1593. }
  1594. // called from handler goroutines.
  1595. // Notes that the handler for the given stream ID read n bytes of its body
  1596. // and schedules flow control tokens to be sent.
  1597. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1598. sc.serveG.checkNotOn() // NOT on
  1599. select {
  1600. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1601. case <-sc.doneServing:
  1602. }
  1603. }
  1604. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1605. sc.serveG.check()
  1606. sc.sendWindowUpdate(nil, n) // conn-level
  1607. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1608. // Don't send this WINDOW_UPDATE if the stream is closed
  1609. // remotely.
  1610. sc.sendWindowUpdate(st, n)
  1611. }
  1612. }
  1613. // st may be nil for conn-level
  1614. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1615. sc.serveG.check()
  1616. // "The legal range for the increment to the flow control
  1617. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1618. // A Go Read call on 64-bit machines could in theory read
  1619. // a larger Read than this. Very unlikely, but we handle it here
  1620. // rather than elsewhere for now.
  1621. const maxUint31 = 1<<31 - 1
  1622. for n >= maxUint31 {
  1623. sc.sendWindowUpdate32(st, maxUint31)
  1624. n -= maxUint31
  1625. }
  1626. sc.sendWindowUpdate32(st, int32(n))
  1627. }
  1628. // st may be nil for conn-level
  1629. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1630. sc.serveG.check()
  1631. if n == 0 {
  1632. return
  1633. }
  1634. if n < 0 {
  1635. panic("negative update")
  1636. }
  1637. var streamID uint32
  1638. if st != nil {
  1639. streamID = st.id
  1640. }
  1641. sc.writeFrame(frameWriteMsg{
  1642. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1643. stream: st,
  1644. })
  1645. var ok bool
  1646. if st == nil {
  1647. ok = sc.inflow.add(n)
  1648. } else {
  1649. ok = st.inflow.add(n)
  1650. }
  1651. if !ok {
  1652. panic("internal error; sent too many window updates without decrements?")
  1653. }
  1654. }
  1655. type requestBody struct {
  1656. stream *stream
  1657. conn *serverConn
  1658. closed bool
  1659. pipe *pipe // non-nil if we have a HTTP entity message body
  1660. needsContinue bool // need to send a 100-continue
  1661. }
  1662. func (b *requestBody) Close() error {
  1663. if b.pipe != nil {
  1664. b.pipe.CloseWithError(errClosedBody)
  1665. }
  1666. b.closed = true
  1667. return nil
  1668. }
  1669. func (b *requestBody) Read(p []byte) (n int, err error) {
  1670. if b.needsContinue {
  1671. b.needsContinue = false
  1672. b.conn.write100ContinueHeaders(b.stream)
  1673. }
  1674. if b.pipe == nil {
  1675. return 0, io.EOF
  1676. }
  1677. n, err = b.pipe.Read(p)
  1678. if n > 0 {
  1679. b.conn.noteBodyReadFromHandler(b.stream, n)
  1680. }
  1681. return
  1682. }
  1683. // responseWriter is the http.ResponseWriter implementation. It's
  1684. // intentionally small (1 pointer wide) to minimize garbage. The
  1685. // responseWriterState pointer inside is zeroed at the end of a
  1686. // request (in handlerDone) and calls on the responseWriter thereafter
  1687. // simply crash (caller's mistake), but the much larger responseWriterState
  1688. // and buffers are reused between multiple requests.
  1689. type responseWriter struct {
  1690. rws *responseWriterState
  1691. }
  1692. // Optional http.ResponseWriter interfaces implemented.
  1693. var (
  1694. _ http.CloseNotifier = (*responseWriter)(nil)
  1695. _ http.Flusher = (*responseWriter)(nil)
  1696. _ stringWriter = (*responseWriter)(nil)
  1697. )
  1698. type responseWriterState struct {
  1699. // immutable within a request:
  1700. stream *stream
  1701. req *http.Request
  1702. body *requestBody // to close at end of request, if DATA frames didn't
  1703. conn *serverConn
  1704. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1705. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1706. // mutated by http.Handler goroutine:
  1707. handlerHeader http.Header // nil until called
  1708. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1709. trailers []string // set in writeChunk
  1710. status int // status code passed to WriteHeader
  1711. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1712. sentHeader bool // have we sent the header frame?
  1713. handlerDone bool // handler has finished
  1714. sentContentLen int64 // non-zero if handler set a Content-Length header
  1715. wroteBytes int64
  1716. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1717. closeNotifierCh chan bool // nil until first used
  1718. }
  1719. type chunkWriter struct{ rws *responseWriterState }
  1720. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1721. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1722. // declareTrailer is called for each Trailer header when the
  1723. // response header is written. It notes that a header will need to be
  1724. // written in the trailers at the end of the response.
  1725. func (rws *responseWriterState) declareTrailer(k string) {
  1726. k = http.CanonicalHeaderKey(k)
  1727. switch k {
  1728. case "Transfer-Encoding", "Content-Length", "Trailer":
  1729. // Forbidden by RFC 2616 14.40.
  1730. return
  1731. }
  1732. if !strSliceContains(rws.trailers, k) {
  1733. rws.trailers = append(rws.trailers, k)
  1734. }
  1735. }
  1736. // writeChunk writes chunks from the bufio.Writer. But because
  1737. // bufio.Writer may bypass its chunking, sometimes p may be
  1738. // arbitrarily large.
  1739. //
  1740. // writeChunk is also responsible (on the first chunk) for sending the
  1741. // HEADER response.
  1742. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1743. if !rws.wroteHeader {
  1744. rws.writeHeader(200)
  1745. }
  1746. isHeadResp := rws.req.Method == "HEAD"
  1747. if !rws.sentHeader {
  1748. rws.sentHeader = true
  1749. var ctype, clen string
  1750. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1751. rws.snapHeader.Del("Content-Length")
  1752. clen64, err := strconv.ParseInt(clen, 10, 64)
  1753. if err == nil && clen64 >= 0 {
  1754. rws.sentContentLen = clen64
  1755. } else {
  1756. clen = ""
  1757. }
  1758. }
  1759. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1760. clen = strconv.Itoa(len(p))
  1761. }
  1762. _, hasContentType := rws.snapHeader["Content-Type"]
  1763. if !hasContentType && bodyAllowedForStatus(rws.status) {
  1764. ctype = http.DetectContentType(p)
  1765. }
  1766. var date string
  1767. if _, ok := rws.snapHeader["Date"]; !ok {
  1768. // TODO(bradfitz): be faster here, like net/http? measure.
  1769. date = time.Now().UTC().Format(http.TimeFormat)
  1770. }
  1771. for _, v := range rws.snapHeader["Trailer"] {
  1772. foreachHeaderElement(v, rws.declareTrailer)
  1773. }
  1774. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  1775. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1776. streamID: rws.stream.id,
  1777. httpResCode: rws.status,
  1778. h: rws.snapHeader,
  1779. endStream: endStream,
  1780. contentType: ctype,
  1781. contentLength: clen,
  1782. date: date,
  1783. })
  1784. if err != nil {
  1785. return 0, err
  1786. }
  1787. if endStream {
  1788. return 0, nil
  1789. }
  1790. }
  1791. if isHeadResp {
  1792. return len(p), nil
  1793. }
  1794. if len(p) == 0 && !rws.handlerDone {
  1795. return 0, nil
  1796. }
  1797. if rws.handlerDone {
  1798. rws.promoteUndeclaredTrailers()
  1799. }
  1800. endStream := rws.handlerDone && !rws.hasTrailers()
  1801. if len(p) > 0 || endStream {
  1802. // only send a 0 byte DATA frame if we're ending the stream.
  1803. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  1804. return 0, err
  1805. }
  1806. }
  1807. if rws.handlerDone && rws.hasTrailers() {
  1808. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1809. streamID: rws.stream.id,
  1810. h: rws.handlerHeader,
  1811. trailers: rws.trailers,
  1812. endStream: true,
  1813. })
  1814. return len(p), err
  1815. }
  1816. return len(p), nil
  1817. }
  1818. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  1819. // that, if present, signals that the map entry is actually for
  1820. // the response trailers, and not the response headers. The prefix
  1821. // is stripped after the ServeHTTP call finishes and the values are
  1822. // sent in the trailers.
  1823. //
  1824. // This mechanism is intended only for trailers that are not known
  1825. // prior to the headers being written. If the set of trailers is fixed
  1826. // or known before the header is written, the normal Go trailers mechanism
  1827. // is preferred:
  1828. // https://golang.org/pkg/net/http/#ResponseWriter
  1829. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  1830. const TrailerPrefix = "Trailer:"
  1831. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  1832. // after the header has already been flushed. Because the Go
  1833. // ResponseWriter interface has no way to set Trailers (only the
  1834. // Header), and because we didn't want to expand the ResponseWriter
  1835. // interface, and because nobody used trailers, and because RFC 2616
  1836. // says you SHOULD (but not must) predeclare any trailers in the
  1837. // header, the official ResponseWriter rules said trailers in Go must
  1838. // be predeclared, and then we reuse the same ResponseWriter.Header()
  1839. // map to mean both Headers and Trailers. When it's time to write the
  1840. // Trailers, we pick out the fields of Headers that were declared as
  1841. // trailers. That worked for a while, until we found the first major
  1842. // user of Trailers in the wild: gRPC (using them only over http2),
  1843. // and gRPC libraries permit setting trailers mid-stream without
  1844. // predeclarnig them. So: change of plans. We still permit the old
  1845. // way, but we also permit this hack: if a Header() key begins with
  1846. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  1847. // invalid token byte anyway, there is no ambiguity. (And it's already
  1848. // filtered out) It's mildly hacky, but not terrible.
  1849. //
  1850. // This method runs after the Handler is done and promotes any Header
  1851. // fields to be trailers.
  1852. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  1853. for k, vv := range rws.handlerHeader {
  1854. if !strings.HasPrefix(k, TrailerPrefix) {
  1855. continue
  1856. }
  1857. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  1858. rws.declareTrailer(trailerKey)
  1859. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  1860. }
  1861. sort.Strings(rws.trailers)
  1862. }
  1863. func (w *responseWriter) Flush() {
  1864. rws := w.rws
  1865. if rws == nil {
  1866. panic("Header called after Handler finished")
  1867. }
  1868. if rws.bw.Buffered() > 0 {
  1869. if err := rws.bw.Flush(); err != nil {
  1870. // Ignore the error. The frame writer already knows.
  1871. return
  1872. }
  1873. } else {
  1874. // The bufio.Writer won't call chunkWriter.Write
  1875. // (writeChunk with zero bytes, so we have to do it
  1876. // ourselves to force the HTTP response header and/or
  1877. // final DATA frame (with END_STREAM) to be sent.
  1878. rws.writeChunk(nil)
  1879. }
  1880. }
  1881. func (w *responseWriter) CloseNotify() <-chan bool {
  1882. rws := w.rws
  1883. if rws == nil {
  1884. panic("CloseNotify called after Handler finished")
  1885. }
  1886. rws.closeNotifierMu.Lock()
  1887. ch := rws.closeNotifierCh
  1888. if ch == nil {
  1889. ch = make(chan bool, 1)
  1890. rws.closeNotifierCh = ch
  1891. go func() {
  1892. rws.stream.cw.Wait() // wait for close
  1893. ch <- true
  1894. }()
  1895. }
  1896. rws.closeNotifierMu.Unlock()
  1897. return ch
  1898. }
  1899. func (w *responseWriter) Header() http.Header {
  1900. rws := w.rws
  1901. if rws == nil {
  1902. panic("Header called after Handler finished")
  1903. }
  1904. if rws.handlerHeader == nil {
  1905. rws.handlerHeader = make(http.Header)
  1906. }
  1907. return rws.handlerHeader
  1908. }
  1909. func (w *responseWriter) WriteHeader(code int) {
  1910. rws := w.rws
  1911. if rws == nil {
  1912. panic("WriteHeader called after Handler finished")
  1913. }
  1914. rws.writeHeader(code)
  1915. }
  1916. func (rws *responseWriterState) writeHeader(code int) {
  1917. if !rws.wroteHeader {
  1918. rws.wroteHeader = true
  1919. rws.status = code
  1920. if len(rws.handlerHeader) > 0 {
  1921. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1922. }
  1923. }
  1924. }
  1925. func cloneHeader(h http.Header) http.Header {
  1926. h2 := make(http.Header, len(h))
  1927. for k, vv := range h {
  1928. vv2 := make([]string, len(vv))
  1929. copy(vv2, vv)
  1930. h2[k] = vv2
  1931. }
  1932. return h2
  1933. }
  1934. // The Life Of A Write is like this:
  1935. //
  1936. // * Handler calls w.Write or w.WriteString ->
  1937. // * -> rws.bw (*bufio.Writer) ->
  1938. // * (Handler migth call Flush)
  1939. // * -> chunkWriter{rws}
  1940. // * -> responseWriterState.writeChunk(p []byte)
  1941. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1942. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1943. return w.write(len(p), p, "")
  1944. }
  1945. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1946. return w.write(len(s), nil, s)
  1947. }
  1948. // either dataB or dataS is non-zero.
  1949. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1950. rws := w.rws
  1951. if rws == nil {
  1952. panic("Write called after Handler finished")
  1953. }
  1954. if !rws.wroteHeader {
  1955. w.WriteHeader(200)
  1956. }
  1957. if !bodyAllowedForStatus(rws.status) {
  1958. return 0, http.ErrBodyNotAllowed
  1959. }
  1960. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  1961. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  1962. // TODO: send a RST_STREAM
  1963. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  1964. }
  1965. if dataB != nil {
  1966. return rws.bw.Write(dataB)
  1967. } else {
  1968. return rws.bw.WriteString(dataS)
  1969. }
  1970. }
  1971. func (w *responseWriter) handlerDone() {
  1972. rws := w.rws
  1973. rws.handlerDone = true
  1974. w.Flush()
  1975. w.rws = nil
  1976. responseWriterStatePool.Put(rws)
  1977. }
  1978. // foreachHeaderElement splits v according to the "#rule" construction
  1979. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  1980. func foreachHeaderElement(v string, fn func(string)) {
  1981. v = textproto.TrimString(v)
  1982. if v == "" {
  1983. return
  1984. }
  1985. if !strings.Contains(v, ",") {
  1986. fn(v)
  1987. return
  1988. }
  1989. for _, f := range strings.Split(v, ",") {
  1990. if f = textproto.TrimString(f); f != "" {
  1991. fn(f)
  1992. }
  1993. }
  1994. }