server.go 100 KB

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