server.go 104 KB

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