websocket.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. "bytes"
  19. "context"
  20. "crypto/tls"
  21. "encoding/base64"
  22. "encoding/json"
  23. "fmt"
  24. "net"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "strings"
  29. "time"
  30. mapset "github.com/deckarep/golang-set"
  31. "github.com/ethereum/go-ethereum/log"
  32. "golang.org/x/net/websocket"
  33. )
  34. // websocketJSONCodec is a custom JSON codec with payload size enforcement and
  35. // special number parsing.
  36. var websocketJSONCodec = websocket.Codec{
  37. // Marshal is the stock JSON marshaller used by the websocket library too.
  38. Marshal: func(v interface{}) ([]byte, byte, error) {
  39. msg, err := json.Marshal(v)
  40. return msg, websocket.TextFrame, err
  41. },
  42. // Unmarshal is a specialized unmarshaller to properly convert numbers.
  43. Unmarshal: func(msg []byte, payloadType byte, v interface{}) error {
  44. dec := json.NewDecoder(bytes.NewReader(msg))
  45. dec.UseNumber()
  46. return dec.Decode(v)
  47. },
  48. }
  49. // WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
  50. //
  51. // allowedOrigins should be a comma-separated list of allowed origin URLs.
  52. // To allow connections with any origin, pass "*".
  53. func (srv *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
  54. return websocket.Server{
  55. Handshake: wsHandshakeValidator(allowedOrigins),
  56. Handler: func(conn *websocket.Conn) {
  57. // Create a custom encode/decode pair to enforce payload size and number encoding
  58. conn.MaxPayloadBytes = maxRequestContentLength
  59. encoder := func(v interface{}) error {
  60. return websocketJSONCodec.Send(conn, v)
  61. }
  62. decoder := func(v interface{}) error {
  63. return websocketJSONCodec.Receive(conn, v)
  64. }
  65. srv.ServeCodec(NewCodec(conn, encoder, decoder), OptionMethodInvocation|OptionSubscriptions)
  66. },
  67. }
  68. }
  69. // NewWSServer creates a new websocket RPC server around an API provider.
  70. //
  71. // Deprecated: use Server.WebsocketHandler
  72. func NewWSServer(allowedOrigins []string, srv *Server) *http.Server {
  73. return &http.Server{Handler: srv.WebsocketHandler(allowedOrigins)}
  74. }
  75. // wsHandshakeValidator returns a handler that verifies the origin during the
  76. // websocket upgrade process. When a '*' is specified as an allowed origins all
  77. // connections are accepted.
  78. func wsHandshakeValidator(allowedOrigins []string) func(*websocket.Config, *http.Request) error {
  79. origins := mapset.NewSet()
  80. allowAllOrigins := false
  81. for _, origin := range allowedOrigins {
  82. if origin == "*" {
  83. allowAllOrigins = true
  84. }
  85. if origin != "" {
  86. origins.Add(strings.ToLower(origin))
  87. }
  88. }
  89. // allow localhost if no allowedOrigins are specified.
  90. if len(origins.ToSlice()) == 0 {
  91. origins.Add("http://localhost")
  92. if hostname, err := os.Hostname(); err == nil {
  93. origins.Add("http://" + strings.ToLower(hostname))
  94. }
  95. }
  96. log.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v\n", origins.ToSlice()))
  97. f := func(cfg *websocket.Config, req *http.Request) error {
  98. origin := strings.ToLower(req.Header.Get("Origin"))
  99. if allowAllOrigins || origins.Contains(origin) {
  100. return nil
  101. }
  102. log.Warn(fmt.Sprintf("origin '%s' not allowed on WS-RPC interface\n", origin))
  103. return fmt.Errorf("origin %s not allowed", origin)
  104. }
  105. return f
  106. }
  107. func wsGetConfig(endpoint, origin string) (*websocket.Config, error) {
  108. if origin == "" {
  109. var err error
  110. if origin, err = os.Hostname(); err != nil {
  111. return nil, err
  112. }
  113. if strings.HasPrefix(endpoint, "wss") {
  114. origin = "https://" + strings.ToLower(origin)
  115. } else {
  116. origin = "http://" + strings.ToLower(origin)
  117. }
  118. }
  119. config, err := websocket.NewConfig(endpoint, origin)
  120. if err != nil {
  121. return nil, err
  122. }
  123. if config.Location.User != nil {
  124. b64auth := base64.StdEncoding.EncodeToString([]byte(config.Location.User.String()))
  125. config.Header.Add("Authorization", "Basic "+b64auth)
  126. config.Location.User = nil
  127. }
  128. return config, nil
  129. }
  130. // DialWebsocket creates a new RPC client that communicates with a JSON-RPC server
  131. // that is listening on the given endpoint.
  132. //
  133. // The context is used for the initial connection establishment. It does not
  134. // affect subsequent interactions with the client.
  135. func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error) {
  136. config, err := wsGetConfig(endpoint, origin)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return newClient(ctx, func(ctx context.Context) (net.Conn, error) {
  141. return wsDialContext(ctx, config)
  142. })
  143. }
  144. func wsDialContext(ctx context.Context, config *websocket.Config) (*websocket.Conn, error) {
  145. var conn net.Conn
  146. var err error
  147. switch config.Location.Scheme {
  148. case "ws":
  149. conn, err = dialContext(ctx, "tcp", wsDialAddress(config.Location))
  150. case "wss":
  151. dialer := contextDialer(ctx)
  152. conn, err = tls.DialWithDialer(dialer, "tcp", wsDialAddress(config.Location), config.TlsConfig)
  153. default:
  154. err = websocket.ErrBadScheme
  155. }
  156. if err != nil {
  157. return nil, err
  158. }
  159. ws, err := websocket.NewClient(config, conn)
  160. if err != nil {
  161. conn.Close()
  162. return nil, err
  163. }
  164. return ws, err
  165. }
  166. var wsPortMap = map[string]string{"ws": "80", "wss": "443"}
  167. func wsDialAddress(location *url.URL) string {
  168. if _, ok := wsPortMap[location.Scheme]; ok {
  169. if _, _, err := net.SplitHostPort(location.Host); err != nil {
  170. return net.JoinHostPort(location.Host, wsPortMap[location.Scheme])
  171. }
  172. }
  173. return location.Host
  174. }
  175. func dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  176. d := &net.Dialer{KeepAlive: tcpKeepAliveInterval}
  177. return d.DialContext(ctx, network, addr)
  178. }
  179. func contextDialer(ctx context.Context) *net.Dialer {
  180. dialer := &net.Dialer{Cancel: ctx.Done(), KeepAlive: tcpKeepAliveInterval}
  181. if deadline, ok := ctx.Deadline(); ok {
  182. dialer.Deadline = deadline
  183. } else {
  184. dialer.Deadline = time.Now().Add(defaultDialTimeout)
  185. }
  186. return dialer
  187. }