server.go 68 KB

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