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.

143 lines
4.0 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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. _, err = w.Write(jsonBytes)
  52. if err != nil {
  53. panic(err)
  54. }
  55. }
  56. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  57. jsonBytes, err := json.MarshalIndent(res, "", " ")
  58. if err != nil {
  59. panic(err)
  60. }
  61. w.Header().Set("Content-Type", "application/json")
  62. w.WriteHeader(200)
  63. _, err = w.Write(jsonBytes)
  64. if err != nil {
  65. panic(err)
  66. }
  67. }
  68. //-----------------------------------------------------------------------------
  69. // Wraps an HTTP handler, adding error logging.
  70. // If the inner function panics, the outer function recovers, logs, sends an
  71. // HTTP 500 error response.
  72. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  73. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. // Wrap the ResponseWriter to remember the status
  75. rww := &ResponseWriterWrapper{-1, w}
  76. begin := time.Now()
  77. // Common headers
  78. origin := r.Header.Get("Origin")
  79. rww.Header().Set("Access-Control-Allow-Origin", origin)
  80. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  81. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  82. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  83. defer func() {
  84. // Send a 500 error if a panic happens during a handler.
  85. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  86. // at least to my localhost.
  87. if e := recover(); e != nil {
  88. // If RPCResponse
  89. if res, ok := e.(types.RPCResponse); ok {
  90. WriteRPCResponseHTTP(rww, res)
  91. } else {
  92. // For the rest,
  93. logger.Error("Panic in RPC HTTP handler", "err", e, "stack", string(debug.Stack()))
  94. rww.WriteHeader(http.StatusInternalServerError)
  95. WriteRPCResponseHTTP(rww, types.RPCInternalError("", e.(error)))
  96. }
  97. }
  98. // Finally, log.
  99. durationMS := time.Since(begin).Nanoseconds() / 1000000
  100. if rww.Status == -1 {
  101. rww.Status = 200
  102. }
  103. logger.Info("Served RPC HTTP response",
  104. "method", r.Method, "url", r.URL,
  105. "status", rww.Status, "duration", durationMS,
  106. "remoteAddr", r.RemoteAddr,
  107. )
  108. }()
  109. handler.ServeHTTP(rww, r)
  110. })
  111. }
  112. // Remember the status for logging
  113. type ResponseWriterWrapper struct {
  114. Status int
  115. http.ResponseWriter
  116. }
  117. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  118. w.Status = status
  119. w.ResponseWriter.WriteHeader(status)
  120. }
  121. // implements http.Hijacker
  122. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  123. return w.ResponseWriter.(http.Hijacker).Hijack()
  124. }