server.go 104 KB

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