github.com/lianghucheng/zrddz@v0.0.0-20200923083010-c71f680932e2/src/golang.org/x/net/http2/server_test.go (about)

     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  package http2
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"crypto/tls"
    11  	"errors"
    12  	"flag"
    13  	"fmt"
    14  	"io"
    15  	"io/ioutil"
    16  	"log"
    17  	"net"
    18  	"net/http"
    19  	"net/http/httptest"
    20  	"os"
    21  	"os/exec"
    22  	"reflect"
    23  	"runtime"
    24  	"strconv"
    25  	"strings"
    26  	"sync"
    27  	"sync/atomic"
    28  	"testing"
    29  	"time"
    30  
    31  	"golang.org/x/net/http2/hpack"
    32  )
    33  
    34  var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered")
    35  
    36  func stderrv() io.Writer {
    37  	if *stderrVerbose {
    38  		return os.Stderr
    39  	}
    40  
    41  	return ioutil.Discard
    42  }
    43  
    44  type serverTester struct {
    45  	cc             net.Conn // client conn
    46  	t              testing.TB
    47  	ts             *httptest.Server
    48  	fr             *Framer
    49  	serverLogBuf   bytes.Buffer // logger for httptest.Server
    50  	logFilter      []string     // substrings to filter out
    51  	scMu           sync.Mutex   // guards sc
    52  	sc             *serverConn
    53  	hpackDec       *hpack.Decoder
    54  	decodedHeaders [][2]string
    55  
    56  	// If http2debug!=2, then we capture Frame debug logs that will be written
    57  	// to t.Log after a test fails. The read and write logs use separate locks
    58  	// and buffers so we don't accidentally introduce synchronization between
    59  	// the read and write goroutines, which may hide data races.
    60  	frameReadLogMu   sync.Mutex
    61  	frameReadLogBuf  bytes.Buffer
    62  	frameWriteLogMu  sync.Mutex
    63  	frameWriteLogBuf bytes.Buffer
    64  
    65  	// writing headers:
    66  	headerBuf bytes.Buffer
    67  	hpackEnc  *hpack.Encoder
    68  }
    69  
    70  func init() {
    71  	testHookOnPanicMu = new(sync.Mutex)
    72  	goAwayTimeout = 25 * time.Millisecond
    73  }
    74  
    75  func resetHooks() {
    76  	testHookOnPanicMu.Lock()
    77  	testHookOnPanic = nil
    78  	testHookOnPanicMu.Unlock()
    79  }
    80  
    81  type serverTesterOpt string
    82  
    83  var optOnlyServer = serverTesterOpt("only_server")
    84  var optQuiet = serverTesterOpt("quiet_logging")
    85  var optFramerReuseFrames = serverTesterOpt("frame_reuse_frames")
    86  
    87  func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester {
    88  	resetHooks()
    89  
    90  	ts := httptest.NewUnstartedServer(handler)
    91  
    92  	tlsConfig := &tls.Config{
    93  		InsecureSkipVerify: true,
    94  		NextProtos:         []string{NextProtoTLS},
    95  	}
    96  
    97  	var onlyServer, quiet, framerReuseFrames bool
    98  	h2server := new(Server)
    99  	for _, opt := range opts {
   100  		switch v := opt.(type) {
   101  		case func(*tls.Config):
   102  			v(tlsConfig)
   103  		case func(*httptest.Server):
   104  			v(ts)
   105  		case func(*Server):
   106  			v(h2server)
   107  		case serverTesterOpt:
   108  			switch v {
   109  			case optOnlyServer:
   110  				onlyServer = true
   111  			case optQuiet:
   112  				quiet = true
   113  			case optFramerReuseFrames:
   114  				framerReuseFrames = true
   115  			}
   116  		case func(net.Conn, http.ConnState):
   117  			ts.Config.ConnState = v
   118  		default:
   119  			t.Fatalf("unknown newServerTester option type %T", v)
   120  		}
   121  	}
   122  
   123  	ConfigureServer(ts.Config, h2server)
   124  
   125  	st := &serverTester{
   126  		t:  t,
   127  		ts: ts,
   128  	}
   129  	st.hpackEnc = hpack.NewEncoder(&st.headerBuf)
   130  	st.hpackDec = hpack.NewDecoder(initialHeaderTableSize, st.onHeaderField)
   131  
   132  	ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
   133  	if quiet {
   134  		ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
   135  	} else {
   136  		ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv(), twriter{t: t, st: st}, &st.serverLogBuf), "", log.LstdFlags)
   137  	}
   138  	ts.StartTLS()
   139  
   140  	if VerboseLogs {
   141  		t.Logf("Running test server at: %s", ts.URL)
   142  	}
   143  	testHookGetServerConn = func(v *serverConn) {
   144  		st.scMu.Lock()
   145  		defer st.scMu.Unlock()
   146  		st.sc = v
   147  	}
   148  	log.SetOutput(io.MultiWriter(stderrv(), twriter{t: t, st: st}))
   149  	if !onlyServer {
   150  		cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig)
   151  		if err != nil {
   152  			t.Fatal(err)
   153  		}
   154  		st.cc = cc
   155  		st.fr = NewFramer(cc, cc)
   156  		if framerReuseFrames {
   157  			st.fr.SetReuseFrames()
   158  		}
   159  		if !logFrameReads && !logFrameWrites {
   160  			st.fr.debugReadLoggerf = func(m string, v ...interface{}) {
   161  				m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n"
   162  				st.frameReadLogMu.Lock()
   163  				fmt.Fprintf(&st.frameReadLogBuf, m, v...)
   164  				st.frameReadLogMu.Unlock()
   165  			}
   166  			st.fr.debugWriteLoggerf = func(m string, v ...interface{}) {
   167  				m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n"
   168  				st.frameWriteLogMu.Lock()
   169  				fmt.Fprintf(&st.frameWriteLogBuf, m, v...)
   170  				st.frameWriteLogMu.Unlock()
   171  			}
   172  			st.fr.logReads = true
   173  			st.fr.logWrites = true
   174  		}
   175  	}
   176  	return st
   177  }
   178  
   179  func (st *serverTester) closeConn() {
   180  	st.scMu.Lock()
   181  	defer st.scMu.Unlock()
   182  	st.sc.conn.Close()
   183  }
   184  
   185  func (st *serverTester) addLogFilter(phrase string) {
   186  	st.logFilter = append(st.logFilter, phrase)
   187  }
   188  
   189  func (st *serverTester) stream(id uint32) *stream {
   190  	ch := make(chan *stream, 1)
   191  	st.sc.serveMsgCh <- func(int) {
   192  		ch <- st.sc.streams[id]
   193  	}
   194  	return <-ch
   195  }
   196  
   197  func (st *serverTester) streamState(id uint32) streamState {
   198  	ch := make(chan streamState, 1)
   199  	st.sc.serveMsgCh <- func(int) {
   200  		state, _ := st.sc.state(id)
   201  		ch <- state
   202  	}
   203  	return <-ch
   204  }
   205  
   206  // loopNum reports how many times this conn's select loop has gone around.
   207  func (st *serverTester) loopNum() int {
   208  	lastc := make(chan int, 1)
   209  	st.sc.serveMsgCh <- func(loopNum int) {
   210  		lastc <- loopNum
   211  	}
   212  	return <-lastc
   213  }
   214  
   215  // awaitIdle heuristically awaits for the server conn's select loop to be idle.
   216  // The heuristic is that the server connection's serve loop must schedule
   217  // 50 times in a row without any channel sends or receives occurring.
   218  func (st *serverTester) awaitIdle() {
   219  	remain := 50
   220  	last := st.loopNum()
   221  	for remain > 0 {
   222  		n := st.loopNum()
   223  		if n == last+1 {
   224  			remain--
   225  		} else {
   226  			remain = 50
   227  		}
   228  		last = n
   229  	}
   230  }
   231  
   232  func (st *serverTester) Close() {
   233  	if st.t.Failed() {
   234  		st.frameReadLogMu.Lock()
   235  		if st.frameReadLogBuf.Len() > 0 {
   236  			st.t.Logf("Framer read log:\n%s", st.frameReadLogBuf.String())
   237  		}
   238  		st.frameReadLogMu.Unlock()
   239  
   240  		st.frameWriteLogMu.Lock()
   241  		if st.frameWriteLogBuf.Len() > 0 {
   242  			st.t.Logf("Framer write log:\n%s", st.frameWriteLogBuf.String())
   243  		}
   244  		st.frameWriteLogMu.Unlock()
   245  
   246  		// If we failed already (and are likely in a Fatal,
   247  		// unwindowing), force close the connection, so the
   248  		// httptest.Server doesn't wait forever for the conn
   249  		// to close.
   250  		if st.cc != nil {
   251  			st.cc.Close()
   252  		}
   253  	}
   254  	st.ts.Close()
   255  	if st.cc != nil {
   256  		st.cc.Close()
   257  	}
   258  	log.SetOutput(os.Stderr)
   259  }
   260  
   261  // greet initiates the client's HTTP/2 connection into a state where
   262  // frames may be sent.
   263  func (st *serverTester) greet() {
   264  	st.greetAndCheckSettings(func(Setting) error { return nil })
   265  }
   266  
   267  func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error) {
   268  	st.writePreface()
   269  	st.writeInitialSettings()
   270  	st.wantSettings().ForeachSetting(checkSetting)
   271  	st.writeSettingsAck()
   272  
   273  	// The initial WINDOW_UPDATE and SETTINGS ACK can come in any order.
   274  	var gotSettingsAck bool
   275  	var gotWindowUpdate bool
   276  
   277  	for i := 0; i < 2; i++ {
   278  		f, err := st.readFrame()
   279  		if err != nil {
   280  			st.t.Fatal(err)
   281  		}
   282  		switch f := f.(type) {
   283  		case *SettingsFrame:
   284  			if !f.Header().Flags.Has(FlagSettingsAck) {
   285  				st.t.Fatal("Settings Frame didn't have ACK set")
   286  			}
   287  			gotSettingsAck = true
   288  
   289  		case *WindowUpdateFrame:
   290  			if f.FrameHeader.StreamID != 0 {
   291  				st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID)
   292  			}
   293  			incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize)
   294  			if f.Increment != incr {
   295  				st.t.Fatalf("WindowUpdate increment = %d; want %d", f.Increment, incr)
   296  			}
   297  			gotWindowUpdate = true
   298  
   299  		default:
   300  			st.t.Fatalf("Wanting a settings ACK or window update, received a %T", f)
   301  		}
   302  	}
   303  
   304  	if !gotSettingsAck {
   305  		st.t.Fatalf("Didn't get a settings ACK")
   306  	}
   307  	if !gotWindowUpdate {
   308  		st.t.Fatalf("Didn't get a window update")
   309  	}
   310  }
   311  
   312  func (st *serverTester) writePreface() {
   313  	n, err := st.cc.Write(clientPreface)
   314  	if err != nil {
   315  		st.t.Fatalf("Error writing client preface: %v", err)
   316  	}
   317  	if n != len(clientPreface) {
   318  		st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface))
   319  	}
   320  }
   321  
   322  func (st *serverTester) writeInitialSettings() {
   323  	if err := st.fr.WriteSettings(); err != nil {
   324  		st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err)
   325  	}
   326  }
   327  
   328  func (st *serverTester) writeSettingsAck() {
   329  	if err := st.fr.WriteSettingsAck(); err != nil {
   330  		st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err)
   331  	}
   332  }
   333  
   334  func (st *serverTester) writeHeaders(p HeadersFrameParam) {
   335  	if err := st.fr.WriteHeaders(p); err != nil {
   336  		st.t.Fatalf("Error writing HEADERS: %v", err)
   337  	}
   338  }
   339  
   340  func (st *serverTester) writePriority(id uint32, p PriorityParam) {
   341  	if err := st.fr.WritePriority(id, p); err != nil {
   342  		st.t.Fatalf("Error writing PRIORITY: %v", err)
   343  	}
   344  }
   345  
   346  func (st *serverTester) encodeHeaderField(k, v string) {
   347  	err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v})
   348  	if err != nil {
   349  		st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
   350  	}
   351  }
   352  
   353  // encodeHeaderRaw is the magic-free version of encodeHeader.
   354  // It takes 0 or more (k, v) pairs and encodes them.
   355  func (st *serverTester) encodeHeaderRaw(headers ...string) []byte {
   356  	if len(headers)%2 == 1 {
   357  		panic("odd number of kv args")
   358  	}
   359  	st.headerBuf.Reset()
   360  	for len(headers) > 0 {
   361  		k, v := headers[0], headers[1]
   362  		st.encodeHeaderField(k, v)
   363  		headers = headers[2:]
   364  	}
   365  	return st.headerBuf.Bytes()
   366  }
   367  
   368  // encodeHeader encodes headers and returns their HPACK bytes. headers
   369  // must contain an even number of key/value pairs. There may be
   370  // multiple pairs for keys (e.g. "cookie").  The :method, :path, and
   371  // :scheme headers default to GET, / and https. The :authority header
   372  // defaults to st.ts.Listener.Addr().
   373  func (st *serverTester) encodeHeader(headers ...string) []byte {
   374  	if len(headers)%2 == 1 {
   375  		panic("odd number of kv args")
   376  	}
   377  
   378  	st.headerBuf.Reset()
   379  	defaultAuthority := st.ts.Listener.Addr().String()
   380  
   381  	if len(headers) == 0 {
   382  		// Fast path, mostly for benchmarks, so test code doesn't pollute
   383  		// profiles when we're looking to improve server allocations.
   384  		st.encodeHeaderField(":method", "GET")
   385  		st.encodeHeaderField(":scheme", "https")
   386  		st.encodeHeaderField(":authority", defaultAuthority)
   387  		st.encodeHeaderField(":path", "/")
   388  		return st.headerBuf.Bytes()
   389  	}
   390  
   391  	if len(headers) == 2 && headers[0] == ":method" {
   392  		// Another fast path for benchmarks.
   393  		st.encodeHeaderField(":method", headers[1])
   394  		st.encodeHeaderField(":scheme", "https")
   395  		st.encodeHeaderField(":authority", defaultAuthority)
   396  		st.encodeHeaderField(":path", "/")
   397  		return st.headerBuf.Bytes()
   398  	}
   399  
   400  	pseudoCount := map[string]int{}
   401  	keys := []string{":method", ":scheme", ":authority", ":path"}
   402  	vals := map[string][]string{
   403  		":method":    {"GET"},
   404  		":scheme":    {"https"},
   405  		":authority": {defaultAuthority},
   406  		":path":      {"/"},
   407  	}
   408  	for len(headers) > 0 {
   409  		k, v := headers[0], headers[1]
   410  		headers = headers[2:]
   411  		if _, ok := vals[k]; !ok {
   412  			keys = append(keys, k)
   413  		}
   414  		if strings.HasPrefix(k, ":") {
   415  			pseudoCount[k]++
   416  			if pseudoCount[k] == 1 {
   417  				vals[k] = []string{v}
   418  			} else {
   419  				// Allows testing of invalid headers w/ dup pseudo fields.
   420  				vals[k] = append(vals[k], v)
   421  			}
   422  		} else {
   423  			vals[k] = append(vals[k], v)
   424  		}
   425  	}
   426  	for _, k := range keys {
   427  		for _, v := range vals[k] {
   428  			st.encodeHeaderField(k, v)
   429  		}
   430  	}
   431  	return st.headerBuf.Bytes()
   432  }
   433  
   434  // bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set.
   435  func (st *serverTester) bodylessReq1(headers ...string) {
   436  	st.writeHeaders(HeadersFrameParam{
   437  		StreamID:      1, // clients send odd numbers
   438  		BlockFragment: st.encodeHeader(headers...),
   439  		EndStream:     true,
   440  		EndHeaders:    true,
   441  	})
   442  }
   443  
   444  func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) {
   445  	if err := st.fr.WriteData(streamID, endStream, data); err != nil {
   446  		st.t.Fatalf("Error writing DATA: %v", err)
   447  	}
   448  }
   449  
   450  func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, pad []byte) {
   451  	if err := st.fr.WriteDataPadded(streamID, endStream, data, pad); err != nil {
   452  		st.t.Fatalf("Error writing DATA: %v", err)
   453  	}
   454  }
   455  
   456  func readFrameTimeout(fr *Framer, wait time.Duration) (Frame, error) {
   457  	ch := make(chan interface{}, 1)
   458  	go func() {
   459  		fr, err := fr.ReadFrame()
   460  		if err != nil {
   461  			ch <- err
   462  		} else {
   463  			ch <- fr
   464  		}
   465  	}()
   466  	t := time.NewTimer(wait)
   467  	select {
   468  	case v := <-ch:
   469  		t.Stop()
   470  		if fr, ok := v.(Frame); ok {
   471  			return fr, nil
   472  		}
   473  		return nil, v.(error)
   474  	case <-t.C:
   475  		return nil, errors.New("timeout waiting for frame")
   476  	}
   477  }
   478  
   479  func (st *serverTester) readFrame() (Frame, error) {
   480  	return readFrameTimeout(st.fr, 2*time.Second)
   481  }
   482  
   483  func (st *serverTester) wantHeaders() *HeadersFrame {
   484  	f, err := st.readFrame()
   485  	if err != nil {
   486  		st.t.Fatalf("Error while expecting a HEADERS frame: %v", err)
   487  	}
   488  	hf, ok := f.(*HeadersFrame)
   489  	if !ok {
   490  		st.t.Fatalf("got a %T; want *HeadersFrame", f)
   491  	}
   492  	return hf
   493  }
   494  
   495  func (st *serverTester) wantContinuation() *ContinuationFrame {
   496  	f, err := st.readFrame()
   497  	if err != nil {
   498  		st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err)
   499  	}
   500  	cf, ok := f.(*ContinuationFrame)
   501  	if !ok {
   502  		st.t.Fatalf("got a %T; want *ContinuationFrame", f)
   503  	}
   504  	return cf
   505  }
   506  
   507  func (st *serverTester) wantData() *DataFrame {
   508  	f, err := st.readFrame()
   509  	if err != nil {
   510  		st.t.Fatalf("Error while expecting a DATA frame: %v", err)
   511  	}
   512  	df, ok := f.(*DataFrame)
   513  	if !ok {
   514  		st.t.Fatalf("got a %T; want *DataFrame", f)
   515  	}
   516  	return df
   517  }
   518  
   519  func (st *serverTester) wantSettings() *SettingsFrame {
   520  	f, err := st.readFrame()
   521  	if err != nil {
   522  		st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err)
   523  	}
   524  	sf, ok := f.(*SettingsFrame)
   525  	if !ok {
   526  		st.t.Fatalf("got a %T; want *SettingsFrame", f)
   527  	}
   528  	return sf
   529  }
   530  
   531  func (st *serverTester) wantPing() *PingFrame {
   532  	f, err := st.readFrame()
   533  	if err != nil {
   534  		st.t.Fatalf("Error while expecting a PING frame: %v", err)
   535  	}
   536  	pf, ok := f.(*PingFrame)
   537  	if !ok {
   538  		st.t.Fatalf("got a %T; want *PingFrame", f)
   539  	}
   540  	return pf
   541  }
   542  
   543  func (st *serverTester) wantGoAway() *GoAwayFrame {
   544  	f, err := st.readFrame()
   545  	if err != nil {
   546  		st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err)
   547  	}
   548  	gf, ok := f.(*GoAwayFrame)
   549  	if !ok {
   550  		st.t.Fatalf("got a %T; want *GoAwayFrame", f)
   551  	}
   552  	return gf
   553  }
   554  
   555  func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) {
   556  	f, err := st.readFrame()
   557  	if err != nil {
   558  		st.t.Fatalf("Error while expecting an RSTStream frame: %v", err)
   559  	}
   560  	rs, ok := f.(*RSTStreamFrame)
   561  	if !ok {
   562  		st.t.Fatalf("got a %T; want *RSTStreamFrame", f)
   563  	}
   564  	if rs.FrameHeader.StreamID != streamID {
   565  		st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID)
   566  	}
   567  	if rs.ErrCode != errCode {
   568  		st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode)
   569  	}
   570  }
   571  
   572  func (st *serverTester) wantWindowUpdate(streamID, incr uint32) {
   573  	f, err := st.readFrame()
   574  	if err != nil {
   575  		st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err)
   576  	}
   577  	wu, ok := f.(*WindowUpdateFrame)
   578  	if !ok {
   579  		st.t.Fatalf("got a %T; want *WindowUpdateFrame", f)
   580  	}
   581  	if wu.FrameHeader.StreamID != streamID {
   582  		st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID)
   583  	}
   584  	if wu.Increment != incr {
   585  		st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr)
   586  	}
   587  }
   588  
   589  func (st *serverTester) wantSettingsAck() {
   590  	f, err := st.readFrame()
   591  	if err != nil {
   592  		st.t.Fatal(err)
   593  	}
   594  	sf, ok := f.(*SettingsFrame)
   595  	if !ok {
   596  		st.t.Fatalf("Wanting a settings ACK, received a %T", f)
   597  	}
   598  	if !sf.Header().Flags.Has(FlagSettingsAck) {
   599  		st.t.Fatal("Settings Frame didn't have ACK set")
   600  	}
   601  }
   602  
   603  func (st *serverTester) wantPushPromise() *PushPromiseFrame {
   604  	f, err := st.readFrame()
   605  	if err != nil {
   606  		st.t.Fatal(err)
   607  	}
   608  	ppf, ok := f.(*PushPromiseFrame)
   609  	if !ok {
   610  		st.t.Fatalf("Wanted PushPromise, received %T", ppf)
   611  	}
   612  	return ppf
   613  }
   614  
   615  func TestServer(t *testing.T) {
   616  	gotReq := make(chan bool, 1)
   617  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
   618  		w.Header().Set("Foo", "Bar")
   619  		gotReq <- true
   620  	})
   621  	defer st.Close()
   622  
   623  	covers("3.5", `
   624  		The server connection preface consists of a potentially empty
   625  		SETTINGS frame ([SETTINGS]) that MUST be the first frame the
   626  		server sends in the HTTP/2 connection.
   627  	`)
   628  
   629  	st.greet()
   630  	st.writeHeaders(HeadersFrameParam{
   631  		StreamID:      1, // clients send odd numbers
   632  		BlockFragment: st.encodeHeader(),
   633  		EndStream:     true, // no DATA frames
   634  		EndHeaders:    true,
   635  	})
   636  
   637  	select {
   638  	case <-gotReq:
   639  	case <-time.After(2 * time.Second):
   640  		t.Error("timeout waiting for request")
   641  	}
   642  }
   643  
   644  func TestServer_Request_Get(t *testing.T) {
   645  	testServerRequest(t, func(st *serverTester) {
   646  		st.writeHeaders(HeadersFrameParam{
   647  			StreamID:      1, // clients send odd numbers
   648  			BlockFragment: st.encodeHeader("foo-bar", "some-value"),
   649  			EndStream:     true, // no DATA frames
   650  			EndHeaders:    true,
   651  		})
   652  	}, func(r *http.Request) {
   653  		if r.Method != "GET" {
   654  			t.Errorf("Method = %q; want GET", r.Method)
   655  		}
   656  		if r.URL.Path != "/" {
   657  			t.Errorf("URL.Path = %q; want /", r.URL.Path)
   658  		}
   659  		if r.ContentLength != 0 {
   660  			t.Errorf("ContentLength = %v; want 0", r.ContentLength)
   661  		}
   662  		if r.Close {
   663  			t.Error("Close = true; want false")
   664  		}
   665  		if !strings.Contains(r.RemoteAddr, ":") {
   666  			t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr)
   667  		}
   668  		if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 {
   669  			t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor)
   670  		}
   671  		wantHeader := http.Header{
   672  			"Foo-Bar": []string{"some-value"},
   673  		}
   674  		if !reflect.DeepEqual(r.Header, wantHeader) {
   675  			t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
   676  		}
   677  		if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
   678  			t.Errorf("Read = %d, %v; want 0, EOF", n, err)
   679  		}
   680  	})
   681  }
   682  
   683  func TestServer_Request_Get_PathSlashes(t *testing.T) {
   684  	testServerRequest(t, func(st *serverTester) {
   685  		st.writeHeaders(HeadersFrameParam{
   686  			StreamID:      1, // clients send odd numbers
   687  			BlockFragment: st.encodeHeader(":path", "/%2f/"),
   688  			EndStream:     true, // no DATA frames
   689  			EndHeaders:    true,
   690  		})
   691  	}, func(r *http.Request) {
   692  		if r.RequestURI != "/%2f/" {
   693  			t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI)
   694  		}
   695  		if r.URL.Path != "///" {
   696  			t.Errorf("URL.Path = %q; want ///", r.URL.Path)
   697  		}
   698  	})
   699  }
   700  
   701  // TODO: add a test with EndStream=true on the HEADERS but setting a
   702  // Content-Length anyway. Should we just omit it and force it to
   703  // zero?
   704  
   705  func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) {
   706  	testServerRequest(t, func(st *serverTester) {
   707  		st.writeHeaders(HeadersFrameParam{
   708  			StreamID:      1, // clients send odd numbers
   709  			BlockFragment: st.encodeHeader(":method", "POST"),
   710  			EndStream:     true,
   711  			EndHeaders:    true,
   712  		})
   713  	}, func(r *http.Request) {
   714  		if r.Method != "POST" {
   715  			t.Errorf("Method = %q; want POST", r.Method)
   716  		}
   717  		if r.ContentLength != 0 {
   718  			t.Errorf("ContentLength = %v; want 0", r.ContentLength)
   719  		}
   720  		if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 {
   721  			t.Errorf("Read = %d, %v; want 0, EOF", n, err)
   722  		}
   723  	})
   724  }
   725  
   726  func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) {
   727  	testBodyContents(t, -1, "", func(st *serverTester) {
   728  		st.writeHeaders(HeadersFrameParam{
   729  			StreamID:      1, // clients send odd numbers
   730  			BlockFragment: st.encodeHeader(":method", "POST"),
   731  			EndStream:     false, // to say DATA frames are coming
   732  			EndHeaders:    true,
   733  		})
   734  		st.writeData(1, true, nil) // just kidding. empty body.
   735  	})
   736  }
   737  
   738  func TestServer_Request_Post_Body_OneData(t *testing.T) {
   739  	const content = "Some content"
   740  	testBodyContents(t, -1, content, func(st *serverTester) {
   741  		st.writeHeaders(HeadersFrameParam{
   742  			StreamID:      1, // clients send odd numbers
   743  			BlockFragment: st.encodeHeader(":method", "POST"),
   744  			EndStream:     false, // to say DATA frames are coming
   745  			EndHeaders:    true,
   746  		})
   747  		st.writeData(1, true, []byte(content))
   748  	})
   749  }
   750  
   751  func TestServer_Request_Post_Body_TwoData(t *testing.T) {
   752  	const content = "Some content"
   753  	testBodyContents(t, -1, content, func(st *serverTester) {
   754  		st.writeHeaders(HeadersFrameParam{
   755  			StreamID:      1, // clients send odd numbers
   756  			BlockFragment: st.encodeHeader(":method", "POST"),
   757  			EndStream:     false, // to say DATA frames are coming
   758  			EndHeaders:    true,
   759  		})
   760  		st.writeData(1, false, []byte(content[:5]))
   761  		st.writeData(1, true, []byte(content[5:]))
   762  	})
   763  }
   764  
   765  func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) {
   766  	const content = "Some content"
   767  	testBodyContents(t, int64(len(content)), content, func(st *serverTester) {
   768  		st.writeHeaders(HeadersFrameParam{
   769  			StreamID: 1, // clients send odd numbers
   770  			BlockFragment: st.encodeHeader(
   771  				":method", "POST",
   772  				"content-length", strconv.Itoa(len(content)),
   773  			),
   774  			EndStream:  false, // to say DATA frames are coming
   775  			EndHeaders: true,
   776  		})
   777  		st.writeData(1, true, []byte(content))
   778  	})
   779  }
   780  
   781  func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) {
   782  	testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes",
   783  		func(st *serverTester) {
   784  			st.writeHeaders(HeadersFrameParam{
   785  				StreamID: 1, // clients send odd numbers
   786  				BlockFragment: st.encodeHeader(
   787  					":method", "POST",
   788  					"content-length", "3",
   789  				),
   790  				EndStream:  false, // to say DATA frames are coming
   791  				EndHeaders: true,
   792  			})
   793  			st.writeData(1, true, []byte("12"))
   794  		})
   795  }
   796  
   797  func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) {
   798  	testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes",
   799  		func(st *serverTester) {
   800  			st.writeHeaders(HeadersFrameParam{
   801  				StreamID: 1, // clients send odd numbers
   802  				BlockFragment: st.encodeHeader(
   803  					":method", "POST",
   804  					"content-length", "4",
   805  				),
   806  				EndStream:  false, // to say DATA frames are coming
   807  				EndHeaders: true,
   808  			})
   809  			st.writeData(1, true, []byte("12345"))
   810  		})
   811  }
   812  
   813  func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) {
   814  	testServerRequest(t, write, func(r *http.Request) {
   815  		if r.Method != "POST" {
   816  			t.Errorf("Method = %q; want POST", r.Method)
   817  		}
   818  		if r.ContentLength != wantContentLength {
   819  			t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
   820  		}
   821  		all, err := ioutil.ReadAll(r.Body)
   822  		if err != nil {
   823  			t.Fatal(err)
   824  		}
   825  		if string(all) != wantBody {
   826  			t.Errorf("Read = %q; want %q", all, wantBody)
   827  		}
   828  		if err := r.Body.Close(); err != nil {
   829  			t.Fatalf("Close: %v", err)
   830  		}
   831  	})
   832  }
   833  
   834  func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) {
   835  	testServerRequest(t, write, func(r *http.Request) {
   836  		if r.Method != "POST" {
   837  			t.Errorf("Method = %q; want POST", r.Method)
   838  		}
   839  		if r.ContentLength != wantContentLength {
   840  			t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength)
   841  		}
   842  		all, err := ioutil.ReadAll(r.Body)
   843  		if err == nil {
   844  			t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.",
   845  				wantReadError, all)
   846  		}
   847  		if !strings.Contains(err.Error(), wantReadError) {
   848  			t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError)
   849  		}
   850  		if err := r.Body.Close(); err != nil {
   851  			t.Fatalf("Close: %v", err)
   852  		}
   853  	})
   854  }
   855  
   856  // Using a Host header, instead of :authority
   857  func TestServer_Request_Get_Host(t *testing.T) {
   858  	const host = "example.com"
   859  	testServerRequest(t, func(st *serverTester) {
   860  		st.writeHeaders(HeadersFrameParam{
   861  			StreamID:      1, // clients send odd numbers
   862  			BlockFragment: st.encodeHeader(":authority", "", "host", host),
   863  			EndStream:     true,
   864  			EndHeaders:    true,
   865  		})
   866  	}, func(r *http.Request) {
   867  		if r.Host != host {
   868  			t.Errorf("Host = %q; want %q", r.Host, host)
   869  		}
   870  	})
   871  }
   872  
   873  // Using an :authority pseudo-header, instead of Host
   874  func TestServer_Request_Get_Authority(t *testing.T) {
   875  	const host = "example.com"
   876  	testServerRequest(t, func(st *serverTester) {
   877  		st.writeHeaders(HeadersFrameParam{
   878  			StreamID:      1, // clients send odd numbers
   879  			BlockFragment: st.encodeHeader(":authority", host),
   880  			EndStream:     true,
   881  			EndHeaders:    true,
   882  		})
   883  	}, func(r *http.Request) {
   884  		if r.Host != host {
   885  			t.Errorf("Host = %q; want %q", r.Host, host)
   886  		}
   887  	})
   888  }
   889  
   890  func TestServer_Request_WithContinuation(t *testing.T) {
   891  	wantHeader := http.Header{
   892  		"Foo-One":   []string{"value-one"},
   893  		"Foo-Two":   []string{"value-two"},
   894  		"Foo-Three": []string{"value-three"},
   895  	}
   896  	testServerRequest(t, func(st *serverTester) {
   897  		fullHeaders := st.encodeHeader(
   898  			"foo-one", "value-one",
   899  			"foo-two", "value-two",
   900  			"foo-three", "value-three",
   901  		)
   902  		remain := fullHeaders
   903  		chunks := 0
   904  		for len(remain) > 0 {
   905  			const maxChunkSize = 5
   906  			chunk := remain
   907  			if len(chunk) > maxChunkSize {
   908  				chunk = chunk[:maxChunkSize]
   909  			}
   910  			remain = remain[len(chunk):]
   911  
   912  			if chunks == 0 {
   913  				st.writeHeaders(HeadersFrameParam{
   914  					StreamID:      1, // clients send odd numbers
   915  					BlockFragment: chunk,
   916  					EndStream:     true,  // no DATA frames
   917  					EndHeaders:    false, // we'll have continuation frames
   918  				})
   919  			} else {
   920  				err := st.fr.WriteContinuation(1, len(remain) == 0, chunk)
   921  				if err != nil {
   922  					t.Fatal(err)
   923  				}
   924  			}
   925  			chunks++
   926  		}
   927  		if chunks < 2 {
   928  			t.Fatal("too few chunks")
   929  		}
   930  	}, func(r *http.Request) {
   931  		if !reflect.DeepEqual(r.Header, wantHeader) {
   932  			t.Errorf("Header = %#v; want %#v", r.Header, wantHeader)
   933  		}
   934  	})
   935  }
   936  
   937  // Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field")
   938  func TestServer_Request_CookieConcat(t *testing.T) {
   939  	const host = "example.com"
   940  	testServerRequest(t, func(st *serverTester) {
   941  		st.bodylessReq1(
   942  			":authority", host,
   943  			"cookie", "a=b",
   944  			"cookie", "c=d",
   945  			"cookie", "e=f",
   946  		)
   947  	}, func(r *http.Request) {
   948  		const want = "a=b; c=d; e=f"
   949  		if got := r.Header.Get("Cookie"); got != want {
   950  			t.Errorf("Cookie = %q; want %q", got, want)
   951  		}
   952  	})
   953  }
   954  
   955  func TestServer_Request_Reject_CapitalHeader(t *testing.T) {
   956  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") })
   957  }
   958  
   959  func TestServer_Request_Reject_HeaderFieldNameColon(t *testing.T) {
   960  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has:colon", "v") })
   961  }
   962  
   963  func TestServer_Request_Reject_HeaderFieldNameNULL(t *testing.T) {
   964  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has\x00null", "v") })
   965  }
   966  
   967  func TestServer_Request_Reject_HeaderFieldNameEmpty(t *testing.T) {
   968  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("", "v") })
   969  }
   970  
   971  func TestServer_Request_Reject_HeaderFieldValueNewline(t *testing.T) {
   972  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\nnewline") })
   973  }
   974  
   975  func TestServer_Request_Reject_HeaderFieldValueCR(t *testing.T) {
   976  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\rcarriage") })
   977  }
   978  
   979  func TestServer_Request_Reject_HeaderFieldValueDEL(t *testing.T) {
   980  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\x7fdel") })
   981  }
   982  
   983  func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) {
   984  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") })
   985  }
   986  
   987  func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) {
   988  	// 8.1.2.3 Request Pseudo-Header Fields
   989  	// "All HTTP/2 requests MUST include exactly one valid value" ...
   990  	testRejectRequest(t, func(st *serverTester) {
   991  		st.addLogFilter("duplicate pseudo-header")
   992  		st.bodylessReq1(":method", "GET", ":method", "POST")
   993  	})
   994  }
   995  
   996  func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) {
   997  	// 8.1.2.3 Request Pseudo-Header Fields
   998  	// "All pseudo-header fields MUST appear in the header block
   999  	// before regular header fields. Any request or response that
  1000  	// contains a pseudo-header field that appears in a header
  1001  	// block after a regular header field MUST be treated as
  1002  	// malformed (Section 8.1.2.6)."
  1003  	testRejectRequest(t, func(st *serverTester) {
  1004  		st.addLogFilter("pseudo-header after regular header")
  1005  		var buf bytes.Buffer
  1006  		enc := hpack.NewEncoder(&buf)
  1007  		enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"})
  1008  		enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"})
  1009  		enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"})
  1010  		enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"})
  1011  		st.writeHeaders(HeadersFrameParam{
  1012  			StreamID:      1, // clients send odd numbers
  1013  			BlockFragment: buf.Bytes(),
  1014  			EndStream:     true,
  1015  			EndHeaders:    true,
  1016  		})
  1017  	})
  1018  }
  1019  
  1020  func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) {
  1021  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") })
  1022  }
  1023  
  1024  func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) {
  1025  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") })
  1026  }
  1027  
  1028  func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) {
  1029  	testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") })
  1030  }
  1031  
  1032  func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) {
  1033  	testRejectRequest(t, func(st *serverTester) {
  1034  		st.addLogFilter(`invalid pseudo-header ":unknown_thing"`)
  1035  		st.bodylessReq1(":unknown_thing", "")
  1036  	})
  1037  }
  1038  
  1039  func testRejectRequest(t *testing.T, send func(*serverTester)) {
  1040  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1041  		t.Error("server request made it to handler; should've been rejected")
  1042  	})
  1043  	defer st.Close()
  1044  
  1045  	st.greet()
  1046  	send(st)
  1047  	st.wantRSTStream(1, ErrCodeProtocol)
  1048  }
  1049  
  1050  func testRejectRequestWithProtocolError(t *testing.T, send func(*serverTester)) {
  1051  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1052  		t.Error("server request made it to handler; should've been rejected")
  1053  	}, optQuiet)
  1054  	defer st.Close()
  1055  
  1056  	st.greet()
  1057  	send(st)
  1058  	gf := st.wantGoAway()
  1059  	if gf.ErrCode != ErrCodeProtocol {
  1060  		t.Errorf("err code = %v; want %v", gf.ErrCode, ErrCodeProtocol)
  1061  	}
  1062  }
  1063  
  1064  // Section 5.1, on idle connections: "Receiving any frame other than
  1065  // HEADERS or PRIORITY on a stream in this state MUST be treated as a
  1066  // connection error (Section 5.4.1) of type PROTOCOL_ERROR."
  1067  func TestRejectFrameOnIdle_WindowUpdate(t *testing.T) {
  1068  	testRejectRequestWithProtocolError(t, func(st *serverTester) {
  1069  		st.fr.WriteWindowUpdate(123, 456)
  1070  	})
  1071  }
  1072  func TestRejectFrameOnIdle_Data(t *testing.T) {
  1073  	testRejectRequestWithProtocolError(t, func(st *serverTester) {
  1074  		st.fr.WriteData(123, true, nil)
  1075  	})
  1076  }
  1077  func TestRejectFrameOnIdle_RSTStream(t *testing.T) {
  1078  	testRejectRequestWithProtocolError(t, func(st *serverTester) {
  1079  		st.fr.WriteRSTStream(123, ErrCodeCancel)
  1080  	})
  1081  }
  1082  
  1083  func TestServer_Request_Connect(t *testing.T) {
  1084  	testServerRequest(t, func(st *serverTester) {
  1085  		st.writeHeaders(HeadersFrameParam{
  1086  			StreamID: 1,
  1087  			BlockFragment: st.encodeHeaderRaw(
  1088  				":method", "CONNECT",
  1089  				":authority", "example.com:123",
  1090  			),
  1091  			EndStream:  true,
  1092  			EndHeaders: true,
  1093  		})
  1094  	}, func(r *http.Request) {
  1095  		if g, w := r.Method, "CONNECT"; g != w {
  1096  			t.Errorf("Method = %q; want %q", g, w)
  1097  		}
  1098  		if g, w := r.RequestURI, "example.com:123"; g != w {
  1099  			t.Errorf("RequestURI = %q; want %q", g, w)
  1100  		}
  1101  		if g, w := r.URL.Host, "example.com:123"; g != w {
  1102  			t.Errorf("URL.Host = %q; want %q", g, w)
  1103  		}
  1104  	})
  1105  }
  1106  
  1107  func TestServer_Request_Connect_InvalidPath(t *testing.T) {
  1108  	testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1109  		st.writeHeaders(HeadersFrameParam{
  1110  			StreamID: 1,
  1111  			BlockFragment: st.encodeHeaderRaw(
  1112  				":method", "CONNECT",
  1113  				":authority", "example.com:123",
  1114  				":path", "/bogus",
  1115  			),
  1116  			EndStream:  true,
  1117  			EndHeaders: true,
  1118  		})
  1119  	})
  1120  }
  1121  
  1122  func TestServer_Request_Connect_InvalidScheme(t *testing.T) {
  1123  	testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1124  		st.writeHeaders(HeadersFrameParam{
  1125  			StreamID: 1,
  1126  			BlockFragment: st.encodeHeaderRaw(
  1127  				":method", "CONNECT",
  1128  				":authority", "example.com:123",
  1129  				":scheme", "https",
  1130  			),
  1131  			EndStream:  true,
  1132  			EndHeaders: true,
  1133  		})
  1134  	})
  1135  }
  1136  
  1137  func TestServer_Ping(t *testing.T) {
  1138  	st := newServerTester(t, nil)
  1139  	defer st.Close()
  1140  	st.greet()
  1141  
  1142  	// Server should ignore this one, since it has ACK set.
  1143  	ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128}
  1144  	if err := st.fr.WritePing(true, ackPingData); err != nil {
  1145  		t.Fatal(err)
  1146  	}
  1147  
  1148  	// But the server should reply to this one, since ACK is false.
  1149  	pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
  1150  	if err := st.fr.WritePing(false, pingData); err != nil {
  1151  		t.Fatal(err)
  1152  	}
  1153  
  1154  	pf := st.wantPing()
  1155  	if !pf.Flags.Has(FlagPingAck) {
  1156  		t.Error("response ping doesn't have ACK set")
  1157  	}
  1158  	if pf.Data != pingData {
  1159  		t.Errorf("response ping has data %q; want %q", pf.Data, pingData)
  1160  	}
  1161  }
  1162  
  1163  func TestServer_RejectsLargeFrames(t *testing.T) {
  1164  	if runtime.GOOS == "windows" {
  1165  		t.Skip("see golang.org/issue/13434")
  1166  	}
  1167  
  1168  	st := newServerTester(t, nil)
  1169  	defer st.Close()
  1170  	st.greet()
  1171  
  1172  	// Write too large of a frame (too large by one byte)
  1173  	// We ignore the return value because it's expected that the server
  1174  	// will only read the first 9 bytes (the headre) and then disconnect.
  1175  	st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1))
  1176  
  1177  	gf := st.wantGoAway()
  1178  	if gf.ErrCode != ErrCodeFrameSize {
  1179  		t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize)
  1180  	}
  1181  	if st.serverLogBuf.Len() != 0 {
  1182  		// Previously we spun here for a bit until the GOAWAY disconnect
  1183  		// timer fired, logging while we fired.
  1184  		t.Errorf("unexpected server output: %.500s\n", st.serverLogBuf.Bytes())
  1185  	}
  1186  }
  1187  
  1188  func TestServer_Handler_Sends_WindowUpdate(t *testing.T) {
  1189  	puppet := newHandlerPuppet()
  1190  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1191  		puppet.act(w, r)
  1192  	})
  1193  	defer st.Close()
  1194  	defer puppet.done()
  1195  
  1196  	st.greet()
  1197  
  1198  	st.writeHeaders(HeadersFrameParam{
  1199  		StreamID:      1, // clients send odd numbers
  1200  		BlockFragment: st.encodeHeader(":method", "POST"),
  1201  		EndStream:     false, // data coming
  1202  		EndHeaders:    true,
  1203  	})
  1204  	st.writeData(1, false, []byte("abcdef"))
  1205  	puppet.do(readBodyHandler(t, "abc"))
  1206  	st.wantWindowUpdate(0, 3)
  1207  	st.wantWindowUpdate(1, 3)
  1208  
  1209  	puppet.do(readBodyHandler(t, "def"))
  1210  	st.wantWindowUpdate(0, 3)
  1211  	st.wantWindowUpdate(1, 3)
  1212  
  1213  	st.writeData(1, true, []byte("ghijkl")) // END_STREAM here
  1214  	puppet.do(readBodyHandler(t, "ghi"))
  1215  	puppet.do(readBodyHandler(t, "jkl"))
  1216  	st.wantWindowUpdate(0, 3)
  1217  	st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM
  1218  }
  1219  
  1220  // the version of the TestServer_Handler_Sends_WindowUpdate with padding.
  1221  // See golang.org/issue/16556
  1222  func TestServer_Handler_Sends_WindowUpdate_Padding(t *testing.T) {
  1223  	puppet := newHandlerPuppet()
  1224  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1225  		puppet.act(w, r)
  1226  	})
  1227  	defer st.Close()
  1228  	defer puppet.done()
  1229  
  1230  	st.greet()
  1231  
  1232  	st.writeHeaders(HeadersFrameParam{
  1233  		StreamID:      1,
  1234  		BlockFragment: st.encodeHeader(":method", "POST"),
  1235  		EndStream:     false,
  1236  		EndHeaders:    true,
  1237  	})
  1238  	st.writeDataPadded(1, false, []byte("abcdef"), []byte{0, 0, 0, 0})
  1239  
  1240  	// Expect to immediately get our 5 bytes of padding back for
  1241  	// both the connection and stream (4 bytes of padding + 1 byte of length)
  1242  	st.wantWindowUpdate(0, 5)
  1243  	st.wantWindowUpdate(1, 5)
  1244  
  1245  	puppet.do(readBodyHandler(t, "abc"))
  1246  	st.wantWindowUpdate(0, 3)
  1247  	st.wantWindowUpdate(1, 3)
  1248  
  1249  	puppet.do(readBodyHandler(t, "def"))
  1250  	st.wantWindowUpdate(0, 3)
  1251  	st.wantWindowUpdate(1, 3)
  1252  }
  1253  
  1254  func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) {
  1255  	st := newServerTester(t, nil)
  1256  	defer st.Close()
  1257  	st.greet()
  1258  	if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil {
  1259  		t.Fatal(err)
  1260  	}
  1261  	gf := st.wantGoAway()
  1262  	if gf.ErrCode != ErrCodeFlowControl {
  1263  		t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl)
  1264  	}
  1265  	if gf.LastStreamID != 0 {
  1266  		t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0)
  1267  	}
  1268  }
  1269  
  1270  func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) {
  1271  	inHandler := make(chan bool)
  1272  	blockHandler := make(chan bool)
  1273  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1274  		inHandler <- true
  1275  		<-blockHandler
  1276  	})
  1277  	defer st.Close()
  1278  	defer close(blockHandler)
  1279  	st.greet()
  1280  	st.writeHeaders(HeadersFrameParam{
  1281  		StreamID:      1,
  1282  		BlockFragment: st.encodeHeader(":method", "POST"),
  1283  		EndStream:     false, // keep it open
  1284  		EndHeaders:    true,
  1285  	})
  1286  	<-inHandler
  1287  	// Send a bogus window update:
  1288  	if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil {
  1289  		t.Fatal(err)
  1290  	}
  1291  	st.wantRSTStream(1, ErrCodeFlowControl)
  1292  }
  1293  
  1294  // testServerPostUnblock sends a hanging POST with unsent data to handler,
  1295  // then runs fn once in the handler, and verifies that the error returned from
  1296  // handler is acceptable. It fails if takes over 5 seconds for handler to exit.
  1297  func testServerPostUnblock(t *testing.T,
  1298  	handler func(http.ResponseWriter, *http.Request) error,
  1299  	fn func(*serverTester),
  1300  	checkErr func(error),
  1301  	otherHeaders ...string) {
  1302  	inHandler := make(chan bool)
  1303  	errc := make(chan error, 1)
  1304  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1305  		inHandler <- true
  1306  		errc <- handler(w, r)
  1307  	})
  1308  	defer st.Close()
  1309  	st.greet()
  1310  	st.writeHeaders(HeadersFrameParam{
  1311  		StreamID:      1,
  1312  		BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...),
  1313  		EndStream:     false, // keep it open
  1314  		EndHeaders:    true,
  1315  	})
  1316  	<-inHandler
  1317  	fn(st)
  1318  	select {
  1319  	case err := <-errc:
  1320  		if checkErr != nil {
  1321  			checkErr(err)
  1322  		}
  1323  	case <-time.After(5 * time.Second):
  1324  		t.Fatal("timeout waiting for Handler to return")
  1325  	}
  1326  }
  1327  
  1328  func TestServer_RSTStream_Unblocks_Read(t *testing.T) {
  1329  	testServerPostUnblock(t,
  1330  		func(w http.ResponseWriter, r *http.Request) (err error) {
  1331  			_, err = r.Body.Read(make([]byte, 1))
  1332  			return
  1333  		},
  1334  		func(st *serverTester) {
  1335  			if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1336  				t.Fatal(err)
  1337  			}
  1338  		},
  1339  		func(err error) {
  1340  			want := StreamError{StreamID: 0x1, Code: 0x8}
  1341  			if !reflect.DeepEqual(err, want) {
  1342  				t.Errorf("Read error = %v; want %v", err, want)
  1343  			}
  1344  		},
  1345  	)
  1346  }
  1347  
  1348  func TestServer_RSTStream_Unblocks_Header_Write(t *testing.T) {
  1349  	// Run this test a bunch, because it doesn't always
  1350  	// deadlock. But with a bunch, it did.
  1351  	n := 50
  1352  	if testing.Short() {
  1353  		n = 5
  1354  	}
  1355  	for i := 0; i < n; i++ {
  1356  		testServer_RSTStream_Unblocks_Header_Write(t)
  1357  	}
  1358  }
  1359  
  1360  func testServer_RSTStream_Unblocks_Header_Write(t *testing.T) {
  1361  	inHandler := make(chan bool, 1)
  1362  	unblockHandler := make(chan bool, 1)
  1363  	headerWritten := make(chan bool, 1)
  1364  	wroteRST := make(chan bool, 1)
  1365  
  1366  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1367  		inHandler <- true
  1368  		<-wroteRST
  1369  		w.Header().Set("foo", "bar")
  1370  		w.WriteHeader(200)
  1371  		w.(http.Flusher).Flush()
  1372  		headerWritten <- true
  1373  		<-unblockHandler
  1374  	})
  1375  	defer st.Close()
  1376  
  1377  	st.greet()
  1378  	st.writeHeaders(HeadersFrameParam{
  1379  		StreamID:      1,
  1380  		BlockFragment: st.encodeHeader(":method", "POST"),
  1381  		EndStream:     false, // keep it open
  1382  		EndHeaders:    true,
  1383  	})
  1384  	<-inHandler
  1385  	if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1386  		t.Fatal(err)
  1387  	}
  1388  	wroteRST <- true
  1389  	st.awaitIdle()
  1390  	select {
  1391  	case <-headerWritten:
  1392  	case <-time.After(2 * time.Second):
  1393  		t.Error("timeout waiting for header write")
  1394  	}
  1395  	unblockHandler <- true
  1396  }
  1397  
  1398  func TestServer_DeadConn_Unblocks_Read(t *testing.T) {
  1399  	testServerPostUnblock(t,
  1400  		func(w http.ResponseWriter, r *http.Request) (err error) {
  1401  			_, err = r.Body.Read(make([]byte, 1))
  1402  			return
  1403  		},
  1404  		func(st *serverTester) { st.cc.Close() },
  1405  		func(err error) {
  1406  			if err == nil {
  1407  				t.Error("unexpected nil error from Request.Body.Read")
  1408  			}
  1409  		},
  1410  	)
  1411  }
  1412  
  1413  var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error {
  1414  	<-w.(http.CloseNotifier).CloseNotify()
  1415  	return nil
  1416  }
  1417  
  1418  func TestServer_CloseNotify_After_RSTStream(t *testing.T) {
  1419  	testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) {
  1420  		if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  1421  			t.Fatal(err)
  1422  		}
  1423  	}, nil)
  1424  }
  1425  
  1426  func TestServer_CloseNotify_After_ConnClose(t *testing.T) {
  1427  	testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil)
  1428  }
  1429  
  1430  // that CloseNotify unblocks after a stream error due to the client's
  1431  // problem that's unrelated to them explicitly canceling it (which is
  1432  // TestServer_CloseNotify_After_RSTStream above)
  1433  func TestServer_CloseNotify_After_StreamError(t *testing.T) {
  1434  	testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) {
  1435  		// data longer than declared Content-Length => stream error
  1436  		st.writeData(1, true, []byte("1234"))
  1437  	}, nil, "content-length", "3")
  1438  }
  1439  
  1440  func TestServer_StateTransitions(t *testing.T) {
  1441  	var st *serverTester
  1442  	inHandler := make(chan bool)
  1443  	writeData := make(chan bool)
  1444  	leaveHandler := make(chan bool)
  1445  	st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1446  		inHandler <- true
  1447  		if st.stream(1) == nil {
  1448  			t.Errorf("nil stream 1 in handler")
  1449  		}
  1450  		if got, want := st.streamState(1), stateOpen; got != want {
  1451  			t.Errorf("in handler, state is %v; want %v", got, want)
  1452  		}
  1453  		writeData <- true
  1454  		if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF {
  1455  			t.Errorf("body read = %d, %v; want 0, EOF", n, err)
  1456  		}
  1457  		if got, want := st.streamState(1), stateHalfClosedRemote; got != want {
  1458  			t.Errorf("in handler, state is %v; want %v", got, want)
  1459  		}
  1460  
  1461  		<-leaveHandler
  1462  	})
  1463  	st.greet()
  1464  	if st.stream(1) != nil {
  1465  		t.Fatal("stream 1 should be empty")
  1466  	}
  1467  	if got := st.streamState(1); got != stateIdle {
  1468  		t.Fatalf("stream 1 should be idle; got %v", got)
  1469  	}
  1470  
  1471  	st.writeHeaders(HeadersFrameParam{
  1472  		StreamID:      1,
  1473  		BlockFragment: st.encodeHeader(":method", "POST"),
  1474  		EndStream:     false, // keep it open
  1475  		EndHeaders:    true,
  1476  	})
  1477  	<-inHandler
  1478  	<-writeData
  1479  	st.writeData(1, true, nil)
  1480  
  1481  	leaveHandler <- true
  1482  	hf := st.wantHeaders()
  1483  	if !hf.StreamEnded() {
  1484  		t.Fatal("expected END_STREAM flag")
  1485  	}
  1486  
  1487  	if got, want := st.streamState(1), stateClosed; got != want {
  1488  		t.Errorf("at end, state is %v; want %v", got, want)
  1489  	}
  1490  	if st.stream(1) != nil {
  1491  		t.Fatal("at end, stream 1 should be gone")
  1492  	}
  1493  }
  1494  
  1495  // test HEADERS w/o EndHeaders + another HEADERS (should get rejected)
  1496  func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) {
  1497  	testServerRejectsConn(t, func(st *serverTester) {
  1498  		st.writeHeaders(HeadersFrameParam{
  1499  			StreamID:      1,
  1500  			BlockFragment: st.encodeHeader(),
  1501  			EndStream:     true,
  1502  			EndHeaders:    false,
  1503  		})
  1504  		st.writeHeaders(HeadersFrameParam{ // Not a continuation.
  1505  			StreamID:      3, // different stream.
  1506  			BlockFragment: st.encodeHeader(),
  1507  			EndStream:     true,
  1508  			EndHeaders:    true,
  1509  		})
  1510  	})
  1511  }
  1512  
  1513  // test HEADERS w/o EndHeaders + PING (should get rejected)
  1514  func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) {
  1515  	testServerRejectsConn(t, func(st *serverTester) {
  1516  		st.writeHeaders(HeadersFrameParam{
  1517  			StreamID:      1,
  1518  			BlockFragment: st.encodeHeader(),
  1519  			EndStream:     true,
  1520  			EndHeaders:    false,
  1521  		})
  1522  		if err := st.fr.WritePing(false, [8]byte{}); err != nil {
  1523  			t.Fatal(err)
  1524  		}
  1525  	})
  1526  }
  1527  
  1528  // test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected)
  1529  func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) {
  1530  	testServerRejectsConn(t, func(st *serverTester) {
  1531  		st.writeHeaders(HeadersFrameParam{
  1532  			StreamID:      1,
  1533  			BlockFragment: st.encodeHeader(),
  1534  			EndStream:     true,
  1535  			EndHeaders:    true,
  1536  		})
  1537  		st.wantHeaders()
  1538  		if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil {
  1539  			t.Fatal(err)
  1540  		}
  1541  	})
  1542  }
  1543  
  1544  // test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID
  1545  func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) {
  1546  	testServerRejectsConn(t, func(st *serverTester) {
  1547  		st.writeHeaders(HeadersFrameParam{
  1548  			StreamID:      1,
  1549  			BlockFragment: st.encodeHeader(),
  1550  			EndStream:     true,
  1551  			EndHeaders:    false,
  1552  		})
  1553  		if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil {
  1554  			t.Fatal(err)
  1555  		}
  1556  	})
  1557  }
  1558  
  1559  // No HEADERS on stream 0.
  1560  func TestServer_Rejects_Headers0(t *testing.T) {
  1561  	testServerRejectsConn(t, func(st *serverTester) {
  1562  		st.fr.AllowIllegalWrites = true
  1563  		st.writeHeaders(HeadersFrameParam{
  1564  			StreamID:      0,
  1565  			BlockFragment: st.encodeHeader(),
  1566  			EndStream:     true,
  1567  			EndHeaders:    true,
  1568  		})
  1569  	})
  1570  }
  1571  
  1572  // No CONTINUATION on stream 0.
  1573  func TestServer_Rejects_Continuation0(t *testing.T) {
  1574  	testServerRejectsConn(t, func(st *serverTester) {
  1575  		st.fr.AllowIllegalWrites = true
  1576  		if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil {
  1577  			t.Fatal(err)
  1578  		}
  1579  	})
  1580  }
  1581  
  1582  // No PRIORITY on stream 0.
  1583  func TestServer_Rejects_Priority0(t *testing.T) {
  1584  	testServerRejectsConn(t, func(st *serverTester) {
  1585  		st.fr.AllowIllegalWrites = true
  1586  		st.writePriority(0, PriorityParam{StreamDep: 1})
  1587  	})
  1588  }
  1589  
  1590  // No HEADERS frame with a self-dependence.
  1591  func TestServer_Rejects_HeadersSelfDependence(t *testing.T) {
  1592  	testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1593  		st.fr.AllowIllegalWrites = true
  1594  		st.writeHeaders(HeadersFrameParam{
  1595  			StreamID:      1,
  1596  			BlockFragment: st.encodeHeader(),
  1597  			EndStream:     true,
  1598  			EndHeaders:    true,
  1599  			Priority:      PriorityParam{StreamDep: 1},
  1600  		})
  1601  	})
  1602  }
  1603  
  1604  // No PRIORTY frame with a self-dependence.
  1605  func TestServer_Rejects_PrioritySelfDependence(t *testing.T) {
  1606  	testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) {
  1607  		st.fr.AllowIllegalWrites = true
  1608  		st.writePriority(1, PriorityParam{StreamDep: 1})
  1609  	})
  1610  }
  1611  
  1612  func TestServer_Rejects_PushPromise(t *testing.T) {
  1613  	testServerRejectsConn(t, func(st *serverTester) {
  1614  		pp := PushPromiseParam{
  1615  			StreamID:  1,
  1616  			PromiseID: 3,
  1617  		}
  1618  		if err := st.fr.WritePushPromise(pp); err != nil {
  1619  			t.Fatal(err)
  1620  		}
  1621  	})
  1622  }
  1623  
  1624  // testServerRejectsConn tests that the server hangs up with a GOAWAY
  1625  // frame and a server close after the client does something
  1626  // deserving a CONNECTION_ERROR.
  1627  func testServerRejectsConn(t *testing.T, writeReq func(*serverTester)) {
  1628  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  1629  	st.addLogFilter("connection error: PROTOCOL_ERROR")
  1630  	defer st.Close()
  1631  	st.greet()
  1632  	writeReq(st)
  1633  
  1634  	st.wantGoAway()
  1635  	errc := make(chan error, 1)
  1636  	go func() {
  1637  		fr, err := st.fr.ReadFrame()
  1638  		if err == nil {
  1639  			err = fmt.Errorf("got frame of type %T", fr)
  1640  		}
  1641  		errc <- err
  1642  	}()
  1643  	select {
  1644  	case err := <-errc:
  1645  		if err != io.EOF {
  1646  			t.Errorf("ReadFrame = %v; want io.EOF", err)
  1647  		}
  1648  	case <-time.After(2 * time.Second):
  1649  		t.Error("timeout waiting for disconnect")
  1650  	}
  1651  }
  1652  
  1653  // testServerRejectsStream tests that the server sends a RST_STREAM with the provided
  1654  // error code after a client sends a bogus request.
  1655  func testServerRejectsStream(t *testing.T, code ErrCode, writeReq func(*serverTester)) {
  1656  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  1657  	defer st.Close()
  1658  	st.greet()
  1659  	writeReq(st)
  1660  	st.wantRSTStream(1, code)
  1661  }
  1662  
  1663  // testServerRequest sets up an idle HTTP/2 connection and lets you
  1664  // write a single request with writeReq, and then verify that the
  1665  // *http.Request is built correctly in checkReq.
  1666  func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) {
  1667  	gotReq := make(chan bool, 1)
  1668  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  1669  		if r.Body == nil {
  1670  			t.Fatal("nil Body")
  1671  		}
  1672  		checkReq(r)
  1673  		gotReq <- true
  1674  	})
  1675  	defer st.Close()
  1676  
  1677  	st.greet()
  1678  	writeReq(st)
  1679  
  1680  	select {
  1681  	case <-gotReq:
  1682  	case <-time.After(2 * time.Second):
  1683  		t.Error("timeout waiting for request")
  1684  	}
  1685  }
  1686  
  1687  func getSlash(st *serverTester) { st.bodylessReq1() }
  1688  
  1689  func TestServer_Response_NoData(t *testing.T) {
  1690  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1691  		// Nothing.
  1692  		return nil
  1693  	}, func(st *serverTester) {
  1694  		getSlash(st)
  1695  		hf := st.wantHeaders()
  1696  		if !hf.StreamEnded() {
  1697  			t.Fatal("want END_STREAM flag")
  1698  		}
  1699  		if !hf.HeadersEnded() {
  1700  			t.Fatal("want END_HEADERS flag")
  1701  		}
  1702  	})
  1703  }
  1704  
  1705  func TestServer_Response_NoData_Header_FooBar(t *testing.T) {
  1706  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1707  		w.Header().Set("Foo-Bar", "some-value")
  1708  		return nil
  1709  	}, func(st *serverTester) {
  1710  		getSlash(st)
  1711  		hf := st.wantHeaders()
  1712  		if !hf.StreamEnded() {
  1713  			t.Fatal("want END_STREAM flag")
  1714  		}
  1715  		if !hf.HeadersEnded() {
  1716  			t.Fatal("want END_HEADERS flag")
  1717  		}
  1718  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1719  		wanth := [][2]string{
  1720  			{":status", "200"},
  1721  			{"foo-bar", "some-value"},
  1722  			{"content-length", "0"},
  1723  		}
  1724  		if !reflect.DeepEqual(goth, wanth) {
  1725  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1726  		}
  1727  	})
  1728  }
  1729  
  1730  func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) {
  1731  	const msg = "<html>this is HTML."
  1732  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1733  		w.Header().Set("Content-Type", "foo/bar")
  1734  		io.WriteString(w, msg)
  1735  		return nil
  1736  	}, func(st *serverTester) {
  1737  		getSlash(st)
  1738  		hf := st.wantHeaders()
  1739  		if hf.StreamEnded() {
  1740  			t.Fatal("don't want END_STREAM, expecting data")
  1741  		}
  1742  		if !hf.HeadersEnded() {
  1743  			t.Fatal("want END_HEADERS flag")
  1744  		}
  1745  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1746  		wanth := [][2]string{
  1747  			{":status", "200"},
  1748  			{"content-type", "foo/bar"},
  1749  			{"content-length", strconv.Itoa(len(msg))},
  1750  		}
  1751  		if !reflect.DeepEqual(goth, wanth) {
  1752  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1753  		}
  1754  		df := st.wantData()
  1755  		if !df.StreamEnded() {
  1756  			t.Error("expected DATA to have END_STREAM flag")
  1757  		}
  1758  		if got := string(df.Data()); got != msg {
  1759  			t.Errorf("got DATA %q; want %q", got, msg)
  1760  		}
  1761  	})
  1762  }
  1763  
  1764  func TestServer_Response_TransferEncoding_chunked(t *testing.T) {
  1765  	const msg = "hi"
  1766  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1767  		w.Header().Set("Transfer-Encoding", "chunked") // should be stripped
  1768  		io.WriteString(w, msg)
  1769  		return nil
  1770  	}, func(st *serverTester) {
  1771  		getSlash(st)
  1772  		hf := st.wantHeaders()
  1773  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1774  		wanth := [][2]string{
  1775  			{":status", "200"},
  1776  			{"content-type", "text/plain; charset=utf-8"},
  1777  			{"content-length", strconv.Itoa(len(msg))},
  1778  		}
  1779  		if !reflect.DeepEqual(goth, wanth) {
  1780  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1781  		}
  1782  	})
  1783  }
  1784  
  1785  // Header accessed only after the initial write.
  1786  func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) {
  1787  	const msg = "<html>this is HTML."
  1788  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1789  		io.WriteString(w, msg)
  1790  		w.Header().Set("foo", "should be ignored")
  1791  		return nil
  1792  	}, func(st *serverTester) {
  1793  		getSlash(st)
  1794  		hf := st.wantHeaders()
  1795  		if hf.StreamEnded() {
  1796  			t.Fatal("unexpected END_STREAM")
  1797  		}
  1798  		if !hf.HeadersEnded() {
  1799  			t.Fatal("want END_HEADERS flag")
  1800  		}
  1801  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1802  		wanth := [][2]string{
  1803  			{":status", "200"},
  1804  			{"content-type", "text/html; charset=utf-8"},
  1805  			{"content-length", strconv.Itoa(len(msg))},
  1806  		}
  1807  		if !reflect.DeepEqual(goth, wanth) {
  1808  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1809  		}
  1810  	})
  1811  }
  1812  
  1813  // Header accessed before the initial write and later mutated.
  1814  func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) {
  1815  	const msg = "<html>this is HTML."
  1816  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1817  		w.Header().Set("foo", "proper value")
  1818  		io.WriteString(w, msg)
  1819  		w.Header().Set("foo", "should be ignored")
  1820  		return nil
  1821  	}, func(st *serverTester) {
  1822  		getSlash(st)
  1823  		hf := st.wantHeaders()
  1824  		if hf.StreamEnded() {
  1825  			t.Fatal("unexpected END_STREAM")
  1826  		}
  1827  		if !hf.HeadersEnded() {
  1828  			t.Fatal("want END_HEADERS flag")
  1829  		}
  1830  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1831  		wanth := [][2]string{
  1832  			{":status", "200"},
  1833  			{"foo", "proper value"},
  1834  			{"content-type", "text/html; charset=utf-8"},
  1835  			{"content-length", strconv.Itoa(len(msg))},
  1836  		}
  1837  		if !reflect.DeepEqual(goth, wanth) {
  1838  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1839  		}
  1840  	})
  1841  }
  1842  
  1843  func TestServer_Response_Data_SniffLenType(t *testing.T) {
  1844  	const msg = "<html>this is HTML."
  1845  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1846  		io.WriteString(w, msg)
  1847  		return nil
  1848  	}, func(st *serverTester) {
  1849  		getSlash(st)
  1850  		hf := st.wantHeaders()
  1851  		if hf.StreamEnded() {
  1852  			t.Fatal("don't want END_STREAM, expecting data")
  1853  		}
  1854  		if !hf.HeadersEnded() {
  1855  			t.Fatal("want END_HEADERS flag")
  1856  		}
  1857  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1858  		wanth := [][2]string{
  1859  			{":status", "200"},
  1860  			{"content-type", "text/html; charset=utf-8"},
  1861  			{"content-length", strconv.Itoa(len(msg))},
  1862  		}
  1863  		if !reflect.DeepEqual(goth, wanth) {
  1864  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1865  		}
  1866  		df := st.wantData()
  1867  		if !df.StreamEnded() {
  1868  			t.Error("expected DATA to have END_STREAM flag")
  1869  		}
  1870  		if got := string(df.Data()); got != msg {
  1871  			t.Errorf("got DATA %q; want %q", got, msg)
  1872  		}
  1873  	})
  1874  }
  1875  
  1876  func TestServer_Response_Header_Flush_MidWrite(t *testing.T) {
  1877  	const msg = "<html>this is HTML"
  1878  	const msg2 = ", and this is the next chunk"
  1879  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1880  		io.WriteString(w, msg)
  1881  		w.(http.Flusher).Flush()
  1882  		io.WriteString(w, msg2)
  1883  		return nil
  1884  	}, func(st *serverTester) {
  1885  		getSlash(st)
  1886  		hf := st.wantHeaders()
  1887  		if hf.StreamEnded() {
  1888  			t.Fatal("unexpected END_STREAM flag")
  1889  		}
  1890  		if !hf.HeadersEnded() {
  1891  			t.Fatal("want END_HEADERS flag")
  1892  		}
  1893  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1894  		wanth := [][2]string{
  1895  			{":status", "200"},
  1896  			{"content-type", "text/html; charset=utf-8"}, // sniffed
  1897  			// and no content-length
  1898  		}
  1899  		if !reflect.DeepEqual(goth, wanth) {
  1900  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1901  		}
  1902  		{
  1903  			df := st.wantData()
  1904  			if df.StreamEnded() {
  1905  				t.Error("unexpected END_STREAM flag")
  1906  			}
  1907  			if got := string(df.Data()); got != msg {
  1908  				t.Errorf("got DATA %q; want %q", got, msg)
  1909  			}
  1910  		}
  1911  		{
  1912  			df := st.wantData()
  1913  			if !df.StreamEnded() {
  1914  				t.Error("wanted END_STREAM flag on last data chunk")
  1915  			}
  1916  			if got := string(df.Data()); got != msg2 {
  1917  				t.Errorf("got DATA %q; want %q", got, msg2)
  1918  			}
  1919  		}
  1920  	})
  1921  }
  1922  
  1923  func TestServer_Response_LargeWrite(t *testing.T) {
  1924  	const size = 1 << 20
  1925  	const maxFrameSize = 16 << 10
  1926  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  1927  		n, err := w.Write(bytes.Repeat([]byte("a"), size))
  1928  		if err != nil {
  1929  			return fmt.Errorf("Write error: %v", err)
  1930  		}
  1931  		if n != size {
  1932  			return fmt.Errorf("wrong size %d from Write", n)
  1933  		}
  1934  		return nil
  1935  	}, func(st *serverTester) {
  1936  		if err := st.fr.WriteSettings(
  1937  			Setting{SettingInitialWindowSize, 0},
  1938  			Setting{SettingMaxFrameSize, maxFrameSize},
  1939  		); err != nil {
  1940  			t.Fatal(err)
  1941  		}
  1942  		st.wantSettingsAck()
  1943  
  1944  		getSlash(st) // make the single request
  1945  
  1946  		// Give the handler quota to write:
  1947  		if err := st.fr.WriteWindowUpdate(1, size); err != nil {
  1948  			t.Fatal(err)
  1949  		}
  1950  		// Give the handler quota to write to connection-level
  1951  		// window as well
  1952  		if err := st.fr.WriteWindowUpdate(0, size); err != nil {
  1953  			t.Fatal(err)
  1954  		}
  1955  		hf := st.wantHeaders()
  1956  		if hf.StreamEnded() {
  1957  			t.Fatal("unexpected END_STREAM flag")
  1958  		}
  1959  		if !hf.HeadersEnded() {
  1960  			t.Fatal("want END_HEADERS flag")
  1961  		}
  1962  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  1963  		wanth := [][2]string{
  1964  			{":status", "200"},
  1965  			{"content-type", "text/plain; charset=utf-8"}, // sniffed
  1966  			// and no content-length
  1967  		}
  1968  		if !reflect.DeepEqual(goth, wanth) {
  1969  			t.Errorf("Got headers %v; want %v", goth, wanth)
  1970  		}
  1971  		var bytes, frames int
  1972  		for {
  1973  			df := st.wantData()
  1974  			bytes += len(df.Data())
  1975  			frames++
  1976  			for _, b := range df.Data() {
  1977  				if b != 'a' {
  1978  					t.Fatal("non-'a' byte seen in DATA")
  1979  				}
  1980  			}
  1981  			if df.StreamEnded() {
  1982  				break
  1983  			}
  1984  		}
  1985  		if bytes != size {
  1986  			t.Errorf("Got %d bytes; want %d", bytes, size)
  1987  		}
  1988  		if want := int(size / maxFrameSize); frames < want || frames > want*2 {
  1989  			t.Errorf("Got %d frames; want %d", frames, size)
  1990  		}
  1991  	})
  1992  }
  1993  
  1994  // Test that the handler can't write more than the client allows
  1995  func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) {
  1996  	// Make these reads. Before each read, the client adds exactly enough
  1997  	// flow-control to satisfy the read. Numbers chosen arbitrarily.
  1998  	reads := []int{123, 1, 13, 127}
  1999  	size := 0
  2000  	for _, n := range reads {
  2001  		size += n
  2002  	}
  2003  
  2004  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2005  		w.(http.Flusher).Flush()
  2006  		n, err := w.Write(bytes.Repeat([]byte("a"), size))
  2007  		if err != nil {
  2008  			return fmt.Errorf("Write error: %v", err)
  2009  		}
  2010  		if n != size {
  2011  			return fmt.Errorf("wrong size %d from Write", n)
  2012  		}
  2013  		return nil
  2014  	}, func(st *serverTester) {
  2015  		// Set the window size to something explicit for this test.
  2016  		// It's also how much initial data we expect.
  2017  		if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil {
  2018  			t.Fatal(err)
  2019  		}
  2020  		st.wantSettingsAck()
  2021  
  2022  		getSlash(st) // make the single request
  2023  
  2024  		hf := st.wantHeaders()
  2025  		if hf.StreamEnded() {
  2026  			t.Fatal("unexpected END_STREAM flag")
  2027  		}
  2028  		if !hf.HeadersEnded() {
  2029  			t.Fatal("want END_HEADERS flag")
  2030  		}
  2031  
  2032  		df := st.wantData()
  2033  		if got := len(df.Data()); got != reads[0] {
  2034  			t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got)
  2035  		}
  2036  
  2037  		for _, quota := range reads[1:] {
  2038  			if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil {
  2039  				t.Fatal(err)
  2040  			}
  2041  			df := st.wantData()
  2042  			if int(quota) != len(df.Data()) {
  2043  				t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota)
  2044  			}
  2045  		}
  2046  	})
  2047  }
  2048  
  2049  // Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM.
  2050  func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) {
  2051  	const size = 1 << 20
  2052  	const maxFrameSize = 16 << 10
  2053  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2054  		w.(http.Flusher).Flush()
  2055  		errc := make(chan error, 1)
  2056  		go func() {
  2057  			_, err := w.Write(bytes.Repeat([]byte("a"), size))
  2058  			errc <- err
  2059  		}()
  2060  		select {
  2061  		case err := <-errc:
  2062  			if err == nil {
  2063  				return errors.New("unexpected nil error from Write in handler")
  2064  			}
  2065  			return nil
  2066  		case <-time.After(2 * time.Second):
  2067  			return errors.New("timeout waiting for Write in handler")
  2068  		}
  2069  	}, func(st *serverTester) {
  2070  		if err := st.fr.WriteSettings(
  2071  			Setting{SettingInitialWindowSize, 0},
  2072  			Setting{SettingMaxFrameSize, maxFrameSize},
  2073  		); err != nil {
  2074  			t.Fatal(err)
  2075  		}
  2076  		st.wantSettingsAck()
  2077  
  2078  		getSlash(st) // make the single request
  2079  
  2080  		hf := st.wantHeaders()
  2081  		if hf.StreamEnded() {
  2082  			t.Fatal("unexpected END_STREAM flag")
  2083  		}
  2084  		if !hf.HeadersEnded() {
  2085  			t.Fatal("want END_HEADERS flag")
  2086  		}
  2087  
  2088  		if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil {
  2089  			t.Fatal(err)
  2090  		}
  2091  	})
  2092  }
  2093  
  2094  func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) {
  2095  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2096  		w.(http.Flusher).Flush()
  2097  		// Nothing; send empty DATA
  2098  		return nil
  2099  	}, func(st *serverTester) {
  2100  		// Handler gets no data quota:
  2101  		if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil {
  2102  			t.Fatal(err)
  2103  		}
  2104  		st.wantSettingsAck()
  2105  
  2106  		getSlash(st) // make the single request
  2107  
  2108  		hf := st.wantHeaders()
  2109  		if hf.StreamEnded() {
  2110  			t.Fatal("unexpected END_STREAM flag")
  2111  		}
  2112  		if !hf.HeadersEnded() {
  2113  			t.Fatal("want END_HEADERS flag")
  2114  		}
  2115  
  2116  		df := st.wantData()
  2117  		if got := len(df.Data()); got != 0 {
  2118  			t.Fatalf("unexpected %d DATA bytes; want 0", got)
  2119  		}
  2120  		if !df.StreamEnded() {
  2121  			t.Fatal("DATA didn't have END_STREAM")
  2122  		}
  2123  	})
  2124  }
  2125  
  2126  func TestServer_Response_Automatic100Continue(t *testing.T) {
  2127  	const msg = "foo"
  2128  	const reply = "bar"
  2129  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2130  		if v := r.Header.Get("Expect"); v != "" {
  2131  			t.Errorf("Expect header = %q; want empty", v)
  2132  		}
  2133  		buf := make([]byte, len(msg))
  2134  		// This read should trigger the 100-continue being sent.
  2135  		if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg {
  2136  			return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg)
  2137  		}
  2138  		_, err := io.WriteString(w, reply)
  2139  		return err
  2140  	}, func(st *serverTester) {
  2141  		st.writeHeaders(HeadersFrameParam{
  2142  			StreamID:      1, // clients send odd numbers
  2143  			BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"),
  2144  			EndStream:     false,
  2145  			EndHeaders:    true,
  2146  		})
  2147  		hf := st.wantHeaders()
  2148  		if hf.StreamEnded() {
  2149  			t.Fatal("unexpected END_STREAM flag")
  2150  		}
  2151  		if !hf.HeadersEnded() {
  2152  			t.Fatal("want END_HEADERS flag")
  2153  		}
  2154  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  2155  		wanth := [][2]string{
  2156  			{":status", "100"},
  2157  		}
  2158  		if !reflect.DeepEqual(goth, wanth) {
  2159  			t.Fatalf("Got headers %v; want %v", goth, wanth)
  2160  		}
  2161  
  2162  		// Okay, they sent status 100, so we can send our
  2163  		// gigantic and/or sensitive "foo" payload now.
  2164  		st.writeData(1, true, []byte(msg))
  2165  
  2166  		st.wantWindowUpdate(0, uint32(len(msg)))
  2167  
  2168  		hf = st.wantHeaders()
  2169  		if hf.StreamEnded() {
  2170  			t.Fatal("expected data to follow")
  2171  		}
  2172  		if !hf.HeadersEnded() {
  2173  			t.Fatal("want END_HEADERS flag")
  2174  		}
  2175  		goth = st.decodeHeader(hf.HeaderBlockFragment())
  2176  		wanth = [][2]string{
  2177  			{":status", "200"},
  2178  			{"content-type", "text/plain; charset=utf-8"},
  2179  			{"content-length", strconv.Itoa(len(reply))},
  2180  		}
  2181  		if !reflect.DeepEqual(goth, wanth) {
  2182  			t.Errorf("Got headers %v; want %v", goth, wanth)
  2183  		}
  2184  
  2185  		df := st.wantData()
  2186  		if string(df.Data()) != reply {
  2187  			t.Errorf("Client read %q; want %q", df.Data(), reply)
  2188  		}
  2189  		if !df.StreamEnded() {
  2190  			t.Errorf("expect data stream end")
  2191  		}
  2192  	})
  2193  }
  2194  
  2195  func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) {
  2196  	errc := make(chan error, 1)
  2197  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2198  		p := []byte("some data.\n")
  2199  		for {
  2200  			_, err := w.Write(p)
  2201  			if err != nil {
  2202  				errc <- err
  2203  				return nil
  2204  			}
  2205  		}
  2206  	}, func(st *serverTester) {
  2207  		st.writeHeaders(HeadersFrameParam{
  2208  			StreamID:      1,
  2209  			BlockFragment: st.encodeHeader(),
  2210  			EndStream:     false,
  2211  			EndHeaders:    true,
  2212  		})
  2213  		hf := st.wantHeaders()
  2214  		if hf.StreamEnded() {
  2215  			t.Fatal("unexpected END_STREAM flag")
  2216  		}
  2217  		if !hf.HeadersEnded() {
  2218  			t.Fatal("want END_HEADERS flag")
  2219  		}
  2220  		// Close the connection and wait for the handler to (hopefully) notice.
  2221  		st.cc.Close()
  2222  		select {
  2223  		case <-errc:
  2224  		case <-time.After(5 * time.Second):
  2225  			t.Error("timeout")
  2226  		}
  2227  	})
  2228  }
  2229  
  2230  func TestServer_Rejects_Too_Many_Streams(t *testing.T) {
  2231  	const testPath = "/some/path"
  2232  
  2233  	inHandler := make(chan uint32)
  2234  	leaveHandler := make(chan bool)
  2235  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2236  		id := w.(*responseWriter).rws.stream.id
  2237  		inHandler <- id
  2238  		if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath {
  2239  			t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath)
  2240  		}
  2241  		<-leaveHandler
  2242  	})
  2243  	defer st.Close()
  2244  	st.greet()
  2245  	nextStreamID := uint32(1)
  2246  	streamID := func() uint32 {
  2247  		defer func() { nextStreamID += 2 }()
  2248  		return nextStreamID
  2249  	}
  2250  	sendReq := func(id uint32, headers ...string) {
  2251  		st.writeHeaders(HeadersFrameParam{
  2252  			StreamID:      id,
  2253  			BlockFragment: st.encodeHeader(headers...),
  2254  			EndStream:     true,
  2255  			EndHeaders:    true,
  2256  		})
  2257  	}
  2258  	for i := 0; i < defaultMaxStreams; i++ {
  2259  		sendReq(streamID())
  2260  		<-inHandler
  2261  	}
  2262  	defer func() {
  2263  		for i := 0; i < defaultMaxStreams; i++ {
  2264  			leaveHandler <- true
  2265  		}
  2266  	}()
  2267  
  2268  	// And this one should cross the limit:
  2269  	// (It's also sent as a CONTINUATION, to verify we still track the decoder context,
  2270  	// even if we're rejecting it)
  2271  	rejectID := streamID()
  2272  	headerBlock := st.encodeHeader(":path", testPath)
  2273  	frag1, frag2 := headerBlock[:3], headerBlock[3:]
  2274  	st.writeHeaders(HeadersFrameParam{
  2275  		StreamID:      rejectID,
  2276  		BlockFragment: frag1,
  2277  		EndStream:     true,
  2278  		EndHeaders:    false, // CONTINUATION coming
  2279  	})
  2280  	if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil {
  2281  		t.Fatal(err)
  2282  	}
  2283  	st.wantRSTStream(rejectID, ErrCodeProtocol)
  2284  
  2285  	// But let a handler finish:
  2286  	leaveHandler <- true
  2287  	st.wantHeaders()
  2288  
  2289  	// And now another stream should be able to start:
  2290  	goodID := streamID()
  2291  	sendReq(goodID, ":path", testPath)
  2292  	select {
  2293  	case got := <-inHandler:
  2294  		if got != goodID {
  2295  			t.Errorf("Got stream %d; want %d", got, goodID)
  2296  		}
  2297  	case <-time.After(3 * time.Second):
  2298  		t.Error("timeout waiting for handler")
  2299  	}
  2300  }
  2301  
  2302  // So many response headers that the server needs to use CONTINUATION frames:
  2303  func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) {
  2304  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2305  		h := w.Header()
  2306  		for i := 0; i < 5000; i++ {
  2307  			h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i))
  2308  		}
  2309  		return nil
  2310  	}, func(st *serverTester) {
  2311  		getSlash(st)
  2312  		hf := st.wantHeaders()
  2313  		if hf.HeadersEnded() {
  2314  			t.Fatal("got unwanted END_HEADERS flag")
  2315  		}
  2316  		n := 0
  2317  		for {
  2318  			n++
  2319  			cf := st.wantContinuation()
  2320  			if cf.HeadersEnded() {
  2321  				break
  2322  			}
  2323  		}
  2324  		if n < 5 {
  2325  			t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n)
  2326  		}
  2327  	})
  2328  }
  2329  
  2330  // This previously crashed (reported by Mathieu Lonjaret as observed
  2331  // while using Camlistore) because we got a DATA frame from the client
  2332  // after the handler exited and our logic at the time was wrong,
  2333  // keeping a stream in the map in stateClosed, which tickled an
  2334  // invariant check later when we tried to remove that stream (via
  2335  // defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop
  2336  // ended.
  2337  func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) {
  2338  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2339  		// nothing
  2340  		return nil
  2341  	}, func(st *serverTester) {
  2342  		st.writeHeaders(HeadersFrameParam{
  2343  			StreamID:      1,
  2344  			BlockFragment: st.encodeHeader(),
  2345  			EndStream:     false, // DATA is coming
  2346  			EndHeaders:    true,
  2347  		})
  2348  		hf := st.wantHeaders()
  2349  		if !hf.HeadersEnded() || !hf.StreamEnded() {
  2350  			t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf)
  2351  		}
  2352  
  2353  		// Sent when the a Handler closes while a client has
  2354  		// indicated it's still sending DATA:
  2355  		st.wantRSTStream(1, ErrCodeNo)
  2356  
  2357  		// Now the handler has ended, so it's ended its
  2358  		// stream, but the client hasn't closed its side
  2359  		// (stateClosedLocal).  So send more data and verify
  2360  		// it doesn't crash with an internal invariant panic, like
  2361  		// it did before.
  2362  		st.writeData(1, true, []byte("foo"))
  2363  
  2364  		// Get our flow control bytes back, since the handler didn't get them.
  2365  		st.wantWindowUpdate(0, uint32(len("foo")))
  2366  
  2367  		// Sent after a peer sends data anyway (admittedly the
  2368  		// previous RST_STREAM might've still been in-flight),
  2369  		// but they'll get the more friendly 'cancel' code
  2370  		// first.
  2371  		st.wantRSTStream(1, ErrCodeStreamClosed)
  2372  
  2373  		// Set up a bunch of machinery to record the panic we saw
  2374  		// previously.
  2375  		var (
  2376  			panMu    sync.Mutex
  2377  			panicVal interface{}
  2378  		)
  2379  
  2380  		testHookOnPanicMu.Lock()
  2381  		testHookOnPanic = func(sc *serverConn, pv interface{}) bool {
  2382  			panMu.Lock()
  2383  			panicVal = pv
  2384  			panMu.Unlock()
  2385  			return true
  2386  		}
  2387  		testHookOnPanicMu.Unlock()
  2388  
  2389  		// Now force the serve loop to end, via closing the connection.
  2390  		st.cc.Close()
  2391  		select {
  2392  		case <-st.sc.doneServing:
  2393  			// Loop has exited.
  2394  			panMu.Lock()
  2395  			got := panicVal
  2396  			panMu.Unlock()
  2397  			if got != nil {
  2398  				t.Errorf("Got panic: %v", got)
  2399  			}
  2400  		case <-time.After(5 * time.Second):
  2401  			t.Error("timeout")
  2402  		}
  2403  	})
  2404  }
  2405  
  2406  func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) }
  2407  func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) }
  2408  
  2409  func testRejectTLS(t *testing.T, max uint16) {
  2410  	st := newServerTester(t, nil, func(c *tls.Config) {
  2411  		c.MaxVersion = max
  2412  	})
  2413  	defer st.Close()
  2414  	gf := st.wantGoAway()
  2415  	if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2416  		t.Errorf("Got error code %v; want %v", got, want)
  2417  	}
  2418  }
  2419  
  2420  func TestServer_Rejects_TLSBadCipher(t *testing.T) {
  2421  	st := newServerTester(t, nil, func(c *tls.Config) {
  2422  		// All TLS 1.3 ciphers are good. Test with TLS 1.2.
  2423  		c.MaxVersion = tls.VersionTLS12
  2424  		// Only list bad ones:
  2425  		c.CipherSuites = []uint16{
  2426  			tls.TLS_RSA_WITH_RC4_128_SHA,
  2427  			tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  2428  			tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  2429  			tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  2430  			tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  2431  			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  2432  			tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  2433  			tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  2434  			tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  2435  			tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  2436  			tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  2437  			cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
  2438  		}
  2439  	})
  2440  	defer st.Close()
  2441  	gf := st.wantGoAway()
  2442  	if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want {
  2443  		t.Errorf("Got error code %v; want %v", got, want)
  2444  	}
  2445  }
  2446  
  2447  func TestServer_Advertises_Common_Cipher(t *testing.T) {
  2448  	const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  2449  	st := newServerTester(t, nil, func(c *tls.Config) {
  2450  		// Have the client only support the one required by the spec.
  2451  		c.CipherSuites = []uint16{requiredSuite}
  2452  	}, func(ts *httptest.Server) {
  2453  		var srv *http.Server = ts.Config
  2454  		// Have the server configured with no specific cipher suites.
  2455  		// This tests that Go's defaults include the required one.
  2456  		srv.TLSConfig = nil
  2457  	})
  2458  	defer st.Close()
  2459  	st.greet()
  2460  }
  2461  
  2462  func (st *serverTester) onHeaderField(f hpack.HeaderField) {
  2463  	if f.Name == "date" {
  2464  		return
  2465  	}
  2466  	st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value})
  2467  }
  2468  
  2469  func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) {
  2470  	st.decodedHeaders = nil
  2471  	if _, err := st.hpackDec.Write(headerBlock); err != nil {
  2472  		st.t.Fatalf("hpack decoding error: %v", err)
  2473  	}
  2474  	if err := st.hpackDec.Close(); err != nil {
  2475  		st.t.Fatalf("hpack decoding error: %v", err)
  2476  	}
  2477  	return st.decodedHeaders
  2478  }
  2479  
  2480  // testServerResponse sets up an idle HTTP/2 connection. The client function should
  2481  // write a single request that must be handled by the handler. This waits up to 5s
  2482  // for client to return, then up to an additional 2s for the handler to return.
  2483  func testServerResponse(t testing.TB,
  2484  	handler func(http.ResponseWriter, *http.Request) error,
  2485  	client func(*serverTester),
  2486  ) {
  2487  	errc := make(chan error, 1)
  2488  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2489  		if r.Body == nil {
  2490  			t.Fatal("nil Body")
  2491  		}
  2492  		errc <- handler(w, r)
  2493  	})
  2494  	defer st.Close()
  2495  
  2496  	donec := make(chan bool)
  2497  	go func() {
  2498  		defer close(donec)
  2499  		st.greet()
  2500  		client(st)
  2501  	}()
  2502  
  2503  	select {
  2504  	case <-donec:
  2505  	case <-time.After(5 * time.Second):
  2506  		t.Fatal("timeout in client")
  2507  	}
  2508  
  2509  	select {
  2510  	case err := <-errc:
  2511  		if err != nil {
  2512  			t.Fatalf("Error in handler: %v", err)
  2513  		}
  2514  	case <-time.After(2 * time.Second):
  2515  		t.Fatal("timeout in handler")
  2516  	}
  2517  }
  2518  
  2519  // readBodyHandler returns an http Handler func that reads len(want)
  2520  // bytes from r.Body and fails t if the contents read were not
  2521  // the value of want.
  2522  func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) {
  2523  	return func(w http.ResponseWriter, r *http.Request) {
  2524  		buf := make([]byte, len(want))
  2525  		_, err := io.ReadFull(r.Body, buf)
  2526  		if err != nil {
  2527  			t.Error(err)
  2528  			return
  2529  		}
  2530  		if string(buf) != want {
  2531  			t.Errorf("read %q; want %q", buf, want)
  2532  		}
  2533  	}
  2534  }
  2535  
  2536  // TestServerWithCurl currently fails, hence the LenientCipherSuites test. See:
  2537  //   https://github.com/tatsuhiro-t/nghttp2/issues/140 &
  2538  //   http://sourceforge.net/p/curl/bugs/1472/
  2539  func TestServerWithCurl(t *testing.T)                     { testServerWithCurl(t, false) }
  2540  func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) }
  2541  
  2542  func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) {
  2543  	if runtime.GOOS != "linux" {
  2544  		t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2545  	}
  2546  	if testing.Short() {
  2547  		t.Skip("skipping curl test in short mode")
  2548  	}
  2549  	requireCurl(t)
  2550  	var gotConn int32
  2551  	testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) }
  2552  
  2553  	const msg = "Hello from curl!\n"
  2554  	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2555  		w.Header().Set("Foo", "Bar")
  2556  		w.Header().Set("Client-Proto", r.Proto)
  2557  		io.WriteString(w, msg)
  2558  	}))
  2559  	ConfigureServer(ts.Config, &Server{
  2560  		PermitProhibitedCipherSuites: permitProhibitedCipherSuites,
  2561  	})
  2562  	ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config
  2563  	ts.StartTLS()
  2564  	defer ts.Close()
  2565  
  2566  	t.Logf("Running test server for curl to hit at: %s", ts.URL)
  2567  	container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL)
  2568  	defer kill(container)
  2569  	resc := make(chan interface{}, 1)
  2570  	go func() {
  2571  		res, err := dockerLogs(container)
  2572  		if err != nil {
  2573  			resc <- err
  2574  		} else {
  2575  			resc <- res
  2576  		}
  2577  	}()
  2578  	select {
  2579  	case res := <-resc:
  2580  		if err, ok := res.(error); ok {
  2581  			t.Fatal(err)
  2582  		}
  2583  		body := string(res.([]byte))
  2584  		// Search for both "key: value" and "key:value", since curl changed their format
  2585  		// Our Dockerfile contains the latest version (no space), but just in case people
  2586  		// didn't rebuild, check both.
  2587  		if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") {
  2588  			t.Errorf("didn't see foo: Bar header")
  2589  			t.Logf("Got: %s", body)
  2590  		}
  2591  		if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") {
  2592  			t.Errorf("didn't see client-proto: HTTP/2 header")
  2593  			t.Logf("Got: %s", res)
  2594  		}
  2595  		if !strings.Contains(string(res.([]byte)), msg) {
  2596  			t.Errorf("didn't see %q content", msg)
  2597  			t.Logf("Got: %s", res)
  2598  		}
  2599  	case <-time.After(3 * time.Second):
  2600  		t.Errorf("timeout waiting for curl")
  2601  	}
  2602  
  2603  	if atomic.LoadInt32(&gotConn) == 0 {
  2604  		t.Error("never saw an http2 connection")
  2605  	}
  2606  }
  2607  
  2608  var doh2load = flag.Bool("h2load", false, "Run h2load test")
  2609  
  2610  func TestServerWithH2Load(t *testing.T) {
  2611  	if !*doh2load {
  2612  		t.Skip("Skipping without --h2load flag.")
  2613  	}
  2614  	if runtime.GOOS != "linux" {
  2615  		t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway")
  2616  	}
  2617  	requireH2load(t)
  2618  
  2619  	msg := strings.Repeat("Hello, h2load!\n", 5000)
  2620  	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2621  		io.WriteString(w, msg)
  2622  		w.(http.Flusher).Flush()
  2623  		io.WriteString(w, msg)
  2624  	}))
  2625  	ts.StartTLS()
  2626  	defer ts.Close()
  2627  
  2628  	cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl",
  2629  		"-n100000", "-c100", "-m100", ts.URL)
  2630  	cmd.Stdout = os.Stdout
  2631  	cmd.Stderr = os.Stderr
  2632  	if err := cmd.Run(); err != nil {
  2633  		t.Fatal(err)
  2634  	}
  2635  }
  2636  
  2637  // Issue 12843
  2638  func TestServerDoS_MaxHeaderListSize(t *testing.T) {
  2639  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {})
  2640  	defer st.Close()
  2641  
  2642  	// shake hands
  2643  	frameSize := defaultMaxReadFrameSize
  2644  	var advHeaderListSize *uint32
  2645  	st.greetAndCheckSettings(func(s Setting) error {
  2646  		switch s.ID {
  2647  		case SettingMaxFrameSize:
  2648  			if s.Val < minMaxFrameSize {
  2649  				frameSize = minMaxFrameSize
  2650  			} else if s.Val > maxFrameSize {
  2651  				frameSize = maxFrameSize
  2652  			} else {
  2653  				frameSize = int(s.Val)
  2654  			}
  2655  		case SettingMaxHeaderListSize:
  2656  			advHeaderListSize = &s.Val
  2657  		}
  2658  		return nil
  2659  	})
  2660  
  2661  	if advHeaderListSize == nil {
  2662  		t.Errorf("server didn't advertise a max header list size")
  2663  	} else if *advHeaderListSize == 0 {
  2664  		t.Errorf("server advertised a max header list size of 0")
  2665  	}
  2666  
  2667  	st.encodeHeaderField(":method", "GET")
  2668  	st.encodeHeaderField(":path", "/")
  2669  	st.encodeHeaderField(":scheme", "https")
  2670  	cookie := strings.Repeat("*", 4058)
  2671  	st.encodeHeaderField("cookie", cookie)
  2672  	st.writeHeaders(HeadersFrameParam{
  2673  		StreamID:      1,
  2674  		BlockFragment: st.headerBuf.Bytes(),
  2675  		EndStream:     true,
  2676  		EndHeaders:    false,
  2677  	})
  2678  
  2679  	// Capture the short encoding of a duplicate ~4K cookie, now
  2680  	// that we've already sent it once.
  2681  	st.headerBuf.Reset()
  2682  	st.encodeHeaderField("cookie", cookie)
  2683  
  2684  	// Now send 1MB of it.
  2685  	const size = 1 << 20
  2686  	b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len())
  2687  	for len(b) > 0 {
  2688  		chunk := b
  2689  		if len(chunk) > frameSize {
  2690  			chunk = chunk[:frameSize]
  2691  		}
  2692  		b = b[len(chunk):]
  2693  		st.fr.WriteContinuation(1, len(b) == 0, chunk)
  2694  	}
  2695  
  2696  	h := st.wantHeaders()
  2697  	if !h.HeadersEnded() {
  2698  		t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2699  	}
  2700  	headers := st.decodeHeader(h.HeaderBlockFragment())
  2701  	want := [][2]string{
  2702  		{":status", "431"},
  2703  		{"content-type", "text/html; charset=utf-8"},
  2704  		{"content-length", "63"},
  2705  	}
  2706  	if !reflect.DeepEqual(headers, want) {
  2707  		t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2708  	}
  2709  }
  2710  
  2711  func TestServer_Response_Stream_With_Missing_Trailer(t *testing.T) {
  2712  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2713  		w.Header().Set("Trailer", "test-trailer")
  2714  		return nil
  2715  	}, func(st *serverTester) {
  2716  		getSlash(st)
  2717  		hf := st.wantHeaders()
  2718  		if !hf.HeadersEnded() {
  2719  			t.Fatal("want END_HEADERS flag")
  2720  		}
  2721  		df := st.wantData()
  2722  		if len(df.data) != 0 {
  2723  			t.Fatal("did not want data")
  2724  		}
  2725  		if !df.StreamEnded() {
  2726  			t.Fatal("want END_STREAM flag")
  2727  		}
  2728  	})
  2729  }
  2730  
  2731  func TestCompressionErrorOnWrite(t *testing.T) {
  2732  	const maxStrLen = 8 << 10
  2733  	var serverConfig *http.Server
  2734  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2735  		// No response body.
  2736  	}, func(ts *httptest.Server) {
  2737  		serverConfig = ts.Config
  2738  		serverConfig.MaxHeaderBytes = maxStrLen
  2739  	})
  2740  	st.addLogFilter("connection error: COMPRESSION_ERROR")
  2741  	defer st.Close()
  2742  	st.greet()
  2743  
  2744  	maxAllowed := st.sc.framer.maxHeaderStringLen()
  2745  
  2746  	// Crank this up, now that we have a conn connected with the
  2747  	// hpack.Decoder's max string length set has been initialized
  2748  	// from the earlier low ~8K value. We want this higher so don't
  2749  	// hit the max header list size. We only want to test hitting
  2750  	// the max string size.
  2751  	serverConfig.MaxHeaderBytes = 1 << 20
  2752  
  2753  	// First a request with a header that's exactly the max allowed size
  2754  	// for the hpack compression. It's still too long for the header list
  2755  	// size, so we'll get the 431 error, but that keeps the compression
  2756  	// context still valid.
  2757  	hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed))
  2758  
  2759  	st.writeHeaders(HeadersFrameParam{
  2760  		StreamID:      1,
  2761  		BlockFragment: hbf,
  2762  		EndStream:     true,
  2763  		EndHeaders:    true,
  2764  	})
  2765  	h := st.wantHeaders()
  2766  	if !h.HeadersEnded() {
  2767  		t.Fatalf("Got HEADERS without END_HEADERS set: %v", h)
  2768  	}
  2769  	headers := st.decodeHeader(h.HeaderBlockFragment())
  2770  	want := [][2]string{
  2771  		{":status", "431"},
  2772  		{"content-type", "text/html; charset=utf-8"},
  2773  		{"content-length", "63"},
  2774  	}
  2775  	if !reflect.DeepEqual(headers, want) {
  2776  		t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  2777  	}
  2778  	df := st.wantData()
  2779  	if !strings.Contains(string(df.Data()), "HTTP Error 431") {
  2780  		t.Errorf("Unexpected data body: %q", df.Data())
  2781  	}
  2782  	if !df.StreamEnded() {
  2783  		t.Fatalf("expect data stream end")
  2784  	}
  2785  
  2786  	// And now send one that's just one byte too big.
  2787  	hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1))
  2788  	st.writeHeaders(HeadersFrameParam{
  2789  		StreamID:      3,
  2790  		BlockFragment: hbf,
  2791  		EndStream:     true,
  2792  		EndHeaders:    true,
  2793  	})
  2794  	ga := st.wantGoAway()
  2795  	if ga.ErrCode != ErrCodeCompression {
  2796  		t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2797  	}
  2798  }
  2799  
  2800  func TestCompressionErrorOnClose(t *testing.T) {
  2801  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  2802  		// No response body.
  2803  	})
  2804  	st.addLogFilter("connection error: COMPRESSION_ERROR")
  2805  	defer st.Close()
  2806  	st.greet()
  2807  
  2808  	hbf := st.encodeHeader("foo", "bar")
  2809  	hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails.
  2810  	st.writeHeaders(HeadersFrameParam{
  2811  		StreamID:      1,
  2812  		BlockFragment: hbf,
  2813  		EndStream:     true,
  2814  		EndHeaders:    true,
  2815  	})
  2816  	ga := st.wantGoAway()
  2817  	if ga.ErrCode != ErrCodeCompression {
  2818  		t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode)
  2819  	}
  2820  }
  2821  
  2822  // test that a server handler can read trailers from a client
  2823  func TestServerReadsTrailers(t *testing.T) {
  2824  	const testBody = "some test body"
  2825  	writeReq := func(st *serverTester) {
  2826  		st.writeHeaders(HeadersFrameParam{
  2827  			StreamID:      1, // clients send odd numbers
  2828  			BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"),
  2829  			EndStream:     false,
  2830  			EndHeaders:    true,
  2831  		})
  2832  		st.writeData(1, false, []byte(testBody))
  2833  		st.writeHeaders(HeadersFrameParam{
  2834  			StreamID: 1, // clients send odd numbers
  2835  			BlockFragment: st.encodeHeaderRaw(
  2836  				"foo", "foov",
  2837  				"bar", "barv",
  2838  				"baz", "bazv",
  2839  				"surprise", "wasn't declared; shouldn't show up",
  2840  			),
  2841  			EndStream:  true,
  2842  			EndHeaders: true,
  2843  		})
  2844  	}
  2845  	checkReq := func(r *http.Request) {
  2846  		wantTrailer := http.Header{
  2847  			"Foo": nil,
  2848  			"Bar": nil,
  2849  			"Baz": nil,
  2850  		}
  2851  		if !reflect.DeepEqual(r.Trailer, wantTrailer) {
  2852  			t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer)
  2853  		}
  2854  		slurp, err := ioutil.ReadAll(r.Body)
  2855  		if string(slurp) != testBody {
  2856  			t.Errorf("read body %q; want %q", slurp, testBody)
  2857  		}
  2858  		if err != nil {
  2859  			t.Fatalf("Body slurp: %v", err)
  2860  		}
  2861  		wantTrailerAfter := http.Header{
  2862  			"Foo": {"foov"},
  2863  			"Bar": {"barv"},
  2864  			"Baz": {"bazv"},
  2865  		}
  2866  		if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) {
  2867  			t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter)
  2868  		}
  2869  	}
  2870  	testServerRequest(t, writeReq, checkReq)
  2871  }
  2872  
  2873  // test that a server handler can send trailers
  2874  func TestServerWritesTrailers_WithFlush(t *testing.T)    { testServerWritesTrailers(t, true) }
  2875  func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) }
  2876  
  2877  func testServerWritesTrailers(t *testing.T, withFlush bool) {
  2878  	// See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3
  2879  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2880  		w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
  2881  		w.Header().Add("Trailer", "Server-Trailer-C")
  2882  		w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered
  2883  
  2884  		// Regular headers:
  2885  		w.Header().Set("Foo", "Bar")
  2886  		w.Header().Set("Content-Length", "5") // len("Hello")
  2887  
  2888  		io.WriteString(w, "Hello")
  2889  		if withFlush {
  2890  			w.(http.Flusher).Flush()
  2891  		}
  2892  		w.Header().Set("Server-Trailer-A", "valuea")
  2893  		w.Header().Set("Server-Trailer-C", "valuec") // skipping B
  2894  		// After a flush, random keys like Server-Surprise shouldn't show up:
  2895  		w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!")
  2896  		// But we do permit promoting keys to trailers after a
  2897  		// flush if they start with the magic
  2898  		// otherwise-invalid "Trailer:" prefix:
  2899  		w.Header().Set("Trailer:Post-Header-Trailer", "hi1")
  2900  		w.Header().Set("Trailer:post-header-trailer2", "hi2")
  2901  		w.Header().Set("Trailer:Range", "invalid")
  2902  		w.Header().Set("Trailer:Foo\x01Bogus", "invalid")
  2903  		w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 7230 4.1.2")
  2904  		w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 7230 4.1.2")
  2905  		w.Header().Set("Trailer", "should not be included; Forbidden by RFC 7230 4.1.2")
  2906  		return nil
  2907  	}, func(st *serverTester) {
  2908  		getSlash(st)
  2909  		hf := st.wantHeaders()
  2910  		if hf.StreamEnded() {
  2911  			t.Fatal("response HEADERS had END_STREAM")
  2912  		}
  2913  		if !hf.HeadersEnded() {
  2914  			t.Fatal("response HEADERS didn't have END_HEADERS")
  2915  		}
  2916  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  2917  		wanth := [][2]string{
  2918  			{":status", "200"},
  2919  			{"foo", "Bar"},
  2920  			{"trailer", "Server-Trailer-A, Server-Trailer-B"},
  2921  			{"trailer", "Server-Trailer-C"},
  2922  			{"trailer", "Transfer-Encoding, Content-Length, Trailer"},
  2923  			{"content-type", "text/plain; charset=utf-8"},
  2924  			{"content-length", "5"},
  2925  		}
  2926  		if !reflect.DeepEqual(goth, wanth) {
  2927  			t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2928  		}
  2929  		df := st.wantData()
  2930  		if string(df.Data()) != "Hello" {
  2931  			t.Fatalf("Client read %q; want Hello", df.Data())
  2932  		}
  2933  		if df.StreamEnded() {
  2934  			t.Fatalf("data frame had STREAM_ENDED")
  2935  		}
  2936  		tf := st.wantHeaders() // for the trailers
  2937  		if !tf.StreamEnded() {
  2938  			t.Fatalf("trailers HEADERS lacked END_STREAM")
  2939  		}
  2940  		if !tf.HeadersEnded() {
  2941  			t.Fatalf("trailers HEADERS lacked END_HEADERS")
  2942  		}
  2943  		wanth = [][2]string{
  2944  			{"post-header-trailer", "hi1"},
  2945  			{"post-header-trailer2", "hi2"},
  2946  			{"server-trailer-a", "valuea"},
  2947  			{"server-trailer-c", "valuec"},
  2948  		}
  2949  		goth = st.decodeHeader(tf.HeaderBlockFragment())
  2950  		if !reflect.DeepEqual(goth, wanth) {
  2951  			t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2952  		}
  2953  	})
  2954  }
  2955  
  2956  // validate transmitted header field names & values
  2957  // golang.org/issue/14048
  2958  func TestServerDoesntWriteInvalidHeaders(t *testing.T) {
  2959  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  2960  		w.Header().Add("OK1", "x")
  2961  		w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key
  2962  		w.Header().Add("Bad1\x00", "x")  // null in key
  2963  		w.Header().Add("Bad2", "x\x00y") // null in value
  2964  		return nil
  2965  	}, func(st *serverTester) {
  2966  		getSlash(st)
  2967  		hf := st.wantHeaders()
  2968  		if !hf.StreamEnded() {
  2969  			t.Error("response HEADERS lacked END_STREAM")
  2970  		}
  2971  		if !hf.HeadersEnded() {
  2972  			t.Fatal("response HEADERS didn't have END_HEADERS")
  2973  		}
  2974  		goth := st.decodeHeader(hf.HeaderBlockFragment())
  2975  		wanth := [][2]string{
  2976  			{":status", "200"},
  2977  			{"ok1", "x"},
  2978  			{"content-length", "0"},
  2979  		}
  2980  		if !reflect.DeepEqual(goth, wanth) {
  2981  			t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth)
  2982  		}
  2983  	})
  2984  }
  2985  
  2986  func BenchmarkServerGets(b *testing.B) {
  2987  	defer disableGoroutineTracking()()
  2988  	b.ReportAllocs()
  2989  
  2990  	const msg = "Hello, world"
  2991  	st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  2992  		io.WriteString(w, msg)
  2993  	})
  2994  	defer st.Close()
  2995  	st.greet()
  2996  
  2997  	// Give the server quota to reply. (plus it has the 64KB)
  2998  	if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  2999  		b.Fatal(err)
  3000  	}
  3001  
  3002  	for i := 0; i < b.N; i++ {
  3003  		id := 1 + uint32(i)*2
  3004  		st.writeHeaders(HeadersFrameParam{
  3005  			StreamID:      id,
  3006  			BlockFragment: st.encodeHeader(),
  3007  			EndStream:     true,
  3008  			EndHeaders:    true,
  3009  		})
  3010  		st.wantHeaders()
  3011  		df := st.wantData()
  3012  		if !df.StreamEnded() {
  3013  			b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  3014  		}
  3015  	}
  3016  }
  3017  
  3018  func BenchmarkServerPosts(b *testing.B) {
  3019  	defer disableGoroutineTracking()()
  3020  	b.ReportAllocs()
  3021  
  3022  	const msg = "Hello, world"
  3023  	st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3024  		// Consume the (empty) body from th peer before replying, otherwise
  3025  		// the server will sometimes (depending on scheduling) send the peer a
  3026  		// a RST_STREAM with the CANCEL error code.
  3027  		if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  3028  			b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  3029  		}
  3030  		io.WriteString(w, msg)
  3031  	})
  3032  	defer st.Close()
  3033  	st.greet()
  3034  
  3035  	// Give the server quota to reply. (plus it has the 64KB)
  3036  	if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3037  		b.Fatal(err)
  3038  	}
  3039  
  3040  	for i := 0; i < b.N; i++ {
  3041  		id := 1 + uint32(i)*2
  3042  		st.writeHeaders(HeadersFrameParam{
  3043  			StreamID:      id,
  3044  			BlockFragment: st.encodeHeader(":method", "POST"),
  3045  			EndStream:     false,
  3046  			EndHeaders:    true,
  3047  		})
  3048  		st.writeData(id, true, nil)
  3049  		st.wantHeaders()
  3050  		df := st.wantData()
  3051  		if !df.StreamEnded() {
  3052  			b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  3053  		}
  3054  	}
  3055  }
  3056  
  3057  // Send a stream of messages from server to client in separate data frames.
  3058  // Brings up performance issues seen in long streams.
  3059  // Created to show problem in go issue #18502
  3060  func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) {
  3061  	benchmarkServerToClientStream(b)
  3062  }
  3063  
  3064  // Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8
  3065  // Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer.
  3066  func BenchmarkServerToClientStreamReuseFrames(b *testing.B) {
  3067  	benchmarkServerToClientStream(b, optFramerReuseFrames)
  3068  }
  3069  
  3070  func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) {
  3071  	defer disableGoroutineTracking()()
  3072  	b.ReportAllocs()
  3073  	const msgLen = 1
  3074  	// default window size
  3075  	const windowSize = 1<<16 - 1
  3076  
  3077  	// next message to send from the server and for the client to expect
  3078  	nextMsg := func(i int) []byte {
  3079  		msg := make([]byte, msgLen)
  3080  		msg[0] = byte(i)
  3081  		if len(msg) != msgLen {
  3082  			panic("invalid test setup msg length")
  3083  		}
  3084  		return msg
  3085  	}
  3086  
  3087  	st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3088  		// Consume the (empty) body from th peer before replying, otherwise
  3089  		// the server will sometimes (depending on scheduling) send the peer a
  3090  		// a RST_STREAM with the CANCEL error code.
  3091  		if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil {
  3092  			b.Errorf("Copy error; got %v, %v; want 0, nil", n, err)
  3093  		}
  3094  		for i := 0; i < b.N; i += 1 {
  3095  			w.Write(nextMsg(i))
  3096  			w.(http.Flusher).Flush()
  3097  		}
  3098  	}, newServerOpts...)
  3099  	defer st.Close()
  3100  	st.greet()
  3101  
  3102  	const id = uint32(1)
  3103  
  3104  	st.writeHeaders(HeadersFrameParam{
  3105  		StreamID:      id,
  3106  		BlockFragment: st.encodeHeader(":method", "POST"),
  3107  		EndStream:     false,
  3108  		EndHeaders:    true,
  3109  	})
  3110  
  3111  	st.writeData(id, true, nil)
  3112  	st.wantHeaders()
  3113  
  3114  	var pendingWindowUpdate = uint32(0)
  3115  
  3116  	for i := 0; i < b.N; i += 1 {
  3117  		expected := nextMsg(i)
  3118  		df := st.wantData()
  3119  		if bytes.Compare(expected, df.data) != 0 {
  3120  			b.Fatalf("Bad message received; want %v; got %v", expected, df.data)
  3121  		}
  3122  		// try to send infrequent but large window updates so they don't overwhelm the test
  3123  		pendingWindowUpdate += uint32(len(df.data))
  3124  		if pendingWindowUpdate >= windowSize/2 {
  3125  			if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil {
  3126  				b.Fatal(err)
  3127  			}
  3128  			if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil {
  3129  				b.Fatal(err)
  3130  			}
  3131  			pendingWindowUpdate = 0
  3132  		}
  3133  	}
  3134  	df := st.wantData()
  3135  	if !df.StreamEnded() {
  3136  		b.Fatalf("DATA didn't have END_STREAM; got %v", df)
  3137  	}
  3138  }
  3139  
  3140  // go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53
  3141  // Verify we don't hang.
  3142  func TestIssue53(t *testing.T) {
  3143  	const data = "PRI * HTTP/2.0\r\n\r\nSM" +
  3144  		"\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad"
  3145  	s := &http.Server{
  3146  		ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags),
  3147  		Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  3148  			w.Write([]byte("hello"))
  3149  		}),
  3150  	}
  3151  	s2 := &Server{
  3152  		MaxReadFrameSize:             1 << 16,
  3153  		PermitProhibitedCipherSuites: true,
  3154  	}
  3155  	c := &issue53Conn{[]byte(data), false, false}
  3156  	s2.ServeConn(c, &ServeConnOpts{BaseConfig: s})
  3157  	if !c.closed {
  3158  		t.Fatal("connection is not closed")
  3159  	}
  3160  }
  3161  
  3162  type issue53Conn struct {
  3163  	data    []byte
  3164  	closed  bool
  3165  	written bool
  3166  }
  3167  
  3168  func (c *issue53Conn) Read(b []byte) (n int, err error) {
  3169  	if len(c.data) == 0 {
  3170  		return 0, io.EOF
  3171  	}
  3172  	n = copy(b, c.data)
  3173  	c.data = c.data[n:]
  3174  	return
  3175  }
  3176  
  3177  func (c *issue53Conn) Write(b []byte) (n int, err error) {
  3178  	c.written = true
  3179  	return len(b), nil
  3180  }
  3181  
  3182  func (c *issue53Conn) Close() error {
  3183  	c.closed = true
  3184  	return nil
  3185  }
  3186  
  3187  func (c *issue53Conn) LocalAddr() net.Addr {
  3188  	return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  3189  }
  3190  func (c *issue53Conn) RemoteAddr() net.Addr {
  3191  	return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706}
  3192  }
  3193  func (c *issue53Conn) SetDeadline(t time.Time) error      { return nil }
  3194  func (c *issue53Conn) SetReadDeadline(t time.Time) error  { return nil }
  3195  func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil }
  3196  
  3197  // golang.org/issue/12895
  3198  func TestConfigureServer(t *testing.T) {
  3199  	tests := []struct {
  3200  		name      string
  3201  		tlsConfig *tls.Config
  3202  		wantErr   string
  3203  	}{
  3204  		{
  3205  			name: "empty server",
  3206  		},
  3207  		{
  3208  			name: "just the required cipher suite",
  3209  			tlsConfig: &tls.Config{
  3210  				CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  3211  			},
  3212  		},
  3213  		{
  3214  			name: "just the alternative required cipher suite",
  3215  			tlsConfig: &tls.Config{
  3216  				CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  3217  			},
  3218  		},
  3219  		{
  3220  			name: "missing required cipher suite",
  3221  			tlsConfig: &tls.Config{
  3222  				CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
  3223  			},
  3224  			wantErr: "is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.",
  3225  		},
  3226  		{
  3227  			name: "required after bad",
  3228  			tlsConfig: &tls.Config{
  3229  				CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  3230  			},
  3231  			wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after",
  3232  		},
  3233  		{
  3234  			name: "bad after required",
  3235  			tlsConfig: &tls.Config{
  3236  				CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA},
  3237  			},
  3238  		},
  3239  	}
  3240  	for _, tt := range tests {
  3241  		srv := &http.Server{TLSConfig: tt.tlsConfig}
  3242  		err := ConfigureServer(srv, nil)
  3243  		if (err != nil) != (tt.wantErr != "") {
  3244  			if tt.wantErr != "" {
  3245  				t.Errorf("%s: success, but want error", tt.name)
  3246  			} else {
  3247  				t.Errorf("%s: unexpected error: %v", tt.name, err)
  3248  			}
  3249  		}
  3250  		if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) {
  3251  			t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr)
  3252  		}
  3253  		if err == nil && !srv.TLSConfig.PreferServerCipherSuites {
  3254  			t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name)
  3255  		}
  3256  	}
  3257  }
  3258  
  3259  func TestServerRejectHeadWithBody(t *testing.T) {
  3260  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3261  		// No response body.
  3262  	})
  3263  	defer st.Close()
  3264  	st.greet()
  3265  	st.writeHeaders(HeadersFrameParam{
  3266  		StreamID:      1, // clients send odd numbers
  3267  		BlockFragment: st.encodeHeader(":method", "HEAD"),
  3268  		EndStream:     false, // what we're testing, a bogus HEAD request with body
  3269  		EndHeaders:    true,
  3270  	})
  3271  	st.wantRSTStream(1, ErrCodeProtocol)
  3272  }
  3273  
  3274  func TestServerNoAutoContentLengthOnHead(t *testing.T) {
  3275  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3276  		// No response body. (or smaller than one frame)
  3277  	})
  3278  	defer st.Close()
  3279  	st.greet()
  3280  	st.writeHeaders(HeadersFrameParam{
  3281  		StreamID:      1, // clients send odd numbers
  3282  		BlockFragment: st.encodeHeader(":method", "HEAD"),
  3283  		EndStream:     true,
  3284  		EndHeaders:    true,
  3285  	})
  3286  	h := st.wantHeaders()
  3287  	headers := st.decodeHeader(h.HeaderBlockFragment())
  3288  	want := [][2]string{
  3289  		{":status", "200"},
  3290  	}
  3291  	if !reflect.DeepEqual(headers, want) {
  3292  		t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3293  	}
  3294  }
  3295  
  3296  // golang.org/issue/13495
  3297  func TestServerNoDuplicateContentType(t *testing.T) {
  3298  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3299  		w.Header()["Content-Type"] = []string{""}
  3300  		fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
  3301  	})
  3302  	defer st.Close()
  3303  	st.greet()
  3304  	st.writeHeaders(HeadersFrameParam{
  3305  		StreamID:      1,
  3306  		BlockFragment: st.encodeHeader(),
  3307  		EndStream:     true,
  3308  		EndHeaders:    true,
  3309  	})
  3310  	h := st.wantHeaders()
  3311  	headers := st.decodeHeader(h.HeaderBlockFragment())
  3312  	want := [][2]string{
  3313  		{":status", "200"},
  3314  		{"content-type", ""},
  3315  		{"content-length", "41"},
  3316  	}
  3317  	if !reflect.DeepEqual(headers, want) {
  3318  		t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want)
  3319  	}
  3320  }
  3321  
  3322  func disableGoroutineTracking() (restore func()) {
  3323  	old := DebugGoroutines
  3324  	DebugGoroutines = false
  3325  	return func() { DebugGoroutines = old }
  3326  }
  3327  
  3328  func BenchmarkServer_GetRequest(b *testing.B) {
  3329  	defer disableGoroutineTracking()()
  3330  	b.ReportAllocs()
  3331  	const msg = "Hello, world."
  3332  	st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3333  		n, err := io.Copy(ioutil.Discard, r.Body)
  3334  		if err != nil || n > 0 {
  3335  			b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3336  		}
  3337  		io.WriteString(w, msg)
  3338  	})
  3339  	defer st.Close()
  3340  
  3341  	st.greet()
  3342  	// Give the server quota to reply. (plus it has the 64KB)
  3343  	if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3344  		b.Fatal(err)
  3345  	}
  3346  	hbf := st.encodeHeader(":method", "GET")
  3347  	for i := 0; i < b.N; i++ {
  3348  		streamID := uint32(1 + 2*i)
  3349  		st.writeHeaders(HeadersFrameParam{
  3350  			StreamID:      streamID,
  3351  			BlockFragment: hbf,
  3352  			EndStream:     true,
  3353  			EndHeaders:    true,
  3354  		})
  3355  		st.wantHeaders()
  3356  		st.wantData()
  3357  	}
  3358  }
  3359  
  3360  func BenchmarkServer_PostRequest(b *testing.B) {
  3361  	defer disableGoroutineTracking()()
  3362  	b.ReportAllocs()
  3363  	const msg = "Hello, world."
  3364  	st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) {
  3365  		n, err := io.Copy(ioutil.Discard, r.Body)
  3366  		if err != nil || n > 0 {
  3367  			b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err)
  3368  		}
  3369  		io.WriteString(w, msg)
  3370  	})
  3371  	defer st.Close()
  3372  	st.greet()
  3373  	// Give the server quota to reply. (plus it has the 64KB)
  3374  	if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil {
  3375  		b.Fatal(err)
  3376  	}
  3377  	hbf := st.encodeHeader(":method", "POST")
  3378  	for i := 0; i < b.N; i++ {
  3379  		streamID := uint32(1 + 2*i)
  3380  		st.writeHeaders(HeadersFrameParam{
  3381  			StreamID:      streamID,
  3382  			BlockFragment: hbf,
  3383  			EndStream:     false,
  3384  			EndHeaders:    true,
  3385  		})
  3386  		st.writeData(streamID, true, nil)
  3387  		st.wantHeaders()
  3388  		st.wantData()
  3389  	}
  3390  }
  3391  
  3392  type connStateConn struct {
  3393  	net.Conn
  3394  	cs tls.ConnectionState
  3395  }
  3396  
  3397  func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs }
  3398  
  3399  // golang.org/issue/12737 -- handle any net.Conn, not just
  3400  // *tls.Conn.
  3401  func TestServerHandleCustomConn(t *testing.T) {
  3402  	var s Server
  3403  	c1, c2 := net.Pipe()
  3404  	clientDone := make(chan struct{})
  3405  	handlerDone := make(chan struct{})
  3406  	var req *http.Request
  3407  	go func() {
  3408  		defer close(clientDone)
  3409  		defer c2.Close()
  3410  		fr := NewFramer(c2, c2)
  3411  		io.WriteString(c2, ClientPreface)
  3412  		fr.WriteSettings()
  3413  		fr.WriteSettingsAck()
  3414  		f, err := fr.ReadFrame()
  3415  		if err != nil {
  3416  			t.Error(err)
  3417  			return
  3418  		}
  3419  		if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() {
  3420  			t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f))
  3421  			return
  3422  		}
  3423  		f, err = fr.ReadFrame()
  3424  		if err != nil {
  3425  			t.Error(err)
  3426  			return
  3427  		}
  3428  		if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() {
  3429  			t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f))
  3430  			return
  3431  		}
  3432  		var henc hpackEncoder
  3433  		fr.WriteHeaders(HeadersFrameParam{
  3434  			StreamID:      1,
  3435  			BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"),
  3436  			EndStream:     true,
  3437  			EndHeaders:    true,
  3438  		})
  3439  		go io.Copy(ioutil.Discard, c2)
  3440  		<-handlerDone
  3441  	}()
  3442  	const testString = "my custom ConnectionState"
  3443  	fakeConnState := tls.ConnectionState{
  3444  		ServerName:  testString,
  3445  		Version:     tls.VersionTLS12,
  3446  		CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  3447  	}
  3448  	go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{
  3449  		BaseConfig: &http.Server{
  3450  			Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3451  				defer close(handlerDone)
  3452  				req = r
  3453  			}),
  3454  		}})
  3455  	select {
  3456  	case <-clientDone:
  3457  	case <-time.After(5 * time.Second):
  3458  		t.Fatal("timeout waiting for handler")
  3459  	}
  3460  	if req.TLS == nil {
  3461  		t.Fatalf("Request.TLS is nil. Got: %#v", req)
  3462  	}
  3463  	if req.TLS.ServerName != testString {
  3464  		t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString)
  3465  	}
  3466  }
  3467  
  3468  // golang.org/issue/14214
  3469  func TestServer_Rejects_ConnHeaders(t *testing.T) {
  3470  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3471  		t.Error("should not get to Handler")
  3472  	})
  3473  	defer st.Close()
  3474  	st.greet()
  3475  	st.bodylessReq1("connection", "foo")
  3476  	hf := st.wantHeaders()
  3477  	goth := st.decodeHeader(hf.HeaderBlockFragment())
  3478  	wanth := [][2]string{
  3479  		{":status", "400"},
  3480  		{"content-type", "text/plain; charset=utf-8"},
  3481  		{"x-content-type-options", "nosniff"},
  3482  		{"content-length", "51"},
  3483  	}
  3484  	if !reflect.DeepEqual(goth, wanth) {
  3485  		t.Errorf("Got headers %v; want %v", goth, wanth)
  3486  	}
  3487  }
  3488  
  3489  type hpackEncoder struct {
  3490  	enc *hpack.Encoder
  3491  	buf bytes.Buffer
  3492  }
  3493  
  3494  func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte {
  3495  	if len(headers)%2 == 1 {
  3496  		panic("odd number of kv args")
  3497  	}
  3498  	he.buf.Reset()
  3499  	if he.enc == nil {
  3500  		he.enc = hpack.NewEncoder(&he.buf)
  3501  	}
  3502  	for len(headers) > 0 {
  3503  		k, v := headers[0], headers[1]
  3504  		err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  3505  		if err != nil {
  3506  			t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
  3507  		}
  3508  		headers = headers[2:]
  3509  	}
  3510  	return he.buf.Bytes()
  3511  }
  3512  
  3513  func TestCheckValidHTTP2Request(t *testing.T) {
  3514  	tests := []struct {
  3515  		h    http.Header
  3516  		want error
  3517  	}{
  3518  		{
  3519  			h:    http.Header{"Te": {"trailers"}},
  3520  			want: nil,
  3521  		},
  3522  		{
  3523  			h:    http.Header{"Te": {"trailers", "bogus"}},
  3524  			want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`),
  3525  		},
  3526  		{
  3527  			h:    http.Header{"Foo": {""}},
  3528  			want: nil,
  3529  		},
  3530  		{
  3531  			h:    http.Header{"Connection": {""}},
  3532  			want: errors.New(`request header "Connection" is not valid in HTTP/2`),
  3533  		},
  3534  		{
  3535  			h:    http.Header{"Proxy-Connection": {""}},
  3536  			want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`),
  3537  		},
  3538  		{
  3539  			h:    http.Header{"Keep-Alive": {""}},
  3540  			want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`),
  3541  		},
  3542  		{
  3543  			h:    http.Header{"Upgrade": {""}},
  3544  			want: errors.New(`request header "Upgrade" is not valid in HTTP/2`),
  3545  		},
  3546  	}
  3547  	for i, tt := range tests {
  3548  		got := checkValidHTTP2RequestHeaders(tt.h)
  3549  		if !equalError(got, tt.want) {
  3550  			t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want)
  3551  		}
  3552  	}
  3553  }
  3554  
  3555  // golang.org/issue/14030
  3556  func TestExpect100ContinueAfterHandlerWrites(t *testing.T) {
  3557  	const msg = "Hello"
  3558  	const msg2 = "World"
  3559  
  3560  	doRead := make(chan bool, 1)
  3561  	defer close(doRead) // fallback cleanup
  3562  
  3563  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3564  		io.WriteString(w, msg)
  3565  		w.(http.Flusher).Flush()
  3566  
  3567  		// Do a read, which might force a 100-continue status to be sent.
  3568  		<-doRead
  3569  		r.Body.Read(make([]byte, 10))
  3570  
  3571  		io.WriteString(w, msg2)
  3572  
  3573  	}, optOnlyServer)
  3574  	defer st.Close()
  3575  
  3576  	tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3577  	defer tr.CloseIdleConnections()
  3578  
  3579  	req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20))
  3580  	req.Header.Set("Expect", "100-continue")
  3581  
  3582  	res, err := tr.RoundTrip(req)
  3583  	if err != nil {
  3584  		t.Fatal(err)
  3585  	}
  3586  	defer res.Body.Close()
  3587  
  3588  	buf := make([]byte, len(msg))
  3589  	if _, err := io.ReadFull(res.Body, buf); err != nil {
  3590  		t.Fatal(err)
  3591  	}
  3592  	if string(buf) != msg {
  3593  		t.Fatalf("msg = %q; want %q", buf, msg)
  3594  	}
  3595  
  3596  	doRead <- true
  3597  
  3598  	if _, err := io.ReadFull(res.Body, buf); err != nil {
  3599  		t.Fatal(err)
  3600  	}
  3601  	if string(buf) != msg2 {
  3602  		t.Fatalf("second msg = %q; want %q", buf, msg2)
  3603  	}
  3604  }
  3605  
  3606  type funcReader func([]byte) (n int, err error)
  3607  
  3608  func (f funcReader) Read(p []byte) (n int, err error) { return f(p) }
  3609  
  3610  // golang.org/issue/16481 -- return flow control when streams close with unread data.
  3611  // (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport)
  3612  func TestUnreadFlowControlReturned_Server(t *testing.T) {
  3613  	unblock := make(chan bool, 1)
  3614  	defer close(unblock)
  3615  
  3616  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3617  		// Don't read the 16KB request body. Wait until the client's
  3618  		// done sending it and then return. This should cause the Server
  3619  		// to then return those 16KB of flow control to the client.
  3620  		<-unblock
  3621  	}, optOnlyServer)
  3622  	defer st.Close()
  3623  
  3624  	tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3625  	defer tr.CloseIdleConnections()
  3626  
  3627  	// This previously hung on the 4th iteration.
  3628  	for i := 0; i < 6; i++ {
  3629  		body := io.MultiReader(
  3630  			io.LimitReader(neverEnding('A'), 16<<10),
  3631  			funcReader(func([]byte) (n int, err error) {
  3632  				unblock <- true
  3633  				return 0, io.EOF
  3634  			}),
  3635  		)
  3636  		req, _ := http.NewRequest("POST", st.ts.URL, body)
  3637  		res, err := tr.RoundTrip(req)
  3638  		if err != nil {
  3639  			t.Fatal(err)
  3640  		}
  3641  		res.Body.Close()
  3642  	}
  3643  
  3644  }
  3645  
  3646  func TestServerIdleTimeout(t *testing.T) {
  3647  	if testing.Short() {
  3648  		t.Skip("skipping in short mode")
  3649  	}
  3650  
  3651  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3652  	}, func(h2s *Server) {
  3653  		h2s.IdleTimeout = 500 * time.Millisecond
  3654  	})
  3655  	defer st.Close()
  3656  
  3657  	st.greet()
  3658  	ga := st.wantGoAway()
  3659  	if ga.ErrCode != ErrCodeNo {
  3660  		t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3661  	}
  3662  }
  3663  
  3664  func TestServerIdleTimeout_AfterRequest(t *testing.T) {
  3665  	if testing.Short() {
  3666  		t.Skip("skipping in short mode")
  3667  	}
  3668  	const timeout = 250 * time.Millisecond
  3669  
  3670  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3671  		time.Sleep(timeout * 2)
  3672  	}, func(h2s *Server) {
  3673  		h2s.IdleTimeout = timeout
  3674  	})
  3675  	defer st.Close()
  3676  
  3677  	st.greet()
  3678  
  3679  	// Send a request which takes twice the timeout. Verifies the
  3680  	// idle timeout doesn't fire while we're in a request:
  3681  	st.bodylessReq1()
  3682  	st.wantHeaders()
  3683  
  3684  	// But the idle timeout should be rearmed after the request
  3685  	// is done:
  3686  	ga := st.wantGoAway()
  3687  	if ga.ErrCode != ErrCodeNo {
  3688  		t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3689  	}
  3690  }
  3691  
  3692  // grpc-go closes the Request.Body currently with a Read.
  3693  // Verify that it doesn't race.
  3694  // See https://github.com/grpc/grpc-go/pull/938
  3695  func TestRequestBodyReadCloseRace(t *testing.T) {
  3696  	for i := 0; i < 100; i++ {
  3697  		body := &requestBody{
  3698  			pipe: &pipe{
  3699  				b: new(bytes.Buffer),
  3700  			},
  3701  		}
  3702  		body.pipe.CloseWithError(io.EOF)
  3703  
  3704  		done := make(chan bool, 1)
  3705  		buf := make([]byte, 10)
  3706  		go func() {
  3707  			time.Sleep(1 * time.Millisecond)
  3708  			body.Close()
  3709  			done <- true
  3710  		}()
  3711  		body.Read(buf)
  3712  		<-done
  3713  	}
  3714  }
  3715  
  3716  func TestIssue20704Race(t *testing.T) {
  3717  	if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
  3718  		t.Skip("skipping in short mode")
  3719  	}
  3720  	const (
  3721  		itemSize  = 1 << 10
  3722  		itemCount = 100
  3723  	)
  3724  
  3725  	st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3726  		for i := 0; i < itemCount; i++ {
  3727  			_, err := w.Write(make([]byte, itemSize))
  3728  			if err != nil {
  3729  				return
  3730  			}
  3731  		}
  3732  	}, optOnlyServer)
  3733  	defer st.Close()
  3734  
  3735  	tr := &Transport{TLSClientConfig: tlsConfigInsecure}
  3736  	defer tr.CloseIdleConnections()
  3737  	cl := &http.Client{Transport: tr}
  3738  
  3739  	for i := 0; i < 1000; i++ {
  3740  		resp, err := cl.Get(st.ts.URL)
  3741  		if err != nil {
  3742  			t.Fatal(err)
  3743  		}
  3744  		// Force a RST stream to the server by closing without
  3745  		// reading the body:
  3746  		resp.Body.Close()
  3747  	}
  3748  }
  3749  
  3750  func TestServer_Rejects_TooSmall(t *testing.T) {
  3751  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3752  		ioutil.ReadAll(r.Body)
  3753  		return nil
  3754  	}, func(st *serverTester) {
  3755  		st.writeHeaders(HeadersFrameParam{
  3756  			StreamID: 1, // clients send odd numbers
  3757  			BlockFragment: st.encodeHeader(
  3758  				":method", "POST",
  3759  				"content-length", "4",
  3760  			),
  3761  			EndStream:  false, // to say DATA frames are coming
  3762  			EndHeaders: true,
  3763  		})
  3764  		st.writeData(1, true, []byte("12345"))
  3765  
  3766  		st.wantRSTStream(1, ErrCodeProtocol)
  3767  	})
  3768  }
  3769  
  3770  // Tests that a handler setting "Connection: close" results in a GOAWAY being sent,
  3771  // and the connection still completing.
  3772  func TestServerHandlerConnectionClose(t *testing.T) {
  3773  	unblockHandler := make(chan bool, 1)
  3774  	defer close(unblockHandler) // backup; in case of errors
  3775  	testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error {
  3776  		w.Header().Set("Connection", "close")
  3777  		w.Header().Set("Foo", "bar")
  3778  		w.(http.Flusher).Flush()
  3779  		<-unblockHandler
  3780  		return nil
  3781  	}, func(st *serverTester) {
  3782  		st.writeHeaders(HeadersFrameParam{
  3783  			StreamID:      1,
  3784  			BlockFragment: st.encodeHeader(),
  3785  			EndStream:     true,
  3786  			EndHeaders:    true,
  3787  		})
  3788  		var sawGoAway bool
  3789  		var sawRes bool
  3790  		for {
  3791  			f, err := st.readFrame()
  3792  			if err == io.EOF {
  3793  				break
  3794  			}
  3795  			if err != nil {
  3796  				t.Fatal(err)
  3797  			}
  3798  			switch f := f.(type) {
  3799  			case *GoAwayFrame:
  3800  				sawGoAway = true
  3801  				unblockHandler <- true
  3802  				if f.LastStreamID != 1 || f.ErrCode != ErrCodeNo {
  3803  					t.Errorf("unexpected GOAWAY frame: %v", summarizeFrame(f))
  3804  				}
  3805  			case *HeadersFrame:
  3806  				goth := st.decodeHeader(f.HeaderBlockFragment())
  3807  				wanth := [][2]string{
  3808  					{":status", "200"},
  3809  					{"foo", "bar"},
  3810  				}
  3811  				if !reflect.DeepEqual(goth, wanth) {
  3812  					t.Errorf("got headers %v; want %v", goth, wanth)
  3813  				}
  3814  				sawRes = true
  3815  			case *DataFrame:
  3816  				if f.StreamID != 1 || !f.StreamEnded() || len(f.Data()) != 0 {
  3817  					t.Errorf("unexpected DATA frame: %v", summarizeFrame(f))
  3818  				}
  3819  			default:
  3820  				t.Logf("unexpected frame: %v", summarizeFrame(f))
  3821  			}
  3822  		}
  3823  		if !sawGoAway {
  3824  			t.Errorf("didn't see GOAWAY")
  3825  		}
  3826  		if !sawRes {
  3827  			t.Errorf("didn't see response")
  3828  		}
  3829  	})
  3830  }
  3831  
  3832  func TestServer_Headers_HalfCloseRemote(t *testing.T) {
  3833  	var st *serverTester
  3834  	writeData := make(chan bool)
  3835  	writeHeaders := make(chan bool)
  3836  	leaveHandler := make(chan bool)
  3837  	st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3838  		if st.stream(1) == nil {
  3839  			t.Errorf("nil stream 1 in handler")
  3840  		}
  3841  		if got, want := st.streamState(1), stateOpen; got != want {
  3842  			t.Errorf("in handler, state is %v; want %v", got, want)
  3843  		}
  3844  		writeData <- true
  3845  		if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF {
  3846  			t.Errorf("body read = %d, %v; want 0, EOF", n, err)
  3847  		}
  3848  		if got, want := st.streamState(1), stateHalfClosedRemote; got != want {
  3849  			t.Errorf("in handler, state is %v; want %v", got, want)
  3850  		}
  3851  		writeHeaders <- true
  3852  
  3853  		<-leaveHandler
  3854  	})
  3855  	st.greet()
  3856  
  3857  	st.writeHeaders(HeadersFrameParam{
  3858  		StreamID:      1,
  3859  		BlockFragment: st.encodeHeader(),
  3860  		EndStream:     false, // keep it open
  3861  		EndHeaders:    true,
  3862  	})
  3863  	<-writeData
  3864  	st.writeData(1, true, nil)
  3865  
  3866  	<-writeHeaders
  3867  
  3868  	st.writeHeaders(HeadersFrameParam{
  3869  		StreamID:      1,
  3870  		BlockFragment: st.encodeHeader(),
  3871  		EndStream:     false, // keep it open
  3872  		EndHeaders:    true,
  3873  	})
  3874  
  3875  	defer close(leaveHandler)
  3876  
  3877  	st.wantRSTStream(1, ErrCodeStreamClosed)
  3878  }
  3879  
  3880  func TestServerGracefulShutdown(t *testing.T) {
  3881  	var st *serverTester
  3882  	handlerDone := make(chan struct{})
  3883  	st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
  3884  		defer close(handlerDone)
  3885  		go st.ts.Config.Shutdown(context.Background())
  3886  
  3887  		ga := st.wantGoAway()
  3888  		if ga.ErrCode != ErrCodeNo {
  3889  			t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode)
  3890  		}
  3891  		if ga.LastStreamID != 1 {
  3892  			t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID)
  3893  		}
  3894  
  3895  		w.Header().Set("x-foo", "bar")
  3896  	})
  3897  	defer st.Close()
  3898  
  3899  	st.greet()
  3900  	st.bodylessReq1()
  3901  
  3902  	select {
  3903  	case <-handlerDone:
  3904  	case <-time.After(5 * time.Second):
  3905  		t.Fatalf("server did not shutdown?")
  3906  	}
  3907  	hf := st.wantHeaders()
  3908  	goth := st.decodeHeader(hf.HeaderBlockFragment())
  3909  	wanth := [][2]string{
  3910  		{":status", "200"},
  3911  		{"x-foo", "bar"},
  3912  		{"content-length", "0"},
  3913  	}
  3914  	if !reflect.DeepEqual(goth, wanth) {
  3915  		t.Errorf("Got headers %v; want %v", goth, wanth)
  3916  	}
  3917  
  3918  	n, err := st.cc.Read([]byte{0})
  3919  	if n != 0 || err == nil {
  3920  		t.Errorf("Read = %v, %v; want 0, non-nil", n, err)
  3921  	}
  3922  }