rpcstack.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. "net"
  23. "net/http"
  24. "sort"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  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. prefix string // path prefix on which to mount http handler
  39. jwtSecret []byte // optional JWT secret
  40. }
  41. // wsConfig is the JSON-RPC/Websocket configuration
  42. type wsConfig struct {
  43. Origins []string
  44. Modules []string
  45. prefix string // path prefix on which to mount ws handler
  46. jwtSecret []byte // optional JWT secret
  47. }
  48. type rpcHandler struct {
  49. http.Handler
  50. server *rpc.Server
  51. }
  52. type httpServer struct {
  53. log log.Logger
  54. timeouts rpc.HTTPTimeouts
  55. mux http.ServeMux // registered handlers go here
  56. mu sync.Mutex
  57. server *http.Server
  58. listener net.Listener // non-nil when server is running
  59. // HTTP RPC handler things.
  60. httpConfig httpConfig
  61. httpHandler atomic.Value // *rpcHandler
  62. // WebSocket handler things.
  63. wsConfig wsConfig
  64. wsHandler atomic.Value // *rpcHandler
  65. // These are set by setListenAddr.
  66. endpoint string
  67. host string
  68. port int
  69. handlerNames map[string]string
  70. }
  71. const (
  72. shutdownTimeout = 5 * time.Second
  73. )
  74. func newHTTPServer(log log.Logger, timeouts rpc.HTTPTimeouts) *httpServer {
  75. h := &httpServer{log: log, timeouts: timeouts, handlerNames: make(map[string]string)}
  76. h.httpHandler.Store((*rpcHandler)(nil))
  77. h.wsHandler.Store((*rpcHandler)(nil))
  78. return h
  79. }
  80. // setListenAddr configures the listening address of the server.
  81. // The address can only be set while the server isn't running.
  82. func (h *httpServer) setListenAddr(host string, port int) error {
  83. h.mu.Lock()
  84. defer h.mu.Unlock()
  85. if h.listener != nil && (host != h.host || port != h.port) {
  86. return fmt.Errorf("HTTP server already running on %s", h.endpoint)
  87. }
  88. h.host, h.port = host, port
  89. h.endpoint = fmt.Sprintf("%s:%d", host, port)
  90. return nil
  91. }
  92. // listenAddr returns the listening address of the server.
  93. func (h *httpServer) listenAddr() string {
  94. h.mu.Lock()
  95. defer h.mu.Unlock()
  96. if h.listener != nil {
  97. return h.listener.Addr().String()
  98. }
  99. return h.endpoint
  100. }
  101. // start starts the HTTP server if it is enabled and not already running.
  102. func (h *httpServer) start() error {
  103. h.mu.Lock()
  104. defer h.mu.Unlock()
  105. if h.endpoint == "" || h.listener != nil {
  106. return nil // already running or not configured
  107. }
  108. // Initialize the server.
  109. h.server = &http.Server{Handler: h}
  110. if h.timeouts != (rpc.HTTPTimeouts{}) {
  111. CheckTimeouts(&h.timeouts)
  112. h.server.ReadTimeout = h.timeouts.ReadTimeout
  113. h.server.ReadHeaderTimeout = h.timeouts.ReadHeaderTimeout
  114. h.server.WriteTimeout = h.timeouts.WriteTimeout
  115. h.server.IdleTimeout = h.timeouts.IdleTimeout
  116. }
  117. // Start the server.
  118. listener, err := net.Listen("tcp", h.endpoint)
  119. if err != nil {
  120. // If the server fails to start, we need to clear out the RPC and WS
  121. // configuration so they can be configured another time.
  122. h.disableRPC()
  123. h.disableWS()
  124. return err
  125. }
  126. h.listener = listener
  127. go h.server.Serve(listener)
  128. if h.wsAllowed() {
  129. url := fmt.Sprintf("ws://%v", listener.Addr())
  130. if h.wsConfig.prefix != "" {
  131. url += h.wsConfig.prefix
  132. }
  133. h.log.Info("WebSocket enabled", "url", url)
  134. }
  135. // if server is websocket only, return after logging
  136. if !h.rpcAllowed() {
  137. return nil
  138. }
  139. // Log http endpoint.
  140. h.log.Info("HTTP server started",
  141. "endpoint", listener.Addr(), "auth", (h.httpConfig.jwtSecret != nil),
  142. "prefix", h.httpConfig.prefix,
  143. "cors", strings.Join(h.httpConfig.CorsAllowedOrigins, ","),
  144. "vhosts", strings.Join(h.httpConfig.Vhosts, ","),
  145. )
  146. // Log all handlers mounted on server.
  147. var paths []string
  148. for path := range h.handlerNames {
  149. paths = append(paths, path)
  150. }
  151. sort.Strings(paths)
  152. logged := make(map[string]bool, len(paths))
  153. for _, path := range paths {
  154. name := h.handlerNames[path]
  155. if !logged[name] {
  156. log.Info(name+" enabled", "url", "http://"+listener.Addr().String()+path)
  157. logged[name] = true
  158. }
  159. }
  160. return nil
  161. }
  162. func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  163. // check if ws request and serve if ws enabled
  164. ws := h.wsHandler.Load().(*rpcHandler)
  165. if ws != nil && isWebsocket(r) {
  166. if checkPath(r, h.wsConfig.prefix) {
  167. ws.ServeHTTP(w, r)
  168. }
  169. return
  170. }
  171. // if http-rpc is enabled, try to serve request
  172. rpc := h.httpHandler.Load().(*rpcHandler)
  173. if rpc != nil {
  174. // First try to route in the mux.
  175. // Requests to a path below root are handled by the mux,
  176. // which has all the handlers registered via Node.RegisterHandler.
  177. // These are made available when RPC is enabled.
  178. muxHandler, pattern := h.mux.Handler(r)
  179. if pattern != "" {
  180. muxHandler.ServeHTTP(w, r)
  181. return
  182. }
  183. if checkPath(r, h.httpConfig.prefix) {
  184. rpc.ServeHTTP(w, r)
  185. return
  186. }
  187. }
  188. w.WriteHeader(http.StatusNotFound)
  189. }
  190. // checkPath checks whether a given request URL matches a given path prefix.
  191. func checkPath(r *http.Request, path string) bool {
  192. // if no prefix has been specified, request URL must be on root
  193. if path == "" {
  194. return r.URL.Path == "/"
  195. }
  196. // otherwise, check to make sure prefix matches
  197. return len(r.URL.Path) >= len(path) && r.URL.Path[:len(path)] == path
  198. }
  199. // validatePrefix checks if 'path' is a valid configuration value for the RPC prefix option.
  200. func validatePrefix(what, path string) error {
  201. if path == "" {
  202. return nil
  203. }
  204. if path[0] != '/' {
  205. return fmt.Errorf(`%s RPC path prefix %q does not contain leading "/"`, what, path)
  206. }
  207. if strings.ContainsAny(path, "?#") {
  208. // This is just to avoid confusion. While these would match correctly (i.e. they'd
  209. // match if URL-escaped into path), it's not easy to understand for users when
  210. // setting that on the command line.
  211. return fmt.Errorf("%s RPC path prefix %q contains URL meta-characters", what, path)
  212. }
  213. return nil
  214. }
  215. // stop shuts down the HTTP server.
  216. func (h *httpServer) stop() {
  217. h.mu.Lock()
  218. defer h.mu.Unlock()
  219. h.doStop()
  220. }
  221. func (h *httpServer) doStop() {
  222. if h.listener == nil {
  223. return // not running
  224. }
  225. // Shut down the server.
  226. httpHandler := h.httpHandler.Load().(*rpcHandler)
  227. wsHandler := h.wsHandler.Load().(*rpcHandler)
  228. if httpHandler != nil {
  229. h.httpHandler.Store((*rpcHandler)(nil))
  230. httpHandler.server.Stop()
  231. }
  232. if wsHandler != nil {
  233. h.wsHandler.Store((*rpcHandler)(nil))
  234. wsHandler.server.Stop()
  235. }
  236. ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
  237. defer cancel()
  238. err := h.server.Shutdown(ctx)
  239. if err == ctx.Err() {
  240. h.log.Warn("HTTP server graceful shutdown timed out")
  241. h.server.Close()
  242. }
  243. h.listener.Close()
  244. h.log.Info("HTTP server stopped", "endpoint", h.listener.Addr())
  245. // Clear out everything to allow re-configuring it later.
  246. h.host, h.port, h.endpoint = "", 0, ""
  247. h.server, h.listener = nil, nil
  248. }
  249. // enableRPC turns on JSON-RPC over HTTP on the server.
  250. func (h *httpServer) enableRPC(apis []rpc.API, config httpConfig) error {
  251. h.mu.Lock()
  252. defer h.mu.Unlock()
  253. if h.rpcAllowed() {
  254. return fmt.Errorf("JSON-RPC over HTTP is already enabled")
  255. }
  256. // Create RPC server and handler.
  257. srv := rpc.NewServer()
  258. if err := RegisterApis(apis, config.Modules, srv); err != nil {
  259. return err
  260. }
  261. h.httpConfig = config
  262. h.httpHandler.Store(&rpcHandler{
  263. Handler: NewHTTPHandlerStack(srv, config.CorsAllowedOrigins, config.Vhosts, config.jwtSecret),
  264. server: srv,
  265. })
  266. return nil
  267. }
  268. // disableRPC stops the HTTP RPC handler. This is internal, the caller must hold h.mu.
  269. func (h *httpServer) disableRPC() bool {
  270. handler := h.httpHandler.Load().(*rpcHandler)
  271. if handler != nil {
  272. h.httpHandler.Store((*rpcHandler)(nil))
  273. handler.server.Stop()
  274. }
  275. return handler != nil
  276. }
  277. // enableWS turns on JSON-RPC over WebSocket on the server.
  278. func (h *httpServer) enableWS(apis []rpc.API, config wsConfig) error {
  279. h.mu.Lock()
  280. defer h.mu.Unlock()
  281. if h.wsAllowed() {
  282. return fmt.Errorf("JSON-RPC over WebSocket is already enabled")
  283. }
  284. // Create RPC server and handler.
  285. srv := rpc.NewServer()
  286. if err := RegisterApis(apis, config.Modules, srv); err != nil {
  287. return err
  288. }
  289. h.wsConfig = config
  290. h.wsHandler.Store(&rpcHandler{
  291. Handler: NewWSHandlerStack(srv.WebsocketHandler(config.Origins), config.jwtSecret),
  292. server: srv,
  293. })
  294. return nil
  295. }
  296. // stopWS disables JSON-RPC over WebSocket and also stops the server if it only serves WebSocket.
  297. func (h *httpServer) stopWS() {
  298. h.mu.Lock()
  299. defer h.mu.Unlock()
  300. if h.disableWS() {
  301. if !h.rpcAllowed() {
  302. h.doStop()
  303. }
  304. }
  305. }
  306. // disableWS disables the WebSocket handler. This is internal, the caller must hold h.mu.
  307. func (h *httpServer) disableWS() bool {
  308. ws := h.wsHandler.Load().(*rpcHandler)
  309. if ws != nil {
  310. h.wsHandler.Store((*rpcHandler)(nil))
  311. ws.server.Stop()
  312. }
  313. return ws != nil
  314. }
  315. // rpcAllowed returns true when JSON-RPC over HTTP is enabled.
  316. func (h *httpServer) rpcAllowed() bool {
  317. return h.httpHandler.Load().(*rpcHandler) != nil
  318. }
  319. // wsAllowed returns true when JSON-RPC over WebSocket is enabled.
  320. func (h *httpServer) wsAllowed() bool {
  321. return h.wsHandler.Load().(*rpcHandler) != nil
  322. }
  323. // isWebsocket checks the header of an http request for a websocket upgrade request.
  324. func isWebsocket(r *http.Request) bool {
  325. return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") &&
  326. strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade")
  327. }
  328. // NewHTTPHandlerStack returns wrapped http-related handlers
  329. func NewHTTPHandlerStack(srv http.Handler, cors []string, vhosts []string, jwtSecret []byte) http.Handler {
  330. // Wrap the CORS-handler within a host-handler
  331. handler := newCorsHandler(srv, cors)
  332. handler = newVHostHandler(vhosts, handler)
  333. if len(jwtSecret) != 0 {
  334. handler = newJWTHandler(jwtSecret, handler)
  335. }
  336. return newGzipHandler(handler)
  337. }
  338. // NewWSHandlerStack returns a wrapped ws-related handler.
  339. func NewWSHandlerStack(srv http.Handler, jwtSecret []byte) http.Handler {
  340. if len(jwtSecret) != 0 {
  341. return newJWTHandler(jwtSecret, srv)
  342. }
  343. return srv
  344. }
  345. func newCorsHandler(srv http.Handler, allowedOrigins []string) http.Handler {
  346. // disable CORS support if user has not specified a custom CORS configuration
  347. if len(allowedOrigins) == 0 {
  348. return srv
  349. }
  350. c := cors.New(cors.Options{
  351. AllowedOrigins: allowedOrigins,
  352. AllowedMethods: []string{http.MethodPost, http.MethodGet},
  353. AllowedHeaders: []string{"*"},
  354. MaxAge: 600,
  355. })
  356. return c.Handler(srv)
  357. }
  358. // virtualHostHandler is a handler which validates the Host-header of incoming requests.
  359. // Using virtual hosts can help prevent DNS rebinding attacks, where a 'random' domain name points to
  360. // the service ip address (but without CORS headers). By verifying the targeted virtual host, we can
  361. // ensure that it's a destination that the node operator has defined.
  362. type virtualHostHandler struct {
  363. vhosts map[string]struct{}
  364. next http.Handler
  365. }
  366. func newVHostHandler(vhosts []string, next http.Handler) http.Handler {
  367. vhostMap := make(map[string]struct{})
  368. for _, allowedHost := range vhosts {
  369. vhostMap[strings.ToLower(allowedHost)] = struct{}{}
  370. }
  371. return &virtualHostHandler{vhostMap, next}
  372. }
  373. // ServeHTTP serves JSON-RPC requests over HTTP, implements http.Handler
  374. func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  375. // if r.Host is not set, we can continue serving since a browser would set the Host header
  376. if r.Host == "" {
  377. h.next.ServeHTTP(w, r)
  378. return
  379. }
  380. host, _, err := net.SplitHostPort(r.Host)
  381. if err != nil {
  382. // Either invalid (too many colons) or no port specified
  383. host = r.Host
  384. }
  385. if ipAddr := net.ParseIP(host); ipAddr != nil {
  386. // It's an IP address, we can serve that
  387. h.next.ServeHTTP(w, r)
  388. return
  389. }
  390. // Not an IP address, but a hostname. Need to validate
  391. if _, exist := h.vhosts["*"]; exist {
  392. h.next.ServeHTTP(w, r)
  393. return
  394. }
  395. if _, exist := h.vhosts[host]; exist {
  396. h.next.ServeHTTP(w, r)
  397. return
  398. }
  399. http.Error(w, "invalid host specified", http.StatusForbidden)
  400. }
  401. var gzPool = sync.Pool{
  402. New: func() interface{} {
  403. w := gzip.NewWriter(io.Discard)
  404. return w
  405. },
  406. }
  407. type gzipResponseWriter struct {
  408. io.Writer
  409. http.ResponseWriter
  410. }
  411. func (w *gzipResponseWriter) WriteHeader(status int) {
  412. w.Header().Del("Content-Length")
  413. w.ResponseWriter.WriteHeader(status)
  414. }
  415. func (w *gzipResponseWriter) Write(b []byte) (int, error) {
  416. return w.Writer.Write(b)
  417. }
  418. func newGzipHandler(next http.Handler) http.Handler {
  419. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  420. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  421. next.ServeHTTP(w, r)
  422. return
  423. }
  424. w.Header().Set("Content-Encoding", "gzip")
  425. gz := gzPool.Get().(*gzip.Writer)
  426. defer gzPool.Put(gz)
  427. gz.Reset(w)
  428. defer gz.Close()
  429. next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
  430. })
  431. }
  432. type ipcServer struct {
  433. log log.Logger
  434. endpoint string
  435. mu sync.Mutex
  436. listener net.Listener
  437. srv *rpc.Server
  438. }
  439. func newIPCServer(log log.Logger, endpoint string) *ipcServer {
  440. return &ipcServer{log: log, endpoint: endpoint}
  441. }
  442. // Start starts the httpServer's http.Server
  443. func (is *ipcServer) start(apis []rpc.API) error {
  444. is.mu.Lock()
  445. defer is.mu.Unlock()
  446. if is.listener != nil {
  447. return nil // already running
  448. }
  449. listener, srv, err := rpc.StartIPCEndpoint(is.endpoint, apis)
  450. if err != nil {
  451. is.log.Warn("IPC opening failed", "url", is.endpoint, "error", err)
  452. return err
  453. }
  454. is.log.Info("IPC endpoint opened", "url", is.endpoint)
  455. is.listener, is.srv = listener, srv
  456. return nil
  457. }
  458. func (is *ipcServer) stop() error {
  459. is.mu.Lock()
  460. defer is.mu.Unlock()
  461. if is.listener == nil {
  462. return nil // not running
  463. }
  464. err := is.listener.Close()
  465. is.srv.Stop()
  466. is.listener, is.srv = nil, nil
  467. is.log.Info("IPC endpoint closed", "url", is.endpoint)
  468. return err
  469. }
  470. // RegisterApis checks the given modules' availability, generates an allowlist based on the allowed modules,
  471. // and then registers all of the APIs exposed by the services.
  472. func RegisterApis(apis []rpc.API, modules []string, srv *rpc.Server) error {
  473. if bad, available := checkModuleAvailability(modules, apis); len(bad) > 0 {
  474. log.Error("Unavailable modules in HTTP API list", "unavailable", bad, "available", available)
  475. }
  476. // Generate the allow list based on the allowed modules
  477. allowList := make(map[string]bool)
  478. for _, module := range modules {
  479. allowList[module] = true
  480. }
  481. // Register all the APIs exposed by the services
  482. for _, api := range apis {
  483. if allowList[api.Namespace] || len(allowList) == 0 {
  484. if err := srv.RegisterName(api.Namespace, api.Service); err != nil {
  485. return err
  486. }
  487. }
  488. }
  489. return nil
  490. }