server.go 62 KB

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