server.go 79 KB

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