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.

137 lines
4.0 KiB

8 years ago
8 years ago
8 years ago
8 years ago
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. types "github.com/tendermint/tendermint/rpc/lib/types"
  14. "github.com/tendermint/tmlibs/log"
  15. )
  16. func StartHTTPServer(listenAddr string, handler http.Handler, logger log.Logger) (listener net.Listener, err error) {
  17. // listenAddr should be fully formed including tcp:// or unix:// prefix
  18. var proto, addr string
  19. parts := strings.SplitN(listenAddr, "://", 2)
  20. if len(parts) != 2 {
  21. logger.Error("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix")
  22. // we used to allow addrs without tcp/unix prefix by checking for a colon
  23. // TODO: Deprecate
  24. proto = types.SocketType(listenAddr)
  25. addr = listenAddr
  26. // return nil, errors.Errorf("Invalid listener address %s", lisenAddr)
  27. } else {
  28. proto, addr = parts[0], parts[1]
  29. }
  30. logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr))
  31. listener, err = net.Listen(proto, addr)
  32. if err != nil {
  33. return nil, errors.Errorf("Failed to listen to %v: %v", listenAddr, err)
  34. }
  35. go func() {
  36. res := http.Serve(
  37. listener,
  38. RecoverAndLogHandler(handler, logger),
  39. )
  40. logger.Error("RPC HTTP server stopped", "result", res)
  41. }()
  42. return listener, nil
  43. }
  44. func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RPCResponse) {
  45. jsonBytes, err := json.MarshalIndent(res, "", " ")
  46. if err != nil {
  47. panic(err)
  48. }
  49. w.Header().Set("Content-Type", "application/json")
  50. w.WriteHeader(httpCode)
  51. w.Write(jsonBytes) // nolint: errcheck, gas
  52. }
  53. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  54. jsonBytes, err := json.MarshalIndent(res, "", " ")
  55. if err != nil {
  56. panic(err)
  57. }
  58. w.Header().Set("Content-Type", "application/json")
  59. w.WriteHeader(200)
  60. w.Write(jsonBytes) // nolint: errcheck, gas
  61. }
  62. //-----------------------------------------------------------------------------
  63. // Wraps an HTTP handler, adding error logging.
  64. // If the inner function panics, the outer function recovers, logs, sends an
  65. // HTTP 500 error response.
  66. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  67. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  68. // Wrap the ResponseWriter to remember the status
  69. rww := &ResponseWriterWrapper{-1, w}
  70. begin := time.Now()
  71. // Common headers
  72. origin := r.Header.Get("Origin")
  73. rww.Header().Set("Access-Control-Allow-Origin", origin)
  74. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  75. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  76. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  77. defer func() {
  78. // Send a 500 error if a panic happens during a handler.
  79. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  80. // at least to my localhost.
  81. if e := recover(); e != nil {
  82. // If RPCResponse
  83. if res, ok := e.(types.RPCResponse); ok {
  84. WriteRPCResponseHTTP(rww, res)
  85. } else {
  86. // For the rest,
  87. logger.Error("Panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack()))
  88. rww.WriteHeader(http.StatusInternalServerError)
  89. WriteRPCResponseHTTP(rww, types.RPCInternalError("", e.(error)))
  90. }
  91. }
  92. // Finally, log.
  93. durationMS := time.Since(begin).Nanoseconds() / 1000000
  94. if rww.Status == -1 {
  95. rww.Status = 200
  96. }
  97. logger.Info("Served RPC HTTP response",
  98. "method", r.Method, "url", r.URL,
  99. "status", rww.Status, "duration", durationMS,
  100. "remoteAddr", r.RemoteAddr,
  101. )
  102. }()
  103. handler.ServeHTTP(rww, r)
  104. })
  105. }
  106. // Remember the status for logging
  107. type ResponseWriterWrapper struct {
  108. Status int
  109. http.ResponseWriter
  110. }
  111. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  112. w.Status = status
  113. w.ResponseWriter.WriteHeader(status)
  114. }
  115. // implements http.Hijacker
  116. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  117. return w.ResponseWriter.(http.Hijacker).Hijack()
  118. }