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.

204 lines
5.2 KiB

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