websocket.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Copyright 2015 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 rpc
  17. import (
  18. "context"
  19. "encoding/base64"
  20. "fmt"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "strings"
  25. "sync"
  26. mapset "github.com/deckarep/golang-set"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/gorilla/websocket"
  29. )
  30. const (
  31. wsReadBuffer = 1024
  32. wsWriteBuffer = 1024
  33. )
  34. var wsBufferPool = new(sync.Pool)
  35. // NewWSServer creates a new websocket RPC server around an API provider.
  36. //
  37. // Deprecated: use Server.WebsocketHandler
  38. func NewWSServer(allowedOrigins []string, srv *Server) *http.Server {
  39. return &http.Server{Handler: srv.WebsocketHandler(allowedOrigins)}
  40. }
  41. // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
  42. //
  43. // allowedOrigins should be a comma-separated list of allowed origin URLs.
  44. // To allow connections with any origin, pass "*".
  45. func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
  46. var upgrader = websocket.Upgrader{
  47. ReadBufferSize: wsReadBuffer,
  48. WriteBufferSize: wsWriteBuffer,
  49. WriteBufferPool: wsBufferPool,
  50. CheckOrigin: wsHandshakeValidator(allowedOrigins),
  51. }
  52. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  53. conn, err := upgrader.Upgrade(w, r, nil)
  54. if err != nil {
  55. log.Debug("WebSocket upgrade failed", "err", err)
  56. return
  57. }
  58. codec := newWebsocketCodec(conn)
  59. s.ServeCodec(codec, OptionMethodInvocation|OptionSubscriptions)
  60. })
  61. }
  62. // wsHandshakeValidator returns a handler that verifies the origin during the
  63. // websocket upgrade process. When a '*' is specified as an allowed origins all
  64. // connections are accepted.
  65. func wsHandshakeValidator(allowedOrigins []string) func(*http.Request) bool {
  66. origins := mapset.NewSet()
  67. allowAllOrigins := false
  68. for _, origin := range allowedOrigins {
  69. if origin == "*" {
  70. allowAllOrigins = true
  71. }
  72. if origin != "" {
  73. origins.Add(strings.ToLower(origin))
  74. }
  75. }
  76. // allow localhost if no allowedOrigins are specified.
  77. if len(origins.ToSlice()) == 0 {
  78. origins.Add("http://localhost")
  79. if hostname, err := os.Hostname(); err == nil {
  80. origins.Add("http://" + strings.ToLower(hostname))
  81. }
  82. }
  83. log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v", origins.ToSlice()))
  84. f := func(req *http.Request) bool {
  85. // Skip origin verification if no Origin header is present. The origin check
  86. // is supposed to protect against browser based attacks. Browsers always set
  87. // Origin. Non-browser software can put anything in origin and checking it doesn't
  88. // provide additional security.
  89. if _, ok := req.Header["Origin"]; !ok {
  90. return true
  91. }
  92. // Verify origin against whitelist.
  93. origin := strings.ToLower(req.Header.Get("Origin"))
  94. if allowAllOrigins || origins.Contains(origin) {
  95. return true
  96. }
  97. log.Warn("Rejected WebSocket connection", "origin", origin)
  98. return false
  99. }
  100. return f
  101. }
  102. type wsHandshakeError struct {
  103. err error
  104. status string
  105. }
  106. func (e wsHandshakeError) Error() string {
  107. s := e.err.Error()
  108. if e.status != "" {
  109. s += " (HTTP status " + e.status + ")"
  110. }
  111. return s
  112. }
  113. // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
  114. // that is listening on the given endpoint.
  115. //
  116. // The context is used for the initial connection establishment. It does not
  117. // affect subsequent interactions with the client.
  118. func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
  119. endpoint, header, err := wsClientHeaders(endpoint, origin)
  120. if err != nil {
  121. return nil, err
  122. }
  123. dialer := websocket.Dialer{
  124. ReadBufferSize: wsReadBuffer,
  125. WriteBufferSize: wsWriteBuffer,
  126. WriteBufferPool: wsBufferPool,
  127. }
  128. return newClient(ctx, func(ctx context.Context) (ServerCodec, error) {
  129. conn, resp, err := dialer.DialContext(ctx, endpoint, header)
  130. if err != nil {
  131. hErr := wsHandshakeError{err: err}
  132. if resp != nil {
  133. hErr.status = resp.Status
  134. }
  135. return nil, hErr
  136. }
  137. return newWebsocketCodec(conn), nil
  138. })
  139. }
  140. func wsClientHeaders(endpoint, origin string) (string, http.Header, error) {
  141. endpointURL, err := url.Parse(endpoint)
  142. if err != nil {
  143. return endpoint, nil, err
  144. }
  145. header := make(http.Header)
  146. if origin != "" {
  147. header.Add("origin", origin)
  148. }
  149. if endpointURL.User != nil {
  150. b64auth := base64.StdEncoding.EncodeToString([]byte(endpointURL.User.String()))
  151. header.Add("authorization", "Basic "+b64auth)
  152. endpointURL.User = nil
  153. }
  154. return endpointURL.String(), header, nil
  155. }
  156. func newWebsocketCodec(conn *websocket.Conn) ServerCodec {
  157. conn.SetReadLimit(maxRequestContentLength)
  158. return newCodec(conn, conn.WriteJSON, conn.ReadJSON)
  159. }