server.go 70 KB

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