rpcstack.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Copyright 2020 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package node
  17. import (
  18. "compress/gzip"
  19. "context"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "net"
  24. "net/http"
  25. "sort"
  26. "strings"
  27. "sync"
  28. "sync/atomic"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/rpc"
  31. "github.com/rs/cors"
  32. )
  33. // httpConfig is the JSON-RPC/HTTP configuration.
  34. type httpConfig struct {
  35. Modules []string
  36. CorsAllowedOrigins []string
  37. Vhosts []string
  38. }
  39. // wsConfig is the JSON-RPC/Websocket configuration
  40. type wsConfig struct {
  41. Origins []string
  42. Modules []string
  43. }
  44. type rpcHandler struct {
  45. http.Handler
  46. server *rpc.Server
  47. }
  48. type httpServer struct {
  49. log log.Logger
  50. timeouts rpc.HTTPTimeouts
  51. mux http.ServeMux // registered handlers go here
  52. mu sync.Mutex
  53. server *http.Server
  54. listener net.Listener // non-nil when server is running
  55. // HTTP RPC handler things.
  56. httpConfig httpConfig
  57. httpHandler atomic.Value // *rpcHandler
  58. // WebSocket handler things.
  59. wsConfig wsConfig
  60. wsHandler atomic.Value // *rpcHandler
  61. // These are set by setListenAddr.
  62. endpoint string
  63. host string
  64. port int
  65. handlerNames map[string]string
  66. }
  67. func newHTTPServer(log log.Logger, timeouts rpc.HTTPTimeouts) *httpServer {
  68. h := &httpServer{log: log, timeouts: timeouts, handlerNames: make(map[string]string)}
  69. h.httpHandler.Store((*rpcHandler)(nil))
  70. h.wsHandler.Store((*rpcHandler)(nil))
  71. return h
  72. }
  73. // setListenAddr configures the listening address of the server.
  74. // The address can only be set while the server isn't running.
  75. func (h *httpServer) setListenAddr(host string, port int) error {
  76. h.mu.Lock()
  77. defer h.mu.Unlock()
  78. if h.listener != nil && (host != h.host || port != h.port) {
  79. return fmt.Errorf("HTTP server already running on %s", h.endpoint)
  80. }
  81. h.host, h.port = host, port
  82. h.endpoint = fmt.Sprintf("%s:%d", host, port)
  83. return nil
  84. }
  85. // listenAddr returns the listening address of the server.
  86. func (h *httpServer) listenAddr() string {
  87. h.mu.Lock()
  88. defer h.mu.Unlock()
  89. if h.listener != nil {
  90. return h.listener.Addr().String()
  91. }
  92. return h.endpoint
  93. }
  94. // start starts the HTTP server if it is enabled and not already running.
  95. func (h *httpServer) start() error {
  96. h.mu.Lock()
  97. defer h.mu.Unlock()
  98. if h.endpoint == "" || h.listener != nil {
  99. return nil // already running or not configured
  100. }
  101. // Initialize the server.
  102. h.server = &http.Server{Handler: h}
  103. if h.timeouts != (rpc.HTTPTimeouts{}) {
  104. CheckTimeouts(&h.timeouts)
  105. h.server.ReadTimeout = h.timeouts.ReadTimeout
  106. h.server.WriteTimeout = h.timeouts.WriteTimeout
  107. h.server.IdleTimeout = h.timeouts.IdleTimeout
  108. }
  109. // Start the server.
  110. listener, err := net.Listen("tcp", h.endpoint)
  111. if err != nil {
  112. // If the server fails to start, we need to clear out the RPC and WS
  113. // configuration so they can be configured another time.
  114. h.disableRPC()
  115. h.disableWS()
  116. return err
  117. }
  118. h.listener = listener
  119. go h.server.Serve(listener)
  120. // if server is websocket only, return after logging
  121. if h.wsAllowed() && !h.rpcAllowed() {
  122. h.log.Info("WebSocket enabled", "url", fmt.Sprintf("ws://%v", listener.Addr()))
  123. return nil
  124. }
  125. // Log http endpoint.
  126. h.log.Info("HTTP server started",
  127. "endpoint", listener.Addr(),
  128. "cors", strings.Join(h.httpConfig.CorsAllowedOrigins, ","),
  129. "vhosts", strings.Join(h.httpConfig.Vhosts, ","),
  130. )
  131. // Log all handlers mounted on server.
  132. var paths []string
  133. for path := range h.handlerNames {
  134. paths = append(paths, path)
  135. }
  136. sort.Strings(paths)
  137. logged := make(map[string]bool, len(paths))
  138. for _, path := range paths {
  139. name := h.handlerNames[path]
  140. if !logged[name] {
  141. log.Info(name+" enabled", "url", "http://"+listener.Addr().String()+path)
  142. logged[name] = true
  143. }
  144. }
  145. return nil
  146. }
  147. func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  148. rpc := h.httpHandler.Load().(*rpcHandler)
  149. if r.RequestURI == "/" {
  150. // Serve JSON-RPC on the root path.
  151. ws := h.wsHandler.Load().(*rpcHandler)
  152. if ws != nil && isWebsocket(r) {
  153. ws.ServeHTTP(w, r)
  154. return
  155. }
  156. if rpc != nil {
  157. rpc.ServeHTTP(w, r)
  158. return
  159. }
  160. } else if rpc != nil {
  161. // Requests to a path below root are handled by the mux,
  162. // which has all the handlers registered via Node.RegisterHandler.
  163. // These are made available when RPC is enabled.
  164. h.mux.ServeHTTP(w, r)
  165. return
  166. }
  167. w.WriteHeader(404)
  168. }
  169. // stop shuts down the HTTP server.
  170. func (h *httpServer) stop() {
  171. h.mu.Lock()
  172. defer h.mu.Unlock()
  173. h.doStop()
  174. }
  175. func (h *httpServer) doStop() {
  176. if h.listener == nil {
  177. return // not running
  178. }
  179. // Shut down the server.
  180. httpHandler := h.httpHandler.Load().(*rpcHandler)
  181. wsHandler := h.httpHandler.Load().(*rpcHandler)
  182. if httpHandler != nil {
  183. h.httpHandler.Store((*rpcHandler)(nil))
  184. httpHandler.server.Stop()
  185. }
  186. if wsHandler != nil {
  187. h.wsHandler.Store((*rpcHandler)(nil))
  188. wsHandler.server.Stop()
  189. }
  190. h.server.Shutdown(context.Background())
  191. h.listener.Close()
  192. h.log.Info("HTTP server stopped", "endpoint", h.listener.Addr())
  193. // Clear out everything to allow re-configuring it later.
  194. h.host, h.port, h.endpoint = "", 0, ""
  195. h.server, h.listener = nil, nil
  196. }
  197. // enableRPC turns on JSON-RPC over HTTP on the server.
  198. func (h *httpServer) enableRPC(apis []rpc.API, config httpConfig) error {
  199. h.mu.Lock()
  200. defer h.mu.Unlock()
  201. if h.rpcAllowed() {
  202. return fmt.Errorf("JSON-RPC over HTTP is already enabled")
  203. }
  204. // Create RPC server and handler.
  205. srv := rpc.NewServer()
  206. if err := RegisterApisFromWhitelist(apis, config.Modules, srv, false); err != nil {
  207. return err
  208. }
  209. h.httpConfig = config
  210. h.httpHandler.Store(&rpcHandler{
  211. Handler: NewHTTPHandlerStack(srv, config.CorsAllowedOrigins, config.Vhosts),
  212. server: srv,
  213. })
  214. return nil
  215. }
  216. // disableRPC stops the HTTP RPC handler. This is internal, the caller must hold h.mu.
  217. func (h *httpServer) disableRPC() bool {
  218. handler := h.httpHandler.Load().(*rpcHandler)
  219. if handler != nil {
  220. h.httpHandler.Store((*rpcHandler)(nil))
  221. handler.server.Stop()
  222. }
  223. return handler != nil
  224. }
  225. // enableWS turns on JSON-RPC over WebSocket on the server.
  226. func (h *httpServer) enableWS(apis []rpc.API, config wsConfig) error {
  227. h.mu.Lock()
  228. defer h.mu.Unlock()
  229. if h.wsAllowed() {
  230. return fmt.Errorf("JSON-RPC over WebSocket is already enabled")
  231. }
  232. // Create RPC server and handler.
  233. srv := rpc.NewServer()
  234. if err := RegisterApisFromWhitelist(apis, config.Modules, srv, false); err != nil {
  235. return err
  236. }
  237. h.wsConfig = config
  238. h.wsHandler.Store(&rpcHandler{
  239. Handler: srv.WebsocketHandler(config.Origins),
  240. server: srv,
  241. })
  242. return nil
  243. }
  244. // stopWS disables JSON-RPC over WebSocket and also stops the server if it only serves WebSocket.
  245. func (h *httpServer) stopWS() {
  246. h.mu.Lock()
  247. defer h.mu.Unlock()
  248. if h.disableWS() {
  249. if !h.rpcAllowed() {
  250. h.doStop()
  251. }
  252. }
  253. }
  254. // disableWS disables the WebSocket handler. This is internal, the caller must hold h.mu.
  255. func (h *httpServer) disableWS() bool {
  256. ws := h.wsHandler.Load().(*rpcHandler)
  257. if ws != nil {
  258. h.wsHandler.Store((*rpcHandler)(nil))
  259. ws.server.Stop()
  260. }
  261. return ws != nil
  262. }
  263. // rpcAllowed returns true when JSON-RPC over HTTP is enabled.
  264. func (h *httpServer) rpcAllowed() bool {
  265. return h.httpHandler.Load().(*rpcHandler) != nil
  266. }
  267. // wsAllowed returns true when JSON-RPC over WebSocket is enabled.
  268. func (h *httpServer) wsAllowed() bool {
  269. return h.wsHandler.Load().(*rpcHandler) != nil
  270. }
  271. // isWebsocket checks the header of an http request for a websocket upgrade request.
  272. func isWebsocket(r *http.Request) bool {
  273. return strings.ToLower(r.Header.Get("Upgrade")) == "websocket" &&
  274. strings.ToLower(r.Header.Get("Connection")) == "upgrade"
  275. }
  276. // NewHTTPHandlerStack returns wrapped http-related handlers
  277. func NewHTTPHandlerStack(srv http.Handler, cors []string, vhosts []string) http.Handler {
  278. // Wrap the CORS-handler within a host-handler
  279. handler := newCorsHandler(srv, cors)
  280. handler = newVHostHandler(vhosts, handler)
  281. return newGzipHandler(handler)
  282. }
  283. func newCorsHandler(srv http.Handler, allowedOrigins []string) http.Handler {
  284. // disable CORS support if user has not specified a custom CORS configuration
  285. if len(allowedOrigins) == 0 {
  286. return srv
  287. }
  288. c := cors.New(cors.Options{
  289. AllowedOrigins: allowedOrigins,
  290. AllowedMethods: []string{http.MethodPost, http.MethodGet},
  291. AllowedHeaders: []string{"*"},
  292. MaxAge: 600,
  293. })
  294. return c.Handler(srv)
  295. }
  296. // virtualHostHandler is a handler which validates the Host-header of incoming requests.
  297. // Using virtual hosts can help prevent DNS rebinding attacks, where a 'random' domain name points to
  298. // the service ip address (but without CORS headers). By verifying the targeted virtual host, we can
  299. // ensure that it's a destination that the node operator has defined.
  300. type virtualHostHandler struct {
  301. vhosts map[string]struct{}
  302. next http.Handler
  303. }
  304. func newVHostHandler(vhosts []string, next http.Handler) http.Handler {
  305. vhostMap := make(map[string]struct{})
  306. for _, allowedHost := range vhosts {
  307. vhostMap[strings.ToLower(allowedHost)] = struct{}{}
  308. }
  309. return &virtualHostHandler{vhostMap, next}
  310. }
  311. // ServeHTTP serves JSON-RPC requests over HTTP, implements http.Handler
  312. func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  313. // if r.Host is not set, we can continue serving since a browser would set the Host header
  314. if r.Host == "" {
  315. h.next.ServeHTTP(w, r)
  316. return
  317. }
  318. host, _, err := net.SplitHostPort(r.Host)
  319. if err != nil {
  320. // Either invalid (too many colons) or no port specified
  321. host = r.Host
  322. }
  323. if ipAddr := net.ParseIP(host); ipAddr != nil {
  324. // It's an IP address, we can serve that
  325. h.next.ServeHTTP(w, r)
  326. return
  327. }
  328. // Not an IP address, but a hostname. Need to validate
  329. if _, exist := h.vhosts["*"]; exist {
  330. h.next.ServeHTTP(w, r)
  331. return
  332. }
  333. if _, exist := h.vhosts[host]; exist {
  334. h.next.ServeHTTP(w, r)
  335. return
  336. }
  337. http.Error(w, "invalid host specified", http.StatusForbidden)
  338. }
  339. var gzPool = sync.Pool{
  340. New: func() interface{} {
  341. w := gzip.NewWriter(ioutil.Discard)
  342. return w
  343. },
  344. }
  345. type gzipResponseWriter struct {
  346. io.Writer
  347. http.ResponseWriter
  348. }
  349. func (w *gzipResponseWriter) WriteHeader(status int) {
  350. w.Header().Del("Content-Length")
  351. w.ResponseWriter.WriteHeader(status)
  352. }
  353. func (w *gzipResponseWriter) Write(b []byte) (int, error) {
  354. return w.Writer.Write(b)
  355. }
  356. func newGzipHandler(next http.Handler) http.Handler {
  357. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  358. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  359. next.ServeHTTP(w, r)
  360. return
  361. }
  362. w.Header().Set("Content-Encoding", "gzip")
  363. gz := gzPool.Get().(*gzip.Writer)
  364. defer gzPool.Put(gz)
  365. gz.Reset(w)
  366. defer gz.Close()
  367. next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
  368. })
  369. }
  370. type ipcServer struct {
  371. log log.Logger
  372. endpoint string
  373. mu sync.Mutex
  374. listener net.Listener
  375. srv *rpc.Server
  376. }
  377. func newIPCServer(log log.Logger, endpoint string) *ipcServer {
  378. return &ipcServer{log: log, endpoint: endpoint}
  379. }
  380. // Start starts the httpServer's http.Server
  381. func (is *ipcServer) start(apis []rpc.API) error {
  382. is.mu.Lock()
  383. defer is.mu.Unlock()
  384. if is.listener != nil {
  385. return nil // already running
  386. }
  387. listener, srv, err := rpc.StartIPCEndpoint(is.endpoint, apis)
  388. if err != nil {
  389. return err
  390. }
  391. is.log.Info("IPC endpoint opened", "url", is.endpoint)
  392. is.listener, is.srv = listener, srv
  393. return nil
  394. }
  395. func (is *ipcServer) stop() error {
  396. is.mu.Lock()
  397. defer is.mu.Unlock()
  398. if is.listener == nil {
  399. return nil // not running
  400. }
  401. err := is.listener.Close()
  402. is.srv.Stop()
  403. is.listener, is.srv = nil, nil
  404. is.log.Info("IPC endpoint closed", "url", is.endpoint)
  405. return err
  406. }
  407. // RegisterApisFromWhitelist checks the given modules' availability, generates a whitelist based on the allowed modules,
  408. // and then registers all of the APIs exposed by the services.
  409. func RegisterApisFromWhitelist(apis []rpc.API, modules []string, srv *rpc.Server, exposeAll bool) error {
  410. if bad, available := checkModuleAvailability(modules, apis); len(bad) > 0 {
  411. log.Error("Unavailable modules in HTTP API list", "unavailable", bad, "available", available)
  412. }
  413. // Generate the whitelist based on the allowed modules
  414. whitelist := make(map[string]bool)
  415. for _, module := range modules {
  416. whitelist[module] = true
  417. }
  418. // Register all the APIs exposed by the services
  419. for _, api := range apis {
  420. if exposeAll || whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
  421. if err := srv.RegisterName(api.Namespace, api.Service); err != nil {
  422. return err
  423. }
  424. }
  425. }
  426. return nil
  427. }