server.go 77 KB

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