websocket.go 5.2 KB

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