Source file src/net/http/internal/http2/server.go

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // TODO: turn off the serve goroutine when idle, so
     6  // an idle conn only has the readFrames goroutine active. (which could
     7  // also be optimized probably to pin less memory in crypto/tls). This
     8  // would involve tracking when the serve goroutine is active (atomic
     9  // int32 read/CAS probably?) and starting it up when frames arrive,
    10  // and shutting it down when all handlers exit. the occasional PING
    11  // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
    12  // (which is a no-op if already running) and then queue the PING write
    13  // as normal. The serve loop would then exit in most cases (if no
    14  // Handlers running) and not be woken up again until the PING packet
    15  // returns.
    16  
    17  // TODO (maybe): add a mechanism for Handlers to going into
    18  // half-closed-local mode (rw.(io.Closer) test?) but not exit their
    19  // handler, and continue to be able to read from the
    20  // Request.Body. This would be a somewhat semantic change from HTTP/1
    21  // (or at least what we expose in net/http), so I'd probably want to
    22  // add it there too. For now, this package says that returning from
    23  // the Handler ServeHTTP function means you're both done reading and
    24  // done writing, without a way to stop just one or the other.
    25  
    26  package http2
    27  
    28  import (
    29  	"bufio"
    30  	"bytes"
    31  	"context"
    32  	"crypto/rand"
    33  	"crypto/tls"
    34  	"errors"
    35  	"fmt"
    36  	"io"
    37  	"log"
    38  	"math"
    39  	"net"
    40  	"net/http/internal"
    41  	"net/http/internal/httpcommon"
    42  	"net/textproto"
    43  	"net/url"
    44  	"os"
    45  	"reflect"
    46  	"runtime"
    47  	"slices"
    48  	"strconv"
    49  	"strings"
    50  	"sync"
    51  	"time"
    52  
    53  	"golang.org/x/net/http/httpguts"
    54  	"golang.org/x/net/http2/hpack"
    55  )
    56  
    57  const (
    58  	prefaceTimeout        = 10 * time.Second
    59  	firstSettingsTimeout  = 2 * time.Second // should be in-flight with preface anyway
    60  	handlerChunkWriteSize = 4 << 10
    61  	defaultMaxStreams     = 250 // TODO: make this 100 as the GFE seems to?
    62  
    63  	// maxQueuedControlFrames is the maximum number of control frames like
    64  	// SETTINGS, PING and RST_STREAM that will be queued for writing before
    65  	// the connection is closed to prevent memory exhaustion attacks.
    66  	maxQueuedControlFrames = 10000
    67  )
    68  
    69  var (
    70  	errClientDisconnected = errors.New("client disconnected")
    71  	errClosedBody         = errors.New("body closed by handler")
    72  	errHandlerComplete    = errors.New("http2: request body closed due to handler exiting")
    73  	errStreamClosed       = errors.New("http2: stream closed")
    74  )
    75  
    76  var responseWriterStatePool = sync.Pool{
    77  	New: func() any {
    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  	testHookOnPanicMu *sync.Mutex // nil except in tests
    88  	testHookOnPanic   func(sc *serverConn, panicVal any) (rePanic bool)
    89  )
    90  
    91  // Server is an HTTP/2 server.
    92  type Server struct {
    93  	mu          sync.Mutex
    94  	activeConns map[*serverConn]struct{}
    95  
    96  	// Pool of error channels. This is per-Server rather than global
    97  	// because channels can't be reused across synctest bubbles.
    98  	errChanPool sync.Pool
    99  }
   100  
   101  func (s *Server) registerConn(sc *serverConn) {
   102  	if s == nil {
   103  		return // if the Server was used without calling ConfigureServer
   104  	}
   105  	s.mu.Lock()
   106  	s.activeConns[sc] = struct{}{}
   107  	s.mu.Unlock()
   108  }
   109  
   110  func (s *Server) unregisterConn(sc *serverConn) {
   111  	if s == nil {
   112  		return // if the Server was used without calling ConfigureServer
   113  	}
   114  	s.mu.Lock()
   115  	delete(s.activeConns, sc)
   116  	s.mu.Unlock()
   117  }
   118  
   119  func (s *Server) startGracefulShutdown() {
   120  	if s == nil {
   121  		return // if the Server was used without calling ConfigureServer
   122  	}
   123  	s.mu.Lock()
   124  	for sc := range s.activeConns {
   125  		sc.startGracefulShutdown()
   126  	}
   127  	s.mu.Unlock()
   128  }
   129  
   130  // Global error channel pool used for uninitialized Servers.
   131  // We use a per-Server pool when possible to avoid using channels across synctest bubbles.
   132  var errChanPool = sync.Pool{
   133  	New: func() any { return make(chan error, 1) },
   134  }
   135  
   136  func (s *Server) getErrChan() chan error {
   137  	if s == nil {
   138  		return errChanPool.Get().(chan error) // Server used without calling ConfigureServer
   139  	}
   140  	return s.errChanPool.Get().(chan error)
   141  }
   142  
   143  func (s *Server) putErrChan(ch chan error) {
   144  	if s == nil {
   145  		errChanPool.Put(ch) // Server used without calling ConfigureServer
   146  		return
   147  	}
   148  	s.errChanPool.Put(ch)
   149  }
   150  
   151  func (s *Server) Configure(conf ServerConfig, tcfg *tls.Config) error {
   152  	s.activeConns = make(map[*serverConn]struct{})
   153  	s.errChanPool = sync.Pool{New: func() any { return make(chan error, 1) }}
   154  
   155  	if tcfg.CipherSuites != nil && tcfg.MinVersion < tls.VersionTLS13 {
   156  		// If they already provided a TLS 1.0–1.2 CipherSuite list, return an
   157  		// error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or
   158  		// ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
   159  		haveRequired := false
   160  		for _, cs := range tcfg.CipherSuites {
   161  			switch cs {
   162  			case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   163  				// Alternative MTI cipher to not discourage ECDSA-only servers.
   164  				// See http://golang.org/cl/30721 for further information.
   165  				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
   166  				haveRequired = true
   167  			}
   168  		}
   169  		if !haveRequired {
   170  			return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
   171  		}
   172  	}
   173  
   174  	// Note: not setting MinVersion to tls.VersionTLS12,
   175  	// as we don't want to interfere with HTTP/1.1 traffic
   176  	// on the user's server. We enforce TLS 1.2 later once
   177  	// we accept a connection. Ideally this should be done
   178  	// during next-proto selection, but using TLS <1.2 with
   179  	// HTTP/2 is still the client's bug.
   180  
   181  	return nil
   182  }
   183  
   184  func (s *Server) GracefulShutdown() {
   185  	s.startGracefulShutdown()
   186  }
   187  
   188  // ServeConnOpts are options for the Server.ServeConn method.
   189  type ServeConnOpts struct {
   190  	// Context is the base context to use.
   191  	// If nil, context.Background is used.
   192  	Context context.Context
   193  
   194  	// BaseConfig optionally sets the base configuration
   195  	// for values. If nil, defaults are used.
   196  	BaseConfig ServerConfig
   197  
   198  	// Handler specifies which handler to use for processing
   199  	// requests. If nil, BaseConfig.Handler is used. If BaseConfig
   200  	// or BaseConfig.Handler is nil, http.DefaultServeMux is used.
   201  	Handler Handler
   202  
   203  	// Settings is the decoded contents of the HTTP2-Settings header
   204  	// in an h2c upgrade request.
   205  	Settings []byte
   206  
   207  	UpgradeRequest *ServerRequest
   208  
   209  	// SawClientPreface is set if the HTTP/2 connection preface
   210  	// has already been read from the connection.
   211  	SawClientPreface bool
   212  }
   213  
   214  func (o *ServeConnOpts) context() context.Context {
   215  	if o != nil && o.Context != nil {
   216  		return o.Context
   217  	}
   218  	return context.Background()
   219  }
   220  
   221  // ServeConn serves HTTP/2 requests on the provided connection and
   222  // blocks until the connection is no longer readable.
   223  //
   224  // ServeConn starts speaking HTTP/2 assuming that c has not had any
   225  // reads or writes. It writes its initial settings frame and expects
   226  // to be able to read the preface and settings frame from the
   227  // client. If c has a ConnectionState method like a *tls.Conn, the
   228  // ConnectionState is used to verify the TLS ciphersuite and to set
   229  // the Request.TLS field in Handlers.
   230  //
   231  // ServeConn does not support h2c by itself. Any h2c support must be
   232  // implemented in terms of providing a suitably-behaving net.Conn.
   233  //
   234  // The opts parameter is optional. If nil, default values are used.
   235  func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
   236  	if opts == nil {
   237  		opts = &ServeConnOpts{}
   238  	}
   239  
   240  	var newf func(*serverConn)
   241  	if inTests {
   242  		// Fetch NewConnContextKey if set, leave newf as nil otherwise.
   243  		newf, _ = opts.Context.Value(NewConnContextKey).(func(*serverConn))
   244  	}
   245  
   246  	s.serveConn(c, opts, newf)
   247  }
   248  
   249  type contextKey string
   250  
   251  var (
   252  	NewConnContextKey         = new("NewConnContextKey")
   253  	ConnectionStateContextKey = new("ConnectionStateContextKey")
   254  )
   255  
   256  func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverConn)) {
   257  	baseCtx, cancel := serverConnBaseContext(c, opts)
   258  	defer cancel()
   259  
   260  	conf := configFromServer(opts.BaseConfig)
   261  	sc := &serverConn{
   262  		srv:                         s,
   263  		hs:                          opts.BaseConfig,
   264  		conn:                        c,
   265  		baseCtx:                     baseCtx,
   266  		remoteAddrStr:               c.RemoteAddr().String(),
   267  		bw:                          newBufferedWriter(c, conf.WriteByteTimeout),
   268  		handler:                     opts.Handler,
   269  		streams:                     make(map[uint32]*stream),
   270  		readFrameCh:                 make(chan readFrameResult),
   271  		wantWriteFrameCh:            make(chan FrameWriteRequest, 8),
   272  		serveMsgCh:                  make(chan any, 8),
   273  		wroteFrameCh:                make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
   274  		bodyReadCh:                  make(chan bodyReadMsg),         // buffering doesn't matter either way
   275  		doneServing:                 make(chan struct{}),
   276  		clientMaxStreams:            math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
   277  		advMaxStreams:               uint32(conf.MaxConcurrentStreams),
   278  		initialStreamSendWindowSize: initialWindowSize,
   279  		initialStreamRecvWindowSize: int32(conf.MaxReceiveBufferPerStream),
   280  		maxFrameSize:                initialMaxFrameSize,
   281  		pingTimeout:                 conf.PingTimeout,
   282  		countErrorFunc:              conf.CountError,
   283  		serveG:                      newGoroutineLock(),
   284  		pushEnabled:                 true,
   285  		sawClientPreface:            opts.SawClientPreface,
   286  	}
   287  	if newf != nil {
   288  		newf(sc)
   289  	}
   290  
   291  	s.registerConn(sc)
   292  	defer s.unregisterConn(sc)
   293  
   294  	switch {
   295  	case sc.hs.DisableClientPriority():
   296  		sc.writeSched = newRoundRobinWriteScheduler()
   297  	default:
   298  		sc.writeSched = newPriorityWriteSchedulerRFC9218()
   299  	}
   300  
   301  	// These start at the RFC-specified defaults. If there is a higher
   302  	// configured value for inflow, that will be updated when we send a
   303  	// WINDOW_UPDATE shortly after sending SETTINGS.
   304  	sc.flow.add(initialWindowSize)
   305  	sc.inflow.init(initialWindowSize)
   306  	sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
   307  	sc.hpackEncoder.SetMaxDynamicTableSizeLimit(uint32(conf.MaxEncoderHeaderTableSize))
   308  
   309  	fr := NewFramer(sc.bw, c)
   310  	if conf.CountError != nil {
   311  		fr.countError = conf.CountError
   312  	}
   313  	fr.ReadMetaHeaders = hpack.NewDecoder(uint32(conf.MaxDecoderHeaderTableSize), nil)
   314  	fr.MaxHeaderListSize = sc.maxHeaderListSize()
   315  	fr.MaxHeaderValueCount = sc.hs.MaxHeaderValueCount()
   316  	fr.SetMaxReadFrameSize(uint32(conf.MaxReadFrameSize))
   317  	sc.framer = fr
   318  
   319  	if tc, ok := c.(connectionStater); ok {
   320  		sc.tlsState = new(tls.ConnectionState)
   321  		*sc.tlsState = tc.ConnectionState()
   322  
   323  		// Optionally override the ConnectionState in tests.
   324  		if inTests {
   325  			f, ok := opts.Context.Value(ConnectionStateContextKey).(func() tls.ConnectionState)
   326  			if ok {
   327  				*sc.tlsState = f()
   328  			}
   329  		}
   330  
   331  		// 9.2 Use of TLS Features
   332  		// An implementation of HTTP/2 over TLS MUST use TLS
   333  		// 1.2 or higher with the restrictions on feature set
   334  		// and cipher suite described in this section. Due to
   335  		// implementation limitations, it might not be
   336  		// possible to fail TLS negotiation. An endpoint MUST
   337  		// immediately terminate an HTTP/2 connection that
   338  		// does not meet the TLS requirements described in
   339  		// this section with a connection error (Section
   340  		// 5.4.1) of type INADEQUATE_SECURITY.
   341  		if sc.tlsState.Version < tls.VersionTLS12 {
   342  			sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
   343  			return
   344  		}
   345  
   346  		if sc.tlsState.ServerName == "" {
   347  			// Client must use SNI, but we don't enforce that anymore,
   348  			// since it was causing problems when connecting to bare IP
   349  			// addresses during development.
   350  			//
   351  			// TODO: optionally enforce? Or enforce at the time we receive
   352  			// a new request, and verify the ServerName matches the :authority?
   353  			// But that precludes proxy situations, perhaps.
   354  			//
   355  			// So for now, do nothing here again.
   356  		}
   357  
   358  		if !conf.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
   359  			// "Endpoints MAY choose to generate a connection error
   360  			// (Section 5.4.1) of type INADEQUATE_SECURITY if one of
   361  			// the prohibited cipher suites are negotiated."
   362  			//
   363  			// We choose that. In my opinion, the spec is weak
   364  			// here. It also says both parties must support at least
   365  			// TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
   366  			// excuses here. If we really must, we could allow an
   367  			// "AllowInsecureWeakCiphers" option on the server later.
   368  			// Let's see how it plays out first.
   369  			sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
   370  			return
   371  		}
   372  	}
   373  
   374  	if opts.Settings != nil {
   375  		fr := &SettingsFrame{
   376  			FrameHeader: FrameHeader{valid: true},
   377  			p:           opts.Settings,
   378  		}
   379  		if err := fr.ForeachSetting(sc.processSetting); err != nil {
   380  			sc.rejectConn(ErrCodeProtocol, "invalid settings")
   381  			return
   382  		}
   383  		opts.Settings = nil
   384  	}
   385  
   386  	if opts.UpgradeRequest != nil {
   387  		sc.upgradeRequest(opts.UpgradeRequest)
   388  		opts.UpgradeRequest = nil
   389  	}
   390  
   391  	sc.serve(conf)
   392  }
   393  
   394  func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func()) {
   395  	return context.WithCancel(opts.context())
   396  }
   397  
   398  func (sc *serverConn) rejectConn(err ErrCode, debug string) {
   399  	sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
   400  	// ignoring errors. hanging up anyway.
   401  	sc.framer.WriteGoAway(0, err, []byte(debug))
   402  	sc.bw.Flush()
   403  	sc.conn.Close()
   404  }
   405  
   406  type serverConn struct {
   407  	// Immutable:
   408  	srv              *Server
   409  	hs               ServerConfig
   410  	conn             net.Conn
   411  	bw               *bufferedWriter // writing to conn
   412  	handler          Handler
   413  	baseCtx          context.Context
   414  	framer           *Framer
   415  	doneServing      chan struct{}          // closed when serverConn.serve ends
   416  	readFrameCh      chan readFrameResult   // written by serverConn.readFrames
   417  	wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
   418  	wroteFrameCh     chan frameWriteResult  // from writeFrameAsync -> serve, tickles more frame writes
   419  	bodyReadCh       chan bodyReadMsg       // from handlers -> serve
   420  	serveMsgCh       chan any               // misc messages & code to send to / run on the serve loop
   421  	flow             outflow                // conn-wide (not stream-specific) outbound flow control
   422  	inflow           inflow                 // conn-wide inbound flow control
   423  	tlsState         *tls.ConnectionState   // shared by all handlers, like net/http
   424  	remoteAddrStr    string
   425  	writeSched       WriteScheduler
   426  	countErrorFunc   func(errType string)
   427  
   428  	// Everything following is owned by the serve loop; use serveG.check():
   429  	serveG                      goroutineLock // used to verify funcs are on serve()
   430  	pushEnabled                 bool
   431  	sawClientPreface            bool // preface has already been read, used in h2c upgrade
   432  	sawFirstSettings            bool // got the initial SETTINGS frame after the preface
   433  	needToSendSettingsAck       bool
   434  	unackedSettings             int    // how many SETTINGS have we sent without ACKs?
   435  	queuedControlFrames         int    // control frames in the writeSched queue
   436  	clientMaxStreams            uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
   437  	advMaxStreams               uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
   438  	curClientStreams            uint32 // number of open streams initiated by the client
   439  	curPushedStreams            uint32 // number of open streams initiated by server push
   440  	curHandlers                 uint32 // number of running handler goroutines
   441  	maxClientStreamID           uint32 // max ever seen from client (odd), or 0 if there have been no client requests
   442  	maxPushPromiseID            uint32 // ID of the last push promise (even), or 0 if there have been no pushes
   443  	streams                     map[uint32]*stream
   444  	unstartedHandlers           []unstartedHandler
   445  	initialStreamSendWindowSize int32
   446  	initialStreamRecvWindowSize int32
   447  	maxFrameSize                int32
   448  	peerMaxHeaderListSize       uint32            // zero means unknown (default)
   449  	canonHeader                 map[string]string // http2-lower-case -> Go-Canonical-Case
   450  	canonHeaderKeysSize         int               // canonHeader keys size in bytes
   451  	writingFrame                bool              // started writing a frame (on serve goroutine or separate)
   452  	writingFrameAsync           bool              // started a frame on its own goroutine but haven't heard back on wroteFrameCh
   453  	needsFrameFlush             bool              // last frame write wasn't a flush
   454  	inGoAway                    bool              // we've started to or sent GOAWAY
   455  	inFrameScheduleLoop         bool              // whether we're in the scheduleFrameWrite loop
   456  	needToSendGoAway            bool              // we need to schedule a GOAWAY frame write
   457  	pingSent                    bool
   458  	sentPingData                [8]byte
   459  	goAwayCode                  ErrCode
   460  	shutdownTimer               *time.Timer // nil until used
   461  	idleTimer                   *time.Timer // nil if unused
   462  	readIdleTimeout             time.Duration
   463  	pingTimeout                 time.Duration
   464  	readIdleTimer               *time.Timer // nil if unused
   465  
   466  	// Owned by the writeFrameAsync goroutine:
   467  	headerWriteBuf bytes.Buffer
   468  	hpackEncoder   *hpack.Encoder
   469  
   470  	// Used by startGracefulShutdown.
   471  	shutdownOnce sync.Once
   472  
   473  	// Used for RFC 9218 prioritization.
   474  	hasIntermediary bool // connection is done via an intermediary / proxy
   475  	priorityAware   bool // the client has sent priority signal, meaning that it is aware of it.
   476  }
   477  
   478  func (sc *serverConn) writeSchedIgnoresRFC7540() bool {
   479  	switch sc.writeSched.(type) {
   480  	case *priorityWriteSchedulerRFC9218:
   481  		return true
   482  	case *roundRobinWriteScheduler:
   483  		return true
   484  	default:
   485  		return false
   486  	}
   487  }
   488  
   489  const DefaultMaxHeaderBytes = 1 << 20 // keep this in sync with net/http
   490  
   491  func (sc *serverConn) maxHeaderListSize() uint32 {
   492  	n := sc.hs.MaxHeaderBytes()
   493  	if n <= 0 {
   494  		n = DefaultMaxHeaderBytes
   495  	}
   496  	return uint32(adjustHTTP1MaxHeaderSize(int64(n)))
   497  }
   498  
   499  func (sc *serverConn) curOpenStreams() uint32 {
   500  	sc.serveG.check()
   501  	return sc.curClientStreams + sc.curPushedStreams
   502  }
   503  
   504  // stream represents a stream. This is the minimal metadata needed by
   505  // the serve goroutine. Most of the actual stream state is owned by
   506  // the http.Handler's goroutine in the responseWriter. Because the
   507  // responseWriter's responseWriterState is recycled at the end of a
   508  // handler, this struct intentionally has no pointer to the
   509  // *responseWriter{,State} itself, as the Handler ending nils out the
   510  // responseWriter's state field.
   511  type stream struct {
   512  	// immutable:
   513  	sc        *serverConn
   514  	id        uint32
   515  	body      *pipe       // non-nil if expecting DATA frames
   516  	cw        closeWaiter // closed wait stream transitions to closed state
   517  	ctx       context.Context
   518  	cancelCtx func()
   519  
   520  	// owned by serverConn's serve loop:
   521  	bodyBytes        int64   // body bytes seen so far
   522  	declBodyBytes    int64   // or -1 if undeclared
   523  	flow             outflow // limits writing from Handler to client
   524  	inflow           inflow  // what the client is allowed to POST/etc to us
   525  	state            streamState
   526  	resetQueued      bool        // RST_STREAM queued for write; set by sc.resetStream
   527  	gotTrailerHeader bool        // HEADER frame for trailers was seen
   528  	wroteHeaders     bool        // whether we wrote headers (not status 100)
   529  	readDeadline     *time.Timer // nil if unused
   530  	writeDeadline    *time.Timer // nil if unused
   531  	closeErr         error       // set before cw is closed
   532  
   533  	trailer    Header // accumulated trailers
   534  	reqTrailer Header // handler's Request.Trailer
   535  }
   536  
   537  func (sc *serverConn) Framer() *Framer  { return sc.framer }
   538  func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
   539  func (sc *serverConn) Flush() error     { return sc.bw.Flush() }
   540  func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
   541  	return sc.hpackEncoder, &sc.headerWriteBuf
   542  }
   543  
   544  func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
   545  	sc.serveG.check()
   546  	// http://tools.ietf.org/html/rfc7540#section-5.1
   547  	if st, ok := sc.streams[streamID]; ok {
   548  		return st.state, st
   549  	}
   550  	// "The first use of a new stream identifier implicitly closes all
   551  	// streams in the "idle" state that might have been initiated by
   552  	// that peer with a lower-valued stream identifier. For example, if
   553  	// a client sends a HEADERS frame on stream 7 without ever sending a
   554  	// frame on stream 5, then stream 5 transitions to the "closed"
   555  	// state when the first frame for stream 7 is sent or received."
   556  	if streamID%2 == 1 {
   557  		if streamID <= sc.maxClientStreamID {
   558  			return stateClosed, nil
   559  		}
   560  	} else {
   561  		if streamID <= sc.maxPushPromiseID {
   562  			return stateClosed, nil
   563  		}
   564  	}
   565  	return stateIdle, nil
   566  }
   567  
   568  // setConnState calls the net/http ConnState hook for this connection, if configured.
   569  // Note that the net/http package does StateNew and StateClosed for us.
   570  // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
   571  func (sc *serverConn) setConnState(state ConnState) {
   572  	sc.hs.ConnState(sc.conn, state)
   573  }
   574  
   575  func (sc *serverConn) vlogf(format string, args ...any) {
   576  	if VerboseLogs {
   577  		sc.logf(format, args...)
   578  	}
   579  }
   580  
   581  func (sc *serverConn) logf(format string, args ...any) {
   582  	if lg := sc.hs.ErrorLog(); lg != nil {
   583  		lg.Printf(format, args...)
   584  	} else {
   585  		log.Printf(format, args...)
   586  	}
   587  }
   588  
   589  // errno returns v's underlying uintptr, else 0.
   590  //
   591  // TODO: remove this helper function once http2 can use build
   592  // tags. See comment in isClosedConnError.
   593  func errno(v error) uintptr {
   594  	if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
   595  		return uintptr(rv.Uint())
   596  	}
   597  	return 0
   598  }
   599  
   600  // isClosedConnError reports whether err is an error from use of a closed
   601  // network connection.
   602  func isClosedConnError(err error) bool {
   603  	if err == nil {
   604  		return false
   605  	}
   606  
   607  	if errors.Is(err, net.ErrClosed) {
   608  		return true
   609  	}
   610  
   611  	// TODO(bradfitz): x/tools/cmd/bundle doesn't really support
   612  	// build tags, so I can't make an http2_windows.go file with
   613  	// Windows-specific stuff. Fix that and move this, once we
   614  	// have a way to bundle this into std's net/http somehow.
   615  	if runtime.GOOS == "windows" {
   616  		if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
   617  			if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
   618  				const WSAECONNABORTED = 10053
   619  				const WSAECONNRESET = 10054
   620  				if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
   621  					return true
   622  				}
   623  			}
   624  		}
   625  	}
   626  	return false
   627  }
   628  
   629  func (sc *serverConn) condlogf(err error, format string, args ...any) {
   630  	if err == nil {
   631  		return
   632  	}
   633  	if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout {
   634  		// Boring, expected errors.
   635  		sc.vlogf(format, args...)
   636  	} else {
   637  		sc.logf(format, args...)
   638  	}
   639  }
   640  
   641  // maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
   642  // of the entries in the canonHeader cache.
   643  // This should be larger than the size of unique, uncommon header keys likely to
   644  // be sent by the peer, while not so high as to permit unreasonable memory usage
   645  // if the peer sends an unbounded number of unique header keys.
   646  const maxCachedCanonicalHeadersKeysSize = 2048
   647  
   648  func (sc *serverConn) canonicalHeader(v string) string {
   649  	sc.serveG.check()
   650  	cv, ok := httpcommon.CachedCanonicalHeader(v)
   651  	if ok {
   652  		return cv
   653  	}
   654  	cv, ok = sc.canonHeader[v]
   655  	if ok {
   656  		return cv
   657  	}
   658  	if sc.canonHeader == nil {
   659  		sc.canonHeader = make(map[string]string)
   660  	}
   661  	cv = textproto.CanonicalMIMEHeaderKey(v)
   662  	size := 100 + len(v)*2 // 100 bytes of map overhead + key + value
   663  	if sc.canonHeaderKeysSize+size <= maxCachedCanonicalHeadersKeysSize {
   664  		sc.canonHeader[v] = cv
   665  		sc.canonHeaderKeysSize += size
   666  	}
   667  	return cv
   668  }
   669  
   670  type readFrameResult struct {
   671  	f   Frame // valid until readMore is called
   672  	err error
   673  
   674  	// readMore should be called once the consumer no longer needs or
   675  	// retains f. After readMore, f is invalid and more frames can be
   676  	// read.
   677  	readMore func()
   678  }
   679  
   680  // readFrames is the loop that reads incoming frames.
   681  // It takes care to only read one frame at a time, blocking until the
   682  // consumer is done with the frame.
   683  // It's run on its own goroutine.
   684  func (sc *serverConn) readFrames() {
   685  	gate := make(chan struct{})
   686  	gateDone := func() { gate <- struct{}{} }
   687  	for {
   688  		f, err := sc.framer.ReadFrame()
   689  		select {
   690  		case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
   691  		case <-sc.doneServing:
   692  			return
   693  		}
   694  		select {
   695  		case <-gate:
   696  		case <-sc.doneServing:
   697  			return
   698  		}
   699  		if terminalReadFrameError(err) {
   700  			return
   701  		}
   702  	}
   703  }
   704  
   705  // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
   706  type frameWriteResult struct {
   707  	_   incomparable
   708  	wr  FrameWriteRequest // what was written (or attempted)
   709  	err error             // result of the writeFrame call
   710  }
   711  
   712  // writeFrameAsync runs in its own goroutine and writes a single frame
   713  // and then reports when it's done.
   714  // At most one goroutine can be running writeFrameAsync at a time per
   715  // serverConn.
   716  func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest, wd *writeData) {
   717  	var err error
   718  	if wd == nil {
   719  		err = wr.write.writeFrame(sc)
   720  	} else {
   721  		err = sc.framer.endWrite()
   722  	}
   723  	sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err}
   724  }
   725  
   726  func (sc *serverConn) closeAllStreamsOnConnClose() {
   727  	sc.serveG.check()
   728  	for _, st := range sc.streams {
   729  		sc.closeStream(st, errClientDisconnected)
   730  	}
   731  }
   732  
   733  func (sc *serverConn) stopShutdownTimer() {
   734  	sc.serveG.check()
   735  	if t := sc.shutdownTimer; t != nil {
   736  		t.Stop()
   737  	}
   738  }
   739  
   740  func (sc *serverConn) notePanic() {
   741  	// Note: this is for serverConn.serve panicking, not http.Handler code.
   742  	if testHookOnPanicMu != nil {
   743  		testHookOnPanicMu.Lock()
   744  		defer testHookOnPanicMu.Unlock()
   745  	}
   746  	if testHookOnPanic != nil {
   747  		if e := recover(); e != nil {
   748  			if testHookOnPanic(sc, e) {
   749  				panic(e)
   750  			}
   751  		}
   752  	}
   753  }
   754  
   755  func (sc *serverConn) serve(conf Config) {
   756  	sc.serveG.check()
   757  	defer sc.notePanic()
   758  	defer sc.conn.Close()
   759  	defer sc.closeAllStreamsOnConnClose()
   760  	defer sc.stopShutdownTimer()
   761  	defer close(sc.doneServing) // unblocks handlers trying to send
   762  
   763  	if VerboseLogs {
   764  		sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
   765  	}
   766  
   767  	settings := writeSettings{
   768  		{SettingMaxFrameSize, uint32(conf.MaxReadFrameSize)},
   769  		{SettingMaxConcurrentStreams, sc.advMaxStreams},
   770  		{SettingMaxHeaderListSize, sc.maxHeaderListSize()},
   771  		{SettingHeaderTableSize, uint32(conf.MaxDecoderHeaderTableSize)},
   772  		{SettingInitialWindowSize, uint32(sc.initialStreamRecvWindowSize)},
   773  	}
   774  	if !disableExtendedConnectProtocol {
   775  		settings = append(settings, Setting{SettingEnableConnectProtocol, 1})
   776  	}
   777  	if sc.writeSchedIgnoresRFC7540() {
   778  		settings = append(settings, Setting{SettingNoRFC7540Priorities, 1})
   779  	}
   780  	sc.writeFrame(FrameWriteRequest{
   781  		write: settings,
   782  	})
   783  	sc.unackedSettings++
   784  
   785  	// Each connection starts with initialWindowSize inflow tokens.
   786  	// If a higher value is configured, we add more tokens.
   787  	if diff := conf.MaxReceiveBufferPerConnection - initialWindowSize; diff > 0 {
   788  		sc.sendWindowUpdate(nil, int(diff))
   789  	}
   790  
   791  	if err := sc.readPreface(); err != nil {
   792  		sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
   793  		return
   794  	}
   795  	// Now that we've got the preface, get us out of the
   796  	// "StateNew" state. We can't go directly to idle, though.
   797  	// Active means we read some data and anticipate a request. We'll
   798  	// do another Active when we get a HEADERS frame.
   799  	sc.setConnState(ConnStateActive)
   800  	sc.setConnState(ConnStateIdle)
   801  
   802  	if idle := sc.hs.IdleTimeout(); idle > 0 {
   803  		sc.idleTimer = time.AfterFunc(idle, sc.onIdleTimer)
   804  		defer sc.idleTimer.Stop()
   805  	}
   806  
   807  	if conf.SendPingTimeout > 0 {
   808  		sc.readIdleTimeout = conf.SendPingTimeout
   809  		sc.readIdleTimer = time.AfterFunc(conf.SendPingTimeout, sc.onReadIdleTimer)
   810  		defer sc.readIdleTimer.Stop()
   811  	}
   812  
   813  	go sc.readFrames() // closed by defer sc.conn.Close above
   814  
   815  	settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
   816  	defer settingsTimer.Stop()
   817  
   818  	lastFrameTime := time.Now()
   819  	loopNum := 0
   820  	for {
   821  		loopNum++
   822  		select {
   823  		case wr := <-sc.wantWriteFrameCh:
   824  			if se, ok := wr.write.(StreamError); ok {
   825  				sc.resetStream(se)
   826  				break
   827  			}
   828  			sc.writeFrame(wr)
   829  		case res := <-sc.wroteFrameCh:
   830  			sc.wroteFrame(res)
   831  		case res := <-sc.readFrameCh:
   832  			lastFrameTime = time.Now()
   833  			// Process any written frames before reading new frames from the client since a
   834  			// written frame could have triggered a new stream to be started.
   835  			if sc.writingFrameAsync {
   836  				select {
   837  				case wroteRes := <-sc.wroteFrameCh:
   838  					sc.wroteFrame(wroteRes)
   839  				default:
   840  				}
   841  			}
   842  			if !sc.processFrameFromReader(res) {
   843  				return
   844  			}
   845  			res.readMore()
   846  			if settingsTimer != nil {
   847  				settingsTimer.Stop()
   848  				settingsTimer = nil
   849  			}
   850  		case m := <-sc.bodyReadCh:
   851  			sc.noteBodyRead(m.st, m.n)
   852  		case msg := <-sc.serveMsgCh:
   853  			switch v := msg.(type) {
   854  			case func(int):
   855  				v(loopNum) // for testing
   856  			case *serverMessage:
   857  				switch v {
   858  				case settingsTimerMsg:
   859  					sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
   860  					return
   861  				case idleTimerMsg:
   862  					sc.vlogf("connection is idle")
   863  					sc.goAway(ErrCodeNo)
   864  				case readIdleTimerMsg:
   865  					sc.handlePingTimer(lastFrameTime)
   866  				case shutdownTimerMsg:
   867  					sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
   868  					return
   869  				case gracefulShutdownMsg:
   870  					sc.startGracefulShutdownInternal()
   871  				case handlerDoneMsg:
   872  					sc.handlerDone()
   873  				default:
   874  					panic("unknown timer")
   875  				}
   876  			case *startPushRequest:
   877  				sc.startPush(v)
   878  			case func(*serverConn):
   879  				v(sc)
   880  			default:
   881  				panic(fmt.Sprintf("unexpected type %T", v))
   882  			}
   883  		}
   884  
   885  		// If the peer is causing us to generate a lot of control frames,
   886  		// but not reading them from us, assume they are trying to make us
   887  		// run out of memory.
   888  		if sc.queuedControlFrames > maxQueuedControlFrames {
   889  			sc.vlogf("http2: too many control frames in send queue, closing connection")
   890  			return
   891  		}
   892  
   893  		// Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
   894  		// with no error code (graceful shutdown), don't start the timer until
   895  		// all open streams have been completed.
   896  		sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
   897  		gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
   898  		if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
   899  			sc.shutDownIn(goAwayTimeout)
   900  		}
   901  	}
   902  }
   903  
   904  func (sc *serverConn) handlePingTimer(lastFrameReadTime time.Time) {
   905  	if sc.pingSent {
   906  		sc.logf("timeout waiting for PING response")
   907  		if f := sc.countErrorFunc; f != nil {
   908  			f("conn_close_lost_ping")
   909  		}
   910  		sc.conn.Close()
   911  		return
   912  	}
   913  
   914  	pingAt := lastFrameReadTime.Add(sc.readIdleTimeout)
   915  	now := time.Now()
   916  	if pingAt.After(now) {
   917  		// We received frames since arming the ping timer.
   918  		// Reset it for the next possible timeout.
   919  		sc.readIdleTimer.Reset(pingAt.Sub(now))
   920  		return
   921  	}
   922  
   923  	sc.pingSent = true
   924  	// Ignore crypto/rand.Read errors: It generally can't fail, and worse case if it does
   925  	// is we send a PING frame containing 0s.
   926  	_, _ = rand.Read(sc.sentPingData[:])
   927  	sc.writeFrame(FrameWriteRequest{
   928  		write: &writePing{data: sc.sentPingData},
   929  	})
   930  	sc.readIdleTimer.Reset(sc.pingTimeout)
   931  }
   932  
   933  type serverMessage int
   934  
   935  // Message values sent to serveMsgCh.
   936  var (
   937  	settingsTimerMsg    = new(serverMessage)
   938  	idleTimerMsg        = new(serverMessage)
   939  	readIdleTimerMsg    = new(serverMessage)
   940  	shutdownTimerMsg    = new(serverMessage)
   941  	gracefulShutdownMsg = new(serverMessage)
   942  	handlerDoneMsg      = new(serverMessage)
   943  )
   944  
   945  func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
   946  func (sc *serverConn) onIdleTimer()     { sc.sendServeMsg(idleTimerMsg) }
   947  func (sc *serverConn) onReadIdleTimer() { sc.sendServeMsg(readIdleTimerMsg) }
   948  func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
   949  
   950  func (sc *serverConn) sendServeMsg(msg any) {
   951  	sc.serveG.checkNotOn() // NOT
   952  	select {
   953  	case sc.serveMsgCh <- msg:
   954  	case <-sc.doneServing:
   955  	}
   956  }
   957  
   958  var errPrefaceTimeout = errors.New("timeout waiting for client preface")
   959  
   960  // readPreface reads the ClientPreface greeting from the peer or
   961  // returns errPrefaceTimeout on timeout, or an error if the greeting
   962  // is invalid.
   963  func (sc *serverConn) readPreface() error {
   964  	if sc.sawClientPreface {
   965  		return nil
   966  	}
   967  	errc := make(chan error, 1)
   968  	go func() {
   969  		// Read the client preface
   970  		buf := make([]byte, len(ClientPreface))
   971  		if _, err := io.ReadFull(sc.conn, buf); err != nil {
   972  			errc <- err
   973  		} else if !bytes.Equal(buf, clientPreface) {
   974  			errc <- fmt.Errorf("bogus greeting %q", buf)
   975  		} else {
   976  			errc <- nil
   977  		}
   978  	}()
   979  	timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
   980  	defer timer.Stop()
   981  	select {
   982  	case <-timer.C:
   983  		return errPrefaceTimeout
   984  	case err := <-errc:
   985  		if err == nil {
   986  			if VerboseLogs {
   987  				sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
   988  			}
   989  		}
   990  		return err
   991  	}
   992  }
   993  
   994  var writeDataPool = sync.Pool{
   995  	New: func() any { return new(writeData) },
   996  }
   997  
   998  // writeDataFromHandler writes DATA response frames from a handler on
   999  // the given stream.
  1000  func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  1001  	ch := sc.srv.getErrChan()
  1002  	writeArg := writeDataPool.Get().(*writeData)
  1003  	*writeArg = writeData{stream.id, data, endStream}
  1004  	err := sc.writeFrameFromHandler(FrameWriteRequest{
  1005  		write:  writeArg,
  1006  		stream: stream,
  1007  		done:   ch,
  1008  	})
  1009  	if err != nil {
  1010  		return err
  1011  	}
  1012  	var frameWriteDone bool // the frame write is done (successfully or not)
  1013  	select {
  1014  	case err = <-ch:
  1015  		frameWriteDone = true
  1016  	case <-sc.doneServing:
  1017  		return errClientDisconnected
  1018  	case <-stream.cw:
  1019  		// If both ch and stream.cw were ready (as might
  1020  		// happen on the final Write after an http.Handler
  1021  		// ends), prefer the write result. Otherwise this
  1022  		// might just be us successfully closing the stream.
  1023  		// The writeFrameAsync and serve goroutines guarantee
  1024  		// that the ch send will happen before the stream.cw
  1025  		// close.
  1026  		select {
  1027  		case err = <-ch:
  1028  			frameWriteDone = true
  1029  		default:
  1030  			return errStreamClosed
  1031  		}
  1032  	}
  1033  	sc.srv.putErrChan(ch)
  1034  	if frameWriteDone {
  1035  		writeDataPool.Put(writeArg)
  1036  	}
  1037  	return err
  1038  }
  1039  
  1040  // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
  1041  // if the connection has gone away.
  1042  //
  1043  // This must not be run from the serve goroutine itself, else it might
  1044  // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  1045  // buffered and is read by serve itself). If you're on the serve
  1046  // goroutine, call writeFrame instead.
  1047  func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
  1048  	sc.serveG.checkNotOn() // NOT
  1049  	select {
  1050  	case sc.wantWriteFrameCh <- wr:
  1051  		return nil
  1052  	case <-sc.doneServing:
  1053  		// Serve loop is gone.
  1054  		// Client has closed their connection to the server.
  1055  		return errClientDisconnected
  1056  	}
  1057  }
  1058  
  1059  // writeFrame schedules a frame to write and sends it if there's nothing
  1060  // already being written.
  1061  //
  1062  // There is no pushback here (the serve goroutine never blocks). It's
  1063  // the http.Handlers that block, waiting for their previous frames to
  1064  // make it onto the wire
  1065  //
  1066  // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  1067  func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
  1068  	sc.serveG.check()
  1069  
  1070  	// If true, wr will not be written and wr.done will not be signaled.
  1071  	var ignoreWrite bool
  1072  
  1073  	// We are not allowed to write frames on closed streams. RFC 7540 Section
  1074  	// 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
  1075  	// a closed stream." Our server never sends PRIORITY, so that exception
  1076  	// does not apply.
  1077  	//
  1078  	// The serverConn might close an open stream while the stream's handler
  1079  	// is still running. For example, the server might close a stream when it
  1080  	// receives bad data from the client. If this happens, the handler might
  1081  	// attempt to write a frame after the stream has been closed (since the
  1082  	// handler hasn't yet been notified of the close). In this case, we simply
  1083  	// ignore the frame. The handler will notice that the stream is closed when
  1084  	// it waits for the frame to be written.
  1085  	//
  1086  	// As an exception to this rule, we allow sending RST_STREAM after close.
  1087  	// This allows us to immediately reject new streams without tracking any
  1088  	// state for those streams (except for the queued RST_STREAM frame). This
  1089  	// may result in duplicate RST_STREAMs in some cases, but the client should
  1090  	// ignore those.
  1091  	if wr.StreamID() != 0 {
  1092  		_, isReset := wr.write.(StreamError)
  1093  		if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
  1094  			ignoreWrite = true
  1095  		}
  1096  	}
  1097  
  1098  	// Don't send a 100-continue response if we've already sent headers.
  1099  	// See golang.org/issue/14030.
  1100  	switch wr.write.(type) {
  1101  	case *writeResHeaders:
  1102  		wr.stream.wroteHeaders = true
  1103  	case write100ContinueHeadersFrame:
  1104  		if wr.stream.wroteHeaders {
  1105  			// We do not need to notify wr.done because this frame is
  1106  			// never written with wr.done != nil.
  1107  			if wr.done != nil {
  1108  				panic("wr.done != nil for write100ContinueHeadersFrame")
  1109  			}
  1110  			ignoreWrite = true
  1111  		}
  1112  	}
  1113  
  1114  	if !ignoreWrite {
  1115  		if wr.isControl() {
  1116  			sc.queuedControlFrames++
  1117  			// For extra safety, detect wraparounds, which should not happen,
  1118  			// and pull the plug.
  1119  			if sc.queuedControlFrames < 0 {
  1120  				sc.conn.Close()
  1121  			}
  1122  		}
  1123  		sc.writeSched.Push(wr)
  1124  	}
  1125  	sc.scheduleFrameWrite()
  1126  }
  1127  
  1128  // startFrameWrite starts a goroutine to write wr (in a separate
  1129  // goroutine since that might block on the network), and updates the
  1130  // serve goroutine's state about the world, updated from info in wr.
  1131  func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
  1132  	sc.serveG.check()
  1133  	if sc.writingFrame {
  1134  		panic("internal error: can only be writing one frame at a time")
  1135  	}
  1136  
  1137  	st := wr.stream
  1138  	if st != nil {
  1139  		switch st.state {
  1140  		case stateHalfClosedLocal:
  1141  			switch wr.write.(type) {
  1142  			case StreamError, handlerPanicRST, writeWindowUpdate:
  1143  				// RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
  1144  				// in this state. (We never send PRIORITY from the server, so that is not checked.)
  1145  			default:
  1146  				panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
  1147  			}
  1148  		case stateClosed:
  1149  			panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
  1150  		}
  1151  	}
  1152  	if wpp, ok := wr.write.(*writePushPromise); ok {
  1153  		var err error
  1154  		wpp.promisedID, err = wpp.allocatePromisedID()
  1155  		if err != nil {
  1156  			sc.writingFrameAsync = false
  1157  			wr.replyToWriter(err)
  1158  			return
  1159  		}
  1160  	}
  1161  
  1162  	sc.writingFrame = true
  1163  	sc.needsFrameFlush = true
  1164  	if wr.write.staysWithinBuffer(sc.bw.Available()) {
  1165  		sc.writingFrameAsync = false
  1166  		err := wr.write.writeFrame(sc)
  1167  		sc.wroteFrame(frameWriteResult{wr: wr, err: err})
  1168  	} else if wd, ok := wr.write.(*writeData); ok {
  1169  		// Encode the frame in the serve goroutine, to ensure we don't have
  1170  		// any lingering asynchronous references to data passed to Write.
  1171  		// See https://go.dev/issue/58446.
  1172  		sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
  1173  		sc.writingFrameAsync = true
  1174  		go sc.writeFrameAsync(wr, wd)
  1175  	} else {
  1176  		sc.writingFrameAsync = true
  1177  		go sc.writeFrameAsync(wr, nil)
  1178  	}
  1179  }
  1180  
  1181  // errHandlerPanicked is the error given to any callers blocked in a read from
  1182  // Request.Body when the main goroutine panics. Since most handlers read in the
  1183  // main ServeHTTP goroutine, this will show up rarely.
  1184  var errHandlerPanicked = errors.New("http2: handler panicked")
  1185  
  1186  // wroteFrame is called on the serve goroutine with the result of
  1187  // whatever happened on writeFrameAsync.
  1188  func (sc *serverConn) wroteFrame(res frameWriteResult) {
  1189  	sc.serveG.check()
  1190  	if !sc.writingFrame {
  1191  		panic("internal error: expected to be already writing a frame")
  1192  	}
  1193  	sc.writingFrame = false
  1194  	sc.writingFrameAsync = false
  1195  
  1196  	if res.err != nil {
  1197  		sc.conn.Close()
  1198  	}
  1199  
  1200  	wr := res.wr
  1201  
  1202  	if writeEndsStream(wr.write) {
  1203  		st := wr.stream
  1204  		if st == nil {
  1205  			panic("internal error: expecting non-nil stream")
  1206  		}
  1207  		switch st.state {
  1208  		case stateOpen:
  1209  			// Here we would go to stateHalfClosedLocal in
  1210  			// theory, but since our handler is done and
  1211  			// the net/http package provides no mechanism
  1212  			// for closing a ResponseWriter while still
  1213  			// reading data (see possible TODO at top of
  1214  			// this file), we go into closed state here
  1215  			// anyway, after telling the peer we're
  1216  			// hanging up on them. We'll transition to
  1217  			// stateClosed after the RST_STREAM frame is
  1218  			// written.
  1219  			st.state = stateHalfClosedLocal
  1220  			// Section 8.1: a server MAY request that the client abort
  1221  			// transmission of a request without error by sending a
  1222  			// RST_STREAM with an error code of NO_ERROR after sending
  1223  			// a complete response.
  1224  			sc.resetStream(streamError(st.id, ErrCodeNo))
  1225  		case stateHalfClosedRemote:
  1226  			sc.closeStream(st, errHandlerComplete)
  1227  		}
  1228  	} else {
  1229  		switch v := wr.write.(type) {
  1230  		case StreamError:
  1231  			// st may be unknown if the RST_STREAM was generated to reject bad input.
  1232  			if st, ok := sc.streams[v.StreamID]; ok {
  1233  				sc.closeStream(st, v)
  1234  			}
  1235  		case handlerPanicRST:
  1236  			sc.closeStream(wr.stream, errHandlerPanicked)
  1237  		}
  1238  	}
  1239  
  1240  	// Reply (if requested) to unblock the ServeHTTP goroutine.
  1241  	wr.replyToWriter(res.err)
  1242  
  1243  	sc.scheduleFrameWrite()
  1244  }
  1245  
  1246  // scheduleFrameWrite tickles the frame writing scheduler.
  1247  //
  1248  // If a frame is already being written, nothing happens. This will be called again
  1249  // when the frame is done being written.
  1250  //
  1251  // If a frame isn't being written and we need to send one, the best frame
  1252  // to send is selected by writeSched.
  1253  //
  1254  // If a frame isn't being written and there's nothing else to send, we
  1255  // flush the write buffer.
  1256  func (sc *serverConn) scheduleFrameWrite() {
  1257  	sc.serveG.check()
  1258  	if sc.writingFrame || sc.inFrameScheduleLoop {
  1259  		return
  1260  	}
  1261  	sc.inFrameScheduleLoop = true
  1262  	for !sc.writingFrameAsync {
  1263  		if sc.needToSendGoAway {
  1264  			sc.needToSendGoAway = false
  1265  			sc.startFrameWrite(FrameWriteRequest{
  1266  				write: &writeGoAway{
  1267  					maxStreamID: sc.maxClientStreamID,
  1268  					code:        sc.goAwayCode,
  1269  				},
  1270  			})
  1271  			continue
  1272  		}
  1273  		if sc.needToSendSettingsAck {
  1274  			sc.needToSendSettingsAck = false
  1275  			sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  1276  			continue
  1277  		}
  1278  		if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
  1279  			if wr, ok := sc.writeSched.Pop(); ok {
  1280  				if wr.isControl() {
  1281  					sc.queuedControlFrames--
  1282  				}
  1283  				sc.startFrameWrite(wr)
  1284  				continue
  1285  			}
  1286  		}
  1287  		if sc.needsFrameFlush {
  1288  			sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  1289  			sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  1290  			continue
  1291  		}
  1292  		break
  1293  	}
  1294  	sc.inFrameScheduleLoop = false
  1295  }
  1296  
  1297  // startGracefulShutdown gracefully shuts down a connection. This
  1298  // sends GOAWAY with ErrCodeNo to tell the client we're gracefully
  1299  // shutting down. The connection isn't closed until all current
  1300  // streams are done.
  1301  //
  1302  // startGracefulShutdown returns immediately; it does not wait until
  1303  // the connection has shut down.
  1304  func (sc *serverConn) startGracefulShutdown() {
  1305  	sc.serveG.checkNotOn() // NOT
  1306  	sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
  1307  }
  1308  
  1309  // After sending GOAWAY with an error code (non-graceful shutdown), the
  1310  // connection will close after goAwayTimeout.
  1311  //
  1312  // If we close the connection immediately after sending GOAWAY, there may
  1313  // be unsent data in our kernel receive buffer, which will cause the kernel
  1314  // to send a TCP RST on close() instead of a FIN. This RST will abort the
  1315  // connection immediately, whether or not the client had received the GOAWAY.
  1316  //
  1317  // Ideally we should delay for at least 1 RTT + epsilon so the client has
  1318  // a chance to read the GOAWAY and stop sending messages. Measuring RTT
  1319  // is hard, so we approximate with 1 second. See golang.org/issue/18701.
  1320  //
  1321  // This is a var so it can be shorter in tests, where all requests uses the
  1322  // loopback interface making the expected RTT very small.
  1323  //
  1324  // TODO: configurable?
  1325  var goAwayTimeout = 1 * time.Second
  1326  
  1327  func (sc *serverConn) startGracefulShutdownInternal() {
  1328  	sc.goAway(ErrCodeNo)
  1329  }
  1330  
  1331  func (sc *serverConn) goAway(code ErrCode) {
  1332  	sc.serveG.check()
  1333  	if sc.inGoAway {
  1334  		if sc.goAwayCode == ErrCodeNo {
  1335  			sc.goAwayCode = code
  1336  		}
  1337  		return
  1338  	}
  1339  	sc.inGoAway = true
  1340  	sc.needToSendGoAway = true
  1341  	sc.goAwayCode = code
  1342  	sc.scheduleFrameWrite()
  1343  }
  1344  
  1345  func (sc *serverConn) shutDownIn(d time.Duration) {
  1346  	sc.serveG.check()
  1347  	sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
  1348  }
  1349  
  1350  func (sc *serverConn) resetStream(se StreamError) {
  1351  	sc.serveG.check()
  1352  	sc.writeFrame(FrameWriteRequest{write: se})
  1353  	if st, ok := sc.streams[se.StreamID]; ok {
  1354  		st.resetQueued = true
  1355  	}
  1356  }
  1357  
  1358  // processFrameFromReader processes the serve loop's read from readFrameCh from the
  1359  // frame-reading goroutine.
  1360  // processFrameFromReader returns whether the connection should be kept open.
  1361  func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  1362  	sc.serveG.check()
  1363  	err := res.err
  1364  	if err != nil {
  1365  		if err == ErrFrameTooLarge {
  1366  			sc.goAway(ErrCodeFrameSize)
  1367  			return true // goAway will close the loop
  1368  		}
  1369  		clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  1370  		if clientGone {
  1371  			// TODO: could we also get into this state if
  1372  			// the peer does a half close
  1373  			// (e.g. CloseWrite) because they're done
  1374  			// sending frames but they're still wanting
  1375  			// our open replies?  Investigate.
  1376  			// TODO: add CloseWrite to crypto/tls.Conn first
  1377  			// so we have a way to test this? I suppose
  1378  			// just for testing we could have a non-TLS mode.
  1379  			return false
  1380  		}
  1381  	} else {
  1382  		f := res.f
  1383  		if VerboseLogs {
  1384  			sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1385  		}
  1386  		err = sc.processFrame(f)
  1387  		if err == nil {
  1388  			return true
  1389  		}
  1390  	}
  1391  
  1392  	switch ev := err.(type) {
  1393  	case StreamError:
  1394  		sc.resetStream(ev)
  1395  		return true
  1396  	case goAwayFlowError:
  1397  		sc.goAway(ErrCodeFlowControl)
  1398  		return true
  1399  	case ConnectionError:
  1400  		if res.f != nil {
  1401  			if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
  1402  				sc.maxClientStreamID = id
  1403  			}
  1404  		}
  1405  		sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1406  		sc.goAway(ErrCode(ev))
  1407  		return true // goAway will handle shutdown
  1408  	default:
  1409  		if res.err != nil {
  1410  			sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1411  		} else {
  1412  			sc.logf("http2: server closing client connection: %v", err)
  1413  		}
  1414  		return false
  1415  	}
  1416  }
  1417  
  1418  func (sc *serverConn) processFrame(f Frame) error {
  1419  	sc.serveG.check()
  1420  
  1421  	// First frame received must be SETTINGS.
  1422  	if !sc.sawFirstSettings {
  1423  		if _, ok := f.(*SettingsFrame); !ok {
  1424  			return sc.countError("first_settings", ConnectionError(ErrCodeProtocol))
  1425  		}
  1426  		sc.sawFirstSettings = true
  1427  	}
  1428  
  1429  	// Discard frames for streams initiated after the identified last
  1430  	// stream sent in a GOAWAY, or all frames after sending an error.
  1431  	// We still need to return connection-level flow control for DATA frames.
  1432  	// RFC 9113 Section 6.8.
  1433  	if sc.inGoAway && (sc.goAwayCode != ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
  1434  
  1435  		if f, ok := f.(*DataFrame); ok {
  1436  			if !sc.inflow.take(f.Length) {
  1437  				return sc.countError("data_flow", streamError(f.Header().StreamID, ErrCodeFlowControl))
  1438  			}
  1439  			sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1440  		}
  1441  		return nil
  1442  	}
  1443  
  1444  	switch f := f.(type) {
  1445  	case *SettingsFrame:
  1446  		return sc.processSettings(f)
  1447  	case *MetaHeadersFrame:
  1448  		return sc.processHeaders(f)
  1449  	case *WindowUpdateFrame:
  1450  		return sc.processWindowUpdate(f)
  1451  	case *PingFrame:
  1452  		return sc.processPing(f)
  1453  	case *DataFrame:
  1454  		return sc.processData(f)
  1455  	case *RSTStreamFrame:
  1456  		return sc.processResetStream(f)
  1457  	case *PriorityFrame:
  1458  		return sc.processPriority(f)
  1459  	case *GoAwayFrame:
  1460  		return sc.processGoAway(f)
  1461  	case *PushPromiseFrame:
  1462  		// A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1463  		// frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1464  		return sc.countError("push_promise", ConnectionError(ErrCodeProtocol))
  1465  	case *PriorityUpdateFrame:
  1466  		return sc.processPriorityUpdate(f)
  1467  	default:
  1468  		sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1469  		return nil
  1470  	}
  1471  }
  1472  
  1473  func (sc *serverConn) processPing(f *PingFrame) error {
  1474  	sc.serveG.check()
  1475  	if f.IsAck() {
  1476  		if sc.pingSent && sc.sentPingData == f.Data {
  1477  			// This is a response to a PING we sent.
  1478  			sc.pingSent = false
  1479  			sc.readIdleTimer.Reset(sc.readIdleTimeout)
  1480  		}
  1481  		// 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1482  		// containing this flag."
  1483  		return nil
  1484  	}
  1485  	if f.StreamID != 0 {
  1486  		// "PING frames are not associated with any individual
  1487  		// stream. If a PING frame is received with a stream
  1488  		// identifier field value other than 0x0, the recipient MUST
  1489  		// respond with a connection error (Section 5.4.1) of type
  1490  		// PROTOCOL_ERROR."
  1491  		return sc.countError("ping_on_stream", ConnectionError(ErrCodeProtocol))
  1492  	}
  1493  	sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1494  	return nil
  1495  }
  1496  
  1497  func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1498  	sc.serveG.check()
  1499  	switch {
  1500  	case f.StreamID != 0: // stream-level flow control
  1501  		state, st := sc.state(f.StreamID)
  1502  		if state == stateIdle {
  1503  			// Section 5.1: "Receiving any frame other than HEADERS
  1504  			// or PRIORITY on a stream in this state MUST be
  1505  			// treated as a connection error (Section 5.4.1) of
  1506  			// type PROTOCOL_ERROR."
  1507  			return sc.countError("stream_idle", ConnectionError(ErrCodeProtocol))
  1508  		}
  1509  		if st == nil {
  1510  			// "WINDOW_UPDATE can be sent by a peer that has sent a
  1511  			// frame bearing the END_STREAM flag. This means that a
  1512  			// receiver could receive a WINDOW_UPDATE frame on a "half
  1513  			// closed (remote)" or "closed" stream. A receiver MUST
  1514  			// NOT treat this as an error, see Section 5.1."
  1515  			return nil
  1516  		}
  1517  		if !st.flow.add(int32(f.Increment)) {
  1518  			return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl))
  1519  		}
  1520  	default: // connection-level flow control
  1521  		if !sc.flow.add(int32(f.Increment)) {
  1522  			return goAwayFlowError{}
  1523  		}
  1524  	}
  1525  	sc.scheduleFrameWrite()
  1526  	return nil
  1527  }
  1528  
  1529  func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1530  	sc.serveG.check()
  1531  
  1532  	state, st := sc.state(f.StreamID)
  1533  	if state == stateIdle {
  1534  		// 6.4 "RST_STREAM frames MUST NOT be sent for a
  1535  		// stream in the "idle" state. If a RST_STREAM frame
  1536  		// identifying an idle stream is received, the
  1537  		// recipient MUST treat this as a connection error
  1538  		// (Section 5.4.1) of type PROTOCOL_ERROR.
  1539  		return sc.countError("reset_idle_stream", ConnectionError(ErrCodeProtocol))
  1540  	}
  1541  	if st != nil {
  1542  		st.cancelCtx()
  1543  		sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1544  	}
  1545  	return nil
  1546  }
  1547  
  1548  func (sc *serverConn) closeStream(st *stream, err error) {
  1549  	sc.serveG.check()
  1550  	if st.state == stateIdle || st.state == stateClosed {
  1551  		panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1552  	}
  1553  	st.state = stateClosed
  1554  	if st.readDeadline != nil {
  1555  		st.readDeadline.Stop()
  1556  	}
  1557  	if st.writeDeadline != nil {
  1558  		st.writeDeadline.Stop()
  1559  	}
  1560  	if st.isPushed() {
  1561  		sc.curPushedStreams--
  1562  	} else {
  1563  		sc.curClientStreams--
  1564  	}
  1565  	delete(sc.streams, st.id)
  1566  	if len(sc.streams) == 0 {
  1567  		sc.setConnState(ConnStateIdle)
  1568  		idleTimeout := sc.hs.IdleTimeout()
  1569  		if idleTimeout > 0 && sc.idleTimer != nil {
  1570  			sc.idleTimer.Reset(idleTimeout)
  1571  		}
  1572  		if h1ServerKeepAlivesDisabled(sc.hs) {
  1573  			sc.startGracefulShutdownInternal()
  1574  		}
  1575  	}
  1576  	if p := st.body; p != nil {
  1577  		// Return any buffered unread bytes worth of conn-level flow control.
  1578  		// See golang.org/issue/16481
  1579  		sc.sendWindowUpdate(nil, p.Len())
  1580  
  1581  		p.CloseWithError(err)
  1582  	}
  1583  	if e, ok := err.(StreamError); ok {
  1584  		if e.Cause != nil {
  1585  			err = e.Cause
  1586  		} else {
  1587  			err = errStreamClosed
  1588  		}
  1589  	}
  1590  	st.closeErr = err
  1591  	st.cancelCtx()
  1592  	st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1593  	sc.writeSched.CloseStream(st.id)
  1594  }
  1595  
  1596  func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1597  	sc.serveG.check()
  1598  	if f.IsAck() {
  1599  		sc.unackedSettings--
  1600  		if sc.unackedSettings < 0 {
  1601  			// Why is the peer ACKing settings we never sent?
  1602  			// The spec doesn't mention this case, but
  1603  			// hang up on them anyway.
  1604  			return sc.countError("ack_mystery", ConnectionError(ErrCodeProtocol))
  1605  		}
  1606  		return nil
  1607  	}
  1608  	if f.NumSettings() > 100 || f.HasDuplicates() {
  1609  		// This isn't actually in the spec, but hang up on
  1610  		// suspiciously large settings frames or those with
  1611  		// duplicate entries.
  1612  		return sc.countError("settings_big_or_dups", ConnectionError(ErrCodeProtocol))
  1613  	}
  1614  	if err := f.ForeachSetting(sc.processSetting); err != nil {
  1615  		return err
  1616  	}
  1617  	// TODO: judging by RFC 7540, Section 6.5.3 each SETTINGS frame should be
  1618  	// acknowledged individually, even if multiple are received before the ACK.
  1619  	sc.needToSendSettingsAck = true
  1620  	sc.scheduleFrameWrite()
  1621  	return nil
  1622  }
  1623  
  1624  func (sc *serverConn) processSetting(s Setting) error {
  1625  	sc.serveG.check()
  1626  	if err := s.Valid(); err != nil {
  1627  		return err
  1628  	}
  1629  	if VerboseLogs {
  1630  		sc.vlogf("http2: server processing setting %v", s)
  1631  	}
  1632  	switch s.ID {
  1633  	case SettingHeaderTableSize:
  1634  		sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1635  	case SettingEnablePush:
  1636  		sc.pushEnabled = s.Val != 0
  1637  	case SettingMaxConcurrentStreams:
  1638  		sc.clientMaxStreams = s.Val
  1639  	case SettingInitialWindowSize:
  1640  		return sc.processSettingInitialWindowSize(s.Val)
  1641  	case SettingMaxFrameSize:
  1642  		sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1643  	case SettingMaxHeaderListSize:
  1644  		sc.peerMaxHeaderListSize = s.Val
  1645  	case SettingEnableConnectProtocol:
  1646  		// Receipt of this parameter by a server does not
  1647  		// have any impact
  1648  	case SettingNoRFC7540Priorities:
  1649  		if s.Val > 1 {
  1650  			return ConnectionError(ErrCodeProtocol)
  1651  		}
  1652  	default:
  1653  		// Unknown setting: "An endpoint that receives a SETTINGS
  1654  		// frame with any unknown or unsupported identifier MUST
  1655  		// ignore that setting."
  1656  		if VerboseLogs {
  1657  			sc.vlogf("http2: server ignoring unknown setting %v", s)
  1658  		}
  1659  	}
  1660  	return nil
  1661  }
  1662  
  1663  func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1664  	sc.serveG.check()
  1665  	// Note: val already validated to be within range by
  1666  	// processSetting's Valid call.
  1667  
  1668  	// "A SETTINGS frame can alter the initial flow control window
  1669  	// size for all current streams. When the value of
  1670  	// SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1671  	// adjust the size of all stream flow control windows that it
  1672  	// maintains by the difference between the new value and the
  1673  	// old value."
  1674  	old := sc.initialStreamSendWindowSize
  1675  	sc.initialStreamSendWindowSize = int32(val)
  1676  	growth := int32(val) - old // may be negative
  1677  	for _, st := range sc.streams {
  1678  		if !st.flow.add(growth) {
  1679  			// 6.9.2 Initial Flow Control Window Size
  1680  			// "An endpoint MUST treat a change to
  1681  			// SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1682  			// control window to exceed the maximum size as a
  1683  			// connection error (Section 5.4.1) of type
  1684  			// FLOW_CONTROL_ERROR."
  1685  			return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl))
  1686  		}
  1687  	}
  1688  	return nil
  1689  }
  1690  
  1691  func (sc *serverConn) processData(f *DataFrame) error {
  1692  	sc.serveG.check()
  1693  	id := f.Header().StreamID
  1694  
  1695  	data := f.Data()
  1696  	state, st := sc.state(id)
  1697  	if id == 0 || state == stateIdle {
  1698  		// Section 6.1: "DATA frames MUST be associated with a
  1699  		// stream. If a DATA frame is received whose stream
  1700  		// identifier field is 0x0, the recipient MUST respond
  1701  		// with a connection error (Section 5.4.1) of type
  1702  		// PROTOCOL_ERROR."
  1703  		//
  1704  		// Section 5.1: "Receiving any frame other than HEADERS
  1705  		// or PRIORITY on a stream in this state MUST be
  1706  		// treated as a connection error (Section 5.4.1) of
  1707  		// type PROTOCOL_ERROR."
  1708  		return sc.countError("data_on_idle", ConnectionError(ErrCodeProtocol))
  1709  	}
  1710  
  1711  	// "If a DATA frame is received whose stream is not in "open"
  1712  	// or "half closed (local)" state, the recipient MUST respond
  1713  	// with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1714  	if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
  1715  		// This includes sending a RST_STREAM if the stream is
  1716  		// in stateHalfClosedLocal (which currently means that
  1717  		// the http.Handler returned, so it's done reading &
  1718  		// done writing). Try to stop the client from sending
  1719  		// more DATA.
  1720  
  1721  		// But still enforce their connection-level flow control,
  1722  		// and return any flow control bytes since we're not going
  1723  		// to consume them.
  1724  		if !sc.inflow.take(f.Length) {
  1725  			return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
  1726  		}
  1727  		sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1728  
  1729  		if st != nil && st.resetQueued {
  1730  			// Already have a stream error in flight. Don't send another.
  1731  			return nil
  1732  		}
  1733  		return sc.countError("closed", streamError(id, ErrCodeStreamClosed))
  1734  	}
  1735  	if st.body == nil {
  1736  		panic("internal error: should have a body in this state")
  1737  	}
  1738  
  1739  	// Sender sending more than they'd declared?
  1740  	if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1741  		if !sc.inflow.take(f.Length) {
  1742  			return sc.countError("data_flow", streamError(id, ErrCodeFlowControl))
  1743  		}
  1744  		sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1745  
  1746  		st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1747  		// RFC 7540, sec 8.1.2.6: A request or response is also malformed if the
  1748  		// value of a content-length header field does not equal the sum of the
  1749  		// DATA frame payload lengths that form the body.
  1750  		return sc.countError("send_too_much", streamError(id, ErrCodeProtocol))
  1751  	}
  1752  	if f.Length > 0 {
  1753  		// Check whether the client has flow control quota.
  1754  		if !takeInflows(&sc.inflow, &st.inflow, f.Length) {
  1755  			return sc.countError("flow_on_data_length", streamError(id, ErrCodeFlowControl))
  1756  		}
  1757  
  1758  		if len(data) > 0 {
  1759  			st.bodyBytes += int64(len(data))
  1760  			wrote, err := st.body.Write(data)
  1761  			if err != nil {
  1762  				// The handler has closed the request body.
  1763  				// Return the connection-level flow control for the discarded data,
  1764  				// but not the stream-level flow control.
  1765  				sc.sendWindowUpdate(nil, int(f.Length)-wrote)
  1766  				return nil
  1767  			}
  1768  			if wrote != len(data) {
  1769  				panic("internal error: bad Writer")
  1770  			}
  1771  		}
  1772  
  1773  		// Return any padded flow control now, since we won't
  1774  		// refund it later on body reads.
  1775  		// Call sendWindowUpdate even if there is no padding,
  1776  		// to return buffered flow control credit if the sent
  1777  		// window has shrunk.
  1778  		pad := int32(f.Length) - int32(len(data))
  1779  		sc.sendWindowUpdate32(nil, pad)
  1780  		sc.sendWindowUpdate32(st, pad)
  1781  	}
  1782  	if f.StreamEnded() {
  1783  		st.endStream()
  1784  	}
  1785  	return nil
  1786  }
  1787  
  1788  func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
  1789  	sc.serveG.check()
  1790  	if f.ErrCode != ErrCodeNo {
  1791  		sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1792  	} else {
  1793  		sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1794  	}
  1795  	sc.startGracefulShutdownInternal()
  1796  	// http://tools.ietf.org/html/rfc7540#section-6.8
  1797  	// We should not create any new streams, which means we should disable push.
  1798  	sc.pushEnabled = false
  1799  	return nil
  1800  }
  1801  
  1802  // isPushed reports whether the stream is server-initiated.
  1803  func (st *stream) isPushed() bool {
  1804  	return st.id%2 == 0
  1805  }
  1806  
  1807  // endStream closes a Request.Body's pipe. It is called when a DATA
  1808  // frame says a request body is over (or after trailers).
  1809  func (st *stream) endStream() {
  1810  	sc := st.sc
  1811  	sc.serveG.check()
  1812  
  1813  	if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1814  		st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1815  			st.declBodyBytes, st.bodyBytes))
  1816  	} else {
  1817  		st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1818  		st.body.CloseWithError(io.EOF)
  1819  	}
  1820  	st.state = stateHalfClosedRemote
  1821  }
  1822  
  1823  // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1824  // its Request.Body.Read just before it gets io.EOF.
  1825  func (st *stream) copyTrailersToHandlerRequest() {
  1826  	for k, vv := range st.trailer {
  1827  		if _, ok := st.reqTrailer[k]; ok {
  1828  			// Only copy it over it was pre-declared.
  1829  			st.reqTrailer[k] = vv
  1830  		}
  1831  	}
  1832  }
  1833  
  1834  // onReadTimeout is run on its own goroutine (from time.AfterFunc)
  1835  // when the stream's ReadTimeout has fired.
  1836  func (st *stream) onReadTimeout() {
  1837  	if st.body != nil {
  1838  		// Wrap the ErrDeadlineExceeded to avoid callers depending on us
  1839  		// returning the bare error.
  1840  		st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
  1841  	}
  1842  }
  1843  
  1844  // onWriteTimeout is run on its own goroutine (from time.AfterFunc)
  1845  // when the stream's WriteTimeout has fired.
  1846  func (st *stream) onWriteTimeout() {
  1847  	st.sc.writeFrameFromHandler(FrameWriteRequest{write: StreamError{
  1848  		StreamID: st.id,
  1849  		Code:     ErrCodeInternal,
  1850  		Cause:    os.ErrDeadlineExceeded,
  1851  	}})
  1852  }
  1853  
  1854  func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1855  	sc.serveG.check()
  1856  	id := f.StreamID
  1857  	// http://tools.ietf.org/html/rfc7540#section-5.1.1
  1858  	// Streams initiated by a client MUST use odd-numbered stream
  1859  	// identifiers. [...] An endpoint that receives an unexpected
  1860  	// stream identifier MUST respond with a connection error
  1861  	// (Section 5.4.1) of type PROTOCOL_ERROR.
  1862  	if id%2 != 1 {
  1863  		return sc.countError("headers_even", ConnectionError(ErrCodeProtocol))
  1864  	}
  1865  	// A HEADERS frame can be used to create a new stream or
  1866  	// send a trailer for an open one. If we already have a stream
  1867  	// open, let it process its own HEADERS frame (trailers at this
  1868  	// point, if it's valid).
  1869  	if st := sc.streams[f.StreamID]; st != nil {
  1870  		if st.resetQueued {
  1871  			// We're sending RST_STREAM to close the stream, so don't bother
  1872  			// processing this frame.
  1873  			return nil
  1874  		}
  1875  		// RFC 7540, sec 5.1: If an endpoint receives additional frames, other than
  1876  		// WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in
  1877  		// this state, it MUST respond with a stream error (Section 5.4.2) of
  1878  		// type STREAM_CLOSED.
  1879  		if st.state == stateHalfClosedRemote {
  1880  			return sc.countError("headers_half_closed", streamError(id, ErrCodeStreamClosed))
  1881  		}
  1882  		return st.processTrailerHeaders(f)
  1883  	}
  1884  
  1885  	// [...] The identifier of a newly established stream MUST be
  1886  	// numerically greater than all streams that the initiating
  1887  	// endpoint has opened or reserved. [...]  An endpoint that
  1888  	// receives an unexpected stream identifier MUST respond with
  1889  	// a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1890  	if id <= sc.maxClientStreamID {
  1891  		return sc.countError("stream_went_down", ConnectionError(ErrCodeProtocol))
  1892  	}
  1893  	sc.maxClientStreamID = id
  1894  
  1895  	if sc.idleTimer != nil {
  1896  		sc.idleTimer.Stop()
  1897  	}
  1898  
  1899  	// http://tools.ietf.org/html/rfc7540#section-5.1.2
  1900  	// [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1901  	// endpoint that receives a HEADERS frame that causes their
  1902  	// advertised concurrent stream limit to be exceeded MUST treat
  1903  	// this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1904  	// or REFUSED_STREAM.
  1905  	if sc.curClientStreams+1 > sc.advMaxStreams {
  1906  		if sc.unackedSettings == 0 {
  1907  			// They should know better.
  1908  			return sc.countError("over_max_streams", streamError(id, ErrCodeProtocol))
  1909  		}
  1910  		// Assume it's a network race, where they just haven't
  1911  		// received our last SETTINGS update. But actually
  1912  		// this can't happen yet, because we don't yet provide
  1913  		// a way for users to adjust server parameters at
  1914  		// runtime.
  1915  		return sc.countError("over_max_streams_race", streamError(id, ErrCodeRefusedStream))
  1916  	}
  1917  
  1918  	initialState := stateOpen
  1919  	if f.StreamEnded() {
  1920  		initialState = stateHalfClosedRemote
  1921  	}
  1922  
  1923  	// We are handling two special cases here:
  1924  	// 1. When a request is sent via an intermediary, we force priority to be
  1925  	// u=3,i. This is essentially a round-robin behavior, and is done to ensure
  1926  	// fairness between, for example, multiple clients using the same proxy.
  1927  	// 2. Until a client has shown that it is aware of RFC 9218, we make its
  1928  	// streams non-incremental by default. This is done to preserve the
  1929  	// historical behavior of handling streams in a round-robin manner, rather
  1930  	// than one-by-one to completion.
  1931  	initialPriority := defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary)
  1932  	if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); ok && !sc.hasIntermediary {
  1933  		headerPriority, priorityAware, hasIntermediary := f.rfc9218Priority(sc.priorityAware)
  1934  		initialPriority = headerPriority
  1935  		sc.hasIntermediary = hasIntermediary
  1936  		if priorityAware {
  1937  			sc.priorityAware = true
  1938  		}
  1939  	}
  1940  	st := sc.newStream(id, 0, initialState, initialPriority)
  1941  
  1942  	if f.HasPriority() {
  1943  		if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
  1944  			return err
  1945  		}
  1946  		if !sc.writeSchedIgnoresRFC7540() {
  1947  			sc.writeSched.AdjustStream(st.id, f.Priority)
  1948  		}
  1949  	}
  1950  
  1951  	rw, req, err := sc.newWriterAndRequest(st, f)
  1952  	if err != nil {
  1953  		return err
  1954  	}
  1955  	st.reqTrailer = req.Trailer
  1956  	if st.reqTrailer != nil {
  1957  		st.trailer = make(Header)
  1958  	}
  1959  	st.body = req.Body.(*requestBody).pipe // may be nil
  1960  	st.declBodyBytes = req.ContentLength
  1961  
  1962  	handler := sc.handler.ServeHTTP
  1963  	if f.Truncated {
  1964  		// Their header list was too long. Send a 431 error.
  1965  		handler = handleHeaderListTooLong
  1966  	} else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1967  		handler = serve400Handler{err}.ServeHTTP
  1968  	}
  1969  
  1970  	if sc.hs.ReadTimeout() > 0 {
  1971  		st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout(), st.onReadTimeout)
  1972  	}
  1973  
  1974  	return sc.scheduleHandler(id, rw, req, handler)
  1975  }
  1976  
  1977  func (sc *serverConn) upgradeRequest(req *ServerRequest) {
  1978  	sc.serveG.check()
  1979  	id := uint32(1)
  1980  	sc.maxClientStreamID = id
  1981  	st := sc.newStream(id, 0, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
  1982  	st.reqTrailer = req.Trailer
  1983  	if st.reqTrailer != nil {
  1984  		st.trailer = make(Header)
  1985  	}
  1986  	rw := sc.newResponseWriter(st)
  1987  	rw.rws.req = *req
  1988  	req = &rw.rws.req
  1989  
  1990  	// This is the first request on the connection,
  1991  	// so start the handler directly rather than going
  1992  	// through scheduleHandler.
  1993  	sc.curHandlers++
  1994  	go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  1995  }
  1996  
  1997  func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1998  	sc := st.sc
  1999  	sc.serveG.check()
  2000  	if st.gotTrailerHeader {
  2001  		return sc.countError("dup_trailers", ConnectionError(ErrCodeProtocol))
  2002  	}
  2003  	st.gotTrailerHeader = true
  2004  	if !f.StreamEnded() {
  2005  		return sc.countError("trailers_not_ended", streamError(st.id, ErrCodeProtocol))
  2006  	}
  2007  
  2008  	if len(f.PseudoFields()) > 0 {
  2009  		return sc.countError("trailers_pseudo", streamError(st.id, ErrCodeProtocol))
  2010  	}
  2011  	if f.Truncated {
  2012  		return sc.countError("trailers_too_large", streamError(st.id, ErrCodeProtocol))
  2013  	}
  2014  	if st.trailer != nil {
  2015  		for _, hf := range f.RegularFields() {
  2016  			key := sc.canonicalHeader(hf.Name)
  2017  			if !httpguts.ValidTrailerHeader(key) {
  2018  				// TODO: send more details to the peer somehow. But http2 has
  2019  				// no way to send debug data at a stream level. Discuss with
  2020  				// HTTP folk.
  2021  				return sc.countError("trailers_bogus", streamError(st.id, ErrCodeProtocol))
  2022  			}
  2023  			st.trailer[key] = append(st.trailer[key], hf.Value)
  2024  		}
  2025  	}
  2026  	st.endStream()
  2027  	return nil
  2028  }
  2029  
  2030  func (sc *serverConn) checkPriority(streamID uint32, p PriorityParam) error {
  2031  	if streamID == p.StreamDep {
  2032  		// Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  2033  		// this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  2034  		// Section 5.3.3 says that a stream can depend on one of its dependencies,
  2035  		// so it's only self-dependencies that are forbidden.
  2036  		return sc.countError("priority", streamError(streamID, ErrCodeProtocol))
  2037  	}
  2038  	return nil
  2039  }
  2040  
  2041  func (sc *serverConn) processPriority(f *PriorityFrame) error {
  2042  	if err := sc.checkPriority(f.StreamID, f.PriorityParam); err != nil {
  2043  		return err
  2044  	}
  2045  	// We need to avoid calling AdjustStream when using the RFC 9218 write
  2046  	// scheduler. Otherwise, incremental's zero value in PriorityParam will
  2047  	// unexpectedly make all streams non-incremental. This causes us to process
  2048  	// streams one-by-one to completion rather than doing it in a round-robin
  2049  	// manner (the historical behavior), which might be unexpected to users.
  2050  	if sc.writeSchedIgnoresRFC7540() {
  2051  		return nil
  2052  	}
  2053  	sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  2054  	return nil
  2055  }
  2056  
  2057  func (sc *serverConn) processPriorityUpdate(f *PriorityUpdateFrame) error {
  2058  	sc.priorityAware = true
  2059  	if _, ok := sc.writeSched.(*priorityWriteSchedulerRFC9218); !ok {
  2060  		return nil
  2061  	}
  2062  	p, ok := parseRFC9218Priority(f.Priority, sc.priorityAware)
  2063  	if !ok {
  2064  		return sc.countError("unparsable_priority_update", streamError(f.PrioritizedStreamID, ErrCodeProtocol))
  2065  	}
  2066  	sc.writeSched.AdjustStream(f.PrioritizedStreamID, p)
  2067  	return nil
  2068  }
  2069  
  2070  func (sc *serverConn) newStream(id, pusherID uint32, state streamState, priority PriorityParam) *stream {
  2071  	sc.serveG.check()
  2072  	if id == 0 {
  2073  		panic("internal error: cannot create stream with id 0")
  2074  	}
  2075  
  2076  	ctx, cancelCtx := context.WithCancel(sc.baseCtx)
  2077  	st := &stream{
  2078  		sc:        sc,
  2079  		id:        id,
  2080  		state:     state,
  2081  		ctx:       ctx,
  2082  		cancelCtx: cancelCtx,
  2083  	}
  2084  	st.cw.Init()
  2085  	st.flow.conn = &sc.flow // link to conn-level counter
  2086  	st.flow.add(sc.initialStreamSendWindowSize)
  2087  	st.inflow.init(sc.initialStreamRecvWindowSize)
  2088  	if writeTimeout := sc.hs.WriteTimeout(); writeTimeout > 0 {
  2089  		st.writeDeadline = time.AfterFunc(writeTimeout, st.onWriteTimeout)
  2090  	}
  2091  
  2092  	sc.streams[id] = st
  2093  	sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID, priority: priority})
  2094  	if st.isPushed() {
  2095  		sc.curPushedStreams++
  2096  	} else {
  2097  		sc.curClientStreams++
  2098  	}
  2099  	if sc.curOpenStreams() == 1 {
  2100  		sc.setConnState(ConnStateActive)
  2101  	}
  2102  
  2103  	return st
  2104  }
  2105  
  2106  func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *ServerRequest, error) {
  2107  	sc.serveG.check()
  2108  
  2109  	rp := httpcommon.ServerRequestParam{
  2110  		Method:    f.PseudoValue("method"),
  2111  		Scheme:    f.PseudoValue("scheme"),
  2112  		Authority: f.PseudoValue("authority"),
  2113  		Path:      f.PseudoValue("path"),
  2114  		Protocol:  f.PseudoValue("protocol"),
  2115  	}
  2116  
  2117  	// extended connect is disabled, so we should not see :protocol
  2118  	if disableExtendedConnectProtocol && rp.Protocol != "" {
  2119  		return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
  2120  	}
  2121  
  2122  	isConnect := rp.Method == "CONNECT"
  2123  	if isConnect {
  2124  		if rp.Protocol == "" && (rp.Path != "" || rp.Scheme != "" || rp.Authority == "") {
  2125  			return nil, nil, sc.countError("bad_connect", streamError(f.StreamID, ErrCodeProtocol))
  2126  		}
  2127  	} else if rp.Method == "" || rp.Path == "" || (rp.Scheme != "https" && rp.Scheme != "http") {
  2128  		// See 8.1.2.6 Malformed Requests and Responses:
  2129  		//
  2130  		// Malformed requests or responses that are detected
  2131  		// MUST be treated as a stream error (Section 5.4.2)
  2132  		// of type PROTOCOL_ERROR."
  2133  		//
  2134  		// 8.1.2.3 Request Pseudo-Header Fields
  2135  		// "All HTTP/2 requests MUST include exactly one valid
  2136  		// value for the :method, :scheme, and :path
  2137  		// pseudo-header fields"
  2138  		return nil, nil, sc.countError("bad_path_method", streamError(f.StreamID, ErrCodeProtocol))
  2139  	}
  2140  
  2141  	header := make(Header)
  2142  	rp.Header = header
  2143  	for _, hf := range f.RegularFields() {
  2144  		header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  2145  	}
  2146  	if rp.Authority == "" {
  2147  		rp.Authority = header.Get("Host")
  2148  	}
  2149  	if rp.Protocol != "" {
  2150  		header.Set(":protocol", rp.Protocol)
  2151  	}
  2152  
  2153  	rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  2154  	if err != nil {
  2155  		return nil, nil, err
  2156  	}
  2157  	bodyOpen := !f.StreamEnded()
  2158  	if clens, ok := rp.Header["Content-Length"]; ok {
  2159  		if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
  2160  			req.ContentLength = int64(cl)
  2161  		} else {
  2162  			req.ContentLength = 0
  2163  		}
  2164  		if !bodyOpen && req.ContentLength != 0 {
  2165  			return nil, nil, sc.countError("bodyless_content_length", streamError(f.StreamID, ErrCodeProtocol))
  2166  		}
  2167  		if len(clens) > 1 {
  2168  			for _, dup := range clens[1:] {
  2169  				if clens[0] != dup {
  2170  					return nil, nil, sc.countError("duplicate_content_length", streamError(f.StreamID, ErrCodeProtocol))
  2171  				}
  2172  			}
  2173  			rp.Header["Content-Length"] = clens[:1]
  2174  		}
  2175  	}
  2176  	if bodyOpen {
  2177  		if _, ok := rp.Header["Content-Length"]; !ok {
  2178  			req.ContentLength = -1
  2179  		}
  2180  		req.Body.(*requestBody).pipe = &pipe{
  2181  			b: &dataBuffer{expected: req.ContentLength},
  2182  		}
  2183  	}
  2184  	return rw, req, nil
  2185  }
  2186  
  2187  func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.ServerRequestParam) (*responseWriter, *ServerRequest, error) {
  2188  	sc.serveG.check()
  2189  
  2190  	var tlsState *tls.ConnectionState // nil if not scheme https
  2191  	if rp.Scheme == "https" {
  2192  		tlsState = sc.tlsState
  2193  	}
  2194  
  2195  	res := httpcommon.NewServerRequest(rp)
  2196  	if res.InvalidReason != "" {
  2197  		return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol))
  2198  	}
  2199  
  2200  	body := &requestBody{
  2201  		conn:          sc,
  2202  		stream:        st,
  2203  		needsContinue: res.NeedsContinue,
  2204  	}
  2205  	rw := sc.newResponseWriter(st)
  2206  	rw.rws.req = ServerRequest{
  2207  		Context:    st.ctx,
  2208  		Method:     rp.Method,
  2209  		URL:        res.URL,
  2210  		RemoteAddr: sc.remoteAddrStr,
  2211  		Header:     rp.Header,
  2212  		RequestURI: res.RequestURI,
  2213  		Proto:      "HTTP/2.0",
  2214  		ProtoMajor: 2,
  2215  		ProtoMinor: 0,
  2216  		TLS:        tlsState,
  2217  		Host:       rp.Authority,
  2218  		Body:       body,
  2219  		Trailer:    res.Trailer,
  2220  	}
  2221  	return rw, &rw.rws.req, nil
  2222  }
  2223  
  2224  func (sc *serverConn) newResponseWriter(st *stream) *responseWriter {
  2225  	rws := responseWriterStatePool.Get().(*responseWriterState)
  2226  	bwSave := rws.bw
  2227  	*rws = responseWriterState{} // zero all the fields
  2228  	rws.conn = sc
  2229  	rws.bw = bwSave
  2230  	rws.bw.Reset(chunkWriter{rws})
  2231  	rws.stream = st
  2232  	return &responseWriter{rws: rws}
  2233  }
  2234  
  2235  type unstartedHandler struct {
  2236  	streamID uint32
  2237  	rw       *responseWriter
  2238  	req      *ServerRequest
  2239  	handler  func(*ResponseWriter, *ServerRequest)
  2240  }
  2241  
  2242  // scheduleHandler starts a handler goroutine,
  2243  // or schedules one to start as soon as an existing handler finishes.
  2244  func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) error {
  2245  	sc.serveG.check()
  2246  	maxHandlers := sc.advMaxStreams
  2247  	if sc.curHandlers < maxHandlers {
  2248  		sc.curHandlers++
  2249  		go sc.runHandler(rw, req, handler)
  2250  		return nil
  2251  	}
  2252  	if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
  2253  		return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm))
  2254  	}
  2255  	sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{
  2256  		streamID: streamID,
  2257  		rw:       rw,
  2258  		req:      req,
  2259  		handler:  handler,
  2260  	})
  2261  	return nil
  2262  }
  2263  
  2264  func (sc *serverConn) handlerDone() {
  2265  	sc.serveG.check()
  2266  	sc.curHandlers--
  2267  	i := 0
  2268  	maxHandlers := sc.advMaxStreams
  2269  	for ; i < len(sc.unstartedHandlers); i++ {
  2270  		u := sc.unstartedHandlers[i]
  2271  		if sc.streams[u.streamID] == nil {
  2272  			// This stream was reset before its goroutine had a chance to start.
  2273  			continue
  2274  		}
  2275  		if sc.curHandlers >= maxHandlers {
  2276  			break
  2277  		}
  2278  		sc.curHandlers++
  2279  		go sc.runHandler(u.rw, u.req, u.handler)
  2280  		sc.unstartedHandlers[i] = unstartedHandler{} // don't retain references
  2281  	}
  2282  	sc.unstartedHandlers = sc.unstartedHandlers[i:]
  2283  	if len(sc.unstartedHandlers) == 0 {
  2284  		sc.unstartedHandlers = nil
  2285  	}
  2286  }
  2287  
  2288  // Run on its own goroutine.
  2289  func (sc *serverConn) runHandler(rw *responseWriter, req *ServerRequest, handler func(*ResponseWriter, *ServerRequest)) {
  2290  	defer sc.sendServeMsg(handlerDoneMsg)
  2291  	didPanic := true
  2292  	defer func() {
  2293  		rw.rws.stream.cancelCtx()
  2294  		if req.MultipartForm != nil {
  2295  			req.MultipartForm.RemoveAll()
  2296  		}
  2297  		if didPanic {
  2298  			e := recover()
  2299  			sc.writeFrameFromHandler(FrameWriteRequest{
  2300  				write:  handlerPanicRST{rw.rws.stream.id},
  2301  				stream: rw.rws.stream,
  2302  			})
  2303  			// Same as net/http:
  2304  			if e != nil && e != ErrAbortHandler {
  2305  				const size = 64 << 10
  2306  				buf := make([]byte, size)
  2307  				buf = buf[:runtime.Stack(buf, false)]
  2308  				sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  2309  			}
  2310  			return
  2311  		}
  2312  		rw.handlerDone()
  2313  	}()
  2314  	handler(rw, req)
  2315  	didPanic = false
  2316  }
  2317  
  2318  func handleHeaderListTooLong(w *ResponseWriter, r *ServerRequest) {
  2319  	// 10.5.1 Limits on Header Block Size:
  2320  	// .. "A server that receives a larger header block than it is
  2321  	// willing to handle can send an HTTP 431 (Request Header Fields Too
  2322  	// Large) status code"
  2323  	const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  2324  	w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  2325  	io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  2326  }
  2327  
  2328  // called from handler goroutines.
  2329  // h may be nil.
  2330  func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  2331  	sc.serveG.checkNotOn() // NOT on
  2332  	var errc chan error
  2333  	if headerData.h != nil {
  2334  		// If there's a header map (which we don't own), so we have to block on
  2335  		// waiting for this frame to be written, so an http.Flush mid-handler
  2336  		// writes out the correct value of keys, before a handler later potentially
  2337  		// mutates it.
  2338  		errc = sc.srv.getErrChan()
  2339  	}
  2340  	if err := sc.writeFrameFromHandler(FrameWriteRequest{
  2341  		write:  headerData,
  2342  		stream: st,
  2343  		done:   errc,
  2344  	}); err != nil {
  2345  		return err
  2346  	}
  2347  	if errc != nil {
  2348  		select {
  2349  		case err := <-errc:
  2350  			sc.srv.putErrChan(errc)
  2351  			return err
  2352  		case <-sc.doneServing:
  2353  			return errClientDisconnected
  2354  		case <-st.cw:
  2355  			return errStreamClosed
  2356  		}
  2357  	}
  2358  	return nil
  2359  }
  2360  
  2361  // called from handler goroutines.
  2362  func (sc *serverConn) write100ContinueHeaders(st *stream) {
  2363  	sc.writeFrameFromHandler(FrameWriteRequest{
  2364  		write:  write100ContinueHeadersFrame{st.id},
  2365  		stream: st,
  2366  	})
  2367  }
  2368  
  2369  // A bodyReadMsg tells the server loop that the http.Handler read n
  2370  // bytes of the DATA from the client on the given stream.
  2371  type bodyReadMsg struct {
  2372  	st *stream
  2373  	n  int
  2374  }
  2375  
  2376  // called from handler goroutines.
  2377  // Notes that the handler for the given stream ID read n bytes of its body
  2378  // and schedules flow control tokens to be sent.
  2379  func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  2380  	sc.serveG.checkNotOn() // NOT on
  2381  	if n > 0 {
  2382  		select {
  2383  		case sc.bodyReadCh <- bodyReadMsg{st, n}:
  2384  		case <-sc.doneServing:
  2385  		}
  2386  	}
  2387  }
  2388  
  2389  func (sc *serverConn) noteBodyRead(st *stream, n int) {
  2390  	sc.serveG.check()
  2391  	sc.sendWindowUpdate(nil, n) // conn-level
  2392  	if st.state != stateHalfClosedRemote && st.state != stateClosed {
  2393  		// Don't send this WINDOW_UPDATE if the stream is closed
  2394  		// remotely.
  2395  		sc.sendWindowUpdate(st, n)
  2396  	}
  2397  }
  2398  
  2399  // st may be nil for conn-level
  2400  func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  2401  	sc.sendWindowUpdate(st, int(n))
  2402  }
  2403  
  2404  // st may be nil for conn-level
  2405  func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  2406  	sc.serveG.check()
  2407  	var streamID uint32
  2408  	var send int32
  2409  	if st == nil {
  2410  		send = sc.inflow.add(n)
  2411  	} else {
  2412  		streamID = st.id
  2413  		send = st.inflow.add(n)
  2414  	}
  2415  	if send == 0 {
  2416  		return
  2417  	}
  2418  	sc.writeFrame(FrameWriteRequest{
  2419  		write:  writeWindowUpdate{streamID: streamID, n: uint32(send)},
  2420  		stream: st,
  2421  	})
  2422  }
  2423  
  2424  // requestBody is the Handler's Request.Body type.
  2425  // Read and Close may be called concurrently.
  2426  type requestBody struct {
  2427  	_             incomparable
  2428  	stream        *stream
  2429  	conn          *serverConn
  2430  	closeOnce     sync.Once // for use by Close only
  2431  	sawEOF        bool      // for use by Read only
  2432  	pipe          *pipe     // non-nil if we have an HTTP entity message body
  2433  	needsContinue bool      // need to send a 100-continue
  2434  }
  2435  
  2436  func (b *requestBody) Close() error {
  2437  	b.closeOnce.Do(func() {
  2438  		if b.pipe != nil {
  2439  			b.pipe.BreakWithError(errClosedBody)
  2440  		}
  2441  	})
  2442  	return nil
  2443  }
  2444  
  2445  func (b *requestBody) Read(p []byte) (n int, err error) {
  2446  	if b.needsContinue {
  2447  		b.needsContinue = false
  2448  		b.conn.write100ContinueHeaders(b.stream)
  2449  	}
  2450  	if b.pipe == nil || b.sawEOF {
  2451  		return 0, io.EOF
  2452  	}
  2453  	n, err = b.pipe.Read(p)
  2454  	if err == io.EOF {
  2455  		b.sawEOF = true
  2456  	}
  2457  	if b.conn == nil {
  2458  		return
  2459  	}
  2460  	b.conn.noteBodyReadFromHandler(b.stream, n, err)
  2461  	return
  2462  }
  2463  
  2464  // responseWriter is the http.ResponseWriter implementation. It's
  2465  // intentionally small (1 pointer wide) to minimize garbage. The
  2466  // responseWriterState pointer inside is zeroed at the end of a
  2467  // request (in handlerDone) and calls on the responseWriter thereafter
  2468  // simply crash (caller's mistake), but the much larger responseWriterState
  2469  // and buffers are reused between multiple requests.
  2470  type responseWriter struct {
  2471  	rws *responseWriterState
  2472  }
  2473  
  2474  type responseWriterState struct {
  2475  	// immutable within a request:
  2476  	stream *stream
  2477  	req    ServerRequest
  2478  	conn   *serverConn
  2479  
  2480  	// TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  2481  	bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  2482  
  2483  	// mutated by http.Handler goroutine:
  2484  	handlerHeader Header   // nil until called
  2485  	snapHeader    Header   // snapshot of handlerHeader at WriteHeader time
  2486  	trailers      []string // set in writeChunk
  2487  	status        int      // status code passed to WriteHeader
  2488  	wroteHeader   bool     // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  2489  	sentHeader    bool     // have we sent the header frame?
  2490  	handlerDone   bool     // handler has finished
  2491  
  2492  	sentContentLen int64 // non-zero if handler set a Content-Length header
  2493  	wroteBytes     int64
  2494  
  2495  	closeNotifierMu sync.Mutex // guards closeNotifierCh
  2496  	closeNotifierCh chan bool  // nil until first used
  2497  }
  2498  
  2499  type chunkWriter struct{ rws *responseWriterState }
  2500  
  2501  func (cw chunkWriter) Write(p []byte) (n int, err error) {
  2502  	n, err = cw.rws.writeChunk(p)
  2503  	if err == errStreamClosed {
  2504  		// If writing failed because the stream has been closed,
  2505  		// return the reason it was closed.
  2506  		err = cw.rws.stream.closeErr
  2507  	}
  2508  	return n, err
  2509  }
  2510  
  2511  func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
  2512  
  2513  func (rws *responseWriterState) hasNonemptyTrailers() bool {
  2514  	for _, trailer := range rws.trailers {
  2515  		if _, ok := rws.handlerHeader[trailer]; ok {
  2516  			return true
  2517  		}
  2518  	}
  2519  	return false
  2520  }
  2521  
  2522  // declareTrailer is called for each Trailer header when the
  2523  // response header is written. It notes that a header will need to be
  2524  // written in the trailers at the end of the response.
  2525  func (rws *responseWriterState) declareTrailer(k string) {
  2526  	k = textproto.CanonicalMIMEHeaderKey(k)
  2527  	if !httpguts.ValidTrailerHeader(k) {
  2528  		// Forbidden by RFC 7230, section 4.1.2.
  2529  		rws.conn.logf("ignoring invalid trailer %q", k)
  2530  		return
  2531  	}
  2532  	if !slices.Contains(rws.trailers, k) {
  2533  		rws.trailers = append(rws.trailers, k)
  2534  	}
  2535  }
  2536  
  2537  const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // keep in sync with net/http
  2538  
  2539  // writeChunk writes chunks from the bufio.Writer. But because
  2540  // bufio.Writer may bypass its chunking, sometimes p may be
  2541  // arbitrarily large.
  2542  //
  2543  // writeChunk is also responsible (on the first chunk) for sending the
  2544  // HEADER response.
  2545  func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  2546  	if !rws.wroteHeader {
  2547  		rws.writeHeader(200)
  2548  	}
  2549  
  2550  	if rws.handlerDone {
  2551  		rws.promoteUndeclaredTrailers()
  2552  	}
  2553  
  2554  	isHeadResp := rws.req.Method == "HEAD"
  2555  	if !rws.sentHeader {
  2556  		rws.sentHeader = true
  2557  		var ctype, clen string
  2558  		if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  2559  			rws.snapHeader.Del("Content-Length")
  2560  			if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
  2561  				rws.sentContentLen = int64(cl)
  2562  			} else {
  2563  				clen = ""
  2564  			}
  2565  		}
  2566  		_, hasContentLength := rws.snapHeader["Content-Length"]
  2567  		if !hasContentLength && clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  2568  			clen = strconv.Itoa(len(p))
  2569  		}
  2570  		_, hasContentType := rws.snapHeader["Content-Type"]
  2571  		// If the Content-Encoding is non-blank, we shouldn't
  2572  		// sniff the body. See Issue golang.org/issue/31753.
  2573  		ce := rws.snapHeader.Get("Content-Encoding")
  2574  		hasCE := len(ce) > 0
  2575  		if !hasCE && !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
  2576  			ctype = internal.DetectContentType(p)
  2577  		}
  2578  		var date string
  2579  		if _, ok := rws.snapHeader["Date"]; !ok {
  2580  			// TODO(bradfitz): be faster here, like net/http? measure.
  2581  			date = time.Now().UTC().Format(TimeFormat)
  2582  		}
  2583  
  2584  		for _, v := range rws.snapHeader["Trailer"] {
  2585  			foreachHeaderElement(v, rws.declareTrailer)
  2586  		}
  2587  
  2588  		// "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),
  2589  		// but respect "Connection" == "close" to mean sending a GOAWAY and tearing
  2590  		// down the TCP connection when idle, like we do for HTTP/1.
  2591  		// TODO: remove more Connection-specific header fields here, in addition
  2592  		// to "Connection".
  2593  		if _, ok := rws.snapHeader["Connection"]; ok {
  2594  			v := rws.snapHeader.Get("Connection")
  2595  			delete(rws.snapHeader, "Connection")
  2596  			if v == "close" {
  2597  				rws.conn.startGracefulShutdown()
  2598  			}
  2599  		}
  2600  
  2601  		endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  2602  		err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2603  			streamID:      rws.stream.id,
  2604  			httpResCode:   rws.status,
  2605  			h:             rws.snapHeader,
  2606  			endStream:     endStream,
  2607  			contentType:   ctype,
  2608  			contentLength: clen,
  2609  			date:          date,
  2610  		})
  2611  		if err != nil {
  2612  			return 0, err
  2613  		}
  2614  		if endStream {
  2615  			return 0, nil
  2616  		}
  2617  	}
  2618  	if isHeadResp {
  2619  		return len(p), nil
  2620  	}
  2621  	if len(p) == 0 && !rws.handlerDone {
  2622  		return 0, nil
  2623  	}
  2624  
  2625  	// only send trailers if they have actually been defined by the
  2626  	// server handler.
  2627  	hasNonemptyTrailers := rws.hasNonemptyTrailers()
  2628  	endStream := rws.handlerDone && !hasNonemptyTrailers
  2629  	if len(p) > 0 || endStream {
  2630  		// only send a 0 byte DATA frame if we're ending the stream.
  2631  		if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  2632  			return 0, err
  2633  		}
  2634  	}
  2635  
  2636  	if rws.handlerDone && hasNonemptyTrailers {
  2637  		err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2638  			streamID:  rws.stream.id,
  2639  			h:         rws.handlerHeader,
  2640  			trailers:  rws.trailers,
  2641  			endStream: true,
  2642  		})
  2643  		return len(p), err
  2644  	}
  2645  	return len(p), nil
  2646  }
  2647  
  2648  // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  2649  // that, if present, signals that the map entry is actually for
  2650  // the response trailers, and not the response headers. The prefix
  2651  // is stripped after the ServeHTTP call finishes and the values are
  2652  // sent in the trailers.
  2653  //
  2654  // This mechanism is intended only for trailers that are not known
  2655  // prior to the headers being written. If the set of trailers is fixed
  2656  // or known before the header is written, the normal Go trailers mechanism
  2657  // is preferred:
  2658  //
  2659  //	https://golang.org/pkg/net/http/#ResponseWriter
  2660  //	https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  2661  const TrailerPrefix = "Trailer:"
  2662  
  2663  // promoteUndeclaredTrailers permits http.Handlers to set trailers
  2664  // after the header has already been flushed. Because the Go
  2665  // ResponseWriter interface has no way to set Trailers (only the
  2666  // Header), and because we didn't want to expand the ResponseWriter
  2667  // interface, and because nobody used trailers, and because RFC 7230
  2668  // says you SHOULD (but not must) predeclare any trailers in the
  2669  // header, the official ResponseWriter rules said trailers in Go must
  2670  // be predeclared, and then we reuse the same ResponseWriter.Header()
  2671  // map to mean both Headers and Trailers. When it's time to write the
  2672  // Trailers, we pick out the fields of Headers that were declared as
  2673  // trailers. That worked for a while, until we found the first major
  2674  // user of Trailers in the wild: gRPC (using them only over http2),
  2675  // and gRPC libraries permit setting trailers mid-stream without
  2676  // predeclaring them. So: change of plans. We still permit the old
  2677  // way, but we also permit this hack: if a Header() key begins with
  2678  // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2679  // invalid token byte anyway, there is no ambiguity. (And it's already
  2680  // filtered out) It's mildly hacky, but not terrible.
  2681  //
  2682  // This method runs after the Handler is done and promotes any Header
  2683  // fields to be trailers.
  2684  func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2685  	for k, vv := range rws.handlerHeader {
  2686  		if !strings.HasPrefix(k, TrailerPrefix) {
  2687  			continue
  2688  		}
  2689  		trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2690  		rws.declareTrailer(trailerKey)
  2691  		rws.handlerHeader[textproto.CanonicalMIMEHeaderKey(trailerKey)] = vv
  2692  	}
  2693  
  2694  	if len(rws.trailers) > 1 {
  2695  		slices.Sort(rws.trailers)
  2696  	}
  2697  }
  2698  
  2699  func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
  2700  	st := w.rws.stream
  2701  	if !deadline.IsZero() && deadline.Before(time.Now()) {
  2702  		// If we're setting a deadline in the past, reset the stream immediately
  2703  		// so writes after SetWriteDeadline returns will fail.
  2704  		st.onReadTimeout()
  2705  		return nil
  2706  	}
  2707  	w.rws.conn.sendServeMsg(func(sc *serverConn) {
  2708  		if st.readDeadline != nil {
  2709  			if !st.readDeadline.Stop() {
  2710  				// Deadline already exceeded, or stream has been closed.
  2711  				return
  2712  			}
  2713  		}
  2714  		if deadline.IsZero() {
  2715  			st.readDeadline = nil
  2716  		} else if st.readDeadline == nil {
  2717  			st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
  2718  		} else {
  2719  			st.readDeadline.Reset(deadline.Sub(time.Now()))
  2720  		}
  2721  	})
  2722  	return nil
  2723  }
  2724  
  2725  func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
  2726  	st := w.rws.stream
  2727  	if !deadline.IsZero() && deadline.Before(time.Now()) {
  2728  		// If we're setting a deadline in the past, reset the stream immediately
  2729  		// so writes after SetWriteDeadline returns will fail.
  2730  		st.onWriteTimeout()
  2731  		return nil
  2732  	}
  2733  	w.rws.conn.sendServeMsg(func(sc *serverConn) {
  2734  		if st.writeDeadline != nil {
  2735  			if !st.writeDeadline.Stop() {
  2736  				// Deadline already exceeded, or stream has been closed.
  2737  				return
  2738  			}
  2739  		}
  2740  		if deadline.IsZero() {
  2741  			st.writeDeadline = nil
  2742  		} else if st.writeDeadline == nil {
  2743  			st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
  2744  		} else {
  2745  			st.writeDeadline.Reset(deadline.Sub(time.Now()))
  2746  		}
  2747  	})
  2748  	return nil
  2749  }
  2750  
  2751  func (w *responseWriter) EnableFullDuplex() error {
  2752  	// We always support full duplex responses, so this is a no-op.
  2753  	return nil
  2754  }
  2755  
  2756  func (w *responseWriter) Flush() {
  2757  	w.FlushError()
  2758  }
  2759  
  2760  func (w *responseWriter) FlushError() error {
  2761  	rws := w.rws
  2762  	if rws == nil {
  2763  		panic("Header called after Handler finished")
  2764  	}
  2765  	var err error
  2766  	if rws.bw.Buffered() > 0 {
  2767  		err = rws.bw.Flush()
  2768  	} else {
  2769  		// The bufio.Writer won't call chunkWriter.Write
  2770  		// (writeChunk with zero bytes), so we have to do it
  2771  		// ourselves to force the HTTP response header and/or
  2772  		// final DATA frame (with END_STREAM) to be sent.
  2773  		_, err = chunkWriter{rws}.Write(nil)
  2774  		if err == nil {
  2775  			select {
  2776  			case <-rws.stream.cw:
  2777  				err = rws.stream.closeErr
  2778  			default:
  2779  			}
  2780  		}
  2781  	}
  2782  	return err
  2783  }
  2784  
  2785  func (w *responseWriter) CloseNotify() <-chan bool {
  2786  	rws := w.rws
  2787  	if rws == nil {
  2788  		panic("CloseNotify called after Handler finished")
  2789  	}
  2790  	rws.closeNotifierMu.Lock()
  2791  	ch := rws.closeNotifierCh
  2792  	if ch == nil {
  2793  		ch = make(chan bool, 1)
  2794  		rws.closeNotifierCh = ch
  2795  		cw := rws.stream.cw
  2796  		go func() {
  2797  			cw.Wait() // wait for close
  2798  			ch <- true
  2799  		}()
  2800  	}
  2801  	rws.closeNotifierMu.Unlock()
  2802  	return ch
  2803  }
  2804  
  2805  func (w *responseWriter) Header() Header {
  2806  	rws := w.rws
  2807  	if rws == nil {
  2808  		panic("Header called after Handler finished")
  2809  	}
  2810  	if rws.handlerHeader == nil {
  2811  		rws.handlerHeader = make(Header)
  2812  	}
  2813  	return rws.handlerHeader
  2814  }
  2815  
  2816  // checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
  2817  func checkWriteHeaderCode(code int) {
  2818  	// Issue 22880: require valid WriteHeader status codes.
  2819  	// For now we only enforce that it's three digits.
  2820  	// In the future we might block things over 599 (600 and above aren't defined
  2821  	// at http://httpwg.org/specs/rfc7231.html#status.codes).
  2822  	// But for now any three digits.
  2823  	//
  2824  	// We used to send "HTTP/1.1 000 0" on the wire in responses but there's
  2825  	// no equivalent bogus thing we can realistically send in HTTP/2,
  2826  	// so we'll consistently panic instead and help people find their bugs
  2827  	// early. (We can't return an error from WriteHeader even if we wanted to.)
  2828  	if code < 100 || code > 999 {
  2829  		panic(fmt.Sprintf("invalid WriteHeader code %v", code))
  2830  	}
  2831  }
  2832  
  2833  func (w *responseWriter) WriteHeader(code int) {
  2834  	rws := w.rws
  2835  	if rws == nil {
  2836  		panic("WriteHeader called after Handler finished")
  2837  	}
  2838  	rws.writeHeader(code)
  2839  }
  2840  
  2841  func (rws *responseWriterState) writeHeader(code int) {
  2842  	if rws.wroteHeader {
  2843  		return
  2844  	}
  2845  
  2846  	checkWriteHeaderCode(code)
  2847  
  2848  	// Handle informational headers
  2849  	if code >= 100 && code <= 199 {
  2850  		// Per RFC 8297 we must not clear the current header map
  2851  		h := rws.handlerHeader
  2852  
  2853  		_, cl := h["Content-Length"]
  2854  		_, te := h["Transfer-Encoding"]
  2855  		if cl || te {
  2856  			h = cloneHeader(h)
  2857  			h.Del("Content-Length")
  2858  			h.Del("Transfer-Encoding")
  2859  		}
  2860  
  2861  		rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2862  			streamID:    rws.stream.id,
  2863  			httpResCode: code,
  2864  			h:           h,
  2865  			endStream:   rws.handlerDone && !rws.hasTrailers(),
  2866  		})
  2867  
  2868  		return
  2869  	}
  2870  
  2871  	rws.wroteHeader = true
  2872  	rws.status = code
  2873  	if len(rws.handlerHeader) > 0 {
  2874  		rws.snapHeader = cloneHeader(rws.handlerHeader)
  2875  	}
  2876  }
  2877  
  2878  func cloneHeader(h Header) Header {
  2879  	h2 := make(Header, len(h))
  2880  	for k, vv := range h {
  2881  		vv2 := make([]string, len(vv))
  2882  		copy(vv2, vv)
  2883  		h2[k] = vv2
  2884  	}
  2885  	return h2
  2886  }
  2887  
  2888  // The Life Of A Write is like this:
  2889  //
  2890  // * Handler calls w.Write or w.WriteString ->
  2891  // * -> rws.bw (*bufio.Writer) ->
  2892  // * (Handler might call Flush)
  2893  // * -> chunkWriter{rws}
  2894  // * -> responseWriterState.writeChunk(p []byte)
  2895  // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2896  func (w *responseWriter) Write(p []byte) (n int, err error) {
  2897  	return w.write(len(p), p, "")
  2898  }
  2899  
  2900  func (w *responseWriter) WriteString(s string) (n int, err error) {
  2901  	return w.write(len(s), nil, s)
  2902  }
  2903  
  2904  // either dataB or dataS is non-zero.
  2905  func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2906  	rws := w.rws
  2907  	if rws == nil {
  2908  		panic("Write called after Handler finished")
  2909  	}
  2910  	if !rws.wroteHeader {
  2911  		w.WriteHeader(200)
  2912  	}
  2913  	if !bodyAllowedForStatus(rws.status) {
  2914  		return 0, ErrBodyNotAllowed
  2915  	}
  2916  	rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2917  	if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2918  		// TODO: send a RST_STREAM
  2919  		return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2920  	}
  2921  
  2922  	if dataB != nil {
  2923  		return rws.bw.Write(dataB)
  2924  	} else {
  2925  		return rws.bw.WriteString(dataS)
  2926  	}
  2927  }
  2928  
  2929  func (w *responseWriter) handlerDone() {
  2930  	rws := w.rws
  2931  	rws.handlerDone = true
  2932  	w.Flush()
  2933  	w.rws = nil
  2934  	responseWriterStatePool.Put(rws)
  2935  }
  2936  
  2937  // Push errors.
  2938  var (
  2939  	ErrRecursivePush    = errors.New("http2: recursive push not allowed")
  2940  	ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2941  )
  2942  
  2943  func (w *responseWriter) Push(target, method string, header Header) error {
  2944  	st := w.rws.stream
  2945  	sc := st.sc
  2946  	sc.serveG.checkNotOn()
  2947  
  2948  	// No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2949  	// http://tools.ietf.org/html/rfc7540#section-6.6
  2950  	if st.isPushed() {
  2951  		return ErrRecursivePush
  2952  	}
  2953  
  2954  	// Default options.
  2955  	if method == "" {
  2956  		method = "GET"
  2957  	}
  2958  	if header == nil {
  2959  		header = Header{}
  2960  	}
  2961  	wantScheme := "http"
  2962  	if w.rws.req.TLS != nil {
  2963  		wantScheme = "https"
  2964  	}
  2965  
  2966  	// Validate the request.
  2967  	u, err := url.Parse(target)
  2968  	if err != nil {
  2969  		return err
  2970  	}
  2971  	if u.Scheme == "" {
  2972  		if !strings.HasPrefix(target, "/") {
  2973  			return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2974  		}
  2975  		u.Scheme = wantScheme
  2976  		u.Host = w.rws.req.Host
  2977  	} else {
  2978  		if u.Scheme != wantScheme {
  2979  			return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2980  		}
  2981  		if u.Host == "" {
  2982  			return errors.New("URL must have a host")
  2983  		}
  2984  	}
  2985  	for k := range header {
  2986  		if strings.HasPrefix(k, ":") {
  2987  			return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  2988  		}
  2989  		// These headers are meaningful only if the request has a body,
  2990  		// but PUSH_PROMISE requests cannot have a body.
  2991  		// http://tools.ietf.org/html/rfc7540#section-8.2
  2992  		// Also disallow Host, since the promised URL must be absolute.
  2993  		if asciiEqualFold(k, "content-length") ||
  2994  			asciiEqualFold(k, "content-encoding") ||
  2995  			asciiEqualFold(k, "trailer") ||
  2996  			asciiEqualFold(k, "te") ||
  2997  			asciiEqualFold(k, "expect") ||
  2998  			asciiEqualFold(k, "host") {
  2999  			return fmt.Errorf("promised request headers cannot include %q", k)
  3000  		}
  3001  	}
  3002  	if err := checkValidHTTP2RequestHeaders(header); err != nil {
  3003  		return err
  3004  	}
  3005  
  3006  	// The RFC effectively limits promised requests to GET and HEAD:
  3007  	// "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  3008  	// http://tools.ietf.org/html/rfc7540#section-8.2
  3009  	if method != "GET" && method != "HEAD" {
  3010  		return fmt.Errorf("method %q must be GET or HEAD", method)
  3011  	}
  3012  
  3013  	msg := &startPushRequest{
  3014  		parent: st,
  3015  		method: method,
  3016  		url:    u,
  3017  		header: cloneHeader(header),
  3018  		done:   sc.srv.getErrChan(),
  3019  	}
  3020  
  3021  	select {
  3022  	case <-sc.doneServing:
  3023  		return errClientDisconnected
  3024  	case <-st.cw:
  3025  		return errStreamClosed
  3026  	case sc.serveMsgCh <- msg:
  3027  	}
  3028  
  3029  	select {
  3030  	case <-sc.doneServing:
  3031  		return errClientDisconnected
  3032  	case <-st.cw:
  3033  		return errStreamClosed
  3034  	case err := <-msg.done:
  3035  		sc.srv.putErrChan(msg.done)
  3036  		return err
  3037  	}
  3038  }
  3039  
  3040  type startPushRequest struct {
  3041  	parent *stream
  3042  	method string
  3043  	url    *url.URL
  3044  	header Header
  3045  	done   chan error
  3046  }
  3047  
  3048  func (sc *serverConn) startPush(msg *startPushRequest) {
  3049  	sc.serveG.check()
  3050  
  3051  	// http://tools.ietf.org/html/rfc7540#section-6.6.
  3052  	// PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  3053  	// is in either the "open" or "half-closed (remote)" state.
  3054  	if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  3055  		// responseWriter.Push checks that the stream is peer-initiated.
  3056  		msg.done <- errStreamClosed
  3057  		return
  3058  	}
  3059  
  3060  	// http://tools.ietf.org/html/rfc7540#section-6.6.
  3061  	if !sc.pushEnabled {
  3062  		msg.done <- ErrNotSupported
  3063  		return
  3064  	}
  3065  
  3066  	// PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  3067  	// we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  3068  	// is written. Once the ID is allocated, we start the request handler.
  3069  	allocatePromisedID := func() (uint32, error) {
  3070  		sc.serveG.check()
  3071  
  3072  		// Check this again, just in case. Technically, we might have received
  3073  		// an updated SETTINGS by the time we got around to writing this frame.
  3074  		if !sc.pushEnabled {
  3075  			return 0, ErrNotSupported
  3076  		}
  3077  		// http://tools.ietf.org/html/rfc7540#section-6.5.2.
  3078  		if sc.curPushedStreams+1 > sc.clientMaxStreams {
  3079  			return 0, ErrPushLimitReached
  3080  		}
  3081  
  3082  		// http://tools.ietf.org/html/rfc7540#section-5.1.1.
  3083  		// Streams initiated by the server MUST use even-numbered identifiers.
  3084  		// A server that is unable to establish a new stream identifier can send a GOAWAY
  3085  		// frame so that the client is forced to open a new connection for new streams.
  3086  		if sc.maxPushPromiseID+2 >= 1<<31 {
  3087  			sc.startGracefulShutdownInternal()
  3088  			return 0, ErrPushLimitReached
  3089  		}
  3090  		sc.maxPushPromiseID += 2
  3091  		promisedID := sc.maxPushPromiseID
  3092  
  3093  		// http://tools.ietf.org/html/rfc7540#section-8.2.
  3094  		// Strictly speaking, the new stream should start in "reserved (local)", then
  3095  		// transition to "half closed (remote)" after sending the initial HEADERS, but
  3096  		// we start in "half closed (remote)" for simplicity.
  3097  		// See further comments at the definition of stateHalfClosedRemote.
  3098  		promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote, defaultRFC9218Priority(sc.priorityAware && !sc.hasIntermediary))
  3099  		rw, req, err := sc.newWriterAndRequestNoBody(promised, httpcommon.ServerRequestParam{
  3100  			Method:    msg.method,
  3101  			Scheme:    msg.url.Scheme,
  3102  			Authority: msg.url.Host,
  3103  			Path:      msg.url.RequestURI(),
  3104  			Header:    cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  3105  		})
  3106  		if err != nil {
  3107  			// Should not happen, since we've already validated msg.url.
  3108  			panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  3109  		}
  3110  
  3111  		sc.curHandlers++
  3112  		go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  3113  		return promisedID, nil
  3114  	}
  3115  
  3116  	sc.writeFrame(FrameWriteRequest{
  3117  		write: &writePushPromise{
  3118  			streamID:           msg.parent.id,
  3119  			method:             msg.method,
  3120  			url:                msg.url,
  3121  			h:                  msg.header,
  3122  			allocatePromisedID: allocatePromisedID,
  3123  		},
  3124  		stream: msg.parent,
  3125  		done:   msg.done,
  3126  	})
  3127  }
  3128  
  3129  // foreachHeaderElement splits v according to the "#rule" construction
  3130  // in RFC 7230 section 7 and calls fn for each non-empty element.
  3131  func foreachHeaderElement(v string, fn func(string)) {
  3132  	v = textproto.TrimString(v)
  3133  	if v == "" {
  3134  		return
  3135  	}
  3136  	if !strings.Contains(v, ",") {
  3137  		fn(v)
  3138  		return
  3139  	}
  3140  	for f := range strings.SplitSeq(v, ",") {
  3141  		if f = textproto.TrimString(f); f != "" {
  3142  			fn(f)
  3143  		}
  3144  	}
  3145  }
  3146  
  3147  // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  3148  var connHeaders = []string{
  3149  	"Connection",
  3150  	"Keep-Alive",
  3151  	"Proxy-Connection",
  3152  	"Transfer-Encoding",
  3153  	"Upgrade",
  3154  }
  3155  
  3156  // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  3157  // per RFC 7540 Section 8.1.2.2.
  3158  // The returned error is reported to users.
  3159  func checkValidHTTP2RequestHeaders(h Header) error {
  3160  	for _, k := range connHeaders {
  3161  		if _, ok := h[k]; ok {
  3162  			return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  3163  		}
  3164  	}
  3165  	te := h["Te"]
  3166  	if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  3167  		return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  3168  	}
  3169  	return nil
  3170  }
  3171  
  3172  type serve400Handler struct {
  3173  	err error
  3174  }
  3175  
  3176  func (handler serve400Handler) ServeHTTP(w *ResponseWriter, r *ServerRequest) {
  3177  	const statusBadRequest = 400
  3178  
  3179  	// TODO: Dedup with http.Error?
  3180  	h := w.Header()
  3181  	h.Del("Content-Length")
  3182  	h.Set("Content-Type", "text/plain; charset=utf-8")
  3183  	h.Set("X-Content-Type-Options", "nosniff")
  3184  	w.WriteHeader(statusBadRequest)
  3185  	fmt.Fprintln(w, handler.err.Error())
  3186  }
  3187  
  3188  // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  3189  // disabled. See comments on h1ServerShutdownChan above for why
  3190  // the code is written this way.
  3191  func h1ServerKeepAlivesDisabled(hs ServerConfig) bool {
  3192  	return !hs.DoKeepAlives()
  3193  }
  3194  
  3195  func (sc *serverConn) countError(name string, err error) error {
  3196  	if sc == nil || sc.srv == nil {
  3197  		return err
  3198  	}
  3199  	f := sc.countErrorFunc
  3200  	if f == nil {
  3201  		return err
  3202  	}
  3203  	var typ string
  3204  	var code ErrCode
  3205  	switch e := err.(type) {
  3206  	case ConnectionError:
  3207  		typ = "conn"
  3208  		code = ErrCode(e)
  3209  	case StreamError:
  3210  		typ = "stream"
  3211  		code = ErrCode(e.Code)
  3212  	default:
  3213  		return err
  3214  	}
  3215  	codeStr := errCodeName[code]
  3216  	if codeStr == "" {
  3217  		codeStr = strconv.Itoa(int(code))
  3218  	}
  3219  	f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
  3220  	return err
  3221  }
  3222  

View as plain text