rpcstack.go 14 KB

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