server.go 94 KB

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