rpcstack.go 15 KB

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