server.go 84 KB

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