server.go 100 KB

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