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.

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