rpcstack.go 16 KB

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