server.go 79 KB

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