server.go 64 KB

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