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