server.go 58 KB

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