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