server.go 90 KB

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