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.

220 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. go func() {
  95. err := http.ServeTLS(
  96. listener,
  97. RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
  98. certFile,
  99. keyFile,
  100. )
  101. logger.Error("RPC HTTPS server stopped", "err", err)
  102. }()
  103. return listener, nil
  104. }
  105. func WriteRPCResponseHTTPError(
  106. w http.ResponseWriter,
  107. httpCode int,
  108. res types.RPCResponse,
  109. ) {
  110. jsonBytes, err := json.MarshalIndent(res, "", " ")
  111. if err != nil {
  112. panic(err)
  113. }
  114. w.Header().Set("Content-Type", "application/json")
  115. w.WriteHeader(httpCode)
  116. w.Write(jsonBytes) // nolint: errcheck, gas
  117. }
  118. func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) {
  119. jsonBytes, err := json.MarshalIndent(res, "", " ")
  120. if err != nil {
  121. panic(err)
  122. }
  123. w.Header().Set("Content-Type", "application/json")
  124. w.WriteHeader(200)
  125. w.Write(jsonBytes) // nolint: errcheck, gas
  126. }
  127. //-----------------------------------------------------------------------------
  128. // Wraps an HTTP handler, adding error logging.
  129. // If the inner function panics, the outer function recovers, logs, sends an
  130. // HTTP 500 error response.
  131. func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
  132. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  133. // Wrap the ResponseWriter to remember the status
  134. rww := &ResponseWriterWrapper{-1, w}
  135. begin := time.Now()
  136. // Common headers
  137. origin := r.Header.Get("Origin")
  138. rww.Header().Set("Access-Control-Allow-Origin", origin)
  139. rww.Header().Set("Access-Control-Allow-Credentials", "true")
  140. rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time")
  141. rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
  142. defer func() {
  143. // Send a 500 error if a panic happens during a handler.
  144. // Without this, Chrome & Firefox were retrying aborted ajax requests,
  145. // at least to my localhost.
  146. if e := recover(); e != nil {
  147. // If RPCResponse
  148. if res, ok := e.(types.RPCResponse); ok {
  149. WriteRPCResponseHTTP(rww, res)
  150. } else {
  151. // For the rest,
  152. logger.Error(
  153. "Panic in RPC HTTP handler", "err", e, "stack",
  154. string(debug.Stack()),
  155. )
  156. rww.WriteHeader(http.StatusInternalServerError)
  157. WriteRPCResponseHTTP(rww, types.RPCInternalError("", e.(error)))
  158. }
  159. }
  160. // Finally, log.
  161. durationMS := time.Since(begin).Nanoseconds() / 1000000
  162. if rww.Status == -1 {
  163. rww.Status = 200
  164. }
  165. logger.Info("Served RPC HTTP response",
  166. "method", r.Method, "url", r.URL,
  167. "status", rww.Status, "duration", durationMS,
  168. "remoteAddr", r.RemoteAddr,
  169. )
  170. }()
  171. handler.ServeHTTP(rww, r)
  172. })
  173. }
  174. // Remember the status for logging
  175. type ResponseWriterWrapper struct {
  176. Status int
  177. http.ResponseWriter
  178. }
  179. func (w *ResponseWriterWrapper) WriteHeader(status int) {
  180. w.Status = status
  181. w.ResponseWriter.WriteHeader(status)
  182. }
  183. // implements http.Hijacker
  184. func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  185. return w.ResponseWriter.(http.Hijacker).Hijack()
  186. }
  187. type maxBytesHandler struct {
  188. h http.Handler
  189. n int64
  190. }
  191. func (h maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  192. r.Body = http.MaxBytesReader(w, r.Body, h.n)
  193. h.h.ServeHTTP(w, r)
  194. }