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.

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