github.com/MagHErmit/tendermint@v0.282.1/rpc/jsonrpc/server/http_server.go (about)

     1  // Commons for HTTP handling
     2  package server
     3  
     4  import (
     5  	"bufio"
     6  	"encoding/json"
     7  	"errors"
     8  	"fmt"
     9  	"net"
    10  	"net/http"
    11  	"os"
    12  	"runtime/debug"
    13  	"strings"
    14  	"time"
    15  
    16  	"golang.org/x/net/netutil"
    17  
    18  	"github.com/MagHErmit/tendermint/libs/log"
    19  	types "github.com/MagHErmit/tendermint/rpc/jsonrpc/types"
    20  )
    21  
    22  // Config is a RPC server configuration.
    23  type Config struct {
    24  	// see netutil.LimitListener
    25  	MaxOpenConnections int
    26  	// mirrors http.Server#ReadTimeout
    27  	ReadTimeout time.Duration
    28  	// mirrors http.Server#WriteTimeout
    29  	WriteTimeout time.Duration
    30  	// MaxBodyBytes controls the maximum number of bytes the
    31  	// server will read parsing the request body.
    32  	MaxBodyBytes int64
    33  	// mirrors http.Server#MaxHeaderBytes
    34  	MaxHeaderBytes int
    35  }
    36  
    37  // DefaultConfig returns a default configuration.
    38  func DefaultConfig() *Config {
    39  	return &Config{
    40  		MaxOpenConnections: 0, // unlimited
    41  		ReadTimeout:        10 * time.Second,
    42  		WriteTimeout:       10 * time.Second,
    43  		MaxBodyBytes:       int64(1000000), // 1MB
    44  		MaxHeaderBytes:     1 << 20,        // same as the net/http default
    45  	}
    46  }
    47  
    48  // Serve creates a http.Server and calls Serve with the given listener. It
    49  // wraps handler with RecoverAndLogHandler and a handler, which limits the max
    50  // body size to config.MaxBodyBytes.
    51  //
    52  // NOTE: This function blocks - you may want to call it in a go-routine.
    53  func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
    54  	logger.Info("serve", "msg", log.NewLazySprintf("Starting RPC HTTP server on %s", listener.Addr()))
    55  	s := &http.Server{
    56  		Handler:           RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger),
    57  		ReadTimeout:       config.ReadTimeout,
    58  		ReadHeaderTimeout: config.ReadTimeout,
    59  		WriteTimeout:      config.WriteTimeout,
    60  		MaxHeaderBytes:    config.MaxHeaderBytes,
    61  	}
    62  	err := s.Serve(listener)
    63  	logger.Info("RPC HTTP server stopped", "err", err)
    64  	return err
    65  }
    66  
    67  // Serve creates a http.Server and calls ServeTLS with the given listener,
    68  // certFile and keyFile. It wraps handler with RecoverAndLogHandler and a
    69  // handler, which limits the max body size to config.MaxBodyBytes.
    70  //
    71  // NOTE: This function blocks - you may want to call it in a go-routine.
    72  func ServeTLS(
    73  	listener net.Listener,
    74  	handler http.Handler,
    75  	certFile, keyFile string,
    76  	logger log.Logger,
    77  	config *Config,
    78  ) error {
    79  	logger.Info("serve tls", "msg", log.NewLazySprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)",
    80  		listener.Addr(), certFile, keyFile))
    81  	s := &http.Server{
    82  		Handler:           RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger),
    83  		ReadTimeout:       config.ReadTimeout,
    84  		ReadHeaderTimeout: config.ReadTimeout,
    85  		WriteTimeout:      config.WriteTimeout,
    86  		MaxHeaderBytes:    config.MaxHeaderBytes,
    87  	}
    88  	err := s.ServeTLS(listener, certFile, keyFile)
    89  
    90  	logger.Error("RPC HTTPS server stopped", "err", err)
    91  	return err
    92  }
    93  
    94  // WriteRPCResponseHTTPError marshals res as JSON (with indent) and writes it
    95  // to w.
    96  //
    97  // source: https://www.jsonrpc.org/historical/json-rpc-over-http.html
    98  func WriteRPCResponseHTTPError(
    99  	w http.ResponseWriter,
   100  	httpCode int,
   101  	res types.RPCResponse,
   102  ) error {
   103  	if res.Error == nil {
   104  		panic("tried to write http error response without RPC error")
   105  	}
   106  
   107  	jsonBytes, err := json.MarshalIndent(res, "", "  ")
   108  	if err != nil {
   109  		return fmt.Errorf("json marshal: %w", err)
   110  	}
   111  
   112  	w.Header().Set("Content-Type", "application/json")
   113  	w.WriteHeader(httpCode)
   114  	_, err = w.Write(jsonBytes)
   115  	return err
   116  }
   117  
   118  // WriteRPCResponseHTTP marshals res as JSON (with indent) and writes it to w.
   119  func WriteRPCResponseHTTP(w http.ResponseWriter, res ...types.RPCResponse) error {
   120  	var v interface{}
   121  	if len(res) == 1 {
   122  		v = res[0]
   123  	} else {
   124  		v = res
   125  	}
   126  
   127  	jsonBytes, err := json.MarshalIndent(v, "", "  ")
   128  	if err != nil {
   129  		return fmt.Errorf("json marshal: %w", err)
   130  	}
   131  	w.Header().Set("Content-Type", "application/json")
   132  	w.WriteHeader(200)
   133  	_, err = w.Write(jsonBytes)
   134  	return err
   135  }
   136  
   137  //-----------------------------------------------------------------------------
   138  
   139  // RecoverAndLogHandler wraps an HTTP handler, adding error logging.
   140  // If the inner function panics, the outer function recovers, logs, sends an
   141  // HTTP 500 error response.
   142  func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
   143  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   144  		// Wrap the ResponseWriter to remember the status
   145  		rww := &responseWriterWrapper{-1, w}
   146  		begin := time.Now()
   147  
   148  		rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
   149  
   150  		defer func() {
   151  			// Handle any panics in the panic handler below. Does not use the logger, since we want
   152  			// to avoid any further panics. However, we try to return a 500, since it otherwise
   153  			// defaults to 200 and there is no other way to terminate the connection. If that
   154  			// should panic for whatever reason then the Go HTTP server will handle it and
   155  			// terminate the connection - panicing is the de-facto and only way to get the Go HTTP
   156  			// server to terminate the request and close the connection/stream:
   157  			// https://github.com/golang/go/issues/17790#issuecomment-258481416
   158  			if e := recover(); e != nil {
   159  				fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack()))
   160  				w.WriteHeader(500)
   161  			}
   162  		}()
   163  
   164  		defer func() {
   165  			// Send a 500 error if a panic happens during a handler.
   166  			// Without this, Chrome & Firefox were retrying aborted ajax requests,
   167  			// at least to my localhost.
   168  			if e := recover(); e != nil {
   169  
   170  				// If RPCResponse
   171  				if res, ok := e.(types.RPCResponse); ok {
   172  					if wErr := WriteRPCResponseHTTP(rww, res); wErr != nil {
   173  						logger.Error("failed to write response", "res", res, "err", wErr)
   174  					}
   175  				} else {
   176  					// Panics can contain anything, attempt to normalize it as an error.
   177  					var err error
   178  					switch e := e.(type) {
   179  					case error:
   180  						err = e
   181  					case string:
   182  						err = errors.New(e)
   183  					case fmt.Stringer:
   184  						err = errors.New(e.String())
   185  					default:
   186  					}
   187  
   188  					logger.Error("panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack()))
   189  
   190  					res := types.RPCInternalError(types.JSONRPCIntID(-1), err)
   191  					if wErr := WriteRPCResponseHTTPError(rww, http.StatusInternalServerError, res); wErr != nil {
   192  						logger.Error("failed to write response", "res", res, "err", wErr)
   193  					}
   194  				}
   195  			}
   196  
   197  			// Finally, log.
   198  			durationMS := time.Since(begin).Nanoseconds() / 1000000
   199  			if rww.Status == -1 {
   200  				rww.Status = 200
   201  			}
   202  			logger.Debug("served RPC HTTP response",
   203  				"method", r.Method,
   204  				"url", r.URL,
   205  				"status", rww.Status,
   206  				"duration", durationMS,
   207  				"remoteAddr", r.RemoteAddr,
   208  			)
   209  		}()
   210  
   211  		handler.ServeHTTP(rww, r)
   212  	})
   213  }
   214  
   215  // Remember the status for logging
   216  type responseWriterWrapper struct {
   217  	Status int
   218  	http.ResponseWriter
   219  }
   220  
   221  func (w *responseWriterWrapper) WriteHeader(status int) {
   222  	w.Status = status
   223  	w.ResponseWriter.WriteHeader(status)
   224  }
   225  
   226  // implements http.Hijacker
   227  func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
   228  	return w.ResponseWriter.(http.Hijacker).Hijack()
   229  }
   230  
   231  type maxBytesHandler struct {
   232  	h http.Handler
   233  	n int64
   234  }
   235  
   236  func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   237  	r.Body = http.MaxBytesReader(w, r.Body, h.n)
   238  	h.h.ServeHTTP(w, r)
   239  }
   240  
   241  // Listen starts a new net.Listener on the given address.
   242  // It returns an error if the address is invalid or the call to Listen() fails.
   243  func Listen(addr string, config *Config) (listener net.Listener, err error) {
   244  	parts := strings.SplitN(addr, "://", 2)
   245  	if len(parts) != 2 {
   246  		return nil, fmt.Errorf(
   247  			"invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
   248  			addr,
   249  		)
   250  	}
   251  	proto, addr := parts[0], parts[1]
   252  	listener, err = net.Listen(proto, addr)
   253  	if err != nil {
   254  		return nil, fmt.Errorf("failed to listen on %v: %v", addr, err)
   255  	}
   256  	if config.MaxOpenConnections > 0 {
   257  		listener = netutil.LimitListener(listener, config.MaxOpenConnections)
   258  	}
   259  
   260  	return listener, nil
   261  }