github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmhttp/httptest/server.go (about)

     1  // Copyright 2011 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  // Implementation of Server
     6  
     7  package httptest
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"log"
    13  	"net"
    14  	"os"
    15  	"strings"
    16  	"sync"
    17  	"time"
    18  
    19  	http "github.com/hxx258456/ccgo/gmhttp"
    20  	"github.com/hxx258456/ccgo/gmhttp/internal/testcert"
    21  	tls "github.com/hxx258456/ccgo/gmtls"
    22  	"github.com/hxx258456/ccgo/x509"
    23  )
    24  
    25  // A Server is an HTTP server listening on a system-chosen port on the
    26  // local loopback interface, for use in end-to-end HTTP tests.
    27  type Server struct {
    28  	URL      string // base URL of form http://ipaddr:port with no trailing slash
    29  	Listener net.Listener
    30  
    31  	// EnableHTTP2 controls whether HTTP/2 is enabled
    32  	// on the server. It must be set between calling
    33  	// NewUnstartedServer and calling Server.StartTLS.
    34  	EnableHTTP2 bool
    35  
    36  	// TLS is the optional TLS configuration, populated with a new config
    37  	// after TLS is started. If set on an unstarted server before StartTLS
    38  	// is called, existing fields are copied into the new config.
    39  	TLS *tls.Config
    40  
    41  	// Config may be changed after calling NewUnstartedServer and
    42  	// before Start or StartTLS.
    43  	Config *http.Server
    44  
    45  	// certificate is a parsed version of the TLS config certificate, if present.
    46  	certificate *x509.Certificate
    47  
    48  	// wg counts the number of outstanding HTTP requests on this server.
    49  	// Close blocks until all requests are finished.
    50  	wg sync.WaitGroup
    51  
    52  	mu     sync.Mutex // guards closed and conns
    53  	closed bool
    54  	conns  map[net.Conn]http.ConnState // except terminal states
    55  
    56  	// client is configured for use with the server.
    57  	// Its transport is automatically closed when Close is called.
    58  	client *http.Client
    59  }
    60  
    61  func newLocalListener() net.Listener {
    62  	if serveFlag != "" {
    63  		l, err := net.Listen("tcp", serveFlag)
    64  		if err != nil {
    65  			panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err))
    66  		}
    67  		return l
    68  	}
    69  	l, err := net.Listen("tcp", "127.0.0.1:0")
    70  	if err != nil {
    71  		if l, err = net.Listen("tcp6", "[::1]:0"); err != nil {
    72  			panic(fmt.Sprintf("httptest: failed to listen on a port: %v", err))
    73  		}
    74  	}
    75  	return l
    76  }
    77  
    78  // When debugging a particular http server-based test,
    79  // this flag lets you run
    80  //	go test -run=BrokenTest -httptest.serve=127.0.0.1:8000
    81  // to start the broken server so you can interact with it manually.
    82  // We only register this flag if it looks like the caller knows about it
    83  // and is trying to use it as we don't want to pollute flags and this
    84  // isn't really part of our API. Don't depend on this.
    85  var serveFlag string
    86  
    87  func init() {
    88  	if strSliceContainsPrefix(os.Args, "-httptest.serve=") || strSliceContainsPrefix(os.Args, "--httptest.serve=") {
    89  		flag.StringVar(&serveFlag, "httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks.")
    90  	}
    91  }
    92  
    93  func strSliceContainsPrefix(v []string, pre string) bool {
    94  	for _, s := range v {
    95  		if strings.HasPrefix(s, pre) {
    96  			return true
    97  		}
    98  	}
    99  	return false
   100  }
   101  
   102  // NewServer starts and returns a new Server.
   103  // The caller should call Close when finished, to shut it down.
   104  func NewServer(handler http.Handler) *Server {
   105  	ts := NewUnstartedServer(handler)
   106  	ts.Start()
   107  	return ts
   108  }
   109  
   110  // NewUnstartedServer returns a new Server but doesn't start it.
   111  //
   112  // After changing its configuration, the caller should call Start or
   113  // StartTLS.
   114  //
   115  // The caller should call Close when finished, to shut it down.
   116  func NewUnstartedServer(handler http.Handler) *Server {
   117  	return &Server{
   118  		Listener: newLocalListener(),
   119  		Config:   &http.Server{Handler: handler},
   120  	}
   121  }
   122  
   123  // Start starts a server from NewUnstartedServer.
   124  func (s *Server) Start() {
   125  	if s.URL != "" {
   126  		panic("Server already started")
   127  	}
   128  	if s.client == nil {
   129  		s.client = &http.Client{Transport: &http.Transport{}}
   130  	}
   131  	s.URL = "http://" + s.Listener.Addr().String()
   132  	s.wrap()
   133  	s.goServe()
   134  	if serveFlag != "" {
   135  		fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL)
   136  		select {}
   137  	}
   138  }
   139  
   140  // StartTLS starts TLS on a server from NewUnstartedServer.
   141  func (s *Server) StartTLS() {
   142  	if s.URL != "" {
   143  		panic("Server already started")
   144  	}
   145  	if s.client == nil {
   146  		s.client = &http.Client{Transport: &http.Transport{}}
   147  	}
   148  	cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey)
   149  	if err != nil {
   150  		panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
   151  	}
   152  
   153  	existingConfig := s.TLS
   154  	if existingConfig != nil {
   155  		s.TLS = existingConfig.Clone()
   156  	} else {
   157  		s.TLS = new(tls.Config)
   158  	}
   159  	if s.TLS.NextProtos == nil {
   160  		nextProtos := []string{"http/1.1"}
   161  		if s.EnableHTTP2 {
   162  			nextProtos = []string{"h2"}
   163  		}
   164  		s.TLS.NextProtos = nextProtos
   165  	}
   166  	if len(s.TLS.Certificates) == 0 {
   167  		s.TLS.Certificates = []tls.Certificate{cert}
   168  	}
   169  	s.certificate, err = x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0])
   170  	if err != nil {
   171  		panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
   172  	}
   173  	certpool := x509.NewCertPool()
   174  	certpool.AddCert(s.certificate)
   175  	s.client.Transport = &http.Transport{
   176  		TLSClientConfig: &tls.Config{
   177  			RootCAs: certpool,
   178  		},
   179  		ForceAttemptHTTP2: s.EnableHTTP2,
   180  	}
   181  	s.Listener = tls.NewListener(s.Listener, s.TLS)
   182  	s.URL = "https://" + s.Listener.Addr().String()
   183  	s.wrap()
   184  	s.goServe()
   185  }
   186  
   187  // NewTLSServer starts and returns a new Server using TLS.
   188  // The caller should call Close when finished, to shut it down.
   189  func NewTLSServer(handler http.Handler) *Server {
   190  	ts := NewUnstartedServer(handler)
   191  	ts.StartTLS()
   192  	return ts
   193  }
   194  
   195  type closeIdleTransport interface {
   196  	CloseIdleConnections()
   197  }
   198  
   199  // Close shuts down the server and blocks until all outstanding
   200  // requests on this server have completed.
   201  func (s *Server) Close() {
   202  	s.mu.Lock()
   203  	if !s.closed {
   204  		s.closed = true
   205  		s.Listener.Close()
   206  		s.Config.SetKeepAlivesEnabled(false)
   207  		for c, st := range s.conns {
   208  			// Force-close any idle connections (those between
   209  			// requests) and new connections (those which connected
   210  			// but never sent a request). StateNew connections are
   211  			// super rare and have only been seen (in
   212  			// previously-flaky tests) in the case of
   213  			// socket-late-binding races from the http Client
   214  			// dialing this server and then getting an idle
   215  			// connection before the dial completed. There is thus
   216  			// a connected connection in StateNew with no
   217  			// associated Request. We only close StateIdle and
   218  			// StateNew because they're not doing anything. It's
   219  			// possible StateNew is about to do something in a few
   220  			// milliseconds, but a previous CL to check again in a
   221  			// few milliseconds wasn't liked (early versions of
   222  			// https://golang.org/cl/15151) so now we just
   223  			// forcefully close StateNew. The docs for Server.Close say
   224  			// we wait for "outstanding requests", so we don't close things
   225  			// in StateActive.
   226  			if st == http.StateIdle || st == http.StateNew {
   227  				s.closeConn(c)
   228  			}
   229  		}
   230  		// If this server doesn't shut down in 5 seconds, tell the user why.
   231  		t := time.AfterFunc(5*time.Second, s.logCloseHangDebugInfo)
   232  		defer t.Stop()
   233  	}
   234  	s.mu.Unlock()
   235  
   236  	// Not part of httptest.Server's correctness, but assume most
   237  	// users of httptest.Server will be using the standard
   238  	// transport, so help them out and close any idle connections for them.
   239  	if t, ok := http.DefaultTransport.(closeIdleTransport); ok {
   240  		t.CloseIdleConnections()
   241  	}
   242  
   243  	// Also close the client idle connections.
   244  	if s.client != nil {
   245  		if t, ok := s.client.Transport.(closeIdleTransport); ok {
   246  			t.CloseIdleConnections()
   247  		}
   248  	}
   249  
   250  	s.wg.Wait()
   251  }
   252  
   253  func (s *Server) logCloseHangDebugInfo() {
   254  	s.mu.Lock()
   255  	defer s.mu.Unlock()
   256  	var buf strings.Builder
   257  	buf.WriteString("httptest.Server blocked in Close after 5 seconds, waiting for connections:\n")
   258  	for c, st := range s.conns {
   259  		fmt.Fprintf(&buf, "  %T %p %v in state %v\n", c, c, c.RemoteAddr(), st)
   260  	}
   261  	log.Print(buf.String())
   262  }
   263  
   264  // CloseClientConnections closes any open HTTP connections to the test Server.
   265  func (s *Server) CloseClientConnections() {
   266  	s.mu.Lock()
   267  	nconn := len(s.conns)
   268  	ch := make(chan struct{}, nconn)
   269  	for c := range s.conns {
   270  		go s.closeConnChan(c, ch)
   271  	}
   272  	s.mu.Unlock()
   273  
   274  	// Wait for outstanding closes to finish.
   275  	//
   276  	// Out of paranoia for making a late change in Go 1.6, we
   277  	// bound how long this can wait, since golang.org/issue/14291
   278  	// isn't fully understood yet. At least this should only be used
   279  	// in tests.
   280  	timer := time.NewTimer(5 * time.Second)
   281  	defer timer.Stop()
   282  	for i := 0; i < nconn; i++ {
   283  		select {
   284  		case <-ch:
   285  		case <-timer.C:
   286  			// Too slow. Give up.
   287  			return
   288  		}
   289  	}
   290  }
   291  
   292  // Certificate returns the certificate used by the server, or nil if
   293  // the server doesn't use TLS.
   294  func (s *Server) Certificate() *x509.Certificate {
   295  	return s.certificate
   296  }
   297  
   298  // Client returns an HTTP client configured for making requests to the server.
   299  // It is configured to trust the server's TLS test certificate and will
   300  // close its idle connections on Server.Close.
   301  func (s *Server) Client() *http.Client {
   302  	return s.client
   303  }
   304  
   305  func (s *Server) goServe() {
   306  	s.wg.Add(1)
   307  	go func() {
   308  		defer s.wg.Done()
   309  		s.Config.Serve(s.Listener)
   310  	}()
   311  }
   312  
   313  // wrap installs the connection state-tracking hook to know which
   314  // connections are idle.
   315  func (s *Server) wrap() {
   316  	oldHook := s.Config.ConnState
   317  	s.Config.ConnState = func(c net.Conn, cs http.ConnState) {
   318  		s.mu.Lock()
   319  		defer s.mu.Unlock()
   320  
   321  		// Keep Close from returning until the user's ConnState hook
   322  		// (if any) finishes. Without this, the call to forgetConn
   323  		// below might send the count to 0 before we run the hook.
   324  		s.wg.Add(1)
   325  		defer s.wg.Done()
   326  
   327  		switch cs {
   328  		case http.StateNew:
   329  			s.wg.Add(1)
   330  			if _, exists := s.conns[c]; exists {
   331  				panic("invalid state transition")
   332  			}
   333  			if s.conns == nil {
   334  				s.conns = make(map[net.Conn]http.ConnState)
   335  			}
   336  			s.conns[c] = cs
   337  			if s.closed {
   338  				// Probably just a socket-late-binding dial from
   339  				// the default transport that lost the race (and
   340  				// thus this connection is now idle and will
   341  				// never be used).
   342  				s.closeConn(c)
   343  			}
   344  		case http.StateActive:
   345  			if oldState, ok := s.conns[c]; ok {
   346  				if oldState != http.StateNew && oldState != http.StateIdle {
   347  					panic("invalid state transition")
   348  				}
   349  				s.conns[c] = cs
   350  			}
   351  		case http.StateIdle:
   352  			if oldState, ok := s.conns[c]; ok {
   353  				if oldState != http.StateActive {
   354  					panic("invalid state transition")
   355  				}
   356  				s.conns[c] = cs
   357  			}
   358  			if s.closed {
   359  				s.closeConn(c)
   360  			}
   361  		case http.StateHijacked, http.StateClosed:
   362  			s.forgetConn(c)
   363  		}
   364  		if oldHook != nil {
   365  			oldHook(c, cs)
   366  		}
   367  	}
   368  }
   369  
   370  // closeConn closes c.
   371  // s.mu must be held.
   372  func (s *Server) closeConn(c net.Conn) { s.closeConnChan(c, nil) }
   373  
   374  // closeConnChan is like closeConn, but takes an optional channel to receive a value
   375  // when the goroutine closing c is done.
   376  func (s *Server) closeConnChan(c net.Conn, done chan<- struct{}) {
   377  	c.Close()
   378  	if done != nil {
   379  		done <- struct{}{}
   380  	}
   381  }
   382  
   383  // forgetConn removes c from the set of tracked conns and decrements it from the
   384  // waitgroup, unless it was previously removed.
   385  // s.mu must be held.
   386  func (s *Server) forgetConn(c net.Conn) {
   387  	if _, ok := s.conns[c]; ok {
   388  		delete(s.conns, c)
   389  		s.wg.Done()
   390  	}
   391  }