server.go 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281
  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. "context"
  28. "crypto/tls"
  29. "errors"
  30. "fmt"
  31. "io"
  32. "log"
  33. "math"
  34. "net"
  35. "net/http"
  36. "net/textproto"
  37. "net/url"
  38. "os"
  39. "reflect"
  40. "runtime"
  41. "strconv"
  42. "strings"
  43. "sync"
  44. "time"
  45. "golang.org/x/net/http/httpguts"
  46. "golang.org/x/net/http2/hpack"
  47. )
  48. const (
  49. prefaceTimeout = 10 * time.Second
  50. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  51. handlerChunkWriteSize = 4 << 10
  52. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  53. maxQueuedControlFrames = 10000
  54. )
  55. var (
  56. errClientDisconnected = errors.New("client disconnected")
  57. errClosedBody = errors.New("body closed by handler")
  58. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  59. errStreamClosed = errors.New("http2: stream closed")
  60. )
  61. var responseWriterStatePool = sync.Pool{
  62. New: func() interface{} {
  63. rws := &responseWriterState{}
  64. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  65. return rws
  66. },
  67. }
  68. // Test hooks.
  69. var (
  70. testHookOnConn func()
  71. testHookGetServerConn func(*serverConn)
  72. testHookOnPanicMu *sync.Mutex // nil except in tests
  73. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  74. )
  75. // Server is an HTTP/2 server.
  76. type Server struct {
  77. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  78. // which may run at a time over all connections.
  79. // Negative or zero no limit.
  80. // TODO: implement
  81. MaxHandlers int
  82. // MaxConcurrentStreams optionally specifies the number of
  83. // concurrent streams that each client may have open at a
  84. // time. This is unrelated to the number of http.Handler goroutines
  85. // which may be active globally, which is MaxHandlers.
  86. // If zero, MaxConcurrentStreams defaults to at least 100, per
  87. // the HTTP/2 spec's recommendations.
  88. MaxConcurrentStreams uint32
  89. // MaxDecoderHeaderTableSize optionally specifies the http2
  90. // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
  91. // informs the remote endpoint of the maximum size of the header compression
  92. // table used to decode header blocks, in octets. If zero, the default value
  93. // of 4096 is used.
  94. MaxDecoderHeaderTableSize uint32
  95. // MaxEncoderHeaderTableSize optionally specifies an upper limit for the
  96. // header compression table used for encoding request headers. Received
  97. // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
  98. // the default value of 4096 is used.
  99. MaxEncoderHeaderTableSize uint32
  100. // MaxReadFrameSize optionally specifies the largest frame
  101. // this server is willing to read. A valid value is between
  102. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  103. // default value is used.
  104. MaxReadFrameSize uint32
  105. // PermitProhibitedCipherSuites, if true, permits the use of
  106. // cipher suites prohibited by the HTTP/2 spec.
  107. PermitProhibitedCipherSuites bool
  108. // IdleTimeout specifies how long until idle clients should be
  109. // closed with a GOAWAY frame. PING frames are not considered
  110. // activity for the purposes of IdleTimeout.
  111. // If zero or negative, there is no timeout.
  112. IdleTimeout time.Duration
  113. // MaxUploadBufferPerConnection is the size of the initial flow
  114. // control window for each connections. The HTTP/2 spec does not
  115. // allow this to be smaller than 65535 or larger than 2^32-1.
  116. // If the value is outside this range, a default value will be
  117. // used instead.
  118. MaxUploadBufferPerConnection int32
  119. // MaxUploadBufferPerStream is the size of the initial flow control
  120. // window for each stream. The HTTP/2 spec does not allow this to
  121. // be larger than 2^32-1. If the value is zero or larger than the
  122. // maximum, a default value will be used instead.
  123. MaxUploadBufferPerStream int32
  124. // NewWriteScheduler constructs a write scheduler for a connection.
  125. // If nil, a default scheduler is chosen.
  126. NewWriteScheduler func() WriteScheduler
  127. // CountError, if non-nil, is called on HTTP/2 server errors.
  128. // It's intended to increment a metric for monitoring, such
  129. // as an expvar or Prometheus metric.
  130. // The errType consists of only ASCII word characters.
  131. CountError func(errType string)
  132. // Internal state. This is a pointer (rather than embedded directly)
  133. // so that we don't embed a Mutex in this struct, which will make the
  134. // struct non-copyable, which might break some callers.
  135. state *serverInternalState
  136. }
  137. func (s *Server) initialConnRecvWindowSize() int32 {
  138. if s.MaxUploadBufferPerConnection >= initialWindowSize {
  139. return s.MaxUploadBufferPerConnection
  140. }
  141. return 1 << 20
  142. }
  143. func (s *Server) initialStreamRecvWindowSize() int32 {
  144. if s.MaxUploadBufferPerStream > 0 {
  145. return s.MaxUploadBufferPerStream
  146. }
  147. return 1 << 20
  148. }
  149. func (s *Server) maxReadFrameSize() uint32 {
  150. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  151. return v
  152. }
  153. return defaultMaxReadFrameSize
  154. }
  155. func (s *Server) maxConcurrentStreams() uint32 {
  156. if v := s.MaxConcurrentStreams; v > 0 {
  157. return v
  158. }
  159. return defaultMaxStreams
  160. }
  161. func (s *Server) maxDecoderHeaderTableSize() uint32 {
  162. if v := s.MaxDecoderHeaderTableSize; v > 0 {
  163. return v
  164. }
  165. return initialHeaderTableSize
  166. }
  167. func (s *Server) maxEncoderHeaderTableSize() uint32 {
  168. if v := s.MaxEncoderHeaderTableSize; v > 0 {
  169. return v
  170. }
  171. return initialHeaderTableSize
  172. }
  173. // maxQueuedControlFrames is the maximum number of control frames like
  174. // SETTINGS, PING and RST_STREAM that will be queued for writing before
  175. // the connection is closed to prevent memory exhaustion attacks.
  176. func (s *Server) maxQueuedControlFrames() int {
  177. // TODO: if anybody asks, add a Server field, and remember to define the
  178. // behavior of negative values.
  179. return maxQueuedControlFrames
  180. }
  181. type serverInternalState struct {
  182. mu sync.Mutex
  183. activeConns map[*serverConn]struct{}
  184. }
  185. func (s *serverInternalState) registerConn(sc *serverConn) {
  186. if s == nil {
  187. return // if the Server was used without calling ConfigureServer
  188. }
  189. s.mu.Lock()
  190. s.activeConns[sc] = struct{}{}
  191. s.mu.Unlock()
  192. }
  193. func (s *serverInternalState) unregisterConn(sc *serverConn) {
  194. if s == nil {
  195. return // if the Server was used without calling ConfigureServer
  196. }
  197. s.mu.Lock()
  198. delete(s.activeConns, sc)
  199. s.mu.Unlock()
  200. }
  201. func (s *serverInternalState) startGracefulShutdown() {
  202. if s == nil {
  203. return // if the Server was used without calling ConfigureServer
  204. }
  205. s.mu.Lock()
  206. for sc := range s.activeConns {
  207. sc.startGracefulShutdown()
  208. }
  209. s.mu.Unlock()
  210. }
  211. // ConfigureServer adds HTTP/2 support to a net/http Server.
  212. //
  213. // The configuration conf may be nil.
  214. //
  215. // ConfigureServer must be called before s begins serving.
  216. func ConfigureServer(s *http.Server, conf *Server) error {
  217. if s == nil {
  218. panic("nil *http.Server")
  219. }
  220. if conf == nil {
  221. conf = new(Server)
  222. }
  223. conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})}
  224. if h1, h2 := s, conf; h2.IdleTimeout == 0 {
  225. if h1.IdleTimeout != 0 {
  226. h2.IdleTimeout = h1.IdleTimeout
  227. } else {
  228. h2.IdleTimeout = h1.ReadTimeout
  229. }
  230. }
  231. s.RegisterOnShutdown(conf.state.startGracefulShutdown)
  232. if s.TLSConfig == nil {
  233. s.TLSConfig = new(tls.Config)
  234. } else if s.TLSConfig.CipherSuites != nil && s.TLSConfig.MinVersion < tls.VersionTLS13 {
  235. // If they already provided a TLS 1.0–1.2 CipherSuite list, return an
  236. // error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or
  237. // ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
  238. haveRequired := false
  239. for _, cs := range s.TLSConfig.CipherSuites {
  240. switch cs {
  241. case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  242. // Alternative MTI cipher to not discourage ECDSA-only servers.
  243. // See http://golang.org/cl/30721 for further information.
  244. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
  245. haveRequired = true
  246. }
  247. }
  248. if !haveRequired {
  249. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
  250. }
  251. }
  252. // Note: not setting MinVersion to tls.VersionTLS12,
  253. // as we don't want to interfere with HTTP/1.1 traffic
  254. // on the user's server. We enforce TLS 1.2 later once
  255. // we accept a connection. Ideally this should be done
  256. // during next-proto selection, but using TLS <1.2 with
  257. // HTTP/2 is still the client's bug.
  258. s.TLSConfig.PreferServerCipherSuites = true
  259. if !strSliceContains(s.TLSConfig.NextProtos, NextProtoTLS) {
  260. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  261. }
  262. if !strSliceContains(s.TLSConfig.NextProtos, "http/1.1") {
  263. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1")
  264. }
  265. if s.TLSNextProto == nil {
  266. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  267. }
  268. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  269. if testHookOnConn != nil {
  270. testHookOnConn()
  271. }
  272. // The TLSNextProto interface predates contexts, so
  273. // the net/http package passes down its per-connection
  274. // base context via an exported but unadvertised
  275. // method on the Handler. This is for internal
  276. // net/http<=>http2 use only.
  277. var ctx context.Context
  278. type baseContexter interface {
  279. BaseContext() context.Context
  280. }
  281. if bc, ok := h.(baseContexter); ok {
  282. ctx = bc.BaseContext()
  283. }
  284. conf.ServeConn(c, &ServeConnOpts{
  285. Context: ctx,
  286. Handler: h,
  287. BaseConfig: hs,
  288. })
  289. }
  290. s.TLSNextProto[NextProtoTLS] = protoHandler
  291. return nil
  292. }
  293. // ServeConnOpts are options for the Server.ServeConn method.
  294. type ServeConnOpts struct {
  295. // Context is the base context to use.
  296. // If nil, context.Background is used.
  297. Context context.Context
  298. // BaseConfig optionally sets the base configuration
  299. // for values. If nil, defaults are used.
  300. BaseConfig *http.Server
  301. // Handler specifies which handler to use for processing
  302. // requests. If nil, BaseConfig.Handler is used. If BaseConfig
  303. // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
  304. Handler http.Handler
  305. // UpgradeRequest is an initial request received on a connection
  306. // undergoing an h2c upgrade. The request body must have been
  307. // completely read from the connection before calling ServeConn,
  308. // and the 101 Switching Protocols response written.
  309. UpgradeRequest *http.Request
  310. // Settings is the decoded contents of the HTTP2-Settings header
  311. // in an h2c upgrade request.
  312. Settings []byte
  313. // SawClientPreface is set if the HTTP/2 connection preface
  314. // has already been read from the connection.
  315. SawClientPreface bool
  316. }
  317. func (o *ServeConnOpts) context() context.Context {
  318. if o != nil && o.Context != nil {
  319. return o.Context
  320. }
  321. return context.Background()
  322. }
  323. func (o *ServeConnOpts) baseConfig() *http.Server {
  324. if o != nil && o.BaseConfig != nil {
  325. return o.BaseConfig
  326. }
  327. return new(http.Server)
  328. }
  329. func (o *ServeConnOpts) handler() http.Handler {
  330. if o != nil {
  331. if o.Handler != nil {
  332. return o.Handler
  333. }
  334. if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
  335. return o.BaseConfig.Handler
  336. }
  337. }
  338. return http.DefaultServeMux
  339. }
  340. // ServeConn serves HTTP/2 requests on the provided connection and
  341. // blocks until the connection is no longer readable.
  342. //
  343. // ServeConn starts speaking HTTP/2 assuming that c has not had any
  344. // reads or writes. It writes its initial settings frame and expects
  345. // to be able to read the preface and settings frame from the
  346. // client. If c has a ConnectionState method like a *tls.Conn, the
  347. // ConnectionState is used to verify the TLS ciphersuite and to set
  348. // the Request.TLS field in Handlers.
  349. //
  350. // ServeConn does not support h2c by itself. Any h2c support must be
  351. // implemented in terms of providing a suitably-behaving net.Conn.
  352. //
  353. // The opts parameter is optional. If nil, default values are used.
  354. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
  355. baseCtx, cancel := serverConnBaseContext(c, opts)
  356. defer cancel()
  357. sc := &serverConn{
  358. srv: s,
  359. hs: opts.baseConfig(),
  360. conn: c,
  361. baseCtx: baseCtx,
  362. remoteAddrStr: c.RemoteAddr().String(),
  363. bw: newBufferedWriter(c),
  364. handler: opts.handler(),
  365. streams: make(map[uint32]*stream),
  366. readFrameCh: make(chan readFrameResult),
  367. wantWriteFrameCh: make(chan FrameWriteRequest, 8),
  368. serveMsgCh: make(chan interface{}, 8),
  369. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  370. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  371. doneServing: make(chan struct{}),
  372. clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
  373. advMaxStreams: s.maxConcurrentStreams(),
  374. initialStreamSendWindowSize: initialWindowSize,
  375. maxFrameSize: initialMaxFrameSize,
  376. serveG: newGoroutineLock(),
  377. pushEnabled: true,
  378. sawClientPreface: opts.SawClientPreface,
  379. }
  380. s.state.registerConn(sc)
  381. defer s.state.unregisterConn(sc)
  382. // The net/http package sets the write deadline from the
  383. // http.Server.WriteTimeout during the TLS handshake, but then
  384. // passes the connection off to us with the deadline already set.
  385. // Write deadlines are set per stream in serverConn.newStream.
  386. // Disarm the net.Conn write deadline here.
  387. if sc.hs.WriteTimeout > 0 {
  388. sc.conn.SetWriteDeadline(time.Time{})
  389. }
  390. if s.NewWriteScheduler != nil {
  391. sc.writeSched = s.NewWriteScheduler()
  392. } else {
  393. sc.writeSched = newRoundRobinWriteScheduler()
  394. }
  395. // These start at the RFC-specified defaults. If there is a higher
  396. // configured value for inflow, that will be updated when we send a
  397. // WINDOW_UPDATE shortly after sending SETTINGS.
  398. sc.flow.add(initialWindowSize)
  399. sc.inflow.init(initialWindowSize)
  400. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  401. sc.hpackEncoder.SetMaxDynamicTableSizeLimit(s.maxEncoderHeaderTableSize())
  402. fr := NewFramer(sc.bw, c)
  403. if s.CountError != nil {
  404. fr.countError = s.CountError
  405. }
  406. fr.ReadMetaHeaders = hpack.NewDecoder(s.maxDecoderHeaderTableSize(), nil)
  407. fr.MaxHeaderListSize = sc.maxHeaderListSize()
  408. fr.SetMaxReadFrameSize(s.maxReadFrameSize())
  409. sc.framer = fr
  410. if tc, ok := c.(connectionStater); ok {
  411. sc.tlsState = new(tls.ConnectionState)
  412. *sc.tlsState = tc.ConnectionState()
  413. // 9.2 Use of TLS Features
  414. // An implementation of HTTP/2 over TLS MUST use TLS
  415. // 1.2 or higher with the restrictions on feature set
  416. // and cipher suite described in this section. Due to
  417. // implementation limitations, it might not be
  418. // possible to fail TLS negotiation. An endpoint MUST
  419. // immediately terminate an HTTP/2 connection that
  420. // does not meet the TLS requirements described in
  421. // this section with a connection error (Section
  422. // 5.4.1) of type INADEQUATE_SECURITY.
  423. if sc.tlsState.Version < tls.VersionTLS12 {
  424. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  425. return
  426. }
  427. if sc.tlsState.ServerName == "" {
  428. // Client must use SNI, but we don't enforce that anymore,
  429. // since it was causing problems when connecting to bare IP
  430. // addresses during development.
  431. //
  432. // TODO: optionally enforce? Or enforce at the time we receive
  433. // a new request, and verify the ServerName matches the :authority?
  434. // But that precludes proxy situations, perhaps.
  435. //
  436. // So for now, do nothing here again.
  437. }
  438. if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  439. // "Endpoints MAY choose to generate a connection error
  440. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  441. // the prohibited cipher suites are negotiated."
  442. //
  443. // We choose that. In my opinion, the spec is weak
  444. // here. It also says both parties must support at least
  445. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  446. // excuses here. If we really must, we could allow an
  447. // "AllowInsecureWeakCiphers" option on the server later.
  448. // Let's see how it plays out first.
  449. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  450. return
  451. }
  452. }
  453. if opts.Settings != nil {
  454. fr := &SettingsFrame{
  455. FrameHeader: FrameHeader{valid: true},
  456. p: opts.Settings,
  457. }
  458. if err := fr.ForeachSetting(sc.processSetting); err != nil {
  459. sc.rejectConn(ErrCodeProtocol, "invalid settings")
  460. return
  461. }
  462. opts.Settings = nil
  463. }
  464. if hook := testHookGetServerConn; hook != nil {
  465. hook(sc)
  466. }
  467. if opts.UpgradeRequest != nil {
  468. sc.upgradeRequest(opts.UpgradeRequest)
  469. opts.UpgradeRequest = nil
  470. }
  471. sc.serve()
  472. }
  473. func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func()) {
  474. ctx, cancel = context.WithCancel(opts.context())
  475. ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr())
  476. if hs := opts.baseConfig(); hs != nil {
  477. ctx = context.WithValue(ctx, http.ServerContextKey, hs)
  478. }
  479. return
  480. }
  481. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  482. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  483. // ignoring errors. hanging up anyway.
  484. sc.framer.WriteGoAway(0, err, []byte(debug))
  485. sc.bw.Flush()
  486. sc.conn.Close()
  487. }
  488. type serverConn struct {
  489. // Immutable:
  490. srv *Server
  491. hs *http.Server
  492. conn net.Conn
  493. bw *bufferedWriter // writing to conn
  494. handler http.Handler
  495. baseCtx context.Context
  496. framer *Framer
  497. doneServing chan struct{} // closed when serverConn.serve ends
  498. readFrameCh chan readFrameResult // written by serverConn.readFrames
  499. wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
  500. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  501. bodyReadCh chan bodyReadMsg // from handlers -> serve
  502. serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop
  503. flow outflow // conn-wide (not stream-specific) outbound flow control
  504. inflow inflow // conn-wide inbound flow control
  505. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  506. remoteAddrStr string
  507. writeSched WriteScheduler
  508. // Everything following is owned by the serve loop; use serveG.check():
  509. serveG goroutineLock // used to verify funcs are on serve()
  510. pushEnabled bool
  511. sawClientPreface bool // preface has already been read, used in h2c upgrade
  512. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  513. needToSendSettingsAck bool
  514. unackedSettings int // how many SETTINGS have we sent without ACKs?
  515. queuedControlFrames int // control frames in the writeSched queue
  516. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  517. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  518. curClientStreams uint32 // number of open streams initiated by the client
  519. curPushedStreams uint32 // number of open streams initiated by server push
  520. curHandlers uint32 // number of running handler goroutines
  521. maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests
  522. maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
  523. streams map[uint32]*stream
  524. unstartedHandlers []unstartedHandler
  525. initialStreamSendWindowSize int32
  526. maxFrameSize int32
  527. peerMaxHeaderListSize uint32 // zero means unknown (default)
  528. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  529. canonHeaderKeysSize int // canonHeader keys size in bytes
  530. writingFrame bool // started writing a frame (on serve goroutine or separate)
  531. writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
  532. needsFrameFlush bool // last frame write wasn't a flush
  533. inGoAway bool // we've started to or sent GOAWAY
  534. inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
  535. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  536. goAwayCode ErrCode
  537. shutdownTimer *time.Timer // nil until used
  538. idleTimer *time.Timer // nil if unused
  539. // Owned by the writeFrameAsync goroutine:
  540. headerWriteBuf bytes.Buffer
  541. hpackEncoder *hpack.Encoder
  542. // Used by startGracefulShutdown.
  543. shutdownOnce sync.Once
  544. }
  545. func (sc *serverConn) maxHeaderListSize() uint32 {
  546. n := sc.hs.MaxHeaderBytes
  547. if n <= 0 {
  548. n = http.DefaultMaxHeaderBytes
  549. }
  550. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  551. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  552. const perFieldOverhead = 32 // per http2 spec
  553. const typicalHeaders = 10 // conservative
  554. return uint32(n + typicalHeaders*perFieldOverhead)
  555. }
  556. func (sc *serverConn) curOpenStreams() uint32 {
  557. sc.serveG.check()
  558. return sc.curClientStreams + sc.curPushedStreams
  559. }
  560. // stream represents a stream. This is the minimal metadata needed by
  561. // the serve goroutine. Most of the actual stream state is owned by
  562. // the http.Handler's goroutine in the responseWriter. Because the
  563. // responseWriter's responseWriterState is recycled at the end of a
  564. // handler, this struct intentionally has no pointer to the
  565. // *responseWriter{,State} itself, as the Handler ending nils out the
  566. // responseWriter's state field.
  567. type stream struct {
  568. // immutable:
  569. sc *serverConn
  570. id uint32
  571. body *pipe // non-nil if expecting DATA frames
  572. cw closeWaiter // closed wait stream transitions to closed state
  573. ctx context.Context
  574. cancelCtx func()
  575. // owned by serverConn's serve loop:
  576. bodyBytes int64 // body bytes seen so far
  577. declBodyBytes int64 // or -1 if undeclared
  578. flow outflow // limits writing from Handler to client
  579. inflow inflow // what the client is allowed to POST/etc to us
  580. state streamState
  581. resetQueued bool // RST_STREAM queued for write; set by sc.resetStream
  582. gotTrailerHeader bool // HEADER frame for trailers was seen
  583. wroteHeaders bool // whether we wrote headers (not status 100)
  584. readDeadline *time.Timer // nil if unused
  585. writeDeadline *time.Timer // nil if unused
  586. closeErr error // set before cw is closed
  587. trailer http.Header // accumulated trailers
  588. reqTrailer http.Header // handler's Request.Trailer
  589. }
  590. func (sc *serverConn) Framer() *Framer { return sc.framer }
  591. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  592. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  593. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  594. return sc.hpackEncoder, &sc.headerWriteBuf
  595. }
  596. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  597. sc.serveG.check()
  598. // http://tools.ietf.org/html/rfc7540#section-5.1
  599. if st, ok := sc.streams[streamID]; ok {
  600. return st.state, st
  601. }
  602. // "The first use of a new stream identifier implicitly closes all
  603. // streams in the "idle" state that might have been initiated by
  604. // that peer with a lower-valued stream identifier. For example, if
  605. // a client sends a HEADERS frame on stream 7 without ever sending a
  606. // frame on stream 5, then stream 5 transitions to the "closed"
  607. // state when the first frame for stream 7 is sent or received."
  608. if streamID%2 == 1 {
  609. if streamID <= sc.maxClientStreamID {
  610. return stateClosed, nil
  611. }
  612. } else {
  613. if streamID <= sc.maxPushPromiseID {
  614. return stateClosed, nil
  615. }
  616. }
  617. return stateIdle, nil
  618. }
  619. // setConnState calls the net/http ConnState hook for this connection, if configured.
  620. // Note that the net/http package does StateNew and StateClosed for us.
  621. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  622. func (sc *serverConn) setConnState(state http.ConnState) {
  623. if sc.hs.ConnState != nil {
  624. sc.hs.ConnState(sc.conn, state)
  625. }
  626. }
  627. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  628. if VerboseLogs {
  629. sc.logf(format, args...)
  630. }
  631. }
  632. func (sc *serverConn) logf(format string, args ...interface{}) {
  633. if lg := sc.hs.ErrorLog; lg != nil {
  634. lg.Printf(format, args...)
  635. } else {
  636. log.Printf(format, args...)
  637. }
  638. }
  639. // errno returns v's underlying uintptr, else 0.
  640. //
  641. // TODO: remove this helper function once http2 can use build
  642. // tags. See comment in isClosedConnError.
  643. func errno(v error) uintptr {
  644. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  645. return uintptr(rv.Uint())
  646. }
  647. return 0
  648. }
  649. // isClosedConnError reports whether err is an error from use of a closed
  650. // network connection.
  651. func isClosedConnError(err error) bool {
  652. if err == nil {
  653. return false
  654. }
  655. // TODO: remove this string search and be more like the Windows
  656. // case below. That might involve modifying the standard library
  657. // to return better error types.
  658. str := err.Error()
  659. if strings.Contains(str, "use of closed network connection") {
  660. return true
  661. }
  662. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  663. // build tags, so I can't make an http2_windows.go file with
  664. // Windows-specific stuff. Fix that and move this, once we
  665. // have a way to bundle this into std's net/http somehow.
  666. if runtime.GOOS == "windows" {
  667. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  668. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  669. const WSAECONNABORTED = 10053
  670. const WSAECONNRESET = 10054
  671. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  672. return true
  673. }
  674. }
  675. }
  676. }
  677. return false
  678. }
  679. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  680. if err == nil {
  681. return
  682. }
  683. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout {
  684. // Boring, expected errors.
  685. sc.vlogf(format, args...)
  686. } else {
  687. sc.logf(format, args...)
  688. }
  689. }
  690. // maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
  691. // of the entries in the canonHeader cache.
  692. // This should be larger than the size of unique, uncommon header keys likely to
  693. // be sent by the peer, while not so high as to permit unreasonable memory usage
  694. // if the peer sends an unbounded number of unique header keys.
  695. const maxCachedCanonicalHeadersKeysSize = 2048
  696. func (sc *serverConn) canonicalHeader(v string) string {
  697. sc.serveG.check()
  698. buildCommonHeaderMapsOnce()
  699. cv, ok := commonCanonHeader[v]
  700. if ok {
  701. return cv
  702. }
  703. cv, ok = sc.canonHeader[v]
  704. if ok {
  705. return cv
  706. }
  707. if sc.canonHeader == nil {
  708. sc.canonHeader = make(map[string]string)
  709. }
  710. cv = http.CanonicalHeaderKey(v)
  711. size := 100 + len(v)*2 // 100 bytes of map overhead + key + value
  712. if sc.canonHeaderKeysSize+size <= maxCachedCanonicalHeadersKeysSize {
  713. sc.canonHeader[v] = cv
  714. sc.canonHeaderKeysSize += size
  715. }
  716. return cv
  717. }
  718. type readFrameResult struct {
  719. f Frame // valid until readMore is called
  720. err error
  721. // readMore should be called once the consumer no longer needs or
  722. // retains f. After readMore, f is invalid and more frames can be
  723. // read.
  724. readMore func()
  725. }
  726. // readFrames is the loop that reads incoming frames.
  727. // It takes care to only read one frame at a time, blocking until the
  728. // consumer is done with the frame.
  729. // It's run on its own goroutine.
  730. func (sc *serverConn) readFrames() {
  731. gate := make(gate)
  732. gateDone := gate.Done
  733. for {
  734. f, err := sc.framer.ReadFrame()
  735. select {
  736. case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
  737. case <-sc.doneServing:
  738. return
  739. }
  740. select {
  741. case <-gate:
  742. case <-sc.doneServing:
  743. return
  744. }
  745. if terminalReadFrameError(err) {
  746. return
  747. }
  748. }
  749. }
  750. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  751. type frameWriteResult struct {
  752. _ incomparable
  753. wr FrameWriteRequest // what was written (or attempted)
  754. err error // result of the writeFrame call
  755. }
  756. // writeFrameAsync runs in its own goroutine and writes a single frame
  757. // and then reports when it's done.
  758. // At most one goroutine can be running writeFrameAsync at a time per
  759. // serverConn.
  760. func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest, wd *writeData) {
  761. var err error
  762. if wd == nil {
  763. err = wr.write.writeFrame(sc)
  764. } else {
  765. err = sc.framer.endWrite()
  766. }
  767. sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err}
  768. }
  769. func (sc *serverConn) closeAllStreamsOnConnClose() {
  770. sc.serveG.check()
  771. for _, st := range sc.streams {
  772. sc.closeStream(st, errClientDisconnected)
  773. }
  774. }
  775. func (sc *serverConn) stopShutdownTimer() {
  776. sc.serveG.check()
  777. if t := sc.shutdownTimer; t != nil {
  778. t.Stop()
  779. }
  780. }
  781. func (sc *serverConn) notePanic() {
  782. // Note: this is for serverConn.serve panicking, not http.Handler code.
  783. if testHookOnPanicMu != nil {
  784. testHookOnPanicMu.Lock()
  785. defer testHookOnPanicMu.Unlock()
  786. }
  787. if testHookOnPanic != nil {
  788. if e := recover(); e != nil {
  789. if testHookOnPanic(sc, e) {
  790. panic(e)
  791. }
  792. }
  793. }
  794. }
  795. func (sc *serverConn) serve() {
  796. sc.serveG.check()
  797. defer sc.notePanic()
  798. defer sc.conn.Close()
  799. defer sc.closeAllStreamsOnConnClose()
  800. defer sc.stopShutdownTimer()
  801. defer close(sc.doneServing) // unblocks handlers trying to send
  802. if VerboseLogs {
  803. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  804. }
  805. sc.writeFrame(FrameWriteRequest{
  806. write: writeSettings{
  807. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  808. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  809. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  810. {SettingHeaderTableSize, sc.srv.maxDecoderHeaderTableSize()},
  811. {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
  812. },
  813. })
  814. sc.unackedSettings++
  815. // Each connection starts with initialWindowSize inflow tokens.
  816. // If a higher value is configured, we add more tokens.
  817. if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 {
  818. sc.sendWindowUpdate(nil, int(diff))
  819. }
  820. if err := sc.readPreface(); err != nil {
  821. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  822. return
  823. }
  824. // Now that we've got the preface, get us out of the
  825. // "StateNew" state. We can't go directly to idle, though.
  826. // Active means we read some data and anticipate a request. We'll
  827. // do another Active when we get a HEADERS frame.
  828. sc.setConnState(http.StateActive)
  829. sc.setConnState(http.StateIdle)
  830. if sc.srv.IdleTimeout > 0 {
  831. sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
  832. defer sc.idleTimer.Stop()
  833. }
  834. go sc.readFrames() // closed by defer sc.conn.Close above
  835. settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
  836. defer settingsTimer.Stop()
  837. loopNum := 0
  838. for {
  839. loopNum++
  840. select {
  841. case wr := <-sc.wantWriteFrameCh:
  842. if se, ok := wr.write.(StreamError); ok {
  843. sc.resetStream(se)
  844. break
  845. }
  846. sc.writeFrame(wr)
  847. case res := <-sc.wroteFrameCh:
  848. sc.wroteFrame(res)
  849. case res := <-sc.readFrameCh:
  850. // Process any written frames before reading new frames from the client since a
  851. // written frame could have triggered a new stream to be started.
  852. if sc.writingFrameAsync {
  853. select {
  854. case wroteRes := <-sc.wroteFrameCh:
  855. sc.wroteFrame(wroteRes)
  856. default:
  857. }
  858. }
  859. if !sc.processFrameFromReader(res) {
  860. return
  861. }
  862. res.readMore()
  863. if settingsTimer != nil {
  864. settingsTimer.Stop()
  865. settingsTimer = nil
  866. }
  867. case m := <-sc.bodyReadCh:
  868. sc.noteBodyRead(m.st, m.n)
  869. case msg := <-sc.serveMsgCh:
  870. switch v := msg.(type) {
  871. case func(int):
  872. v(loopNum) // for testing
  873. case *serverMessage:
  874. switch v {
  875. case settingsTimerMsg:
  876. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  877. return
  878. case idleTimerMsg:
  879. sc.vlogf("connection is idle")
  880. sc.goAway(ErrCodeNo)
  881. case shutdownTimerMsg:
  882. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  883. return
  884. case gracefulShutdownMsg:
  885. sc.startGracefulShutdownInternal()
  886. case handlerDoneMsg:
  887. sc.handlerDone()
  888. default:
  889. panic("unknown timer")
  890. }
  891. case *startPushRequest:
  892. sc.startPush(v)
  893. case func(*serverConn):
  894. v(sc)
  895. default:
  896. panic(fmt.Sprintf("unexpected type %T", v))
  897. }
  898. }
  899. // If the peer is causing us to generate a lot of control frames,
  900. // but not reading them from us, assume they are trying to make us
  901. // run out of memory.
  902. if sc.queuedControlFrames > sc.srv.maxQueuedControlFrames() {
  903. sc.vlogf("http2: too many control frames in send queue, closing connection")
  904. return
  905. }
  906. // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
  907. // with no error code (graceful shutdown), don't start the timer until
  908. // all open streams have been completed.
  909. sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
  910. gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
  911. if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
  912. sc.shutDownIn(goAwayTimeout)
  913. }
  914. }
  915. }
  916. type serverMessage int
  917. // Message values sent to serveMsgCh.
  918. var (
  919. settingsTimerMsg = new(serverMessage)
  920. idleTimerMsg = new(serverMessage)
  921. shutdownTimerMsg = new(serverMessage)
  922. gracefulShutdownMsg = new(serverMessage)
  923. handlerDoneMsg = new(serverMessage)
  924. )
  925. func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
  926. func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) }
  927. func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
  928. func (sc *serverConn) sendServeMsg(msg interface{}) {
  929. sc.serveG.checkNotOn() // NOT
  930. select {
  931. case sc.serveMsgCh <- msg:
  932. case <-sc.doneServing:
  933. }
  934. }
  935. var errPrefaceTimeout = errors.New("timeout waiting for client preface")
  936. // readPreface reads the ClientPreface greeting from the peer or
  937. // returns errPrefaceTimeout on timeout, or an error if the greeting
  938. // is invalid.
  939. func (sc *serverConn) readPreface() error {
  940. if sc.sawClientPreface {
  941. return nil
  942. }
  943. errc := make(chan error, 1)
  944. go func() {
  945. // Read the client preface
  946. buf := make([]byte, len(ClientPreface))
  947. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  948. errc <- err
  949. } else if !bytes.Equal(buf, clientPreface) {
  950. errc <- fmt.Errorf("bogus greeting %q", buf)
  951. } else {
  952. errc <- nil
  953. }
  954. }()
  955. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  956. defer timer.Stop()
  957. select {
  958. case <-timer.C:
  959. return errPrefaceTimeout
  960. case err := <-errc:
  961. if err == nil {
  962. if VerboseLogs {
  963. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  964. }
  965. }
  966. return err
  967. }
  968. }
  969. var errChanPool = sync.Pool{
  970. New: func() interface{} { return make(chan error, 1) },
  971. }
  972. var writeDataPool = sync.Pool{
  973. New: func() interface{} { return new(writeData) },
  974. }
  975. // writeDataFromHandler writes DATA response frames from a handler on
  976. // the given stream.
  977. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  978. ch := errChanPool.Get().(chan error)
  979. writeArg := writeDataPool.Get().(*writeData)
  980. *writeArg = writeData{stream.id, data, endStream}
  981. err := sc.writeFrameFromHandler(FrameWriteRequest{
  982. write: writeArg,
  983. stream: stream,
  984. done: ch,
  985. })
  986. if err != nil {
  987. return err
  988. }
  989. var frameWriteDone bool // the frame write is done (successfully or not)
  990. select {
  991. case err = <-ch:
  992. frameWriteDone = true
  993. case <-sc.doneServing:
  994. return errClientDisconnected
  995. case <-stream.cw:
  996. // If both ch and stream.cw were ready (as might
  997. // happen on the final Write after an http.Handler
  998. // ends), prefer the write result. Otherwise this
  999. // might just be us successfully closing the stream.
  1000. // The writeFrameAsync and serve goroutines guarantee
  1001. // that the ch send will happen before the stream.cw
  1002. // close.
  1003. select {
  1004. case err = <-ch:
  1005. frameWriteDone = true
  1006. default:
  1007. return errStreamClosed
  1008. }
  1009. }
  1010. errChanPool.Put(ch)
  1011. if frameWriteDone {
  1012. writeDataPool.Put(writeArg)
  1013. }
  1014. return err
  1015. }
  1016. // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
  1017. // if the connection has gone away.
  1018. //
  1019. // This must not be run from the serve goroutine itself, else it might
  1020. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  1021. // buffered and is read by serve itself). If you're on the serve
  1022. // goroutine, call writeFrame instead.
  1023. func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
  1024. sc.serveG.checkNotOn() // NOT
  1025. select {
  1026. case sc.wantWriteFrameCh <- wr:
  1027. return nil
  1028. case <-sc.doneServing:
  1029. // Serve loop is gone.
  1030. // Client has closed their connection to the server.
  1031. return errClientDisconnected
  1032. }
  1033. }
  1034. // writeFrame schedules a frame to write and sends it if there's nothing
  1035. // already being written.
  1036. //
  1037. // There is no pushback here (the serve goroutine never blocks). It's
  1038. // the http.Handlers that block, waiting for their previous frames to
  1039. // make it onto the wire
  1040. //
  1041. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  1042. func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
  1043. sc.serveG.check()
  1044. // If true, wr will not be written and wr.done will not be signaled.
  1045. var ignoreWrite bool
  1046. // We are not allowed to write frames on closed streams. RFC 7540 Section
  1047. // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
  1048. // a closed stream." Our server never sends PRIORITY, so that exception
  1049. // does not apply.
  1050. //
  1051. // The serverConn might close an open stream while the stream's handler
  1052. // is still running. For example, the server might close a stream when it
  1053. // receives bad data from the client. If this happens, the handler might
  1054. // attempt to write a frame after the stream has been closed (since the
  1055. // handler hasn't yet been notified of the close). In this case, we simply
  1056. // ignore the frame. The handler will notice that the stream is closed when
  1057. // it waits for the frame to be written.
  1058. //
  1059. // As an exception to this rule, we allow sending RST_STREAM after close.
  1060. // This allows us to immediately reject new streams without tracking any
  1061. // state for those streams (except for the queued RST_STREAM frame). This
  1062. // may result in duplicate RST_STREAMs in some cases, but the client should
  1063. // ignore those.
  1064. if wr.StreamID() != 0 {
  1065. _, isReset := wr.write.(StreamError)
  1066. if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
  1067. ignoreWrite = true
  1068. }
  1069. }
  1070. // Don't send a 100-continue response if we've already sent headers.
  1071. // See golang.org/issue/14030.
  1072. switch wr.write.(type) {
  1073. case *writeResHeaders:
  1074. wr.stream.wroteHeaders = true
  1075. case write100ContinueHeadersFrame:
  1076. if wr.stream.wroteHeaders {
  1077. // We do not need to notify wr.done because this frame is
  1078. // never written with wr.done != nil.
  1079. if wr.done != nil {
  1080. panic("wr.done != nil for write100ContinueHeadersFrame")
  1081. }
  1082. ignoreWrite = true
  1083. }
  1084. }
  1085. if !ignoreWrite {
  1086. if wr.isControl() {
  1087. sc.queuedControlFrames++
  1088. // For extra safety, detect wraparounds, which should not happen,
  1089. // and pull the plug.
  1090. if sc.queuedControlFrames < 0 {
  1091. sc.conn.Close()
  1092. }
  1093. }
  1094. sc.writeSched.Push(wr)
  1095. }
  1096. sc.scheduleFrameWrite()
  1097. }
  1098. // startFrameWrite starts a goroutine to write wr (in a separate
  1099. // goroutine since that might block on the network), and updates the
  1100. // serve goroutine's state about the world, updated from info in wr.
  1101. func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
  1102. sc.serveG.check()
  1103. if sc.writingFrame {
  1104. panic("internal error: can only be writing one frame at a time")
  1105. }
  1106. st := wr.stream
  1107. if st != nil {
  1108. switch st.state {
  1109. case stateHalfClosedLocal:
  1110. switch wr.write.(type) {
  1111. case StreamError, handlerPanicRST, writeWindowUpdate:
  1112. // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
  1113. // in this state. (We never send PRIORITY from the server, so that is not checked.)
  1114. default:
  1115. panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
  1116. }
  1117. case stateClosed:
  1118. panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
  1119. }
  1120. }
  1121. if wpp, ok := wr.write.(*writePushPromise); ok {
  1122. var err error
  1123. wpp.promisedID, err = wpp.allocatePromisedID()
  1124. if err != nil {
  1125. sc.writingFrameAsync = false
  1126. wr.replyToWriter(err)
  1127. return
  1128. }
  1129. }
  1130. sc.writingFrame = true
  1131. sc.needsFrameFlush = true
  1132. if wr.write.staysWithinBuffer(sc.bw.Available()) {
  1133. sc.writingFrameAsync = false
  1134. err := wr.write.writeFrame(sc)
  1135. sc.wroteFrame(frameWriteResult{wr: wr, err: err})
  1136. } else if wd, ok := wr.write.(*writeData); ok {
  1137. // Encode the frame in the serve goroutine, to ensure we don't have
  1138. // any lingering asynchronous references to data passed to Write.
  1139. // See https://go.dev/issue/58446.
  1140. sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
  1141. sc.writingFrameAsync = true
  1142. go sc.writeFrameAsync(wr, wd)
  1143. } else {
  1144. sc.writingFrameAsync = true
  1145. go sc.writeFrameAsync(wr, nil)
  1146. }
  1147. }
  1148. // errHandlerPanicked is the error given to any callers blocked in a read from
  1149. // Request.Body when the main goroutine panics. Since most handlers read in the
  1150. // main ServeHTTP goroutine, this will show up rarely.
  1151. var errHandlerPanicked = errors.New("http2: handler panicked")
  1152. // wroteFrame is called on the serve goroutine with the result of
  1153. // whatever happened on writeFrameAsync.
  1154. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  1155. sc.serveG.check()
  1156. if !sc.writingFrame {
  1157. panic("internal error: expected to be already writing a frame")
  1158. }
  1159. sc.writingFrame = false
  1160. sc.writingFrameAsync = false
  1161. wr := res.wr
  1162. if writeEndsStream(wr.write) {
  1163. st := wr.stream
  1164. if st == nil {
  1165. panic("internal error: expecting non-nil stream")
  1166. }
  1167. switch st.state {
  1168. case stateOpen:
  1169. // Here we would go to stateHalfClosedLocal in
  1170. // theory, but since our handler is done and
  1171. // the net/http package provides no mechanism
  1172. // for closing a ResponseWriter while still
  1173. // reading data (see possible TODO at top of
  1174. // this file), we go into closed state here
  1175. // anyway, after telling the peer we're
  1176. // hanging up on them. We'll transition to
  1177. // stateClosed after the RST_STREAM frame is
  1178. // written.
  1179. st.state = stateHalfClosedLocal
  1180. // Section 8.1: a server MAY request that the client abort
  1181. // transmission of a request without error by sending a
  1182. // RST_STREAM with an error code of NO_ERROR after sending
  1183. // a complete response.
  1184. sc.resetStream(streamError(st.id, ErrCodeNo))
  1185. case stateHalfClosedRemote:
  1186. sc.closeStream(st, errHandlerComplete)
  1187. }
  1188. } else {
  1189. switch v := wr.write.(type) {
  1190. case StreamError:
  1191. // st may be unknown if the RST_STREAM was generated to reject bad input.
  1192. if st, ok := sc.streams[v.StreamID]; ok {
  1193. sc.closeStream(st, v)
  1194. }
  1195. case handlerPanicRST:
  1196. sc.closeStream(wr.stream, errHandlerPanicked)
  1197. }
  1198. }
  1199. // Reply (if requested) to unblock the ServeHTTP goroutine.
  1200. wr.replyToWriter(res.err)
  1201. sc.scheduleFrameWrite()
  1202. }
  1203. // scheduleFrameWrite tickles the frame writing scheduler.
  1204. //
  1205. // If a frame is already being written, nothing happens. This will be called again
  1206. // when the frame is done being written.
  1207. //
  1208. // If a frame isn't being written and we need to send one, the best frame
  1209. // to send is selected by writeSched.
  1210. //
  1211. // If a frame isn't being written and there's nothing else to send, we
  1212. // flush the write buffer.
  1213. func (sc *serverConn) scheduleFrameWrite() {
  1214. sc.serveG.check()
  1215. if sc.writingFrame || sc.inFrameScheduleLoop {
  1216. return
  1217. }
  1218. sc.inFrameScheduleLoop = true
  1219. for !sc.writingFrameAsync {
  1220. if sc.needToSendGoAway {
  1221. sc.needToSendGoAway = false
  1222. sc.startFrameWrite(FrameWriteRequest{
  1223. write: &writeGoAway{
  1224. maxStreamID: sc.maxClientStreamID,
  1225. code: sc.goAwayCode,
  1226. },
  1227. })
  1228. continue
  1229. }
  1230. if sc.needToSendSettingsAck {
  1231. sc.needToSendSettingsAck = false
  1232. sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  1233. continue
  1234. }
  1235. if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
  1236. if wr, ok := sc.writeSched.Pop(); ok {
  1237. if wr.isControl() {
  1238. sc.queuedControlFrames--
  1239. }
  1240. sc.startFrameWrite(wr)
  1241. continue
  1242. }
  1243. }
  1244. if sc.needsFrameFlush {
  1245. sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  1246. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  1247. continue
  1248. }
  1249. break
  1250. }
  1251. sc.inFrameScheduleLoop = false
  1252. }
  1253. // startGracefulShutdown gracefully shuts down a connection. This
  1254. // sends GOAWAY with ErrCodeNo to tell the client we're gracefully
  1255. // shutting down. The connection isn't closed until all current
  1256. // streams are done.
  1257. //
  1258. // startGracefulShutdown returns immediately; it does not wait until
  1259. // the connection has shut down.
  1260. func (sc *serverConn) startGracefulShutdown() {
  1261. sc.serveG.checkNotOn() // NOT
  1262. sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
  1263. }
  1264. // After sending GOAWAY with an error code (non-graceful shutdown), the
  1265. // connection will close after goAwayTimeout.
  1266. //
  1267. // If we close the connection immediately after sending GOAWAY, there may
  1268. // be unsent data in our kernel receive buffer, which will cause the kernel
  1269. // to send a TCP RST on close() instead of a FIN. This RST will abort the
  1270. // connection immediately, whether or not the client had received the GOAWAY.
  1271. //
  1272. // Ideally we should delay for at least 1 RTT + epsilon so the client has
  1273. // a chance to read the GOAWAY and stop sending messages. Measuring RTT
  1274. // is hard, so we approximate with 1 second. See golang.org/issue/18701.
  1275. //
  1276. // This is a var so it can be shorter in tests, where all requests uses the
  1277. // loopback interface making the expected RTT very small.
  1278. //
  1279. // TODO: configurable?
  1280. var goAwayTimeout = 1 * time.Second
  1281. func (sc *serverConn) startGracefulShutdownInternal() {
  1282. sc.goAway(ErrCodeNo)
  1283. }
  1284. func (sc *serverConn) goAway(code ErrCode) {
  1285. sc.serveG.check()
  1286. if sc.inGoAway {
  1287. if sc.goAwayCode == ErrCodeNo {
  1288. sc.goAwayCode = code
  1289. }
  1290. return
  1291. }
  1292. sc.inGoAway = true
  1293. sc.needToSendGoAway = true
  1294. sc.goAwayCode = code
  1295. sc.scheduleFrameWrite()
  1296. }
  1297. func (sc *serverConn) shutDownIn(d time.Duration) {
  1298. sc.serveG.check()
  1299. sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
  1300. }
  1301. func (sc *serverConn) resetStream(se StreamError) {
  1302. sc.serveG.check()
  1303. sc.writeFrame(FrameWriteRequest{write: se})
  1304. if st, ok := sc.streams[se.StreamID]; ok {
  1305. st.resetQueued = true
  1306. }
  1307. }
  1308. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  1309. // frame-reading goroutine.
  1310. // processFrameFromReader returns whether the connection should be kept open.
  1311. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  1312. sc.serveG.check()
  1313. err := res.err
  1314. if err != nil {
  1315. if err == ErrFrameTooLarge {
  1316. sc.goAway(ErrCodeFrameSize)
  1317. return true // goAway will close the loop
  1318. }
  1319. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  1320. if clientGone {
  1321. // TODO: could we also get into this state if
  1322. // the peer does a half close
  1323. // (e.g. CloseWrite) because they're done
  1324. // sending frames but they're still wanting
  1325. // our open replies? Investigate.
  1326. // TODO: add CloseWrite to crypto/tls.Conn first
  1327. // so we have a way to test this? I suppose
  1328. // just for testing we could have a non-TLS mode.
  1329. return false
  1330. }
  1331. } else {
  1332. f := res.f
  1333. if VerboseLogs {
  1334. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1335. }
  1336. err = sc.processFrame(f)
  1337. if err == nil {
  1338. return true
  1339. }
  1340. }
  1341. switch ev := err.(type) {
  1342. case StreamError:
  1343. sc.resetStream(ev)
  1344. return true
  1345. case goAwayFlowError:
  1346. sc.goAway(ErrCodeFlowControl)
  1347. return true
  1348. case ConnectionError:
  1349. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1350. sc.goAway(ErrCode(ev))
  1351. return true // goAway will handle shutdown
  1352. default:
  1353. if res.err != nil {
  1354. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1355. } else {
  1356. sc.logf("http2: server closing client connection: %v", err)
  1357. }
  1358. return false
  1359. }
  1360. }
  1361. func (sc *serverConn) processFrame(f Frame) error {
  1362. sc.serveG.check()
  1363. // First frame received must be SETTINGS.
  1364. if !sc.sawFirstSettings {
  1365. if _, ok := f.(*SettingsFrame); !ok {
  1366. return sc.countError("first_settings", ConnectionError(ErrCodeProtocol))
  1367. }
  1368. sc.sawFirstSettings = true
  1369. }
  1370. // Discard frames for streams initiated after the identified last
  1371. // stream sent in a GOAWAY, or all frames after sending an error.
  1372. // We still need to return connection-level flow control for DATA frames.
  1373. // RFC 9113 Section 6.8.
  1374. if sc.inGoAway && (sc.goAwayCode != ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
  1375. if f, ok := f.(*DataFrame); ok {
  1376. if !sc.inflow.take(f.Length) {
  1377. return sc.countError("data_flow", streamError(f.Header().StreamID, ErrCodeFlowControl))
  1378. }
  1379. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1380. }
  1381. return nil
  1382. }
  1383. switch f := f.(type) {
  1384. case *SettingsFrame:
  1385. return sc.processSettings(f)
  1386. case *MetaHeadersFrame:
  1387. return sc.processHeaders(f)
  1388. case *WindowUpdateFrame:
  1389. return sc.processWindowUpdate(f)
  1390. case *PingFrame:
  1391. return sc.processPing(f)
  1392. case *DataFrame:
  1393. return sc.processData(f)
  1394. case *RSTStreamFrame:
  1395. return sc.processResetStream(f)
  1396. case *PriorityFrame:
  1397. return sc.processPriority(f)
  1398. case *GoAwayFrame:
  1399. return sc.processGoAway(f)
  1400. case *PushPromiseFrame:
  1401. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1402. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1403. return sc.countError("push_promise", ConnectionError(ErrCodeProtocol))
  1404. default:
  1405. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1406. return nil
  1407. }
  1408. }
  1409. func (sc *serverConn) processPing(f *PingFrame) error {
  1410. sc.serveG.check()
  1411. if f.IsAck() {
  1412. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1413. // containing this flag."
  1414. return nil
  1415. }
  1416. if f.StreamID != 0 {
  1417. // "PING frames are not associated with any individual
  1418. // stream. If a PING frame is received with a stream
  1419. // identifier field value other than 0x0, the recipient MUST
  1420. // respond with a connection error (Section 5.4.1) of type
  1421. // PROTOCOL_ERROR."
  1422. return sc.countError("ping_on_stream", ConnectionError(ErrCodeProtocol))
  1423. }
  1424. sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1425. return nil
  1426. }
  1427. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1428. sc.serveG.check()
  1429. switch {
  1430. case f.StreamID != 0: // stream-level flow control
  1431. state, st := sc.state(f.StreamID)
  1432. if state == stateIdle {
  1433. // Section 5.1: "Receiving any frame other than HEADERS
  1434. // or PRIORITY on a stream in this state MUST be
  1435. // treated as a connection error (Section 5.4.1) of
  1436. // type PROTOCOL_ERROR."
  1437. return sc.countError("stream_idle", ConnectionError(ErrCodeProtocol))
  1438. }
  1439. if st == nil {
  1440. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1441. // frame bearing the END_STREAM flag. This means that a
  1442. // receiver could receive a WINDOW_UPDATE frame on a "half
  1443. // closed (remote)" or "closed" stream. A receiver MUST
  1444. // NOT treat this as an error, see Section 5.1."
  1445. return nil
  1446. }
  1447. if !st.flow.add(int32(f.Increment)) {
  1448. return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl))
  1449. }
  1450. default: // connection-level flow control
  1451. if !sc.flow.add(int32(f.Increment)) {
  1452. return goAwayFlowError{}
  1453. }
  1454. }
  1455. sc.scheduleFrameWrite()
  1456. return nil
  1457. }
  1458. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1459. sc.serveG.check()
  1460. state, st := sc.state(f.StreamID)
  1461. if state == stateIdle {
  1462. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1463. // stream in the "idle" state. If a RST_STREAM frame
  1464. // identifying an idle stream is received, the
  1465. // recipient MUST treat this as a connection error
  1466. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1467. return sc.countError("reset_idle_stream", ConnectionError(ErrCodeProtocol))
  1468. }
  1469. if st != nil {
  1470. st.cancelCtx()
  1471. sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1472. }
  1473. return nil
  1474. }
  1475. func (sc *serverConn) closeStream(st *stream, err error) {
  1476. sc.serveG.check()
  1477. if st.state == stateIdle || st.state == stateClosed {
  1478. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1479. }
  1480. st.state = stateClosed
  1481. if st.readDeadline != nil {
  1482. st.readDeadline.Stop()
  1483. }
  1484. if st.writeDeadline != nil {
  1485. st.writeDeadline.Stop()
  1486. }
  1487. if st.isPushed() {
  1488. sc.curPushedStreams--
  1489. } else {
  1490. sc.curClientStreams--
  1491. }
  1492. delete(sc.streams, st.id)
  1493. if len(sc.streams) == 0 {
  1494. sc.setConnState(http.StateIdle)
  1495. if sc.srv.IdleTimeout > 0 {
  1496. sc.idleTimer.Reset(sc.srv.IdleTimeout)
  1497. }
  1498. if h1ServerKeepAlivesDisabled(sc.hs) {
  1499. sc.startGracefulShutdownInternal()
  1500. }
  1501. }
  1502. if p := st.body; p != nil {
  1503. // Return any buffered unread bytes worth of conn-level flow control.
  1504. // See golang.org/issue/16481
  1505. sc.sendWindowUpdate(nil, p.Len())
  1506. p.CloseWithError(err)
  1507. }
  1508. if e, ok := err.(StreamError); ok {
  1509. if e.Cause != nil {
  1510. err = e.Cause
  1511. } else {
  1512. err = errStreamClosed
  1513. }
  1514. }
  1515. st.closeErr = err
  1516. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1517. sc.writeSched.CloseStream(st.id)
  1518. }
  1519. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1520. sc.serveG.check()
  1521. if f.IsAck() {
  1522. sc.unackedSettings--
  1523. if sc.unackedSettings < 0 {
  1524. // Why is the peer ACKing settings we never sent?
  1525. // The spec doesn't mention this case, but
  1526. // hang up on them anyway.
  1527. return sc.countError("ack_mystery", ConnectionError(ErrCodeProtocol))
  1528. }
  1529. return nil
  1530. }
  1531. if f.NumSettings() > 100 || f.HasDuplicates() {
  1532. // This isn't actually in the spec, but hang up on
  1533. // suspiciously large settings frames or those with
  1534. // duplicate entries.
  1535. return sc.countError("settings_big_or_dups", ConnectionError(ErrCodeProtocol))
  1536. }
  1537. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1538. return err
  1539. }
  1540. // TODO: judging by RFC 7540, Section 6.5.3 each SETTINGS frame should be
  1541. // acknowledged individually, even if multiple are received before the ACK.
  1542. sc.needToSendSettingsAck = true
  1543. sc.scheduleFrameWrite()
  1544. return nil
  1545. }
  1546. func (sc *serverConn) processSetting(s Setting) error {
  1547. sc.serveG.check()
  1548. if err := s.Valid(); err != nil {
  1549. return err
  1550. }
  1551. if VerboseLogs {
  1552. sc.vlogf("http2: server processing setting %v", s)
  1553. }
  1554. switch s.ID {
  1555. case SettingHeaderTableSize:
  1556. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1557. case SettingEnablePush:
  1558. sc.pushEnabled = s.Val != 0
  1559. case SettingMaxConcurrentStreams:
  1560. sc.clientMaxStreams = s.Val
  1561. case SettingInitialWindowSize:
  1562. return sc.processSettingInitialWindowSize(s.Val)
  1563. case SettingMaxFrameSize:
  1564. sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1565. case SettingMaxHeaderListSize:
  1566. sc.peerMaxHeaderListSize = s.Val
  1567. default:
  1568. // Unknown setting: "An endpoint that receives a SETTINGS
  1569. // frame with any unknown or unsupported identifier MUST
  1570. // ignore that setting."
  1571. if VerboseLogs {
  1572. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1573. }
  1574. }
  1575. return nil
  1576. }
  1577. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1578. sc.serveG.check()
  1579. // Note: val already validated to be within range by
  1580. // processSetting's Valid call.
  1581. // "A SETTINGS frame can alter the initial flow control window
  1582. // size for all current streams. When the value of
  1583. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1584. // adjust the size of all stream flow control windows that it
  1585. // maintains by the difference between the new value and the
  1586. // old value."
  1587. old := sc.initialStreamSendWindowSize
  1588. sc.initialStreamSendWindowSize = int32(val)
  1589. growth := int32(val) - old // may be negative
  1590. for _, st := range sc.streams {
  1591. if !st.flow.add(growth) {
  1592. // 6.9.2 Initial Flow Control Window Size
  1593. // "An endpoint MUST treat a change to
  1594. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1595. // control window to exceed the maximum size as a
  1596. // connection error (Section 5.4.1) of type
  1597. // FLOW_CONTROL_ERROR."
  1598. return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
  1599. }
  1600. }
  1601. return nil
  1602. }
  1603. func (sc *serverConn) processData(f *DataFrame) error {
  1604. sc.serveG.check()
  1605. id := f.Header().StreamID
  1606. data := f.Data()
  1607. state, st := sc.state(id)
  1608. if id == 0 || state == stateIdle {
  1609. // Section 6.1: "DATA frames MUST be associated with a
  1610. // stream. If a DATA frame is received whose stream
  1611. // identifier field is 0x0, the recipient MUST respond
  1612. // with a connection error (Section 5.4.1) of type
  1613. // PROTOCOL_ERROR."
  1614. //
  1615. // Section 5.1: "Receiving any frame other than HEADERS
  1616. // or PRIORITY on a stream in this state MUST be
  1617. // treated as a connection error (Section 5.4.1) of
  1618. // type PROTOCOL_ERROR."
  1619. return sc.countError("data_on_idle", ConnectionError(ErrCodeProtocol))
  1620. }
  1621. // "If a DATA frame is received whose stream is not in "open"
  1622. // or "half closed (local)" state, the recipient MUST respond
  1623. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1624. if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
  1625. // This includes sending a RST_STREAM if the stream is
  1626. // in stateHalfClosedLocal (which currently means that
  1627. // the http.Handler returned, so it's done reading &
  1628. // done writing). Try to stop the client from sending
  1629. // more DATA.
  1630. // But still enforce their connection-level flow control,
  1631. // and return any flow control bytes since we're not going
  1632. // to consume them.
  1633. if !sc.inflow.take(f.Length) {
  1634. return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
  1635. }
  1636. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1637. if st != nil && st.resetQueued {
  1638. // Already have a stream error in flight. Don't send another.
  1639. return nil
  1640. }
  1641. return sc.countError("closed", streamError(id, ErrCodeStreamClosed))
  1642. }
  1643. if st.body == nil {
  1644. panic("internal error: should have a body in this state")
  1645. }
  1646. // Sender sending more than they'd declared?
  1647. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1648. if !sc.inflow.take(f.Length) {
  1649. return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
  1650. }
  1651. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1652. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1653. // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the
  1654. // value of a content-length header field does not equal the sum of the
  1655. // DATA frame payload lengths that form the body.
  1656. return sc.countError("send_too_much", streamError(id, ErrCodeProtocol))
  1657. }
  1658. if f.Length > 0 {
  1659. // Check whether the client has flow control quota.
  1660. if !takeInflows(&sc.inflow, &st.inflow, f.Length) {
  1661. return sc.countError("flow_on_data_length", streamError(id, ErrCodeFlowControl))
  1662. }
  1663. if len(data) > 0 {
  1664. st.bodyBytes += int64(len(data))
  1665. wrote, err := st.body.Write(data)
  1666. if err != nil {
  1667. // The handler has closed the request body.
  1668. // Return the connection-level flow control for the discarded data,
  1669. // but not the stream-level flow control.
  1670. sc.sendWindowUpdate(nil, int(f.Length)-wrote)
  1671. return nil
  1672. }
  1673. if wrote != len(data) {
  1674. panic("internal error: bad Writer")
  1675. }
  1676. }
  1677. // Return any padded flow control now, since we won't
  1678. // refund it later on body reads.
  1679. // Call sendWindowUpdate even if there is no padding,
  1680. // to return buffered flow control credit if the sent
  1681. // window has shrunk.
  1682. pad := int32(f.Length) - int32(len(data))
  1683. sc.sendWindowUpdate32(nil, pad)
  1684. sc.sendWindowUpdate32(st, pad)
  1685. }
  1686. if f.StreamEnded() {
  1687. st.endStream()
  1688. }
  1689. return nil
  1690. }
  1691. func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
  1692. sc.serveG.check()
  1693. if f.ErrCode != ErrCodeNo {
  1694. sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1695. } else {
  1696. sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1697. }
  1698. sc.startGracefulShutdownInternal()
  1699. // http://tools.ietf.org/html/rfc7540#section-6.8
  1700. // We should not create any new streams, which means we should disable push.
  1701. sc.pushEnabled = false
  1702. return nil
  1703. }
  1704. // isPushed reports whether the stream is server-initiated.
  1705. func (st *stream) isPushed() bool {
  1706. return st.id%2 == 0
  1707. }
  1708. // endStream closes a Request.Body's pipe. It is called when a DATA
  1709. // frame says a request body is over (or after trailers).
  1710. func (st *stream) endStream() {
  1711. sc := st.sc
  1712. sc.serveG.check()
  1713. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1714. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1715. st.declBodyBytes, st.bodyBytes))
  1716. } else {
  1717. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1718. st.body.CloseWithError(io.EOF)
  1719. }
  1720. st.state = stateHalfClosedRemote
  1721. }
  1722. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1723. // its Request.Body.Read just before it gets io.EOF.
  1724. func (st *stream) copyTrailersToHandlerRequest() {
  1725. for k, vv := range st.trailer {
  1726. if _, ok := st.reqTrailer[k]; ok {
  1727. // Only copy it over it was pre-declared.
  1728. st.reqTrailer[k] = vv
  1729. }
  1730. }
  1731. }
  1732. // onReadTimeout is run on its own goroutine (from time.AfterFunc)
  1733. // when the stream's ReadTimeout has fired.
  1734. func (st *stream) onReadTimeout() {
  1735. if st.body != nil {
  1736. // Wrap the ErrDeadlineExceeded to avoid callers depending on us
  1737. // returning the bare error.
  1738. st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
  1739. }
  1740. }
  1741. // onWriteTimeout is run on its own goroutine (from time.AfterFunc)
  1742. // when the stream's WriteTimeout has fired.
  1743. func (st *stream) onWriteTimeout() {
  1744. st.sc.writeFrameFromHandler(FrameWriteRequest{write: StreamError{
  1745. StreamID: st.id,
  1746. Code: ErrCodeInternal,
  1747. Cause: os.ErrDeadlineExceeded,
  1748. }})
  1749. }
  1750. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1751. sc.serveG.check()
  1752. id := f.StreamID
  1753. // http://tools.ietf.org/html/rfc7540#section-5.1.1
  1754. // Streams initiated by a client MUST use odd-numbered stream
  1755. // identifiers. [...] An endpoint that receives an unexpected
  1756. // stream identifier MUST respond with a connection error
  1757. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1758. if id%2 != 1 {
  1759. return sc.countError("headers_even", ConnectionError(ErrCodeProtocol))
  1760. }
  1761. // A HEADERS frame can be used to create a new stream or
  1762. // send a trailer for an open one. If we already have a stream
  1763. // open, let it process its own HEADERS frame (trailers at this
  1764. // point, if it's valid).
  1765. if st := sc.streams[f.StreamID]; st != nil {
  1766. if st.resetQueued {
  1767. // We're sending RST_STREAM to close the stream, so don't bother
  1768. // processing this frame.
  1769. return nil
  1770. }
  1771. // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than
  1772. // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in
  1773. // this state, it MUST respond with a stream error (Section 5.4.2) of
  1774. // type STREAM_CLOSED.
  1775. if st.state == stateHalfClosedRemote {
  1776. return sc.countError("headers_half_closed", streamError(id, ErrCodeStreamClosed))
  1777. }
  1778. return st.processTrailerHeaders(f)
  1779. }
  1780. // [...] The identifier of a newly established stream MUST be
  1781. // numerically greater than all streams that the initiating
  1782. // endpoint has opened or reserved. [...] An endpoint that
  1783. // receives an unexpected stream identifier MUST respond with
  1784. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1785. if id <= sc.maxClientStreamID {
  1786. return sc.countError("stream_went_down", ConnectionError(ErrCodeProtocol))
  1787. }
  1788. sc.maxClientStreamID = id
  1789. if sc.idleTimer != nil {
  1790. sc.idleTimer.Stop()
  1791. }
  1792. // http://tools.ietf.org/html/rfc7540#section-5.1.2
  1793. // [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1794. // endpoint that receives a HEADERS frame that causes their
  1795. // advertised concurrent stream limit to be exceeded MUST treat
  1796. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1797. // or REFUSED_STREAM.
  1798. if sc.curClientStreams+1 > sc.advMaxStreams {
  1799. if sc.unackedSettings == 0 {
  1800. // They should know better.
  1801. return sc.countError("over_max_streams", streamError(id, ErrCodeProtocol))
  1802. }
  1803. // Assume it's a network race, where they just haven't
  1804. // received our last SETTINGS update. But actually
  1805. // this can't happen yet, because we don't yet provide
  1806. // a way for users to adjust server parameters at
  1807. // runtime.
  1808. return sc.countError("over_max_streams_race", streamError(id, ErrCodeRefusedStream))
  1809. }
  1810. initialState := stateOpen
  1811. if f.StreamEnded() {
  1812. initialState = stateHalfClosedRemote
  1813. }
  1814. st := sc.newStream(id, 0, initialState)
  1815. if f.HasPriority() {
  1816. if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
  1817. return err
  1818. }
  1819. sc.writeSched.AdjustStream(st.id, f.Priority)
  1820. }
  1821. rw, req, err := sc.newWriterAndRequest(st, f)
  1822. if err != nil {
  1823. return err
  1824. }
  1825. st.reqTrailer = req.Trailer
  1826. if st.reqTrailer != nil {
  1827. st.trailer = make(http.Header)
  1828. }
  1829. st.body = req.Body.(*requestBody).pipe // may be nil
  1830. st.declBodyBytes = req.ContentLength
  1831. handler := sc.handler.ServeHTTP
  1832. if f.Truncated {
  1833. // Their header list was too long. Send a 431 error.
  1834. handler = handleHeaderListTooLong
  1835. } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1836. handler = new400Handler(err)
  1837. }
  1838. // The net/http package sets the read deadline from the
  1839. // http.Server.ReadTimeout during the TLS handshake, but then
  1840. // passes the connection off to us with the deadline already
  1841. // set. Disarm it here after the request headers are read,
  1842. // similar to how the http1 server works. Here it's
  1843. // technically more like the http1 Server's ReadHeaderTimeout
  1844. // (in Go 1.8), though. That's a more sane option anyway.
  1845. if sc.hs.ReadTimeout > 0 {
  1846. sc.conn.SetReadDeadline(time.Time{})
  1847. st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout)
  1848. }
  1849. return sc.scheduleHandler(id, rw, req, handler)
  1850. }
  1851. func (sc *serverConn) upgradeRequest(req *http.Request) {
  1852. sc.serveG.check()
  1853. id := uint32(1)
  1854. sc.maxClientStreamID = id
  1855. st := sc.newStream(id, 0, stateHalfClosedRemote)
  1856. st.reqTrailer = req.Trailer
  1857. if st.reqTrailer != nil {
  1858. st.trailer = make(http.Header)
  1859. }
  1860. rw := sc.newResponseWriter(st, req)
  1861. // Disable any read deadline set by the net/http package
  1862. // prior to the upgrade.
  1863. if sc.hs.ReadTimeout > 0 {
  1864. sc.conn.SetReadDeadline(time.Time{})
  1865. }
  1866. // This is the first request on the connection,
  1867. // so start the handler directly rather than going
  1868. // through scheduleHandler.
  1869. sc.curHandlers++
  1870. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  1871. }
  1872. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1873. sc := st.sc
  1874. sc.serveG.check()
  1875. if st.gotTrailerHeader {
  1876. return sc.countError("dup_trailers", ConnectionError(ErrCodeProtocol))
  1877. }
  1878. st.gotTrailerHeader = true
  1879. if !f.StreamEnded() {
  1880. return sc.countError("trailers_not_ended", streamError(st.id, ErrCodeProtocol))
  1881. }
  1882. if len(f.PseudoFields()) > 0 {
  1883. return sc.countError("trailers_pseudo", streamError(st.id, ErrCodeProtocol))
  1884. }
  1885. if st.trailer != nil {
  1886. for _, hf := range f.RegularFields() {
  1887. key := sc.canonicalHeader(hf.Name)
  1888. if !httpguts.ValidTrailerHeader(key) {
  1889. // TODO: send more details to the peer somehow. But http2 has
  1890. // no way to send debug data at a stream level. Discuss with
  1891. // HTTP folk.
  1892. return sc.countError("trailers_bogus", streamError(st.id, ErrCodeProtocol))
  1893. }
  1894. st.trailer[key] = append(st.trailer[key], hf.Value)
  1895. }
  1896. }
  1897. st.endStream()
  1898. return nil
  1899. }
  1900. func (sc *serverConn) checkPriority(streamID uint32, p PriorityParam) error {
  1901. if streamID == p.StreamDep {
  1902. // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  1903. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  1904. // Section 5.3.3 says that a stream can depend on one of its dependencies,
  1905. // so it's only self-dependencies that are forbidden.
  1906. return sc.countError("priority", streamError(streamID, ErrCodeProtocol))
  1907. }
  1908. return nil
  1909. }
  1910. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1911. if err := sc.checkPriority(f.StreamID, f.PriorityParam); err != nil {
  1912. return err
  1913. }
  1914. sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  1915. return nil
  1916. }
  1917. func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
  1918. sc.serveG.check()
  1919. if id == 0 {
  1920. panic("internal error: cannot create stream with id 0")
  1921. }
  1922. ctx, cancelCtx := context.WithCancel(sc.baseCtx)
  1923. st := &stream{
  1924. sc: sc,
  1925. id: id,
  1926. state: state,
  1927. ctx: ctx,
  1928. cancelCtx: cancelCtx,
  1929. }
  1930. st.cw.Init()
  1931. st.flow.conn = &sc.flow // link to conn-level counter
  1932. st.flow.add(sc.initialStreamSendWindowSize)
  1933. st.inflow.init(sc.srv.initialStreamRecvWindowSize())
  1934. if sc.hs.WriteTimeout > 0 {
  1935. st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
  1936. }
  1937. sc.streams[id] = st
  1938. sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
  1939. if st.isPushed() {
  1940. sc.curPushedStreams++
  1941. } else {
  1942. sc.curClientStreams++
  1943. }
  1944. if sc.curOpenStreams() == 1 {
  1945. sc.setConnState(http.StateActive)
  1946. }
  1947. return st
  1948. }
  1949. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1950. sc.serveG.check()
  1951. rp := requestParam{
  1952. method: f.PseudoValue("method"),
  1953. scheme: f.PseudoValue("scheme"),
  1954. authority: f.PseudoValue("authority"),
  1955. path: f.PseudoValue("path"),
  1956. }
  1957. isConnect := rp.method == "CONNECT"
  1958. if isConnect {
  1959. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1960. return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
  1961. }
  1962. } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
  1963. // See 8.1.2.6 Malformed Requests and Responses:
  1964. //
  1965. // Malformed requests or responses that are detected
  1966. // MUST be treated as a stream error (Section 5.4.2)
  1967. // of type PROTOCOL_ERROR."
  1968. //
  1969. // 8.1.2.3 Request Pseudo-Header Fields
  1970. // "All HTTP/2 requests MUST include exactly one valid
  1971. // value for the :method, :scheme, and :path
  1972. // pseudo-header fields"
  1973. return nil, nil, sc.countError("bad_path_method", streamError(f.StreamID, ErrCodeProtocol))
  1974. }
  1975. rp.header = make(http.Header)
  1976. for _, hf := range f.RegularFields() {
  1977. rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1978. }
  1979. if rp.authority == "" {
  1980. rp.authority = rp.header.Get("Host")
  1981. }
  1982. rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  1983. if err != nil {
  1984. return nil, nil, err
  1985. }
  1986. bodyOpen := !f.StreamEnded()
  1987. if bodyOpen {
  1988. if vv, ok := rp.header["Content-Length"]; ok {
  1989. if cl, err := strconv.ParseUint(vv[0], 10, 63); err == nil {
  1990. req.ContentLength = int64(cl)
  1991. } else {
  1992. req.ContentLength = 0
  1993. }
  1994. } else {
  1995. req.ContentLength = -1
  1996. }
  1997. req.Body.(*requestBody).pipe = &pipe{
  1998. b: &dataBuffer{expected: req.ContentLength},
  1999. }
  2000. }
  2001. return rw, req, nil
  2002. }
  2003. type requestParam struct {
  2004. method string
  2005. scheme, authority, path string
  2006. header http.Header
  2007. }
  2008. func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
  2009. sc.serveG.check()
  2010. var tlsState *tls.ConnectionState // nil if not scheme https
  2011. if rp.scheme == "https" {
  2012. tlsState = sc.tlsState
  2013. }
  2014. needsContinue := httpguts.HeaderValuesContainsToken(rp.header["Expect"], "100-continue")
  2015. if needsContinue {
  2016. rp.header.Del("Expect")
  2017. }
  2018. // Merge Cookie headers into one "; "-delimited value.
  2019. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  2020. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  2021. }
  2022. // Setup Trailers
  2023. var trailer http.Header
  2024. for _, v := range rp.header["Trailer"] {
  2025. for _, key := range strings.Split(v, ",") {
  2026. key = http.CanonicalHeaderKey(textproto.TrimString(key))
  2027. switch key {
  2028. case "Transfer-Encoding", "Trailer", "Content-Length":
  2029. // Bogus. (copy of http1 rules)
  2030. // Ignore.
  2031. default:
  2032. if trailer == nil {
  2033. trailer = make(http.Header)
  2034. }
  2035. trailer[key] = nil
  2036. }
  2037. }
  2038. }
  2039. delete(rp.header, "Trailer")
  2040. var url_ *url.URL
  2041. var requestURI string
  2042. if rp.method == "CONNECT" {
  2043. url_ = &url.URL{Host: rp.authority}
  2044. requestURI = rp.authority // mimic HTTP/1 server behavior
  2045. } else {
  2046. var err error
  2047. url_, err = url.ParseRequestURI(rp.path)
  2048. if err != nil {
  2049. return nil, nil, sc.countError("bad_path", streamError(st.id, ErrCodeProtocol))
  2050. }
  2051. requestURI = rp.path
  2052. }
  2053. body := &requestBody{
  2054. conn: sc,
  2055. stream: st,
  2056. needsContinue: needsContinue,
  2057. }
  2058. req := &http.Request{
  2059. Method: rp.method,
  2060. URL: url_,
  2061. RemoteAddr: sc.remoteAddrStr,
  2062. Header: rp.header,
  2063. RequestURI: requestURI,
  2064. Proto: "HTTP/2.0",
  2065. ProtoMajor: 2,
  2066. ProtoMinor: 0,
  2067. TLS: tlsState,
  2068. Host: rp.authority,
  2069. Body: body,
  2070. Trailer: trailer,
  2071. }
  2072. req = req.WithContext(st.ctx)
  2073. rw := sc.newResponseWriter(st, req)
  2074. return rw, req, nil
  2075. }
  2076. func (sc *serverConn) newResponseWriter(st *stream, req *http.Request) *responseWriter {
  2077. rws := responseWriterStatePool.Get().(*responseWriterState)
  2078. bwSave := rws.bw
  2079. *rws = responseWriterState{} // zero all the fields
  2080. rws.conn = sc
  2081. rws.bw = bwSave
  2082. rws.bw.Reset(chunkWriter{rws})
  2083. rws.stream = st
  2084. rws.req = req
  2085. return &responseWriter{rws: rws}
  2086. }
  2087. type unstartedHandler struct {
  2088. streamID uint32
  2089. rw *responseWriter
  2090. req *http.Request
  2091. handler func(http.ResponseWriter, *http.Request)
  2092. }
  2093. // scheduleHandler starts a handler goroutine,
  2094. // or schedules one to start as soon as an existing handler finishes.
  2095. func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error {
  2096. sc.serveG.check()
  2097. maxHandlers := sc.advMaxStreams
  2098. if sc.curHandlers < maxHandlers {
  2099. sc.curHandlers++
  2100. go sc.runHandler(rw, req, handler)
  2101. return nil
  2102. }
  2103. if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
  2104. return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
  2105. }
  2106. sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
  2107. streamID: streamID,
  2108. rw: rw,
  2109. req: req,
  2110. handler: handler,
  2111. })
  2112. return nil
  2113. }
  2114. func (sc *serverConn) handlerDone() {
  2115. sc.serveG.check()
  2116. sc.curHandlers--
  2117. i := 0
  2118. maxHandlers := sc.advMaxStreams
  2119. for ; i < len(sc.unstartedHandlers); i++ {
  2120. u := sc.unstartedHandlers[i]
  2121. if sc.streams[u.streamID] == nil {
  2122. // This stream was reset before its goroutine had a chance to start.
  2123. continue
  2124. }
  2125. if sc.curHandlers >= maxHandlers {
  2126. break
  2127. }
  2128. sc.curHandlers++
  2129. go sc.runHandler(u.rw, u.req, u.handler)
  2130. sc.unstartedHandlers[i] = unstartedHandler{} // don't retain references
  2131. }
  2132. sc.unstartedHandlers = sc.unstartedHandlers[i:]
  2133. if len(sc.unstartedHandlers) == 0 {
  2134. sc.unstartedHandlers = nil
  2135. }
  2136. }
  2137. // Run on its own goroutine.
  2138. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  2139. defer sc.sendServeMsg(handlerDoneMsg)
  2140. didPanic := true
  2141. defer func() {
  2142. rw.rws.stream.cancelCtx()
  2143. if req.MultipartForm != nil {
  2144. req.MultipartForm.RemoveAll()
  2145. }
  2146. if didPanic {
  2147. e := recover()
  2148. sc.writeFrameFromHandler(FrameWriteRequest{
  2149. write: handlerPanicRST{rw.rws.stream.id},
  2150. stream: rw.rws.stream,
  2151. })
  2152. // Same as net/http:
  2153. if e != nil && e != http.ErrAbortHandler {
  2154. const size = 64 << 10
  2155. buf := make([]byte, size)
  2156. buf = buf[:runtime.Stack(buf, false)]
  2157. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  2158. }
  2159. return
  2160. }
  2161. rw.handlerDone()
  2162. }()
  2163. handler(rw, req)
  2164. didPanic = false
  2165. }
  2166. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  2167. // 10.5.1 Limits on Header Block Size:
  2168. // .. "A server that receives a larger header block than it is
  2169. // willing to handle can send an HTTP 431 (Request Header Fields Too
  2170. // Large) status code"
  2171. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  2172. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  2173. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  2174. }
  2175. // called from handler goroutines.
  2176. // h may be nil.
  2177. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  2178. sc.serveG.checkNotOn() // NOT on
  2179. var errc chan error
  2180. if headerData.h != nil {
  2181. // If there's a header map (which we don't own), so we have to block on
  2182. // waiting for this frame to be written, so an http.Flush mid-handler
  2183. // writes out the correct value of keys, before a handler later potentially
  2184. // mutates it.
  2185. errc = errChanPool.Get().(chan error)
  2186. }
  2187. if err := sc.writeFrameFromHandler(FrameWriteRequest{
  2188. write: headerData,
  2189. stream: st,
  2190. done: errc,
  2191. }); err != nil {
  2192. return err
  2193. }
  2194. if errc != nil {
  2195. select {
  2196. case err := <-errc:
  2197. errChanPool.Put(errc)
  2198. return err
  2199. case <-sc.doneServing:
  2200. return errClientDisconnected
  2201. case <-st.cw:
  2202. return errStreamClosed
  2203. }
  2204. }
  2205. return nil
  2206. }
  2207. // called from handler goroutines.
  2208. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  2209. sc.writeFrameFromHandler(FrameWriteRequest{
  2210. write: write100ContinueHeadersFrame{st.id},
  2211. stream: st,
  2212. })
  2213. }
  2214. // A bodyReadMsg tells the server loop that the http.Handler read n
  2215. // bytes of the DATA from the client on the given stream.
  2216. type bodyReadMsg struct {
  2217. st *stream
  2218. n int
  2219. }
  2220. // called from handler goroutines.
  2221. // Notes that the handler for the given stream ID read n bytes of its body
  2222. // and schedules flow control tokens to be sent.
  2223. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  2224. sc.serveG.checkNotOn() // NOT on
  2225. if n > 0 {
  2226. select {
  2227. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  2228. case <-sc.doneServing:
  2229. }
  2230. }
  2231. }
  2232. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  2233. sc.serveG.check()
  2234. sc.sendWindowUpdate(nil, n) // conn-level
  2235. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  2236. // Don't send this WINDOW_UPDATE if the stream is closed
  2237. // remotely.
  2238. sc.sendWindowUpdate(st, n)
  2239. }
  2240. }
  2241. // st may be nil for conn-level
  2242. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  2243. sc.sendWindowUpdate(st, int(n))
  2244. }
  2245. // st may be nil for conn-level
  2246. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  2247. sc.serveG.check()
  2248. var streamID uint32
  2249. var send int32
  2250. if st == nil {
  2251. send = sc.inflow.add(n)
  2252. } else {
  2253. streamID = st.id
  2254. send = st.inflow.add(n)
  2255. }
  2256. if send == 0 {
  2257. return
  2258. }
  2259. sc.writeFrame(FrameWriteRequest{
  2260. write: writeWindowUpdate{streamID: streamID, n: uint32(send)},
  2261. stream: st,
  2262. })
  2263. }
  2264. // requestBody is the Handler's Request.Body type.
  2265. // Read and Close may be called concurrently.
  2266. type requestBody struct {
  2267. _ incomparable
  2268. stream *stream
  2269. conn *serverConn
  2270. closeOnce sync.Once // for use by Close only
  2271. sawEOF bool // for use by Read only
  2272. pipe *pipe // non-nil if we have an HTTP entity message body
  2273. needsContinue bool // need to send a 100-continue
  2274. }
  2275. func (b *requestBody) Close() error {
  2276. b.closeOnce.Do(func() {
  2277. if b.pipe != nil {
  2278. b.pipe.BreakWithError(errClosedBody)
  2279. }
  2280. })
  2281. return nil
  2282. }
  2283. func (b *requestBody) Read(p []byte) (n int, err error) {
  2284. if b.needsContinue {
  2285. b.needsContinue = false
  2286. b.conn.write100ContinueHeaders(b.stream)
  2287. }
  2288. if b.pipe == nil || b.sawEOF {
  2289. return 0, io.EOF
  2290. }
  2291. n, err = b.pipe.Read(p)
  2292. if err == io.EOF {
  2293. b.sawEOF = true
  2294. }
  2295. if b.conn == nil && inTests {
  2296. return
  2297. }
  2298. b.conn.noteBodyReadFromHandler(b.stream, n, err)
  2299. return
  2300. }
  2301. // responseWriter is the http.ResponseWriter implementation. It's
  2302. // intentionally small (1 pointer wide) to minimize garbage. The
  2303. // responseWriterState pointer inside is zeroed at the end of a
  2304. // request (in handlerDone) and calls on the responseWriter thereafter
  2305. // simply crash (caller's mistake), but the much larger responseWriterState
  2306. // and buffers are reused between multiple requests.
  2307. type responseWriter struct {
  2308. rws *responseWriterState
  2309. }
  2310. // Optional http.ResponseWriter interfaces implemented.
  2311. var (
  2312. _ http.CloseNotifier = (*responseWriter)(nil)
  2313. _ http.Flusher = (*responseWriter)(nil)
  2314. _ stringWriter = (*responseWriter)(nil)
  2315. )
  2316. type responseWriterState struct {
  2317. // immutable within a request:
  2318. stream *stream
  2319. req *http.Request
  2320. conn *serverConn
  2321. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  2322. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  2323. // mutated by http.Handler goroutine:
  2324. handlerHeader http.Header // nil until called
  2325. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  2326. trailers []string // set in writeChunk
  2327. status int // status code passed to WriteHeader
  2328. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  2329. sentHeader bool // have we sent the header frame?
  2330. handlerDone bool // handler has finished
  2331. sentContentLen int64 // non-zero if handler set a Content-Length header
  2332. wroteBytes int64
  2333. closeNotifierMu sync.Mutex // guards closeNotifierCh
  2334. closeNotifierCh chan bool // nil until first used
  2335. }
  2336. type chunkWriter struct{ rws *responseWriterState }
  2337. func (cw chunkWriter) Write(p []byte) (n int, err error) {
  2338. n, err = cw.rws.writeChunk(p)
  2339. if err == errStreamClosed {
  2340. // If writing failed because the stream has been closed,
  2341. // return the reason it was closed.
  2342. err = cw.rws.stream.closeErr
  2343. }
  2344. return n, err
  2345. }
  2346. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
  2347. func (rws *responseWriterState) hasNonemptyTrailers() bool {
  2348. for _, trailer := range rws.trailers {
  2349. if _, ok := rws.handlerHeader[trailer]; ok {
  2350. return true
  2351. }
  2352. }
  2353. return false
  2354. }
  2355. // declareTrailer is called for each Trailer header when the
  2356. // response header is written. It notes that a header will need to be
  2357. // written in the trailers at the end of the response.
  2358. func (rws *responseWriterState) declareTrailer(k string) {
  2359. k = http.CanonicalHeaderKey(k)
  2360. if !httpguts.ValidTrailerHeader(k) {
  2361. // Forbidden by RFC 7230, section 4.1.2.
  2362. rws.conn.logf("ignoring invalid trailer %q", k)
  2363. return
  2364. }
  2365. if !strSliceContains(rws.trailers, k) {
  2366. rws.trailers = append(rws.trailers, k)
  2367. }
  2368. }
  2369. // writeChunk writes chunks from the bufio.Writer. But because
  2370. // bufio.Writer may bypass its chunking, sometimes p may be
  2371. // arbitrarily large.
  2372. //
  2373. // writeChunk is also responsible (on the first chunk) for sending the
  2374. // HEADER response.
  2375. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  2376. if !rws.wroteHeader {
  2377. rws.writeHeader(200)
  2378. }
  2379. if rws.handlerDone {
  2380. rws.promoteUndeclaredTrailers()
  2381. }
  2382. isHeadResp := rws.req.Method == "HEAD"
  2383. if !rws.sentHeader {
  2384. rws.sentHeader = true
  2385. var ctype, clen string
  2386. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  2387. rws.snapHeader.Del("Content-Length")
  2388. if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
  2389. rws.sentContentLen = int64(cl)
  2390. } else {
  2391. clen = ""
  2392. }
  2393. }
  2394. _, hasContentLength := rws.snapHeader["Content-Length"]
  2395. if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  2396. clen = strconv.Itoa(len(p))
  2397. }
  2398. _, hasContentType := rws.snapHeader["Content-Type"]
  2399. // If the Content-Encoding is non-blank, we shouldn't
  2400. // sniff the body. See Issue golang.org/issue/31753.
  2401. ce := rws.snapHeader.Get("Content-Encoding")
  2402. hasCE := len(ce) > 0
  2403. if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
  2404. ctype = http.DetectContentType(p)
  2405. }
  2406. var date string
  2407. if _, ok := rws.snapHeader["Date"]; !ok {
  2408. // TODO(bradfitz): be faster here, like net/http? measure.
  2409. date = time.Now().UTC().Format(http.TimeFormat)
  2410. }
  2411. for _, v := range rws.snapHeader["Trailer"] {
  2412. foreachHeaderElement(v, rws.declareTrailer)
  2413. }
  2414. // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),
  2415. // but respect "Connection" == "close" to mean sending a GOAWAY and tearing
  2416. // down the TCP connection when idle, like we do for HTTP/1.
  2417. // TODO: remove more Connection-specific header fields here, in addition
  2418. // to "Connection".
  2419. if _, ok := rws.snapHeader["Connection"]; ok {
  2420. v := rws.snapHeader.Get("Connection")
  2421. delete(rws.snapHeader, "Connection")
  2422. if v == "close" {
  2423. rws.conn.startGracefulShutdown()
  2424. }
  2425. }
  2426. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  2427. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2428. streamID: rws.stream.id,
  2429. httpResCode: rws.status,
  2430. h: rws.snapHeader,
  2431. endStream: endStream,
  2432. contentType: ctype,
  2433. contentLength: clen,
  2434. date: date,
  2435. })
  2436. if err != nil {
  2437. return 0, err
  2438. }
  2439. if endStream {
  2440. return 0, nil
  2441. }
  2442. }
  2443. if isHeadResp {
  2444. return len(p), nil
  2445. }
  2446. if len(p) == 0 && !rws.handlerDone {
  2447. return 0, nil
  2448. }
  2449. // only send trailers if they have actually been defined by the
  2450. // server handler.
  2451. hasNonemptyTrailers := rws.hasNonemptyTrailers()
  2452. endStream := rws.handlerDone && !hasNonemptyTrailers
  2453. if len(p) > 0 || endStream {
  2454. // only send a 0 byte DATA frame if we're ending the stream.
  2455. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  2456. return 0, err
  2457. }
  2458. }
  2459. if rws.handlerDone && hasNonemptyTrailers {
  2460. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2461. streamID: rws.stream.id,
  2462. h: rws.handlerHeader,
  2463. trailers: rws.trailers,
  2464. endStream: true,
  2465. })
  2466. return len(p), err
  2467. }
  2468. return len(p), nil
  2469. }
  2470. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  2471. // that, if present, signals that the map entry is actually for
  2472. // the response trailers, and not the response headers. The prefix
  2473. // is stripped after the ServeHTTP call finishes and the values are
  2474. // sent in the trailers.
  2475. //
  2476. // This mechanism is intended only for trailers that are not known
  2477. // prior to the headers being written. If the set of trailers is fixed
  2478. // or known before the header is written, the normal Go trailers mechanism
  2479. // is preferred:
  2480. //
  2481. // https://golang.org/pkg/net/http/#ResponseWriter
  2482. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  2483. const TrailerPrefix = "Trailer:"
  2484. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  2485. // after the header has already been flushed. Because the Go
  2486. // ResponseWriter interface has no way to set Trailers (only the
  2487. // Header), and because we didn't want to expand the ResponseWriter
  2488. // interface, and because nobody used trailers, and because RFC 7230
  2489. // says you SHOULD (but not must) predeclare any trailers in the
  2490. // header, the official ResponseWriter rules said trailers in Go must
  2491. // be predeclared, and then we reuse the same ResponseWriter.Header()
  2492. // map to mean both Headers and Trailers. When it's time to write the
  2493. // Trailers, we pick out the fields of Headers that were declared as
  2494. // trailers. That worked for a while, until we found the first major
  2495. // user of Trailers in the wild: gRPC (using them only over http2),
  2496. // and gRPC libraries permit setting trailers mid-stream without
  2497. // predeclaring them. So: change of plans. We still permit the old
  2498. // way, but we also permit this hack: if a Header() key begins with
  2499. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2500. // invalid token byte anyway, there is no ambiguity. (And it's already
  2501. // filtered out) It's mildly hacky, but not terrible.
  2502. //
  2503. // This method runs after the Handler is done and promotes any Header
  2504. // fields to be trailers.
  2505. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2506. for k, vv := range rws.handlerHeader {
  2507. if !strings.HasPrefix(k, TrailerPrefix) {
  2508. continue
  2509. }
  2510. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2511. rws.declareTrailer(trailerKey)
  2512. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  2513. }
  2514. if len(rws.trailers) > 1 {
  2515. sorter := sorterPool.Get().(*sorter)
  2516. sorter.SortStrings(rws.trailers)
  2517. sorterPool.Put(sorter)
  2518. }
  2519. }
  2520. func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
  2521. st := w.rws.stream
  2522. if !deadline.IsZero() && deadline.Before(time.Now()) {
  2523. // If we're setting a deadline in the past, reset the stream immediately
  2524. // so writes after SetWriteDeadline returns will fail.
  2525. st.onReadTimeout()
  2526. return nil
  2527. }
  2528. w.rws.conn.sendServeMsg(func(sc *serverConn) {
  2529. if st.readDeadline != nil {
  2530. if !st.readDeadline.Stop() {
  2531. // Deadline already exceeded, or stream has been closed.
  2532. return
  2533. }
  2534. }
  2535. if deadline.IsZero() {
  2536. st.readDeadline = nil
  2537. } else if st.readDeadline == nil {
  2538. st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
  2539. } else {
  2540. st.readDeadline.Reset(deadline.Sub(time.Now()))
  2541. }
  2542. })
  2543. return nil
  2544. }
  2545. func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
  2546. st := w.rws.stream
  2547. if !deadline.IsZero() && deadline.Before(time.Now()) {
  2548. // If we're setting a deadline in the past, reset the stream immediately
  2549. // so writes after SetWriteDeadline returns will fail.
  2550. st.onWriteTimeout()
  2551. return nil
  2552. }
  2553. w.rws.conn.sendServeMsg(func(sc *serverConn) {
  2554. if st.writeDeadline != nil {
  2555. if !st.writeDeadline.Stop() {
  2556. // Deadline already exceeded, or stream has been closed.
  2557. return
  2558. }
  2559. }
  2560. if deadline.IsZero() {
  2561. st.writeDeadline = nil
  2562. } else if st.writeDeadline == nil {
  2563. st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
  2564. } else {
  2565. st.writeDeadline.Reset(deadline.Sub(time.Now()))
  2566. }
  2567. })
  2568. return nil
  2569. }
  2570. func (w *responseWriter) Flush() {
  2571. w.FlushError()
  2572. }
  2573. func (w *responseWriter) FlushError() error {
  2574. rws := w.rws
  2575. if rws == nil {
  2576. panic("Header called after Handler finished")
  2577. }
  2578. var err error
  2579. if rws.bw.Buffered() > 0 {
  2580. err = rws.bw.Flush()
  2581. } else {
  2582. // The bufio.Writer won't call chunkWriter.Write
  2583. // (writeChunk with zero bytes), so we have to do it
  2584. // ourselves to force the HTTP response header and/or
  2585. // final DATA frame (with END_STREAM) to be sent.
  2586. _, err = chunkWriter{rws}.Write(nil)
  2587. if err == nil {
  2588. select {
  2589. case <-rws.stream.cw:
  2590. err = rws.stream.closeErr
  2591. default:
  2592. }
  2593. }
  2594. }
  2595. return err
  2596. }
  2597. func (w *responseWriter) CloseNotify() <-chan bool {
  2598. rws := w.rws
  2599. if rws == nil {
  2600. panic("CloseNotify called after Handler finished")
  2601. }
  2602. rws.closeNotifierMu.Lock()
  2603. ch := rws.closeNotifierCh
  2604. if ch == nil {
  2605. ch = make(chan bool, 1)
  2606. rws.closeNotifierCh = ch
  2607. cw := rws.stream.cw
  2608. go func() {
  2609. cw.Wait() // wait for close
  2610. ch <- true
  2611. }()
  2612. }
  2613. rws.closeNotifierMu.Unlock()
  2614. return ch
  2615. }
  2616. func (w *responseWriter) Header() http.Header {
  2617. rws := w.rws
  2618. if rws == nil {
  2619. panic("Header called after Handler finished")
  2620. }
  2621. if rws.handlerHeader == nil {
  2622. rws.handlerHeader = make(http.Header)
  2623. }
  2624. return rws.handlerHeader
  2625. }
  2626. // checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
  2627. func checkWriteHeaderCode(code int) {
  2628. // Issue 22880: require valid WriteHeader status codes.
  2629. // For now we only enforce that it's three digits.
  2630. // In the future we might block things over 599 (600 and above aren't defined
  2631. // at http://httpwg.org/specs/rfc7231.html#status.codes).
  2632. // But for now any three digits.
  2633. //
  2634. // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
  2635. // no equivalent bogus thing we can realistically send in HTTP/2,
  2636. // so we'll consistently panic instead and help people find their bugs
  2637. // early. (We can't return an error from WriteHeader even if we wanted to.)
  2638. if code < 100 || code > 999 {
  2639. panic(fmt.Sprintf("invalid WriteHeader code %v", code))
  2640. }
  2641. }
  2642. func (w *responseWriter) WriteHeader(code int) {
  2643. rws := w.rws
  2644. if rws == nil {
  2645. panic("WriteHeader called after Handler finished")
  2646. }
  2647. rws.writeHeader(code)
  2648. }
  2649. func (rws *responseWriterState) writeHeader(code int) {
  2650. if rws.wroteHeader {
  2651. return
  2652. }
  2653. checkWriteHeaderCode(code)
  2654. // Handle informational headers
  2655. if code >= 100 && code <= 199 {
  2656. // Per RFC 8297 we must not clear the current header map
  2657. h := rws.handlerHeader
  2658. _, cl := h["Content-Length"]
  2659. _, te := h["Transfer-Encoding"]
  2660. if cl || te {
  2661. h = h.Clone()
  2662. h.Del("Content-Length")
  2663. h.Del("Transfer-Encoding")
  2664. }
  2665. rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2666. streamID: rws.stream.id,
  2667. httpResCode: code,
  2668. h: h,
  2669. endStream: rws.handlerDone && !rws.hasTrailers(),
  2670. })
  2671. return
  2672. }
  2673. rws.wroteHeader = true
  2674. rws.status = code
  2675. if len(rws.handlerHeader) > 0 {
  2676. rws.snapHeader = cloneHeader(rws.handlerHeader)
  2677. }
  2678. }
  2679. func cloneHeader(h http.Header) http.Header {
  2680. h2 := make(http.Header, len(h))
  2681. for k, vv := range h {
  2682. vv2 := make([]string, len(vv))
  2683. copy(vv2, vv)
  2684. h2[k] = vv2
  2685. }
  2686. return h2
  2687. }
  2688. // The Life Of A Write is like this:
  2689. //
  2690. // * Handler calls w.Write or w.WriteString ->
  2691. // * -> rws.bw (*bufio.Writer) ->
  2692. // * (Handler might call Flush)
  2693. // * -> chunkWriter{rws}
  2694. // * -> responseWriterState.writeChunk(p []byte)
  2695. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2696. func (w *responseWriter) Write(p []byte) (n int, err error) {
  2697. return w.write(len(p), p, "")
  2698. }
  2699. func (w *responseWriter) WriteString(s string) (n int, err error) {
  2700. return w.write(len(s), nil, s)
  2701. }
  2702. // either dataB or dataS is non-zero.
  2703. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2704. rws := w.rws
  2705. if rws == nil {
  2706. panic("Write called after Handler finished")
  2707. }
  2708. if !rws.wroteHeader {
  2709. w.WriteHeader(200)
  2710. }
  2711. if !bodyAllowedForStatus(rws.status) {
  2712. return 0, http.ErrBodyNotAllowed
  2713. }
  2714. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2715. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2716. // TODO: send a RST_STREAM
  2717. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2718. }
  2719. if dataB != nil {
  2720. return rws.bw.Write(dataB)
  2721. } else {
  2722. return rws.bw.WriteString(dataS)
  2723. }
  2724. }
  2725. func (w *responseWriter) handlerDone() {
  2726. rws := w.rws
  2727. rws.handlerDone = true
  2728. w.Flush()
  2729. w.rws = nil
  2730. responseWriterStatePool.Put(rws)
  2731. }
  2732. // Push errors.
  2733. var (
  2734. ErrRecursivePush = errors.New("http2: recursive push not allowed")
  2735. ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2736. )
  2737. var _ http.Pusher = (*responseWriter)(nil)
  2738. func (w *responseWriter) Push(target string, opts *http.PushOptions) error {
  2739. st := w.rws.stream
  2740. sc := st.sc
  2741. sc.serveG.checkNotOn()
  2742. // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2743. // http://tools.ietf.org/html/rfc7540#section-6.6
  2744. if st.isPushed() {
  2745. return ErrRecursivePush
  2746. }
  2747. if opts == nil {
  2748. opts = new(http.PushOptions)
  2749. }
  2750. // Default options.
  2751. if opts.Method == "" {
  2752. opts.Method = "GET"
  2753. }
  2754. if opts.Header == nil {
  2755. opts.Header = http.Header{}
  2756. }
  2757. wantScheme := "http"
  2758. if w.rws.req.TLS != nil {
  2759. wantScheme = "https"
  2760. }
  2761. // Validate the request.
  2762. u, err := url.Parse(target)
  2763. if err != nil {
  2764. return err
  2765. }
  2766. if u.Scheme == "" {
  2767. if !strings.HasPrefix(target, "/") {
  2768. return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2769. }
  2770. u.Scheme = wantScheme
  2771. u.Host = w.rws.req.Host
  2772. } else {
  2773. if u.Scheme != wantScheme {
  2774. return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2775. }
  2776. if u.Host == "" {
  2777. return errors.New("URL must have a host")
  2778. }
  2779. }
  2780. for k := range opts.Header {
  2781. if strings.HasPrefix(k, ":") {
  2782. return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  2783. }
  2784. // These headers are meaningful only if the request has a body,
  2785. // but PUSH_PROMISE requests cannot have a body.
  2786. // http://tools.ietf.org/html/rfc7540#section-8.2
  2787. // Also disallow Host, since the promised URL must be absolute.
  2788. if asciiEqualFold(k, "content-length") ||
  2789. asciiEqualFold(k, "content-encoding") ||
  2790. asciiEqualFold(k, "trailer") ||
  2791. asciiEqualFold(k, "te") ||
  2792. asciiEqualFold(k, "expect") ||
  2793. asciiEqualFold(k, "host") {
  2794. return fmt.Errorf("promised request headers cannot include %q", k)
  2795. }
  2796. }
  2797. if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  2798. return err
  2799. }
  2800. // The RFC effectively limits promised requests to GET and HEAD:
  2801. // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  2802. // http://tools.ietf.org/html/rfc7540#section-8.2
  2803. if opts.Method != "GET" && opts.Method != "HEAD" {
  2804. return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  2805. }
  2806. msg := &startPushRequest{
  2807. parent: st,
  2808. method: opts.Method,
  2809. url: u,
  2810. header: cloneHeader(opts.Header),
  2811. done: errChanPool.Get().(chan error),
  2812. }
  2813. select {
  2814. case <-sc.doneServing:
  2815. return errClientDisconnected
  2816. case <-st.cw:
  2817. return errStreamClosed
  2818. case sc.serveMsgCh <- msg:
  2819. }
  2820. select {
  2821. case <-sc.doneServing:
  2822. return errClientDisconnected
  2823. case <-st.cw:
  2824. return errStreamClosed
  2825. case err := <-msg.done:
  2826. errChanPool.Put(msg.done)
  2827. return err
  2828. }
  2829. }
  2830. type startPushRequest struct {
  2831. parent *stream
  2832. method string
  2833. url *url.URL
  2834. header http.Header
  2835. done chan error
  2836. }
  2837. func (sc *serverConn) startPush(msg *startPushRequest) {
  2838. sc.serveG.check()
  2839. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2840. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  2841. // is in either the "open" or "half-closed (remote)" state.
  2842. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  2843. // responseWriter.Push checks that the stream is peer-initiated.
  2844. msg.done <- errStreamClosed
  2845. return
  2846. }
  2847. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2848. if !sc.pushEnabled {
  2849. msg.done <- http.ErrNotSupported
  2850. return
  2851. }
  2852. // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  2853. // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  2854. // is written. Once the ID is allocated, we start the request handler.
  2855. allocatePromisedID := func() (uint32, error) {
  2856. sc.serveG.check()
  2857. // Check this again, just in case. Technically, we might have received
  2858. // an updated SETTINGS by the time we got around to writing this frame.
  2859. if !sc.pushEnabled {
  2860. return 0, http.ErrNotSupported
  2861. }
  2862. // http://tools.ietf.org/html/rfc7540#section-6.5.2.
  2863. if sc.curPushedStreams+1 > sc.clientMaxStreams {
  2864. return 0, ErrPushLimitReached
  2865. }
  2866. // http://tools.ietf.org/html/rfc7540#section-5.1.1.
  2867. // Streams initiated by the server MUST use even-numbered identifiers.
  2868. // A server that is unable to establish a new stream identifier can send a GOAWAY
  2869. // frame so that the client is forced to open a new connection for new streams.
  2870. if sc.maxPushPromiseID+2 >= 1<<31 {
  2871. sc.startGracefulShutdownInternal()
  2872. return 0, ErrPushLimitReached
  2873. }
  2874. sc.maxPushPromiseID += 2
  2875. promisedID := sc.maxPushPromiseID
  2876. // http://tools.ietf.org/html/rfc7540#section-8.2.
  2877. // Strictly speaking, the new stream should start in "reserved (local)", then
  2878. // transition to "half closed (remote)" after sending the initial HEADERS, but
  2879. // we start in "half closed (remote)" for simplicity.
  2880. // See further comments at the definition of stateHalfClosedRemote.
  2881. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
  2882. rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
  2883. method: msg.method,
  2884. scheme: msg.url.Scheme,
  2885. authority: msg.url.Host,
  2886. path: msg.url.RequestURI(),
  2887. header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  2888. })
  2889. if err != nil {
  2890. // Should not happen, since we've already validated msg.url.
  2891. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  2892. }
  2893. sc.curHandlers++
  2894. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  2895. return promisedID, nil
  2896. }
  2897. sc.writeFrame(FrameWriteRequest{
  2898. write: &writePushPromise{
  2899. streamID: msg.parent.id,
  2900. method: msg.method,
  2901. url: msg.url,
  2902. h: msg.header,
  2903. allocatePromisedID: allocatePromisedID,
  2904. },
  2905. stream: msg.parent,
  2906. done: msg.done,
  2907. })
  2908. }
  2909. // foreachHeaderElement splits v according to the "#rule" construction
  2910. // in RFC 7230 section 7 and calls fn for each non-empty element.
  2911. func foreachHeaderElement(v string, fn func(string)) {
  2912. v = textproto.TrimString(v)
  2913. if v == "" {
  2914. return
  2915. }
  2916. if !strings.Contains(v, ",") {
  2917. fn(v)
  2918. return
  2919. }
  2920. for _, f := range strings.Split(v, ",") {
  2921. if f = textproto.TrimString(f); f != "" {
  2922. fn(f)
  2923. }
  2924. }
  2925. }
  2926. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2927. var connHeaders = []string{
  2928. "Connection",
  2929. "Keep-Alive",
  2930. "Proxy-Connection",
  2931. "Transfer-Encoding",
  2932. "Upgrade",
  2933. }
  2934. // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  2935. // per RFC 7540 Section 8.1.2.2.
  2936. // The returned error is reported to users.
  2937. func checkValidHTTP2RequestHeaders(h http.Header) error {
  2938. for _, k := range connHeaders {
  2939. if _, ok := h[k]; ok {
  2940. return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  2941. }
  2942. }
  2943. te := h["Te"]
  2944. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2945. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2946. }
  2947. return nil
  2948. }
  2949. func new400Handler(err error) http.HandlerFunc {
  2950. return func(w http.ResponseWriter, r *http.Request) {
  2951. http.Error(w, err.Error(), http.StatusBadRequest)
  2952. }
  2953. }
  2954. // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  2955. // disabled. See comments on h1ServerShutdownChan above for why
  2956. // the code is written this way.
  2957. func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
  2958. var x interface{} = hs
  2959. type I interface {
  2960. doKeepAlives() bool
  2961. }
  2962. if hs, ok := x.(I); ok {
  2963. return !hs.doKeepAlives()
  2964. }
  2965. return false
  2966. }
  2967. func (sc *serverConn) countError(name string, err error) error {
  2968. if sc == nil || sc.srv == nil {
  2969. return err
  2970. }
  2971. f := sc.srv.CountError
  2972. if f == nil {
  2973. return err
  2974. }
  2975. var typ string
  2976. var code ErrCode
  2977. switch e := err.(type) {
  2978. case ConnectionError:
  2979. typ = "conn"
  2980. code = ErrCode(e)
  2981. case StreamError:
  2982. typ = "stream"
  2983. code = ErrCode(e.Code)
  2984. default:
  2985. return err
  2986. }
  2987. codeStr := errCodeName[code]
  2988. if codeStr == "" {
  2989. codeStr = strconv.Itoa(int(code))
  2990. }
  2991. f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
  2992. return err
  2993. }