websocket.go 6.9 KB

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