rpcstack.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. "io"
  20. "io/ioutil"
  21. "net"
  22. "net/http"
  23. "strings"
  24. "sync"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/rs/cors"
  27. )
  28. // NewHTTPHandlerStack returns wrapped http-related handlers
  29. func NewHTTPHandlerStack(srv http.Handler, cors []string, vhosts []string) http.Handler {
  30. // Wrap the CORS-handler within a host-handler
  31. handler := newCorsHandler(srv, cors)
  32. handler = newVHostHandler(vhosts, handler)
  33. return newGzipHandler(handler)
  34. }
  35. func newCorsHandler(srv http.Handler, allowedOrigins []string) http.Handler {
  36. // disable CORS support if user has not specified a custom CORS configuration
  37. if len(allowedOrigins) == 0 {
  38. return srv
  39. }
  40. c := cors.New(cors.Options{
  41. AllowedOrigins: allowedOrigins,
  42. AllowedMethods: []string{http.MethodPost, http.MethodGet},
  43. MaxAge: 600,
  44. AllowedHeaders: []string{"*"},
  45. })
  46. return c.Handler(srv)
  47. }
  48. // virtualHostHandler is a handler which validates the Host-header of incoming requests.
  49. // Using virtual hosts can help prevent DNS rebinding attacks, where a 'random' domain name points to
  50. // the service ip address (but without CORS headers). By verifying the targeted virtual host, we can
  51. // ensure that it's a destination that the node operator has defined.
  52. type virtualHostHandler struct {
  53. vhosts map[string]struct{}
  54. next http.Handler
  55. }
  56. func newVHostHandler(vhosts []string, next http.Handler) http.Handler {
  57. vhostMap := make(map[string]struct{})
  58. for _, allowedHost := range vhosts {
  59. vhostMap[strings.ToLower(allowedHost)] = struct{}{}
  60. }
  61. return &virtualHostHandler{vhostMap, next}
  62. }
  63. // ServeHTTP serves JSON-RPC requests over HTTP, implements http.Handler
  64. func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  65. // if r.Host is not set, we can continue serving since a browser would set the Host header
  66. if r.Host == "" {
  67. h.next.ServeHTTP(w, r)
  68. return
  69. }
  70. host, _, err := net.SplitHostPort(r.Host)
  71. if err != nil {
  72. // Either invalid (too many colons) or no port specified
  73. host = r.Host
  74. }
  75. if ipAddr := net.ParseIP(host); ipAddr != nil {
  76. // It's an IP address, we can serve that
  77. h.next.ServeHTTP(w, r)
  78. return
  79. }
  80. // Not an IP address, but a hostname. Need to validate
  81. if _, exist := h.vhosts["*"]; exist {
  82. h.next.ServeHTTP(w, r)
  83. return
  84. }
  85. if _, exist := h.vhosts[host]; exist {
  86. h.next.ServeHTTP(w, r)
  87. return
  88. }
  89. http.Error(w, "invalid host specified", http.StatusForbidden)
  90. }
  91. var gzPool = sync.Pool{
  92. New: func() interface{} {
  93. w := gzip.NewWriter(ioutil.Discard)
  94. return w
  95. },
  96. }
  97. type gzipResponseWriter struct {
  98. io.Writer
  99. http.ResponseWriter
  100. }
  101. func (w *gzipResponseWriter) WriteHeader(status int) {
  102. w.Header().Del("Content-Length")
  103. w.ResponseWriter.WriteHeader(status)
  104. }
  105. func (w *gzipResponseWriter) Write(b []byte) (int, error) {
  106. return w.Writer.Write(b)
  107. }
  108. func newGzipHandler(next http.Handler) http.Handler {
  109. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  110. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  111. next.ServeHTTP(w, r)
  112. return
  113. }
  114. w.Header().Set("Content-Encoding", "gzip")
  115. gz := gzPool.Get().(*gzip.Writer)
  116. defer gzPool.Put(gz)
  117. gz.Reset(w)
  118. defer gz.Close()
  119. next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
  120. })
  121. }
  122. // NewWebsocketUpgradeHandler returns a websocket handler that serves an incoming request only if it contains an upgrade
  123. // request to the websocket protocol. If not, serves the the request with the http handler.
  124. func NewWebsocketUpgradeHandler(h http.Handler, ws http.Handler) http.Handler {
  125. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  126. if isWebsocket(r) {
  127. ws.ServeHTTP(w, r)
  128. log.Debug("serving websocket request")
  129. return
  130. }
  131. h.ServeHTTP(w, r)
  132. })
  133. }
  134. // isWebsocket checks the header of an http request for a websocket upgrade request.
  135. func isWebsocket(r *http.Request) bool {
  136. return strings.ToLower(r.Header.Get("Upgrade")) == "websocket" &&
  137. strings.ToLower(r.Header.Get("Connection")) == "upgrade"
  138. }