You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

208 lines
5.8 KiB

7 years ago
7 years ago
8 years ago
8 years ago
  1. // Commons for HTTP handling
  2. package rpcserver
  3. import (
  4. "bufio"
  5. "encoding/json"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "runtime/debug"
  10. "strings"
  11. "time"
  12. "github.com/pkg/errors"
  13. "golang.org/x/net/netutil"
  14. "github.com/tendermint/tendermint/libs/log"
  15. types "github.com/tendermint/tendermint/rpc/lib/types"
  16. )
  17. // Config is a RPC server configuration.
  18. type Config struct {
  19. // see netutil.LimitListener
  20. MaxOpenConnections int
  21. // mirrors http.Server#ReadTimeout
  22. ReadTimeout time.Duration
  23. // mirrors http.Server#WriteTimeout
  24. WriteTimeout time.Duration
  25. }
  26. // DefaultConfig returns a default configuration.
  27. func DefaultConfig() *Config {
  28. return &Config{
  29. MaxOpenConnections: 0, // unlimited
  30. ReadTimeout: 10 * time.Second,
  31. WriteTimeout: 10 * time.Second,
  32. }
  33. }
  34. const (
  35. // maxBodyBytes controls the maximum number of bytes the
  36. // server will read parsing the request body.
  37. maxBodyBytes = int64(1000000) // 1MB
  38. // same as the net/http default
  39. maxHeaderBytes = 1 << 20
  40. )
  41. // StartHTTPServer takes a listener and starts an HTTP server with the given handler.
  42. // It wraps handler with RecoverAndLogHandler.
  43. // NOTE: This function blocks - you may want to call it in a go-routine.
  44. func StartHTTPServer(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
  45. logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr()))
  46. s := &http.Server{
  47. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
  48. ReadTimeout: config.ReadTimeout,
  49. WriteTimeout: config.WriteTimeout,
  50. MaxHeaderBytes: maxHeaderBytes,
  51. }
  52. err := s.Serve(listener)
  53. logger.Info("RPC HTTP server stopped", "err", err)
  54. return err
  55. }
  56. // StartHTTPAndTLSServer takes a listener and starts an HTTPS server with the given handler.
  57. // It wraps handler with RecoverAndLogHandler.
  58. // NOTE: This function blocks - you may want to call it in a go-routine.
  59. func StartHTTPAndTLSServer(
  60. listener net.Listener,
  61. handler http.Handler,
  62. certFile, keyFile string,
  63. logger log.Logger,
  64. config *Config,
  65. ) error {
  66. logger.Info(fmt.Sprintf("Starting RPC HTTPS server on %s (cert: %q, key: %q)",
  67. listener.Addr(), certFile, keyFile))
  68. s := &http.Server{
  69. Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
  70. ReadTimeout: config.ReadTimeout,
  71. WriteTimeout: config.WriteTimeout,
  72. MaxHeaderBytes: maxHeaderBytes,
  73. }
  74. err := s.ServeTLS(listener, certFile, keyFile)
  75. logger.Error("RPC HTTPS server stopped", "err", err)
  76. return err
  77. }
  78. func WriteRPCResponseHTTPError(
  79. w http.ResponseWriter,
  80. httpCode int,
  81. res types.RPCResponse,
  82. ) {
  83. jsonBytes, err := json.MarshalIndent(res, "", " ")
  84. if err != nil {
  85. panic(err)
  86. }
  87. w.Header().Set("Content-Type", "application/json")
  88. w.WriteHeader(httpCode)
  89. w.Write(jsonBytes) // nolint: errcheck, gas
  90. }
  91. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  92. jsonBytes, err := json.MarshalIndent(res, "", " ")
  93. if err != nil {
  94. panic(err)
  95. }
  96. w.Header().Set("Content-Type", "application/json")
  97. w.WriteHeader(200)
  98. w.Write(jsonBytes) // nolint: errcheck, gas
  99. }
  100. //-----------------------------------------------------------------------------
  101. // Wraps an HTTP handler, adding error logging.
  102. // If the inner function panics, the outer function recovers, logs, sends an
  103. // HTTP 500 error response.
  104. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  105. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  106. // Wrap the ResponseWriter to remember the status
  107. rww := &ResponseWriterWrapper{-1, w}
  108. begin := time.Now()
  109. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  110. defer func() {
  111. // Send a 500 error if a panic happens during a handler.
  112. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  113. // at least to my localhost.
  114. if e := recover(); e != nil {
  115. // If RPCResponse
  116. if res, ok := e.(types.RPCResponse); ok {
  117. WriteRPCResponseHTTP(rww, res)
  118. } else {
  119. // For the rest,
  120. logger.Error(
  121. "Panic in RPC HTTP handler", "err", e, "stack",
  122. string(debug.Stack()),
  123. )
  124. WriteRPCResponseHTTPError(rww, http.StatusInternalServerError, types.RPCInternalError(types.JSONRPCStringID(""), e.(error)))
  125. }
  126. }
  127. // Finally, log.
  128. durationMS := time.Since(begin).Nanoseconds() / 1000000
  129. if rww.Status == -1 {
  130. rww.Status = 200
  131. }
  132. logger.Info("Served RPC HTTP response",
  133. "method", r.Method, "url", r.URL,
  134. "status", rww.Status, "duration", durationMS,
  135. "remoteAddr", r.RemoteAddr,
  136. )
  137. }()
  138. handler.ServeHTTP(rww, r)
  139. })
  140. }
  141. // Remember the status for logging
  142. type ResponseWriterWrapper struct {
  143. Status int
  144. http.ResponseWriter
  145. }
  146. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  147. w.Status = status
  148. w.ResponseWriter.WriteHeader(status)
  149. }
  150. // implements http.Hijacker
  151. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  152. return w.ResponseWriter.(http.Hijacker).Hijack()
  153. }
  154. type maxBytesHandler struct {
  155. h http.Handler
  156. n int64
  157. }
  158. func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  159. r.Body = http.MaxBytesReader(w, r.Body, h.n)
  160. h.h.ServeHTTP(w, r)
  161. }
  162. // Listen starts a new net.Listener on the given address.
  163. // It returns an error if the address is invalid or the call to Listen() fails.
  164. func Listen(addr string, config *Config) (listener net.Listener, err error) {
  165. parts := strings.SplitN(addr, "://", 2)
  166. if len(parts) != 2 {
  167. return nil, errors.Errorf(
  168. "Invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)",
  169. addr,
  170. )
  171. }
  172. proto, addr := parts[0], parts[1]
  173. listener, err = net.Listen(proto, addr)
  174. if err != nil {
  175. return nil, errors.Errorf("Failed to listen on %v: %v", addr, err)
  176. }
  177. if config.MaxOpenConnections > 0 {
  178. listener = netutil.LimitListener(listener, config.MaxOpenConnections)
  179. }
  180. return listener, nil
  181. }